OpenXLSX 1.12.1
Modern C++ Excel Library (Fork of OpenXLSX by Kenneth Troldal Balslev)
Loading...
Searching...
No Matches
XLFormulaEngine.hpp
Go to the documentation of this file.
1/*
2 * OpenXLSX-NX - Modern High-Performance C++ Excel Library
3 *
4 * Original work Copyright (c) 2018-2025, Kenneth Troldal Balslev and OpenXLSX contributors
5 * Modified work Copyright (c) 2026, Curry Tang and OpenXLSX-NX contributors
6 *
7 * Distributed under the BSD 3-Clause License.
8 * See LICENSE.md in the project root or https://opensource.org/licenses/BSD-3-Clause
9 */
10
11#ifndef OPENXLSX_XLFORMULAENGINE_HPP
12#define OPENXLSX_XLFORMULAENGINE_HPP
13
14#ifdef _MSC_VER
15# pragma warning(push)
16# pragma warning(disable : 4251)
17# pragma warning(disable : 4275)
18#endif
19
20// ===== Standard Library ===== //
21#include <array>
22#include <cstddef>
23#include <cstdint>
24#include <functional>
25#include <memory>
26#include <mutex>
27#include <optional>
28#include <string>
29#include <string_view>
30#include <unordered_map>
31#include <vector>
32
33// ===== GSL ===== //
34#include <gsl/gsl>
35
36// ===== OpenXLSX Includes ===== //
37#include "OpenXLSX-Exports.hpp"
38#include "XLCellReference.hpp"
39#include "XLCellValue.hpp"
41
42// Forward declare XLWorksheet and IXLCellProvider so callers can use makeResolver without pulling the full header.
43namespace OpenXLSX
44{
45 class XLWorksheet;
46 class IXLCellProvider;
47} // namespace OpenXLSX
48
49namespace OpenXLSX
50{
51 // =========================================================================
52 // Lexer
53 // =========================================================================
54
87
91 struct OPENXLSX_EXPORT XLToken
92 {
94 std::string text;
95 double number{0.0};
96 bool boolean{false};
97 std::size_t offset{0};
98 };
99
106 class OPENXLSX_EXPORT XLFormulaLexer
107 {
108 public:
114 static std::vector<XLToken> tokenize(std::string_view formula);
115
116 private:
117 // Stateless helper – everything runs in tokenize().
118 };
119
120 // =========================================================================
121 // AST
122 // =========================================================================
123
137
142 struct OPENXLSX_EXPORT XLASTNode
143 {
145
146 // ---- Leaf payloads ----
147 double number{0.0};
148 std::string text;
149 bool boolean{false};
151
152 // ---- Pre-bound execution cache (Parse-Time Binding) ----
153 const void* funcImpl{nullptr};
154 bool isRefFunction{false};
155
156 // ---- Children ----
157 std::vector<std::unique_ptr<XLASTNode>> children;
158
159 explicit XLASTNode(XLNodeKind k) : kind(k) {}
160
161 // Non-copyable due to unique_ptr children; movable.
162 XLASTNode(const XLASTNode&) = delete;
163 XLASTNode& operator=(const XLASTNode&) = delete;
164 XLASTNode(XLASTNode&&) = default;
166 };
167
168 // =========================================================================
169 // Diagnostics
170 // =========================================================================
171
172 struct OPENXLSX_EXPORT XLFormulaDiagnostic
173 {
174 std::string message;
175 std::size_t offset{0};
176 };
177
178 class OPENXLSX_EXPORT XLFormulaDiagnosticReporter
179 {
180 public:
182 explicit XLFormulaDiagnosticReporter(std::string formula) : m_formula(std::move(formula)) {}
183
184 void reportError(std::string message, std::size_t offset);
185
186 [[nodiscard]] const std::vector<XLFormulaDiagnostic>& diagnostics() const;
187 [[nodiscard]] bool hasErrors() const;
188 void clear();
189 [[nodiscard]] std::string getFullReport() const;
190
191 private:
192 std::string m_formula;
193 std::vector<XLFormulaDiagnostic> m_diagnostics;
194 };
195
196 // =========================================================================
197 // Parser
198 // =========================================================================
199
203 class OPENXLSX_EXPORT XLFormulaParser
204 {
205 public:
213 static std::unique_ptr<XLASTNode> parse(gsl::span<const XLToken> tokens, XLFormulaDiagnosticReporter* reporter = nullptr);
214
215 private:
216 // All state is local to the recursive parse calls below.
217 struct ParseContext
218 {
219 gsl::span<const XLToken> tokens;
220 std::size_t pos{0};
221 XLFormulaDiagnosticReporter* reporter{nullptr};
222 bool panicMode{false};
223 std::size_t depth{0};
224 static constexpr std::size_t kMaxDepth{256};
225
226 [[nodiscard]] const XLToken& current() const;
227 [[nodiscard]] const XLToken& peek(std::size_t offset = 1) const;
228 const XLToken& consume();
229 bool matchKind(XLTokenKind k);
230
231 void reportError(std::string message, std::size_t offset);
232 };
233
234 struct ParseDepthGuard
235 {
236 ParseContext& ctx;
237 bool ok{true};
238 explicit ParseDepthGuard(ParseContext& c) : ctx(c)
239 {
240 ++ctx.depth;
241 if (ctx.depth > ParseContext::kMaxDepth) {
242 ok = false;
243 ctx.reportError("Formula exceeds maximum nesting depth (" + std::to_string(ParseContext::kMaxDepth) + ")",
244 ctx.current().offset);
245 }
246 }
247 ~ParseDepthGuard()
248 {
249 if (ctx.depth > 0) --ctx.depth;
250 }
251 [[nodiscard]] bool isValid() const noexcept { return ok; }
252 };
253
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);
258
259 static int precedence(XLTokenKind k);
260 static bool isRightAssoc(XLTokenKind k);
261 };
262
263 // =========================================================================
264 // Evaluator / Engine
265 // =========================================================================
266
278 using XLCellResolver = std::function<XLCellValue(std::string_view ref)>;
279
284 using XLNameResolver = std::function<std::optional<std::string>(std::string_view name)>;
285
286 // Forward-declare so XLEvalSession can appear before XLFormulaArg details are complete.
287 class XLFormulaArg;
288 class XLFormulaEngine;
289
303 class OPENXLSX_EXPORT XLEvalSession
304 {
305 public:
306 static constexpr int kMaxCallDepth = 128;
307
308 XLEvalSession() = default;
309 explicit XLEvalSession(const XLCellResolver& resolver) : m_resolver(&resolver) {}
310
312 {
313 m_resolver = &resolver;
314 return *this;
315 }
316
318 {
319 m_nameResolver = std::move(nameResolver);
320 return *this;
321 }
322
327 XLEvalSession& setCurrentCell(uint32_t row, uint16_t col)
328 {
329 m_currentRow = row;
330 m_currentCol = col;
331 m_hasCurrentCell = (row > 0 && col > 0);
332 return *this;
333 }
334
335 XLEvalSession& setCurrentSheet(std::string sheetName)
336 {
337 m_currentSheet = std::move(sheetName);
338 return *this;
339 }
340
341 [[nodiscard]] bool hasResolver() const { return m_resolver != nullptr && static_cast<bool>(*m_resolver); }
342
343 [[nodiscard]] const XLCellResolver* resolverPtr() const { return m_resolver; }
344
345 [[nodiscard]] XLCellValue cellValue(std::string_view ref) const
346 {
347 if (!hasResolver()) return XLCellValue{};
348 return (*m_resolver)(ref);
349 }
350
351 [[nodiscard]] std::optional<std::string> resolveName(std::string_view name) const
352 {
353 if (!m_nameResolver) return std::nullopt;
354 return m_nameResolver(name);
355 }
356
357 [[nodiscard]] bool hasCurrentCell() const noexcept { return m_hasCurrentCell; }
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; }
361
367 {
368 if (m_callDepth >= kMaxCallDepth) return false;
369 ++m_callDepth;
370 return true;
371 }
372
373 void leaveCall() noexcept
374 {
375 if (m_callDepth > 0) --m_callDepth;
376 }
377
378 [[nodiscard]] int callDepth() const noexcept { return m_callDepth; }
379
380 static constexpr int kMaxNodeEvalDepth = 256;
381
387 {
388 if (m_nodeEvalDepth >= kMaxNodeEvalDepth) return false;
389 ++m_nodeEvalDepth;
390 return true;
391 }
392
393 void leaveNodeEval() noexcept
394 {
395 if (m_nodeEvalDepth > 0) --m_nodeEvalDepth;
396 }
397
398 [[nodiscard]] int nodeEvalDepth() const noexcept { return m_nodeEvalDepth; }
399
405 {
406 uint64_t value{0};
407 constexpr PackedCellKey() = default;
408 constexpr explicit PackedCellKey(uint64_t v) : value(v) {}
409 constexpr bool operator==(const PackedCellKey& o) const noexcept { return value == o.value; }
410 constexpr bool operator!=(const PackedCellKey& o) const noexcept { return value != o.value; }
411 constexpr explicit operator bool() const noexcept { return value != 0; }
412 };
413
414 static constexpr size_t kInlineCellStackCapacity = 32;
415
420 bool pushEvaluatingCell(std::string_view ref);
421 void popEvaluatingCell() noexcept;
422
423 [[nodiscard]] PackedCellKey parsePackedKey(std::string_view ref) const;
424
429 [[nodiscard]] XLFormulaArg expandRange(std::string_view rangeRef) const;
430
431 private:
432 const XLCellResolver* m_resolver{nullptr};
433 XLNameResolver m_nameResolver;
434 uint32_t m_currentRow{0};
435 uint16_t m_currentCol{0};
436 bool m_hasCurrentCell{false};
437 std::string m_currentSheet;
438 int m_callDepth{0};
439 int m_nodeEvalDepth{0};
440 std::array<PackedCellKey, kInlineCellStackCapacity> m_evaluatingCellsInline{};
441 size_t m_evaluatingCellsInlineCount{0};
442 std::vector<PackedCellKey> m_evaluatingCellsHeap;
443 };
444
448 class OPENXLSX_EXPORT XLEvalCallGuard
449 {
450 public:
451 explicit XLEvalCallGuard(XLEvalSession& session) : m_session(&session), m_ok(session.enterCall()) {}
453 {
454 if (m_ok && m_session) m_session->leaveCall();
455 }
458 [[nodiscard]] bool ok() const noexcept { return m_ok; }
459
460 private:
461 XLEvalSession* m_session{nullptr};
462 bool m_ok{false};
463 };
464
468 class OPENXLSX_EXPORT XLEvalNodeGuard
469 {
470 public:
471 explicit XLEvalNodeGuard(XLEvalSession& session) : m_session(&session), m_ok(session.enterNodeEval()) {}
473 {
474 if (m_ok && m_session) m_session->leaveNodeEval();
475 }
478 [[nodiscard]] bool ok() const noexcept { return m_ok; }
479
480 private:
481 XLEvalSession* m_session{nullptr};
482 bool m_ok{false};
483 };
484
488 class OPENXLSX_EXPORT XLEvalCellGuard
489 {
490 public:
491 XLEvalCellGuard(XLEvalSession& session, std::string_view ref) : m_session(&session), m_ok(session.pushEvaluatingCell(ref)) {}
493 {
494 if (m_ok && m_session) m_session->popEvaluatingCell();
495 }
498 [[nodiscard]] bool ok() const noexcept { return m_ok; }
499
500 private:
501 XLEvalSession* m_session{nullptr};
502 bool m_ok{false};
503 };
504
521
522 class OPENXLSX_EXPORT XLFormulaArg
523 {
524 public:
525 enum class Type { Empty, Scalar, Array, LazyRange };
526
527 private:
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};
537
538 public:
539 XLFormulaArg() = default;
540 XLFormulaArg(XLCellValue v) : m_type(Type::Scalar), m_scalar(std::move(v)) {}
541
546 XLFormulaArg(std::vector<XLCellValue> arr)
547 : m_type(Type::Array),
548 m_array(std::move(arr)),
549 m_arrayRows(m_array.size()),
550 m_arrayCols(m_array.empty() ? 0 : 1)
551 {}
552
557 XLFormulaArg(std::vector<XLCellValue> data, size_t rows, size_t cols)
558 : m_type(Type::Array),
559 m_array(std::move(data)),
560 m_arrayRows(rows),
561 m_arrayCols(cols)
562 {
563 if (m_arrayRows * m_arrayCols != m_array.size()) {
564 // Recover a consistent rectangular shape when possible.
565 if (m_array.empty()) {
566 m_arrayRows = 0;
567 m_arrayCols = 0;
568 }
569 else if (cols > 0 && m_array.size() % cols == 0) {
570 m_arrayRows = m_array.size() / cols;
571 m_arrayCols = cols;
572 }
573 else {
574 m_arrayRows = m_array.size();
575 m_arrayCols = 1;
576 }
577 }
578 }
579
580 XLFormulaArg(uint32_t r1,
581 uint32_t r2,
582 uint16_t c1,
583 uint16_t c2,
584 std::string sheetName,
585 const std::function<XLCellValue(std::string_view)>* resolver)
586 : m_type(Type::LazyRange),
587 m_r1(r1),
588 m_r2(r2),
589 m_c1(c1),
590 m_c2(c2),
591 m_sheetName(std::move(sheetName)),
592 m_resolver(resolver)
593 {}
594
595 Type type() const { return m_type; }
596
597 size_t rows() const
598 {
599 if (m_type == Type::LazyRange) return static_cast<size_t>(m_r2 - m_r1 + 1);
600 if (m_type == Type::Array) return m_arrayRows;
601 return m_type == Type::Scalar ? 1 : 0;
602 }
603
604 size_t cols() const
605 {
606 if (m_type == Type::LazyRange) return static_cast<size_t>(m_c2 - m_c1 + 1);
607 if (m_type == Type::Array) return m_arrayCols;
608 return m_type == Type::Scalar ? 1 : 0;
609 }
610
612 uint32_t firstRow() const noexcept { return m_type == Type::LazyRange ? m_r1 : 0; }
613
615 uint16_t firstCol() const noexcept { return m_type == Type::LazyRange ? m_c1 : 0; }
616
618 uint32_t lastRow() const noexcept { return m_type == Type::LazyRange ? m_r2 : 0; }
619
621 uint16_t lastCol() const noexcept { return m_type == Type::LazyRange ? m_c2 : 0; }
622
623 [[nodiscard]] const std::string& sheetName() const noexcept { return m_sheetName; }
624
625 bool empty() const
626 {
627 if (m_type == Type::Empty) return true;
628 if (m_type == Type::Scalar) return m_scalar.type() == XLValueType::Empty;
629 if (m_type == Type::Array) return m_array.empty();
630 return m_r1 > m_r2 || m_c1 > m_c2;
631 }
632 size_t size() const
633 {
634 if (m_type == Type::Empty) return 0;
635 if (m_type == Type::Scalar) return 1;
636 if (m_type == Type::Array) return m_array.size();
637 return static_cast<size_t>(m_r2 - m_r1 + 1) * static_cast<size_t>(m_c2 - m_c1 + 1);
638 }
639
643 [[nodiscard]] XLCellValue at(size_t row, size_t col) const
644 {
645 if (m_type == Type::Scalar) return (row == 0 && col == 0) ? m_scalar : XLCellValue();
646 if (m_type == Type::Array) {
647 if (row >= m_arrayRows || col >= m_arrayCols) return XLCellValue();
648 return m_array[row * m_arrayCols + col];
649 }
650 if (m_type == Type::LazyRange) {
651 if (row >= rows() || col >= cols()) return XLCellValue();
652 return (*this)[row * cols() + col];
653 }
654 return XLCellValue();
655 }
656
657 XLCellValue operator[](size_t index) const
658 {
659 if (m_type == Type::Scalar) return index == 0 ? m_scalar : XLCellValue();
660 if (m_type == Type::Array) return index < m_array.size() ? m_array[index] : XLCellValue();
661 if (m_type == Type::LazyRange) {
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 += "!";
667 ref += XLCellReference(row, col).address();
668 if (m_resolver && *m_resolver) return (*m_resolver)(ref);
669 }
670 return XLCellValue();
671 }
672
677 [[nodiscard]] XLFormulaArg materialize() const
678 {
679 if (m_type == Type::Array) return *this;
680 if (m_type == Type::Scalar) {
681 std::vector<XLCellValue> d{m_scalar};
682 return XLFormulaArg(std::move(d), 1, 1);
683 }
684 if (m_type == Type::LazyRange) {
685 const size_t r = rows();
686 const size_t c = cols();
687 std::vector<XLCellValue> d;
688 d.reserve(r * c);
689 for (size_t i = 0; i < r * c; ++i) d.push_back((*this)[i]);
690 return XLFormulaArg(std::move(d), r, c);
691 }
692 return XLFormulaArg();
693 }
694
698 [[nodiscard]] XLCellValue asScalar() const
699 {
700 if (empty()) return XLCellValue{};
701 if (m_type == Type::Scalar) return m_scalar;
702 return (*this)[0];
703 }
704
706 {
707 const XLFormulaArg* arg;
708 size_t index;
709
710 public:
711 Iterator(const XLFormulaArg* a, size_t i) : arg(a), index(i) {}
712 XLCellValue operator*() const { return (*arg)[index]; }
714 {
715 ++index;
716 return *this;
717 }
718 bool operator!=(const Iterator& other) const { return index != other.index; }
719 };
720 Iterator begin() const { return Iterator(this, 0); }
721 Iterator end() const { return Iterator(this, size()); }
722 };
723
727 using XLSpillWriter = std::function<void(uint32_t row, uint16_t col, const XLCellValue& value)>;
728
733 using XLSpillOccupancy = std::function<bool(uint32_t row, uint16_t col)>;
734
738 struct OPENXLSX_EXPORT XLSpillResult
739 {
740 bool ok{false};
741 size_t cellsWritten{0};
743 size_t rows{0};
744 size_t cols{0};
745 };
746
755 OPENXLSX_EXPORT size_t spillArray(const XLFormulaArg& result, uint32_t topRow, uint16_t leftCol, const XLSpillWriter& write);
756
762 OPENXLSX_EXPORT bool spillRangeIsClear(const XLFormulaArg& result,
763 uint32_t topRow,
764 uint16_t leftCol,
765 const XLSpillOccupancy& isOccupied,
766 uint32_t anchorRow = 0,
767 uint16_t anchorCol = 0);
768
773 OPENXLSX_EXPORT XLSpillResult spillArrayChecked(const XLFormulaArg& result,
774 uint32_t topRow,
775 uint16_t leftCol,
776 const XLSpillWriter& write,
777 const XLSpillOccupancy& isOccupied,
778 uint32_t anchorRow = 0,
779 uint16_t anchorCol = 0);
780
781 class ShardedAstCache;
782
783 class OPENXLSX_EXPORT XLFormulaEngine
784 {
785 public:
788
793
794 // ---- Phase D: AST cache (formula string → parsed tree) ----
795
797 void setAstCacheEnabled(bool enabled) noexcept { m_astCacheEnabled = enabled; }
798 [[nodiscard]] bool astCacheEnabled() const noexcept { return m_astCacheEnabled; }
799
801 void setAstCacheCapacity(std::size_t capacity) noexcept;
802 [[nodiscard]] std::size_t astCacheCapacity() const noexcept { return m_astCacheCapacity; }
803
805 [[nodiscard]] std::size_t astCacheSize() const;
806
808 void clearAstCache();
809
824 [[nodiscard]] XLCellValue
825 evaluate(std::string_view formula, const XLCellResolver& resolver = {}, XLFormulaDiagnosticReporter* reporter = nullptr) const;
826
832 [[nodiscard]] XLCellValue
833 evaluate(std::string_view formula, XLEvalSession& session, XLFormulaDiagnosticReporter* reporter = nullptr) const;
834
838 [[nodiscard]] XLFormulaArg evaluateArray(std::string_view formula,
839 const XLCellResolver& resolver = {},
840 XLFormulaDiagnosticReporter* reporter = nullptr) const;
841
845 [[nodiscard]] XLFormulaArg
846 evaluateArray(std::string_view formula, XLEvalSession& session, XLFormulaDiagnosticReporter* reporter = nullptr) const;
847
854 [[nodiscard]] static XLCellResolver makeResolver(const XLEvaluationContext& context);
855
863 [[nodiscard]] static XLCellResolver makeResolver(const XLWorksheet& wks);
864
871 [[nodiscard]] static XLCellResolver makeResolver(const IXLCellProvider& provider);
872
877 [[nodiscard]] static XLFormulaArg expandRange(std::string_view rangeRef, const XLCellResolver& resolver);
878
879 private:
880 // ---- Internal evaluation helpers ----
881
885 static std::vector<double> collectNumbers(const std::vector<XLCellValue>& flat, bool countBlanks = false);
886
890 [[nodiscard]] XLCellValue evalNode(const XLASTNode& node, XLEvalSession& session) const;
891
895 [[nodiscard]] XLFormulaArg evalAsArg(const XLASTNode& node, XLEvalSession& session) const;
896
900 [[nodiscard]] XLFormulaArg expandArg(const XLASTNode& argNode, XLEvalSession& session) const;
901
905 [[nodiscard]] XLFormulaArg evalRefFunction(const XLASTNode& node, XLEvalSession& session) const;
906
910 [[nodiscard]] XLFormulaArg evalFunctionAsArg(const XLASTNode& node, XLEvalSession& session) const;
911
912 [[nodiscard]] static bool isRefReturningFunction(std::string_view name);
913
914 friend class XLFormulaParser;
915
916 // ---- Built-in function table ----
917 // Session-aware: every builtin returns XLFormulaArg (scalar or multi-cell array).
918 using FuncImpl = std::function<XLFormulaArg(const std::vector<XLFormulaArg>&, XLEvalSession&)>;
919 static const FuncImpl* findBuiltin(std::string_view name);
920
922 [[nodiscard]] static std::string cacheKey(std::string_view formula);
923
925 [[nodiscard]] std::shared_ptr<XLASTNode> getOrParseAst(std::string_view formula, XLFormulaDiagnosticReporter* reporter) const;
926
927 bool m_astCacheEnabled{true};
928 std::size_t m_astCacheCapacity{512};
929 std::unique_ptr<ShardedAstCache> m_astCache;
930 };
931
932} // namespace OpenXLSX
933
934#ifdef _MSC_VER
935# pragma warning(pop)
936#endif
937
938#endif // OPENXLSX_XLFORMULAENGINE_HPP
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
Definition XLFormulaEngine.hpp:706
Iterator(const XLFormulaArg *a, size_t i)
Definition XLFormulaEngine.hpp:711
bool operator!=(const Iterator &other) const
Definition XLFormulaEngine.hpp:718
Iterator & operator++()
Definition XLFormulaEngine.hpp:713
XLCellValue operator*() const
Definition XLFormulaEngine.hpp:712
Lightweight formula evaluation engine.
Definition XLFormulaEngine.hpp:523
uint32_t firstRow() const noexcept
Return the 1-based row of the top-left cell (LazyRange only; 0 for other types).
Definition XLFormulaEngine.hpp:612
size_t rows() const
Definition XLFormulaEngine.hpp:597
uint16_t lastCol() const noexcept
Bottom-right column for LazyRange (0 otherwise).
Definition XLFormulaEngine.hpp:621
XLFormulaArg(uint32_t r1, uint32_t r2, uint16_t c1, uint16_t c2, std::string sheetName, const std::function< XLCellValue(std::string_view)> *resolver)
Definition XLFormulaEngine.hpp:580
uint16_t firstCol() const noexcept
Return the 1-based column of the top-left cell (LazyRange only; 0 for other types).
Definition XLFormulaEngine.hpp:615
Iterator end() const
Definition XLFormulaEngine.hpp:721
bool empty() const
Definition XLFormulaEngine.hpp:625
XLCellValue at(size_t row, size_t col) const
0-based (row, col) access. Works for Scalar, Array, and LazyRange.
Definition XLFormulaEngine.hpp:643
XLFormulaArg(std::vector< XLCellValue > data, size_t rows, size_t cols)
Construct a dense row-major 2-D array.
Definition XLFormulaEngine.hpp:557
XLFormulaArg(std::vector< XLCellValue > arr)
Construct a column vector (N×1) from a flat list.
Definition XLFormulaEngine.hpp:546
XLCellValue operator[](size_t index) const
Definition XLFormulaEngine.hpp:657
XLCellValue asScalar() const
Implicit-intersection / top-left scalar projection.
Definition XLFormulaEngine.hpp:698
size_t cols() const
Definition XLFormulaEngine.hpp:604
XLFormulaArg(XLCellValue v)
Definition XLFormulaEngine.hpp:540
size_t size() const
Definition XLFormulaEngine.hpp:632
Iterator begin() const
Definition XLFormulaEngine.hpp:720
Type type() const
Definition XLFormulaEngine.hpp:595
XLFormulaArg materialize() const
Materialize any arg into a dense row-major Array (copy).
Definition XLFormulaEngine.hpp:677
uint32_t lastRow() const noexcept
Bottom-right row for LazyRange (0 otherwise).
Definition XLFormulaEngine.hpp:618
const std::string & sheetName() const noexcept
Definition XLFormulaEngine.hpp:623
Type
Definition XLFormulaEngine.hpp:525
@ Array
Definition XLFormulaEngine.hpp:525
@ LazyRange
Definition XLFormulaEngine.hpp:525
@ Empty
Definition XLFormulaEngine.hpp:525
@ Scalar
Definition XLFormulaEngine.hpp:525
Definition XLFormulaEngine.hpp:179
XLFormulaDiagnosticReporter(std::string formula)
Definition XLFormulaEngine.hpp:182
Definition XLFormulaEngine.hpp:784
XLFormulaEngine & operator=(const XLFormulaEngine &)=delete
XLFormulaEngine & operator=(XLFormulaEngine &&)=delete
std::size_t astCacheCapacity() const noexcept
Definition XLFormulaEngine.hpp:802
bool astCacheEnabled() const noexcept
Definition XLFormulaEngine.hpp:798
XLFormulaEngine()
Definition XLFormulaEngine.cpp:1029
friend class XLFormulaParser
Definition XLFormulaEngine.hpp:914
XLFormulaEngine(const XLFormulaEngine &)=delete
XLFormulaEngine(XLFormulaEngine &&)=delete
void setAstCacheEnabled(bool enabled) noexcept
Definition XLFormulaEngine.hpp:797
Tokenises a raw Excel formula string (with or without leading '=').
Definition XLFormulaEngine.hpp:107
static std::vector< XLToken > tokenize(std::string_view formula)
Tokenise the given formula.
Definition XLFormulaParser.cpp:20
Recursive-descent (Pratt) parser that converts a token stream into an AST.
Definition XLFormulaEngine.hpp:204
static std::unique_ptr< XLASTNode > parse(gsl::span< const XLToken > tokens, XLFormulaDiagnosticReporter *reporter=nullptr)
Parse the token list produced by XLFormulaLexer::tokenize().
Definition XLFormulaParser.cpp:354
A class encapsulating an Excel worksheet. Access to XLWorksheet objects should be via the workbook ob...
Definition XLWorksheet.hpp:132
Definition XLFormulaUtils.hpp:37
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 bool operator!=(const PackedCellKey &o) const noexcept
Definition XLFormulaEngine.hpp:410
Definition XLFormulaEngine.hpp:173
std::string message
Definition XLFormulaEngine.hpp:174
std::size_t offset
Definition XLFormulaEngine.hpp:175
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