@sheetxl/sdk 0.7.28-beta.2 → 0.7.28-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/browser/cjs/{BREMLtxkQhtNSVra.cjs → BF14ZEAnaqxXroSj.cjs} +1 -1
  2. package/browser/cjs/{BG7YDVxiC4ErxvF1.cjs → BXtvdT1Z-MsB_o5F.cjs} +1 -1
  3. package/browser/cjs/Bc4JjVVZfFo3R4He.cjs +33 -0
  4. package/browser/cjs/{CQf4zxkBmheTVbjX.cjs → CD2RXdnfqSYNc6gX.cjs} +2 -2
  5. package/browser/cjs/DcLpXGexEtOxi-dD.cjs +1 -0
  6. package/browser/cjs/index.cjs +2 -2
  7. package/browser/esm/{DN4d5bDBkti28wuc.mjs → 0Mj5WKM362q6CECb.mjs} +213 -207
  8. package/browser/esm/{BxIOX1TojvA-1ZZP.mjs → CHSahmMFYNB0Ajkf.mjs} +2 -2
  9. package/browser/esm/{CZO1RubmqnJV96rq.mjs → CKk58ZLcrllMzfou.mjs} +2 -2
  10. package/browser/esm/{DRWu3TmcE9JFf78V.mjs → CPTtL2f6_4iblmFM.mjs} +2 -2
  11. package/browser/esm/{DPOelA1J3WHbMXyh.mjs → CoA-sUxjiIUIpTUF.mjs} +2 -2
  12. package/browser/esm/{vHWuKF-ftK7LM1uw.mjs → DBIu6NUHIcxOOBQp.mjs} +1 -1
  13. package/browser/esm/{CB_4gdPPPruwremH.mjs → Dy4Sdpju1T2icURu.mjs} +4748 -3883
  14. package/browser/esm/index.mjs +419 -411
  15. package/node/esm/{XQhP3dYwF_tEuswB.mjs → BtGxbEbBm79YvF_k.mjs} +303 -297
  16. package/node/esm/{B-tgcZihStNV9CbZ.mjs → DUYP6faJJHCaW1Xf.mjs} +1 -1
  17. package/node/esm/{C8tfYGL3wHy9IDDc.mjs → DqgWsVXROpSgKq6c.mjs} +2 -2
  18. package/node/esm/index.mjs +8686 -7802
  19. package/package.json +6 -6
  20. package/resources/locales/de/model.msg.json +12 -0
  21. package/resources/locales/en/model.msg.json +12 -0
  22. package/types/scripting-enums.json +2 -0
  23. package/types/scripting.d.ts +341 -15
  24. package/types/src/anchored/IAnchored.d.ts +27 -0
  25. package/types/src/calculation/Calculation.d.ts +21 -12
  26. package/types/src/calculation/ICalculation.d.ts +183 -0
  27. package/types/src/calculation/compiler/CompilerUtils.d.ts +20 -0
  28. package/types/src/calculation/compiler/FormulaParser.d.ts +32 -6
  29. package/types/src/calculation/executor/CalcExecutor.d.ts +204 -13
  30. package/types/src/calculation/executor/CalcExecutorUtils.d.ts +31 -0
  31. package/types/src/calculation/executor/CircularReference.d.ts +81 -0
  32. package/types/src/calculation/functions/Operators.d.ts +1 -1
  33. package/types/src/calculation/grid/CalcGrid.d.ts +5 -1
  34. package/types/src/calculation/grid/CalcGridUtils.d.ts +3 -2
  35. package/types/src/calculation/grid/ICalcGrid.d.ts +23 -1
  36. package/types/src/calculation/spatial/CircularEntry.d.ts +18 -0
  37. package/types/src/calculation/spatial/index.d.ts +1 -0
  38. package/types/src/calculation/state/CalcNode.d.ts +24 -17
  39. package/types/src/calculation/state/CalcState.d.ts +78 -15
  40. package/types/src/calculation/state/CalculationContext.d.ts +39 -0
  41. package/types/src/calculation/state/_ReadObservedGrid.d.ts +90 -0
  42. package/types/src/cell/ICell.d.ts +16 -0
  43. package/types/src/cellRange/ICellRange.d.ts +72 -6
  44. package/types/src/condition/AnchoredConditional.d.ts +26 -6
  45. package/types/src/conditionalFormat/ConditionalFormat.d.ts +8 -1
  46. package/types/src/conditionalFormat/IConditionalFormat.d.ts +4 -1
  47. package/types/src/conditionalFormat/IConditionalFormatCollection.d.ts +6 -2
  48. package/types/src/dataValidation/IDataValidationCollection.d.ts +6 -2
  49. package/types/src/hyperlink/IHyperlink.d.ts +3 -1
  50. package/types/src/hyperlink/_Hyperlink.d.ts +6 -0
  51. package/types/src/lib/utils/utils.browser.d.ts +5 -0
  52. package/types/src/license/LicenseDetails.d.ts +5 -0
  53. package/types/src/primitives/CalcSignal.d.ts +20 -0
  54. package/types/src/protectedRange/IProtectedRangeCollection.d.ts +7 -2
  55. package/types/src/scripting/_ScriptUtils.d.ts +13 -0
  56. package/types/src/sheet/Sheet.d.ts +33 -2
  57. package/types/src/sheet/SheetCell.d.ts +2 -0
  58. package/types/src/sheet/SheetRange.d.ts +12 -1
  59. package/types/src/sheet/_SheetStateTypes.d.ts +14 -1
  60. package/types/src/style/IStyle.d.ts +5 -0
  61. package/types/src/table/AnchoredTable.d.ts +17 -1
  62. package/types/src/text/TextUtils.d.ts +18 -0
  63. package/browser/cjs/DoemwsUQoGCk0vBK.cjs +0 -33
  64. package/browser/cjs/_c2uwwpr03Y7lzIj.cjs +0 -1
