Files
htab/engine/address.cpp
T

386 lines
12 KiB
C++

#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