Repository navigation
Expand file tree
/
Copy pathformula.cpp
More file actions
106 lines (91 loc) · 3.16 KB
/
Copy pathformula.cpp
File metadata and controls
106 lines (91 loc) · 3.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include "formula.h"
#include "FormulaAST.h"
#include <algorithm>
#include <cassert>
#include <cctype>
#include <sstream>
using namespace std::literals;
FormulaError::FormulaError(Category category) : category_(category) {}
FormulaError::Category FormulaError::GetCategory() const { return category_; }
bool FormulaError::operator==(FormulaError rhs) const { return category_ == rhs.category_; }
std::string_view FormulaError::ToString() const {
switch (category_) {
case Category::Ref:
return "#REF!";
case Category::Value:
return "#VALUE!";
case Category::Div0:
return "#DIV/0!";
}
return "";
}
std::ostream& operator<<(std::ostream& output, FormulaError fe) {
return output << fe.ToString();
}
namespace {
class Formula : public FormulaInterface {
public:
explicit Formula(std::string expression) try : ast_(ParseFormulaAST(expression)) {
}
catch (const std::exception& e) {
std::throw_with_nested(FormulaException(e.what()));
}
Value Evaluate(const SheetInterface& sheet) const override {
const SheetArgs args = [&sheet](const Position p) -> double {
if (!p.IsValid()) {
throw FormulaError(FormulaError::Category::Ref);
}
const auto* cell = sheet.GetCell(p);
if (!cell) {
return 0;
}
if (std::holds_alternative<double>(cell->GetValue())) {
return std::get<double>(cell->GetValue());
}
if (std::holds_alternative<std::string>(cell->GetValue())) {
auto value = std::get<std::string>(cell->GetValue());
double result = 0;
if (!value.empty()) {
std::istringstream in(value);
if (!(in >> result) || !in.eof()) {
throw FormulaError(FormulaError::Category::Value);
}
}
return result;
}
throw FormulaError(std::get<FormulaError>(cell->GetValue()));
};
try {
return ast_.Execute(args);
}
catch (FormulaError& e) {
return e;
}
}
std::vector<Position> GetReferencedCells() const override {
std::vector<Position> cells;
for (auto cell : ast_.GetCells()) {
if (cell.IsValid()) {
cells.push_back(cell);
}
}
cells.resize(std::unique(cells.begin(), cells.end()) - cells.begin());
return cells;
}
std::string GetExpression() const override {
std::ostringstream result;
ast_.PrintFormula(result);
return result.str();
}
private:
const FormulaAST ast_;
};
} // namespace
std::unique_ptr<FormulaInterface> ParseFormula(std::string expression) {
try {
return std::make_unique<Formula>(std::move(expression));
}
catch (...) {
throw FormulaException("");
}
}