@@ -44,6 +44,15 @@ export declare class Calculation extends AbstractModel<State, ICalculation.JSON,
44
44
  protected _pendingPriority: (() => Promise<unknown>)[] | null;
45
45
  protected _draining: boolean;
46
46
  protected _drainScheduled: boolean;
47
+ protected _calcOwed: boolean;
48
+ /** {@link ICalculation.getCalculationMode} — gates the reactive pass in {@link _calculate}. */
49
+ protected _calcMode: ICalculation.CalculationMode;
50
+ /** {@link ICalculation.getIterativeCalculation} — handed to the executor per pass. */
51
+ protected _iterate: boolean;
52
+ protected _maxIterations: number;
53
+ protected _maxIterateChange: number;
54
+ /** The `calcPr` the file carried, kept whole so settings this engine ignores still round-trip. */
55
+ protected _calcJSON: ICalculation.JSON | null;
47
56
  protected _removeNamedItemsListeners: (() => void) | null;
48
57
  protected _namedDependents: Map<string, IRange.Coords[]> | null;
49
58
  protected _namedDependentsOf: ISpatialMap3D<FormulaSpatialValue> | null;
@@ -218,6 +227,18 @@ export declare class Calculation extends AbstractModel<State, ICalculation.JSON,
218
227
  stop(): Promise<void>;
219
228
  /** @inheritdoc ICalculation.getStatus */
220
229
  getStatus(): ICalculation.Status;
230
+ /** @inheritdoc ICalculation.getCalculationMode */
231
+ getCalculationMode(): ICalculation.CalculationMode;
232
+ /** @inheritdoc ICalculation.setCalculationMode */
233
+ setCalculationMode(mode: ICalculation.CalculationMode): this;
234
+ /** @inheritdoc ICalculation.isCalculationRequired */
235
+ isCalculationRequired(): boolean;
236
+ /** @inheritdoc ICalculation.getIterativeCalculation */
237
+ getIterativeCalculation(): ICalculation.IterativeCalculation;
238
+ /** @inheritdoc ICalculation.setIterativeCalculation */
239
+ setIterativeCalculation(options: boolean | Partial<ICalculation.IterativeCalculation>): this;
240
+ /** @inheritdoc ICalculation.toJSON */
241
+ toJSON(): ICalculation.JSON;
221
242
  /** @inheritdoc ICalculation.ready */
222
243
  ready(options?: ICalculation.CalculateOptions): Promise<ICalculation.Status>;
223
244
  /**
@@ -421,18 +442,6 @@ interface State extends AbstractModel.State {
421
442
  * Listeners to individual named items
422
443
  */
423
444
  itemRemoveListeners: (() => void)[];
424
- /**
425
- * Indicates if calculation will do iterative calcs
426
- */
427
- iterate: boolean;
428
- /**
429
- * The maximum number of iterations to perform when calculating.
430
- */
431
- maxIterations: number;
432
- /**
433
- * The maximum change allowed between iterations when performing iterative calculations.
434
- */
435
- maxIterateChange: number;
436
445
  }
437
446
  interface CommitView extends AbstractModel.CommitView {
438
447
  }
