Initial commit: HTab spreadsheet engine and GemUI X11 frontend

This commit is contained in:
Luxferre committed 2026-11-30 17:45:17 +02:00
commit 395f458fee
55 files changed
+12682

No files matched your search

+385
View File
@@ -0,0 +1,385 @@
#include "engine/address.hpp"
#include "engine/lexer.hpp"
#include "engine/value.hpp"
#include <algorithm>
#include <cctype>
#include <cstdint>
#include <vector>
namespace htab {
std::string col_to_letters(int col) {
if (col < 0) return "";
std::string rev;
int n = col;
while (n >= 0) {
rev.push_back(static_cast<char>('A' + (n % 26)));
n = n / 26 - 1;
}
return std::string(rev.rbegin(), rev.rend());
}
int letters_to_col(std::string_view s) {
if (s.empty() || s.size() > 3) return -1;
int64_t val = 0;
for (char ch : s) {
if (!std::isalpha(static_cast<unsigned char>(ch))) return -1;
int d = std::toupper(static_cast<unsigned char>(ch)) - 'A' + 1;
val = val * 26 + d;
}
int col = static_cast<int>(val - 1);
if (col < 0 || col >= kMaxCols) return -1;
return col;
}
static bool needs_sheet_quoting(const std::string& name) {
if (name.empty()) return false;
if (std::isdigit(static_cast<unsigned char>(name[0]))) return true;
if (iequals_ascii(name, "TRUE") || iequals_ascii(name, "FALSE")) return true;
for (char ch : name) {
unsigned char uc = static_cast<unsigned char>(ch);
if (!(std::isalnum(uc) || ch == '_' || ch == '.')) {
return true;
}
}
// If sheet name looks like a valid cell address (e.g. "A1"), quote it.
if (parse_cell_ref(name).has_value()) {
return true;
}
return false;
}
std::string format_sheet_prefix(const std::string& sheet_name) {
if (sheet_name.empty()) return "";
if (!needs_sheet_quoting(sheet_name)) {
return sheet_name + "!";
}
std::string out = "'";
for (char ch : sheet_name) {
if (ch == '\'') out += "''";
else out.push_back(ch);
}
out += "'!";
return out;
}
std::string format_cell_ref(const CellRef& r) {
if (r.invalid) {
return "#REF!";
}
std::string out = format_sheet_prefix(r.sheet_name);
if (r.abs_col) out.push_back('$');
out += col_to_letters(r.col);
if (r.abs_row) out.push_back('$');
out += std::to_string(r.row + 1);
return out;
}
std::string format_range_ref(const RangeRef& r) {
if (r.invalid || r.start.invalid || r.end.invalid) {
return "#REF!";
}
CellRef s = r.start;
if (s.sheet_name.empty() && !r.sheet_name.empty()) {
s.sheet_name = r.sheet_name;
}
CellRef e = r.end;
e.sheet_name.clear();
return format_cell_ref(s) + ":" + format_cell_ref(e);
}
std::optional<CellRef> parse_cell_ref(std::string_view text) {
if (text.empty()) return std::nullopt;
CellRef ref;
size_t pos = 0;
if (text[0] == '\'') {
pos = 1;
std::string sheet;
bool closed = false;
while (pos < text.size()) {
if (text[pos] == '\'') {
if (pos + 1 < text.size() && text[pos + 1] == '\'') {
sheet.push_back('\'');
pos += 2;
} else {
++pos;
closed = true;
break;
}
} else {
sheet.push_back(text[pos++]);
}
}
if (!closed || pos >= text.size() || text[pos] != '!' || sheet.empty()) {
return std::nullopt;
}
++pos;
ref.sheet_name = std::move(sheet);
} else {
size_t bang = text.find('!');
if (bang != std::string_view::npos) {
if (bang == 0) return std::nullopt;
ref.sheet_name = std::string(text.substr(0, bang));
pos = bang + 1;
}
}
if (pos >= text.size()) return std::nullopt;
if (text[pos] == '$') {
ref.abs_col = true;
++pos;
}
size_t col_start = pos;
while (pos < text.size() && std::isalpha(static_cast<unsigned char>(text[pos]))) {
++pos;
}
if (pos == col_start) return std::nullopt;
int col = letters_to_col(text.substr(col_start, pos - col_start));
if (col < 0) return std::nullopt;
ref.col = col;
if (pos < text.size() && text[pos] == '$') {
ref.abs_row = true;
++pos;
}
size_t row_start = pos;
int64_t row1 = 0;
while (pos < text.size() && std::isdigit(static_cast<unsigned char>(text[pos]))) {
row1 = row1 * 10 + (text[pos] - '0');
if (row1 > kMaxRows) return std::nullopt;
++pos;
}
if (pos == row_start || pos != text.size() || row1 < 1) {
return std::nullopt;
}
ref.row = static_cast<int>(row1 - 1);
return ref;
}
namespace {
struct TextReplacement {
size_t start = 0;
size_t end = 0;
std::string text;
};
std::string apply_replacements(const std::string& src, std::vector<TextReplacement> reps) {
if (reps.empty()) return src;
std::sort(reps.begin(), reps.end(), [](const TextReplacement& a, const TextReplacement& b) {
return a.start < b.start;
});
std::string out;
out.reserve(src.size() + 32);
size_t cursor = 0;
for (const auto& r : reps) {
if (r.start < cursor) continue;
out.append(src, cursor, r.start - cursor);
out.append(r.text);
cursor = r.end;
}
out.append(src, cursor, src.size() - cursor);
return out;
}
bool rewrite_interval(int& lo, int& hi, bool is_insert, int index, int count, int max_limit) {
if (count <= 0) return true;
if (is_insert) {
if (index <= lo) {
lo += count;
hi += count;
} else if (index <= hi) {
hi += count;
}
return lo >= 0 && hi < max_limit;
}
// Delete [index, index + count - 1]
int del_start = index;
int del_end = index + count - 1;
if (del_end < lo) {
lo -= count;
hi -= count;
return lo >= 0;
}
if (del_start > hi) {
return true;
}
if (del_start <= lo && del_end >= hi) {
return false; // entire range deleted -> #REF!
}
if (del_start <= lo && del_end < hi) {
lo = del_start;
hi -= count;
return true;
}
if (del_start > lo && del_end >= hi) {
hi = del_start - 1;
return lo <= hi;
}
// Deleted strictly inside (lo, hi)
hi -= count;
return lo <= hi;
}
bool rewrite_point(int& coord, bool is_insert, int index, int count, int max_limit) {
if (count <= 0) return true;
if (is_insert) {
if (coord >= index) {
coord += count;
if (coord >= max_limit) return false;
}
return true;
}
if (coord >= index && coord < index + count) {
return false;
}
if (coord >= index + count) {
coord -= count;
}
return true;
}
} // namespace
std::string translate_formula_refs(const std::string& formula, int drow, int dcol) {
if (formula.empty() || formula[0] != '=' || (drow == 0 && dcol == 0)) {
return formula;
}
auto tokens = Lexer::tokenize(formula, true);
std::vector<TextReplacement> reps;
for (const auto& tok : tokens) {
if (tok.kind != TokenKind::CellRef) continue;
CellRef r = tok.ref_val;
int nr = r.abs_row ? r.row : (r.row + drow);
int nc = r.abs_col ? r.col : (r.col + dcol);
if (nr < 0 || nr >= kMaxRows || nc < 0 || nc >= kMaxCols) {
r.invalid = true;
} else {
r.row = nr;
r.col = nc;
}
reps.push_back({tok.start, tok.end, format_cell_ref(r)});
}
return apply_replacements(formula, std::move(reps));
}
std::string rewrite_formula_structural(const std::string& formula,
const std::string& current_sheet,
const std::string& target_sheet,
StructuralOp op,
int index,
int count,
const std::string& new_name) {
if (formula.empty() || formula[0] != '=') {
return formula;
}
auto tokens = Lexer::tokenize(formula, true);
std::vector<TextReplacement> reps;
for (size_t i = 0; i < tokens.size(); ++i) {
// Handle range pair: CellRef : CellRef
if (tokens[i].kind == TokenKind::CellRef &&
i + 2 < tokens.size() &&
tokens[i + 1].kind == TokenKind::Colon &&
tokens[i + 2].kind == TokenKind::CellRef) {
CellRef lhs = tokens[i].ref_val;
CellRef rhs = tokens[i + 2].ref_val;
std::string eff_lhs = lhs.sheet_name.empty() ? current_sheet : lhs.sheet_name;
std::string eff_rhs = rhs.sheet_name.empty() ? eff_lhs : rhs.sheet_name;
bool match_lhs = iequals_ascii(eff_lhs, target_sheet);
bool match_rhs = iequals_ascii(eff_rhs, target_sheet);
if (op == StructuralOp::RenameSheet) {
if (!lhs.sheet_name.empty() && iequals_ascii(lhs.sheet_name, target_sheet)) {
lhs.sheet_name = new_name;
reps.push_back({tokens[i].start, tokens[i].end, format_cell_ref(lhs)});
}
if (!rhs.sheet_name.empty() && iequals_ascii(rhs.sheet_name, target_sheet)) {
rhs.sheet_name = new_name;
reps.push_back({tokens[i + 2].start, tokens[i + 2].end, format_cell_ref(rhs)});
}
i += 2;
continue;
}
if (op == StructuralOp::DeleteSheet) {
if ((!lhs.sheet_name.empty() && match_lhs) || (!rhs.sheet_name.empty() && match_rhs)) {
reps.push_back({tokens[i].start, tokens[i + 2].end, "#REF!"});
}
i += 2;
continue;
}
if (match_lhs && match_rhs) {
bool is_row = (op == StructuralOp::InsertRow || op == StructuralOp::DeleteRow);
bool is_insert = (op == StructuralOp::InsertRow || op == StructuralOp::InsertCol);
int lo = is_row ? std::min(lhs.row, rhs.row) : std::min(lhs.col, rhs.col);
int hi = is_row ? std::max(lhs.row, rhs.row) : std::max(lhs.col, rhs.col);
bool rev = is_row ? (lhs.row > rhs.row) : (lhs.col > rhs.col);
bool ok = rewrite_interval(lo, hi, is_insert, index, count, is_row ? kMaxRows : kMaxCols);
if (!ok) {
reps.push_back({tokens[i].start, tokens[i + 2].end, "#REF!"});
} else {
if (is_row) {
lhs.row = rev ? hi : lo;
rhs.row = rev ? lo : hi;
} else {
lhs.col = rev ? hi : lo;
rhs.col = rev ? lo : hi;
}
reps.push_back({tokens[i].start, tokens[i + 2].end,
format_cell_ref(lhs) + ":" + format_cell_ref(rhs)});
}
i += 2;
continue;
}
// Different sheets in range endpoints: fall through to handle independently
}
if (tokens[i].kind == TokenKind::CellRef) {
CellRef ref = tokens[i].ref_val;
std::string eff_sheet = ref.sheet_name.empty() ? current_sheet : ref.sheet_name;
if (!iequals_ascii(eff_sheet, target_sheet)) continue;
if (op == StructuralOp::RenameSheet) {
if (!ref.sheet_name.empty()) {
ref.sheet_name = new_name;
reps.push_back({tokens[i].start, tokens[i].end, format_cell_ref(ref)});
}
continue;
}
if (op == StructuralOp::DeleteSheet) {
if (!ref.sheet_name.empty()) {
reps.push_back({tokens[i].start, tokens[i].end, "#REF!"});
}
continue;
}
bool is_row = (op == StructuralOp::InsertRow || op == StructuralOp::DeleteRow);
bool is_insert = (op == StructuralOp::InsertRow || op == StructuralOp::InsertCol);
int coord = is_row ? ref.row : ref.col;
if (!rewrite_point(coord, is_insert, index, count, is_row ? kMaxRows : kMaxCols)) {
reps.push_back({tokens[i].start, tokens[i].end, "#REF!"});
} else {
if (is_row) ref.row = coord;
else ref.col = coord;
reps.push_back({tokens[i].start, tokens[i].end, format_cell_ref(ref)});
}
} else if (tokens[i].kind == TokenKind::Error && tokens[i].err_val == ErrorCode::Ref &&
tokens[i].ref_val.invalid && !tokens[i].ref_val.sheet_name.empty() &&
iequals_ascii(tokens[i].ref_val.sheet_name, target_sheet)) {
if (op == StructuralOp::RenameSheet) {
reps.push_back({tokens[i].start, tokens[i].end,
format_sheet_prefix(new_name) + "#REF!"});
} else if (op == StructuralOp::DeleteSheet) {
reps.push_back({tokens[i].start, tokens[i].end, "#REF!"});
}
}
}
return apply_replacements(formula, std::move(reps));
}
} // namespace htab
+103
View File
@@ -0,0 +1,103 @@
#pragma once
#include <cstddef>
#include <functional>
#include <optional>
#include <string>
#include <string_view>
namespace htab {
inline constexpr int kMaxRows = 1048576;
inline constexpr int kMaxCols = 16384; // A..XFD (0..16383)
struct CellKey {
int row = 0;
int col = 0;
bool operator==(const CellKey&) const = default;
};
struct CellKeyHash {
size_t operator()(const CellKey& k) const noexcept {
size_t h1 = std::hash<int>{}(k.row);
size_t h2 = std::hash<int>{}(k.col);
return h1 ^ (h2 + 0x9e3779b97f4a7c15ULL + (h1 << 6) + (h1 >> 2));
}
};
struct GlobalAddr {
int sheet = 0;
int row = 0;
int col = 0;
bool operator==(const GlobalAddr&) const = default;
};
struct GlobalAddrHash {
size_t operator()(const GlobalAddr& a) const noexcept {
size_t h = std::hash<int>{}(a.sheet);
h ^= std::hash<int>{}(a.row) + 0x9e3779b97f4a7c15ULL + (h << 6) + (h >> 2);
h ^= std::hash<int>{}(a.col) + 0x9e3779b97f4a7c15ULL + (h << 6) + (h >> 2);
return h;
}
};
struct CellRef {
std::string sheet_name;
int row = 0;
int col = 0;
bool abs_row = false;
bool abs_col = false;
bool invalid = false;
bool operator==(const CellRef&) const = default;
};
struct RangeRef {
std::string sheet_name;
CellRef start;
CellRef end;
bool invalid = false;
};
struct CellRange {
int sheet = 0;
int r1 = 0;
int c1 = 0;
int r2 = 0;
int c2 = 0;
bool operator==(const CellRange&) const = default;
int row_count() const { return r2 - r1 + 1; }
int col_count() const { return c2 - c1 + 1; }
bool contains(int s, int r, int c) const {
return s == sheet && r >= r1 && r <= r2 && c >= c1 && c <= c2;
}
};
std::string col_to_letters(int col);
int letters_to_col(std::string_view s);
std::string format_sheet_prefix(const std::string& sheet_name);
std::string format_cell_ref(const CellRef& r);
std::string format_range_ref(const RangeRef& r);
std::optional<CellRef> parse_cell_ref(std::string_view text);
enum class StructuralOp {
InsertRow,
DeleteRow,
InsertCol,
DeleteCol,
RenameSheet,
DeleteSheet,
};
std::string translate_formula_refs(const std::string& formula, int drow, int dcol);
std::string rewrite_formula_structural(const std::string& formula,
const std::string& current_sheet,
const std::string& target_sheet,
StructuralOp op,
int index,
int count,
const std::string& new_name = "");
} // namespace htab
+626
View File
@@ -0,0 +1,626 @@
#include "engine/dag.hpp"
#include "engine/evaluator.hpp"
#include "engine/workbook.hpp"
#include <algorithm>
#include <cstdint>
#include <queue>
#include <stack>
namespace htab {
namespace {
constexpr int64_t kSmallRangeExpandLimit = 4096;
void extract_deps_walk(const Expr* expr,
int current_sheet,
const Workbook& wb,
std::vector<GlobalAddr>& out_cells,
std::vector<CellRange>& out_ranges) {
if (!expr) return;
switch (expr->kind) {
case Expr::Kind::Literal:
case Expr::Kind::UnknownName:
return;
case Expr::Kind::CellRef: {
const auto& ref = static_cast<const CellRefExpr*>(expr)->ref;
if (ref.invalid) return;
int s = ref.sheet_name.empty() ? current_sheet : wb.find_sheet(ref.sheet_name);
if (s >= 0) {
out_cells.push_back(GlobalAddr{s, ref.row, ref.col});
}
return;
}
case Expr::Kind::Range: {
const auto* rng = static_cast<const RangeExpr*>(expr);
if (rng->lhs && rng->rhs &&
rng->lhs->kind == Expr::Kind::CellRef &&
rng->rhs->kind == Expr::Kind::CellRef) {
const auto& lref = static_cast<const CellRefExpr*>(rng->lhs.get())->ref;
const auto& rref = static_cast<const CellRefExpr*>(rng->rhs.get())->ref;
if (!lref.invalid && !rref.invalid) {
int ls = lref.sheet_name.empty() ? current_sheet : wb.find_sheet(lref.sheet_name);
int rs = rref.sheet_name.empty() ? ls : wb.find_sheet(rref.sheet_name);
if (ls >= 0 && ls == rs) {
out_ranges.push_back(CellRange{
ls,
std::min(lref.row, rref.row),
std::min(lref.col, rref.col),
std::max(lref.row, rref.row),
std::max(lref.col, rref.col),
});
return;
}
}
}
extract_deps_walk(rng->lhs.get(), current_sheet, wb, out_cells, out_ranges);
extract_deps_walk(rng->rhs.get(), current_sheet, wb, out_cells, out_ranges);
return;
}
case Expr::Kind::Unary:
extract_deps_walk(static_cast<const UnaryExpr*>(expr)->operand.get(),
current_sheet, wb, out_cells, out_ranges);
return;
case Expr::Kind::Percent:
extract_deps_walk(static_cast<const PercentExpr*>(expr)->operand.get(),
current_sheet, wb, out_cells, out_ranges);
return;
case Expr::Kind::Binary: {
const auto* b = static_cast<const BinaryExpr*>(expr);
extract_deps_walk(b->lhs.get(), current_sheet, wb, out_cells, out_ranges);
extract_deps_walk(b->rhs.get(), current_sheet, wb, out_cells, out_ranges);
return;
}
case Expr::Kind::Call: {
const auto* c = static_cast<const CallExpr*>(expr);
for (const auto& arg : c->args) {
extract_deps_walk(arg.get(), current_sheet, wb, out_cells, out_ranges);
}
return;
}
}
}
bool ranges_overlap(const CellRange& a, const CellRange& b) {
if (a.sheet != b.sheet) return false;
return a.r1 <= b.r2 && b.r1 <= a.r2 && a.c1 <= b.c2 && b.c1 <= a.c2;
}
} // namespace
void DependencyGraph::clear() {
cell_precedents_.clear();
range_precedents_.clear();
dependents_.clear();
large_range_dependents_.clear();
spill_ranges_.clear();
spill_owner_.clear();
spill_blocked_by_.clear();
origin_blockers_.clear();
}
void DependencyGraph::remove_cell_deps_only(const GlobalAddr& cell) {
auto cp_it = cell_precedents_.find(cell);
if (cp_it != cell_precedents_.end()) {
for (const auto& p : cp_it->second) {
auto dep_it = dependents_.find(p);
if (dep_it != dependents_.end()) {
dep_it->second.erase(cell);
if (dep_it->second.empty()) dependents_.erase(dep_it);
}
}
cell_precedents_.erase(cp_it);
}
auto rp_it = range_precedents_.find(cell);
if (rp_it != range_precedents_.end()) {
for (const auto& rng : rp_it->second) {
auto l_it = large_range_dependents_.find(rng.sheet);
if (l_it != large_range_dependents_.end()) {
auto& vec = l_it->second;
vec.erase(std::remove_if(vec.begin(), vec.end(),
[&](const LargeRangeEntry& e) { return e.dependent == cell; }),
vec.end());
}
}
range_precedents_.erase(rp_it);
}
}
void DependencyGraph::update_cell_deps(const Workbook& wb, const GlobalAddr& cell, const Expr* ast) {
remove_cell_deps_only(cell);
if (!ast) return;
std::vector<GlobalAddr> raw_cells;
std::vector<CellRange> raw_ranges;
extract_deps_walk(ast, cell.sheet, wb, raw_cells, raw_ranges);
std::unordered_set<GlobalAddr, GlobalAddrHash> unique_cells;
for (const auto& p : raw_cells) {
unique_cells.insert(p);
}
std::vector<CellRange> large_ranges;
for (const auto& rng : raw_ranges) {
int64_t cnt = static_cast<int64_t>(rng.row_count()) * rng.col_count();
if (cnt <= kSmallRangeExpandLimit) {
for (int r = rng.r1; r <= rng.r2; ++r) {
for (int c = rng.c1; c <= rng.c2; ++c) {
unique_cells.insert(GlobalAddr{rng.sheet, r, c});
}
}
} else {
large_ranges.push_back(rng);
}
}
if (!unique_cells.empty()) {
auto& cp = cell_precedents_[cell];
cp.reserve(unique_cells.size());
for (const auto& p : unique_cells) {
cp.push_back(p);
dependents_[p].insert(cell);
}
}
if (!large_ranges.empty()) {
for (const auto& rng : large_ranges) {
large_range_dependents_[rng.sheet].push_back(LargeRangeEntry{cell, rng});
}
range_precedents_[cell] = std::move(large_ranges);
}
}
void DependencyGraph::remove_cell(const GlobalAddr& cell) {
remove_cell_deps_only(cell);
std::vector<GlobalAddr> unused;
clear_spill_for_origin(cell, unused);
clear_blocked_entries_for_origin(cell);
}
void DependencyGraph::clear_blocked_entries_for_origin(const GlobalAddr& origin) {
auto it = origin_blockers_.find(origin);
if (it == origin_blockers_.end()) return;
for (const auto& b : it->second) {
auto bit = spill_blocked_by_.find(b);
if (bit != spill_blocked_by_.end()) {
bit->second.erase(origin);
if (bit->second.empty()) spill_blocked_by_.erase(bit);
}
}
origin_blockers_.erase(it);
}
void DependencyGraph::clear_spill_for_origin(const GlobalAddr& origin,
std::vector<GlobalAddr>& affected_cells) {
auto it = spill_ranges_.find(origin);
if (it == spill_ranges_.end()) return;
CellRange sr = it->second;
spill_ranges_.erase(it);
for (int r = sr.r1; r <= sr.r2; ++r) {
for (int c = sr.c1; c <= sr.c2; ++c) {
if (r == origin.row && c == origin.col) continue;
GlobalAddr t{sr.sheet, r, c};
auto oit = spill_owner_.find(t);
if (oit != spill_owner_.end() && oit->second == origin) {
spill_owner_.erase(oit);
affected_cells.push_back(t);
}
}
}
}
void DependencyGraph::collect_dependents_of(const GlobalAddr& cell,
std::vector<GlobalAddr>& out) const {
auto dit = dependents_.find(cell);
if (dit != dependents_.end()) {
for (const auto& d : dit->second) out.push_back(d);
}
auto lit = large_range_dependents_.find(cell.sheet);
if (lit != large_range_dependents_.end()) {
for (const auto& entry : lit->second) {
if (entry.range.contains(cell.sheet, cell.row, cell.col)) {
out.push_back(entry.dependent);
}
}
}
}
bool DependencyGraph::apply_spill_for_cell(Workbook& wb,
const GlobalAddr& origin,
const Value& val,
std::vector<GlobalAddr>& followup_seeds) {
clear_blocked_entries_for_origin(origin);
if (!val.is_array()) {
std::vector<GlobalAddr> cleared;
clear_spill_for_origin(origin, cleared);
for (const auto& c : cleared) {
collect_dependents_of(c, followup_seeds);
}
return false;
}
const auto& arr = val.as_array();
if (!arr || arr->rows <= 0 || arr->cols <= 0) {
std::vector<GlobalAddr> cleared;
clear_spill_for_origin(origin, cleared);
for (const auto& c : cleared) {
collect_dependents_of(c, followup_seeds);
}
return false;
}
if (arr->rows == 1 && arr->cols == 1) {
std::vector<GlobalAddr> cleared;
clear_spill_for_origin(origin, cleared);
for (const auto& c : cleared) {
collect_dependents_of(c, followup_seeds);
}
return false;
}
int r2 = origin.row + arr->rows - 1;
int c2 = origin.col + arr->cols - 1;
if (r2 >= kMaxRows || c2 >= kMaxCols) {
std::vector<GlobalAddr> cleared;
clear_spill_for_origin(origin, cleared);
for (const auto& c : cleared) {
collect_dependents_of(c, followup_seeds);
}
Cell* cell = wb.sheet_mut(origin.sheet).cells.count(CellKey{origin.row, origin.col})
? &wb.sheet_mut(origin.sheet).cells[CellKey{origin.row, origin.col}]
: nullptr;
if (cell) cell->value = Value::make_error(ErrorCode::Spill);
return true;
}
std::vector<GlobalAddr> blockers;
for (int r = origin.row; r <= r2; ++r) {
for (int c = origin.col; c <= c2; ++c) {
if (r == origin.row && c == origin.col) continue;
const Cell* target_cell = wb.get_cell(origin.sheet, r, c);
if (target_cell && !target_cell->raw_input.empty()) {
blockers.push_back(GlobalAddr{origin.sheet, r, c});
continue;
}
GlobalAddr t{origin.sheet, r, c};
auto oit = spill_owner_.find(t);
if (oit != spill_owner_.end() && oit->second != origin) {
blockers.push_back(t);
}
}
}
if (!blockers.empty()) {
std::vector<GlobalAddr> cleared;
clear_spill_for_origin(origin, cleared);
for (const auto& c : cleared) {
collect_dependents_of(c, followup_seeds);
}
auto& ob = origin_blockers_[origin];
ob = std::move(blockers);
for (const auto& b : ob) {
spill_blocked_by_[b].insert(origin);
}
auto& cells_map = wb.sheet_mut(origin.sheet).cells;
auto cit = cells_map.find(CellKey{origin.row, origin.col});
if (cit != cells_map.end()) {
cit->second.value = Value::make_error(ErrorCode::Spill);
}
return true;
}
// Can spill cleanly: diff against previous spill range
CellRange new_rect{origin.sheet, origin.row, origin.col, r2, c2};
bool range_changed = true;
auto prev_it = spill_ranges_.find(origin);
if (prev_it != spill_ranges_.end() && prev_it->second == new_rect) {
range_changed = false;
}
if (range_changed) {
std::vector<GlobalAddr> cleared;
clear_spill_for_origin(origin, cleared);
spill_ranges_[origin] = new_rect;
for (int r = new_rect.r1; r <= new_rect.r2; ++r) {
for (int c = new_rect.c1; c <= new_rect.c2; ++c) {
if (r == origin.row && c == origin.col) continue;
GlobalAddr t{origin.sheet, r, c};
spill_owner_[t] = origin;
collect_dependents_of(t, followup_seeds);
}
}
for (const auto& c : cleared) {
if (!new_rect.contains(c.sheet, c.row, c.col)) {
collect_dependents_of(c, followup_seeds);
}
}
}
return false;
}
void DependencyGraph::rebuild(Workbook& wb) {
clear();
std::vector<GlobalAddr> all_formulas;
for (int si = 0; si < wb.sheet_count(); ++si) {
const Sheet& s = wb.sheet(si);
for (const auto& [key, cell] : s.cells) {
if (cell.ast) {
GlobalAddr addr{si, key.row, key.col};
update_cell_deps(wb, addr, cell.ast.get());
all_formulas.push_back(addr);
}
}
}
if (!all_formulas.empty()) {
recalculate_from(wb, std::move(all_formulas));
}
}
void DependencyGraph::recalculate_from(Workbook& wb, std::vector<GlobalAddr> seeds) {
for (int pass = 0; pass < 32 && !seeds.empty(); ++pass) {
std::unordered_set<GlobalAddr, GlobalAddrHash> expanded_seeds;
for (const auto& s : seeds) {
expanded_seeds.insert(s);
auto oit = spill_owner_.find(s);
if (oit != spill_owner_.end()) {
expanded_seeds.insert(oit->second);
}
auto bit = spill_blocked_by_.find(s);
if (bit != spill_blocked_by_.end()) {
for (const auto& blocked_origin : bit->second) {
expanded_seeds.insert(blocked_origin);
}
}
}
// BFS forward to gather all dirty cells
std::unordered_set<GlobalAddr, GlobalAddrHash> dirty;
std::queue<GlobalAddr> bfs;
for (const auto& s : expanded_seeds) {
if (dirty.insert(s).second) {
bfs.push(s);
}
}
while (!bfs.empty()) {
GlobalAddr u = bfs.front();
bfs.pop();
std::vector<GlobalAddr> next_deps;
collect_dependents_of(u, next_deps);
auto srit = spill_ranges_.find(u);
if (srit != spill_ranges_.end()) {
const CellRange& sr = srit->second;
for (int r = sr.r1; r <= sr.r2; ++r) {
for (int c = sr.c1; c <= sr.c2; ++c) {
if (r == u.row && c == u.col) continue;
collect_dependents_of(GlobalAddr{sr.sheet, r, c}, next_deps);
}
}
}
for (const auto& d : next_deps) {
if (dirty.insert(d).second) {
bfs.push(d);
}
}
}
// Build subgraph edges among dirty nodes
std::vector<GlobalAddr> nodes(dirty.begin(), dirty.end());
std::unordered_map<GlobalAddr, size_t, GlobalAddrHash> id_of;
id_of.reserve(nodes.size() * 2 + 1);
for (size_t i = 0; i < nodes.size(); ++i) {
id_of[nodes[i]] = i;
}
std::vector<std::vector<size_t>> adj(nodes.size());
std::vector<int> in_degree(nodes.size(), 0);
std::vector<bool> self_loop(nodes.size(), false);
for (size_t vi = 0; vi < nodes.size(); ++vi) {
const GlobalAddr& v = nodes[vi];
std::unordered_set<size_t> preds;
auto cp_it = cell_precedents_.find(v);
if (cp_it != cell_precedents_.end()) {
for (const auto& p : cp_it->second) {
auto it = id_of.find(p);
if (it != id_of.end()) preds.insert(it->second);
auto oit = spill_owner_.find(p);
if (oit != spill_owner_.end()) {
auto o_id = id_of.find(oit->second);
if (o_id != id_of.end()) preds.insert(o_id->second);
}
}
}
auto rp_it = range_precedents_.find(v);
if (rp_it != range_precedents_.end()) {
for (const auto& rng : rp_it->second) {
for (size_t ui = 0; ui < nodes.size(); ++ui) {
const GlobalAddr& u = nodes[ui];
if (rng.contains(u.sheet, u.row, u.col)) {
preds.insert(ui);
} else {
auto srit = spill_ranges_.find(u);
if (srit != spill_ranges_.end() && ranges_overlap(rng, srit->second)) {
preds.insert(ui);
}
}
}
}
}
for (size_t ui : preds) {
if (ui == vi) {
self_loop[vi] = true;
} else {
adj[ui].push_back(vi);
}
in_degree[vi]++;
}
}
std::vector<GlobalAddr> followup_seeds;
auto eval_node = [&](size_t idx, bool force_cycle) {
const GlobalAddr& addr = nodes[idx];
if (addr.sheet < 0 || addr.sheet >= wb.sheet_count()) return;
auto& cells_map = wb.sheet_mut(addr.sheet).cells;
auto cit = cells_map.find(CellKey{addr.row, addr.col});
if (cit == cells_map.end() || !cit->second.ast) {
// Non-formula cell (or cleared): ensure any old spill is cleared.
std::vector<GlobalAddr> cleared;
clear_spill_for_origin(addr, cleared);
clear_blocked_entries_for_origin(addr);
for (const auto& c : cleared) collect_dependents_of(c, followup_seeds);
return;
}
if (force_cycle) {
std::vector<GlobalAddr> cleared;
clear_spill_for_origin(addr, cleared);
clear_blocked_entries_for_origin(addr);
for (const auto& c : cleared) collect_dependents_of(c, followup_seeds);
cit->second.value = Value::make_error(ErrorCode::Cycle);
return;
}
EvalContext ctx{&wb, addr.sheet, addr.row, addr.col};
EvalResult res = evaluate_ast(cit->second.ast.get(), ctx);
Value val = deref_to_value(res, wb);
cit->second.value = val;
apply_spill_for_cell(wb, addr, val, followup_seeds);
};
// Pass 1: Kahn's topological sort
std::vector<bool> visited(nodes.size(), false);
std::queue<size_t> q;
for (size_t i = 0; i < nodes.size(); ++i) {
if (in_degree[i] == 0) {
q.push(i);
}
}
while (!q.empty()) {
size_t u = q.front();
q.pop();
visited[u] = true;
eval_node(u, false);
for (size_t v : adj[u]) {
if (--in_degree[v] == 0) {
q.push(v);
}
}
}
// Pass 2: Tarjan's SCC for remaining cyclic / cycle-downstream nodes
std::vector<size_t> rem_nodes;
for (size_t i = 0; i < nodes.size(); ++i) {
if (!visited[i]) rem_nodes.push_back(i);
}
if (!rem_nodes.empty()) {
int tarjan_timer = 0;
std::vector<int> disc(nodes.size(), -1);
std::vector<int> low(nodes.size(), -1);
std::vector<bool> on_stack(nodes.size(), false);
std::stack<size_t> st;
std::vector<std::vector<size_t>> sccs;
auto strongconnect = [&](auto& self_fn, size_t u) -> void {
disc[u] = low[u] = tarjan_timer++;
st.push(u);
on_stack[u] = true;
for (size_t v : adj[u]) {
if (visited[v]) continue;
if (disc[v] == -1) {
self_fn(self_fn, v);
low[u] = std::min(low[u], low[v]);
} else if (on_stack[v]) {
low[u] = std::min(low[u], disc[v]);
}
}
if (low[u] == disc[u]) {
std::vector<size_t> comp;
while (true) {
size_t w = st.top();
st.pop();
on_stack[w] = false;
comp.push_back(w);
if (w == u) break;
}
sccs.push_back(std::move(comp));
}
};
for (size_t idx : rem_nodes) {
if (disc[idx] == -1) {
strongconnect(strongconnect, idx);
}
}
// Tarjan yields SCCs in reverse topological order; iterate in reverse.
for (auto it = sccs.rbegin(); it != sccs.rend(); ++it) {
const auto& comp = *it;
bool is_cycle = (comp.size() > 1) || (comp.size() == 1 && self_loop[comp[0]]);
for (size_t idx : comp) {
eval_node(idx, is_cycle);
}
}
}
if (pass == 31 && !followup_seeds.empty()) {
for (const auto& f : followup_seeds) {
if (f.sheet >= 0 && f.sheet < wb.sheet_count()) {
auto& cmap = wb.sheet_mut(f.sheet).cells;
auto cit = cmap.find(CellKey{f.row, f.col});
if (cit != cmap.end() && cit->second.ast) {
cit->second.value = Value::make_error(ErrorCode::Cycle);
}
}
}
break;
}
seeds = std::move(followup_seeds);
}
}
bool DependencyGraph::is_spilled_cell(int sheet, int row, int col) const {
return spill_owner_.find(GlobalAddr{sheet, row, col}) != spill_owner_.end();
}
std::optional<CellRange> DependencyGraph::get_spill_range(int sheet, int row, int col) const {
GlobalAddr addr{sheet, row, col};
auto it = spill_ranges_.find(addr);
if (it != spill_ranges_.end()) return it->second;
auto oit = spill_owner_.find(addr);
if (oit != spill_owner_.end()) {
auto it2 = spill_ranges_.find(oit->second);
if (it2 != spill_ranges_.end()) return it2->second;
}
return std::nullopt;
}
std::optional<GlobalAddr> DependencyGraph::get_spill_origin(int sheet, int row, int col) const {
auto oit = spill_owner_.find(GlobalAddr{sheet, row, col});
if (oit != spill_owner_.end()) return oit->second;
return std::nullopt;
}
Value DependencyGraph::get_spill_value(const Workbook& wb, int sheet, int row, int col) const {
auto oit = spill_owner_.find(GlobalAddr{sheet, row, col});
if (oit == spill_owner_.end()) return Value::make_empty();
const GlobalAddr& origin = oit->second;
const Cell* oc = wb.get_cell(origin.sheet, origin.row, origin.col);
if (!oc || !oc->value.is_array()) return Value::make_empty();
const auto& arr = oc->value.as_array();
int dr = row - origin.row;
int dc = col - origin.col;
if (!arr || dr < 0 || dc < 0 || dr >= arr->rows || dc >= arr->cols) {
return Value::make_empty();
}
return arr->at(dr, dc);
}
} // namespace htab
+64
View File
@@ -0,0 +1,64 @@
#pragma once
#include "engine/address.hpp"
#include "engine/parser.hpp"
#include "engine/value.hpp"
#include <optional>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace htab {
class Workbook;
class DependencyGraph {
public:
void clear();
void rebuild(Workbook& wb);
void update_cell_deps(const Workbook& wb, const GlobalAddr& cell, const Expr* ast);
void remove_cell(const GlobalAddr& cell);
void recalculate_from(Workbook& wb, std::vector<GlobalAddr> seeds);
bool is_spilled_cell(int sheet, int row, int col) const;
std::optional<CellRange> get_spill_range(int sheet, int row, int col) const;
std::optional<GlobalAddr> get_spill_origin(int sheet, int row, int col) const;
Value get_spill_value(const Workbook& wb, int sheet, int row, int col) const;
const std::unordered_map<GlobalAddr, CellRange, GlobalAddrHash>& spill_ranges() const {
return spill_ranges_;
}
private:
struct LargeRangeEntry {
GlobalAddr dependent;
CellRange range;
};
void remove_cell_deps_only(const GlobalAddr& cell);
void clear_spill_for_origin(const GlobalAddr& origin,
std::vector<GlobalAddr>& affected_cells);
void clear_blocked_entries_for_origin(const GlobalAddr& origin);
bool apply_spill_for_cell(Workbook& wb,
const GlobalAddr& origin,
const Value& val,
std::vector<GlobalAddr>& followup_seeds);
void collect_dependents_of(const GlobalAddr& cell,
std::vector<GlobalAddr>& out) const;
std::unordered_map<GlobalAddr, std::vector<GlobalAddr>, GlobalAddrHash> cell_precedents_;
std::unordered_map<GlobalAddr, std::vector<CellRange>, GlobalAddrHash> range_precedents_;
std::unordered_map<GlobalAddr, std::unordered_set<GlobalAddr, GlobalAddrHash>, GlobalAddrHash>
dependents_;
std::unordered_map<int, std::vector<LargeRangeEntry>> large_range_dependents_;
// Spill state
std::unordered_map<GlobalAddr, CellRange, GlobalAddrHash> spill_ranges_;
std::unordered_map<GlobalAddr, GlobalAddr, GlobalAddrHash> spill_owner_;
std::unordered_map<GlobalAddr, std::unordered_set<GlobalAddr, GlobalAddrHash>, GlobalAddrHash>
spill_blocked_by_;
std::unordered_map<GlobalAddr, std::vector<GlobalAddr>, GlobalAddrHash> origin_blockers_;
};
} // namespace htab
+312
View File
@@ -0,0 +1,312 @@
#include "engine/evaluator.hpp"
#include "engine/functions/registry.hpp"
#include "engine/workbook.hpp"
#include <algorithm>
#include <cmath>
#include <variant>
namespace htab {
namespace {
constexpr int kMaxArrayCells = 1000000;
Value eval_scalar_binary(BinOp op, const Value& a, const Value& b) {
if (a.is_error()) return a;
if (b.is_error()) return b;
switch (op) {
case BinOp::Add:
case BinOp::Sub:
case BinOp::Mul:
case BinOp::Div:
case BinOp::Pow: {
auto na = to_number(a);
if (std::holds_alternative<ErrorCode>(na)) return Value::make_error(std::get<ErrorCode>(na));
auto nb = to_number(b);
if (std::holds_alternative<ErrorCode>(nb)) return Value::make_error(std::get<ErrorCode>(nb));
double da = std::get<double>(na);
double db = std::get<double>(nb);
switch (op) {
case BinOp::Add: return Value::make_checked_number(da + db);
case BinOp::Sub: return Value::make_checked_number(da - db);
case BinOp::Mul: return Value::make_checked_number(da * db);
case BinOp::Div:
if (db == 0.0) return Value::make_error(ErrorCode::Div0);
return Value::make_checked_number(da / db);
case BinOp::Pow:
if (da == 0.0 && db < 0.0) return Value::make_error(ErrorCode::Div0);
return Value::make_checked_number(std::pow(da, db));
default: break;
}
break;
}
case BinOp::Concat: {
auto sa = to_string(a);
if (std::holds_alternative<ErrorCode>(sa)) return Value::make_error(std::get<ErrorCode>(sa));
auto sb = to_string(b);
if (std::holds_alternative<ErrorCode>(sb)) return Value::make_error(std::get<ErrorCode>(sb));
return Value::make_string(std::get<std::string>(sa) + std::get<std::string>(sb));
}
case BinOp::Eq:
case BinOp::Neq:
case BinOp::Lt:
case BinOp::Gt:
case BinOp::Le:
case BinOp::Ge: {
auto cmp = compare_values(a, b);
if (std::holds_alternative<ErrorCode>(cmp)) return Value::make_error(std::get<ErrorCode>(cmp));
int c = std::get<int>(cmp);
switch (op) {
case BinOp::Eq: return Value::make_bool(c == 0);
case BinOp::Neq: return Value::make_bool(c != 0);
case BinOp::Lt: return Value::make_bool(c < 0);
case BinOp::Gt: return Value::make_bool(c > 0);
case BinOp::Le: return Value::make_bool(c <= 0);
case BinOp::Ge: return Value::make_bool(c >= 0);
default: break;
}
break;
}
default:
break;
}
return Value::make_error(ErrorCode::Value);
}
Value eval_scalar_unary(char op, const Value& v) {
if (v.is_error()) return v;
auto n = to_number(v);
if (std::holds_alternative<ErrorCode>(n)) return Value::make_error(std::get<ErrorCode>(n));
double d = std::get<double>(n);
return Value::make_checked_number(op == '-' ? -d : d);
}
Value eval_scalar_percent(const Value& v) {
if (v.is_error()) return v;
auto n = to_number(v);
if (std::holds_alternative<ErrorCode>(n)) return Value::make_error(std::get<ErrorCode>(n));
return Value::make_checked_number(std::get<double>(n) / 100.0);
}
Value broadcast_binary(BinOp op, const Value& lhs, const Value& rhs) {
if (!lhs.is_array() && !rhs.is_array()) {
return eval_scalar_binary(op, lhs, rhs);
}
int lr = lhs.is_array() ? lhs.as_array()->rows : 1;
int lc = lhs.is_array() ? lhs.as_array()->cols : 1;
int rr = rhs.is_array() ? rhs.as_array()->rows : 1;
int rc = rhs.is_array() ? rhs.as_array()->cols : 1;
if (lr <= 0 || lc <= 0 || rr <= 0 || rc <= 0) {
return Value::make_error(ErrorCode::Value);
}
if (lr != rr && lr != 1 && rr != 1) return Value::make_error(ErrorCode::Value);
if (lc != rc && lc != 1 && rc != 1) return Value::make_error(ErrorCode::Value);
int out_r = std::max(lr, rr);
int out_c = std::max(lc, rc);
if (static_cast<int64_t>(out_r) * out_c > kMaxArrayCells) {
return Value::make_error(ErrorCode::Num);
}
auto out = std::make_shared<Array2D>(out_r, out_c);
for (int r = 0; r < out_r; ++r) {
for (int c = 0; c < out_c; ++c) {
const Value& va = lhs.is_array() ? lhs.as_array()->at(lr == 1 ? 0 : r, lc == 1 ? 0 : c) : lhs;
const Value& vb = rhs.is_array() ? rhs.as_array()->at(rr == 1 ? 0 : r, rc == 1 ? 0 : c) : rhs;
out->at(r, c) = eval_scalar_binary(op, va, vb);
}
}
if (out_r == 1 && out_c == 1) {
return out->at(0, 0);
}
return Value::make_array(std::move(out));
}
template <typename Fn>
Value map_unary(const Value& v, Fn&& fn) {
if (!v.is_array()) return fn(v);
const auto& arr = v.as_array();
if (!arr || arr->rows <= 0 || arr->cols <= 0) {
return Value::make_error(ErrorCode::Value);
}
auto out = std::make_shared<Array2D>(arr->rows, arr->cols);
for (int r = 0; r < arr->rows; ++r) {
for (int c = 0; c < arr->cols; ++c) {
out->at(r, c) = fn(arr->at(r, c));
}
}
if (arr->rows == 1 && arr->cols == 1) {
return out->at(0, 0);
}
return Value::make_array(std::move(out));
}
int resolve_sheet(const std::string& sheet_name, const EvalContext& ctx) {
if (sheet_name.empty()) return ctx.current_sheet;
return ctx.wb->find_sheet(sheet_name);
}
} // namespace
Value deref_to_value(const EvalResult& res, const Workbook& wb) {
if (!res.is_ref) {
return res.value;
}
if (res.ranges.size() != 1) {
return Value::make_error(ErrorCode::Value);
}
const CellRange& rng = res.ranges[0];
int rc = rng.row_count();
int cc = rng.col_count();
if (rc == 1 && cc == 1) {
return wb.get_scalar_value(rng.sheet, rng.r1, rng.c1);
}
if (static_cast<int64_t>(rc) * cc > kMaxArrayCells) {
return Value::make_error(ErrorCode::Num);
}
auto arr = std::make_shared<Array2D>(rc, cc);
for (int r = 0; r < rc; ++r) {
for (int c = 0; c < cc; ++c) {
arr->at(r, c) = wb.get_scalar_value(rng.sheet, rng.r1 + r, rng.c1 + c);
}
}
return Value::make_array(std::move(arr));
}
EvalResult evaluate_ast(const Expr* expr, const EvalContext& ctx) {
if (!expr || !ctx.wb) {
return EvalResult::from_value(Value::make_error(ErrorCode::Value));
}
switch (expr->kind) {
case Expr::Kind::Literal: {
return EvalResult::from_value(static_cast<const LiteralExpr*>(expr)->value);
}
case Expr::Kind::UnknownName: {
return EvalResult::from_value(Value::make_error(ErrorCode::Name));
}
case Expr::Kind::CellRef: {
const auto& ref = static_cast<const CellRefExpr*>(expr)->ref;
if (ref.invalid) {
return EvalResult::from_value(Value::make_error(ErrorCode::Ref));
}
int s = resolve_sheet(ref.sheet_name, ctx);
if (s < 0) {
return EvalResult::from_value(Value::make_error(ErrorCode::Ref));
}
return EvalResult::from_range(CellRange{s, ref.row, ref.col, ref.row, ref.col});
}
case Expr::Kind::Range: {
const auto* rng = static_cast<const RangeExpr*>(expr);
EvalResult lr = evaluate_ast(rng->lhs.get(), ctx);
if (!lr.is_ref) {
return EvalResult::from_value(
lr.value.is_error() ? lr.value : Value::make_error(ErrorCode::Value));
}
// Inherit sheet name when writing Sheet2!A1:B5 where RHS omitted the sheet prefix.
EvalContext rhs_ctx = ctx;
if (rng->lhs->kind == Expr::Kind::CellRef && rng->rhs->kind == Expr::Kind::CellRef) {
const auto& lref = static_cast<const CellRefExpr*>(rng->lhs.get())->ref;
const auto& rref = static_cast<const CellRefExpr*>(rng->rhs.get())->ref;
if (!lref.sheet_name.empty() && rref.sheet_name.empty() && !lr.ranges.empty()) {
rhs_ctx.current_sheet = lr.ranges[0].sheet;
}
}
EvalResult rr = evaluate_ast(rng->rhs.get(), rhs_ctx);
if (!rr.is_ref) {
return EvalResult::from_value(
rr.value.is_error() ? rr.value : Value::make_error(ErrorCode::Value));
}
if (lr.ranges.size() != 1 || rr.ranges.size() != 1) {
return EvalResult::from_value(Value::make_error(ErrorCode::Value));
}
const CellRange& a = lr.ranges[0];
const CellRange& b = rr.ranges[0];
if (a.sheet != b.sheet) {
return EvalResult::from_value(Value::make_error(ErrorCode::Value));
}
return EvalResult::from_range(CellRange{
a.sheet,
std::min(a.r1, b.r1),
std::min(a.c1, b.c1),
std::max(a.r2, b.r2),
std::max(a.c2, b.c2),
});
}
case Expr::Kind::Unary: {
const auto* u = static_cast<const UnaryExpr*>(expr);
Value val = deref_to_value(evaluate_ast(u->operand.get(), ctx), *ctx.wb);
return EvalResult::from_value(
map_unary(val, [op = u->op](const Value& item) { return eval_scalar_unary(op, item); }));
}
case Expr::Kind::Percent: {
const auto* p = static_cast<const PercentExpr*>(expr);
Value val = deref_to_value(evaluate_ast(p->operand.get(), ctx), *ctx.wb);
return EvalResult::from_value(map_unary(val, eval_scalar_percent));
}
case Expr::Kind::Binary: {
const auto* b = static_cast<const BinaryExpr*>(expr);
EvalResult lr = evaluate_ast(b->lhs.get(), ctx);
EvalResult rr = evaluate_ast(b->rhs.get(), ctx);
if (b->op == BinOp::Union) {
if (!lr.is_ref) {
return EvalResult::from_value(
lr.value.is_error() ? lr.value : Value::make_error(ErrorCode::Value));
}
if (!rr.is_ref) {
return EvalResult::from_value(
rr.value.is_error() ? rr.value : Value::make_error(ErrorCode::Value));
}
std::vector<CellRange> combined = std::move(lr.ranges);
combined.insert(combined.end(), rr.ranges.begin(), rr.ranges.end());
return EvalResult::from_ranges(std::move(combined));
}
if (b->op == BinOp::Intersect) {
if (!lr.is_ref) {
return EvalResult::from_value(
lr.value.is_error() ? lr.value : Value::make_error(ErrorCode::Value));
}
if (!rr.is_ref) {
return EvalResult::from_value(
rr.value.is_error() ? rr.value : Value::make_error(ErrorCode::Value));
}
std::vector<CellRange> overlaps;
for (const auto& ra : lr.ranges) {
for (const auto& rb : rr.ranges) {
if (ra.sheet != rb.sheet) continue;
int r1 = std::max(ra.r1, rb.r1);
int c1 = std::max(ra.c1, rb.c1);
int r2 = std::min(ra.r2, rb.r2);
int c2 = std::min(ra.c2, rb.c2);
if (r1 <= r2 && c1 <= c2) {
overlaps.push_back(CellRange{ra.sheet, r1, c1, r2, c2});
}
}
}
if (overlaps.empty()) {
return EvalResult::from_value(Value::make_error(ErrorCode::NA));
}
return EvalResult::from_ranges(std::move(overlaps));
}
Value lv = deref_to_value(lr, *ctx.wb);
Value rv = deref_to_value(rr, *ctx.wb);
return EvalResult::from_value(broadcast_binary(b->op, lv, rv));
}
case Expr::Kind::Call: {
const auto* call = static_cast<const CallExpr*>(expr);
const auto* fn = FunctionRegistry::instance().find(call->name);
if (!fn) {
return EvalResult::from_value(Value::make_error(ErrorCode::Name));
}
return (*fn)(call->args, ctx);
}
}
return EvalResult::from_value(Value::make_error(ErrorCode::Value));
}
} // namespace htab
+50
View File
@@ -0,0 +1,50 @@
#pragma once
#include "engine/address.hpp"
#include "engine/parser.hpp"
#include "engine/value.hpp"
#include <vector>
namespace htab {
class Workbook;
struct EvalResult {
bool is_ref = false;
Value value;
std::vector<CellRange> ranges;
static EvalResult from_value(Value v) {
EvalResult r;
r.is_ref = false;
r.value = std::move(v);
return r;
}
static EvalResult from_range(CellRange rng) {
EvalResult r;
r.is_ref = true;
r.ranges.push_back(rng);
return r;
}
static EvalResult from_ranges(std::vector<CellRange> rngs) {
EvalResult r;
r.is_ref = true;
r.ranges = std::move(rngs);
return r;
}
};
struct EvalContext {
const Workbook* wb = nullptr;
int current_sheet = 0;
int current_row = 0;
int current_col = 0;
};
Value deref_to_value(const EvalResult& res, const Workbook& wb);
EvalResult evaluate_ast(const Expr* expr, const EvalContext& ctx);
} // namespace htab
+185
View File
@@ -0,0 +1,185 @@
#include "engine/format.hpp"
#include <cmath>
#include <cstdint>
#include <cstdio>
namespace htab {
namespace {
// Howard Hinnant civil-from-days / days-from-civil (epoch 1970-01-01)
constexpr int64_t kEpochOffset = 25569; // days between 1899-12-30 and 1970-01-01
int64_t days_from_civil(int64_t y, unsigned m, unsigned d) {
y -= m <= 2;
const int64_t era = (y >= 0 ? y : y - 399) / 400;
const unsigned yoe = static_cast<unsigned>(y - era * 400);
const unsigned doy = (153 * (m + (m > 2 ? static_cast<unsigned>(-3) : 9)) + 2) / 5 + d - 1;
const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
return era * 146097 + static_cast<int64_t>(doe) - 719468;
}
void civil_from_days(int64_t z, int& y_out, int& m_out, int& d_out) {
z += 719468;
const int64_t era = (z >= 0 ? z : z - 146096) / 146097;
const unsigned doe = static_cast<unsigned>(z - era * 146097);
const unsigned yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
const int64_t y = static_cast<int64_t>(yoe) + era * 400;
const unsigned doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
const unsigned mp = (5 * doy + 2) / 153;
const unsigned d = doy - (153 * mp + 2) / 5 + 1;
const unsigned m = mp + (mp < 10 ? 3 : static_cast<unsigned>(-9));
y_out = static_cast<int>(y + (m <= 2));
m_out = static_cast<int>(m);
d_out = static_cast<int>(d);
}
std::string insert_thousands_commas(const std::string& int_digits) {
if (int_digits.size() <= 3) return int_digits;
std::string out;
out.reserve(int_digits.size() + int_digits.size() / 3);
size_t rem = int_digits.size() % 3;
size_t idx = 0;
if (rem > 0) {
out.append(int_digits, 0, rem);
idx = rem;
}
while (idx < int_digits.size()) {
if (!out.empty()) out.push_back(',');
out.append(int_digits, idx, 3);
idx += 3;
}
return out;
}
std::string format_fixed_num(double v, int decimals, bool thousands) {
if (!std::isfinite(v)) return "#NUM!";
bool neg = v < 0.0;
double av = std::fabs(v);
char buf[128];
std::snprintf(buf, sizeof(buf), "%.*f", decimals, av);
std::string s(buf);
// Prevent "-0.00" when rounded value is zero.
bool all_zero = true;
for (char ch : s) {
if (ch >= '1' && ch <= '9') {
all_zero = false;
break;
}
}
if (all_zero) neg = false;
if (thousands) {
size_t dot = s.find('.');
std::string int_part = (dot == std::string::npos) ? s : s.substr(0, dot);
std::string frac_part = (dot == std::string::npos) ? "" : s.substr(dot);
s = insert_thousands_commas(int_part) + frac_part;
}
if (neg) s.insert(s.begin(), '-');
return s;
}
} // namespace
int ymd_to_serial(int year, int month, int day) {
int64_t total_months = static_cast<int64_t>(year) * 12 + static_cast<int64_t>(month - 1);
int64_t norm_y = total_months >= 0 ? (total_months / 12) : ((total_months - 11) / 12);
int64_t norm_m = total_months - norm_y * 12 + 1;
int64_t days = days_from_civil(norm_y, static_cast<unsigned>(norm_m), 1) +
static_cast<int64_t>(day - 1) + kEpochOffset;
return static_cast<int>(days);
}
void serial_to_ymd(int serial, int& year, int& month, int& day) {
civil_from_days(static_cast<int64_t>(serial) - kEpochOffset, year, month, day);
}
void serial_to_hms(double serial, int& hour, int& minute, int& second) {
double frac = serial - std::floor(serial);
long long total = std::llround(frac * 86400.0);
total = ((total % 86400) + 86400) % 86400;
hour = static_cast<int>(total / 3600);
minute = static_cast<int>((total % 3600) / 60);
second = static_cast<int>(total % 60);
}
std::string format_value(const Value& val, const std::string& fmt) {
if (val.is_empty()) return "";
if (val.is_error()) return std::string(error_to_string(val.as_error()));
if (val.is_bool()) return val.as_bool() ? "TRUE" : "FALSE";
if (val.is_string()) return val.as_string();
if (val.is_array()) {
const auto& arr = val.as_array();
if (arr && !arr->data.empty()) {
return format_value(arr->at(0, 0), fmt);
}
return "";
}
double d = val.as_number();
if (fmt.empty() || iequals_ascii(fmt, "General")) {
auto s = to_string(val);
return std::holds_alternative<std::string>(s) ? std::get<std::string>(s) : "#VALUE!";
}
if (iequals_ascii(fmt, "Fixed") || fmt == "0.00") {
return format_fixed_num(d, 2, false);
}
if (iequals_ascii(fmt, "Integer") || fmt == "#,##0" || fmt == "0") {
return format_fixed_num(d, 0, fmt != "0");
}
if (iequals_ascii(fmt, "Currency") || fmt == "$#,##0.00") {
bool neg = d < 0.0;
std::string body = format_fixed_num(std::fabs(d), 2, true);
bool all_zero = (body == "0.00");
if (neg && !all_zero) return "-$" + body;
return "$" + body;
}
if (iequals_ascii(fmt, "Percentage") || fmt == "0.00%" || fmt == "0%") {
int dec = (fmt == "0%") ? 0 : 2;
return format_fixed_num(d * 100.0, dec, false) + "%";
}
if (iequals_ascii(fmt, "Date") || iequals_ascii(fmt, "yyyy-mm-dd")) {
int y = 0, m = 0, day = 0;
serial_to_ymd(static_cast<int>(std::floor(d)), y, m, day);
char buf[32];
std::snprintf(buf, sizeof(buf), "%04d-%02d-%02d", y, m, day);
return std::string(buf);
}
if (iequals_ascii(fmt, "Time") || iequals_ascii(fmt, "hh:mm:ss")) {
int hh = 0, mm = 0, ss = 0;
serial_to_hms(d, hh, mm, ss);
char buf[32];
std::snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hh, mm, ss);
return std::string(buf);
}
if (iequals_ascii(fmt, "DateTime") || iequals_ascii(fmt, "yyyy-mm-dd hh:mm")) {
int y = 0, m = 0, day = 0, hh = 0, mm = 0, ss = 0;
long long rounded_sec = std::llround((d - std::floor(d)) * 86400.0);
int day_serial = static_cast<int>(std::floor(d));
if (rounded_sec >= 86400) {
day_serial += 1;
}
serial_to_ymd(day_serial, y, m, day);
serial_to_hms(d, hh, mm, ss);
char buf[48];
std::snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d", y, m, day, hh, mm);
return std::string(buf);
}
// Fallback for custom decimal formats like "0.0" or "0.000%".
if (fmt.rfind("0.", 0) == 0) {
bool pct = fmt.back() == '%';
size_t dec = fmt.size() - 2 - (pct ? 1 : 0);
if (dec <= 8) {
return format_fixed_num(pct ? d * 100.0 : d, static_cast<int>(dec), false) +
(pct ? "%" : "");
}
}
auto s = to_string(val);
return std::holds_alternative<std::string>(s) ? std::get<std::string>(s) : "#VALUE!";
}
} // namespace htab
+16
View File
@@ -0,0 +1,16 @@
#pragma once
#include "engine/value.hpp"
#include <string>
namespace htab {
// Pure proleptic Gregorian calendar with serial 0 = 1899-12-30.
int ymd_to_serial(int year, int month, int day);
void serial_to_ymd(int serial, int& year, int& month, int& day);
void serial_to_hms(double serial, int& hour, int& minute, int& second);
std::string format_value(const Value& val, const std::string& fmt);
} // namespace htab
+269
View File
@@ -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
+316
View File
@@ -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
+377
View File
@@ -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
+387
View File
@@ -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
+54
View File
@@ -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
+122
View File
@@ -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
+353
View File
@@ -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
+324
View File
@@ -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
+31
View File
@@ -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
+41
View File
@@ -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
+222
View File
@@ -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
+293
View File
@@ -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
+213
View File
@@ -0,0 +1,213 @@
#include "engine/io_csv.hpp"
#include <fstream>
#include <sstream>
#include <vector>
namespace htab {
namespace {
bool parse_rfc4180_csv(std::string_view text,
std::vector<std::vector<std::string>>& rows_out,
std::string* err) {
rows_out.clear();
if (text.size() >= 3 &&
static_cast<unsigned char>(text[0]) == 0xEF &&
static_cast<unsigned char>(text[1]) == 0xBB &&
static_cast<unsigned char>(text[2]) == 0xBF) {
text.remove_prefix(3);
}
if (text.empty()) return true;
size_t i = 0;
std::vector<std::string> current_row;
while (i < text.size()) {
std::string field;
if (text[i] == '"') {
++i;
bool closed = false;
while (i < text.size()) {
if (text[i] == '"') {
if (i + 1 < text.size() && text[i + 1] == '"') {
field.push_back('"');
i += 2;
} else {
++i;
closed = true;
break;
}
} else {
field.push_back(text[i++]);
}
}
if (!closed) {
if (err) *err = "Unterminated quoted CSV field";
return false;
}
if (i < text.size() && text[i] != ',' && text[i] != '\r' && text[i] != '\n') {
if (err) *err = "Unexpected character after closing CSV quote";
return false;
}
} else {
while (i < text.size() && text[i] != ',' && text[i] != '\r' && text[i] != '\n') {
if (text[i] == '"') {
if (err) *err = "Unexpected quote inside unquoted CSV field";
return false;
}
field.push_back(text[i++]);
}
}
current_row.push_back(std::move(field));
if (i >= text.size()) {
rows_out.push_back(std::move(current_row));
current_row.clear();
break;
}
if (text[i] == ',') {
++i;
if (i >= text.size()) {
// Trailing comma at EOF -> final empty field
current_row.emplace_back("");
rows_out.push_back(std::move(current_row));
current_row.clear();
break;
}
continue;
}
// End of line (\r\n, \n, or \r)
if (text[i] == '\r') {
++i;
if (i < text.size() && text[i] == '\n') ++i;
} else if (text[i] == '\n') {
++i;
}
rows_out.push_back(std::move(current_row));
current_row.clear();
}
return true;
}
std::string escape_csv_field(const std::string& s) {
bool needs_quote = false;
for (char ch : s) {
if (ch == ',' || ch == '"' || ch == '\n' || ch == '\r') {
needs_quote = true;
break;
}
}
if (!needs_quote) return s;
std::string out;
out.reserve(s.size() + 4);
out.push_back('"');
for (char ch : s) {
if (ch == '"') out += "\"\"";
else out.push_back(ch);
}
out.push_back('"');
return out;
}
} // namespace
bool import_csv_string(Workbook& wb,
int sheet_idx,
std::string_view csv_text,
std::string* err) {
if (sheet_idx < 0 || sheet_idx >= wb.sheet_count()) {
if (err) *err = "Invalid sheet index";
return false;
}
std::vector<std::vector<std::string>> rows;
if (!parse_rfc4180_csv(csv_text, rows, err)) {
return false;
}
std::unordered_map<CellKey, Cell, CellKeyHash> new_cells;
for (size_t r = 0; r < rows.size(); ++r) {
if (r >= static_cast<size_t>(kMaxRows)) break;
for (size_t c = 0; c < rows[r].size(); ++c) {
if (c >= static_cast<size_t>(kMaxCols)) break;
if (rows[r][c].empty()) continue;
Cell cell;
cell.raw_input = rows[r][c];
new_cells.emplace(CellKey{static_cast<int>(r), static_cast<int>(c)}, std::move(cell));
}
}
wb.replace_sheet_cells(sheet_idx, std::move(new_cells));
return true;
}
bool import_csv_file(Workbook& wb,
int sheet_idx,
const std::string& path,
std::string* err) {
std::ifstream in(path, std::ios::binary);
if (!in) {
if (err) *err = "Cannot open CSV file for reading: " + path;
return false;
}
std::ostringstream oss;
oss << in.rdbuf();
return import_csv_string(wb, sheet_idx, oss.str(), err);
}
std::string export_csv_string(const Workbook& wb,
int sheet_idx,
bool export_formulas) {
auto bounds = wb.get_used_bounds(sheet_idx);
if (!bounds) return "";
std::string out;
for (int r = 0; r <= bounds->r2; ++r) {
int row_last_col = -1;
std::vector<std::string> row_vals(static_cast<size_t>(bounds->c2 + 1));
for (int c = 0; c <= bounds->c2; ++c) {
std::string val;
if (export_formulas) {
const Cell* cell = wb.get_cell(sheet_idx, r, c);
if (cell && !cell->raw_input.empty()) {
val = cell->raw_input;
}
} else {
val = wb.get_formatted_value(sheet_idx, r, c);
}
if (!val.empty()) row_last_col = c;
row_vals[static_cast<size_t>(c)] = std::move(val);
}
int limit = (row_last_col >= 0) ? row_last_col : -1;
for (int c = 0; c <= limit; ++c) {
if (c > 0) out.push_back(',');
out += escape_csv_field(row_vals[static_cast<size_t>(c)]);
}
out += "\r\n";
}
return out;
}
bool export_csv_file(const Workbook& wb,
int sheet_idx,
const std::string& path,
bool export_formulas,
std::string* err) {
std::ofstream out(path, std::ios::binary | std::ios::trunc);
if (!out) {
if (err) *err = "Cannot open CSV file for writing: " + path;
return false;
}
std::string data = export_csv_string(wb, sheet_idx, export_formulas);
out.write(data.data(), static_cast<std::streamsize>(data.size()));
if (!out) {
if (err) *err = "Failed writing CSV file: " + path;
return false;
}
return true;
}
} // namespace htab
+30
View File
@@ -0,0 +1,30 @@
#pragma once
#include "engine/workbook.hpp"
#include <string>
#include <string_view>
namespace htab {
bool import_csv_string(Workbook& wb,
int sheet_idx,
std::string_view csv_text,
std::string* err = nullptr);
bool import_csv_file(Workbook& wb,
int sheet_idx,
const std::string& path,
std::string* err = nullptr);
std::string export_csv_string(const Workbook& wb,
int sheet_idx,
bool export_formulas = false);
bool export_csv_file(const Workbook& wb,
int sheet_idx,
const std::string& path,
bool export_formulas = false,
std::string* err = nullptr);
} // namespace htab
+530
View File
@@ -0,0 +1,530 @@
#include "engine/io_native.hpp"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <map>
#include <sstream>
#include <variant>
#include <vector>
namespace htab {
namespace {
void append_json_string(std::string& out, const std::string& s) {
out.push_back('"');
for (unsigned char ch : s) {
switch (ch) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (ch < 0x20) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast<unsigned>(ch));
out += buf;
} else {
out.push_back(static_cast<char>(ch));
}
break;
}
}
out.push_back('"');
}
struct JsonValue;
using JsonArray = std::vector<JsonValue>;
using JsonObject = std::vector<std::pair<std::string, JsonValue>>;
struct JsonValue {
std::variant<std::nullptr_t, bool, double, std::string, JsonArray, JsonObject> data;
bool is_null() const { return std::holds_alternative<std::nullptr_t>(data); }
bool is_bool() const { return std::holds_alternative<bool>(data); }
bool is_number() const { return std::holds_alternative<double>(data); }
bool is_string() const { return std::holds_alternative<std::string>(data); }
bool is_array() const { return std::holds_alternative<JsonArray>(data); }
bool is_object() const { return std::holds_alternative<JsonObject>(data); }
const JsonValue* find(std::string_view key) const {
if (!is_object()) return nullptr;
for (const auto& [k, v] : std::get<JsonObject>(data)) {
if (k == key) return &v;
}
return nullptr;
}
};
class JsonParser {
public:
explicit JsonParser(std::string_view src) : src_(src) {}
bool parse(JsonValue& out, std::string& err) {
skip_ws();
if (!parse_value(out, 0, err)) return false;
skip_ws();
if (pos_ != src_.size()) {
err = "Unexpected trailing data in JSON";
return false;
}
return true;
}
private:
void skip_ws() {
while (pos_ < src_.size() &&
(src_[pos_] == ' ' || src_[pos_] == '\t' ||
src_[pos_] == '\r' || src_[pos_] == '\n')) {
++pos_;
}
}
static void append_utf8(std::string& out, uint32_t cp) {
if (cp <= 0x7F) {
out.push_back(static_cast<char>(cp));
} else if (cp <= 0x7FF) {
out.push_back(static_cast<char>(0xC0 | (cp >> 6)));
out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
} else if (cp <= 0xFFFF) {
out.push_back(static_cast<char>(0xE0 | (cp >> 12)));
out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
} else {
out.push_back(static_cast<char>(0xF0 | (cp >> 18)));
out.push_back(static_cast<char>(0x80 | ((cp >> 12) & 0x3F)));
out.push_back(static_cast<char>(0x80 | ((cp >> 6) & 0x3F)));
out.push_back(static_cast<char>(0x80 | (cp & 0x3F)));
}
}
bool parse_hex4(uint32_t& out) {
if (pos_ + 4 > src_.size()) return false;
uint32_t v = 0;
for (int i = 0; i < 4; ++i) {
char ch = src_[pos_++];
v <<= 4;
if (ch >= '0' && ch <= '9') v |= static_cast<uint32_t>(ch - '0');
else if (ch >= 'a' && ch <= 'f') v |= static_cast<uint32_t>(ch - 'a' + 10);
else if (ch >= 'A' && ch <= 'F') v |= static_cast<uint32_t>(ch - 'A' + 10);
else return false;
}
out = v;
return true;
}
bool parse_string(std::string& out, std::string& err) {
if (pos_ >= src_.size() || src_[pos_] != '"') {
err = "Expected '\"'";
return false;
}
++pos_;
out.clear();
while (pos_ < src_.size()) {
char ch = src_[pos_++];
if (ch == '"') return true;
if (static_cast<unsigned char>(ch) < 0x20) {
err = "Control character in JSON string";
return false;
}
if (ch == '\\') {
if (pos_ >= src_.size()) {
err = "Unterminated escape in JSON string";
return false;
}
char esc = src_[pos_++];
switch (esc) {
case '"': out.push_back('"'); break;
case '\\': out.push_back('\\'); break;
case '/': out.push_back('/'); break;
case 'b': out.push_back('\b'); break;
case 'f': out.push_back('\f'); break;
case 'n': out.push_back('\n'); break;
case 'r': out.push_back('\r'); break;
case 't': out.push_back('\t'); break;
case 'u': {
uint32_t cp = 0;
if (!parse_hex4(cp)) {
err = "Invalid \\u escape in JSON";
return false;
}
if (cp >= 0xD800 && cp <= 0xDBFF && pos_ + 6 <= src_.size() &&
src_[pos_] == '\\' && src_[pos_ + 1] == 'u') {
pos_ += 2;
uint32_t low = 0;
if (!parse_hex4(low) || low < 0xDC00 || low > 0xDFFF) {
err = "Invalid UTF-16 surrogate pair in JSON";
return false;
}
cp = 0x10000 + (((cp - 0xD800) << 10) | (low - 0xDC00));
}
append_utf8(out, cp);
break;
}
default:
err = "Unknown escape in JSON string";
return false;
}
} else {
out.push_back(ch);
}
}
err = "Unterminated JSON string";
return false;
}
bool parse_number(double& out, std::string& err) {
size_t start = pos_;
if (pos_ < src_.size() && src_[pos_] == '-') ++pos_;
if (pos_ >= src_.size() || !std::isdigit(static_cast<unsigned char>(src_[pos_]))) {
err = "Invalid JSON number";
return false;
}
if (src_[pos_] == '0') {
++pos_;
} else {
while (pos_ < src_.size() && std::isdigit(static_cast<unsigned char>(src_[pos_]))) ++pos_;
}
if (pos_ < src_.size() && src_[pos_] == '.') {
++pos_;
if (pos_ >= src_.size() || !std::isdigit(static_cast<unsigned char>(src_[pos_]))) {
err = "Invalid JSON fraction";
return false;
}
while (pos_ < src_.size() && std::isdigit(static_cast<unsigned char>(src_[pos_]))) ++pos_;
}
if (pos_ < src_.size() && (src_[pos_] == 'e' || src_[pos_] == 'E')) {
++pos_;
if (pos_ < src_.size() && (src_[pos_] == '+' || src_[pos_] == '-')) ++pos_;
if (pos_ >= src_.size() || !std::isdigit(static_cast<unsigned char>(src_[pos_]))) {
err = "Invalid JSON exponent";
return false;
}
while (pos_ < src_.size() && std::isdigit(static_cast<unsigned char>(src_[pos_]))) ++pos_;
}
std::string num_str(src_.substr(start, pos_ - start));
char* endptr = nullptr;
double val = std::strtod(num_str.c_str(), &endptr);
if (endptr != num_str.c_str() + num_str.size() || !std::isfinite(val)) {
err = "Non-finite JSON number";
return false;
}
out = val;
return true;
}
bool parse_value(JsonValue& out, int depth, std::string& err) {
if (depth > 64) {
err = "JSON nesting too deep";
return false;
}
skip_ws();
if (pos_ >= src_.size()) {
err = "Unexpected end of JSON";
return false;
}
char ch = src_[pos_];
if (ch == '"') {
std::string s;
if (!parse_string(s, err)) return false;
out.data = std::move(s);
return true;
}
if (ch == '{') {
++pos_;
JsonObject obj;
skip_ws();
if (pos_ < src_.size() && src_[pos_] == '}') {
++pos_;
out.data = std::move(obj);
return true;
}
while (true) {
skip_ws();
std::string key;
if (!parse_string(key, err)) return false;
skip_ws();
if (pos_ >= src_.size() || src_[pos_] != ':') {
err = "Expected ':' in JSON object";
return false;
}
++pos_;
JsonValue val;
if (!parse_value(val, depth + 1, err)) return false;
obj.emplace_back(std::move(key), std::move(val));
skip_ws();
if (pos_ >= src_.size()) {
err = "Unterminated JSON object";
return false;
}
if (src_[pos_] == '}') {
++pos_;
out.data = std::move(obj);
return true;
}
if (src_[pos_] != ',') {
err = "Expected ',' or '}' in JSON object";
return false;
}
++pos_;
}
}
if (ch == '[') {
++pos_;
JsonArray arr;
skip_ws();
if (pos_ < src_.size() && src_[pos_] == ']') {
++pos_;
out.data = std::move(arr);
return true;
}
while (true) {
JsonValue elem;
if (!parse_value(elem, depth + 1, err)) return false;
arr.push_back(std::move(elem));
skip_ws();
if (pos_ >= src_.size()) {
err = "Unterminated JSON array";
return false;
}
if (src_[pos_] == ']') {
++pos_;
out.data = std::move(arr);
return true;
}
if (src_[pos_] != ',') {
err = "Expected ',' or ']' in JSON array";
return false;
}
++pos_;
}
}
if (src_.substr(pos_, 4) == "true") {
pos_ += 4;
out.data = true;
return true;
}
if (src_.substr(pos_, 5) == "false") {
pos_ += 5;
out.data = false;
return true;
}
if (src_.substr(pos_, 4) == "null") {
pos_ += 4;
out.data = nullptr;
return true;
}
if (ch == '-' || std::isdigit(static_cast<unsigned char>(ch))) {
double d = 0.0;
if (!parse_number(d, err)) return false;
out.data = d;
return true;
}
err = "Unexpected token in JSON";
return false;
}
std::string_view src_;
size_t pos_ = 0;
};
} // namespace
std::string save_native_string(const Workbook& wb) {
std::string out;
out.reserve(4096);
out += "{\n \"htab_version\": 1,\n \"active_sheet\": ";
out += std::to_string(wb.active_sheet());
out += ",\n \"sheets\": [\n";
for (int si = 0; si < wb.sheet_count(); ++si) {
const Sheet& s = wb.sheet(si);
out += " {\n \"name\": ";
append_json_string(out, s.name);
// Deterministic sorted order for col_widths, row_heights, and cells
std::map<int, int> sorted_cw(s.col_widths.begin(), s.col_widths.end());
out += ",\n \"col_widths\": {";
bool first_cw = true;
for (const auto& [col, w] : sorted_cw) {
if (!first_cw) out += ", ";
first_cw = false;
append_json_string(out, std::to_string(col));
out += ": " + std::to_string(w);
}
out += "}";
std::map<int, int> sorted_rh(s.row_heights.begin(), s.row_heights.end());
out += ",\n \"row_heights\": {";
bool first_rh = true;
for (const auto& [row, h] : sorted_rh) {
if (!first_rh) out += ", ";
first_rh = false;
append_json_string(out, std::to_string(row));
out += ": " + std::to_string(h);
}
out += "}";
std::vector<std::pair<CellKey, const Cell*>> sorted_cells;
sorted_cells.reserve(s.cells.size());
for (const auto& [key, cell] : s.cells) {
if (cell.raw_input.empty() && cell.number_format.empty()) continue;
sorted_cells.emplace_back(key, &cell);
}
std::sort(sorted_cells.begin(), sorted_cells.end(),
[](const auto& a, const auto& b) {
if (a.first.row != b.first.row) return a.first.row < b.first.row;
return a.first.col < b.first.col;
});
out += ",\n \"cells\": [";
if (!sorted_cells.empty()) out.push_back('\n');
for (size_t idx = 0; idx < sorted_cells.size(); ++idx) {
const auto& [key, cell] = sorted_cells[idx];
out += " {\"r\": " + std::to_string(key.row) +
", \"c\": " + std::to_string(key.col) + ", \"raw\": ";
append_json_string(out, cell->raw_input);
if (!cell->number_format.empty()) {
out += ", \"fmt\": ";
append_json_string(out, cell->number_format);
}
out.push_back('}');
if (idx + 1 < sorted_cells.size()) out.push_back(',');
out.push_back('\n');
}
if (!sorted_cells.empty()) out += " ";
out += "]\n }";
if (si + 1 < wb.sheet_count()) out.push_back(',');
out.push_back('\n');
}
out += " ]\n}\n";
return out;
}
bool save_native_file(const Workbook& wb, const std::string& path, std::string* err) {
std::ofstream out(path, std::ios::binary | std::ios::trunc);
if (!out) {
if (err) *err = "Cannot open file for writing: " + path;
return false;
}
std::string data = save_native_string(wb);
out.write(data.data(), static_cast<std::streamsize>(data.size()));
if (!out) {
if (err) *err = "Failed writing workbook file: " + path;
return false;
}
return true;
}
bool load_native_string(Workbook& wb, std::string_view json_text, std::string* err) {
JsonParser parser(json_text);
JsonValue root;
std::string parse_err;
if (!parser.parse(root, parse_err)) {
if (err) *err = parse_err;
return false;
}
if (!root.is_object()) {
if (err) *err = "Root JSON value must be an object";
return false;
}
const JsonValue* ver = root.find("htab_version");
if (!ver || !ver->is_number() || static_cast<int>(std::get<double>(ver->data)) != 1) {
if (err) *err = "Unsupported or missing htab_version";
return false;
}
const JsonValue* sheets_val = root.find("sheets");
if (!sheets_val || !sheets_val->is_array() || std::get<JsonArray>(sheets_val->data).empty()) {
if (err) *err = "Missing or empty sheets array";
return false;
}
int active_sheet = 0;
if (const JsonValue* act = root.find("active_sheet")) {
if (act->is_number()) active_sheet = static_cast<int>(std::get<double>(act->data));
}
std::vector<Sheet> loaded_sheets;
for (const auto& sv : std::get<JsonArray>(sheets_val->data)) {
if (!sv.is_object()) {
if (err) *err = "Sheet entry must be an object";
return false;
}
Sheet s;
const JsonValue* name_v = sv.find("name");
if (!name_v || !name_v->is_string() || std::get<std::string>(name_v->data).empty()) {
if (err) *err = "Sheet entry missing valid name";
return false;
}
s.name = std::get<std::string>(name_v->data);
if (const JsonValue* cw = sv.find("col_widths"); cw && cw->is_object()) {
for (const auto& [k, v] : std::get<JsonObject>(cw->data)) {
if (v.is_number()) {
int col = std::atoi(k.c_str());
int w = static_cast<int>(std::get<double>(v.data));
if (col >= 0 && col < kMaxCols && w > 0) s.col_widths[col] = w;
}
}
}
if (const JsonValue* rh = sv.find("row_heights"); rh && rh->is_object()) {
for (const auto& [k, v] : std::get<JsonObject>(rh->data)) {
if (v.is_number()) {
int row = std::atoi(k.c_str());
int h = static_cast<int>(std::get<double>(v.data));
if (row >= 0 && row < kMaxRows && h > 0) s.row_heights[row] = h;
}
}
}
if (const JsonValue* cells = sv.find("cells"); cells && cells->is_array()) {
for (const auto& cv : std::get<JsonArray>(cells->data)) {
if (!cv.is_object()) continue;
const JsonValue* rv = cv.find("r");
const JsonValue* colv = cv.find("c");
const JsonValue* rawv = cv.find("raw");
if (!rv || !rv->is_number() || !colv || !colv->is_number() || !rawv || !rawv->is_string()) {
if (err) *err = "Invalid cell object in JSON";
return false;
}
int r = static_cast<int>(std::get<double>(rv->data));
int c = static_cast<int>(std::get<double>(colv->data));
if (r < 0 || r >= kMaxRows || c < 0 || c >= kMaxCols) {
if (err) *err = "Cell coordinates out of bounds";
return false;
}
Cell cell;
cell.raw_input = std::get<std::string>(rawv->data);
if (const JsonValue* fmtv = cv.find("fmt"); fmtv && fmtv->is_string()) {
cell.number_format = std::get<std::string>(fmtv->data);
}
s.cells.emplace(CellKey{r, c}, std::move(cell));
}
}
loaded_sheets.push_back(std::move(s));
}
wb.replace_all_sheets(std::move(loaded_sheets), active_sheet);
return true;
}
bool load_native_file(Workbook& wb, const std::string& path, std::string* err) {
std::ifstream in(path, std::ios::binary);
if (!in) {
if (err) *err = "Cannot open workbook file for reading: " + path;
return false;
}
std::ostringstream oss;
oss << in.rdbuf();
return load_native_string(wb, oss.str(), err);
}
} // namespace htab
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include "engine/workbook.hpp"
#include <string>
#include <string_view>
namespace htab {
std::string save_native_string(const Workbook& wb);
bool save_native_file(const Workbook& wb,
const std::string& path,
std::string* err = nullptr);
bool load_native_string(Workbook& wb,
std::string_view json_text,
std::string* err = nullptr);
bool load_native_file(Workbook& wb,
const std::string& path,
std::string* err = nullptr);
} // namespace htab
+428
View File
@@ -0,0 +1,428 @@
#include "engine/lexer.hpp"
#include <cctype>
#include <cmath>
#include <cstdlib>
namespace htab {
namespace {
bool is_ident_start(char ch) {
unsigned char uc = static_cast<unsigned char>(ch);
return std::isalpha(uc) || ch == '_';
}
bool is_ident_cont(char ch) {
unsigned char uc = static_cast<unsigned char>(ch);
return std::isalnum(uc) || ch == '_' || ch == '.';
}
bool try_parse_ref_tail(std::string_view src, size_t pos, size_t& end_out, CellRef& ref_out) {
size_t i = pos;
if (i < src.size() && src[i] == '$') {
ref_out.abs_col = true;
++i;
}
size_t col_start = i;
while (i < src.size() && std::isalpha(static_cast<unsigned char>(src[i]))) {
++i;
}
if (i == col_start) return false;
int col = letters_to_col(src.substr(col_start, i - col_start));
if (col < 0) return false;
if (i < src.size() && src[i] == '$') {
ref_out.abs_row = true;
++i;
}
size_t row_start = i;
int64_t row1 = 0;
while (i < src.size() && std::isdigit(static_cast<unsigned char>(src[i]))) {
row1 = row1 * 10 + (src[i] - '0');
if (row1 > kMaxRows) return false;
++i;
}
if (i == row_start || row1 < 1) return false;
// Must not immediately continue into identifier characters or '(' (unless '$' anchored).
if (i < src.size()) {
if (is_ident_cont(src[i])) return false;
if (!ref_out.abs_col && !ref_out.abs_row && src[i] == '(') return false;
}
ref_out.col = col;
ref_out.row = static_cast<int>(row1 - 1);
end_out = i;
return true;
}
bool try_parse_error_at(std::string_view src, size_t pos, size_t& end_out, ErrorCode& err_out) {
static constexpr const char* kErrors[] = {
"#DIV/0!", "#VALUE!", "#NAME?", "#N/A", "#REF!", "#NUM!", "#CYCLE!", "#SPILL!",
};
for (const char* lit : kErrors) {
std::string_view lv(lit);
if (pos + lv.size() <= src.size() && iequals_ascii(src.substr(pos, lv.size()), lv)) {
end_out = pos + lv.size();
err_out = *parse_error_code(lv);
return true;
}
}
return false;
}
} // namespace
std::vector<Token> Lexer::tokenize(std::string_view input, bool skip_leading_equals) {
std::vector<Token> tokens;
size_t i = 0;
if (skip_leading_equals && i < input.size() && input[i] == '=') {
++i;
}
while (i < input.size()) {
bool had_space = false;
while (i < input.size() && (input[i] == ' ' || input[i] == '\t' ||
input[i] == '\r' || input[i] == '\n')) {
had_space = true;
++i;
}
if (i >= input.size()) break;
size_t start = i;
char ch = input[i];
// String literal "..."
if (ch == '"') {
++i;
std::string val;
bool closed = false;
while (i < input.size()) {
if (input[i] == '"') {
if (i + 1 < input.size() && input[i + 1] == '"') {
val.push_back('"');
i += 2;
} else {
++i;
closed = true;
break;
}
} else {
val.push_back(input[i++]);
}
}
Token tok;
tok.start = start;
tok.end = i;
tok.had_space_before = had_space;
if (closed) {
tok.kind = TokenKind::String;
tok.text = std::move(val);
} else {
tok.kind = TokenKind::Invalid;
tok.text = std::string(input.substr(start, i - start));
}
tokens.push_back(std::move(tok));
continue;
}
// Quoted sheet name '...'!CellRef or '...'!#REF!
if (ch == '\'') {
++i;
std::string sheet;
bool closed = false;
while (i < input.size()) {
if (input[i] == '\'') {
if (i + 1 < input.size() && input[i + 1] == '\'') {
sheet.push_back('\'');
i += 2;
} else {
++i;
closed = true;
break;
}
} else {
sheet.push_back(input[i++]);
}
}
Token tok;
tok.start = start;
tok.had_space_before = had_space;
if (!closed || sheet.empty() || i >= input.size() || input[i] != '!') {
tok.kind = TokenKind::Invalid;
tok.end = i;
tok.text = std::string(input.substr(start, i - start));
tokens.push_back(std::move(tok));
continue;
}
++i; // skip '!'
ErrorCode err = ErrorCode::Ref;
size_t end_pos = i;
if (try_parse_error_at(input, i, end_pos, err) && err == ErrorCode::Ref) {
tok.kind = TokenKind::Error;
tok.err_val = ErrorCode::Ref;
tok.ref_val.sheet_name = sheet;
tok.ref_val.invalid = true;
tok.end = end_pos;
tok.text = std::string(input.substr(start, end_pos - start));
i = end_pos;
tokens.push_back(std::move(tok));
continue;
}
CellRef ref;
ref.sheet_name = std::move(sheet);
if (try_parse_ref_tail(input, i, end_pos, ref)) {
tok.kind = TokenKind::CellRef;
tok.ref_val = std::move(ref);
tok.end = end_pos;
tok.text = std::string(input.substr(start, end_pos - start));
i = end_pos;
} else {
tok.kind = TokenKind::Invalid;
tok.end = i;
tok.text = std::string(input.substr(start, i - start));
}
tokens.push_back(std::move(tok));
continue;
}
// Error literal #...
if (ch == '#') {
ErrorCode err = ErrorCode::Value;
size_t end_pos = i;
Token tok;
tok.start = start;
tok.had_space_before = had_space;
if (try_parse_error_at(input, i, end_pos, err)) {
tok.kind = TokenKind::Error;
tok.err_val = err;
tok.end = end_pos;
tok.text = std::string(input.substr(start, end_pos - start));
i = end_pos;
} else {
++i;
tok.kind = TokenKind::Invalid;
tok.end = i;
tok.text = std::string(input.substr(start, 1));
}
tokens.push_back(std::move(tok));
continue;
}
// Number literal
if (std::isdigit(static_cast<unsigned char>(ch)) ||
(ch == '.' && i + 1 < input.size() && std::isdigit(static_cast<unsigned char>(input[i + 1])))) {
while (i < input.size() && std::isdigit(static_cast<unsigned char>(input[i]))) ++i;
if (i < input.size() && input[i] == '.') {
++i;
while (i < input.size() && std::isdigit(static_cast<unsigned char>(input[i]))) ++i;
}
if (i < input.size() && (input[i] == 'e' || input[i] == 'E')) {
size_t exp_save = i;
++i;
if (i < input.size() && (input[i] == '+' || input[i] == '-')) ++i;
if (i < input.size() && std::isdigit(static_cast<unsigned char>(input[i]))) {
while (i < input.size() && std::isdigit(static_cast<unsigned char>(input[i]))) ++i;
} else {
i = exp_save;
}
}
std::string num_str(input.substr(start, i - start));
char* endptr = nullptr;
double val = std::strtod(num_str.c_str(), &endptr);
bool valid_num = (endptr == num_str.c_str() + num_str.size()) && std::isfinite(val);
Token tok;
tok.start = start;
tok.end = i;
tok.had_space_before = had_space;
tok.text = std::move(num_str);
if (valid_num) {
tok.kind = TokenKind::Number;
tok.num_val = (val == 0.0) ? 0.0 : val;
} else {
tok.kind = TokenKind::Error;
tok.err_val = ErrorCode::Num;
}
tokens.push_back(std::move(tok));
continue;
}
// Anchored cell reference starting with '$'
if (ch == '$') {
CellRef ref;
size_t end_pos = i;
Token tok;
tok.start = start;
tok.had_space_before = had_space;
if (try_parse_ref_tail(input, i, end_pos, ref)) {
tok.kind = TokenKind::CellRef;
tok.ref_val = std::move(ref);
tok.end = end_pos;
tok.text = std::string(input.substr(start, end_pos - start));
i = end_pos;
} else {
++i;
tok.kind = TokenKind::Invalid;
tok.end = i;
tok.text = "$";
}
tokens.push_back(std::move(tok));
continue;
}
// Identifier, Boolean, CellRef, or Unquoted Sheet!Ref
if (is_ident_start(ch)) {
while (i < input.size() && is_ident_cont(input[i])) ++i;
// Handle A$1 where '$' follows column letters directly
if (i < input.size() && input[i] == '$') {
CellRef ref;
size_t end_pos = start;
if (try_parse_ref_tail(input, start, end_pos, ref)) {
Token tok;
tok.kind = TokenKind::CellRef;
tok.ref_val = std::move(ref);
tok.start = start;
tok.end = end_pos;
tok.had_space_before = had_space;
tok.text = std::string(input.substr(start, end_pos - start));
i = end_pos;
tokens.push_back(std::move(tok));
continue;
}
}
std::string word(input.substr(start, i - start));
Token tok;
tok.start = start;
tok.had_space_before = had_space;
if (i < input.size() && input[i] == '!') {
++i;
ErrorCode err = ErrorCode::Ref;
size_t end_pos = i;
if (try_parse_error_at(input, i, end_pos, err) && err == ErrorCode::Ref) {
tok.kind = TokenKind::Error;
tok.err_val = ErrorCode::Ref;
tok.ref_val.sheet_name = std::move(word);
tok.ref_val.invalid = true;
tok.end = end_pos;
tok.text = std::string(input.substr(start, end_pos - start));
i = end_pos;
tokens.push_back(std::move(tok));
continue;
}
CellRef ref;
ref.sheet_name = std::move(word);
if (try_parse_ref_tail(input, i, end_pos, ref)) {
tok.kind = TokenKind::CellRef;
tok.ref_val = std::move(ref);
tok.end = end_pos;
tok.text = std::string(input.substr(start, end_pos - start));
i = end_pos;
} else {
tok.kind = TokenKind::Invalid;
tok.end = i;
tok.text = std::string(input.substr(start, i - start));
}
tokens.push_back(std::move(tok));
continue;
}
// If immediately followed by '(', it is always a function name (e.g. LOG10(...), TRUE()).
if (i < input.size() && input[i] == '(') {
tok.kind = TokenKind::Ident;
tok.end = i;
tok.text = to_upper_ascii(word);
tokens.push_back(std::move(tok));
continue;
}
if (iequals_ascii(word, "TRUE")) {
tok.kind = TokenKind::Bool;
tok.bool_val = true;
tok.end = i;
tok.text = std::move(word);
tokens.push_back(std::move(tok));
continue;
}
if (iequals_ascii(word, "FALSE")) {
tok.kind = TokenKind::Bool;
tok.bool_val = false;
tok.end = i;
tok.text = std::move(word);
tokens.push_back(std::move(tok));
continue;
}
// Check if valid unanchored cell ref like A1 or AA100
CellRef ref;
size_t end_pos = start;
if (try_parse_ref_tail(input, start, end_pos, ref) && end_pos == i) {
tok.kind = TokenKind::CellRef;
tok.ref_val = std::move(ref);
tok.end = i;
tok.text = std::move(word);
tokens.push_back(std::move(tok));
continue;
}
tok.kind = TokenKind::Ident;
tok.end = i;
tok.text = to_upper_ascii(word);
tokens.push_back(std::move(tok));
continue;
}
// Two-character operators
if (i + 1 < input.size()) {
std::string_view two = input.substr(i, 2);
if (two == "<>" || two == "<=" || two == ">=") {
Token tok;
tok.kind = (two == "<>") ? TokenKind::Neq : (two == "<=" ? TokenKind::Le : TokenKind::Ge);
tok.text = std::string(two);
tok.start = start;
tok.end = i + 2;
tok.had_space_before = had_space;
i += 2;
tokens.push_back(std::move(tok));
continue;
}
}
// Single-character operators
TokenKind sk = TokenKind::Invalid;
switch (ch) {
case ':': sk = TokenKind::Colon; break;
case ',': sk = TokenKind::Comma; break;
case '+': sk = TokenKind::Plus; break;
case '-': sk = TokenKind::Minus; break;
case '*': sk = TokenKind::Star; break;
case '/': sk = TokenKind::Slash; break;
case '^': sk = TokenKind::Caret; break;
case '%': sk = TokenKind::Percent; break;
case '&': sk = TokenKind::Amp; break;
case '=': sk = TokenKind::Eq; break;
case '<': sk = TokenKind::Lt; break;
case '>': sk = TokenKind::Gt; break;
case '(': sk = TokenKind::LParen; break;
case ')': sk = TokenKind::RParen; break;
default: sk = TokenKind::Invalid; break;
}
++i;
Token tok;
tok.kind = sk;
tok.text = std::string(1, ch);
tok.start = start;
tok.end = i;
tok.had_space_before = had_space;
tokens.push_back(std::move(tok));
}
Token eof;
eof.kind = TokenKind::Eof;
eof.start = input.size();
eof.end = input.size();
tokens.push_back(std::move(eof));
return tokens;
}
} // namespace htab
+58
View File
@@ -0,0 +1,58 @@
#pragma once
#include "engine/address.hpp"
#include "engine/value.hpp"
#include <cstddef>
#include <string>
#include <string_view>
#include <vector>
namespace htab {
enum class TokenKind {
Number,
String,
Bool,
Error,
CellRef,
Ident,
Colon,
Comma,
Plus,
Minus,
Star,
Slash,
Caret,
Percent,
Amp,
Eq,
Neq,
Lt,
Gt,
Le,
Ge,
LParen,
RParen,
Eof,
Invalid,
};
struct Token {
TokenKind kind = TokenKind::Invalid;
std::string text;
size_t start = 0;
size_t end = 0;
bool had_space_before = false;
double num_val = 0.0;
bool bool_val = false;
ErrorCode err_val = ErrorCode::Value;
CellRef ref_val;
};
class Lexer {
public:
static std::vector<Token> tokenize(std::string_view input, bool skip_leading_equals = true);
};
} // namespace htab
+227
View File
@@ -0,0 +1,227 @@
#include "engine/parser.hpp"
namespace htab {
namespace {
class PrattParser {
public:
explicit PrattParser(std::vector<Token> tokens) : tokens_(std::move(tokens)) {}
ParseResult parse() {
if (peek().kind == TokenKind::Eof) {
return {nullptr, false, "Empty formula"};
}
auto expr = parse_expr(0, false);
if (!expr) {
return {nullptr, false, error_.empty() ? "Syntax error" : error_};
}
if (peek().kind != TokenKind::Eof) {
return {nullptr, false, "Unexpected trailing token: " + peek().text};
}
return {std::move(expr), true, ""};
}
private:
const Token& peek() const { return tokens_[pos_]; }
const Token& advance() {
const Token& t = tokens_[pos_];
if (pos_ + 1 < tokens_.size()) ++pos_;
return t;
}
static bool is_ref_capable(const Expr* e) {
if (!e) return false;
switch (e->kind) {
case Expr::Kind::CellRef:
case Expr::Kind::Range:
case Expr::Kind::Call:
return true;
case Expr::Kind::Binary: {
auto* b = static_cast<const BinaryExpr*>(e);
return b->op == BinOp::Intersect || b->op == BinOp::Union;
}
default:
return false;
}
}
static bool infix_bp(TokenKind kind, int& lbp, int& rbp, BinOp& op) {
switch (kind) {
case TokenKind::Eq: lbp = 10; rbp = 11; op = BinOp::Eq; return true;
case TokenKind::Neq: lbp = 10; rbp = 11; op = BinOp::Neq; return true;
case TokenKind::Lt: lbp = 10; rbp = 11; op = BinOp::Lt; return true;
case TokenKind::Gt: lbp = 10; rbp = 11; op = BinOp::Gt; return true;
case TokenKind::Le: lbp = 10; rbp = 11; op = BinOp::Le; return true;
case TokenKind::Ge: lbp = 10; rbp = 11; op = BinOp::Ge; return true;
case TokenKind::Amp: lbp = 20; rbp = 21; op = BinOp::Concat; return true;
case TokenKind::Plus: lbp = 30; rbp = 31; op = BinOp::Add; return true;
case TokenKind::Minus: lbp = 30; rbp = 31; op = BinOp::Sub; return true;
case TokenKind::Star: lbp = 40; rbp = 41; op = BinOp::Mul; return true;
case TokenKind::Slash: lbp = 40; rbp = 41; op = BinOp::Div; return true;
case TokenKind::Caret: lbp = 50; rbp = 51; op = BinOp::Pow; return true;
default: return false;
}
}
std::shared_ptr<Expr> parse_expr(int min_bp, bool allow_union) {
auto lhs = parse_nud();
if (!lhs) return nullptr;
while (true) {
const Token& t = peek();
if (t.kind == TokenKind::Invalid) {
error_ = "Invalid token: " + t.text;
return nullptr;
}
// Range operator ':' (precedence 90, left-assoc)
if (t.kind == TokenKind::Colon) {
if (90 < min_bp) break;
advance();
auto rhs = parse_expr(91, allow_union);
if (!rhs) return nullptr;
lhs = std::make_shared<RangeExpr>(std::move(lhs), std::move(rhs));
continue;
}
// Implicit intersection operator ' ' (precedence 85, left-assoc)
if (t.had_space_before && is_ref_capable(lhs.get()) &&
(t.kind == TokenKind::CellRef || t.kind == TokenKind::LParen ||
t.kind == TokenKind::Ident)) {
if (85 < min_bp) break;
auto rhs = parse_expr(86, allow_union);
if (!rhs) return nullptr;
lhs = std::make_shared<BinaryExpr>(BinOp::Intersect, std::move(lhs), std::move(rhs));
continue;
}
// Union operator ',' inside parenthesized expressions (precedence 80, left-assoc)
if (allow_union && t.kind == TokenKind::Comma) {
if (80 < min_bp) break;
advance();
auto rhs = parse_expr(81, allow_union);
if (!rhs) return nullptr;
lhs = std::make_shared<BinaryExpr>(BinOp::Union, std::move(lhs), std::move(rhs));
continue;
}
// Postfix '%' (precedence 60, below unary prefix 70 and above '^' 50)
if (t.kind == TokenKind::Percent) {
if (60 < min_bp) break;
advance();
lhs = std::make_shared<PercentExpr>(std::move(lhs));
continue;
}
int lbp = 0, rbp = 0;
BinOp op = BinOp::Add;
if (infix_bp(t.kind, lbp, rbp, op)) {
if (lbp < min_bp) break;
advance();
auto rhs = parse_expr(rbp, allow_union);
if (!rhs) return nullptr;
lhs = std::make_shared<BinaryExpr>(op, std::move(lhs), std::move(rhs));
continue;
}
break;
}
return lhs;
}
std::shared_ptr<Expr> parse_nud() {
const Token& t = peek();
switch (t.kind) {
case TokenKind::Number: {
double v = t.num_val;
advance();
return std::make_shared<LiteralExpr>(Value::make_number(v));
}
case TokenKind::String: {
std::string s = t.text;
advance();
return std::make_shared<LiteralExpr>(Value::make_string(std::move(s)));
}
case TokenKind::Bool: {
bool b = t.bool_val;
advance();
return std::make_shared<LiteralExpr>(Value::make_bool(b));
}
case TokenKind::Error: {
ErrorCode err = t.err_val;
advance();
return std::make_shared<LiteralExpr>(Value::make_error(err));
}
case TokenKind::CellRef: {
CellRef ref = t.ref_val;
advance();
return std::make_shared<CellRefExpr>(std::move(ref));
}
case TokenKind::Ident: {
std::string name = t.text;
advance();
if (peek().kind == TokenKind::LParen) {
advance(); // consume '('
std::vector<std::shared_ptr<Expr>> args;
if (peek().kind != TokenKind::RParen) {
while (true) {
auto arg = parse_expr(0, false);
if (!arg) return nullptr;
args.push_back(std::move(arg));
if (peek().kind == TokenKind::Comma) {
advance();
continue;
}
break;
}
}
if (peek().kind != TokenKind::RParen) {
error_ = "Expected ')' in call to " + name;
return nullptr;
}
advance();
return std::make_shared<CallExpr>(std::move(name), std::move(args));
}
return std::make_shared<UnknownNameExpr>(std::move(name));
}
case TokenKind::Plus:
case TokenKind::Minus: {
char op = (t.kind == TokenKind::Plus) ? '+' : '-';
advance();
auto rhs = parse_expr(70, false);
if (!rhs) return nullptr;
return std::make_shared<UnaryExpr>(op, std::move(rhs));
}
case TokenKind::LParen: {
advance();
auto inner = parse_expr(0, true);
if (!inner) return nullptr;
if (peek().kind != TokenKind::RParen) {
error_ = "Expected ')'";
return nullptr;
}
advance();
return inner;
}
default:
error_ = "Unexpected token: " + t.text;
return nullptr;
}
}
std::vector<Token> tokens_;
size_t pos_ = 0;
std::string error_;
};
} // namespace
ParseResult Parser::parse_formula(std::string_view formula) {
auto tokens = Lexer::tokenize(formula, true);
PrattParser p(std::move(tokens));
return p.parse();
}
} // namespace htab
+107
View File
@@ -0,0 +1,107 @@
#pragma once
#include "engine/address.hpp"
#include "engine/lexer.hpp"
#include "engine/value.hpp"
#include <memory>
#include <string>
#include <vector>
namespace htab {
enum class BinOp {
Add,
Sub,
Mul,
Div,
Pow,
Concat,
Eq,
Neq,
Lt,
Gt,
Le,
Ge,
Intersect,
Union,
};
struct Expr {
enum class Kind {
Literal,
CellRef,
Range,
Unary,
Percent,
Binary,
Call,
UnknownName,
};
Kind kind;
explicit Expr(Kind k) : kind(k) {}
virtual ~Expr() = default;
};
struct LiteralExpr : Expr {
Value value;
explicit LiteralExpr(Value v) : Expr(Kind::Literal), value(std::move(v)) {}
};
struct CellRefExpr : Expr {
CellRef ref;
explicit CellRefExpr(CellRef r) : Expr(Kind::CellRef), ref(std::move(r)) {}
};
struct RangeExpr : Expr {
std::shared_ptr<Expr> lhs;
std::shared_ptr<Expr> rhs;
RangeExpr(std::shared_ptr<Expr> l, std::shared_ptr<Expr> r)
: Expr(Kind::Range), lhs(std::move(l)), rhs(std::move(r)) {}
};
struct UnaryExpr : Expr {
char op = '+';
std::shared_ptr<Expr> operand;
UnaryExpr(char o, std::shared_ptr<Expr> e)
: Expr(Kind::Unary), op(o), operand(std::move(e)) {}
};
struct PercentExpr : Expr {
std::shared_ptr<Expr> operand;
explicit PercentExpr(std::shared_ptr<Expr> e) : Expr(Kind::Percent), operand(std::move(e)) {}
};
struct BinaryExpr : Expr {
BinOp op;
std::shared_ptr<Expr> lhs;
std::shared_ptr<Expr> rhs;
BinaryExpr(BinOp o, std::shared_ptr<Expr> l, std::shared_ptr<Expr> r)
: Expr(Kind::Binary), op(o), lhs(std::move(l)), rhs(std::move(r)) {}
};
struct CallExpr : Expr {
std::string name;
std::vector<std::shared_ptr<Expr>> args;
CallExpr(std::string n, std::vector<std::shared_ptr<Expr>> a)
: Expr(Kind::Call), name(std::move(n)), args(std::move(a)) {}
};
struct UnknownNameExpr : Expr {
std::string name;
explicit UnknownNameExpr(std::string n) : Expr(Kind::UnknownName), name(std::move(n)) {}
};
struct ParseResult {
std::shared_ptr<Expr> ast;
bool ok = false;
std::string error;
};
class Parser {
public:
static ParseResult parse_formula(std::string_view formula);
};
} // namespace htab
+275
View File
@@ -0,0 +1,275 @@
#include "engine/value.hpp"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
namespace htab {
namespace {
bool is_ascii_space(char ch) {
return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n';
}
std::optional<double> parse_numeric_text(std::string_view sv) {
sv = trim_ascii(sv);
if (sv.empty()) {
return std::nullopt;
}
bool is_percent = false;
if (sv.back() == '%') {
is_percent = 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_digits = false;
while (i < sv.size() && std::isdigit(static_cast<unsigned char>(sv[i]))) {
exp_digits = true;
++i;
}
if (!exp_digits) {
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 (is_percent) {
val /= 100.0;
}
if (val == 0.0) {
val = 0.0;
}
return val;
}
Value unwrap_1x1(const Value& v) {
if (!v.is_array()) {
return v;
}
const auto& arr = v.as_array();
if (arr && arr->rows == 1 && arr->cols == 1 && !arr->data.empty()) {
return arr->at(0, 0);
}
return Value::make_error(ErrorCode::Value);
}
int compare_strings_ci(std::string_view a, std::string_view b) {
size_t n = std::min(a.size(), b.size());
for (size_t i = 0; i < n; ++i) {
unsigned char ca = static_cast<unsigned char>(std::tolower(static_cast<unsigned char>(a[i])));
unsigned char cb = static_cast<unsigned char>(std::tolower(static_cast<unsigned char>(b[i])));
if (ca < cb) return -1;
if (ca > cb) return 1;
}
if (a.size() < b.size()) return -1;
if (a.size() > b.size()) return 1;
return 0;
}
int type_rank(const Value& v) {
if (v.is_number()) return 0;
if (v.is_string()) return 1;
if (v.is_bool()) return 2;
return 3;
}
} // namespace
std::string_view error_to_string(ErrorCode err) {
switch (err) {
case ErrorCode::Div0: return "#DIV/0!";
case ErrorCode::Value: return "#VALUE!";
case ErrorCode::Name: return "#NAME?";
case ErrorCode::NA: return "#N/A";
case ErrorCode::Ref: return "#REF!";
case ErrorCode::Num: return "#NUM!";
case ErrorCode::Cycle: return "#CYCLE!";
case ErrorCode::Spill: return "#SPILL!";
}
return "#VALUE!";
}
std::optional<ErrorCode> parse_error_code(std::string_view text) {
text = trim_ascii(text);
if (iequals_ascii(text, "#DIV/0!")) return ErrorCode::Div0;
if (iequals_ascii(text, "#VALUE!")) return ErrorCode::Value;
if (iequals_ascii(text, "#NAME?")) return ErrorCode::Name;
if (iequals_ascii(text, "#N/A")) return ErrorCode::NA;
if (iequals_ascii(text, "#REF!")) return ErrorCode::Ref;
if (iequals_ascii(text, "#NUM!")) return ErrorCode::Num;
if (iequals_ascii(text, "#CYCLE!")) return ErrorCode::Cycle;
if (iequals_ascii(text, "#SPILL!")) return ErrorCode::Spill;
return std::nullopt;
}
Value Value::make_number(double d) {
return Value(d == 0.0 ? 0.0 : d);
}
Value Value::make_checked_number(double d) {
if (!std::isfinite(d)) {
return Value::make_error(ErrorCode::Num);
}
return Value(d == 0.0 ? 0.0 : d);
}
std::variant<double, ErrorCode> to_number(const Value& v) {
Value u = unwrap_1x1(v);
if (u.is_error()) return u.as_error();
if (u.is_empty()) return 0.0;
if (u.is_number()) return u.as_number();
if (u.is_bool()) return u.as_bool() ? 1.0 : 0.0;
if (u.is_string()) {
auto parsed = parse_numeric_text(u.as_string());
if (parsed) return *parsed;
return ErrorCode::Value;
}
return ErrorCode::Value;
}
std::variant<bool, ErrorCode> to_bool(const Value& v) {
Value u = unwrap_1x1(v);
if (u.is_error()) return u.as_error();
if (u.is_empty()) return false;
if (u.is_bool()) return u.as_bool();
if (u.is_number()) return u.as_number() != 0.0;
if (u.is_string()) {
auto t = trim_ascii(u.as_string());
if (iequals_ascii(t, "TRUE")) return true;
if (iequals_ascii(t, "FALSE")) return false;
return ErrorCode::Value;
}
return ErrorCode::Value;
}
std::variant<std::string, ErrorCode> to_string(const Value& v) {
Value u = unwrap_1x1(v);
if (u.is_error()) return u.as_error();
if (u.is_empty()) return std::string{};
if (u.is_string()) return u.as_string();
if (u.is_bool()) return u.as_bool() ? std::string("TRUE") : std::string("FALSE");
if (u.is_number()) {
double d = u.as_number();
if (d == 0.0) d = 0.0;
char buf[64];
std::snprintf(buf, sizeof(buf), "%.15g", d);
return std::string(buf);
}
return ErrorCode::Value;
}
std::variant<int, ErrorCode> compare_values(const Value& a_in, const Value& b_in) {
Value a = unwrap_1x1(a_in);
if (a.is_error()) return a.as_error();
Value b = unwrap_1x1(b_in);
if (b.is_error()) return b.as_error();
if (a.is_empty() && b.is_empty()) {
return 0;
}
if (a.is_empty()) {
if (b.is_number()) a = Value::make_number(0.0);
else if (b.is_string()) a = Value::make_string("");
else if (b.is_bool()) a = Value::make_bool(false);
} else if (b.is_empty()) {
if (a.is_number()) b = Value::make_number(0.0);
else if (a.is_string()) b = Value::make_string("");
else if (a.is_bool()) b = Value::make_bool(false);
}
int ra = type_rank(a);
int rb = type_rank(b);
if (ra != rb) {
return ra < rb ? -1 : 1;
}
if (a.is_number()) {
double da = a.as_number();
double db = b.as_number();
if (da < db) return -1;
if (da > db) return 1;
return 0;
}
if (a.is_string()) {
return compare_strings_ci(a.as_string(), b.as_string());
}
if (a.is_bool()) {
bool ba = a.as_bool();
bool bb = b.as_bool();
if (ba == bb) return 0;
return ba ? 1 : -1;
}
return 0;
}
bool iequals_ascii(std::string_view a, std::string_view b) {
if (a.size() != b.size()) return false;
for (size_t i = 0; i < a.size(); ++i) {
if (std::tolower(static_cast<unsigned char>(a[i])) !=
std::tolower(static_cast<unsigned char>(b[i]))) {
return false;
}
}
return true;
}
std::string to_upper_ascii(std::string_view s) {
std::string out(s);
for (char& ch : out) {
ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
}
return out;
}
std::string to_lower_ascii(std::string_view s) {
std::string out(s);
for (char& ch : out) {
ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch)));
}
return out;
}
std::string_view trim_ascii(std::string_view s) {
while (!s.empty() && is_ascii_space(s.front())) s.remove_prefix(1);
while (!s.empty() && is_ascii_space(s.back())) s.remove_suffix(1);
return s;
}
} // namespace htab
+97
View File
@@ -0,0 +1,97 @@
#pragma once
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <variant>
#include <vector>
namespace htab {
enum class ErrorCode {
Div0,
Value,
Name,
NA,
Ref,
Num,
Cycle,
Spill,
};
std::string_view error_to_string(ErrorCode err);
std::optional<ErrorCode> parse_error_code(std::string_view text);
struct Empty {
bool operator==(const Empty&) const = default;
};
struct Array2D;
struct Value {
using Variant = std::variant<Empty, double, bool, std::string, ErrorCode,
std::shared_ptr<Array2D>>;
Variant data;
Value() : data(Empty{}) {}
explicit Value(Empty e) : data(e) {}
explicit Value(double d) : data(d == 0.0 ? 0.0 : d) {}
explicit Value(bool b) : data(b) {}
explicit Value(std::string s) : data(std::move(s)) {}
explicit Value(ErrorCode err) : data(err) {}
explicit Value(std::shared_ptr<Array2D> arr) : data(std::move(arr)) {}
static Value make_empty() { return Value(Empty{}); }
static Value make_number(double d);
static Value make_checked_number(double d);
static Value make_bool(bool b) { return Value(b); }
static Value make_string(std::string s) { return Value(std::move(s)); }
static Value make_error(ErrorCode err) { return Value(err); }
static Value make_array(std::shared_ptr<Array2D> arr) { return Value(std::move(arr)); }
bool is_empty() const { return std::holds_alternative<Empty>(data); }
bool is_number() const { return std::holds_alternative<double>(data); }
bool is_bool() const { return std::holds_alternative<bool>(data); }
bool is_string() const { return std::holds_alternative<std::string>(data); }
bool is_error() const { return std::holds_alternative<ErrorCode>(data); }
bool is_array() const { return std::holds_alternative<std::shared_ptr<Array2D>>(data); }
double as_number() const { return std::get<double>(data); }
bool as_bool() const { return std::get<bool>(data); }
const std::string& as_string() const { return std::get<std::string>(data); }
ErrorCode as_error() const { return std::get<ErrorCode>(data); }
const std::shared_ptr<Array2D>& as_array() const {
return std::get<std::shared_ptr<Array2D>>(data);
}
};
struct Array2D {
int rows = 0;
int cols = 0;
std::vector<Value> data;
Array2D() = default;
Array2D(int r, int c, Value fill = Value::make_empty())
: rows(r), cols(c), data(static_cast<size_t>(r) * static_cast<size_t>(c), std::move(fill)) {}
const Value& at(int r, int c) const {
return data[static_cast<size_t>(r) * static_cast<size_t>(cols) + static_cast<size_t>(c)];
}
Value& at(int r, int c) {
return data[static_cast<size_t>(r) * static_cast<size_t>(cols) + static_cast<size_t>(c)];
}
};
std::variant<double, ErrorCode> to_number(const Value& v);
std::variant<bool, ErrorCode> to_bool(const Value& v);
std::variant<std::string, ErrorCode> to_string(const Value& v);
std::variant<int, ErrorCode> compare_values(const Value& a, const Value& b);
bool iequals_ascii(std::string_view a, std::string_view b);
std::string to_upper_ascii(std::string_view s);
std::string to_lower_ascii(std::string_view s);
std::string_view trim_ascii(std::string_view s);
} // namespace htab
+887
View File
@@ -0,0 +1,887 @@
#include "engine/workbook.hpp"
#include "engine/dag.hpp"
#include "engine/evaluator.hpp"
#include "engine/format.hpp"
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdlib>
namespace htab {
namespace {
constexpr size_t kMaxUndoDepth = 200;
bool try_parse_plain_number(std::string_view raw, double& val_out, bool& is_pct_out) {
std::string_view sv = trim_ascii(raw);
if (sv.empty()) return false;
is_pct_out = false;
if (sv.back() == '%') {
is_pct_out = true;
sv.remove_suffix(1);
sv = trim_ascii(sv);
if (sv.empty()) return false;
}
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 false;
if (i < sv.size() && (sv[i] == 'e' || sv[i] == 'E')) {
++i;
if (i < sv.size() && (sv[i] == '+' || sv[i] == '-')) ++i;
bool exp_digits = false;
while (i < sv.size() && std::isdigit(static_cast<unsigned char>(sv[i]))) {
exp_digits = true;
++i;
}
if (!exp_digits) return false;
}
if (i != sv.size()) return false;
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 false;
if (is_pct_out) val /= 100.0;
val_out = (val == 0.0) ? 0.0 : val;
return true;
}
struct CellDelta {
int row = 0;
int col = 0;
std::string old_raw;
std::string old_fmt;
std::string new_raw;
std::string new_fmt;
};
} // namespace
class EditCellsCmd : public Workbook::Command {
public:
EditCellsCmd(int sheet_idx, std::vector<CellDelta> deltas)
: sheet_idx_(sheet_idx), deltas_(std::move(deltas)) {}
void undo(Workbook& wb) override {
std::vector<GlobalAddr> seeds;
seeds.reserve(deltas_.size());
for (const auto& d : deltas_) {
wb.set_cell_raw_no_recalc(sheet_idx_, d.row, d.col, d.old_raw, d.old_fmt, seeds);
}
wb.dag_->recalculate_from(wb, std::move(seeds));
}
void redo(Workbook& wb) override {
std::vector<GlobalAddr> seeds;
seeds.reserve(deltas_.size());
for (const auto& d : deltas_) {
wb.set_cell_raw_no_recalc(sheet_idx_, d.row, d.col, d.new_raw, d.new_fmt, seeds);
}
wb.dag_->recalculate_from(wb, std::move(seeds));
}
private:
int sheet_idx_ = 0;
std::vector<CellDelta> deltas_;
};
class SnapshotCmd : public Workbook::Command {
public:
SnapshotCmd(std::vector<Sheet> before_sheets,
int before_active,
std::vector<Sheet> after_sheets,
int after_active)
: before_sheets_(std::move(before_sheets)),
before_active_(before_active),
after_sheets_(std::move(after_sheets)),
after_active_(after_active) {}
void undo(Workbook& wb) override {
wb.sheets_ = before_sheets_;
wb.active_sheet_ = std::clamp(before_active_, 0, wb.sheet_count() - 1);
wb.dag_->rebuild(wb);
}
void redo(Workbook& wb) override {
wb.sheets_ = after_sheets_;
wb.active_sheet_ = std::clamp(after_active_, 0, wb.sheet_count() - 1);
wb.dag_->rebuild(wb);
}
private:
std::vector<Sheet> before_sheets_;
int before_active_ = 0;
std::vector<Sheet> after_sheets_;
int after_active_ = 0;
};
class DimEditCmd : public Workbook::Command {
public:
DimEditCmd(int sheet_idx, bool is_col, int index, int old_val, int new_val)
: sheet_idx_(sheet_idx),
is_col_(is_col),
index_(index),
old_val_(old_val),
new_val_(new_val) {}
void undo(Workbook& wb) override { apply(wb, old_val_); }
void redo(Workbook& wb) override { apply(wb, new_val_); }
private:
void apply(Workbook& wb, int val) {
if (sheet_idx_ < 0 || sheet_idx_ >= wb.sheet_count()) return;
auto& map = is_col_ ? wb.sheet_mut(sheet_idx_).col_widths
: wb.sheet_mut(sheet_idx_).row_heights;
if (val <= 0) map.erase(index_);
else map[index_] = val;
}
int sheet_idx_ = 0;
bool is_col_ = false;
int index_ = 0;
int old_val_ = 0;
int new_val_ = 0;
};
Workbook::Workbook() : dag_(std::make_unique<DependencyGraph>()) {
Sheet s;
s.name = "Sheet1";
sheets_.push_back(std::move(s));
}
Workbook::~Workbook() = default;
Workbook::Workbook(Workbook&&) noexcept = default;
Workbook& Workbook::operator=(Workbook&&) noexcept = default;
void Workbook::set_active_sheet(int idx) {
if (idx >= 0 && idx < sheet_count()) {
active_sheet_ = idx;
}
}
int Workbook::find_sheet(std::string_view name) const {
for (size_t i = 0; i < sheets_.size(); ++i) {
if (iequals_ascii(sheets_[i].name, name)) {
return static_cast<int>(i);
}
}
return -1;
}
void Workbook::push_command(std::unique_ptr<Command> cmd) {
redo_stack_.clear();
undo_stack_.push_back(std::move(cmd));
if (undo_stack_.size() > kMaxUndoDepth) {
undo_stack_.erase(undo_stack_.begin());
}
}
void Workbook::clear_history() {
undo_stack_.clear();
redo_stack_.clear();
}
bool Workbook::undo() {
if (undo_stack_.empty()) return false;
auto cmd = std::move(undo_stack_.back());
undo_stack_.pop_back();
cmd->undo(*this);
redo_stack_.push_back(std::move(cmd));
return true;
}
bool Workbook::redo() {
if (redo_stack_.empty()) return false;
auto cmd = std::move(redo_stack_.back());
redo_stack_.pop_back();
cmd->redo(*this);
undo_stack_.push_back(std::move(cmd));
return true;
}
int Workbook::add_sheet(std::string name) {
auto before_sheets = sheets_;
int before_active = active_sheet_;
if (name.empty()) {
int n = sheet_count() + 1;
while (true) {
std::string cand = "Sheet" + std::to_string(n);
if (find_sheet(cand) < 0) {
name = std::move(cand);
break;
}
++n;
}
} else if (find_sheet(name) >= 0) {
return -1;
}
Sheet s;
s.name = std::move(name);
sheets_.push_back(std::move(s));
int idx = sheet_count() - 1;
dag_->rebuild(*this);
push_command(std::make_unique<SnapshotCmd>(
std::move(before_sheets), before_active, sheets_, active_sheet_));
return idx;
}
bool Workbook::rename_sheet(int sheet_idx, const std::string& new_name) {
if (sheet_idx < 0 || sheet_idx >= sheet_count()) return false;
std::string trimmed(trim_ascii(new_name));
if (trimmed.empty()) return false;
int existing = find_sheet(trimmed);
if (existing >= 0 && existing != sheet_idx) return false;
if (sheets_[static_cast<size_t>(sheet_idx)].name == trimmed) return true;
auto before_sheets = sheets_;
int before_active = active_sheet_;
std::string old_name = sheets_[static_cast<size_t>(sheet_idx)].name;
sheets_[static_cast<size_t>(sheet_idx)].name = trimmed;
rewrite_all_formulas(old_name, StructuralOp::RenameSheet, 0, 0, trimmed);
dag_->rebuild(*this);
push_command(std::make_unique<SnapshotCmd>(
std::move(before_sheets), before_active, sheets_, active_sheet_));
return true;
}
bool Workbook::delete_sheet(int sheet_idx) {
if (sheet_count() <= 1 || sheet_idx < 0 || sheet_idx >= sheet_count()) return false;
auto before_sheets = sheets_;
int before_active = active_sheet_;
std::string deleted_name = sheets_[static_cast<size_t>(sheet_idx)].name;
sheets_.erase(sheets_.begin() + sheet_idx);
if (active_sheet_ >= sheet_count()) {
active_sheet_ = sheet_count() - 1;
} else if (active_sheet_ > sheet_idx) {
--active_sheet_;
}
rewrite_all_formulas(deleted_name, StructuralOp::DeleteSheet, 0, 0);
dag_->rebuild(*this);
push_command(std::make_unique<SnapshotCmd>(
std::move(before_sheets), before_active, sheets_, active_sheet_));
return true;
}
void Workbook::parse_cell_input(Cell& cell, const std::string& raw) {
cell.raw_input = raw;
cell.ast.reset();
cell.parse_error = false;
if (raw.empty()) {
cell.value = Value::make_empty();
return;
}
if (raw[0] == '=') {
auto res = Parser::parse_formula(raw);
if (res.ok) {
cell.ast = std::move(res.ast);
} else {
cell.parse_error = true;
cell.value = Value::make_error(ErrorCode::Value);
}
return;
}
if (raw[0] == '\'') {
cell.value = Value::make_string(raw.substr(1));
return;
}
auto trimmed = trim_ascii(raw);
if (iequals_ascii(trimmed, "TRUE")) {
cell.value = Value::make_bool(true);
return;
}
if (iequals_ascii(trimmed, "FALSE")) {
cell.value = Value::make_bool(false);
return;
}
if (auto err = parse_error_code(trimmed)) {
cell.value = Value::make_error(*err);
return;
}
double num = 0.0;
bool is_pct = false;
if (try_parse_plain_number(raw, num, is_pct)) {
cell.value = Value::make_number(num);
if (is_pct && cell.number_format.empty()) {
cell.number_format = "0.00%";
}
return;
}
cell.value = Value::make_string(raw);
}
void Workbook::set_cell_raw_no_recalc(int sheet_idx,
int row,
int col,
const std::string& raw,
const std::optional<std::string>& fmt_override,
std::vector<GlobalAddr>& dirty_seeds) {
if (sheet_idx < 0 || sheet_idx >= sheet_count() ||
row < 0 || row >= kMaxRows || col < 0 || col >= kMaxCols) {
return;
}
Sheet& s = sheets_[static_cast<size_t>(sheet_idx)];
CellKey key{row, col};
GlobalAddr addr{sheet_idx, row, col};
std::string target_fmt;
if (fmt_override.has_value()) {
target_fmt = *fmt_override;
} else {
auto it = s.cells.find(key);
if (it != s.cells.end()) target_fmt = it->second.number_format;
}
if (raw.empty() && target_fmt.empty()) {
s.cells.erase(key);
dag_->remove_cell(addr);
dirty_seeds.push_back(addr);
return;
}
Cell& cell = s.cells[key];
cell.number_format = std::move(target_fmt);
parse_cell_input(cell, raw);
if (cell.ast) {
dag_->update_cell_deps(*this, addr, cell.ast.get());
} else {
dag_->remove_cell(addr);
}
dirty_seeds.push_back(addr);
}
void Workbook::set_cell_input(int sheet_idx, int row, int col, const std::string& raw) {
apply_cell_edits(sheet_idx, {CellEdit{row, col, raw, std::nullopt}});
}
void Workbook::apply_cell_edits(int sheet_idx, const std::vector<CellEdit>& edits) {
if (sheet_idx < 0 || sheet_idx >= sheet_count() || edits.empty()) return;
std::vector<CellDelta> deltas;
deltas.reserve(edits.size());
std::vector<GlobalAddr> seeds;
seeds.reserve(edits.size());
for (const auto& ed : edits) {
if (ed.row < 0 || ed.row >= kMaxRows || ed.col < 0 || ed.col >= kMaxCols) continue;
const Cell* existing = get_cell(sheet_idx, ed.row, ed.col);
CellDelta delta;
delta.row = ed.row;
delta.col = ed.col;
delta.old_raw = existing ? existing->raw_input : "";
delta.old_fmt = existing ? existing->number_format : "";
delta.new_raw = ed.raw_input;
set_cell_raw_no_recalc(sheet_idx, ed.row, ed.col, ed.raw_input, ed.number_format, seeds);
const Cell* after = get_cell(sheet_idx, ed.row, ed.col);
delta.new_fmt = after ? after->number_format : "";
if (delta.old_raw != delta.new_raw || delta.old_fmt != delta.new_fmt) {
deltas.push_back(std::move(delta));
}
}
if (!seeds.empty()) {
dag_->recalculate_from(*this, std::move(seeds));
}
if (!deltas.empty()) {
push_command(std::make_unique<EditCellsCmd>(sheet_idx, std::move(deltas)));
}
}
void Workbook::set_cell_format(int sheet_idx, int row, int col, const std::string& fmt) {
apply_range_format(sheet_idx, CellRange{sheet_idx, row, col, row, col}, fmt);
}
void Workbook::apply_range_format(int sheet_idx, CellRange range, const std::string& fmt) {
if (sheet_idx < 0 || sheet_idx >= sheet_count()) return;
int r1 = std::max(0, std::min(range.r1, range.r2));
int r2 = std::min(kMaxRows - 1, std::max(range.r1, range.r2));
int c1 = std::max(0, std::min(range.c1, range.c2));
int c2 = std::min(kMaxCols - 1, std::max(range.c1, range.c2));
if (static_cast<int64_t>(r2 - r1 + 1) * (c2 - c1 + 1) > 10000) return;
std::vector<CellDelta> deltas;
for (int r = r1; r <= r2; ++r) {
for (int c = c1; c <= c2; ++c) {
const Cell* existing = get_cell(sheet_idx, r, c);
std::string raw = existing ? existing->raw_input : "";
std::string old_fmt = existing ? existing->number_format : "";
if (old_fmt == fmt) continue;
CellDelta d;
d.row = r;
d.col = c;
d.old_raw = raw;
d.old_fmt = old_fmt;
d.new_raw = raw;
d.new_fmt = fmt;
if (raw.empty() && fmt.empty()) {
sheets_[static_cast<size_t>(sheet_idx)].cells.erase(CellKey{r, c});
} else {
Cell& cell = sheets_[static_cast<size_t>(sheet_idx)].cells[CellKey{r, c}];
cell.number_format = fmt;
}
deltas.push_back(std::move(d));
}
}
if (!deltas.empty()) {
push_command(std::make_unique<EditCellsCmd>(sheet_idx, std::move(deltas)));
}
}
void Workbook::rewrite_all_formulas(const std::string& target_sheet,
StructuralOp op,
int index,
int count,
const std::string& new_name) {
for (size_t si = 0; si < sheets_.size(); ++si) {
Sheet& s = sheets_[si];
for (auto& [key, cell] : s.cells) {
if (!cell.raw_input.empty() && cell.raw_input[0] == '=') {
std::string updated = rewrite_formula_structural(
cell.raw_input, s.name, target_sheet, op, index, count, new_name);
if (updated != cell.raw_input) {
parse_cell_input(cell, updated);
}
}
}
}
}
void Workbook::insert_rows(int sheet_idx, int row, int count) {
if (sheet_idx < 0 || sheet_idx >= sheet_count() || row < 0 || count <= 0) return;
auto before_sheets = sheets_;
int before_active = active_sheet_;
Sheet& s = sheets_[static_cast<size_t>(sheet_idx)];
std::string target_name = s.name;
std::unordered_map<CellKey, Cell, CellKeyHash> moved;
moved.reserve(s.cells.size());
for (auto& [key, cell] : s.cells) {
int nr = (key.row >= row) ? (key.row + count) : key.row;
if (nr < kMaxRows) {
moved.emplace(CellKey{nr, key.col}, std::move(cell));
}
}
s.cells = std::move(moved);
std::unordered_map<int, int> moved_h;
for (const auto& [r, h] : s.row_heights) {
int nr = (r >= row) ? (r + count) : r;
if (nr < kMaxRows) moved_h[nr] = h;
}
s.row_heights = std::move(moved_h);
rewrite_all_formulas(target_name, StructuralOp::InsertRow, row, count);
dag_->rebuild(*this);
push_command(std::make_unique<SnapshotCmd>(
std::move(before_sheets), before_active, sheets_, active_sheet_));
}
void Workbook::delete_rows(int sheet_idx, int row, int count) {
if (sheet_idx < 0 || sheet_idx >= sheet_count() || row < 0 || count <= 0) return;
auto before_sheets = sheets_;
int before_active = active_sheet_;
Sheet& s = sheets_[static_cast<size_t>(sheet_idx)];
std::string target_name = s.name;
std::unordered_map<CellKey, Cell, CellKeyHash> moved;
moved.reserve(s.cells.size());
for (auto& [key, cell] : s.cells) {
if (key.row >= row && key.row < row + count) continue;
int nr = (key.row >= row + count) ? (key.row - count) : key.row;
moved.emplace(CellKey{nr, key.col}, std::move(cell));
}
s.cells = std::move(moved);
std::unordered_map<int, int> moved_h;
for (const auto& [r, h] : s.row_heights) {
if (r >= row && r < row + count) continue;
int nr = (r >= row + count) ? (r - count) : r;
moved_h[nr] = h;
}
s.row_heights = std::move(moved_h);
rewrite_all_formulas(target_name, StructuralOp::DeleteRow, row, count);
dag_->rebuild(*this);
push_command(std::make_unique<SnapshotCmd>(
std::move(before_sheets), before_active, sheets_, active_sheet_));
}
void Workbook::insert_cols(int sheet_idx, int col, int count) {
if (sheet_idx < 0 || sheet_idx >= sheet_count() || col < 0 || count <= 0) return;
auto before_sheets = sheets_;
int before_active = active_sheet_;
Sheet& s = sheets_[static_cast<size_t>(sheet_idx)];
std::string target_name = s.name;
std::unordered_map<CellKey, Cell, CellKeyHash> moved;
moved.reserve(s.cells.size());
for (auto& [key, cell] : s.cells) {
int nc = (key.col >= col) ? (key.col + count) : key.col;
if (nc < kMaxCols) {
moved.emplace(CellKey{key.row, nc}, std::move(cell));
}
}
s.cells = std::move(moved);
std::unordered_map<int, int> moved_w;
for (const auto& [c, w] : s.col_widths) {
int nc = (c >= col) ? (c + count) : c;
if (nc < kMaxCols) moved_w[nc] = w;
}
s.col_widths = std::move(moved_w);
rewrite_all_formulas(target_name, StructuralOp::InsertCol, col, count);
dag_->rebuild(*this);
push_command(std::make_unique<SnapshotCmd>(
std::move(before_sheets), before_active, sheets_, active_sheet_));
}
void Workbook::delete_cols(int sheet_idx, int col, int count) {
if (sheet_idx < 0 || sheet_idx >= sheet_count() || col < 0 || count <= 0) return;
auto before_sheets = sheets_;
int before_active = active_sheet_;
Sheet& s = sheets_[static_cast<size_t>(sheet_idx)];
std::string target_name = s.name;
std::unordered_map<CellKey, Cell, CellKeyHash> moved;
moved.reserve(s.cells.size());
for (auto& [key, cell] : s.cells) {
if (key.col >= col && key.col < col + count) continue;
int nc = (key.col >= col + count) ? (key.col - count) : key.col;
moved.emplace(CellKey{key.row, nc}, std::move(cell));
}
s.cells = std::move(moved);
std::unordered_map<int, int> moved_w;
for (const auto& [c, w] : s.col_widths) {
if (c >= col && c < col + count) continue;
int nc = (c >= col + count) ? (c - count) : c;
moved_w[nc] = w;
}
s.col_widths = std::move(moved_w);
rewrite_all_formulas(target_name, StructuralOp::DeleteCol, col, count);
dag_->rebuild(*this);
push_command(std::make_unique<SnapshotCmd>(
std::move(before_sheets), before_active, sheets_, active_sheet_));
}
void Workbook::set_col_width(int sheet_idx, int col, int width) {
if (sheet_idx < 0 || sheet_idx >= sheet_count() || col < 0 || col >= kMaxCols) return;
auto& cw = sheets_[static_cast<size_t>(sheet_idx)].col_widths;
int old_w = cw.count(col) ? cw[col] : 0;
if (old_w == width) return;
if (width <= 0) cw.erase(col);
else cw[col] = width;
push_command(std::make_unique<DimEditCmd>(sheet_idx, true, col, old_w, width));
}
int Workbook::get_col_width(int sheet_idx, int col, int default_width) const {
if (sheet_idx < 0 || sheet_idx >= sheet_count()) return default_width;
const auto& cw = sheets_[static_cast<size_t>(sheet_idx)].col_widths;
auto it = cw.find(col);
return (it != cw.end() && it->second > 0) ? it->second : default_width;
}
void Workbook::set_row_height(int sheet_idx, int row, int height) {
if (sheet_idx < 0 || sheet_idx >= sheet_count() || row < 0 || row >= kMaxRows) return;
auto& rh = sheets_[static_cast<size_t>(sheet_idx)].row_heights;
int old_h = rh.count(row) ? rh[row] : 0;
if (old_h == height) return;
if (height <= 0) rh.erase(row);
else rh[row] = height;
push_command(std::make_unique<DimEditCmd>(sheet_idx, false, row, old_h, height));
}
int Workbook::get_row_height(int sheet_idx, int row, int default_height) const {
if (sheet_idx < 0 || sheet_idx >= sheet_count()) return default_height;
const auto& rh = sheets_[static_cast<size_t>(sheet_idx)].row_heights;
auto it = rh.find(row);
return (it != rh.end() && it->second > 0) ? it->second : default_height;
}
const Cell* Workbook::get_cell(int sheet_idx, int row, int col) const {
if (sheet_idx < 0 || sheet_idx >= sheet_count()) return nullptr;
const Sheet& s = sheets_[static_cast<size_t>(sheet_idx)];
auto it = s.cells.find(CellKey{row, col});
if (it == s.cells.end()) return nullptr;
return &it->second;
}
Value Workbook::get_scalar_value(int sheet_idx, int row, int col) const {
const Cell* c = get_cell(sheet_idx, row, col);
if (c && !c->raw_input.empty()) {
if (c->value.is_array()) {
const auto& arr = c->value.as_array();
if (arr && !arr->data.empty()) return arr->at(0, 0);
return Value::make_empty();
}
return c->value;
}
return dag_->get_spill_value(*this, sheet_idx, row, col);
}
std::string Workbook::get_formatted_value(int sheet_idx, int row, int col) const {
const Cell* c = get_cell(sheet_idx, row, col);
Value v = get_scalar_value(sheet_idx, row, col);
std::string fmt = c ? c->number_format : std::string{};
return format_value(v, fmt);
}
bool Workbook::is_spilled_cell(int sheet_idx, int row, int col) const {
return dag_->is_spilled_cell(sheet_idx, row, col);
}
std::optional<CellRange> Workbook::get_spill_range(int sheet_idx, int row, int col) const {
return dag_->get_spill_range(sheet_idx, row, col);
}
ClipboardGrid Workbook::copy_range(int sheet_idx, CellRange range, bool is_cut) const {
ClipboardGrid grid;
grid.src_sheet = sheet_idx;
grid.src_range = CellRange{
sheet_idx,
std::min(range.r1, range.r2),
std::min(range.c1, range.c2),
std::max(range.r1, range.r2),
std::max(range.c1, range.c2),
};
grid.is_cut = is_cut;
for (int r = grid.src_range.r1; r <= grid.src_range.r2; ++r) {
for (int c = grid.src_range.c1; c <= grid.src_range.c2; ++c) {
const Cell* cell = get_cell(sheet_idx, r, c);
ClipboardCell cc;
cc.dr = r - grid.src_range.r1;
cc.dc = c - grid.src_range.c1;
if (cell && !cell->raw_input.empty()) {
cc.raw_input = cell->raw_input;
cc.number_format = cell->number_format;
} else {
Value sv = get_scalar_value(sheet_idx, r, c);
if (!sv.is_empty()) {
auto s = to_string(sv);
cc.raw_input = std::holds_alternative<std::string>(s) ? std::get<std::string>(s) : "";
}
}
cc.evaluated_value = get_scalar_value(sheet_idx, r, c);
grid.cells.push_back(std::move(cc));
}
}
return grid;
}
void Workbook::paste_range(int sheet_idx,
int dest_row,
int dest_col,
const ClipboardGrid& grid,
bool translate_refs) {
if (sheet_idx < 0 || sheet_idx >= sheet_count() || grid.cells.empty()) return;
int drow = dest_row - grid.src_range.r1;
int dcol = dest_col - grid.src_range.c1;
std::vector<CellEdit> edits;
if (grid.is_cut && grid.src_sheet == sheet_idx) {
for (int r = grid.src_range.r1; r <= grid.src_range.r2; ++r) {
for (int c = grid.src_range.c1; c <= grid.src_range.c2; ++c) {
edits.push_back(CellEdit{r, c, "", std::string{}});
}
}
}
for (const auto& cc : grid.cells) {
int tr = dest_row + cc.dr;
int tc = dest_col + cc.dc;
if (tr < 0 || tr >= kMaxRows || tc < 0 || tc >= kMaxCols) continue;
std::string raw = cc.raw_input;
if (translate_refs && !raw.empty() && raw[0] == '=' && !grid.is_cut) {
raw = translate_formula_refs(raw, drow, dcol);
}
edits.push_back(CellEdit{tr, tc, std::move(raw), cc.number_format});
}
apply_cell_edits(sheet_idx, edits);
}
void Workbook::autofill_range(int sheet_idx, CellRange src, CellRange dst) {
if (sheet_idx < 0 || sheet_idx >= sheet_count()) return;
CellRange s{sheet_idx, std::min(src.r1, src.r2), std::min(src.c1, src.c2),
std::max(src.r1, src.r2), std::max(src.c1, src.c2)};
CellRange d{sheet_idx, std::min(dst.r1, dst.r2), std::min(dst.c1, dst.c2),
std::max(dst.r1, dst.r2), std::max(dst.c1, dst.c2)};
bool vertical = (d.r1 < s.r1 || d.r2 > s.r2);
std::vector<CellEdit> edits;
if (vertical) {
int src_h = s.row_count();
for (int c = d.c1; c <= d.c2; ++c) {
int sc = s.c1 + ((c - s.c1) % s.col_count() + s.col_count()) % s.col_count();
// Check if source column slice is pure numeric trend with >= 2 cells
bool all_numeric = (src_h >= 2);
std::vector<double> nums;
for (int r = s.r1; r <= s.r2 && all_numeric; ++r) {
const Cell* cell = get_cell(sheet_idx, r, sc);
if (!cell || (!cell->raw_input.empty() && cell->raw_input[0] == '=')) {
all_numeric = false;
break;
}
if (!cell || !cell->value.is_number()) {
all_numeric = false;
break;
}
nums.push_back(cell->value.as_number());
}
double step = 0.0;
if (all_numeric && nums.size() >= 2) {
step = (nums.back() - nums.front()) / static_cast<double>(nums.size() - 1);
}
for (int r = d.r1; r <= d.r2; ++r) {
if (s.contains(sheet_idx, r, c)) continue;
if (all_numeric) {
double v = nums.front() + step * static_cast<double>(r - s.r1);
const Cell* template_c = get_cell(sheet_idx, s.r1, sc);
auto str = to_string(Value::make_number(v));
std::string raw = std::holds_alternative<std::string>(str) ? std::get<std::string>(str) : "";
edits.push_back(CellEdit{r, c, std::move(raw),
template_c ? template_c->number_format : std::string{}});
} else {
int off = ((r - s.r1) % src_h + src_h) % src_h;
int sr = s.r1 + off;
const Cell* src_c = get_cell(sheet_idx, sr, sc);
std::string raw = src_c ? src_c->raw_input : "";
std::string fmt = src_c ? src_c->number_format : "";
if (!raw.empty() && raw[0] == '=') {
raw = translate_formula_refs(raw, r - sr, c - sc);
}
edits.push_back(CellEdit{r, c, std::move(raw), std::move(fmt)});
}
}
}
} else {
int src_w = s.col_count();
for (int r = d.r1; r <= d.r2; ++r) {
int sr = s.r1 + ((r - s.r1) % s.row_count() + s.row_count()) % s.row_count();
bool all_numeric = (src_w >= 2);
std::vector<double> nums;
for (int c = s.c1; c <= s.c2 && all_numeric; ++c) {
const Cell* cell = get_cell(sheet_idx, sr, c);
if (!cell || (!cell->raw_input.empty() && cell->raw_input[0] == '=') ||
!cell->value.is_number()) {
all_numeric = false;
break;
}
nums.push_back(cell->value.as_number());
}
double step = 0.0;
if (all_numeric && nums.size() >= 2) {
step = (nums.back() - nums.front()) / static_cast<double>(nums.size() - 1);
}
for (int c = d.c1; c <= d.c2; ++c) {
if (s.contains(sheet_idx, r, c)) continue;
if (all_numeric) {
double v = nums.front() + step * static_cast<double>(c - s.c1);
const Cell* template_c = get_cell(sheet_idx, sr, s.c1);
auto str = to_string(Value::make_number(v));
std::string raw = std::holds_alternative<std::string>(str) ? std::get<std::string>(str) : "";
edits.push_back(CellEdit{r, c, std::move(raw),
template_c ? template_c->number_format : std::string{}});
} else {
int off = ((c - s.c1) % src_w + src_w) % src_w;
int sc = s.c1 + off;
const Cell* src_c = get_cell(sheet_idx, sr, sc);
std::string raw = src_c ? src_c->raw_input : "";
std::string fmt = src_c ? src_c->number_format : "";
if (!raw.empty() && raw[0] == '=') {
raw = translate_formula_refs(raw, r - sr, c - sc);
}
edits.push_back(CellEdit{r, c, std::move(raw), std::move(fmt)});
}
}
}
}
apply_cell_edits(sheet_idx, edits);
}
void Workbook::replace_all_sheets(std::vector<Sheet> new_sheets, int active_sheet) {
if (new_sheets.empty()) {
Sheet s;
s.name = "Sheet1";
new_sheets.push_back(std::move(s));
}
sheets_ = std::move(new_sheets);
for (auto& s : sheets_) {
for (auto& [key, cell] : s.cells) {
parse_cell_input(cell, cell.raw_input);
}
}
active_sheet_ = std::clamp(active_sheet, 0, sheet_count() - 1);
clear_history();
recalculate_all();
}
void Workbook::replace_sheet_cells(int sheet_idx,
std::unordered_map<CellKey, Cell, CellKeyHash> new_cells) {
if (sheet_idx < 0 || sheet_idx >= sheet_count()) return;
Sheet& s = sheets_[static_cast<size_t>(sheet_idx)];
s.cells = std::move(new_cells);
for (auto& [key, cell] : s.cells) {
parse_cell_input(cell, cell.raw_input);
}
clear_history();
recalculate_all();
}
std::optional<CellRange> Workbook::get_used_bounds(int sheet_idx) const {
if (sheet_idx < 0 || sheet_idx >= sheet_count()) return std::nullopt;
const Sheet& s = sheets_[static_cast<size_t>(sheet_idx)];
bool any = false;
int max_r = 0;
int max_c = 0;
for (const auto& [key, cell] : s.cells) {
if (cell.raw_input.empty() && cell.value.is_empty()) continue;
any = true;
max_r = std::max(max_r, key.row);
max_c = std::max(max_c, key.col);
}
for (const auto& [origin, sr] : dag_->spill_ranges()) {
if (origin.sheet == sheet_idx) {
any = true;
max_r = std::max(max_r, sr.r2);
max_c = std::max(max_c, sr.c2);
}
}
if (!any) return std::nullopt;
return CellRange{sheet_idx, 0, 0, max_r, max_c};
}
void Workbook::recalculate_all() {
dag_->rebuild(*this);
}
} // namespace htab
+150
View File
@@ -0,0 +1,150 @@
#pragma once
#include "engine/address.hpp"
#include "engine/parser.hpp"
#include "engine/value.hpp"
#include <memory>
#include <optional>
#include <string>
#include <unordered_map>
#include <vector>
namespace htab {
class DependencyGraph;
struct Cell {
std::string raw_input;
std::string number_format;
Value value;
std::shared_ptr<Expr> ast;
bool parse_error = false;
};
struct Sheet {
std::string name;
std::unordered_map<CellKey, Cell, CellKeyHash> cells;
std::unordered_map<int, int> col_widths;
std::unordered_map<int, int> row_heights;
};
struct CellEdit {
int row = 0;
int col = 0;
std::string raw_input;
std::optional<std::string> number_format;
};
struct ClipboardCell {
int dr = 0;
int dc = 0;
std::string raw_input;
std::string number_format;
Value evaluated_value;
};
struct ClipboardGrid {
int src_sheet = 0;
CellRange src_range;
std::vector<ClipboardCell> cells;
bool is_cut = false;
};
class Workbook {
public:
struct Command {
virtual ~Command() = default;
virtual void undo(Workbook& wb) = 0;
virtual void redo(Workbook& wb) = 0;
};
Workbook();
~Workbook();
Workbook(Workbook&&) noexcept;
Workbook& operator=(Workbook&&) noexcept;
Workbook(const Workbook&) = delete;
Workbook& operator=(const Workbook&) = delete;
int sheet_count() const { return static_cast<int>(sheets_.size()); }
int active_sheet() const { return active_sheet_; }
void set_active_sheet(int idx);
const Sheet& sheet(int idx) const { return sheets_[static_cast<size_t>(idx)]; }
Sheet& sheet_mut(int idx) { return sheets_[static_cast<size_t>(idx)]; }
int find_sheet(std::string_view name) const;
int add_sheet(std::string name = "");
bool rename_sheet(int sheet_idx, const std::string& new_name);
bool delete_sheet(int sheet_idx);
void set_cell_input(int sheet_idx, int row, int col, const std::string& raw);
void apply_cell_edits(int sheet_idx, const std::vector<CellEdit>& edits);
void set_cell_format(int sheet_idx, int row, int col, const std::string& fmt);
void apply_range_format(int sheet_idx, CellRange range, const std::string& fmt);
void insert_rows(int sheet_idx, int row, int count = 1);
void delete_rows(int sheet_idx, int row, int count = 1);
void insert_cols(int sheet_idx, int col, int count = 1);
void delete_cols(int sheet_idx, int col, int count = 1);
void set_col_width(int sheet_idx, int col, int width);
int get_col_width(int sheet_idx, int col, int default_width) const;
void set_row_height(int sheet_idx, int row, int height);
int get_row_height(int sheet_idx, int row, int default_height) const;
bool can_undo() const { return !undo_stack_.empty(); }
bool can_redo() const { return !redo_stack_.empty(); }
bool undo();
bool redo();
void clear_history();
const Cell* get_cell(int sheet_idx, int row, int col) const;
Value get_scalar_value(int sheet_idx, int row, int col) const;
std::string get_formatted_value(int sheet_idx, int row, int col) const;
bool is_spilled_cell(int sheet_idx, int row, int col) const;
std::optional<CellRange> get_spill_range(int sheet_idx, int row, int col) const;
ClipboardGrid copy_range(int sheet_idx, CellRange range, bool is_cut = false) const;
void paste_range(int sheet_idx,
int dest_row,
int dest_col,
const ClipboardGrid& grid,
bool translate_refs = true);
void autofill_range(int sheet_idx, CellRange src, CellRange dst);
void replace_all_sheets(std::vector<Sheet> new_sheets, int active_sheet);
void replace_sheet_cells(int sheet_idx,
std::unordered_map<CellKey, Cell, CellKeyHash> new_cells);
std::optional<CellRange> get_used_bounds(int sheet_idx) const;
void recalculate_all();
const DependencyGraph& dag() const { return *dag_; }
private:
friend class EditCellsCmd;
friend class SnapshotCmd;
void parse_cell_input(Cell& cell, const std::string& raw);
void set_cell_raw_no_recalc(int sheet_idx,
int row,
int col,
const std::string& raw,
const std::optional<std::string>& fmt_override,
std::vector<GlobalAddr>& dirty_seeds);
void push_command(std::unique_ptr<Command> cmd);
void rewrite_all_formulas(const std::string& target_sheet,
StructuralOp op,
int index,
int count,
const std::string& new_name = "");
std::vector<Sheet> sheets_;
int active_sheet_ = 0;
std::unique_ptr<DependencyGraph> dag_;
std::vector<std::unique_ptr<Command>> undo_stack_;
std::vector<std::unique_ptr<Command>> redo_stack_;
};
} // namespace htab