11#ifndef OPENXLSX_XLFORMULAENGINE_HPP
12#define OPENXLSX_XLFORMULAENGINE_HPP
16# pragma warning(disable : 4251)
17# pragma warning(disable : 4275)
30#include <unordered_map>
37#include "OpenXLSX-Exports.hpp"
184 void reportError(std::string message, std::size_t offset);
186 [[nodiscard]]
const std::vector<XLFormulaDiagnostic>& diagnostics()
const;
187 [[nodiscard]]
bool hasErrors()
const;
189 [[nodiscard]] std::string getFullReport()
const;
192 std::string m_formula;
193 std::vector<XLFormulaDiagnostic> m_diagnostics;
219 gsl::span<const XLToken> tokens;
222 bool panicMode{
false};
223 std::size_t depth{0};
224 static constexpr std::size_t kMaxDepth{256};
226 [[nodiscard]]
const XLToken& current()
const;
227 [[nodiscard]]
const XLToken& peek(std::size_t offset = 1)
const;
231 void reportError(std::string message, std::size_t offset);
234 struct ParseDepthGuard
238 explicit ParseDepthGuard(ParseContext& c) : ctx(c)
241 if (ctx.depth > ParseContext::kMaxDepth) {
243 ctx.reportError(
"Formula exceeds maximum nesting depth (" + std::to_string(ParseContext::kMaxDepth) +
")",
249 if (ctx.depth > 0) --ctx.depth;
251 [[nodiscard]]
bool isValid()
const noexcept {
return ok; }
254 static std::unique_ptr<XLASTNode> parseExpr(ParseContext& ctx,
int minPrec = 0);
255 static std::unique_ptr<XLASTNode> parseUnary(ParseContext& ctx);
256 static std::unique_ptr<XLASTNode> parsePrimary(ParseContext& ctx);
257 static std::unique_ptr<XLASTNode> parseFuncCall(std::string name, ParseContext& ctx);
284 using XLNameResolver = std::function<std::optional<std::string>(std::string_view name)>;
313 m_resolver = &resolver;
319 m_nameResolver = std::move(nameResolver);
331 m_hasCurrentCell = (row > 0 && col > 0);
337 m_currentSheet = std::move(sheetName);
341 [[nodiscard]]
bool hasResolver()
const {
return m_resolver !=
nullptr &&
static_cast<bool>(*m_resolver); }
348 return (*m_resolver)(ref);
351 [[nodiscard]] std::optional<std::string>
resolveName(std::string_view name)
const
353 if (!m_nameResolver)
return std::nullopt;
354 return m_nameResolver(name);
358 [[nodiscard]] uint32_t
currentRow() const noexcept {
return m_currentRow; }
359 [[nodiscard]] uint16_t
currentCol() const noexcept {
return m_currentCol; }
360 [[nodiscard]]
const std::string&
currentSheet() const noexcept {
return m_currentSheet; }
375 if (m_callDepth > 0) --m_callDepth;
378 [[nodiscard]]
int callDepth() const noexcept {
return m_callDepth; }
395 if (m_nodeEvalDepth > 0) --m_nodeEvalDepth;
398 [[nodiscard]]
int nodeEvalDepth() const noexcept {
return m_nodeEvalDepth; }
411 constexpr explicit operator bool() const noexcept {
return value != 0; }
434 uint32_t m_currentRow{0};
435 uint16_t m_currentCol{0};
436 bool m_hasCurrentCell{
false};
437 std::string m_currentSheet;
439 int m_nodeEvalDepth{0};
440 std::array<PackedCellKey, kInlineCellStackCapacity> m_evaluatingCellsInline{};
441 size_t m_evaluatingCellsInlineCount{0};
442 std::vector<PackedCellKey> m_evaluatingCellsHeap;
454 if (m_ok && m_session) m_session->leaveCall();
458 [[nodiscard]]
bool ok() const noexcept {
return m_ok; }
474 if (m_ok && m_session) m_session->leaveNodeEval();
478 [[nodiscard]]
bool ok() const noexcept {
return m_ok; }
494 if (m_ok && m_session) m_session->popEvaluatingCell();
498 [[nodiscard]]
bool ok() const noexcept {
return m_ok; }
528 Type m_type{Type::Empty};
529 XLCellValue m_scalar;
530 std::vector<XLCellValue> m_array;
531 size_t m_arrayRows{0};
532 size_t m_arrayCols{0};
533 uint32_t m_r1{0}, m_r2{0};
534 uint16_t m_c1{0}, m_c2{0};
535 std::string m_sheetName;
536 const std::function<XLCellValue(std::string_view)>* m_resolver{
nullptr};
548 m_array(
std::move(arr)),
549 m_arrayRows(m_array.
size()),
550 m_arrayCols(m_array.
empty() ? 0 : 1)
559 m_array(
std::move(data)),
563 if (m_arrayRows * m_arrayCols != m_array.size()) {
565 if (m_array.empty()) {
569 else if (
cols > 0 && m_array.size() %
cols == 0) {
570 m_arrayRows = m_array.size() / cols;
574 m_arrayRows = m_array.size();
585 const std::function<
XLCellValue(std::string_view)>* resolver)
586 : m_type(
Type::LazyRange),
599 if (m_type ==
Type::LazyRange)
return static_cast<size_t>(m_r2 - m_r1 + 1);
606 if (m_type ==
Type::LazyRange)
return static_cast<size_t>(m_c2 - m_c1 + 1);
623 [[nodiscard]]
const std::string&
sheetName() const noexcept {
return m_sheetName; }
630 return m_r1 > m_r2 || m_c1 > m_c2;
637 return static_cast<size_t>(m_r2 - m_r1 + 1) *
static_cast<size_t>(m_c2 - m_c1 + 1);
647 if (row >= m_arrayRows || col >= m_arrayCols)
return XLCellValue();
648 return m_array[row * m_arrayCols + col];
652 return (*
this)[row *
cols() + col];
662 uint16_t w = m_c2 - m_c1 + 1;
663 uint32_t row = m_r1 +
static_cast<uint32_t
>(index / w);
664 uint16_t col = m_c1 +
static_cast<uint16_t
>(index % w);
665 std::string ref = m_sheetName;
666 if (!ref.empty()) ref +=
"!";
668 if (m_resolver && *m_resolver)
return (*m_resolver)(ref);
681 std::vector<XLCellValue> d{m_scalar};
685 const size_t r =
rows();
686 const size_t c =
cols();
687 std::vector<XLCellValue> d;
689 for (
size_t i = 0; i < r * c; ++i) d.push_back((*
this)[i]);
755 OPENXLSX_EXPORT
size_t spillArray(
const XLFormulaArg& result, uint32_t topRow, uint16_t leftCol,
const XLSpillWriter& write);
762 OPENXLSX_EXPORT
bool spillRangeIsClear(
const XLFormulaArg& result,
765 const XLSpillOccupancy& isOccupied,
766 uint32_t anchorRow = 0,
767 uint16_t anchorCol = 0);
773 OPENXLSX_EXPORT XLSpillResult spillArrayChecked(
const XLFormulaArg& result,
776 const XLSpillWriter& write,
777 const XLSpillOccupancy& isOccupied,
778 uint32_t anchorRow = 0,
779 uint16_t anchorCol = 0);
781 class ShardedAstCache;
801 void setAstCacheCapacity(std::size_t capacity)
noexcept;
805 [[nodiscard]] std::size_t astCacheSize()
const;
808 void clearAstCache();
825 evaluate(std::string_view
formula,
const XLCellResolver& resolver = {}, XLFormulaDiagnosticReporter* reporter =
nullptr)
const;
832 [[nodiscard]] XLCellValue
833 evaluate(std::string_view formula, XLEvalSession& session, XLFormulaDiagnosticReporter* reporter =
nullptr)
const;
838 [[nodiscard]] XLFormulaArg evaluateArray(std::string_view formula,
839 const XLCellResolver& resolver = {},
840 XLFormulaDiagnosticReporter* reporter =
nullptr)
const;
845 [[nodiscard]] XLFormulaArg
846 evaluateArray(std::string_view formula, XLEvalSession& session, XLFormulaDiagnosticReporter* reporter =
nullptr)
const;
854 [[nodiscard]]
static XLCellResolver makeResolver(
const XLEvaluationContext& context);
863 [[nodiscard]]
static XLCellResolver makeResolver(
const XLWorksheet& wks);
871 [[nodiscard]]
static XLCellResolver makeResolver(
const IXLCellProvider& provider);
877 [[nodiscard]]
static XLFormulaArg expandRange(std::string_view rangeRef,
const XLCellResolver& resolver);
885 static std::vector<double> collectNumbers(
const std::vector<XLCellValue>& flat,
bool countBlanks =
false);
890 [[nodiscard]] XLCellValue evalNode(
const XLASTNode& node, XLEvalSession& session)
const;
895 [[nodiscard]] XLFormulaArg evalAsArg(
const XLASTNode& node, XLEvalSession& session)
const;
900 [[nodiscard]] XLFormulaArg expandArg(
const XLASTNode& argNode, XLEvalSession& session)
const;
905 [[nodiscard]] XLFormulaArg evalRefFunction(
const XLASTNode& node, XLEvalSession& session)
const;
910 [[nodiscard]] XLFormulaArg evalFunctionAsArg(
const XLASTNode& node, XLEvalSession& session)
const;
912 [[nodiscard]]
static bool isRefReturningFunction(std::string_view name);
919 static const FuncImpl* findBuiltin(std::string_view name);
922 [[nodiscard]]
static std::string cacheKey(std::string_view
formula);
927 bool m_astCacheEnabled{
true};
928 std::size_t m_astCacheCapacity{512};
929 std::unique_ptr<ShardedAstCache> m_astCache;
Abstract immutable interface for accessing cell values and formulas across spreadsheet grids.
Definition IXLCellProvider.hpp:32
Definition XLCellReference.hpp:44
std::string address() const
Get the address of the XLCellReference.
Definition XLCellReference.cpp:207
Class encapsulating a cell value.
Definition XLCellValue.hpp:89
bool ok() const noexcept
Definition XLFormulaEngine.hpp:458
~XLEvalCallGuard()
Definition XLFormulaEngine.hpp:452
XLEvalCallGuard & operator=(const XLEvalCallGuard &)=delete
XLEvalCallGuard(const XLEvalCallGuard &)=delete
XLEvalCallGuard(XLEvalSession &session)
Definition XLFormulaEngine.hpp:451
XLEvalCellGuard(const XLEvalCellGuard &)=delete
bool ok() const noexcept
Definition XLFormulaEngine.hpp:498
XLEvalCellGuard & operator=(const XLEvalCellGuard &)=delete
~XLEvalCellGuard()
Definition XLFormulaEngine.hpp:492
XLEvalCellGuard(XLEvalSession &session, std::string_view ref)
Definition XLFormulaEngine.hpp:491
XLEvalNodeGuard(const XLEvalNodeGuard &)=delete
bool ok() const noexcept
Definition XLFormulaEngine.hpp:478
XLEvalNodeGuard & operator=(const XLEvalNodeGuard &)=delete
XLEvalNodeGuard(XLEvalSession &session)
Definition XLFormulaEngine.hpp:471
~XLEvalNodeGuard()
Definition XLFormulaEngine.hpp:472
Per-evaluation session shared by the engine and session-aware functions.
Definition XLFormulaEngine.hpp:304
uint16_t currentCol() const noexcept
Definition XLFormulaEngine.hpp:359
const XLCellResolver * resolverPtr() const
Definition XLFormulaEngine.hpp:343
std::optional< std::string > resolveName(std::string_view name) const
Definition XLFormulaEngine.hpp:351
int callDepth() const noexcept
Definition XLFormulaEngine.hpp:378
void leaveNodeEval() noexcept
Definition XLFormulaEngine.hpp:393
XLFormulaArg expandRange(std::string_view rangeRef) const
Expand an A1-style cell/range text into a LazyRange (or scalar error).
Definition XLFormulaEngine.cpp:174
void leaveCall() noexcept
Definition XLFormulaEngine.hpp:373
XLEvalSession & setNameResolver(XLNameResolver nameResolver)
Definition XLFormulaEngine.hpp:317
XLEvalSession & setCurrentSheet(std::string sheetName)
Definition XLFormulaEngine.hpp:335
XLCellValue cellValue(std::string_view ref) const
Definition XLFormulaEngine.hpp:345
static constexpr int kMaxNodeEvalDepth
Definition XLFormulaEngine.hpp:380
PackedCellKey parsePackedKey(std::string_view ref) const
Definition XLFormulaEngine.cpp:49
bool pushEvaluatingCell(std::string_view ref)
Check and track cell references to detect circular dependency during evaluation.
Definition XLFormulaEngine.cpp:147
void popEvaluatingCell() noexcept
Definition XLFormulaEngine.cpp:166
uint32_t currentRow() const noexcept
Definition XLFormulaEngine.hpp:358
bool hasResolver() const
Definition XLFormulaEngine.hpp:341
static constexpr int kMaxCallDepth
Definition XLFormulaEngine.hpp:306
bool hasCurrentCell() const noexcept
Definition XLFormulaEngine.hpp:357
const std::string & currentSheet() const noexcept
Definition XLFormulaEngine.hpp:360
bool enterCall()
Enter a nested function/ref resolution (INDIRECT, etc.).
Definition XLFormulaEngine.hpp:366
XLEvalSession & setResolver(const XLCellResolver &resolver)
Definition XLFormulaEngine.hpp:311
XLEvalSession & setCurrentCell(uint32_t row, uint16_t col)
Bind the cell that owns the formula (1-based Excel coordinates).
Definition XLFormulaEngine.hpp:327
XLEvalSession(const XLCellResolver &resolver)
Definition XLFormulaEngine.hpp:309
static constexpr size_t kInlineCellStackCapacity
Definition XLFormulaEngine.hpp:414
int nodeEvalDepth() const noexcept
Definition XLFormulaEngine.hpp:398
bool enterNodeEval()
Enter AST node evaluation recursion.
Definition XLFormulaEngine.hpp:386
A class encapsulating an Excel worksheet. Access to XLWorksheet objects should be via the workbook ob...
Definition XLWorksheet.hpp:132
Definition IXLCellProvider.hpp:24
std::function< void(uint32_t row, uint16_t col, const XLCellValue &value)> XLSpillWriter
Callback used by spillArray to write one spill cell (1-based Excel coordinates).
Definition XLFormulaEngine.hpp:727
std::function< XLCellValue(std::string_view ref)> XLCellResolver
Callback type: resolves a cell reference string to a cell value.
Definition XLFormulaEngine.hpp:278
@ Star
Definition XLChart.hpp:72
@ Plus
Definition XLChart.hpp:72
std::function< bool(uint32_t row, uint16_t col)> XLSpillOccupancy
Callback: return true if (row,col) is occupied and must not be overwritten by a spill (except the for...
Definition XLFormulaEngine.hpp:733
@ String
Definition XLCellValue.hpp:47
@ Empty
Definition XLCellValue.hpp:47
@ Error
Definition XLCalculationEngine.hpp:129
@ Empty
Definition XLCalculationEngine.hpp:130
XLNodeKind
Kind discriminator for AST nodes.
Definition XLFormulaEngine.hpp:125
@ BoolLit
Definition XLFormulaEngine.hpp:128
@ ArrayLit
Excel array constant {1,2;3,4} — children row-major; number=rows, text=cols.
Definition XLFormulaEngine.hpp:134
@ UnaryOp
Definition XLFormulaEngine.hpp:132
@ Range
e.g. "A1:B10" – evaluated lazily by the resolver
Definition XLFormulaEngine.hpp:130
@ BinOp
Definition XLFormulaEngine.hpp:131
@ StringLit
Definition XLFormulaEngine.hpp:127
@ FuncCall
Definition XLFormulaEngine.hpp:133
@ ErrorLit
NAME?, etc. – propagated as-is
Definition XLFormulaEngine.hpp:135
@ Percent
Definition XLConditionalFormatting.hpp:80
@ Number
Definition XLConditionalFormatting.hpp:80
XLTokenKind
Kinds of tokens produced by the lexer.
Definition XLFormulaEngine.hpp:58
@ Gt
Definition XLFormulaEngine.hpp:75
@ Amp
& (string concat)
Definition XLFormulaEngine.hpp:70
@ Slash
/
Definition XLFormulaEngine.hpp:67
@ Ident
Function name or named range.
Definition XLFormulaEngine.hpp:63
@ Eq
=
Definition XLFormulaEngine.hpp:71
@ RBrace
} (array constant)
Definition XLFormulaEngine.hpp:83
@ Colon
: (used inside range references parsed by lexer)
Definition XLFormulaEngine.hpp:81
@ Lt
<
Definition XLFormulaEngine.hpp:73
@ LBrace
{ (array constant)
Definition XLFormulaEngine.hpp:82
@ Comma
,
Definition XLFormulaEngine.hpp:79
@ CellRef
Cell reference A1, $B$2, Sheet1!C3.
Definition XLFormulaEngine.hpp:62
@ End
Sentinel – end of input.
Definition XLFormulaEngine.hpp:84
@ LParen
(
Definition XLFormulaEngine.hpp:77
@ Error
Unrecognised character.
Definition XLFormulaEngine.hpp:85
@ Semicolon
; (alternative argument separator in some locales)
Definition XLFormulaEngine.hpp:80
@ Le
<=
Definition XLFormulaEngine.hpp:74
@ Bool
TRUE or FALSE keyword.
Definition XLFormulaEngine.hpp:61
@ Ge
>=
Definition XLFormulaEngine.hpp:76
@ Caret
^ (power)
Definition XLFormulaEngine.hpp:68
@ RParen
)
Definition XLFormulaEngine.hpp:78
@ NEq
<>
Definition XLFormulaEngine.hpp:72
@ Array
Definition XLStreamWriter.hpp:165
@ Minus
Definition XLChart.hpp:110
std::function< std::optional< std::string >(std::string_view name)> XLNameResolver
Optional callback: resolve a defined name to a formula/reference string.
Definition XLFormulaEngine.hpp:284
Definition XLCellIterator.hpp:131
XLASTNode(const XLASTNode &)=delete
XLTokenKind op
operator for BinOp / UnaryOp
Definition XLFormulaEngine.hpp:150
XLASTNode(XLNodeKind k)
Definition XLFormulaEngine.hpp:159
double number
Definition XLFormulaEngine.hpp:147
std::vector< std::unique_ptr< XLASTNode > > children
operands or function arguments
Definition XLFormulaEngine.hpp:157
XLASTNode & operator=(XLASTNode &&)=default
std::string text
string literal, cell-ref text, range text, identifier, error text
Definition XLFormulaEngine.hpp:148
const void * funcImpl
Definition XLFormulaEngine.hpp:153
XLNodeKind kind
Definition XLFormulaEngine.hpp:144
XLASTNode & operator=(const XLASTNode &)=delete
XLASTNode(XLASTNode &&)=default
bool isRefFunction
Definition XLFormulaEngine.hpp:154
64-bit coordinate encoding for fast, normalized circular dependency checking.
Definition XLFormulaEngine.hpp:405
constexpr PackedCellKey(uint64_t v)
Definition XLFormulaEngine.hpp:408
constexpr bool operator==(const PackedCellKey &o) const noexcept
Definition XLFormulaEngine.hpp:409
uint64_t value
Definition XLFormulaEngine.hpp:406
constexpr PackedCellKey()=default
constexpr bool operator!=(const PackedCellKey &o) const noexcept
Definition XLFormulaEngine.hpp:410
Result of a checked spill attempt (dynamic-array SPILL! support).
Definition XLFormulaEngine.hpp:739
size_t rows
spill height
Definition XLFormulaEngine.hpp:743
XLCellValue error
SPILL! when !ok, otherwise empty
Definition XLFormulaEngine.hpp:742
bool ok
false when the spill range is blocked
Definition XLFormulaEngine.hpp:740
size_t cellsWritten
number of cells written (0 on SPILL!)
Definition XLFormulaEngine.hpp:741
size_t cols
spill width
Definition XLFormulaEngine.hpp:744
A single lexical token from a formula string.
Definition XLFormulaEngine.hpp:92
double number
Pre-parsed numeric value when kind == Number.
Definition XLFormulaEngine.hpp:95
XLTokenKind kind
Definition XLFormulaEngine.hpp:93
std::string text
Raw text of the token (number string, identifier, …).
Definition XLFormulaEngine.hpp:94
std::size_t offset
Position in the formula string.
Definition XLFormulaEngine.hpp:97