Initial commit: HTab spreadsheet engine and GemUI X11 frontend
This commit is contained in:
commit
395f458fee
55 files changed
+12682
No files matched your search
@@ -0,0 +1,269 @@
|
||||
#include "engine/functions/helpers.hpp"
|
||||
#include "engine/functions/registry.hpp"
|
||||
#include "engine/workbook.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace htab {
|
||||
|
||||
using namespace htab::fn;
|
||||
|
||||
namespace {
|
||||
|
||||
// Shared helper required by design.md Section 4:
|
||||
// Same criteria row = AND, different criteria rows = OR.
|
||||
std::variant<std::vector<int>, ErrorCode> filterDatabase(const Array2D& db,
|
||||
const Array2D& criteria) {
|
||||
if (db.rows < 2 || db.cols < 1 || criteria.rows < 2 || criteria.cols < 1) {
|
||||
return ErrorCode::Value;
|
||||
}
|
||||
|
||||
std::vector<int> crit_to_db_col(static_cast<size_t>(criteria.cols), -1);
|
||||
for (int jc = 0; jc < criteria.cols; ++jc) {
|
||||
auto h_var = to_string(criteria.at(0, jc));
|
||||
if (std::holds_alternative<ErrorCode>(h_var)) return std::get<ErrorCode>(h_var);
|
||||
const std::string& h = std::get<std::string>(h_var);
|
||||
if (h.empty()) continue;
|
||||
int found = -1;
|
||||
for (int idb = 0; idb < db.cols; ++idb) {
|
||||
auto dh_var = to_string(db.at(0, idb));
|
||||
if (std::holds_alternative<ErrorCode>(dh_var)) return std::get<ErrorCode>(dh_var);
|
||||
if (iequals_ascii(h, std::get<std::string>(dh_var))) {
|
||||
found = idb;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (found < 0) return ErrorCode::Value;
|
||||
crit_to_db_col[static_cast<size_t>(jc)] = found;
|
||||
}
|
||||
|
||||
std::vector<int> matched_rows;
|
||||
for (int r = 1; r < db.rows; ++r) {
|
||||
bool row_matches_any_or_clause = false;
|
||||
for (int cr = 1; cr < criteria.rows; ++cr) {
|
||||
bool clause_matches = true;
|
||||
for (int jc = 0; jc < criteria.cols; ++jc) {
|
||||
const Value& crit_cell = criteria.at(cr, jc);
|
||||
if (crit_cell.is_empty()) continue;
|
||||
int db_col = crit_to_db_col[static_cast<size_t>(jc)];
|
||||
if (db_col < 0) {
|
||||
clause_matches = false;
|
||||
break;
|
||||
}
|
||||
if (!matches_criteria(db.at(r, db_col), crit_cell)) {
|
||||
clause_matches = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (clause_matches) {
|
||||
row_matches_any_or_clause = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (row_matches_any_or_clause) {
|
||||
matched_rows.push_back(r);
|
||||
}
|
||||
}
|
||||
return matched_rows;
|
||||
}
|
||||
|
||||
std::optional<int> resolve_db_field(const Array2D& db, const Value& field, ErrorCode& err_out) {
|
||||
if (field.is_error()) {
|
||||
err_out = field.as_error();
|
||||
return std::nullopt;
|
||||
}
|
||||
if (field.is_number()) {
|
||||
int idx = static_cast<int>(std::trunc(field.as_number())) - 1;
|
||||
if (idx < 0 || idx >= db.cols) {
|
||||
err_out = ErrorCode::Value;
|
||||
return std::nullopt;
|
||||
}
|
||||
return idx;
|
||||
}
|
||||
auto s_var = to_string(field);
|
||||
if (std::holds_alternative<ErrorCode>(s_var)) {
|
||||
err_out = std::get<ErrorCode>(s_var);
|
||||
return std::nullopt;
|
||||
}
|
||||
const std::string& name = std::get<std::string>(s_var);
|
||||
for (int c = 0; c < db.cols; ++c) {
|
||||
auto dh_var = to_string(db.at(0, c));
|
||||
if (std::holds_alternative<ErrorCode>(dh_var)) {
|
||||
err_out = std::get<ErrorCode>(dh_var);
|
||||
return std::nullopt;
|
||||
}
|
||||
if (iequals_ascii(name, std::get<std::string>(dh_var))) {
|
||||
return c;
|
||||
}
|
||||
}
|
||||
err_out = ErrorCode::Value;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
enum class DbOp {
|
||||
Average,
|
||||
Count,
|
||||
CountA,
|
||||
Get,
|
||||
Max,
|
||||
Min,
|
||||
Product,
|
||||
Stdev,
|
||||
StdevP,
|
||||
Sum,
|
||||
Var,
|
||||
VarP,
|
||||
};
|
||||
|
||||
EvalResult run_db_op(const std::vector<std::shared_ptr<Expr>>& args,
|
||||
const EvalContext& ctx,
|
||||
DbOp op) {
|
||||
if (args.size() != 3) return err_res(ErrorCode::Value);
|
||||
auto db_var = result_to_array2d(evaluate_ast(args[0].get(), ctx), *ctx.wb);
|
||||
if (std::holds_alternative<ErrorCode>(db_var)) return err_res(std::get<ErrorCode>(db_var));
|
||||
const Array2D& db = std::get<Array2D>(db_var);
|
||||
|
||||
Value field_val = deref_to_value(evaluate_ast(args[1].get(), ctx), *ctx.wb);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto field_col = resolve_db_field(db, field_val, err);
|
||||
if (!field_col) return err_res(err);
|
||||
|
||||
auto crit_var = result_to_array2d(evaluate_ast(args[2].get(), ctx), *ctx.wb);
|
||||
if (std::holds_alternative<ErrorCode>(crit_var)) return err_res(std::get<ErrorCode>(crit_var));
|
||||
const Array2D& criteria = std::get<Array2D>(crit_var);
|
||||
|
||||
auto rows_var = filterDatabase(db, criteria);
|
||||
if (std::holds_alternative<ErrorCode>(rows_var)) return err_res(std::get<ErrorCode>(rows_var));
|
||||
const std::vector<int>& matched = std::get<std::vector<int>>(rows_var);
|
||||
|
||||
if (op == DbOp::Get) {
|
||||
if (matched.empty()) return err_res(ErrorCode::Value);
|
||||
if (matched.size() > 1) return err_res(ErrorCode::Num);
|
||||
return EvalResult::from_value(db.at(matched[0], *field_col));
|
||||
}
|
||||
|
||||
if (op == DbOp::CountA) {
|
||||
size_t cnt = 0;
|
||||
for (int r : matched) {
|
||||
if (!db.at(r, *field_col).is_empty()) ++cnt;
|
||||
}
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(cnt)));
|
||||
}
|
||||
|
||||
std::vector<double> nums;
|
||||
for (int r : matched) {
|
||||
const Value& v = db.at(r, *field_col);
|
||||
if (v.is_error()) return EvalResult::from_value(v);
|
||||
if (v.is_number()) nums.push_back(v.as_number());
|
||||
}
|
||||
|
||||
switch (op) {
|
||||
case DbOp::Count:
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(nums.size())));
|
||||
case DbOp::Sum: {
|
||||
double s = 0.0;
|
||||
for (double v : nums) s += v;
|
||||
return EvalResult::from_value(Value::make_checked_number(s));
|
||||
}
|
||||
case DbOp::Average: {
|
||||
if (nums.empty()) return err_res(ErrorCode::Div0);
|
||||
double s = 0.0;
|
||||
for (double v : nums) s += v;
|
||||
return EvalResult::from_value(Value::make_checked_number(s / static_cast<double>(nums.size())));
|
||||
}
|
||||
case DbOp::Max:
|
||||
if (nums.empty()) return EvalResult::from_value(Value::make_number(0.0));
|
||||
return EvalResult::from_value(
|
||||
Value::make_number(*std::max_element(nums.begin(), nums.end())));
|
||||
case DbOp::Min:
|
||||
if (nums.empty()) return EvalResult::from_value(Value::make_number(0.0));
|
||||
return EvalResult::from_value(
|
||||
Value::make_number(*std::min_element(nums.begin(), nums.end())));
|
||||
case DbOp::Product: {
|
||||
if (nums.empty()) return EvalResult::from_value(Value::make_number(0.0));
|
||||
double p = 1.0;
|
||||
for (double v : nums) p *= v;
|
||||
return EvalResult::from_value(Value::make_checked_number(p));
|
||||
}
|
||||
case DbOp::Var:
|
||||
case DbOp::VarP:
|
||||
case DbOp::Stdev:
|
||||
case DbOp::StdevP: {
|
||||
bool sample = (op == DbOp::Var || op == DbOp::Stdev);
|
||||
bool take_sqrt = (op == DbOp::Stdev || op == DbOp::StdevP);
|
||||
if (nums.size() < (sample ? 2U : 1U)) return err_res(ErrorCode::Div0);
|
||||
double s = 0.0;
|
||||
for (double v : nums) s += v;
|
||||
double mean = s / static_cast<double>(nums.size());
|
||||
double sq = 0.0;
|
||||
for (double v : nums) {
|
||||
double d = v - mean;
|
||||
sq += d * d;
|
||||
}
|
||||
double var = sq / static_cast<double>(sample ? (nums.size() - 1) : nums.size());
|
||||
return EvalResult::from_value(Value::make_checked_number(take_sqrt ? std::sqrt(var) : var));
|
||||
}
|
||||
default:
|
||||
return err_res(ErrorCode::Value);
|
||||
}
|
||||
}
|
||||
|
||||
EvalResult fn_daverage(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return run_db_op(a, c, DbOp::Average);
|
||||
}
|
||||
EvalResult fn_dcount(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return run_db_op(a, c, DbOp::Count);
|
||||
}
|
||||
EvalResult fn_dcounta(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return run_db_op(a, c, DbOp::CountA);
|
||||
}
|
||||
EvalResult fn_dget(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return run_db_op(a, c, DbOp::Get);
|
||||
}
|
||||
EvalResult fn_dmax(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return run_db_op(a, c, DbOp::Max);
|
||||
}
|
||||
EvalResult fn_dmin(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return run_db_op(a, c, DbOp::Min);
|
||||
}
|
||||
EvalResult fn_dproduct(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return run_db_op(a, c, DbOp::Product);
|
||||
}
|
||||
EvalResult fn_dstdev(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return run_db_op(a, c, DbOp::Stdev);
|
||||
}
|
||||
EvalResult fn_dstdevp(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return run_db_op(a, c, DbOp::StdevP);
|
||||
}
|
||||
EvalResult fn_dsum(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return run_db_op(a, c, DbOp::Sum);
|
||||
}
|
||||
EvalResult fn_dvar(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return run_db_op(a, c, DbOp::Var);
|
||||
}
|
||||
EvalResult fn_dvarp(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return run_db_op(a, c, DbOp::VarP);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_database_functions(FunctionRegistry& reg) {
|
||||
reg.register_fn("DAVERAGE", fn_daverage);
|
||||
reg.register_fn("DCOUNT", fn_dcount);
|
||||
reg.register_fn("DCOUNTA", fn_dcounta);
|
||||
reg.register_fn("DGET", fn_dget);
|
||||
reg.register_fn("DMAX", fn_dmax);
|
||||
reg.register_fn("DMIN", fn_dmin);
|
||||
reg.register_fn("DPRODUCT", fn_dproduct);
|
||||
reg.register_fn("DSTDEV", fn_dstdev);
|
||||
reg.register_fn("DSTDEVP", fn_dstdevp);
|
||||
reg.register_fn("DSUM", fn_dsum);
|
||||
reg.register_fn("DVAR", fn_dvar);
|
||||
reg.register_fn("DVARP", fn_dvarp);
|
||||
}
|
||||
|
||||
} // namespace htab
|
||||
@@ -0,0 +1,316 @@
|
||||
#include "engine/format.hpp"
|
||||
#include "engine/functions/helpers.hpp"
|
||||
#include "engine/functions/registry.hpp"
|
||||
#include "engine/workbook.hpp"
|
||||
|
||||
#include <cctype>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <ctime>
|
||||
|
||||
namespace htab {
|
||||
|
||||
using namespace htab::fn;
|
||||
|
||||
namespace {
|
||||
|
||||
int days_in_month(int y, int m) {
|
||||
static constexpr int kDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
|
||||
if (m < 1 || m > 12) return 0;
|
||||
if (m == 2) {
|
||||
bool leap = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0));
|
||||
return leap ? 29 : 28;
|
||||
}
|
||||
return kDays[m - 1];
|
||||
}
|
||||
|
||||
int parse_month_name(std::string_view s) {
|
||||
static constexpr const char* kShort[] = {
|
||||
"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"};
|
||||
static constexpr const char* kFull[] = {
|
||||
"january", "february", "march", "april", "may", "june",
|
||||
"july", "august", "september", "october", "november", "december"};
|
||||
for (int i = 0; i < 12; ++i) {
|
||||
if (iequals_ascii(s, kShort[i]) || iequals_ascii(s, kFull[i])) return i + 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool parse_uint(std::string_view s, int& out) {
|
||||
if (s.empty()) return false;
|
||||
int64_t val = 0;
|
||||
for (char ch : s) {
|
||||
if (!std::isdigit(static_cast<unsigned char>(ch))) return false;
|
||||
val = val * 10 + (ch - '0');
|
||||
if (val > 1000000) return false;
|
||||
}
|
||||
out = static_cast<int>(val);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<int> parse_date_string(std::string_view raw) {
|
||||
raw = trim_ascii(raw);
|
||||
if (raw.empty()) return std::nullopt;
|
||||
|
||||
// Strip optional trailing time part if separated by space
|
||||
// Wait: "Jan 5, 2024" has spaces, so only strip if contains ':'
|
||||
size_t colon = raw.find(':');
|
||||
if (colon != std::string_view::npos) {
|
||||
size_t sp = raw.rfind(' ', colon);
|
||||
if (sp != std::string_view::npos) {
|
||||
raw = trim_ascii(raw.substr(0, sp));
|
||||
}
|
||||
}
|
||||
|
||||
// Try YYYY-MM-DD or YYYY/MM/DD or MM/DD/YYYY or DD-MM-YYYY
|
||||
auto split_sep = [&](char sep) -> std::vector<std::string_view> {
|
||||
std::vector<std::string_view> parts;
|
||||
size_t start = 0;
|
||||
while (true) {
|
||||
size_t p = raw.find(sep, start);
|
||||
if (p == std::string_view::npos) {
|
||||
parts.push_back(trim_ascii(raw.substr(start)));
|
||||
break;
|
||||
}
|
||||
parts.push_back(trim_ascii(raw.substr(start, p - start)));
|
||||
start = p + 1;
|
||||
}
|
||||
return parts;
|
||||
};
|
||||
|
||||
for (char sep : {'-', '/'}) {
|
||||
if (raw.find(sep) != std::string_view::npos) {
|
||||
auto p = split_sep(sep);
|
||||
if (p.size() == 3) {
|
||||
int a = 0, b = 0, c = 0;
|
||||
if (parse_uint(p[0], a) && parse_uint(p[1], b) && parse_uint(p[2], c)) {
|
||||
int y = 0, m = 0, d = 0;
|
||||
if (p[0].size() == 4) {
|
||||
y = a; m = b; d = c;
|
||||
} else {
|
||||
m = a; d = b; y = c;
|
||||
if (y < 100) y += (y >= 30 ? 1900 : 2000);
|
||||
}
|
||||
if (m >= 1 && m <= 12 && d >= 1 && d <= days_in_month(y, m)) {
|
||||
return ymd_to_serial(y, m, d);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
// Try DD-Mon-YYYY
|
||||
int mon = parse_month_name(p[1]);
|
||||
if (mon > 0 && parse_uint(p[0], a) && parse_uint(p[2], c)) {
|
||||
int y = c;
|
||||
if (y < 100) y += (y >= 30 ? 1900 : 2000);
|
||||
if (a >= 1 && a <= days_in_month(y, mon)) {
|
||||
return ymd_to_serial(y, mon, a);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try "Mon DD, YYYY" or "Mon DD YYYY"
|
||||
std::vector<std::string_view> words;
|
||||
size_t i = 0;
|
||||
while (i < raw.size()) {
|
||||
while (i < raw.size() && (raw[i] == ' ' || raw[i] == ',')) ++i;
|
||||
size_t st = i;
|
||||
while (i < raw.size() && raw[i] != ' ' && raw[i] != ',') ++i;
|
||||
if (i > st) words.push_back(raw.substr(st, i - st));
|
||||
}
|
||||
if (words.size() == 3) {
|
||||
int mon = parse_month_name(words[0]);
|
||||
int d = 0, y = 0;
|
||||
if (mon > 0 && parse_uint(words[1], d) && parse_uint(words[2], y)) {
|
||||
if (d >= 1 && d <= days_in_month(y, mon)) {
|
||||
return ymd_to_serial(y, mon, d);
|
||||
}
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::optional<double> parse_time_string(std::string_view raw) {
|
||||
raw = trim_ascii(raw);
|
||||
if (raw.empty()) return std::nullopt;
|
||||
|
||||
bool has_ampm = false;
|
||||
bool is_pm = false;
|
||||
if (raw.size() >= 2) {
|
||||
std::string_view tail = raw.substr(raw.size() - 2);
|
||||
if (iequals_ascii(tail, "AM") || iequals_ascii(tail, "PM")) {
|
||||
has_ampm = true;
|
||||
is_pm = iequals_ascii(tail, "PM");
|
||||
raw = trim_ascii(raw.substr(0, raw.size() - 2));
|
||||
}
|
||||
}
|
||||
|
||||
// If date precedes space before time, take last space-separated token
|
||||
size_t sp = raw.rfind(' ');
|
||||
if (sp != std::string_view::npos) {
|
||||
raw = trim_ascii(raw.substr(sp + 1));
|
||||
}
|
||||
|
||||
std::vector<std::string_view> parts;
|
||||
size_t start = 0;
|
||||
while (true) {
|
||||
size_t p = raw.find(':', start);
|
||||
if (p == std::string_view::npos) {
|
||||
parts.push_back(raw.substr(start));
|
||||
break;
|
||||
}
|
||||
parts.push_back(raw.substr(start, p - start));
|
||||
start = p + 1;
|
||||
}
|
||||
if (parts.size() < 2 || parts.size() > 3) return std::nullopt;
|
||||
|
||||
int h = 0, m = 0, s = 0;
|
||||
if (!parse_uint(parts[0], h) || !parse_uint(parts[1], m)) return std::nullopt;
|
||||
if (parts.size() == 3 && !parse_uint(parts[2], s)) return std::nullopt;
|
||||
|
||||
if (has_ampm) {
|
||||
if (h < 1 || h > 12) return std::nullopt;
|
||||
if (h == 12) h = 0;
|
||||
if (is_pm) h += 12;
|
||||
} else {
|
||||
if (h > 23) return std::nullopt;
|
||||
}
|
||||
if (m > 59 || s > 59) return std::nullopt;
|
||||
return static_cast<double>(h * 3600 + m * 60 + s) / 86400.0;
|
||||
}
|
||||
|
||||
EvalResult fn_date(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 3) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto yd = eval_number_arg(args[0], ctx, err);
|
||||
if (!yd) return err_res(err);
|
||||
auto md = eval_number_arg(args[1], ctx, err);
|
||||
if (!md) return err_res(err);
|
||||
auto dd = eval_number_arg(args[2], ctx, err);
|
||||
if (!dd) return err_res(err);
|
||||
|
||||
int y = static_cast<int>(std::trunc(*yd));
|
||||
int m = static_cast<int>(std::trunc(*md));
|
||||
int d = static_cast<int>(std::trunc(*dd));
|
||||
if (y < 0 || y >= 10000) return err_res(ErrorCode::Num);
|
||||
if (y < 1900) y += 1900;
|
||||
int serial = ymd_to_serial(y, m, d);
|
||||
if (serial < 0) return err_res(ErrorCode::Num);
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(serial)));
|
||||
}
|
||||
|
||||
EvalResult fn_datevalue(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto s = eval_string_arg(args[0], ctx, err);
|
||||
if (!s) return err_res(err);
|
||||
auto serial = parse_date_string(*s);
|
||||
if (!serial) return err_res(ErrorCode::Value);
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(*serial)));
|
||||
}
|
||||
|
||||
EvalResult fn_time(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 3) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto hd = eval_number_arg(args[0], ctx, err);
|
||||
if (!hd) return err_res(err);
|
||||
auto md = eval_number_arg(args[1], ctx, err);
|
||||
if (!md) return err_res(err);
|
||||
auto sd = eval_number_arg(args[2], ctx, err);
|
||||
if (!sd) return err_res(err);
|
||||
|
||||
long long total = static_cast<long long>(std::trunc(*hd)) * 3600LL +
|
||||
static_cast<long long>(std::trunc(*md)) * 60LL +
|
||||
static_cast<long long>(std::trunc(*sd));
|
||||
if (total < 0) return err_res(ErrorCode::Num);
|
||||
double frac = static_cast<double>(total % 86400LL) / 86400.0;
|
||||
return EvalResult::from_value(Value::make_number(frac));
|
||||
}
|
||||
|
||||
EvalResult fn_timevalue(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto s = eval_string_arg(args[0], ctx, err);
|
||||
if (!s) return err_res(err);
|
||||
auto t = parse_time_string(*s);
|
||||
if (!t) return err_res(ErrorCode::Value);
|
||||
return EvalResult::from_value(Value::make_number(*t));
|
||||
}
|
||||
|
||||
EvalResult fn_now(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext&) {
|
||||
if (!args.empty()) return err_res(ErrorCode::Value);
|
||||
std::time_t now_t = std::time(nullptr);
|
||||
std::tm local_tm{};
|
||||
localtime_r(&now_t, &local_tm);
|
||||
int serial = ymd_to_serial(local_tm.tm_year + 1900, local_tm.tm_mon + 1, local_tm.tm_mday);
|
||||
double frac = static_cast<double>(local_tm.tm_hour * 3600 + local_tm.tm_min * 60 +
|
||||
local_tm.tm_sec) /
|
||||
86400.0;
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(serial) + frac));
|
||||
}
|
||||
|
||||
EvalResult extract_ymd_part(const std::vector<std::shared_ptr<Expr>>& args,
|
||||
const EvalContext& ctx,
|
||||
int which) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto n = eval_number_arg(args[0], ctx, err);
|
||||
if (!n) return err_res(err);
|
||||
if (*n < 0.0) return err_res(ErrorCode::Num);
|
||||
int y = 0, m = 0, d = 0;
|
||||
serial_to_ymd(static_cast<int>(std::floor(*n)), y, m, d);
|
||||
int val = (which == 0) ? y : (which == 1 ? m : d);
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(val)));
|
||||
}
|
||||
|
||||
EvalResult extract_hms_part(const std::vector<std::shared_ptr<Expr>>& args,
|
||||
const EvalContext& ctx,
|
||||
int which) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto n = eval_number_arg(args[0], ctx, err);
|
||||
if (!n) return err_res(err);
|
||||
if (*n < 0.0) return err_res(ErrorCode::Num);
|
||||
int h = 0, m = 0, s = 0;
|
||||
serial_to_hms(*n, h, m, s);
|
||||
int val = (which == 0) ? h : (which == 1 ? m : s);
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(val)));
|
||||
}
|
||||
|
||||
EvalResult fn_year(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return extract_ymd_part(a, c, 0);
|
||||
}
|
||||
EvalResult fn_month(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return extract_ymd_part(a, c, 1);
|
||||
}
|
||||
EvalResult fn_day(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return extract_ymd_part(a, c, 2);
|
||||
}
|
||||
EvalResult fn_hour(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return extract_hms_part(a, c, 0);
|
||||
}
|
||||
EvalResult fn_minute(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return extract_hms_part(a, c, 1);
|
||||
}
|
||||
EvalResult fn_second(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return extract_hms_part(a, c, 2);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_datetime_functions(FunctionRegistry& reg) {
|
||||
reg.register_fn("DATE", fn_date);
|
||||
reg.register_fn("DATEVALUE", fn_datevalue);
|
||||
reg.register_fn("DAY", fn_day);
|
||||
reg.register_fn("HOUR", fn_hour);
|
||||
reg.register_fn("MINUTE", fn_minute);
|
||||
reg.register_fn("MONTH", fn_month);
|
||||
reg.register_fn("NOW", fn_now);
|
||||
reg.register_fn("SECOND", fn_second);
|
||||
reg.register_fn("TIME", fn_time);
|
||||
reg.register_fn("TIMEVALUE", fn_timevalue);
|
||||
reg.register_fn("YEAR", fn_year);
|
||||
}
|
||||
|
||||
} // namespace htab
|
||||
@@ -0,0 +1,377 @@
|
||||
#include "engine/functions/helpers.hpp"
|
||||
#include "engine/functions/registry.hpp"
|
||||
#include "engine/workbook.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <variant>
|
||||
|
||||
namespace htab {
|
||||
|
||||
using namespace htab::fn;
|
||||
|
||||
namespace {
|
||||
|
||||
double tvm_eval(double rate, double nper, double pmt, double pv, double fv, int type) {
|
||||
if (std::fabs(rate) < 1e-12) {
|
||||
return pv + pmt * nper + fv;
|
||||
}
|
||||
double factor = std::pow(1.0 + rate, nper);
|
||||
return pv * factor + pmt * (1.0 + rate * type) * ((factor - 1.0) / rate) + fv;
|
||||
}
|
||||
|
||||
EvalResult fn_fv(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 3 || args.size() > 5) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto rate = eval_number_arg(args[0], ctx, err);
|
||||
if (!rate) return err_res(err);
|
||||
auto nper = eval_number_arg(args[1], ctx, err);
|
||||
if (!nper) return err_res(err);
|
||||
auto pmt = eval_number_arg(args[2], ctx, err);
|
||||
if (!pmt) return err_res(err);
|
||||
double pv = 0.0;
|
||||
int type = 0;
|
||||
if (args.size() >= 4) {
|
||||
auto p = eval_number_arg(args[3], ctx, err);
|
||||
if (!p) return err_res(err);
|
||||
pv = *p;
|
||||
}
|
||||
if (args.size() == 5) {
|
||||
auto t = eval_number_arg(args[4], ctx, err);
|
||||
if (!t) return err_res(err);
|
||||
type = (*t != 0.0) ? 1 : 0;
|
||||
}
|
||||
double fv = 0.0;
|
||||
if (std::fabs(*rate) < 1e-12) {
|
||||
fv = -(pv + *pmt * *nper);
|
||||
} else {
|
||||
double factor = std::pow(1.0 + *rate, *nper);
|
||||
fv = -(pv * factor + *pmt * (1.0 + *rate * type) * ((factor - 1.0) / *rate));
|
||||
}
|
||||
return EvalResult::from_value(Value::make_checked_number(fv));
|
||||
}
|
||||
|
||||
EvalResult fn_pv(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 3 || args.size() > 5) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto rate = eval_number_arg(args[0], ctx, err);
|
||||
if (!rate) return err_res(err);
|
||||
auto nper = eval_number_arg(args[1], ctx, err);
|
||||
if (!nper) return err_res(err);
|
||||
auto pmt = eval_number_arg(args[2], ctx, err);
|
||||
if (!pmt) return err_res(err);
|
||||
double fv = 0.0;
|
||||
int type = 0;
|
||||
if (args.size() >= 4) {
|
||||
auto f = eval_number_arg(args[3], ctx, err);
|
||||
if (!f) return err_res(err);
|
||||
fv = *f;
|
||||
}
|
||||
if (args.size() == 5) {
|
||||
auto t = eval_number_arg(args[4], ctx, err);
|
||||
if (!t) return err_res(err);
|
||||
type = (*t != 0.0) ? 1 : 0;
|
||||
}
|
||||
double pv = 0.0;
|
||||
if (std::fabs(*rate) < 1e-12) {
|
||||
pv = -(*pmt * *nper + fv);
|
||||
} else {
|
||||
double factor = std::pow(1.0 + *rate, *nper);
|
||||
pv = -(fv + *pmt * (1.0 + *rate * type) * ((factor - 1.0) / *rate)) / factor;
|
||||
}
|
||||
return EvalResult::from_value(Value::make_checked_number(pv));
|
||||
}
|
||||
|
||||
EvalResult fn_pmt(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 3 || args.size() > 5) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto rate = eval_number_arg(args[0], ctx, err);
|
||||
if (!rate) return err_res(err);
|
||||
auto nper = eval_number_arg(args[1], ctx, err);
|
||||
if (!nper) return err_res(err);
|
||||
auto pv = eval_number_arg(args[2], ctx, err);
|
||||
if (!pv) return err_res(err);
|
||||
double fv = 0.0;
|
||||
int type = 0;
|
||||
if (args.size() >= 4) {
|
||||
auto f = eval_number_arg(args[3], ctx, err);
|
||||
if (!f) return err_res(err);
|
||||
fv = *f;
|
||||
}
|
||||
if (args.size() == 5) {
|
||||
auto t = eval_number_arg(args[4], ctx, err);
|
||||
if (!t) return err_res(err);
|
||||
type = (*t != 0.0) ? 1 : 0;
|
||||
}
|
||||
if (*nper == 0.0) return err_res(ErrorCode::Num);
|
||||
double pmt = 0.0;
|
||||
if (std::fabs(*rate) < 1e-12) {
|
||||
pmt = -(*pv + fv) / *nper;
|
||||
} else {
|
||||
double factor = std::pow(1.0 + *rate, *nper);
|
||||
double denom = (1.0 + *rate * type) * ((factor - 1.0) / *rate);
|
||||
if (denom == 0.0) return err_res(ErrorCode::Div0);
|
||||
pmt = -(*pv * factor + fv) / denom;
|
||||
}
|
||||
return EvalResult::from_value(Value::make_checked_number(pmt));
|
||||
}
|
||||
|
||||
EvalResult fn_nper(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 3 || args.size() > 5) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto rate = eval_number_arg(args[0], ctx, err);
|
||||
if (!rate) return err_res(err);
|
||||
auto pmt = eval_number_arg(args[1], ctx, err);
|
||||
if (!pmt) return err_res(err);
|
||||
auto pv = eval_number_arg(args[2], ctx, err);
|
||||
if (!pv) return err_res(err);
|
||||
double fv = 0.0;
|
||||
int type = 0;
|
||||
if (args.size() >= 4) {
|
||||
auto f = eval_number_arg(args[3], ctx, err);
|
||||
if (!f) return err_res(err);
|
||||
fv = *f;
|
||||
}
|
||||
if (args.size() == 5) {
|
||||
auto t = eval_number_arg(args[4], ctx, err);
|
||||
if (!t) return err_res(err);
|
||||
type = (*t != 0.0) ? 1 : 0;
|
||||
}
|
||||
if (std::fabs(*rate) < 1e-12) {
|
||||
if (*pmt == 0.0) return err_res(ErrorCode::Div0);
|
||||
return EvalResult::from_value(Value::make_checked_number(-(*pv + fv) / *pmt));
|
||||
}
|
||||
if (*rate <= -1.0) return err_res(ErrorCode::Num);
|
||||
double z = *pmt * (1.0 + *rate * type) / *rate;
|
||||
double num = z - fv;
|
||||
double den = z + *pv;
|
||||
if (den == 0.0 || num / den <= 0.0) return err_res(ErrorCode::Num);
|
||||
double nper = std::log(num / den) / std::log(1.0 + *rate);
|
||||
return EvalResult::from_value(Value::make_checked_number(nper));
|
||||
}
|
||||
|
||||
EvalResult fn_rate(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 3 || args.size() > 6) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto nper = eval_number_arg(args[0], ctx, err);
|
||||
if (!nper) return err_res(err);
|
||||
auto pmt = eval_number_arg(args[1], ctx, err);
|
||||
if (!pmt) return err_res(err);
|
||||
auto pv = eval_number_arg(args[2], ctx, err);
|
||||
if (!pv) return err_res(err);
|
||||
double fv = 0.0;
|
||||
int type = 0;
|
||||
double guess = 0.1;
|
||||
if (args.size() >= 4) {
|
||||
auto f = eval_number_arg(args[3], ctx, err);
|
||||
if (!f) return err_res(err);
|
||||
fv = *f;
|
||||
}
|
||||
if (args.size() >= 5) {
|
||||
auto t = eval_number_arg(args[4], ctx, err);
|
||||
if (!t) return err_res(err);
|
||||
type = (*t != 0.0) ? 1 : 0;
|
||||
}
|
||||
if (args.size() == 6) {
|
||||
auto g = eval_number_arg(args[5], ctx, err);
|
||||
if (!g) return err_res(err);
|
||||
guess = *g;
|
||||
}
|
||||
if (*nper <= 0.0) return err_res(ErrorCode::Num);
|
||||
|
||||
double r = guess;
|
||||
for (int iter = 0; iter < 100; ++iter) {
|
||||
if (r <= -1.0) r = -0.999;
|
||||
double f = tvm_eval(r, *nper, *pmt, *pv, fv, type);
|
||||
if (std::fabs(f) < 1e-10) return EvalResult::from_value(Value::make_checked_number(r));
|
||||
double eps = 1e-6;
|
||||
double df = (tvm_eval(r + eps, *nper, *pmt, *pv, fv, type) - f) / eps;
|
||||
if (!std::isfinite(df) || std::fabs(df) < 1e-14) break;
|
||||
double nr = r - f / df;
|
||||
if (nr <= -1.0) nr = (r - 1.0) * 0.5;
|
||||
if (std::fabs(nr - r) < 1e-10) {
|
||||
return EvalResult::from_value(Value::make_checked_number(nr));
|
||||
}
|
||||
r = nr;
|
||||
}
|
||||
return err_res(ErrorCode::Num);
|
||||
}
|
||||
|
||||
EvalResult fn_npv(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 2) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto rate = eval_number_arg(args[0], ctx, err);
|
||||
if (!rate) return err_res(err);
|
||||
if (*rate == -1.0) return err_res(ErrorCode::Div0);
|
||||
|
||||
std::vector<std::shared_ptr<Expr>> cf_args(args.begin() + 1, args.end());
|
||||
std::vector<double> cfs;
|
||||
if (auto cerr = collect_numeric_args(cf_args, ctx, cfs)) return err_res(*cerr);
|
||||
|
||||
double total = 0.0;
|
||||
double denom = 1.0 + *rate;
|
||||
double pow_d = denom;
|
||||
for (double cf : cfs) {
|
||||
total += cf / pow_d;
|
||||
pow_d *= denom;
|
||||
}
|
||||
return EvalResult::from_value(Value::make_checked_number(total));
|
||||
}
|
||||
|
||||
EvalResult fn_irr(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.empty() || args.size() > 2) return err_res(ErrorCode::Value);
|
||||
std::vector<std::shared_ptr<Expr>> single{args[0]};
|
||||
std::vector<double> cfs;
|
||||
if (auto err = collect_numeric_args(single, ctx, cfs)) return err_res(*err);
|
||||
if (cfs.size() < 2) return err_res(ErrorCode::Num);
|
||||
|
||||
bool has_pos = false, has_neg = false;
|
||||
for (double v : cfs) {
|
||||
if (v > 0.0) has_pos = true;
|
||||
if (v < 0.0) has_neg = true;
|
||||
}
|
||||
if (!has_pos || !has_neg) return err_res(ErrorCode::Num);
|
||||
|
||||
double guess = 0.1;
|
||||
if (args.size() == 2) {
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto g = eval_number_arg(args[1], ctx, err);
|
||||
if (!g) return err_res(err);
|
||||
guess = *g;
|
||||
}
|
||||
|
||||
auto eval_npv_and_deriv = [&](double r, double& f, double& df) {
|
||||
double base = 1.0 + r;
|
||||
f = 0.0;
|
||||
df = 0.0;
|
||||
double pow_b = 1.0;
|
||||
for (size_t i = 0; i < cfs.size(); ++i) {
|
||||
f += cfs[i] / pow_b;
|
||||
if (i > 0) {
|
||||
df -= static_cast<double>(i) * cfs[i] / (pow_b * base);
|
||||
}
|
||||
pow_b *= base;
|
||||
}
|
||||
};
|
||||
|
||||
double r = guess;
|
||||
for (int iter = 0; iter < 100; ++iter) {
|
||||
if (r <= -1.0) r = -0.999;
|
||||
double f = 0.0, df = 0.0;
|
||||
eval_npv_and_deriv(r, f, df);
|
||||
if (std::fabs(f) < 1e-10) return EvalResult::from_value(Value::make_checked_number(r));
|
||||
if (!std::isfinite(df) || std::fabs(df) < 1e-14) break;
|
||||
double nr = r - f / df;
|
||||
if (nr <= -1.0) nr = (r - 1.0) * 0.5;
|
||||
if (std::fabs(nr - r) < 1e-10) {
|
||||
return EvalResult::from_value(Value::make_checked_number(nr));
|
||||
}
|
||||
r = nr;
|
||||
}
|
||||
|
||||
// Bisection fallback on (-0.9999, 100.0]
|
||||
double lo = -0.99, hi = 10.0, f_lo = 0.0, df_unused = 0.0, f_hi = 0.0;
|
||||
eval_npv_and_deriv(lo, f_lo, df_unused);
|
||||
eval_npv_and_deriv(hi, f_hi, df_unused);
|
||||
if (f_lo * f_hi <= 0.0) {
|
||||
for (int iter = 0; iter < 120; ++iter) {
|
||||
double mid = 0.5 * (lo + hi);
|
||||
double f_mid = 0.0;
|
||||
eval_npv_and_deriv(mid, f_mid, df_unused);
|
||||
if (std::fabs(f_mid) < 1e-10 || (hi - lo) < 1e-12) {
|
||||
return EvalResult::from_value(Value::make_checked_number(mid));
|
||||
}
|
||||
if (f_lo * f_mid <= 0.0) {
|
||||
hi = mid;
|
||||
f_hi = f_mid;
|
||||
} else {
|
||||
lo = mid;
|
||||
f_lo = f_mid;
|
||||
}
|
||||
}
|
||||
}
|
||||
return err_res(ErrorCode::Num);
|
||||
}
|
||||
|
||||
EvalResult fn_sln(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 3) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto cost = eval_number_arg(args[0], ctx, err);
|
||||
if (!cost) return err_res(err);
|
||||
auto salvage = eval_number_arg(args[1], ctx, err);
|
||||
if (!salvage) return err_res(err);
|
||||
auto life = eval_number_arg(args[2], ctx, err);
|
||||
if (!life) return err_res(err);
|
||||
if (*life == 0.0) return err_res(ErrorCode::Div0);
|
||||
return EvalResult::from_value(Value::make_checked_number((*cost - *salvage) / *life));
|
||||
}
|
||||
|
||||
EvalResult fn_syd(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 4) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto cost = eval_number_arg(args[0], ctx, err);
|
||||
if (!cost) return err_res(err);
|
||||
auto salvage = eval_number_arg(args[1], ctx, err);
|
||||
if (!salvage) return err_res(err);
|
||||
auto life = eval_number_arg(args[2], ctx, err);
|
||||
if (!life) return err_res(err);
|
||||
auto per = eval_number_arg(args[3], ctx, err);
|
||||
if (!per) return err_res(err);
|
||||
if (*life <= 0.0 || *per <= 0.0 || *per > *life) return err_res(ErrorCode::Num);
|
||||
double res = ((*cost - *salvage) * (*life - *per + 1.0) * 2.0) / (*life * (*life + 1.0));
|
||||
return EvalResult::from_value(Value::make_checked_number(res));
|
||||
}
|
||||
|
||||
EvalResult fn_ddb(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 4 || args.size() > 5) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto cost = eval_number_arg(args[0], ctx, err);
|
||||
if (!cost) return err_res(err);
|
||||
auto salvage = eval_number_arg(args[1], ctx, err);
|
||||
if (!salvage) return err_res(err);
|
||||
auto life = eval_number_arg(args[2], ctx, err);
|
||||
if (!life) return err_res(err);
|
||||
auto period = eval_number_arg(args[3], ctx, err);
|
||||
if (!period) return err_res(err);
|
||||
double factor = 2.0;
|
||||
if (args.size() == 5) {
|
||||
auto f = eval_number_arg(args[4], ctx, err);
|
||||
if (!f) return err_res(err);
|
||||
factor = *f;
|
||||
}
|
||||
if (*cost < 0.0 || *salvage < 0.0 || *life <= 0.0 || *period <= 0.0 ||
|
||||
*period > *life || factor <= 0.0) {
|
||||
return err_res(ErrorCode::Num);
|
||||
}
|
||||
if (*cost <= *salvage) return EvalResult::from_value(Value::make_number(0.0));
|
||||
|
||||
double book = *cost;
|
||||
double rate = std::min(1.0, factor / *life);
|
||||
int full_p = static_cast<int>(std::floor(*period));
|
||||
double dep = 0.0;
|
||||
for (int p = 1; p <= full_p; ++p) {
|
||||
dep = std::min(book * rate, std::max(0.0, book - *salvage));
|
||||
book -= dep;
|
||||
}
|
||||
double rem = *period - static_cast<double>(full_p);
|
||||
if (rem > 1e-12) {
|
||||
dep = std::min(book * rate * rem, std::max(0.0, book - *salvage));
|
||||
}
|
||||
return EvalResult::from_value(Value::make_checked_number(dep));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_financial_functions(FunctionRegistry& reg) {
|
||||
reg.register_fn("DDB", fn_ddb);
|
||||
reg.register_fn("FV", fn_fv);
|
||||
reg.register_fn("IRR", fn_irr);
|
||||
reg.register_fn("NPER", fn_nper);
|
||||
reg.register_fn("NPV", fn_npv);
|
||||
reg.register_fn("PMT", fn_pmt);
|
||||
reg.register_fn("PV", fn_pv);
|
||||
reg.register_fn("RATE", fn_rate);
|
||||
reg.register_fn("SLN", fn_sln);
|
||||
reg.register_fn("SYD", fn_syd);
|
||||
}
|
||||
|
||||
} // namespace htab
|
||||
@@ -0,0 +1,387 @@
|
||||
#include "engine/functions/helpers.hpp"
|
||||
#include "engine/workbook.hpp"
|
||||
|
||||
#include <cctype>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace htab::fn {
|
||||
|
||||
namespace {
|
||||
|
||||
std::optional<double> try_parse_simple_number(std::string_view sv) {
|
||||
sv = trim_ascii(sv);
|
||||
if (sv.empty()) return std::nullopt;
|
||||
bool pct = false;
|
||||
if (sv.back() == '%') {
|
||||
pct = true;
|
||||
sv.remove_suffix(1);
|
||||
sv = trim_ascii(sv);
|
||||
if (sv.empty()) return std::nullopt;
|
||||
}
|
||||
size_t i = 0;
|
||||
if (sv[i] == '+' || sv[i] == '-') ++i;
|
||||
bool has_digits = false;
|
||||
while (i < sv.size() && std::isdigit(static_cast<unsigned char>(sv[i]))) {
|
||||
has_digits = true;
|
||||
++i;
|
||||
}
|
||||
if (i < sv.size() && sv[i] == '.') {
|
||||
++i;
|
||||
while (i < sv.size() && std::isdigit(static_cast<unsigned char>(sv[i]))) {
|
||||
has_digits = true;
|
||||
++i;
|
||||
}
|
||||
}
|
||||
if (!has_digits) return std::nullopt;
|
||||
if (i < sv.size() && (sv[i] == 'e' || sv[i] == 'E')) {
|
||||
++i;
|
||||
if (i < sv.size() && (sv[i] == '+' || sv[i] == '-')) ++i;
|
||||
bool exp_d = false;
|
||||
while (i < sv.size() && std::isdigit(static_cast<unsigned char>(sv[i]))) {
|
||||
exp_d = true;
|
||||
++i;
|
||||
}
|
||||
if (!exp_d) return std::nullopt;
|
||||
}
|
||||
if (i != sv.size()) return std::nullopt;
|
||||
std::string tmp(sv);
|
||||
char* endptr = nullptr;
|
||||
double val = std::strtod(tmp.c_str(), &endptr);
|
||||
if (endptr != tmp.c_str() + tmp.size() || !std::isfinite(val)) return std::nullopt;
|
||||
if (pct) val /= 100.0;
|
||||
return val == 0.0 ? 0.0 : val;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> parse_wildcard_tokens(std::string_view pat) {
|
||||
auto raw_cps = utf8_codepoints(pat);
|
||||
std::vector<std::string_view> out;
|
||||
out.reserve(raw_cps.size());
|
||||
for (size_t i = 0; i < raw_cps.size(); ++i) {
|
||||
out.push_back(raw_cps[i]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
struct PatAtom {
|
||||
enum Kind { WildMany, WildOne, Literal };
|
||||
Kind kind = Literal;
|
||||
std::string_view cp;
|
||||
};
|
||||
|
||||
std::vector<PatAtom> compile_wildcard(std::string_view pattern) {
|
||||
auto cps = parse_wildcard_tokens(pattern);
|
||||
std::vector<PatAtom> atoms;
|
||||
atoms.reserve(cps.size());
|
||||
for (size_t i = 0; i < cps.size(); ++i) {
|
||||
if (cps[i] == "~" && i + 1 < cps.size()) {
|
||||
atoms.push_back({PatAtom::Literal, cps[i + 1]});
|
||||
++i;
|
||||
} else if (cps[i] == "*") {
|
||||
if (atoms.empty() || atoms.back().kind != PatAtom::WildMany) {
|
||||
atoms.push_back({PatAtom::WildMany, {}});
|
||||
}
|
||||
} else if (cps[i] == "?") {
|
||||
atoms.push_back({PatAtom::WildOne, {}});
|
||||
} else {
|
||||
atoms.push_back({PatAtom::Literal, cps[i]});
|
||||
}
|
||||
}
|
||||
return atoms;
|
||||
}
|
||||
|
||||
bool cp_iequals(std::string_view a, std::string_view b) {
|
||||
if (a.size() == 1 && b.size() == 1) {
|
||||
return std::tolower(static_cast<unsigned char>(a[0])) ==
|
||||
std::tolower(static_cast<unsigned char>(b[0]));
|
||||
}
|
||||
return a == b;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::optional<Value> eval_scalar_arg(const std::shared_ptr<Expr>& expr,
|
||||
const EvalContext& ctx) {
|
||||
Value v = deref_to_value(evaluate_ast(expr.get(), ctx), *ctx.wb);
|
||||
return v;
|
||||
}
|
||||
|
||||
std::optional<double> eval_number_arg(const std::shared_ptr<Expr>& expr,
|
||||
const EvalContext& ctx,
|
||||
ErrorCode& err_out) {
|
||||
Value v = deref_to_value(evaluate_ast(expr.get(), ctx), *ctx.wb);
|
||||
auto n = to_number(v);
|
||||
if (std::holds_alternative<ErrorCode>(n)) {
|
||||
err_out = std::get<ErrorCode>(n);
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::get<double>(n);
|
||||
}
|
||||
|
||||
std::optional<bool> eval_bool_arg(const std::shared_ptr<Expr>& expr,
|
||||
const EvalContext& ctx,
|
||||
ErrorCode& err_out) {
|
||||
Value v = deref_to_value(evaluate_ast(expr.get(), ctx), *ctx.wb);
|
||||
auto b = to_bool(v);
|
||||
if (std::holds_alternative<ErrorCode>(b)) {
|
||||
err_out = std::get<ErrorCode>(b);
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::get<bool>(b);
|
||||
}
|
||||
|
||||
std::optional<std::string> eval_string_arg(const std::shared_ptr<Expr>& expr,
|
||||
const EvalContext& ctx,
|
||||
ErrorCode& err_out) {
|
||||
Value v = deref_to_value(evaluate_ast(expr.get(), ctx), *ctx.wb);
|
||||
auto s = to_string(v);
|
||||
if (std::holds_alternative<ErrorCode>(s)) {
|
||||
err_out = std::get<ErrorCode>(s);
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::get<std::string>(s);
|
||||
}
|
||||
|
||||
std::optional<ErrorCode> collect_numeric_args(
|
||||
const std::vector<std::shared_ptr<Expr>>& args,
|
||||
const EvalContext& ctx,
|
||||
std::vector<double>& out_nums) {
|
||||
for (const auto& arg : args) {
|
||||
EvalResult res = evaluate_ast(arg.get(), ctx);
|
||||
if (res.is_ref) {
|
||||
for (const auto& rng : res.ranges) {
|
||||
for (int r = rng.r1; r <= rng.r2; ++r) {
|
||||
for (int c = rng.c1; c <= rng.c2; ++c) {
|
||||
Value v = ctx.wb->get_scalar_value(rng.sheet, r, c);
|
||||
if (v.is_error()) return v.as_error();
|
||||
if (v.is_number()) out_nums.push_back(v.as_number());
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (res.value.is_array()) {
|
||||
const auto& arr = res.value.as_array();
|
||||
if (arr) {
|
||||
for (const auto& v : arr->data) {
|
||||
if (v.is_error()) return v.as_error();
|
||||
if (v.is_number()) out_nums.push_back(v.as_number());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const Value& v = res.value;
|
||||
if (v.is_error()) return v.as_error();
|
||||
if (v.is_empty()) continue;
|
||||
auto num = to_number(v);
|
||||
if (std::holds_alternative<ErrorCode>(num)) {
|
||||
return std::get<ErrorCode>(num);
|
||||
}
|
||||
out_nums.push_back(std::get<double>(num));
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
std::variant<Array2D, ErrorCode> result_to_array2d(const EvalResult& res,
|
||||
const Workbook& wb) {
|
||||
if (res.is_ref) {
|
||||
if (res.ranges.size() != 1) return ErrorCode::Value;
|
||||
const CellRange& rng = res.ranges[0];
|
||||
int rc = rng.row_count();
|
||||
int cc = rng.col_count();
|
||||
Array2D arr(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 arr;
|
||||
}
|
||||
if (res.value.is_error()) return res.value.as_error();
|
||||
if (res.value.is_array()) {
|
||||
const auto& p = res.value.as_array();
|
||||
if (!p) return ErrorCode::Value;
|
||||
return *p;
|
||||
}
|
||||
Array2D single(1, 1, res.value);
|
||||
return single;
|
||||
}
|
||||
|
||||
std::vector<std::string_view> utf8_codepoints(std::string_view s) {
|
||||
std::vector<std::string_view> cps;
|
||||
size_t i = 0;
|
||||
while (i < s.size()) {
|
||||
unsigned char b = static_cast<unsigned char>(s[i]);
|
||||
size_t len = 1;
|
||||
if ((b & 0x80) == 0) len = 1;
|
||||
else if ((b & 0xE0) == 0xC0) len = 2;
|
||||
else if ((b & 0xF0) == 0xE0) len = 3;
|
||||
else if ((b & 0xF8) == 0xF0) len = 4;
|
||||
if (i + len > s.size()) len = 1;
|
||||
cps.push_back(s.substr(i, len));
|
||||
i += len;
|
||||
}
|
||||
return cps;
|
||||
}
|
||||
|
||||
std::string utf8_join(const std::vector<std::string_view>& cps, size_t start, size_t count) {
|
||||
std::string out;
|
||||
size_t end = std::min(cps.size(), start + count);
|
||||
for (size_t i = start; i < end; ++i) {
|
||||
out.append(cps[i]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
bool wildcard_match_ci(std::string_view pattern, std::string_view text) {
|
||||
auto atoms = compile_wildcard(pattern);
|
||||
auto text_cps = utf8_codepoints(text);
|
||||
size_t m = atoms.size();
|
||||
size_t n = text_cps.size();
|
||||
|
||||
std::vector<bool> prev(n + 1, false), curr(n + 1, false);
|
||||
prev[0] = true;
|
||||
for (size_t i = 0; i < m; ++i) {
|
||||
std::fill(curr.begin(), curr.end(), false);
|
||||
if (atoms[i].kind == PatAtom::WildMany) {
|
||||
curr[0] = prev[0];
|
||||
for (size_t j = 1; j <= n; ++j) {
|
||||
curr[j] = prev[j] || curr[j - 1];
|
||||
}
|
||||
} else if (atoms[i].kind == PatAtom::WildOne) {
|
||||
for (size_t j = 1; j <= n; ++j) {
|
||||
curr[j] = prev[j - 1];
|
||||
}
|
||||
} else {
|
||||
for (size_t j = 1; j <= n; ++j) {
|
||||
if (prev[j - 1] && cp_iequals(atoms[i].cp, text_cps[j - 1])) {
|
||||
curr[j] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
prev.swap(curr);
|
||||
}
|
||||
return prev[n];
|
||||
}
|
||||
|
||||
bool matches_criteria(const Value& cell_val, const Value& criteria_val) {
|
||||
if (criteria_val.is_error()) {
|
||||
return cell_val.is_error() && cell_val.as_error() == criteria_val.as_error();
|
||||
}
|
||||
if (criteria_val.is_empty()) {
|
||||
return cell_val.is_empty() ||
|
||||
(cell_val.is_string() && cell_val.as_string().empty());
|
||||
}
|
||||
if (criteria_val.is_number()) {
|
||||
if (cell_val.is_number()) return cell_val.as_number() == criteria_val.as_number();
|
||||
if (cell_val.is_string()) {
|
||||
auto n = try_parse_simple_number(cell_val.as_string());
|
||||
return n.has_value() && *n == criteria_val.as_number();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (criteria_val.is_bool()) {
|
||||
return cell_val.is_bool() && cell_val.as_bool() == criteria_val.as_bool();
|
||||
}
|
||||
if (!criteria_val.is_string()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
std::string_view crit = criteria_val.as_string();
|
||||
enum class Op { Eq, Neq, Lt, Gt, Le, Ge };
|
||||
Op op = Op::Eq;
|
||||
bool has_explicit_op = false;
|
||||
if (crit.rfind("<=", 0) == 0) { op = Op::Le; crit.remove_prefix(2); has_explicit_op = true; }
|
||||
else if (crit.rfind(">=", 0) == 0) { op = Op::Ge; crit.remove_prefix(2); has_explicit_op = true; }
|
||||
else if (crit.rfind("<>", 0) == 0) { op = Op::Neq; crit.remove_prefix(2); has_explicit_op = true; }
|
||||
else if (!crit.empty() && crit[0] == '<') { op = Op::Lt; crit.remove_prefix(1); has_explicit_op = true; }
|
||||
else if (!crit.empty() && crit[0] == '>') { op = Op::Gt; crit.remove_prefix(1); has_explicit_op = true; }
|
||||
else if (!crit.empty() && crit[0] == '=') { op = Op::Eq; crit.remove_prefix(1); has_explicit_op = true; }
|
||||
|
||||
// Special empty checks "=" and "<>"
|
||||
if (has_explicit_op && crit.empty()) {
|
||||
bool is_cell_blank = cell_val.is_empty() ||
|
||||
(cell_val.is_string() && cell_val.as_string().empty());
|
||||
if (op == Op::Eq) return is_cell_blank;
|
||||
if (op == Op::Neq) return !is_cell_blank;
|
||||
return false;
|
||||
}
|
||||
|
||||
auto rhs_num = try_parse_simple_number(crit);
|
||||
if (rhs_num.has_value()) {
|
||||
if (cell_val.is_number()) {
|
||||
double cv = cell_val.as_number();
|
||||
double rv = *rhs_num;
|
||||
switch (op) {
|
||||
case Op::Eq: return cv == rv;
|
||||
case Op::Neq: return cv != rv;
|
||||
case Op::Lt: return cv < rv;
|
||||
case Op::Gt: return cv > rv;
|
||||
case Op::Le: return cv <= rv;
|
||||
case Op::Ge: return cv >= rv;
|
||||
}
|
||||
}
|
||||
if (op == Op::Neq) {
|
||||
if (cell_val.is_string()) {
|
||||
auto cn = try_parse_simple_number(cell_val.as_string());
|
||||
if (cn.has_value()) return *cn != *rhs_num;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (op == Op::Eq && cell_val.is_string()) {
|
||||
auto cn = try_parse_simple_number(cell_val.as_string());
|
||||
return cn.has_value() && *cn == *rhs_num;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Boolean criteria literal
|
||||
std::string_view crit_trim = trim_ascii(crit);
|
||||
if (iequals_ascii(crit_trim, "TRUE") || iequals_ascii(crit_trim, "FALSE")) {
|
||||
bool rb = iequals_ascii(crit_trim, "TRUE");
|
||||
if (cell_val.is_bool()) {
|
||||
bool cb = cell_val.as_bool();
|
||||
switch (op) {
|
||||
case Op::Eq: return cb == rb;
|
||||
case Op::Neq: return cb != rb;
|
||||
case Op::Lt: return !cb && rb;
|
||||
case Op::Gt: return cb && !rb;
|
||||
case Op::Le: return cb <= rb;
|
||||
case Op::Ge: return cb >= rb;
|
||||
}
|
||||
}
|
||||
return op == Op::Neq;
|
||||
}
|
||||
|
||||
// Error criteria literal
|
||||
if (auto rerr = parse_error_code(crit_trim)) {
|
||||
bool same = cell_val.is_error() && cell_val.as_error() == *rerr;
|
||||
if (op == Op::Eq) return same;
|
||||
if (op == Op::Neq) return !same;
|
||||
return false;
|
||||
}
|
||||
|
||||
// String comparison / wildcard matching
|
||||
if (op == Op::Eq) {
|
||||
if (cell_val.is_empty()) return crit.empty();
|
||||
if (!cell_val.is_string()) return false;
|
||||
return wildcard_match_ci(crit, cell_val.as_string());
|
||||
}
|
||||
if (op == Op::Neq) {
|
||||
if (cell_val.is_empty()) return !crit.empty();
|
||||
if (!cell_val.is_string()) return true;
|
||||
return !wildcard_match_ci(crit, cell_val.as_string());
|
||||
}
|
||||
// Relational string comparison (<, >, <=, >=)
|
||||
if (!cell_val.is_string()) return false;
|
||||
auto cmp = compare_values(cell_val, Value::make_string(std::string(crit)));
|
||||
if (!std::holds_alternative<int>(cmp)) return false;
|
||||
int c = std::get<int>(cmp);
|
||||
switch (op) {
|
||||
case Op::Lt: return c < 0;
|
||||
case Op::Gt: return c > 0;
|
||||
case Op::Le: return c <= 0;
|
||||
case Op::Ge: return c >= 0;
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace htab::fn
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include "engine/evaluator.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace htab::fn {
|
||||
|
||||
inline EvalResult err_res(ErrorCode e) {
|
||||
return EvalResult::from_value(Value::make_error(e));
|
||||
}
|
||||
|
||||
std::optional<Value> eval_scalar_arg(const std::shared_ptr<Expr>& expr,
|
||||
const EvalContext& ctx);
|
||||
|
||||
std::optional<double> eval_number_arg(const std::shared_ptr<Expr>& expr,
|
||||
const EvalContext& ctx,
|
||||
ErrorCode& err_out);
|
||||
|
||||
std::optional<bool> eval_bool_arg(const std::shared_ptr<Expr>& expr,
|
||||
const EvalContext& ctx,
|
||||
ErrorCode& err_out);
|
||||
|
||||
std::optional<std::string> eval_string_arg(const std::shared_ptr<Expr>& expr,
|
||||
const EvalContext& ctx,
|
||||
ErrorCode& err_out);
|
||||
|
||||
// Collects numeric values from variadic arguments following spreadsheet semantics:
|
||||
// - Range/Array args: only numbers (ignoring Empty, String, Bool); Error propagates.
|
||||
// - Direct scalar args: coerces numbers, booleans, numeric strings; Empty ignored;
|
||||
// invalid text -> #VALUE!; Error propagates.
|
||||
std::optional<ErrorCode> collect_numeric_args(
|
||||
const std::vector<std::shared_ptr<Expr>>& args,
|
||||
const EvalContext& ctx,
|
||||
std::vector<double>& out_nums);
|
||||
|
||||
// Converts a single EvalResult (CellRange or Value) to Array2D.
|
||||
std::variant<Array2D, ErrorCode> result_to_array2d(const EvalResult& res,
|
||||
const Workbook& wb);
|
||||
|
||||
// Shared criteria matcher used by SUMIF/SUMIFS/COUNTIF/COUNTIFS/Database.
|
||||
bool matches_criteria(const Value& cell_val, const Value& criteria_val);
|
||||
bool wildcard_match_ci(std::string_view pattern, std::string_view text);
|
||||
|
||||
// UTF-8 codepoint helpers
|
||||
std::vector<std::string_view> utf8_codepoints(std::string_view s);
|
||||
std::string utf8_join(const std::vector<std::string_view>& cps, size_t start, size_t count);
|
||||
|
||||
} // namespace htab::fn
|
||||
@@ -0,0 +1,122 @@
|
||||
#include "engine/functions/helpers.hpp"
|
||||
#include "engine/functions/registry.hpp"
|
||||
#include "engine/workbook.hpp"
|
||||
|
||||
#include <variant>
|
||||
|
||||
namespace htab {
|
||||
|
||||
using namespace htab::fn;
|
||||
|
||||
namespace {
|
||||
|
||||
std::optional<ErrorCode> collect_logicals(const std::vector<std::shared_ptr<Expr>>& args,
|
||||
const EvalContext& ctx,
|
||||
bool& any_found,
|
||||
bool is_and,
|
||||
bool& acc) {
|
||||
any_found = false;
|
||||
acc = is_and;
|
||||
for (const auto& arg : args) {
|
||||
EvalResult res = evaluate_ast(arg.get(), ctx);
|
||||
if (res.is_ref) {
|
||||
for (const auto& rng : res.ranges) {
|
||||
for (int r = rng.r1; r <= rng.r2; ++r) {
|
||||
for (int c = rng.c1; c <= rng.c2; ++c) {
|
||||
Value v = ctx.wb->get_scalar_value(rng.sheet, r, c);
|
||||
if (v.is_error()) return v.as_error();
|
||||
if (v.is_bool()) {
|
||||
any_found = true;
|
||||
acc = is_and ? (acc && v.as_bool()) : (acc || v.as_bool());
|
||||
} else if (v.is_number()) {
|
||||
any_found = true;
|
||||
bool b = (v.as_number() != 0.0);
|
||||
acc = is_and ? (acc && b) : (acc || b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (res.value.is_array()) {
|
||||
const auto& arr = res.value.as_array();
|
||||
if (arr) {
|
||||
for (const auto& v : arr->data) {
|
||||
if (v.is_error()) return v.as_error();
|
||||
if (v.is_bool()) {
|
||||
any_found = true;
|
||||
acc = is_and ? (acc && v.as_bool()) : (acc || v.as_bool());
|
||||
} else if (v.is_number()) {
|
||||
any_found = true;
|
||||
bool b = (v.as_number() != 0.0);
|
||||
acc = is_and ? (acc && b) : (acc || b);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const Value& v = res.value;
|
||||
if (v.is_error()) return v.as_error();
|
||||
if (v.is_empty()) continue;
|
||||
auto b = to_bool(v);
|
||||
if (std::holds_alternative<ErrorCode>(b)) return std::get<ErrorCode>(b);
|
||||
any_found = true;
|
||||
acc = is_and ? (acc && std::get<bool>(b)) : (acc || std::get<bool>(b));
|
||||
}
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
EvalResult fn_and(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.empty()) return err_res(ErrorCode::Value);
|
||||
bool any = false, acc = true;
|
||||
if (auto err = collect_logicals(args, ctx, any, true, acc)) return err_res(*err);
|
||||
if (!any) return err_res(ErrorCode::Value);
|
||||
return EvalResult::from_value(Value::make_bool(acc));
|
||||
}
|
||||
|
||||
EvalResult fn_or(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.empty()) return err_res(ErrorCode::Value);
|
||||
bool any = false, acc = false;
|
||||
if (auto err = collect_logicals(args, ctx, any, false, acc)) return err_res(*err);
|
||||
if (!any) return err_res(ErrorCode::Value);
|
||||
return EvalResult::from_value(Value::make_bool(acc));
|
||||
}
|
||||
|
||||
EvalResult fn_not(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto b = eval_bool_arg(args[0], ctx, err);
|
||||
if (!b) return err_res(err);
|
||||
return EvalResult::from_value(Value::make_bool(!*b));
|
||||
}
|
||||
|
||||
EvalResult fn_if(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 2 || args.size() > 3) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto b = eval_bool_arg(args[0], ctx, err);
|
||||
if (!b) return err_res(err);
|
||||
if (*b) return evaluate_ast(args[1].get(), ctx);
|
||||
if (args.size() == 3) return evaluate_ast(args[2].get(), ctx);
|
||||
return EvalResult::from_value(Value::make_bool(false));
|
||||
}
|
||||
|
||||
EvalResult fn_true(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext&) {
|
||||
if (!args.empty()) return err_res(ErrorCode::Value);
|
||||
return EvalResult::from_value(Value::make_bool(true));
|
||||
}
|
||||
|
||||
EvalResult fn_false(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext&) {
|
||||
if (!args.empty()) return err_res(ErrorCode::Value);
|
||||
return EvalResult::from_value(Value::make_bool(false));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_logical_functions(FunctionRegistry& reg) {
|
||||
reg.register_fn("AND", fn_and);
|
||||
reg.register_fn("FALSE", fn_false);
|
||||
reg.register_fn("IF", fn_if);
|
||||
reg.register_fn("NOT", fn_not);
|
||||
reg.register_fn("OR", fn_or);
|
||||
reg.register_fn("TRUE", fn_true);
|
||||
}
|
||||
|
||||
} // namespace htab
|
||||
@@ -0,0 +1,353 @@
|
||||
#include "engine/functions/helpers.hpp"
|
||||
#include "engine/functions/registry.hpp"
|
||||
#include "engine/workbook.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <variant>
|
||||
|
||||
namespace htab {
|
||||
|
||||
using namespace htab::fn;
|
||||
|
||||
namespace {
|
||||
|
||||
bool values_equal_for_lookup(const Value& candidate, const Value& key) {
|
||||
if (candidate.is_error() || key.is_error() || candidate.is_empty() || key.is_empty()) {
|
||||
return false;
|
||||
}
|
||||
if (key.is_string() && candidate.is_string()) {
|
||||
return wildcard_match_ci(key.as_string(), candidate.as_string());
|
||||
}
|
||||
if (key.is_number() && candidate.is_number()) {
|
||||
return candidate.as_number() == key.as_number();
|
||||
}
|
||||
if (key.is_bool() && candidate.is_bool()) {
|
||||
return candidate.as_bool() == key.as_bool();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool same_lookup_type(const Value& a, const Value& b) {
|
||||
return (a.is_number() && b.is_number()) ||
|
||||
(a.is_string() && b.is_string()) ||
|
||||
(a.is_bool() && b.is_bool());
|
||||
}
|
||||
|
||||
EvalResult fn_choose(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 2) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto idx_d = eval_number_arg(args[0], ctx, err);
|
||||
if (!idx_d) return err_res(err);
|
||||
int idx = static_cast<int>(std::trunc(*idx_d));
|
||||
if (idx < 1 || static_cast<size_t>(idx) >= args.size()) return err_res(ErrorCode::Value);
|
||||
return evaluate_ast(args[static_cast<size_t>(idx)].get(), ctx);
|
||||
}
|
||||
|
||||
EvalResult fn_rows(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
EvalResult res = evaluate_ast(args[0].get(), ctx);
|
||||
if (res.is_ref) {
|
||||
if (res.ranges.size() != 1) return err_res(ErrorCode::Value);
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(res.ranges[0].row_count())));
|
||||
}
|
||||
if (res.value.is_error()) return EvalResult::from_value(res.value);
|
||||
if (res.value.is_array()) {
|
||||
const auto& arr = res.value.as_array();
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(arr ? arr->rows : 0)));
|
||||
}
|
||||
return EvalResult::from_value(Value::make_number(1.0));
|
||||
}
|
||||
|
||||
EvalResult fn_columns(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
EvalResult res = evaluate_ast(args[0].get(), ctx);
|
||||
if (res.is_ref) {
|
||||
if (res.ranges.size() != 1) return err_res(ErrorCode::Value);
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(res.ranges[0].col_count())));
|
||||
}
|
||||
if (res.value.is_error()) return EvalResult::from_value(res.value);
|
||||
if (res.value.is_array()) {
|
||||
const auto& arr = res.value.as_array();
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(arr ? arr->cols : 0)));
|
||||
}
|
||||
return EvalResult::from_value(Value::make_number(1.0));
|
||||
}
|
||||
|
||||
EvalResult fn_filter(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 2 || args.size() > 3) return err_res(ErrorCode::Value);
|
||||
auto arr_var = result_to_array2d(evaluate_ast(args[0].get(), ctx), *ctx.wb);
|
||||
if (std::holds_alternative<ErrorCode>(arr_var)) return err_res(std::get<ErrorCode>(arr_var));
|
||||
const Array2D& arr = std::get<Array2D>(arr_var);
|
||||
|
||||
auto inc_var = result_to_array2d(evaluate_ast(args[1].get(), ctx), *ctx.wb);
|
||||
if (std::holds_alternative<ErrorCode>(inc_var)) return err_res(std::get<ErrorCode>(inc_var));
|
||||
const Array2D& inc = std::get<Array2D>(inc_var);
|
||||
|
||||
auto eval_include_flag = [](const Value& v, ErrorCode& err_out) -> std::optional<bool> {
|
||||
if (v.is_error()) { err_out = v.as_error(); return std::nullopt; }
|
||||
if (v.is_empty()) return false;
|
||||
if (v.is_bool()) return v.as_bool();
|
||||
if (v.is_number()) return v.as_number() != 0.0;
|
||||
err_out = ErrorCode::Value;
|
||||
return std::nullopt;
|
||||
};
|
||||
|
||||
// Row filtering: include is (rows x 1)
|
||||
if (inc.cols == 1 && inc.rows == arr.rows) {
|
||||
std::vector<int> kept_rows;
|
||||
for (int r = 0; r < arr.rows; ++r) {
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto flag = eval_include_flag(inc.at(r, 0), err);
|
||||
if (!flag) return err_res(err);
|
||||
if (*flag) kept_rows.push_back(r);
|
||||
}
|
||||
if (kept_rows.empty()) {
|
||||
if (args.size() == 3) return evaluate_ast(args[2].get(), ctx);
|
||||
return err_res(ErrorCode::NA);
|
||||
}
|
||||
auto out = std::make_shared<Array2D>(static_cast<int>(kept_rows.size()), arr.cols);
|
||||
for (size_t i = 0; i < kept_rows.size(); ++i) {
|
||||
for (int c = 0; c < arr.cols; ++c) {
|
||||
out->at(static_cast<int>(i), c) = arr.at(kept_rows[i], c);
|
||||
}
|
||||
}
|
||||
if (out->rows == 1 && out->cols == 1) return EvalResult::from_value(out->at(0, 0));
|
||||
return EvalResult::from_value(Value::make_array(std::move(out)));
|
||||
}
|
||||
|
||||
// Column filtering: include is (1 x cols)
|
||||
if (inc.rows == 1 && inc.cols == arr.cols) {
|
||||
std::vector<int> kept_cols;
|
||||
for (int c = 0; c < arr.cols; ++c) {
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto flag = eval_include_flag(inc.at(0, c), err);
|
||||
if (!flag) return err_res(err);
|
||||
if (*flag) kept_cols.push_back(c);
|
||||
}
|
||||
if (kept_cols.empty()) {
|
||||
if (args.size() == 3) return evaluate_ast(args[2].get(), ctx);
|
||||
return err_res(ErrorCode::NA);
|
||||
}
|
||||
auto out = std::make_shared<Array2D>(arr.rows, static_cast<int>(kept_cols.size()));
|
||||
for (int r = 0; r < arr.rows; ++r) {
|
||||
for (size_t j = 0; j < kept_cols.size(); ++j) {
|
||||
out->at(r, static_cast<int>(j)) = arr.at(r, kept_cols[j]);
|
||||
}
|
||||
}
|
||||
if (out->rows == 1 && out->cols == 1) return EvalResult::from_value(out->at(0, 0));
|
||||
return EvalResult::from_value(Value::make_array(std::move(out)));
|
||||
}
|
||||
|
||||
return err_res(ErrorCode::Value);
|
||||
}
|
||||
|
||||
EvalResult fn_index(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 2 || args.size() > 3) return err_res(ErrorCode::Value);
|
||||
EvalResult arr_res = evaluate_ast(args[0].get(), ctx);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto r_d = eval_number_arg(args[1], ctx, err);
|
||||
if (!r_d) return err_res(err);
|
||||
int row_num = static_cast<int>(std::trunc(*r_d));
|
||||
int col_num = -1;
|
||||
if (args.size() == 3) {
|
||||
auto c_d = eval_number_arg(args[2], ctx, err);
|
||||
if (!c_d) return err_res(err);
|
||||
col_num = static_cast<int>(std::trunc(*c_d));
|
||||
}
|
||||
|
||||
if (arr_res.is_ref) {
|
||||
if (arr_res.ranges.size() != 1) return err_res(ErrorCode::Ref);
|
||||
const CellRange& rng = arr_res.ranges[0];
|
||||
int rc = rng.row_count();
|
||||
int cc = rng.col_count();
|
||||
if (col_num < 0) {
|
||||
if (rc == 1) {
|
||||
col_num = row_num;
|
||||
row_num = 1;
|
||||
} else if (cc == 1) {
|
||||
col_num = 1;
|
||||
} else {
|
||||
col_num = 0;
|
||||
}
|
||||
}
|
||||
if (row_num < 0 || col_num < 0 || row_num > rc || col_num > cc) {
|
||||
return err_res(ErrorCode::Ref);
|
||||
}
|
||||
if (row_num == 0 && col_num == 0) return arr_res;
|
||||
if (row_num == 0) {
|
||||
return EvalResult::from_range(
|
||||
CellRange{rng.sheet, rng.r1, rng.c1 + col_num - 1, rng.r2, rng.c1 + col_num - 1});
|
||||
}
|
||||
if (col_num == 0) {
|
||||
return EvalResult::from_range(
|
||||
CellRange{rng.sheet, rng.r1 + row_num - 1, rng.c1, rng.r1 + row_num - 1, rng.c2});
|
||||
}
|
||||
return EvalResult::from_range(CellRange{
|
||||
rng.sheet, rng.r1 + row_num - 1, rng.c1 + col_num - 1,
|
||||
rng.r1 + row_num - 1, rng.c1 + col_num - 1});
|
||||
}
|
||||
|
||||
auto arr_var = result_to_array2d(arr_res, *ctx.wb);
|
||||
if (std::holds_alternative<ErrorCode>(arr_var)) return err_res(std::get<ErrorCode>(arr_var));
|
||||
const Array2D& arr = std::get<Array2D>(arr_var);
|
||||
if (col_num < 0) {
|
||||
if (arr.rows == 1) {
|
||||
col_num = row_num;
|
||||
row_num = 1;
|
||||
} else if (arr.cols == 1) {
|
||||
col_num = 1;
|
||||
} else {
|
||||
col_num = 0;
|
||||
}
|
||||
}
|
||||
if (row_num < 0 || col_num < 0 || row_num > arr.rows || col_num > arr.cols) {
|
||||
return err_res(ErrorCode::Ref);
|
||||
}
|
||||
if (row_num == 0 && col_num == 0) {
|
||||
return EvalResult::from_value(Value::make_array(std::make_shared<Array2D>(arr)));
|
||||
}
|
||||
if (row_num == 0) {
|
||||
auto out = std::make_shared<Array2D>(arr.rows, 1);
|
||||
for (int r = 0; r < arr.rows; ++r) out->at(r, 0) = arr.at(r, col_num - 1);
|
||||
return EvalResult::from_value(out->rows == 1 ? out->at(0, 0) : Value::make_array(std::move(out)));
|
||||
}
|
||||
if (col_num == 0) {
|
||||
auto out = std::make_shared<Array2D>(1, arr.cols);
|
||||
for (int c = 0; c < arr.cols; ++c) out->at(0, c) = arr.at(row_num - 1, c);
|
||||
return EvalResult::from_value(out->cols == 1 ? out->at(0, 0) : Value::make_array(std::move(out)));
|
||||
}
|
||||
return EvalResult::from_value(arr.at(row_num - 1, col_num - 1));
|
||||
}
|
||||
|
||||
EvalResult fn_match(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 2 || args.size() > 3) return err_res(ErrorCode::Value);
|
||||
Value key = deref_to_value(evaluate_ast(args[0].get(), ctx), *ctx.wb);
|
||||
if (key.is_error()) return EvalResult::from_value(key);
|
||||
|
||||
auto arr_var = result_to_array2d(evaluate_ast(args[1].get(), ctx), *ctx.wb);
|
||||
if (std::holds_alternative<ErrorCode>(arr_var)) return err_res(std::get<ErrorCode>(arr_var));
|
||||
const Array2D& arr = std::get<Array2D>(arr_var);
|
||||
if (arr.rows != 1 && arr.cols != 1) return err_res(ErrorCode::NA);
|
||||
|
||||
int match_type = 1;
|
||||
if (args.size() == 3) {
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto mt = eval_number_arg(args[2], ctx, err);
|
||||
if (!mt) return err_res(err);
|
||||
match_type = static_cast<int>(std::trunc(*mt));
|
||||
}
|
||||
|
||||
int n = static_cast<int>(arr.data.size());
|
||||
if (match_type == 0) {
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (values_equal_for_lookup(arr.data[static_cast<size_t>(i)], key)) {
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(i + 1)));
|
||||
}
|
||||
}
|
||||
return err_res(ErrorCode::NA);
|
||||
}
|
||||
|
||||
if (match_type > 0) {
|
||||
int best = -1;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const Value& elem = arr.data[static_cast<size_t>(i)];
|
||||
if (!same_lookup_type(elem, key)) continue;
|
||||
auto cmp = compare_values(elem, key);
|
||||
if (!std::holds_alternative<int>(cmp)) continue;
|
||||
int c = std::get<int>(cmp);
|
||||
if (c <= 0) best = i;
|
||||
else break;
|
||||
}
|
||||
if (best < 0) return err_res(ErrorCode::NA);
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(best + 1)));
|
||||
}
|
||||
|
||||
// match_type < 0: descending, smallest >= key
|
||||
int best = -1;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
const Value& elem = arr.data[static_cast<size_t>(i)];
|
||||
if (!same_lookup_type(elem, key)) continue;
|
||||
auto cmp = compare_values(elem, key);
|
||||
if (!std::holds_alternative<int>(cmp)) continue;
|
||||
int c = std::get<int>(cmp);
|
||||
if (c >= 0) best = i;
|
||||
else break;
|
||||
}
|
||||
if (best < 0) return err_res(ErrorCode::NA);
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(best + 1)));
|
||||
}
|
||||
|
||||
EvalResult fn_vh_lookup(const std::vector<std::shared_ptr<Expr>>& args,
|
||||
const EvalContext& ctx,
|
||||
bool vertical) {
|
||||
if (args.size() < 3 || args.size() > 4) return err_res(ErrorCode::Value);
|
||||
Value key = deref_to_value(evaluate_ast(args[0].get(), ctx), *ctx.wb);
|
||||
if (key.is_error()) return EvalResult::from_value(key);
|
||||
|
||||
auto tbl_var = result_to_array2d(evaluate_ast(args[1].get(), ctx), *ctx.wb);
|
||||
if (std::holds_alternative<ErrorCode>(tbl_var)) return err_res(std::get<ErrorCode>(tbl_var));
|
||||
const Array2D& tbl = std::get<Array2D>(tbl_var);
|
||||
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto idx_d = eval_number_arg(args[2], ctx, err);
|
||||
if (!idx_d) return err_res(err);
|
||||
int idx = static_cast<int>(std::trunc(*idx_d));
|
||||
if (idx < 1) return err_res(ErrorCode::Value);
|
||||
int max_idx = vertical ? tbl.cols : tbl.rows;
|
||||
if (idx > max_idx) return err_res(ErrorCode::Ref);
|
||||
|
||||
bool range_lookup = true;
|
||||
if (args.size() == 4) {
|
||||
auto rl = eval_bool_arg(args[3], ctx, err);
|
||||
if (!rl) return err_res(err);
|
||||
range_lookup = *rl;
|
||||
}
|
||||
|
||||
int len = vertical ? tbl.rows : tbl.cols;
|
||||
int found = -1;
|
||||
if (!range_lookup) {
|
||||
for (int i = 0; i < len; ++i) {
|
||||
const Value& elem = vertical ? tbl.at(i, 0) : tbl.at(0, i);
|
||||
if (values_equal_for_lookup(elem, key)) {
|
||||
found = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (int i = 0; i < len; ++i) {
|
||||
const Value& elem = vertical ? tbl.at(i, 0) : tbl.at(0, i);
|
||||
if (!same_lookup_type(elem, key)) continue;
|
||||
auto cmp = compare_values(elem, key);
|
||||
if (!std::holds_alternative<int>(cmp)) continue;
|
||||
int c = std::get<int>(cmp);
|
||||
if (c <= 0) found = i;
|
||||
else break;
|
||||
}
|
||||
}
|
||||
|
||||
if (found < 0) return err_res(ErrorCode::NA);
|
||||
Value out = vertical ? tbl.at(found, idx - 1) : tbl.at(idx - 1, found);
|
||||
return EvalResult::from_value(out.is_empty() ? Value::make_number(0.0) : out);
|
||||
}
|
||||
|
||||
EvalResult fn_vlookup(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return fn_vh_lookup(a, c, true);
|
||||
}
|
||||
EvalResult fn_hlookup(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return fn_vh_lookup(a, c, false);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_lookup_functions(FunctionRegistry& reg) {
|
||||
reg.register_fn("CHOOSE", fn_choose);
|
||||
reg.register_fn("COLUMNS", fn_columns);
|
||||
reg.register_fn("FILTER", fn_filter);
|
||||
reg.register_fn("HLOOKUP", fn_hlookup);
|
||||
reg.register_fn("INDEX", fn_index);
|
||||
reg.register_fn("MATCH", fn_match);
|
||||
reg.register_fn("ROWS", fn_rows);
|
||||
reg.register_fn("VLOOKUP", fn_vlookup);
|
||||
}
|
||||
|
||||
} // namespace htab
|
||||
@@ -0,0 +1,324 @@
|
||||
#include "engine/functions/helpers.hpp"
|
||||
#include "engine/functions/registry.hpp"
|
||||
#include "engine/workbook.hpp"
|
||||
|
||||
#include <cmath>
|
||||
#include <random>
|
||||
#include <variant>
|
||||
|
||||
namespace htab {
|
||||
|
||||
using namespace htab::fn;
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
|
||||
template <typename UnaryMathFn>
|
||||
EvalResult unary_math(const std::vector<std::shared_ptr<Expr>>& args,
|
||||
const EvalContext& ctx,
|
||||
UnaryMathFn&& fn) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto num = eval_number_arg(args[0], ctx, err);
|
||||
if (!num) return err_res(err);
|
||||
return EvalResult::from_value(fn(*num));
|
||||
}
|
||||
|
||||
EvalResult fn_abs(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) { return Value::make_checked_number(std::fabs(x)); });
|
||||
}
|
||||
EvalResult fn_acos(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) {
|
||||
if (x < -1.0 || x > 1.0) return Value::make_error(ErrorCode::Num);
|
||||
return Value::make_checked_number(std::acos(x));
|
||||
});
|
||||
}
|
||||
EvalResult fn_asin(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) {
|
||||
if (x < -1.0 || x > 1.0) return Value::make_error(ErrorCode::Num);
|
||||
return Value::make_checked_number(std::asin(x));
|
||||
});
|
||||
}
|
||||
EvalResult fn_atan(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) { return Value::make_checked_number(std::atan(x)); });
|
||||
}
|
||||
EvalResult fn_atan2(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 2) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto x = eval_number_arg(args[0], ctx, err);
|
||||
if (!x) return err_res(err);
|
||||
auto y = eval_number_arg(args[1], ctx, err);
|
||||
if (!y) return err_res(err);
|
||||
if (*x == 0.0 && *y == 0.0) return err_res(ErrorCode::Div0);
|
||||
return EvalResult::from_value(Value::make_checked_number(std::atan2(*y, *x)));
|
||||
}
|
||||
EvalResult fn_cos(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) { return Value::make_checked_number(std::cos(x)); });
|
||||
}
|
||||
EvalResult fn_degrees(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) { return Value::make_checked_number(x * 180.0 / kPi); });
|
||||
}
|
||||
EvalResult fn_exp(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) { return Value::make_checked_number(std::exp(x)); });
|
||||
}
|
||||
EvalResult fn_fact(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) {
|
||||
if (x < 0.0) return Value::make_error(ErrorCode::Num);
|
||||
int n = static_cast<int>(std::trunc(x));
|
||||
if (n > 170) return Value::make_error(ErrorCode::Num);
|
||||
double res = 1.0;
|
||||
for (int i = 2; i <= n; ++i) res *= static_cast<double>(i);
|
||||
return Value::make_checked_number(res);
|
||||
});
|
||||
}
|
||||
EvalResult fn_int(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) { return Value::make_checked_number(std::floor(x)); });
|
||||
}
|
||||
EvalResult fn_ln(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) {
|
||||
if (x <= 0.0) return Value::make_error(ErrorCode::Num);
|
||||
return Value::make_checked_number(std::log(x));
|
||||
});
|
||||
}
|
||||
EvalResult fn_log(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.empty() || args.size() > 2) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto num = eval_number_arg(args[0], ctx, err);
|
||||
if (!num) return err_res(err);
|
||||
double base = 10.0;
|
||||
if (args.size() == 2) {
|
||||
auto b = eval_number_arg(args[1], ctx, err);
|
||||
if (!b) return err_res(err);
|
||||
base = *b;
|
||||
}
|
||||
if (*num <= 0.0 || base <= 0.0 || base == 1.0) return err_res(ErrorCode::Num);
|
||||
return EvalResult::from_value(Value::make_checked_number(std::log(*num) / std::log(base)));
|
||||
}
|
||||
EvalResult fn_log10(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) {
|
||||
if (x <= 0.0) return Value::make_error(ErrorCode::Num);
|
||||
return Value::make_checked_number(std::log10(x));
|
||||
});
|
||||
}
|
||||
EvalResult fn_mod(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 2) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto n = eval_number_arg(args[0], ctx, err);
|
||||
if (!n) return err_res(err);
|
||||
auto d = eval_number_arg(args[1], ctx, err);
|
||||
if (!d) return err_res(err);
|
||||
if (*d == 0.0) return err_res(ErrorCode::Div0);
|
||||
double res = *n - *d * std::floor(*n / *d);
|
||||
return EvalResult::from_value(Value::make_checked_number(res));
|
||||
}
|
||||
EvalResult fn_pi(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext&) {
|
||||
if (!args.empty()) return err_res(ErrorCode::Value);
|
||||
return EvalResult::from_value(Value::make_number(kPi));
|
||||
}
|
||||
EvalResult fn_power(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 2) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto x = eval_number_arg(args[0], ctx, err);
|
||||
if (!x) return err_res(err);
|
||||
auto y = eval_number_arg(args[1], ctx, err);
|
||||
if (!y) return err_res(err);
|
||||
if (*x == 0.0 && *y < 0.0) return err_res(ErrorCode::Div0);
|
||||
return EvalResult::from_value(Value::make_checked_number(std::pow(*x, *y)));
|
||||
}
|
||||
EvalResult fn_product(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.empty()) return err_res(ErrorCode::Value);
|
||||
std::vector<double> nums;
|
||||
if (auto err = collect_numeric_args(args, ctx, nums)) return err_res(*err);
|
||||
if (nums.empty()) return EvalResult::from_value(Value::make_number(0.0));
|
||||
double prod = 1.0;
|
||||
for (double v : nums) prod *= v;
|
||||
return EvalResult::from_value(Value::make_checked_number(prod));
|
||||
}
|
||||
EvalResult fn_radians(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) { return Value::make_checked_number(x * kPi / 180.0); });
|
||||
}
|
||||
EvalResult fn_rand(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext&) {
|
||||
if (!args.empty()) return err_res(ErrorCode::Value);
|
||||
thread_local std::mt19937_64 rng{std::random_device{}()};
|
||||
thread_local std::uniform_real_distribution<double> dist(0.0, 1.0);
|
||||
return EvalResult::from_value(Value::make_number(dist(rng)));
|
||||
}
|
||||
EvalResult fn_round(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 2) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto num = eval_number_arg(args[0], ctx, err);
|
||||
if (!num) return err_res(err);
|
||||
auto dig = eval_number_arg(args[1], ctx, err);
|
||||
if (!dig) return err_res(err);
|
||||
int d = static_cast<int>(std::trunc(*dig));
|
||||
double x = *num;
|
||||
double res = 0.0;
|
||||
if (d >= 0) {
|
||||
double scale = std::pow(10.0, d);
|
||||
double v = x * scale;
|
||||
if (!std::isfinite(v)) return EvalResult::from_value(Value::make_checked_number(x));
|
||||
double r = (v >= 0.0) ? std::floor(v + 0.5) : -std::floor(-v + 0.5);
|
||||
res = r / scale;
|
||||
} else {
|
||||
double scale = std::pow(10.0, -d);
|
||||
double v = x / scale;
|
||||
double r = (v >= 0.0) ? std::floor(v + 0.5) : -std::floor(-v + 0.5);
|
||||
res = r * scale;
|
||||
}
|
||||
return EvalResult::from_value(Value::make_checked_number(res));
|
||||
}
|
||||
EvalResult fn_sin(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) { return Value::make_checked_number(std::sin(x)); });
|
||||
}
|
||||
EvalResult fn_sqrt(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) {
|
||||
if (x < 0.0) return Value::make_error(ErrorCode::Num);
|
||||
return Value::make_checked_number(std::sqrt(x));
|
||||
});
|
||||
}
|
||||
EvalResult fn_sum(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.empty()) return err_res(ErrorCode::Value);
|
||||
std::vector<double> nums;
|
||||
if (auto err = collect_numeric_args(args, ctx, nums)) return err_res(*err);
|
||||
double total = 0.0;
|
||||
for (double v : nums) total += v;
|
||||
return EvalResult::from_value(Value::make_checked_number(total));
|
||||
}
|
||||
EvalResult fn_sumif(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 2 || args.size() > 3) return err_res(ErrorCode::Value);
|
||||
EvalResult cr_res = evaluate_ast(args[0].get(), ctx);
|
||||
auto cr_var = result_to_array2d(cr_res, *ctx.wb);
|
||||
if (std::holds_alternative<ErrorCode>(cr_var)) return err_res(std::get<ErrorCode>(cr_var));
|
||||
const Array2D& cr = std::get<Array2D>(cr_var);
|
||||
|
||||
Value crit = deref_to_value(evaluate_ast(args[1].get(), ctx), *ctx.wb);
|
||||
if (crit.is_error()) return EvalResult::from_value(crit);
|
||||
|
||||
Array2D sr;
|
||||
if (args.size() == 3) {
|
||||
EvalResult sr_res = evaluate_ast(args[2].get(), ctx);
|
||||
if (sr_res.is_ref && sr_res.ranges.size() == 1) {
|
||||
CellRange base = sr_res.ranges[0];
|
||||
sr = Array2D(cr.rows, cr.cols);
|
||||
for (int r = 0; r < cr.rows; ++r) {
|
||||
for (int c = 0; c < cr.cols; ++c) {
|
||||
sr.at(r, c) = ctx.wb->get_scalar_value(base.sheet, base.r1 + r, base.c1 + c);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
auto sr_var = result_to_array2d(sr_res, *ctx.wb);
|
||||
if (std::holds_alternative<ErrorCode>(sr_var)) return err_res(std::get<ErrorCode>(sr_var));
|
||||
sr = std::move(std::get<Array2D>(sr_var));
|
||||
if (sr.rows != cr.rows || sr.cols != cr.cols) return err_res(ErrorCode::Value);
|
||||
}
|
||||
} else {
|
||||
sr = cr;
|
||||
}
|
||||
|
||||
double total = 0.0;
|
||||
for (int r = 0; r < cr.rows; ++r) {
|
||||
for (int c = 0; c < cr.cols; ++c) {
|
||||
if (matches_criteria(cr.at(r, c), crit)) {
|
||||
const Value& sv = sr.at(r, c);
|
||||
if (sv.is_number()) total += sv.as_number();
|
||||
}
|
||||
}
|
||||
}
|
||||
return EvalResult::from_value(Value::make_checked_number(total));
|
||||
}
|
||||
EvalResult fn_sumifs(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 3 || (args.size() - 1) % 2 != 0) return err_res(ErrorCode::Value);
|
||||
auto sr_var = result_to_array2d(evaluate_ast(args[0].get(), ctx), *ctx.wb);
|
||||
if (std::holds_alternative<ErrorCode>(sr_var)) return err_res(std::get<ErrorCode>(sr_var));
|
||||
const Array2D& sr = std::get<Array2D>(sr_var);
|
||||
|
||||
struct Pair { Array2D range; Value crit; };
|
||||
std::vector<Pair> pairs;
|
||||
for (size_t i = 1; i < args.size(); i += 2) {
|
||||
auto cr_var = result_to_array2d(evaluate_ast(args[i].get(), ctx), *ctx.wb);
|
||||
if (std::holds_alternative<ErrorCode>(cr_var)) return err_res(std::get<ErrorCode>(cr_var));
|
||||
Array2D cr = std::move(std::get<Array2D>(cr_var));
|
||||
if (cr.rows != sr.rows || cr.cols != sr.cols) return err_res(ErrorCode::Value);
|
||||
Value crit = deref_to_value(evaluate_ast(args[i + 1].get(), ctx), *ctx.wb);
|
||||
if (crit.is_error()) return EvalResult::from_value(crit);
|
||||
pairs.push_back({std::move(cr), std::move(crit)});
|
||||
}
|
||||
|
||||
double total = 0.0;
|
||||
for (int r = 0; r < sr.rows; ++r) {
|
||||
for (int c = 0; c < sr.cols; ++c) {
|
||||
bool ok = true;
|
||||
for (const auto& p : pairs) {
|
||||
if (!matches_criteria(p.range.at(r, c), p.crit)) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (ok && sr.at(r, c).is_number()) {
|
||||
total += sr.at(r, c).as_number();
|
||||
}
|
||||
}
|
||||
}
|
||||
return EvalResult::from_value(Value::make_checked_number(total));
|
||||
}
|
||||
EvalResult fn_tan(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& ctx) {
|
||||
return unary_math(a, ctx, [](double x) { return Value::make_checked_number(std::tan(x)); });
|
||||
}
|
||||
EvalResult fn_trunc(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.empty() || args.size() > 2) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto num = eval_number_arg(args[0], ctx, err);
|
||||
if (!num) return err_res(err);
|
||||
int d = 0;
|
||||
if (args.size() == 2) {
|
||||
auto dig = eval_number_arg(args[1], ctx, err);
|
||||
if (!dig) return err_res(err);
|
||||
d = static_cast<int>(std::trunc(*dig));
|
||||
}
|
||||
double x = *num;
|
||||
double res = 0.0;
|
||||
if (d >= 0) {
|
||||
double scale = std::pow(10.0, d);
|
||||
double v = x * scale;
|
||||
res = std::isfinite(v) ? (std::trunc(v) / scale) : x;
|
||||
} else {
|
||||
double scale = std::pow(10.0, -d);
|
||||
res = std::trunc(x / scale) * scale;
|
||||
}
|
||||
return EvalResult::from_value(Value::make_checked_number(res));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_math_trig_functions(FunctionRegistry& reg) {
|
||||
reg.register_fn("ABS", fn_abs);
|
||||
reg.register_fn("ACOS", fn_acos);
|
||||
reg.register_fn("ASIN", fn_asin);
|
||||
reg.register_fn("ATAN", fn_atan);
|
||||
reg.register_fn("ATAN2", fn_atan2);
|
||||
reg.register_fn("COS", fn_cos);
|
||||
reg.register_fn("DEGREES", fn_degrees);
|
||||
reg.register_fn("EXP", fn_exp);
|
||||
reg.register_fn("FACT", fn_fact);
|
||||
reg.register_fn("INT", fn_int);
|
||||
reg.register_fn("LN", fn_ln);
|
||||
reg.register_fn("LOG", fn_log);
|
||||
reg.register_fn("LOG10", fn_log10);
|
||||
reg.register_fn("MOD", fn_mod);
|
||||
reg.register_fn("PI", fn_pi);
|
||||
reg.register_fn("POWER", fn_power);
|
||||
reg.register_fn("PRODUCT", fn_product);
|
||||
reg.register_fn("RADIANS", fn_radians);
|
||||
reg.register_fn("RAND", fn_rand);
|
||||
reg.register_fn("ROUND", fn_round);
|
||||
reg.register_fn("SIN", fn_sin);
|
||||
reg.register_fn("SQRT", fn_sqrt);
|
||||
reg.register_fn("SUM", fn_sum);
|
||||
reg.register_fn("SUMIF", fn_sumif);
|
||||
reg.register_fn("SUMIFS", fn_sumifs);
|
||||
reg.register_fn("TAN", fn_tan);
|
||||
reg.register_fn("TRUNC", fn_trunc);
|
||||
}
|
||||
|
||||
} // namespace htab
|
||||
@@ -0,0 +1,31 @@
|
||||
#include "engine/functions/registry.hpp"
|
||||
|
||||
namespace htab {
|
||||
|
||||
const FunctionRegistry& FunctionRegistry::instance() {
|
||||
static const FunctionRegistry reg;
|
||||
return reg;
|
||||
}
|
||||
|
||||
FunctionRegistry::FunctionRegistry() {
|
||||
register_math_trig_functions(*this);
|
||||
register_logical_functions(*this);
|
||||
register_statistical_functions(*this);
|
||||
register_lookup_functions(*this);
|
||||
register_text_functions(*this);
|
||||
register_datetime_functions(*this);
|
||||
register_financial_functions(*this);
|
||||
register_database_functions(*this);
|
||||
}
|
||||
|
||||
void FunctionRegistry::register_fn(std::string name, FunctionImpl fn) {
|
||||
funcs_.emplace(std::move(name), std::move(fn));
|
||||
}
|
||||
|
||||
const FunctionImpl* FunctionRegistry::find(std::string_view upper_name) const {
|
||||
auto it = funcs_.find(std::string(upper_name));
|
||||
if (it == funcs_.end()) return nullptr;
|
||||
return &it->second;
|
||||
}
|
||||
|
||||
} // namespace htab
|
||||
@@ -0,0 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include "engine/evaluator.hpp"
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
namespace htab {
|
||||
|
||||
using FunctionImpl =
|
||||
std::function<EvalResult(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx)>;
|
||||
|
||||
class FunctionRegistry {
|
||||
public:
|
||||
static const FunctionRegistry& instance();
|
||||
|
||||
const FunctionImpl* find(std::string_view upper_name) const;
|
||||
size_t registered_count() const { return funcs_.size(); }
|
||||
|
||||
void register_fn(std::string name, FunctionImpl fn);
|
||||
|
||||
private:
|
||||
FunctionRegistry();
|
||||
|
||||
std::unordered_map<std::string, FunctionImpl> funcs_;
|
||||
};
|
||||
|
||||
void register_math_trig_functions(FunctionRegistry& reg);
|
||||
void register_logical_functions(FunctionRegistry& reg);
|
||||
void register_statistical_functions(FunctionRegistry& reg);
|
||||
void register_lookup_functions(FunctionRegistry& reg);
|
||||
void register_text_functions(FunctionRegistry& reg);
|
||||
void register_datetime_functions(FunctionRegistry& reg);
|
||||
void register_financial_functions(FunctionRegistry& reg);
|
||||
void register_database_functions(FunctionRegistry& reg);
|
||||
|
||||
} // namespace htab
|
||||
@@ -0,0 +1,222 @@
|
||||
#include "engine/functions/helpers.hpp"
|
||||
#include "engine/functions/registry.hpp"
|
||||
#include "engine/workbook.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <numeric>
|
||||
#include <variant>
|
||||
|
||||
namespace htab {
|
||||
|
||||
using namespace htab::fn;
|
||||
|
||||
namespace {
|
||||
|
||||
double compute_variance(const std::vector<double>& nums, bool sample) {
|
||||
double sum = 0.0;
|
||||
for (double v : nums) sum += v;
|
||||
double mean = sum / static_cast<double>(nums.size());
|
||||
double sq_sum = 0.0;
|
||||
for (double v : nums) {
|
||||
double d = v - mean;
|
||||
sq_sum += d * d;
|
||||
}
|
||||
double denom = static_cast<double>(sample ? (nums.size() - 1) : nums.size());
|
||||
return sq_sum / denom;
|
||||
}
|
||||
|
||||
EvalResult fn_average(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.empty()) return err_res(ErrorCode::Value);
|
||||
std::vector<double> nums;
|
||||
if (auto err = collect_numeric_args(args, ctx, nums)) return err_res(*err);
|
||||
if (nums.empty()) return err_res(ErrorCode::Div0);
|
||||
double sum = 0.0;
|
||||
for (double v : nums) sum += v;
|
||||
return EvalResult::from_value(Value::make_checked_number(sum / static_cast<double>(nums.size())));
|
||||
}
|
||||
|
||||
EvalResult fn_count(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.empty()) return err_res(ErrorCode::Value);
|
||||
size_t count = 0;
|
||||
for (const auto& arg : args) {
|
||||
EvalResult res = evaluate_ast(arg.get(), ctx);
|
||||
if (res.is_ref) {
|
||||
for (const auto& rng : res.ranges) {
|
||||
for (int r = rng.r1; r <= rng.r2; ++r) {
|
||||
for (int c = rng.c1; c <= rng.c2; ++c) {
|
||||
Value v = ctx.wb->get_scalar_value(rng.sheet, r, c);
|
||||
if (v.is_number()) ++count;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (res.value.is_array()) {
|
||||
const auto& arr = res.value.as_array();
|
||||
if (arr) {
|
||||
for (const auto& v : arr->data) {
|
||||
if (v.is_number()) ++count;
|
||||
}
|
||||
}
|
||||
} else if (!res.value.is_error() && !res.value.is_empty()) {
|
||||
auto num = to_number(res.value);
|
||||
if (std::holds_alternative<double>(num)) ++count;
|
||||
}
|
||||
}
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(count)));
|
||||
}
|
||||
|
||||
EvalResult fn_counta(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.empty()) return err_res(ErrorCode::Value);
|
||||
size_t count = 0;
|
||||
for (const auto& arg : args) {
|
||||
EvalResult res = evaluate_ast(arg.get(), ctx);
|
||||
if (res.is_ref) {
|
||||
for (const auto& rng : res.ranges) {
|
||||
for (int r = rng.r1; r <= rng.r2; ++r) {
|
||||
for (int c = rng.c1; c <= rng.c2; ++c) {
|
||||
Value v = ctx.wb->get_scalar_value(rng.sheet, r, c);
|
||||
if (!v.is_empty()) ++count;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (res.value.is_array()) {
|
||||
const auto& arr = res.value.as_array();
|
||||
if (arr) {
|
||||
for (const auto& v : arr->data) {
|
||||
if (!v.is_empty()) ++count;
|
||||
}
|
||||
}
|
||||
} else if (!res.value.is_empty()) {
|
||||
++count;
|
||||
}
|
||||
}
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(count)));
|
||||
}
|
||||
|
||||
EvalResult fn_countblank(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
auto arr_var = result_to_array2d(evaluate_ast(args[0].get(), ctx), *ctx.wb);
|
||||
if (std::holds_alternative<ErrorCode>(arr_var)) return err_res(std::get<ErrorCode>(arr_var));
|
||||
const Array2D& arr = std::get<Array2D>(arr_var);
|
||||
size_t count = 0;
|
||||
for (const auto& v : arr.data) {
|
||||
if (v.is_empty() || (v.is_string() && v.as_string().empty())) {
|
||||
++count;
|
||||
}
|
||||
}
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(count)));
|
||||
}
|
||||
|
||||
EvalResult fn_countif(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 2) return err_res(ErrorCode::Value);
|
||||
auto arr_var = result_to_array2d(evaluate_ast(args[0].get(), ctx), *ctx.wb);
|
||||
if (std::holds_alternative<ErrorCode>(arr_var)) return err_res(std::get<ErrorCode>(arr_var));
|
||||
const Array2D& arr = std::get<Array2D>(arr_var);
|
||||
Value crit = deref_to_value(evaluate_ast(args[1].get(), ctx), *ctx.wb);
|
||||
if (crit.is_error()) return EvalResult::from_value(crit);
|
||||
|
||||
size_t count = 0;
|
||||
for (const auto& v : arr.data) {
|
||||
if (matches_criteria(v, crit)) ++count;
|
||||
}
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(count)));
|
||||
}
|
||||
|
||||
EvalResult fn_countifs(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 2 || args.size() % 2 != 0) return err_res(ErrorCode::Value);
|
||||
struct Pair { Array2D range; Value crit; };
|
||||
std::vector<Pair> pairs;
|
||||
int rows = -1, cols = -1;
|
||||
for (size_t i = 0; i < args.size(); i += 2) {
|
||||
auto arr_var = result_to_array2d(evaluate_ast(args[i].get(), ctx), *ctx.wb);
|
||||
if (std::holds_alternative<ErrorCode>(arr_var)) return err_res(std::get<ErrorCode>(arr_var));
|
||||
Array2D arr = std::move(std::get<Array2D>(arr_var));
|
||||
if (rows < 0) {
|
||||
rows = arr.rows;
|
||||
cols = arr.cols;
|
||||
} else if (arr.rows != rows || arr.cols != cols) {
|
||||
return err_res(ErrorCode::Value);
|
||||
}
|
||||
Value crit = deref_to_value(evaluate_ast(args[i + 1].get(), ctx), *ctx.wb);
|
||||
if (crit.is_error()) return EvalResult::from_value(crit);
|
||||
pairs.push_back({std::move(arr), std::move(crit)});
|
||||
}
|
||||
|
||||
size_t count = 0;
|
||||
for (int r = 0; r < rows; ++r) {
|
||||
for (int c = 0; c < cols; ++c) {
|
||||
bool ok = true;
|
||||
for (const auto& p : pairs) {
|
||||
if (!matches_criteria(p.range.at(r, c), p.crit)) {
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (ok) ++count;
|
||||
}
|
||||
}
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(count)));
|
||||
}
|
||||
|
||||
EvalResult fn_max(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.empty()) return err_res(ErrorCode::Value);
|
||||
std::vector<double> nums;
|
||||
if (auto err = collect_numeric_args(args, ctx, nums)) return err_res(*err);
|
||||
if (nums.empty()) return EvalResult::from_value(Value::make_number(0.0));
|
||||
double m = *std::max_element(nums.begin(), nums.end());
|
||||
return EvalResult::from_value(Value::make_number(m));
|
||||
}
|
||||
|
||||
EvalResult fn_min(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.empty()) return err_res(ErrorCode::Value);
|
||||
std::vector<double> nums;
|
||||
if (auto err = collect_numeric_args(args, ctx, nums)) return err_res(*err);
|
||||
if (nums.empty()) return EvalResult::from_value(Value::make_number(0.0));
|
||||
double m = *std::min_element(nums.begin(), nums.end());
|
||||
return EvalResult::from_value(Value::make_number(m));
|
||||
}
|
||||
|
||||
EvalResult fn_var_impl(const std::vector<std::shared_ptr<Expr>>& args,
|
||||
const EvalContext& ctx,
|
||||
bool sample,
|
||||
bool take_sqrt) {
|
||||
if (args.empty()) return err_res(ErrorCode::Value);
|
||||
std::vector<double> nums;
|
||||
if (auto err = collect_numeric_args(args, ctx, nums)) return err_res(*err);
|
||||
if (nums.size() < (sample ? 2U : 1U)) return err_res(ErrorCode::Div0);
|
||||
double v = compute_variance(nums, sample);
|
||||
if (take_sqrt) v = std::sqrt(v);
|
||||
return EvalResult::from_value(Value::make_checked_number(v));
|
||||
}
|
||||
|
||||
EvalResult fn_stdev(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return fn_var_impl(a, c, true, true);
|
||||
}
|
||||
EvalResult fn_stdevp(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return fn_var_impl(a, c, false, true);
|
||||
}
|
||||
EvalResult fn_var(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return fn_var_impl(a, c, true, false);
|
||||
}
|
||||
EvalResult fn_varp(const std::vector<std::shared_ptr<Expr>>& a, const EvalContext& c) {
|
||||
return fn_var_impl(a, c, false, false);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_statistical_functions(FunctionRegistry& reg) {
|
||||
reg.register_fn("AVERAGE", fn_average);
|
||||
reg.register_fn("COUNT", fn_count);
|
||||
reg.register_fn("COUNTA", fn_counta);
|
||||
reg.register_fn("COUNTBLANK", fn_countblank);
|
||||
reg.register_fn("COUNTIF", fn_countif);
|
||||
reg.register_fn("COUNTIFS", fn_countifs);
|
||||
reg.register_fn("MAX", fn_max);
|
||||
reg.register_fn("MIN", fn_min);
|
||||
reg.register_fn("STDEV", fn_stdev);
|
||||
reg.register_fn("STDEVP", fn_stdevp);
|
||||
reg.register_fn("VAR", fn_var);
|
||||
reg.register_fn("VARP", fn_varp);
|
||||
}
|
||||
|
||||
} // namespace htab
|
||||
@@ -0,0 +1,293 @@
|
||||
#include "engine/functions/helpers.hpp"
|
||||
#include "engine/functions/registry.hpp"
|
||||
#include "engine/workbook.hpp"
|
||||
|
||||
#include <cctype>
|
||||
#include <cmath>
|
||||
#include <variant>
|
||||
|
||||
namespace htab {
|
||||
|
||||
using namespace htab::fn;
|
||||
|
||||
namespace {
|
||||
|
||||
EvalResult fn_exact(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 2) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto a = eval_string_arg(args[0], ctx, err);
|
||||
if (!a) return err_res(err);
|
||||
auto b = eval_string_arg(args[1], ctx, err);
|
||||
if (!b) return err_res(err);
|
||||
return EvalResult::from_value(Value::make_bool(*a == *b));
|
||||
}
|
||||
|
||||
EvalResult fn_len(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto s = eval_string_arg(args[0], ctx, err);
|
||||
if (!s) return err_res(err);
|
||||
return EvalResult::from_value(
|
||||
Value::make_number(static_cast<double>(utf8_codepoints(*s).size())));
|
||||
}
|
||||
|
||||
EvalResult fn_lower(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto s = eval_string_arg(args[0], ctx, err);
|
||||
if (!s) return err_res(err);
|
||||
return EvalResult::from_value(Value::make_string(to_lower_ascii(*s)));
|
||||
}
|
||||
|
||||
EvalResult fn_upper(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto s = eval_string_arg(args[0], ctx, err);
|
||||
if (!s) return err_res(err);
|
||||
return EvalResult::from_value(Value::make_string(to_upper_ascii(*s)));
|
||||
}
|
||||
|
||||
EvalResult fn_proper(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto s = eval_string_arg(args[0], ctx, err);
|
||||
if (!s) return err_res(err);
|
||||
std::string out = *s;
|
||||
bool start_word = true;
|
||||
for (char& ch : out) {
|
||||
unsigned char uc = static_cast<unsigned char>(ch);
|
||||
if (std::isalpha(uc)) {
|
||||
ch = static_cast<char>(start_word ? std::toupper(uc) : std::tolower(uc));
|
||||
start_word = false;
|
||||
} else {
|
||||
start_word = true;
|
||||
}
|
||||
}
|
||||
return EvalResult::from_value(Value::make_string(std::move(out)));
|
||||
}
|
||||
|
||||
EvalResult fn_trim(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto s = eval_string_arg(args[0], ctx, err);
|
||||
if (!s) return err_res(err);
|
||||
std::string out;
|
||||
out.reserve(s->size());
|
||||
bool in_space = true;
|
||||
for (char ch : *s) {
|
||||
if (ch == ' ') {
|
||||
if (!in_space) {
|
||||
out.push_back(' ');
|
||||
in_space = true;
|
||||
}
|
||||
} else {
|
||||
out.push_back(ch);
|
||||
in_space = false;
|
||||
}
|
||||
}
|
||||
if (!out.empty() && out.back() == ' ') out.pop_back();
|
||||
return EvalResult::from_value(Value::make_string(std::move(out)));
|
||||
}
|
||||
|
||||
EvalResult fn_left(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.empty() || args.size() > 2) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto s = eval_string_arg(args[0], ctx, err);
|
||||
if (!s) return err_res(err);
|
||||
int count = 1;
|
||||
if (args.size() == 2) {
|
||||
auto n = eval_number_arg(args[1], ctx, err);
|
||||
if (!n) return err_res(err);
|
||||
count = static_cast<int>(std::trunc(*n));
|
||||
}
|
||||
if (count < 0) return err_res(ErrorCode::Value);
|
||||
auto cps = utf8_codepoints(*s);
|
||||
return EvalResult::from_value(Value::make_string(utf8_join(cps, 0, static_cast<size_t>(count))));
|
||||
}
|
||||
|
||||
EvalResult fn_right(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.empty() || args.size() > 2) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto s = eval_string_arg(args[0], ctx, err);
|
||||
if (!s) return err_res(err);
|
||||
int count = 1;
|
||||
if (args.size() == 2) {
|
||||
auto n = eval_number_arg(args[1], ctx, err);
|
||||
if (!n) return err_res(err);
|
||||
count = static_cast<int>(std::trunc(*n));
|
||||
}
|
||||
if (count < 0) return err_res(ErrorCode::Value);
|
||||
auto cps = utf8_codepoints(*s);
|
||||
size_t c = static_cast<size_t>(count);
|
||||
size_t start = (c >= cps.size()) ? 0 : (cps.size() - c);
|
||||
return EvalResult::from_value(Value::make_string(utf8_join(cps, start, c)));
|
||||
}
|
||||
|
||||
EvalResult fn_mid(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 3) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto s = eval_string_arg(args[0], ctx, err);
|
||||
if (!s) return err_res(err);
|
||||
auto st = eval_number_arg(args[1], ctx, err);
|
||||
if (!st) return err_res(err);
|
||||
auto nc = eval_number_arg(args[2], ctx, err);
|
||||
if (!nc) return err_res(err);
|
||||
int start1 = static_cast<int>(std::trunc(*st));
|
||||
int count = static_cast<int>(std::trunc(*nc));
|
||||
if (start1 < 1 || count < 0) return err_res(ErrorCode::Value);
|
||||
auto cps = utf8_codepoints(*s);
|
||||
size_t start0 = static_cast<size_t>(start1 - 1);
|
||||
if (start0 >= cps.size()) return EvalResult::from_value(Value::make_string(""));
|
||||
return EvalResult::from_value(
|
||||
Value::make_string(utf8_join(cps, start0, static_cast<size_t>(count))));
|
||||
}
|
||||
|
||||
EvalResult fn_find(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 2 || args.size() > 3) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto needle = eval_string_arg(args[0], ctx, err);
|
||||
if (!needle) return err_res(err);
|
||||
auto hay = eval_string_arg(args[1], ctx, err);
|
||||
if (!hay) return err_res(err);
|
||||
int start1 = 1;
|
||||
if (args.size() == 3) {
|
||||
auto sn = eval_number_arg(args[2], ctx, err);
|
||||
if (!sn) return err_res(err);
|
||||
start1 = static_cast<int>(std::trunc(*sn));
|
||||
}
|
||||
auto hay_cps = utf8_codepoints(*hay);
|
||||
auto ned_cps = utf8_codepoints(*needle);
|
||||
if (start1 < 1 || static_cast<size_t>(start1) > hay_cps.size() + 1) {
|
||||
return err_res(ErrorCode::Value);
|
||||
}
|
||||
if (ned_cps.empty()) {
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(start1)));
|
||||
}
|
||||
if (ned_cps.size() > hay_cps.size()) return err_res(ErrorCode::Value);
|
||||
for (size_t i = static_cast<size_t>(start1 - 1); i + ned_cps.size() <= hay_cps.size(); ++i) {
|
||||
bool match = true;
|
||||
for (size_t j = 0; j < ned_cps.size(); ++j) {
|
||||
if (hay_cps[i + j] != ned_cps[j]) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match) {
|
||||
return EvalResult::from_value(Value::make_number(static_cast<double>(i + 1)));
|
||||
}
|
||||
}
|
||||
return err_res(ErrorCode::Value);
|
||||
}
|
||||
|
||||
EvalResult fn_replace(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 4) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto old_t = eval_string_arg(args[0], ctx, err);
|
||||
if (!old_t) return err_res(err);
|
||||
auto st = eval_number_arg(args[1], ctx, err);
|
||||
if (!st) return err_res(err);
|
||||
auto nc = eval_number_arg(args[2], ctx, err);
|
||||
if (!nc) return err_res(err);
|
||||
auto new_t = eval_string_arg(args[3], ctx, err);
|
||||
if (!new_t) return err_res(err);
|
||||
|
||||
int start1 = static_cast<int>(std::trunc(*st));
|
||||
int count = static_cast<int>(std::trunc(*nc));
|
||||
if (start1 < 1 || count < 0) return err_res(ErrorCode::Value);
|
||||
|
||||
auto cps = utf8_codepoints(*old_t);
|
||||
size_t s0 = std::min(static_cast<size_t>(start1 - 1), cps.size());
|
||||
size_t e0 = std::min(s0 + static_cast<size_t>(count), cps.size());
|
||||
|
||||
std::string out = utf8_join(cps, 0, s0);
|
||||
out += *new_t;
|
||||
out += utf8_join(cps, e0, cps.size() - e0);
|
||||
return EvalResult::from_value(Value::make_string(std::move(out)));
|
||||
}
|
||||
|
||||
EvalResult fn_rept(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 2) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto t = eval_string_arg(args[0], ctx, err);
|
||||
if (!t) return err_res(err);
|
||||
auto n = eval_number_arg(args[1], ctx, err);
|
||||
if (!n) return err_res(err);
|
||||
int times = static_cast<int>(std::trunc(*n));
|
||||
if (times < 0) return err_res(ErrorCode::Value);
|
||||
if (times == 0 || t->empty()) return EvalResult::from_value(Value::make_string(""));
|
||||
if (t->size() * static_cast<size_t>(times) > 32767) return err_res(ErrorCode::Value);
|
||||
|
||||
std::string out;
|
||||
out.reserve(t->size() * static_cast<size_t>(times));
|
||||
for (int i = 0; i < times; ++i) out += *t;
|
||||
return EvalResult::from_value(Value::make_string(std::move(out)));
|
||||
}
|
||||
|
||||
EvalResult fn_substitute(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() < 3 || args.size() > 4) return err_res(ErrorCode::Value);
|
||||
ErrorCode err = ErrorCode::Value;
|
||||
auto text = eval_string_arg(args[0], ctx, err);
|
||||
if (!text) return err_res(err);
|
||||
auto old_t = eval_string_arg(args[1], ctx, err);
|
||||
if (!old_t) return err_res(err);
|
||||
auto new_t = eval_string_arg(args[2], ctx, err);
|
||||
if (!new_t) return err_res(err);
|
||||
|
||||
int instance_num = 0;
|
||||
if (args.size() == 4) {
|
||||
auto inst = eval_number_arg(args[3], ctx, err);
|
||||
if (!inst) return err_res(err);
|
||||
instance_num = static_cast<int>(std::trunc(*inst));
|
||||
if (instance_num < 1) return err_res(ErrorCode::Value);
|
||||
}
|
||||
if (old_t->empty()) return EvalResult::from_value(Value::make_string(*text));
|
||||
|
||||
std::string out;
|
||||
size_t pos = 0;
|
||||
int seen = 0;
|
||||
while (pos < text->size()) {
|
||||
size_t found = text->find(*old_t, pos);
|
||||
if (found == std::string::npos) {
|
||||
out.append(*text, pos, text->size() - pos);
|
||||
break;
|
||||
}
|
||||
++seen;
|
||||
out.append(*text, pos, found - pos);
|
||||
if (instance_num == 0 || seen == instance_num) {
|
||||
out.append(*new_t);
|
||||
} else {
|
||||
out.append(*old_t);
|
||||
}
|
||||
pos = found + old_t->size();
|
||||
}
|
||||
return EvalResult::from_value(Value::make_string(std::move(out)));
|
||||
}
|
||||
|
||||
EvalResult fn_t(const std::vector<std::shared_ptr<Expr>>& args, const EvalContext& ctx) {
|
||||
if (args.size() != 1) return err_res(ErrorCode::Value);
|
||||
Value v = deref_to_value(evaluate_ast(args[0].get(), ctx), *ctx.wb);
|
||||
if (v.is_error()) return EvalResult::from_value(v);
|
||||
if (v.is_string()) return EvalResult::from_value(v);
|
||||
return EvalResult::from_value(Value::make_string(""));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void register_text_functions(FunctionRegistry& reg) {
|
||||
reg.register_fn("EXACT", fn_exact);
|
||||
reg.register_fn("FIND", fn_find);
|
||||
reg.register_fn("LEFT", fn_left);
|
||||
reg.register_fn("LEN", fn_len);
|
||||
reg.register_fn("LOWER", fn_lower);
|
||||
reg.register_fn("MID", fn_mid);
|
||||
reg.register_fn("PROPER", fn_proper);
|
||||
reg.register_fn("REPLACE", fn_replace);
|
||||
reg.register_fn("REPT", fn_rept);
|
||||
reg.register_fn("RIGHT", fn_right);
|
||||
reg.register_fn("SUBSTITUTE", fn_substitute);
|
||||
reg.register_fn("T", fn_t);
|
||||
reg.register_fn("TRIM", fn_trim);
|
||||
reg.register_fn("UPPER", fn_upper);
|
||||
}
|
||||
|
||||
} // namespace htab
|
||||
Reference in new issue
Block a user