@@ -77,6 +77,63 @@ export interface ICalculation extends IModel {
77
77
  * This is similar convenience method for `getCalculation().createFormula(expression).evaluate(options)`.
78
78
  */
79
79
  evaluate(expression: string, options?: number | ICalculation.EvaluateOptions & Partial<IRange.CellCoords>): Promise<Scalar | IRange>;
80
+ /**
81
+ * When the engine recalculates on its own — Excel's Calculation Options.
82
+ *
83
+ * @remarks
84
+ * In {@link ICalculation.CalculationMode.Automatic} every commit that dirties a formula
85
+ * schedules a pass. In {@link ICalculation.CalculationMode.Manual} an edit only marks its
86
+ * dependents out of date ({@link isCalculationRequired}) and nothing is recalculated — volatile
87
+ * functions (`NOW`, `RAND`) stop re-rolling too — until {@link calculate}: Excel's F9 (every
88
+ * sheet), Shift+F9 (`scope`) and Ctrl+Alt+F9 (`full`). {@link ready} resolves at once in manual
89
+ * mode; a caller that wants current values calls {@link calculate}.
90
+ *
91
+ * @defaultValue {@link ICalculation.CalculationMode.Automatic}
92
+ */
93
+ getCalculationMode(): ICalculation.CalculationMode;
94
+ /**
95
+ * Sets the calculation mode.
96
+ *
97
+ * @remarks
98
+ * Leaving manual mode recalculates whatever is out of date, as Excel does.
99
+ * {@link ICalculation.CalculationMode.AutomaticExceptTables} is accepted for parity with the
100
+ * file format and Office Scripts; this engine has no what-if data tables, so it recalculates
101
+ * exactly as `Automatic` does.
102
+ */
103
+ setCalculationMode(mode: ICalculation.CalculationMode): this;
104
+ /**
105
+ * Whether any formula is out of date — Excel's `Calculate` indicator in the status bar.
106
+ *
107
+ * @remarks
108
+ * Meaningful in manual mode, where edits accumulate until {@link calculate}. In automatic
109
+ * mode it is `true` only between an edit and the pass it schedules.
110
+ */
111
+ isCalculationRequired(): boolean;
112
+ /**
113
+ * How a reference cycle is resolved — Excel's "Enable iterative calculation" and its limits.
114
+ *
115
+ * @see {@link ICalculation.IterativeCalculation}
116
+ */
117
+ getIterativeCalculation(): ICalculation.IterativeCalculation;
118
+ /**
119
+ * Enables, disables or configures iterative calculation.
120
+ *
121
+ * @param options `true`/`false` toggles `enabled` alone; an object updates the fields given and
122
+ * keeps the rest.
123
+ *
124
+ * @remarks
125
+ * Every cell in a cycle is recalculated when this changes: turning iteration on resolves the
126
+ * cycles the workbook shows as unresolved, turning it off writes `0` to them again.
127
+ */
128
+ setIterativeCalculation(options: boolean | Partial<ICalculation.IterativeCalculation>): this;
129
+ /**
130
+ * The calculation settings as JSON — what an xlsx carries in `calcPr`.
131
+ *
132
+ * @remarks
133
+ * Sparse: a setting at its default is omitted. Settings a file carried that this engine does
134
+ * not act on (`calcOnSave`, `fullCalcOnLoad`, `fullPrecision`, …) are kept and written back.
135
+ */
136
+ toJSON(): ICalculation.JSON;
80
137
  /**
81
138
  * Add Listeners.
82
139
  *
@@ -105,6 +162,87 @@ export declare namespace ICalculation {
105
162
  * tokenizer, the AST, a formula input — is ever handed an expression of unbounded size.
106
163
  */
107
164
  const MAX_EXPRESSION_LENGTH = 8192;
165
+ /**
166
+ * A reference cycle — the answer to "why is this cell `0`".
167
+ *
168
+ * @remarks
169
+ * A cell is in a cycle when calculating it opens its own value, directly or through other cells
170
+ * — `=A1+1` in A1, `=OFFSET(A1,0,0)` in A1, `=SUMIF(B1,C1,A1)` in A1 while B1 matches C1. With
171
+ * iterative calculation off (the default, and Excel's) every cell in a cycle, and every cell
172
+ * downstream of one, evaluates to `0`; nothing on the value says why. This does.
173
+ *
174
+ * Reached from a cell — {@link ICell.getCircularReference} answers it for members and for
175
+ * downstream cells alike — and carried by the `ICellRange.Feature.Circular` regions, so a
176
+ * range, a sheet or the workbook is asked the way any other error is asked:
177
+ * `getCounts(Feature.Circular)` for how many, `getRegions(Feature.Circular)` for which, with
178
+ * this object as each region's payload. There is no list of cycles on the calculation: nobody
179
+ * starts from the cycle; they start from a cell or a range and want to know more.
180
+ *
181
+ * Live, not a snapshot: it reads the engine's cycle table on every call and drops members whose
182
+ * formula has since been edited away, so a stale handle answers `getMemberCount() === 0`.
183
+ * Persists until the last member is edited away.
184
+ */
185
+ interface ICircularReference {
186
+ /**
187
+ * The cell named for the cycle, the way Excel's status bar names one
188
+ * (`Worksheet.CircularReference` likewise answers a single cell): the first member in
189
+ * row-major order. `scope` is the sheet name, or `null` when the member lives in a named
190
+ * formula's body rather than on a sheet.
191
+ */
192
+ getRepresentative(): IRange.CellCoords | null;
193
+ /**
194
+ * Every cell IN the cycle, in row-major order, `scope` set to the sheet name. Small — a cycle
195
+ * is the cells that read each other, not everything that reads them (that is
196
+ * {@link getDownstreamCount}).
197
+ */
198
+ getMembers(): readonly IRange.CellCoords[];
199
+ /** How many cells are IN the cycle, the representative included. */
200
+ getMemberCount(): number;
201
+ /** How many cells read the cycle (transitively) and evaluate to `0` because of it. */
202
+ getDownstreamCount(): number;
203
+ /**
204
+ * Whether `coords` is IN the cycle, as opposed to downstream of it. A cell that reads a
205
+ * member's `0` answers `false` here but still resolves this cycle from
206
+ * {@link ICell.getCircularReference} — the tooltip for it says "reads a circular reference
207
+ * at A1", not "is one".
208
+ */
209
+ isMember(coords: IRange.CellCoords): boolean;
210
+ /**
211
+ * The cycle as a walk of reads from `from` back to itself — each cell reads the next, and
212
+ * the last reads the first. A cycle has no start, so it is told from the cell that asks:
213
+ * with `A1 = B1+1` and `B1 = A1+1`, asked from A1 it is `[A1, B1]` (A1 → B1 → A1), asked
214
+ * from B1 it is `[B1, A1]`. A cycle of one is `[A1]`.
215
+ *
216
+ * @remarks
217
+ * Exact, not inferred from formula text: it is the order the engine found the cycle in,
218
+ * which is the order the reads happened — a dynamic read (`INDIRECT`, `OFFSET`) is a step
219
+ * like any other. Interlocking cycles share members; the walk follows the read that closed
220
+ * the cycle `from` was found in, so it is ONE loop through that cell, not every member
221
+ * ({@link getMembers} is every member).
222
+ *
223
+ * Empty when `from` is not a live member — a downstream cell asks from
224
+ * {@link getRepresentative}.
225
+ */
226
+ getPath(from: IRange.CellCoords): readonly IRange.CellCoords[];
227
+ /**
228
+ * Whether iterative calculation was on when the cycle was last evaluated. When `false` the
229
+ * cycle is unresolved and every member and downstream cell is `0`; the iteration answers
230
+ * below are then meaningless (`0` sweeps, no change).
231
+ */
232
+ isIterative(): boolean;
233
+ /**
234
+ * Whether iterative calculation settled it: every member moved by less than the workbook's
235
+ * `maxIterateChange` in the last sweep. Always `false` with iteration off.
236
+ */
237
+ isConverged(): boolean;
238
+ /** How many sweeps the last evaluation ran — up to the workbook's `maxIterations`. */
239
+ getIterationCount(): number;
240
+ /**
241
+ * The largest change any member made in the last sweep — what stopped the iteration when
242
+ * {@link isConverged}, what it never got under when not. `0` with iteration off.
243
+ */
244
+ getLastChange(): number;
245
+ }
108
246
  /**
109
247
  * Represents a formula that can be evaluated.
110
248
  */
@@ -572,6 +710,11 @@ export declare namespace ICalculation {
572
710
  * two diverge exactly where normalization is lossy — a number (`3.0` → `3`, `1**2` → `100`) or a
573
711
  * cell (raw `b2` vs the resolved coords). `undefined` only for a token with no captured source
574
712
  * image (e.g. a reference the engine rewrote programmatically rather than one the user typed).
713
+ *
714
+ * A reference literal is ONE span: a typed sheet qualifier and a trailing spill anchor ride inside
715
+ * the `cell`/`named` token's `text` (`Sheet2!A1#`), so the caret rules an editor applies per token
716
+ * treat the whole reference as one. The anchor keeps its own `postfix` token (carrying the same
717
+ * {@link referenceIndex}) imaging the empty string, so the concatenation above still holds.
575
718
  */
576
719
  text?: string;
577
720
  /**
@@ -778,8 +921,16 @@ export declare namespace ICalculation {
778
921
  /**
779
922
  * Called when the calculation has been updated and
780
923
  * a calculation has not been started.
924
+ *
925
+ * @remarks
926
+ * In manual mode this is every edit that leaves a formula out of date — see
927
+ * {@link ICalculation.isCalculationRequired}.
781
928
  */
782
929
  onStale?(source: ICalculation): void;
930
+ /**
931
+ * Called when the calculation mode or the iterative-calculation settings change.
932
+ */
933
+ onOptionsChange?(source: ICalculation): void;
783
934
  /**
784
935
  * Called when a calculation is starting.
785
936
  */
@@ -863,6 +1014,38 @@ export declare namespace ICalculation {
863
1014
  readonly AutomaticExceptTables: "automaticExceptTables";
864
1015
  };
865
1016
  type CalculationMode = typeof CalculationMode[keyof typeof CalculationMode];
1017
+ /**
1018
+ * Iterative calculation — Excel's "Enable iterative calculation" with its two limits.
1019
+ *
1020
+ * @remarks
1021
+ * With it off a reference cycle evaluates to `0` and is reported as unresolved. With it on the
1022
+ * cells of the cycle are re-evaluated in turn, each read seeing the latest value, until no cell
1023
+ * moved by {@link maxChange} or {@link maxIterations} sweeps ran — and the results persist into
1024
+ * the next recalculation, which re-runs every cycle the way it re-runs `NOW()`: `=A1+1` in A1 is
1025
+ * a counter that advances by `maxIterations` per recalc. A cycle that stops on the sweep cap is
1026
+ * still reported ({@link ICircularReference.isConverged}); a converged one is not.
1027
+ *
1028
+ * Office Scripts calls the count `maxIteration`; the file format `iterateCount` / `iterateDelta`.
1029
+ */
1030
+ interface IterativeCalculation {
1031
+ /**
1032
+ * @defaultValue `false`
1033
+ */
1034
+ enabled: boolean;
1035
+ /**
1036
+ * The most sweeps one recalculation runs over a cycle.
1037
+ *
1038
+ * @defaultValue `100`
1039
+ */
1040
+ maxIterations: number;
1041
+ /**
1042
+ * Sweeps stop early once every cell in the cycle moved by less than this. A non-numeric
1043
+ * change (text, error) never counts as settled.
1044
+ *
1045
+ * @defaultValue `0.001`
1046
+ */
1047
+ maxChange: number;
1048
+ }
866
1049
  /**
867
1050
  * Represents the status of a calculation result
868
1051
  */
@@ -129,6 +129,26 @@ export declare const isRangedNode: (node: ASTNode) => boolean;
129
129
  * parse path has no access to — and "SUM is not a defined name" is an honest answer.
130
130
  */
131
131
  export declare const findNonReferenceIntersectionOperand: (root: ASTNode, getFunction: ((name: string) => IFunction | null) | null) => ASTNode | null;
132
+ /**
133
+ * Finds a spill-anchor (`#`) operand that cannot possibly be a reference, or `null` if the formula
134
+ * has none.
135
+ *
136
+ * @param root The root of the formula's AST.
137
+ * @param getFunction Resolves a function's stableId to its declaration, or `null`.
138
+ *
139
+ * @remarks
140
+ * The anchor answers "where did the formula anchored HERE put its result", so its operand is a
141
+ * location, never a value — Excel's own declaration is `ANCHORARRAY(Range) -> Range|Array`. An
142
+ * operand that provably computes a value is refused at ENTRY, the same verdict (and the same
143
+ * predicate — {@link isDefinitelyNotReferenceNode}) as the intersection operand beside it.
144
+ *
145
+ * Measured against Excel 16.0 desktop (`spreadsheetbench/formula-tests/probe-anchor.ps1`): `=5#`,
146
+ * `={1,2}#` and `=SUM(X1:X3)#` cannot be typed at all, while a reference-returning call
147
+ * (`=INDEX(X1:X3,1)#`, `=OFFSET(B3,0,0)#`) is accepted. A NAME is accepted too — what it resolves
148
+ * to is not knowable here — and answers `#VALUE!` when it turns out to hold a constant, which is
149
+ * the runtime half of this same rule.
150
+ */
151
+ export declare const findNonReferenceAnchorOperand: (root: ASTNode, getFunction: ((name: string) => IFunction | null) | null) => ASTNode | null;
132
152
  /**
133
153
  * Finds an array constant whose rows are not all the same length — a JAGGED literal such as
134
154
  * `{1,2;3}`.
@@ -92,8 +92,11 @@ export declare class FormulaParser extends EmbeddedActionsParser {
92
92
  /** Matches a single `+` or `-` token. Used as a helper by `_rulePrefixOp` and `_ruleLiteralForArray`. */
93
93
  protected _rulePlusMinusOp: import('chevrotain').ParserMethod<[], IToken>;
94
94
  /**
95
- * Applies zero or more postfix operators (`%` percent, `#` spill anchor) to the node
96
- * produced by `_rulePrefixOp`, building a right-growing postfix AST chain.
95
+ * Applies zero or more `%` percent postfixes to the node produced by `_rulePrefixOp`, building a
96
+ * right-growing postfix AST chain.
97
+ *
98
+ * The other postfix, the spill anchor `#`, is NOT here: it binds tighter than the unary prefixes
99
+ * and looser than `:`, so it lives inside `_ruleRangeOp`.
97
100
  */
98
101
  protected _rulePostfixOp: import('chevrotain').ParserMethod<[], ASTNode<TokenType, any>>;
99
102
  /**
@@ -106,10 +109,33 @@ export declare class FormulaParser extends EmbeddedActionsParser {
106
109
  */
107
110
  protected _rulePrefixOp: import('chevrotain').ParserMethod<[], ASTNode<TokenType, any>>;
108
111
  /**
109
- * Folds the range operators (`:` range, `.:.` / `.:` / `:.` range-trim) — Excel's highest-precedence
110
- * operators, binding tighter than the unary prefixes (`_rulePrefixOp`). Left-associative, single level
111
- * (`A1:B2:C3` = `(A1:B2):C3`); every operator produces a reference infix node (`isRange = true`) so the
112
- * whole span resolves to one reference. This rule sits just above the `_ruleCallOp` leaf.
112
+ * Folds the range operators (`:` range, `.:.` / `.:` / `:.` range-trim) and the spill anchor `#` —
113
+ * Excel's highest-precedence operators, binding tighter than the unary prefixes (`_rulePrefixOp`).
114
+ * Left-associative, single level (`A1:B2:C3` = `(A1:B2):C3`); every operator produces a reference
115
+ * node (`isRange = true`) so the whole span resolves to one reference. This rule sits just above the
116
+ * `_ruleCallOp` leaf.
117
+ *
118
+ * ── Why `#` is folded HERE, with the range operators ─────────────────────────────────────────
119
+ *
120
+ * The anchor is a postfix over the reference accumulated SO FAR, not over the primary in front of
121
+ * it: `A1:B2#` is `(A1:B2)#`, whose operand is a multi-cell reference — `#REF!` in Excel. What a
122
+ * `#` before the operator anchors is only its own operand, because that is all that has
123
+ * accumulated yet — `B3#:B1` is `(B3#):B1`, the rectangle spanning B1 and the whole of B3's spill.
124
+ *
125
+ * Measured against Excel 16.0 desktop (`spreadsheetbench/formula-tests/probe-anchor.ps1`); the
126
+ * xlsx round-trip is the unambiguous witness, since the anchor lowers to an explicit call there:
127
+ *
128
+ * | typed | value | stored |
129
+ * | --- | --- | --- |
130
+ * | `B1:B3#` | `#REF!` | `_xlfn.ANCHORARRAY(B1:B3)` |
131
+ * | `B11:B3#` | `#REF!` | `_xlfn.ANCHORARRAY(B3:B11)` — re-imaged as `=B3:B11#` |
132
+ * | `B3#:B1` | B1:B5 | `_xlfn.ANCHORARRAY(B3):B1` |
133
+ *
134
+ * Excel ONLINE parses the same text differently — its grammar attaches `#` to the PRIMARY
135
+ * (`re = q(primary, any(Pound, StructRef), ...)` in the shipped engine), so it reads `A1:(B2#)`.
136
+ * Desktop wins. (The one desktop form this fold does not reproduce is `B3#:B5#`, which Excel
137
+ * stores as `ANCHORARRAY(B3):ANCHORARRAY(B5)` while we anchor the accumulation. Both are `#REF!`
138
+ * — an anchor over a multi-cell reference either way — so only the re-imaged text differs.)
113
139
  */
114
140
  protected _ruleRangeOp: import('chevrotain').ParserMethod<[], ASTNode<TokenType, any>>;
115
141
  /**
@@ -4,6 +4,8 @@ import { ISpatialMap, ISpatialMap3D } from '../../collections';
4
4
  import { FormulaSpatialValue, PrecedentSpatialValue, PrecedentKind } from '../spatial';
5
5
  import { ICalcGrid } from '../grid';
6
6
  import { IContextContainer, CalcNode } from '../state';
7
+ import { ReadHook } from '../state/_ReadObservedGrid';
8
+ import { CircularReference, CycleHost } from './CircularReference';
7
9
  /**
8
10
  * Executes a calculation cycle: collect → mark-and-plan → evaluate.
9
11
  *
@@ -17,16 +19,77 @@ export declare class CalcExecutor {
17
19
  private readonly _requestCalculate;
18
20
  protected _pendingCalcs: Set<CalcNode>;
19
21
  /**
20
- * Nodes the topological sort could not order — a reference cycle and everything downstream of it.
21
- * Rewritten by every `doMarkAndPlan` that detects one; meaningless otherwise.
22
+ * The last pass's circular roster: every node it evaluated by demand (a `doMarkAndPlan` that
23
+ * could not order, or the iteration guard's hand-over) plus every node whose dynamic read
24
+ * landed on its own cell, each carrying its `cycleRole`. The module scratch `_circularNodes`,
25
+ * this many; a node in it is flagged `CalcState.Rostered`. Emptied when a pass starts.
22
26
  */
23
- protected _circularNodes: CalcNode[];
27
+ protected _circularNodesLength: number;
28
+ /** The nodes the current `doMarkAndPlan` handed to demand evaluation, in worklist order. */
29
+ protected _demandBatch: CalcNode[];
30
+ /** {@link _onPassRead} as a bound hook — one closure for the executor's lifetime. */
31
+ protected _passHook: ReadHook;
24
32
  /**
25
- * Identifies the cycle last reported, so an unchanged one is not re-announced. A circular
26
- * reference persists until the user edits it away, and every pass re-detects it — including
27
- * volatile ones, which would otherwise log forever. `null` once a pass completes cycle-free.
33
+ * Marks a node downstream of the cycle `_taintGroup` names (design §2.1: every cell that reads
34
+ * a cycle, however it came to, is `0`). It skips evaluation — `Done` with a demand result of
35
+ * `0` — and taints its own dependents when the plan reaches it. A node already in a cycle keeps
36
+ * its role.
28
37
  */
29
- protected _circularReported: string | null;
38
+ protected _taintDownstream: (calc: CalcNode) => void;
39
+ protected _taintGroup: number;
40
+ /**
41
+ * Iterative calculation for the pass in progress (design §6.3); `null` with it off. Under it a
42
+ * read of a `Waiting` node is not an abort: the reader goes on with the node's previous value
43
+ * and the slice is marked once the reader returns (`_iterHits`); a read of a member's result
44
+ * makes the reader downstream without aborting it either; and {@link _demandSweep}
45
+ * re-evaluates the members until they settle.
46
+ */
47
+ protected _iterate: CalcExecutor.IterateOptions | null;
48
+ /** Inside {@link doDemandEvaluate} — where a `Waiting` read under iteration is marked in place. */
49
+ protected _demandActive: boolean;
50
+ /**
51
+ * Lengths of the module scratch lists of one {@link doDemandEvaluate}: `_iterHits`, the
52
+ * `Waiting` nodes the evaluation in progress read under iteration (each flagged
53
+ * `CalcState.IterHit`; consumed when it returns); `_iterMembers`, the members the call marked,
54
+ * in marking order — the sweep order; `_iterDownstream`, the nodes it marked downstream,
55
+ * evaluated once more after the sweeps. On the executor rather than local because the lists
56
+ * grow across the runs a sweep nests.
57
+ */
58
+ protected _iterHitsLength: number;
59
+ protected _iterMembersLength: number;
60
+ protected _iterDownstreamLength: number;
61
+ /** The pass the hook answers for; inert otherwise. Set by `doMarkAndPlan`, released with `_gridUpdates`. */
62
+ protected _passActive: boolean;
63
+ protected _passCycleId: number;
64
+ protected _passMarkId: number;
65
+ /**
66
+ * Commits `doEvaluate`'s pending batch — installed for the length of a `doEvaluate`. A read
67
+ * that lands on a node evaluated but not yet committed needs nothing more than this: the
68
+ * value is right, it is just not in the grid yet.
69
+ */
70
+ protected _flush: (() => void) | null;
71
+ /**
72
+ * The cycle table (design §7.3): per cycle id, one live {@link CircularReference} holding the
73
+ * nodes the sheet index currently shows as its members and as downstream of it — the object
74
+ * the index payloads carry and `ICell.getCircularReference()` answers. Persists across passes
75
+ * (a node moves when a commit writes its delta, `_trackCircular`) and is confirmed against the
76
+ * graph on read, since a deleted formula's node lingers here until something re-evaluates its
77
+ * cell. A cycle is created on first sight and dropped when its last node leaves.
78
+ */
79
+ protected _cycles: Map<number, CircularReference>;
80
+ /** What a {@link CircularReference} may ask of this executor; built once, shared by all. */
81
+ protected _cycleHost: CycleHost;
82
+ /** Last cycle id handed out by a demand pass; ids are unique across passes. */
83
+ protected _cycleGroupNext: number;
84
+ /**
85
+ * Counters over every demand pass since construction: nodes evaluated by demand and
86
+ * `NeedsFirst` retries. A retry is the cost of the path (a formula run and thrown away), so a
87
+ * chain Kahn could not order should show about one per node at most.
88
+ */
89
+ protected _demandStats: {
90
+ evaluations: number;
91
+ retries: number;
92
+ };
30
93
  _gridUpdates: Map<string, ICalcGrid.IncrementalUpdates> | null;
31
94
  _addDynamicPrecedent: ((node: CalcNode, range: IRange.Coords | undefined, kind: PrecedentKind) => void) | null;
32
95
  constructor(container: IContextContainer, context: IFormulaContext, requestCalculate: () => void);
@@ -45,14 +108,124 @@ export declare class CalcExecutor {
45
108
  */
46
109
  execute(cycleId: number, options: CalcExecutor.ExecuteOptions, state: CalcExecutor.ExecuteState): CalcExecutor.ExecuteResult | null;
47
110
  /**
48
- * Reports the reference cycle found by the preceding {@link doMarkAndPlan}.
111
+ * The read hook of a pass (DESIGN-CIRCULAR-CALC.md §4.3, §5), shared by both paths: armed for
112
+ * every reference while a node is evaluated by demand, and for dynamic-branch references
113
+ * (`OFFSET`/`INDIRECT`/`INDEX` results) on the ordinary path. A read that lands on a node of
114
+ * THIS pass decides: `Waiting` (on the in-progress stack — transitively waiting on the reader)
115
+ * is a cycle; `Unevaluated` suspends the reader until it is done; `Evaluated` (in the pending
116
+ * batch) is committed on the spot and read; `Done` with a cycle role makes the reader
117
+ * downstream. Any other cell is a value. Inert outside a pass, so a reference built during one
118
+ * and read later (a spill committed afterwards) is plain values.
119
+ */
120
+ private _onPassRead;
121
+ /**
122
+ * Under iteration, a read of a `Done` cycle node by the node being evaluated: the reader is
123
+ * downstream of that cycle (design §6.3) unless it is in one itself. Nothing is aborted — the
124
+ * reader goes on with the value — so the mark is made here, on the reader.
125
+ */
126
+ private _iterRead;
127
+ /**
128
+ * The nodes of this pass inside `coords` that are still `Unevaluated`, written into `into` from
129
+ * slot `length` on; returns the new length.
130
+ */
131
+ private _collectUnevaluated;
132
+ /**
133
+ * Evaluates `worklist` by demand (DESIGN-CIRCULAR-CALC.md §4.3): each node is evaluated with the
134
+ * read hook armed; a read that lands on one not yet evaluated suspends the reader and evaluates
135
+ * that one first (`NeedsFirst`); a read that lands on one already suspended — waiting,
136
+ * transitively, on the reader — is a cycle (`Circular`), and the in-progress stack from it up
137
+ * to the reader are the members, written `0`. A node that reads a member is downstream and
138
+ * writes `0` too. Everything else simply computes: an unorderable static edge that is never
139
+ * read (`OFFSET`'s anchor, `ROW`'s argument, an untaken `IF` branch) makes no cycle.
140
+ *
141
+ * @remarks
142
+ * Two callers: `doEvaluate` when the plan reaches the nodes `doMarkAndPlan` could not order
143
+ * (the batch, after everything ordered is committed), and `doEvaluate` again for a single
144
+ * ordered node whose dynamic read landed on a node not yet evaluated — the same suspension,
145
+ * on the ordinary path (§5). Every node evaluated here is flagged `circular`, so the plan
146
+ * takes its `demandValue` when it reaches it, and its finalized scalar is already in the grid
147
+ * for later lazy reads; `flush` commits the ordered path's pending batch when a read needs a
148
+ * value still sitting in it. Flat: the stack is an array, so a 1,560-row chain is 1,560
149
+ * evaluations, not 1,560 JS frames. A node is retried at most once per `NeedsFirst` it raises,
150
+ * and with the prefetch of its static precedents that is normally once.
151
+ */
152
+ protected doDemandEvaluate(cycleId: number, getUpdates: (scope: string) => ICalcGrid.IncrementalUpdates, worklist: readonly CalcNode[], flush: () => void): void;
153
+ /**
154
+ * The finalized scalar goes into the grid now, so a later lazy read sees it; `doEvaluate`
155
+ * commits the same value with the notifications when it reaches the node.
156
+ */
157
+ private _writeEarly;
158
+ /** The worklist loop of {@link doDemandEvaluate}; re-entered by a sweep for the nodes a read needs first. */
159
+ private _demandRun;
160
+ /**
161
+ * Marks the started (`Waiting`) nodes on the in-progress stack from `read` up to the top as one
162
+ * cycle — the slice a `Waiting` read names (design §4.3). A slice touching a member of an
163
+ * earlier cycle joins that cycle. The started nodes are on the stack in READ order — each is
164
+ * there because the one below it read it, and the reader on top read `read` — so the slice is
165
+ * the walk `getPath` answers: each member is linked to the next, the last back to the first.
166
+ * The demand state is left as it is: the caller finishes the members (iteration off) or lets
167
+ * them run on (iteration on). Returns the stack index of `read`.
168
+ */
169
+ private _markCycleSlice;
170
+ /**
171
+ * Iterative calculation (design §6.3) over the members {@link _demandRun} marked, which it
172
+ * evaluated once each — sweep 1. Every further sweep re-evaluates them in marking order, each
173
+ * read seeing the latest value (Gauss–Seidel, as Excel: `probe-iterative.ps1`), until no member
174
+ * moved by `maxChange` or `maxIterations` sweeps ran. The limits are global, as in Excel — one
175
+ * unsettled member keeps every cycle of the pass sweeping. Downstream nodes read the members
176
+ * once more afterwards; they never feed a cycle, so they need no sweeping. The members are then
177
+ * registered as volatile so the next recalculation re-runs them, which is how `=A1+1` advances
178
+ * per recalc (Excel re-iterates every cycle on every `Calculate()`).
179
+ */
180
+ private _demandSweep;
181
+ /** Clears the `IterHit` flags of the hits not consumed by {@link _demandRun}'s loop and empties the list. */
182
+ private _drainIterHits;
183
+ /**
184
+ * One evaluation of a `Done` node under iteration, with the read hook armed. A read that
185
+ * needs a node not yet evaluated (a handed-over node's sweep runs before the batch) runs those
186
+ * by demand and retries; a `Waiting` read cannot occur (nothing is waiting) and a member's
187
+ * result is a value (`_iterRead`), so nothing aborts.
188
+ */
189
+ private _demandEvaluateOne;
190
+ /**
191
+ * @internal
192
+ * Every cell the sheets currently show in a cycle or downstream of one, as dirty regions — what
193
+ * a change of the iterative-calculation setting re-evaluates.
194
+ */
195
+ getCycleCells(): ISpatialMap.Entry[];
196
+ /** Whether the pass in progress found a cycle member. */
197
+ protected _hasCycle(): boolean;
198
+ /** Adds `node` to the pass's circular roster, once. */
199
+ private _addCircular;
200
+ /** Empties the roster for a new pass, clearing each node's `Rostered` flag on the way out. */
201
+ private _resetCircular;
202
+ /**
203
+ * Records the difference between what the sheet's circular index shows for `node` and what
204
+ * this pass decided, in the cycle table and in the pass's conflating delta — the same path a
205
+ * pending status takes to the sheet (design §7.2). Called only when one of the two is set.
206
+ */
207
+ protected _trackCircular(node: CalcNode, updates: ICalcGrid.IncrementalUpdates, major: number, minor: number, isColumn: boolean): void;
208
+ /** The public face of cycle `group`, created on first sight. */
209
+ private _cycleOf;
210
+ /**
211
+ * Whether `node` is still the node registered for its own cell.
49
212
  *
50
213
  * @remarks
51
- * One line per calculation pass, naming a representative cell the way Excel's status bar does
52
- * (`Worksheet.CircularReference` likewise returns a single cell, not the whole set). The count
53
- * covers everything downstream of the cycle too, so it is normally larger than the cycle itself.
214
+ * A `CalcNode` is a plain graph object reachable by identity long after the grid has replaced or
215
+ * dropped its block — the same hazard `doCollectVolatileCalcs` guards against with `isLiveBlock`.
216
+ */
217
+ protected isLiveNode(node: CalcNode): boolean;
218
+ /**
219
+ * @internal
220
+ * A copy of the last pass's circular roster — see {@link _circularNodesLength} — each node
221
+ * carrying the {@link CycleRole} its reads gave it. Describes the last pass only.
54
222
  */
55
- protected reportCircular(): void;
223
+ getCircularNodes(): readonly CalcNode[];
224
+ /** @internal Demand-pass counters since construction: evaluations and `NeedsFirst` retries. */
225
+ getDemandStats(): {
226
+ evaluations: number;
227
+ retries: number;
228
+ };
56
229
  /**
57
230
  * Collects and marks all volatile CalcNodes.
58
231
  *
@@ -79,7 +252,7 @@ export declare class CalcExecutor {
79
252
  * @remarks
80
253
  * Uses Kahn's algorithm.
81
254
  */
82
- doMarkAndPlan(cycleId: number, markId: number, initial: FixedPackedArray<CalcNode>, plan: FixedPackedArray<CalcNode>): boolean;
255
+ doMarkAndPlan(cycleId: number, markId: number, initial: FixedPackedArray<CalcNode>, plan: FixedPackedArray<CalcNode>, forceDemand?: boolean): boolean;
83
256
  doEvaluate(cycleId: number, getUpdates: (scope: string) => ICalcGrid.IncrementalUpdates, scheduleRecalculation: (cycleId: number, calcNode?: CalcNode) => void, commit: (calcNodes: CalcNode[], calcNodesLength: number) => void, forceFull: boolean, plan: FixedPackedArray<CalcNode>): ISpatialMap | undefined;
84
257
  }
85
258
  export declare namespace CalcExecutor {
@@ -96,6 +269,24 @@ export declare namespace CalcExecutor {
96
269
  * The grid to seed the pass FROM — `ICalculation.CalculateOptions.scope`, i.e. "Calculate Sheet".
97
270
  */
98
271
  scopeGridId?: string;
272
+ /**
273
+ * Iterative calculation (design §6.3) for the pass; `null`/absent with it off.
274
+ */
275
+ iterate?: IterateOptions | null;
276
+ }
277
+ /** The two limits of `ICalculation.IterativeCalculation`. */
278
+ interface IterateOptions {
279
+ maxIterations: number;
280
+ maxChange: number;
281
+ }
282
+ /** How a cycle's last iterated evaluation ended — what `ICircularReference` answers. */
283
+ interface IterationResult {
284
+ /** Every member moved by less than `maxChange` in the last sweep. */
285
+ converged: boolean;
286
+ /** Sweeps run, the first evaluation included. */
287
+ iterationCount: number;
288
+ /** The largest change any member made in the last sweep. */
289
+ lastChange: number;
99
290
  }
100
291
  /** Snapshot of Calculation's persistent state for one pass */
101
292
  interface ExecuteState {
@@ -1,7 +1,38 @@
1
1
  import { IRange, Scalar } from '@sheetxl/primitives';
2
2
  import { Tuple, ISpatialMap } from '../../collections';
3
+ import { CalcSignal } from '../../primitives/CalcSignal';
3
4
  import { CalcNode } from '../state';
4
5
  import { PrecedentSpatialValue, FormulaSpatialValue } from '../spatial';
6
+ /**
7
+ * Raised from a read that landed on unorderable nodes not yet evaluated: the reader is suspended,
8
+ * `nodes` are evaluated first, and the reader is retried from scratch.
9
+ */
10
+ export declare class NeedsFirstSignal extends CalcSignal {
11
+ readonly nodes: readonly CalcNode[];
12
+ readonly count: number;
13
+ /**
14
+ * @param nodes A scratch array the executor reuses across reads; only the first `count` slots
15
+ * belong to this read, and the catcher consumes them before the next read can overwrite them.
16
+ */
17
+ constructor(nodes: readonly CalcNode[], count: number);
18
+ }
19
+ /**
20
+ * Raised from a read that landed on a node already suspended — one that is, transitively,
21
+ * waiting on the reader. The in-progress stack from `node` up to the reader is a cycle.
22
+ */
23
+ export declare class CircularSignal extends CalcSignal {
24
+ readonly node: CalcNode;
25
+ constructor(node: CalcNode);
26
+ }
27
+ /**
28
+ * Raised from a read that landed on a cycle member or a cell downstream of one: the reader is
29
+ * downstream too and writes `0` without finishing (Excel, iterative calc off — `=A1+100` beside
30
+ * `=A1+1` in A1 is `0`, not `100`).
31
+ */
32
+ export declare class DownstreamSignal extends CalcSignal {
33
+ readonly node: CalcNode;
34
+ constructor(node: CalcNode);
35
+ }
5
36
  export declare function rangeToTuples(range: IRange, offsetMajor?: number, offsetMinor?: number): Tuple.BoundedTuples<Scalar>;
6
37
  /**
7
38
  * TODO - document and/or rationalize with visitPrecedentBlock