@libregrid/formulas 1.3.1
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.
- package/LICENSE +21 -0
- package/NOTICE +1 -0
- package/README.md +63 -0
- package/dist/expression.d.ts +221 -0
- package/dist/expression.js +1142 -0
- package/dist/expression.js.map +1 -0
- package/dist/formulaCellEditor.d.ts +58 -0
- package/dist/formulaCellEditor.js +299 -0
- package/dist/formulaCellEditor.js.map +1 -0
- package/dist/formulaDataService.d.ts +33 -0
- package/dist/formulaDataService.js +84 -0
- package/dist/formulaDataService.js.map +1 -0
- package/dist/formulaInputManager.d.ts +19 -0
- package/dist/formulaInputManager.js +37 -0
- package/dist/formulaInputManager.js.map +1 -0
- package/dist/formulaService.d.ts +154 -0
- package/dist/formulaService.js +661 -0
- package/dist/formulaService.js.map +1 -0
- package/dist/formulasCss.d.ts +5 -0
- package/dist/formulasCss.js +91 -0
- package/dist/formulasCss.js.map +1 -0
- package/dist/formulasModule.d.ts +37 -0
- package/dist/formulasModule.js +59 -0
- package/dist/formulasModule.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +4 -0
- package/dist/version.js.map +1 -0
- package/package.json +22 -0
|
@@ -0,0 +1,1142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Expression engine for calculated columns and per-cell formulas.
|
|
3
|
+
*
|
|
4
|
+
* Two parse modes share one grammar core:
|
|
5
|
+
*
|
|
6
|
+
* - **`'expression'` mode** (default — calculated columns, gap-plan A2):
|
|
7
|
+
* same-row bracket references (`[colId]`), the public operator set, and the
|
|
8
|
+
* public provided-function set (AG Grid docs 36.1, "Calculated Columns" +
|
|
9
|
+
* "Formula Reference": the same operators and functions Formulas uses).
|
|
10
|
+
* Evaluation is same-row: a reference resolves the referenced column's value
|
|
11
|
+
* in the *same* row.
|
|
12
|
+
* - **`'cell'` mode** (per-cell formulas, gap-plan A1): additionally accepts
|
|
13
|
+
* A1-notation cell references (`B2`, `AA12`), `$`-absolute refs (`$A$1`,
|
|
14
|
+
* `A$1`, `=$A1`), rectangular ranges (`A1:B2`) and the LibreGrid long-hand
|
|
15
|
+
* reference format (`[colId:rowId]`, ranges `[colIdStart:rowIdStart..colIdEnd:rowIdEnd]`).
|
|
16
|
+
* Range-taking functions (`SUMIF`, `COUNTIF`) receive ranges as iterable
|
|
17
|
+
* `RangeParam`-shaped arguments; built-ins flatten them per argument.
|
|
18
|
+
*
|
|
19
|
+
* Errors are spreadsheet-style codes returned as `FormulaError`; the formula
|
|
20
|
+
* service renders the code text in the cell (`#REF!`, `#NAME?`, `#CIRCREF!`,
|
|
21
|
+
* `#PARSE!`, `#VALUE!`, `#DIV/0!`, `#ERROR!`) and hands the error object to
|
|
22
|
+
* Community's formula-error CSS/tooltip hooks (`getFormulaError`).
|
|
23
|
+
*
|
|
24
|
+
* Grammar (precedence, low → high):
|
|
25
|
+
* or: and ('OR' and)*
|
|
26
|
+
* and: cmp (('AND') cmp)*
|
|
27
|
+
* cmp: add (( '=' | '<>' | '>' | '<' | '>=' | '<=' ) add)?
|
|
28
|
+
* add: mult (('+' | '-' | '&') mult)*
|
|
29
|
+
* mult: pow (('*' | '/') pow)*
|
|
30
|
+
* pow: unary ('^' pow)? (right-associative)
|
|
31
|
+
* unary: '-' unary | '+' unary | '!' unary | postfix
|
|
32
|
+
* postfix: primary ('%')*
|
|
33
|
+
* primary: number | string | '[ref]' | true | false | ident '(' args ')' | '(' or ')'
|
|
34
|
+
* cell mode extends primary with: A1 cell refs, `$`-absolute cell refs,
|
|
35
|
+
* cell ranges (`cell ':' cell`) and long-hand bracket refs.
|
|
36
|
+
* A bare identifier that is not a call is an unknown function (`#NAME?` at
|
|
37
|
+
* evaluation time, not parse time, so validation reports the right reason).
|
|
38
|
+
*/
|
|
39
|
+
/** Spreadsheet-style formula error. `code` is the cell-rendered text. */
|
|
40
|
+
export class FormulaError extends Error {
|
|
41
|
+
code;
|
|
42
|
+
constructor(code, message) {
|
|
43
|
+
super(message);
|
|
44
|
+
this.code = code;
|
|
45
|
+
this.name = 'FormulaError';
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function fail(message) {
|
|
49
|
+
throw new FormulaError('#PARSE!', message);
|
|
50
|
+
}
|
|
51
|
+
/** A1 cell reference: 1–3 column letters then a 1-based row number. */
|
|
52
|
+
const CELL_REF_RE = /^([A-Za-z]{1,3})([0-9]+)$/;
|
|
53
|
+
/** True when `text` looks like a shorthand cell reference and not a function call or name. */
|
|
54
|
+
export function isCellRefText(text) {
|
|
55
|
+
return CELL_REF_RE.test(text);
|
|
56
|
+
}
|
|
57
|
+
export function tokenize(source, mode = 'expression') {
|
|
58
|
+
const tokens = [];
|
|
59
|
+
let i = 0;
|
|
60
|
+
while (i < source.length) {
|
|
61
|
+
const ch = source.charAt(i);
|
|
62
|
+
if (/\s/.test(ch)) {
|
|
63
|
+
i++;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
if (/[0-9]/.test(ch) || (ch === '.' && i + 1 < source.length && /[0-9]/.test(source.charAt(i + 1)))) {
|
|
67
|
+
let j = i;
|
|
68
|
+
while (j < source.length && /[0-9.]/.test(source.charAt(j)))
|
|
69
|
+
j++;
|
|
70
|
+
const text = source.slice(i, j);
|
|
71
|
+
const value = Number(text);
|
|
72
|
+
if (!Number.isFinite(value))
|
|
73
|
+
fail(`invalid number "${text}"`);
|
|
74
|
+
tokens.push({ type: 'num', value: text });
|
|
75
|
+
i = j;
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (ch === '"' || ch === "'") {
|
|
79
|
+
let j = i + 1;
|
|
80
|
+
while (j < source.length && source.charAt(j) !== ch)
|
|
81
|
+
j++;
|
|
82
|
+
if (j >= source.length)
|
|
83
|
+
fail('unterminated string literal');
|
|
84
|
+
tokens.push({ type: 'str', value: source.slice(i + 1, j) });
|
|
85
|
+
i = j + 1;
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
if (ch === '[') {
|
|
89
|
+
let j = i + 1;
|
|
90
|
+
while (j < source.length && source.charAt(j) !== ']')
|
|
91
|
+
j++;
|
|
92
|
+
if (j >= source.length)
|
|
93
|
+
fail('unterminated bracket reference');
|
|
94
|
+
const content = source.slice(i + 1, j).trim();
|
|
95
|
+
if (content.length === 0)
|
|
96
|
+
fail('empty bracket reference');
|
|
97
|
+
tokens.push({ type: 'ref', value: content });
|
|
98
|
+
i = j + 1;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (mode === 'cell' && (ch === '$' || /[A-Za-z]/.test(ch))) {
|
|
102
|
+
// Cell mode: scan names including `$` anchors so `B2`, `A$1`, `$A1` and
|
|
103
|
+
// `$A$1` each arrive as one token. `SUM(` stays an identifier (call).
|
|
104
|
+
let j = i;
|
|
105
|
+
while (j < source.length && /[A-Za-z0-9_$]/.test(source.charAt(j)))
|
|
106
|
+
j++;
|
|
107
|
+
const text = source.slice(i, j);
|
|
108
|
+
const next = source.slice(j).match(/^\s*\(/);
|
|
109
|
+
if (!next && /^\$?[A-Za-z]{1,3}\$?[0-9]+$/.test(text)) {
|
|
110
|
+
tokens.push({ type: 'cell', value: text });
|
|
111
|
+
i = j;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (text.includes('$'))
|
|
115
|
+
fail(`invalid cell reference "${text}"`);
|
|
116
|
+
tokens.push({ type: 'ident', value: text });
|
|
117
|
+
i = j;
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (/[A-Za-z_]/.test(ch)) {
|
|
121
|
+
let j = i;
|
|
122
|
+
while (j < source.length && /[A-Za-z0-9_]/.test(source.charAt(j)))
|
|
123
|
+
j++;
|
|
124
|
+
const text = source.slice(i, j);
|
|
125
|
+
tokens.push({ type: 'ident', value: text });
|
|
126
|
+
i = j;
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
const two = source.slice(i, i + 2);
|
|
130
|
+
if (two === '<>' || two === '>=' || two === '<=') {
|
|
131
|
+
tokens.push({ type: 'op', value: two });
|
|
132
|
+
i += 2;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if ((mode === 'cell' && ch === ':') || '+-*/^&=<>!%,()'.includes(ch)) {
|
|
136
|
+
tokens.push({ type: 'op', value: ch });
|
|
137
|
+
i++;
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
fail(`unexpected character "${ch}"`);
|
|
141
|
+
}
|
|
142
|
+
return tokens;
|
|
143
|
+
}
|
|
144
|
+
// ---------------------------------------------------------------------------
|
|
145
|
+
// Parser
|
|
146
|
+
// ---------------------------------------------------------------------------
|
|
147
|
+
class Parser {
|
|
148
|
+
tokens;
|
|
149
|
+
mode;
|
|
150
|
+
pos = 0;
|
|
151
|
+
constructor(tokens, mode = 'expression') {
|
|
152
|
+
this.tokens = tokens;
|
|
153
|
+
this.mode = mode;
|
|
154
|
+
}
|
|
155
|
+
parse() {
|
|
156
|
+
if (this.tokens.length === 0)
|
|
157
|
+
fail('empty expression');
|
|
158
|
+
const node = this.parseOr();
|
|
159
|
+
if (this.pos < this.tokens.length)
|
|
160
|
+
fail('unexpected trailing input');
|
|
161
|
+
return node;
|
|
162
|
+
}
|
|
163
|
+
peek() {
|
|
164
|
+
return this.tokens[this.pos];
|
|
165
|
+
}
|
|
166
|
+
matchOp(op) {
|
|
167
|
+
const t = this.peek();
|
|
168
|
+
if (t && t.type === 'op' && t.value === op) {
|
|
169
|
+
this.pos++;
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
matchIdent(value) {
|
|
175
|
+
const t = this.peek();
|
|
176
|
+
if (t && t.type === 'ident' && t.value.toUpperCase() === value) {
|
|
177
|
+
this.pos++;
|
|
178
|
+
return true;
|
|
179
|
+
}
|
|
180
|
+
return false;
|
|
181
|
+
}
|
|
182
|
+
parseOr() {
|
|
183
|
+
let left = this.parseAnd();
|
|
184
|
+
while (this.matchIdent('OR')) {
|
|
185
|
+
const right = this.parseAnd();
|
|
186
|
+
left = { kind: 'binary', op: 'or', left, right };
|
|
187
|
+
}
|
|
188
|
+
return left;
|
|
189
|
+
}
|
|
190
|
+
parseAnd() {
|
|
191
|
+
let left = this.parseComparison();
|
|
192
|
+
while (this.matchIdent('AND')) {
|
|
193
|
+
const right = this.parseComparison();
|
|
194
|
+
left = { kind: 'binary', op: 'and', left, right };
|
|
195
|
+
}
|
|
196
|
+
return left;
|
|
197
|
+
}
|
|
198
|
+
parseComparison() {
|
|
199
|
+
const left = this.parseAdditive();
|
|
200
|
+
const t = this.peek();
|
|
201
|
+
if (t && t.type === 'op' && ['=', '<>', '>', '<', '>=', '<='].includes(t.value)) {
|
|
202
|
+
this.pos++;
|
|
203
|
+
const right = this.parseAdditive();
|
|
204
|
+
return { kind: 'binary', op: t.value, left, right };
|
|
205
|
+
}
|
|
206
|
+
return left;
|
|
207
|
+
}
|
|
208
|
+
parseAdditive() {
|
|
209
|
+
let left = this.parseMultiplicative();
|
|
210
|
+
for (;;) {
|
|
211
|
+
const t = this.peek();
|
|
212
|
+
if (t && t.type === 'op' && (t.value === '+' || t.value === '-' || t.value === '&')) {
|
|
213
|
+
this.pos++;
|
|
214
|
+
const right = this.parseMultiplicative();
|
|
215
|
+
left = { kind: 'binary', op: t.value, left, right };
|
|
216
|
+
}
|
|
217
|
+
else {
|
|
218
|
+
return left;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
parseMultiplicative() {
|
|
223
|
+
let left = this.parseUnary();
|
|
224
|
+
for (;;) {
|
|
225
|
+
const t = this.peek();
|
|
226
|
+
if (t && t.type === 'op' && (t.value === '*' || t.value === '/')) {
|
|
227
|
+
this.pos++;
|
|
228
|
+
const right = this.parseExponent();
|
|
229
|
+
left = { kind: 'binary', op: t.value, left, right };
|
|
230
|
+
}
|
|
231
|
+
else {
|
|
232
|
+
return left;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
parseUnary() {
|
|
237
|
+
const t = this.peek();
|
|
238
|
+
if (t && t.type === 'op' && (t.value === '-' || t.value === '+' || t.value === '!')) {
|
|
239
|
+
this.pos++;
|
|
240
|
+
// Spreadsheet semantics: exponentiation binds tighter than unary
|
|
241
|
+
// minus, so -2^2 parses as -(2^2).
|
|
242
|
+
return { kind: 'unary', op: t.value, operand: this.parseUnary() };
|
|
243
|
+
}
|
|
244
|
+
return this.parseExponent();
|
|
245
|
+
}
|
|
246
|
+
parseExponent() {
|
|
247
|
+
const base = this.parsePostfix();
|
|
248
|
+
const t = this.peek();
|
|
249
|
+
if (t && t.type === 'op' && t.value === '^') {
|
|
250
|
+
this.pos++;
|
|
251
|
+
// Right-associative; the exponent may itself be unary (2^-3).
|
|
252
|
+
const exponent = this.parseUnary();
|
|
253
|
+
return { kind: 'binary', op: '^', left: base, right: exponent };
|
|
254
|
+
}
|
|
255
|
+
return base;
|
|
256
|
+
}
|
|
257
|
+
parsePostfix() {
|
|
258
|
+
let node = this.parsePrimary();
|
|
259
|
+
while (this.matchOp('%')) {
|
|
260
|
+
node = { kind: 'percent', operand: node };
|
|
261
|
+
}
|
|
262
|
+
return node;
|
|
263
|
+
}
|
|
264
|
+
parsePrimary() {
|
|
265
|
+
const t = this.peek();
|
|
266
|
+
if (!t)
|
|
267
|
+
fail('unexpected end of expression');
|
|
268
|
+
if (t.type === 'num') {
|
|
269
|
+
this.pos++;
|
|
270
|
+
return { kind: 'number', value: Number(t.value) };
|
|
271
|
+
}
|
|
272
|
+
if (t.type === 'str') {
|
|
273
|
+
this.pos++;
|
|
274
|
+
return { kind: 'string', value: t.value };
|
|
275
|
+
}
|
|
276
|
+
if (t.type === 'cell') {
|
|
277
|
+
this.pos++;
|
|
278
|
+
const start = parseCellRefText(t.value);
|
|
279
|
+
if (this.matchOp(':')) {
|
|
280
|
+
const endTok = this.peek();
|
|
281
|
+
if (!endTok || endTok.type !== 'cell')
|
|
282
|
+
fail('range end must be a cell reference');
|
|
283
|
+
this.pos++;
|
|
284
|
+
return { kind: 'range', start, end: parseCellRefText(endTok.value) };
|
|
285
|
+
}
|
|
286
|
+
return { kind: 'cell', ref: start };
|
|
287
|
+
}
|
|
288
|
+
if (t.type === 'ref') {
|
|
289
|
+
this.pos++;
|
|
290
|
+
// Bracket content: `[colId]` (calculated columns), or in cell mode the
|
|
291
|
+
// long-hand forms `[colId:rowId]` and `[colIdStart:rowIdStart..colIdEnd:rowIdEnd]`.
|
|
292
|
+
if (this.mode === 'cell' && t.value.includes(':')) {
|
|
293
|
+
const rangeParts = t.value.split('..');
|
|
294
|
+
if (rangeParts.length === 2) {
|
|
295
|
+
const [a, b] = rangeParts.map((p) => p.split(':').map((s) => s.trim()));
|
|
296
|
+
if (!a || !b || a.length !== 2 || b.length !== 2 || !a[0] || !a[1] || !b[0] || !b[1]) {
|
|
297
|
+
fail(`invalid long-hand range "[${t.value}]"`);
|
|
298
|
+
}
|
|
299
|
+
return {
|
|
300
|
+
kind: 'range',
|
|
301
|
+
start: { shorthand: false, colId: a[0], rowId: a[1] },
|
|
302
|
+
end: { shorthand: false, colId: b[0], rowId: b[1] },
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
const parts = t.value.split(':').map((s) => s.trim());
|
|
306
|
+
if (parts.length !== 2 || !parts[0] || !parts[1])
|
|
307
|
+
fail(`invalid long-hand reference "[${t.value}]"`);
|
|
308
|
+
return { kind: 'cell', ref: { shorthand: false, colId: parts[0], rowId: parts[1] } };
|
|
309
|
+
}
|
|
310
|
+
return { kind: 'ref', colId: t.value };
|
|
311
|
+
}
|
|
312
|
+
if (t.type === 'ident') {
|
|
313
|
+
this.pos++;
|
|
314
|
+
const lower = t.value.toLowerCase();
|
|
315
|
+
if (lower === 'true')
|
|
316
|
+
return { kind: 'boolean', value: true };
|
|
317
|
+
if (lower === 'false')
|
|
318
|
+
return { kind: 'boolean', value: false };
|
|
319
|
+
const next = this.peek();
|
|
320
|
+
if (next && next.type === 'op' && next.value === '(') {
|
|
321
|
+
this.pos++; // consume '('
|
|
322
|
+
const args = [];
|
|
323
|
+
if (!this.matchOp(')')) {
|
|
324
|
+
for (;;) {
|
|
325
|
+
args.push(this.parseOr());
|
|
326
|
+
if (!this.matchOp(','))
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
329
|
+
if (!this.matchOp(')'))
|
|
330
|
+
fail(`missing ")" in call to ${t.value}`);
|
|
331
|
+
}
|
|
332
|
+
return { kind: 'call', name: t.value, args };
|
|
333
|
+
}
|
|
334
|
+
// Bare identifier — unknown function or typo; resolved at evaluation
|
|
335
|
+
// time so validation reports #NAME? (not #PARSE!) for unknown names.
|
|
336
|
+
return { kind: 'call', name: t.value, args: [] };
|
|
337
|
+
}
|
|
338
|
+
if (t.type === 'op' && t.value === '(') {
|
|
339
|
+
this.pos++;
|
|
340
|
+
const node = this.parseOr();
|
|
341
|
+
if (!this.matchOp(')'))
|
|
342
|
+
fail('missing ")"');
|
|
343
|
+
return node;
|
|
344
|
+
}
|
|
345
|
+
fail(`unexpected "${t.value}"`);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
/** Parse a tokenised A1 reference (`B2`, `$A$1`, `A$1`) into a `CellRef`. */
|
|
349
|
+
export function parseCellRefText(text) {
|
|
350
|
+
const m = /^(\$?)([A-Za-z]{1,3})(\$?)([0-9]+)$/.exec(text);
|
|
351
|
+
if (!m)
|
|
352
|
+
fail(`invalid cell reference "${text}"`);
|
|
353
|
+
return {
|
|
354
|
+
shorthand: true,
|
|
355
|
+
letters: m[2].toUpperCase(),
|
|
356
|
+
row: Number(m[4]),
|
|
357
|
+
absCol: m[1] === '$',
|
|
358
|
+
absRow: m[3] === '$',
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
export function parseExpression(source, mode = 'expression') {
|
|
362
|
+
return new Parser(tokenize(source, mode), mode).parse();
|
|
363
|
+
}
|
|
364
|
+
/** Parse a per-cell formula body, stripping one leading `=` when present. */
|
|
365
|
+
export function parseCellFormula(source) {
|
|
366
|
+
const body = source.startsWith('=') ? source.slice(1) : source;
|
|
367
|
+
return parseExpression(body, 'cell');
|
|
368
|
+
}
|
|
369
|
+
/** Whether the formula text carries the `=` value-form prefix. */
|
|
370
|
+
export function hasFormulaPrefix(value) {
|
|
371
|
+
return value.startsWith('=');
|
|
372
|
+
}
|
|
373
|
+
// ---------------------------------------------------------------------------
|
|
374
|
+
// Value coercion
|
|
375
|
+
// ---------------------------------------------------------------------------
|
|
376
|
+
function display(v) {
|
|
377
|
+
if (v === null || v === undefined)
|
|
378
|
+
return 'empty';
|
|
379
|
+
if (v instanceof Date)
|
|
380
|
+
return v.toISOString();
|
|
381
|
+
return String(v);
|
|
382
|
+
}
|
|
383
|
+
export function toNum(v) {
|
|
384
|
+
if (typeof v === 'number') {
|
|
385
|
+
if (!Number.isFinite(v))
|
|
386
|
+
throw new FormulaError('#VALUE!', 'non-finite number');
|
|
387
|
+
return v;
|
|
388
|
+
}
|
|
389
|
+
if (typeof v === 'boolean')
|
|
390
|
+
return v ? 1 : 0;
|
|
391
|
+
if (v instanceof Date)
|
|
392
|
+
return v.getTime();
|
|
393
|
+
if (v === null || v === undefined)
|
|
394
|
+
return 0;
|
|
395
|
+
if (typeof v === 'string') {
|
|
396
|
+
const t = v.trim();
|
|
397
|
+
if (t === '')
|
|
398
|
+
return 0;
|
|
399
|
+
const n = Number(t);
|
|
400
|
+
if (Number.isFinite(n))
|
|
401
|
+
return n;
|
|
402
|
+
}
|
|
403
|
+
throw new FormulaError('#VALUE!', `cannot convert to a number: ${display(v)}`);
|
|
404
|
+
}
|
|
405
|
+
export function toBool(v) {
|
|
406
|
+
if (v === null || v === undefined)
|
|
407
|
+
return false;
|
|
408
|
+
if (typeof v === 'boolean')
|
|
409
|
+
return v;
|
|
410
|
+
if (typeof v === 'number')
|
|
411
|
+
return v !== 0;
|
|
412
|
+
if (v instanceof Date)
|
|
413
|
+
return true;
|
|
414
|
+
if (typeof v === 'string') {
|
|
415
|
+
const t = v.trim().toLowerCase();
|
|
416
|
+
if (t === '')
|
|
417
|
+
return false;
|
|
418
|
+
if (t === 'true')
|
|
419
|
+
return true;
|
|
420
|
+
if (t === 'false')
|
|
421
|
+
return false;
|
|
422
|
+
const n = Number(t);
|
|
423
|
+
return Number.isFinite(n) && n !== 0;
|
|
424
|
+
}
|
|
425
|
+
return true;
|
|
426
|
+
}
|
|
427
|
+
export function toStr(v) {
|
|
428
|
+
if (v === null || v === undefined)
|
|
429
|
+
return '';
|
|
430
|
+
if (typeof v === 'string')
|
|
431
|
+
return v;
|
|
432
|
+
if (typeof v === 'number')
|
|
433
|
+
return String(v);
|
|
434
|
+
if (typeof v === 'boolean')
|
|
435
|
+
return v ? 'TRUE' : 'FALSE';
|
|
436
|
+
if (v instanceof Date)
|
|
437
|
+
return v.toISOString();
|
|
438
|
+
return String(v);
|
|
439
|
+
}
|
|
440
|
+
/** Three-way compare with cross-type rules (numbers, dates, strings, empties). */
|
|
441
|
+
function compare(a, b) {
|
|
442
|
+
const aEmpty = a === null || a === undefined || a === '';
|
|
443
|
+
const bEmpty = b === null || b === undefined || b === '';
|
|
444
|
+
if (aEmpty || bEmpty) {
|
|
445
|
+
// Empty cells compare as 0 against numbers and as '' against strings.
|
|
446
|
+
if (aEmpty && bEmpty)
|
|
447
|
+
return 0;
|
|
448
|
+
const other = aEmpty ? b : a;
|
|
449
|
+
const dir = aEmpty ? 1 : -1;
|
|
450
|
+
if (typeof other === 'number' || typeof other === 'boolean')
|
|
451
|
+
return dir * (toNum(other) === 0 ? 0 : 1);
|
|
452
|
+
if (other instanceof Date)
|
|
453
|
+
return dir;
|
|
454
|
+
if (typeof other === 'string')
|
|
455
|
+
return dir;
|
|
456
|
+
return 0;
|
|
457
|
+
}
|
|
458
|
+
if (a instanceof Date && b instanceof Date)
|
|
459
|
+
return a.getTime() - b.getTime();
|
|
460
|
+
if (a instanceof Date)
|
|
461
|
+
return toNum(a) - toNum(b);
|
|
462
|
+
if (b instanceof Date)
|
|
463
|
+
return toNum(a) - toNum(b);
|
|
464
|
+
if (typeof a === 'string' && typeof b === 'string') {
|
|
465
|
+
return a.toLowerCase() === b.toLowerCase() ? 0 : a.toLowerCase() < b.toLowerCase() ? -1 : 1;
|
|
466
|
+
}
|
|
467
|
+
if (typeof a === 'string' || typeof b === 'string') {
|
|
468
|
+
// Numeric string vs number compares numerically.
|
|
469
|
+
return toNum(a) - toNum(b);
|
|
470
|
+
}
|
|
471
|
+
return toNum(a) - toNum(b);
|
|
472
|
+
}
|
|
473
|
+
const DAY_MS = 86_400_000;
|
|
474
|
+
function addValues(op, left, right) {
|
|
475
|
+
if (op === '&')
|
|
476
|
+
return toStr(left) + toStr(right);
|
|
477
|
+
if (left instanceof Date || right instanceof Date) {
|
|
478
|
+
if (op === '+') {
|
|
479
|
+
// Exactly one operand is guaranteed to be a Date (the outer check).
|
|
480
|
+
const d = left instanceof Date ? left : right;
|
|
481
|
+
const n = toNum(left instanceof Date ? right : left);
|
|
482
|
+
return new Date(d.getTime() + n * DAY_MS);
|
|
483
|
+
}
|
|
484
|
+
if (op === '-' && left instanceof Date && right instanceof Date) {
|
|
485
|
+
return (left.getTime() - right.getTime()) / DAY_MS;
|
|
486
|
+
}
|
|
487
|
+
if (op === '-' && left instanceof Date) {
|
|
488
|
+
return new Date(left.getTime() - toNum(right) * DAY_MS);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
switch (op) {
|
|
492
|
+
case '=':
|
|
493
|
+
return compare(left, right) === 0;
|
|
494
|
+
case '<>':
|
|
495
|
+
return compare(left, right) !== 0;
|
|
496
|
+
case '>':
|
|
497
|
+
return compare(left, right) > 0;
|
|
498
|
+
case '<':
|
|
499
|
+
return compare(left, right) < 0;
|
|
500
|
+
case '>=':
|
|
501
|
+
return compare(left, right) >= 0;
|
|
502
|
+
case '<=':
|
|
503
|
+
return compare(left, right) <= 0;
|
|
504
|
+
case 'or':
|
|
505
|
+
return toBool(left) || toBool(right);
|
|
506
|
+
case 'and':
|
|
507
|
+
return toBool(left) && toBool(right);
|
|
508
|
+
}
|
|
509
|
+
const l = toNum(left);
|
|
510
|
+
const r = toNum(right);
|
|
511
|
+
switch (op) {
|
|
512
|
+
case '+':
|
|
513
|
+
return l + r;
|
|
514
|
+
case '-':
|
|
515
|
+
return l - r;
|
|
516
|
+
case '*':
|
|
517
|
+
return l * r;
|
|
518
|
+
case '/':
|
|
519
|
+
if (r === 0)
|
|
520
|
+
throw new FormulaError('#DIV/0!', 'division by zero');
|
|
521
|
+
return l / r;
|
|
522
|
+
case '^': {
|
|
523
|
+
const v = Math.pow(l, r);
|
|
524
|
+
if (!Number.isFinite(v))
|
|
525
|
+
throw new FormulaError('#VALUE!', `invalid power result for ${l} ^ ${r}`);
|
|
526
|
+
return v;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
function arity(name, args, min, max) {
|
|
531
|
+
if (args.length < min || args.length > max) {
|
|
532
|
+
throw new FormulaError('#VALUE!', `${name} takes ${min === max ? min : `${min}–${max}`} argument(s), got ${args.length}`);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
/**
|
|
536
|
+
* Spread one level of nested array/iterable arguments (a cell-mode range
|
|
537
|
+
* arrives as an array-valued argument). Range-taking functions (`SUMIF`,
|
|
538
|
+
* `COUNTIF`) deliberately do not use this — their first argument *is* the
|
|
539
|
+
* range array.
|
|
540
|
+
*/
|
|
541
|
+
function flat(args) {
|
|
542
|
+
return args.flatMap((a) => {
|
|
543
|
+
if (Array.isArray(a))
|
|
544
|
+
return a;
|
|
545
|
+
if (a !== null && typeof a === 'object' && Symbol.iterator in a)
|
|
546
|
+
return [...a];
|
|
547
|
+
return [a];
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
function numericArgs(args) {
|
|
551
|
+
return flat(args).filter((v) => v !== null && v !== undefined && v !== '').map(toNum);
|
|
552
|
+
}
|
|
553
|
+
function toRange(v, fn) {
|
|
554
|
+
if (Array.isArray(v))
|
|
555
|
+
return v;
|
|
556
|
+
if (v !== null && typeof v === 'object' && Symbol.iterator in v) {
|
|
557
|
+
return Array.from(v);
|
|
558
|
+
}
|
|
559
|
+
throw new FormulaError('#VALUE!', `${fn} ranges require a cell range (Formulas feature); got a scalar`);
|
|
560
|
+
}
|
|
561
|
+
function matchesCriteria(value, criteria) {
|
|
562
|
+
if (typeof criteria === 'number' || typeof criteria === 'boolean') {
|
|
563
|
+
return compare(value, criteria) === 0;
|
|
564
|
+
}
|
|
565
|
+
const c = toStr(criteria).trim();
|
|
566
|
+
if (c === '')
|
|
567
|
+
return value === null || value === undefined || value === '';
|
|
568
|
+
const m = c.match(/^(>=|<=|<>|>|<|=)([\s\S]*)$/);
|
|
569
|
+
if (m) {
|
|
570
|
+
const op = m[1];
|
|
571
|
+
const target = m[2];
|
|
572
|
+
const cmp = compare(value, target);
|
|
573
|
+
switch (op) {
|
|
574
|
+
case '=': return cmp === 0;
|
|
575
|
+
case '<>': return cmp !== 0;
|
|
576
|
+
case '>': return cmp > 0;
|
|
577
|
+
case '<': return cmp < 0;
|
|
578
|
+
case '>=': return cmp >= 0;
|
|
579
|
+
case '<=': return cmp <= 0;
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
return compare(value, c) === 0;
|
|
583
|
+
}
|
|
584
|
+
function sumif(args) {
|
|
585
|
+
arity('SUMIF', args, 2, 3);
|
|
586
|
+
const range = toRange(args[0], 'SUMIF');
|
|
587
|
+
const sumRange = args.length === 3 ? toRange(args[2], 'SUMIF') : range;
|
|
588
|
+
if (range.length !== sumRange.length) {
|
|
589
|
+
throw new FormulaError('#VALUE!', 'SUMIF range and sum_range must be the same length');
|
|
590
|
+
}
|
|
591
|
+
let total = 0;
|
|
592
|
+
for (let i = 0; i < range.length; i++) {
|
|
593
|
+
if (matchesCriteria(range[i], args[1]))
|
|
594
|
+
total += toNum(sumRange[i]);
|
|
595
|
+
}
|
|
596
|
+
return total;
|
|
597
|
+
}
|
|
598
|
+
function countif(args) {
|
|
599
|
+
arity('COUNTIF', args, 2, 2);
|
|
600
|
+
const range = toRange(args[0], 'COUNTIF');
|
|
601
|
+
let count = 0;
|
|
602
|
+
for (let i = 0; i < range.length; i++) {
|
|
603
|
+
if (matchesCriteria(range[i], args[1]))
|
|
604
|
+
count++;
|
|
605
|
+
}
|
|
606
|
+
return count;
|
|
607
|
+
}
|
|
608
|
+
export const FORMULA_FUNCTIONS = {
|
|
609
|
+
SUM: (a) => numericArgs(a).reduce((s, v) => s + v, 0),
|
|
610
|
+
PRODUCT: (a) => numericArgs(a).reduce((p, v) => p * v, 1),
|
|
611
|
+
MIN: (a) => {
|
|
612
|
+
const nums = numericArgs(a);
|
|
613
|
+
return nums.length === 0 ? 0 : Math.min(...nums);
|
|
614
|
+
},
|
|
615
|
+
MAX: (a) => {
|
|
616
|
+
const nums = numericArgs(a);
|
|
617
|
+
return nums.length === 0 ? 0 : Math.max(...nums);
|
|
618
|
+
},
|
|
619
|
+
AVERAGE: (a) => {
|
|
620
|
+
const nums = numericArgs(a);
|
|
621
|
+
if (nums.length === 0)
|
|
622
|
+
throw new FormulaError('#DIV/0!', 'AVERAGE has no numeric arguments');
|
|
623
|
+
return nums.reduce((s, v) => s + v, 0) / nums.length;
|
|
624
|
+
},
|
|
625
|
+
MEDIAN: (a) => {
|
|
626
|
+
const nums = numericArgs(a).sort((x, y) => x - y);
|
|
627
|
+
if (nums.length === 0)
|
|
628
|
+
throw new FormulaError('#VALUE!', 'MEDIAN has no numeric arguments');
|
|
629
|
+
const mid = Math.floor(nums.length / 2);
|
|
630
|
+
return nums.length % 2 === 1 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
|
|
631
|
+
},
|
|
632
|
+
POWER: (a) => {
|
|
633
|
+
arity('POWER', a, 2, 2);
|
|
634
|
+
const v = Math.pow(toNum(a[0]), toNum(a[1]));
|
|
635
|
+
if (!Number.isFinite(v))
|
|
636
|
+
throw new FormulaError('#VALUE!', `invalid power result for ${a[0]} ^ ${a[1]}`);
|
|
637
|
+
return v;
|
|
638
|
+
},
|
|
639
|
+
RAND: () => Math.random(),
|
|
640
|
+
NOW: () => new Date(),
|
|
641
|
+
TODAY: () => {
|
|
642
|
+
const d = new Date();
|
|
643
|
+
d.setHours(0, 0, 0, 0);
|
|
644
|
+
return d;
|
|
645
|
+
},
|
|
646
|
+
CONCAT: (a) => flat(a).map(toStr).join(''),
|
|
647
|
+
IF: (a) => {
|
|
648
|
+
arity('IF', a, 2, 3);
|
|
649
|
+
return toBool(a[0]) ? a[1] : (a[2] ?? null);
|
|
650
|
+
},
|
|
651
|
+
COUNT: (a) => flat(a).filter((v) => typeof v === 'number').length,
|
|
652
|
+
COUNTA: (a) => flat(a).filter((v) => v !== null && v !== undefined && v !== '').length,
|
|
653
|
+
COUNTBLANK: (a) => flat(a).filter((v) => v === null || v === undefined || v === '').length,
|
|
654
|
+
AND: (a) => flat(a).every(toBool),
|
|
655
|
+
OR: (a) => flat(a).some(toBool),
|
|
656
|
+
NOT: (a) => {
|
|
657
|
+
arity('NOT', a, 1, 1);
|
|
658
|
+
return !toBool(a[0]);
|
|
659
|
+
},
|
|
660
|
+
SUMIF: sumif,
|
|
661
|
+
COUNTIF: countif,
|
|
662
|
+
};
|
|
663
|
+
export const FORMULA_FUNCTION_NAMES = Object.keys(FORMULA_FUNCTIONS).sort();
|
|
664
|
+
export function getFormulaFunction(name) {
|
|
665
|
+
return FORMULA_FUNCTIONS[name.toUpperCase()];
|
|
666
|
+
}
|
|
667
|
+
/** Build the iterable `RangeParam`-shaped object the docs' custom functions receive. */
|
|
668
|
+
function toRangeParam(bounds) {
|
|
669
|
+
return {
|
|
670
|
+
kind: 'range',
|
|
671
|
+
rowStart: bounds.rowStart,
|
|
672
|
+
rowEnd: bounds.rowEnd,
|
|
673
|
+
colStart: bounds.colStart,
|
|
674
|
+
colEnd: bounds.colEnd,
|
|
675
|
+
values: bounds.values,
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
/** Flatten params into one lazy iterator of raw values (the docs' `params.values`). */
|
|
679
|
+
function* flattenValues(params) {
|
|
680
|
+
for (const p of params) {
|
|
681
|
+
if (p.kind === 'value')
|
|
682
|
+
yield p.value;
|
|
683
|
+
else
|
|
684
|
+
yield* p.values;
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
/** A lazily-evaluated argument: ranges stay `RangeParam`-shaped for custom functions. */
|
|
688
|
+
function evaluateParam(node, ev) {
|
|
689
|
+
if (node.kind === 'range') {
|
|
690
|
+
if (!ev.resolveRange)
|
|
691
|
+
throw new FormulaError('#ERROR!', 'ranges are not supported in this context');
|
|
692
|
+
return toRangeParam(ev.resolveRange(node.start, node.end));
|
|
693
|
+
}
|
|
694
|
+
return { kind: 'value', value: evaluate(node, ev) };
|
|
695
|
+
}
|
|
696
|
+
export function evaluate(node, ev) {
|
|
697
|
+
switch (node.kind) {
|
|
698
|
+
case 'number':
|
|
699
|
+
return node.value;
|
|
700
|
+
case 'string':
|
|
701
|
+
return node.value;
|
|
702
|
+
case 'boolean':
|
|
703
|
+
return node.value;
|
|
704
|
+
case 'ref': {
|
|
705
|
+
if (ev.isResolving(node.colId)) {
|
|
706
|
+
throw new FormulaError('#CIRCREF!', `circular reference through [${node.colId}]`);
|
|
707
|
+
}
|
|
708
|
+
return ev.resolveColumn(node.colId);
|
|
709
|
+
}
|
|
710
|
+
case 'cell': {
|
|
711
|
+
if (!ev.resolveCell)
|
|
712
|
+
throw new FormulaError('#ERROR!', 'cell references are not supported in this context');
|
|
713
|
+
return ev.resolveCell(node.ref);
|
|
714
|
+
}
|
|
715
|
+
case 'range':
|
|
716
|
+
// A bare range outside a call cannot coerce to a scalar.
|
|
717
|
+
throw new FormulaError('#VALUE!', 'a cell range can only be used as a function argument');
|
|
718
|
+
case 'binary':
|
|
719
|
+
return addValues(node.op, evaluate(node.left, ev), evaluate(node.right, ev));
|
|
720
|
+
case 'unary': {
|
|
721
|
+
const v = evaluate(node.operand, ev);
|
|
722
|
+
if (node.op === '!')
|
|
723
|
+
return !toBool(v);
|
|
724
|
+
const n = toNum(v);
|
|
725
|
+
return node.op === '-' ? -n : n;
|
|
726
|
+
}
|
|
727
|
+
case 'percent':
|
|
728
|
+
return toNum(evaluate(node.operand, ev)) / 100;
|
|
729
|
+
case 'call': {
|
|
730
|
+
const name = node.name.toUpperCase();
|
|
731
|
+
if (name === 'IF') {
|
|
732
|
+
// Spreadsheet semantics: only the taken branch is evaluated.
|
|
733
|
+
if (node.args.length < 2 || node.args.length > 3) {
|
|
734
|
+
throw new FormulaError('#VALUE!', `IF takes 2–3 argument(s), got ${node.args.length}`);
|
|
735
|
+
}
|
|
736
|
+
const condition = evaluate(node.args[0], ev);
|
|
737
|
+
const branch = (arg) => {
|
|
738
|
+
if (!arg)
|
|
739
|
+
return null;
|
|
740
|
+
if (ev.mode === 'cell') {
|
|
741
|
+
const p = evaluateParam(arg, ev);
|
|
742
|
+
return p.kind === 'value' ? p.value : (p.values[0] ?? null);
|
|
743
|
+
}
|
|
744
|
+
return evaluate(arg, ev);
|
|
745
|
+
};
|
|
746
|
+
return toBool(condition) ? branch(node.args[1]) : branch(node.args[2]);
|
|
747
|
+
}
|
|
748
|
+
if (ev.mode === 'cell') {
|
|
749
|
+
// Cell mode: range arguments stay `RangeParam`-shaped for custom
|
|
750
|
+
// functions; built-ins receive ranges flattened per argument.
|
|
751
|
+
const params = node.args.map((a) => evaluateParam(a, ev));
|
|
752
|
+
const custom = ev.resolveCustomFunction?.(node.name);
|
|
753
|
+
if (custom) {
|
|
754
|
+
const ctx = ev.functionContext ?? { row: undefined, column: undefined };
|
|
755
|
+
try {
|
|
756
|
+
return custom({ row: ctx.row, column: ctx.column, args: params, values: flattenValues(params) });
|
|
757
|
+
}
|
|
758
|
+
catch (e) {
|
|
759
|
+
if (e instanceof FormulaError)
|
|
760
|
+
throw e;
|
|
761
|
+
throw new FormulaError('#ERROR!', `${node.name} failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
const fn = getFormulaFunction(node.name);
|
|
765
|
+
if (!fn)
|
|
766
|
+
throw new FormulaError('#NAME?', `unknown function "${node.name}"`);
|
|
767
|
+
const args = params.map((p) => (p.kind === 'value' ? p.value : p.values));
|
|
768
|
+
try {
|
|
769
|
+
return fn(args);
|
|
770
|
+
}
|
|
771
|
+
catch (e) {
|
|
772
|
+
if (e instanceof FormulaError)
|
|
773
|
+
throw e;
|
|
774
|
+
throw new FormulaError('#ERROR!', `${node.name} failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
const fn = getFormulaFunction(name);
|
|
778
|
+
if (!fn)
|
|
779
|
+
throw new FormulaError('#NAME?', `unknown function "${node.name}"`);
|
|
780
|
+
const args = node.args.map((a) => evaluate(a, ev));
|
|
781
|
+
try {
|
|
782
|
+
return fn(args);
|
|
783
|
+
}
|
|
784
|
+
catch (e) {
|
|
785
|
+
if (e instanceof FormulaError)
|
|
786
|
+
throw e;
|
|
787
|
+
throw new FormulaError('#ERROR!', `${node.name} failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
/** Parse (and optionally reference-check) without evaluating. `null` when valid. */
|
|
793
|
+
export function validateExpression(source, options = {}) {
|
|
794
|
+
let ast;
|
|
795
|
+
try {
|
|
796
|
+
ast = parseExpression(source, options.mode ?? 'expression');
|
|
797
|
+
}
|
|
798
|
+
catch (e) {
|
|
799
|
+
return e instanceof FormulaError ? e : new FormulaError('#PARSE!', String(e));
|
|
800
|
+
}
|
|
801
|
+
if (options.resolveReference) {
|
|
802
|
+
const ids = referencedColumnIds(ast);
|
|
803
|
+
for (const id of ids) {
|
|
804
|
+
if (!options.resolveReference(id)) {
|
|
805
|
+
return new FormulaError('#REF!', `unknown column reference [${id}]`);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
return null;
|
|
810
|
+
}
|
|
811
|
+
/** Unique referenced colIds (bracket refs) in declaration order. */
|
|
812
|
+
export function referencedColumnIds(node) {
|
|
813
|
+
const seen = new Set();
|
|
814
|
+
const out = [];
|
|
815
|
+
const visit = (n) => {
|
|
816
|
+
switch (n.kind) {
|
|
817
|
+
case 'ref':
|
|
818
|
+
if (!seen.has(n.colId)) {
|
|
819
|
+
seen.add(n.colId);
|
|
820
|
+
out.push(n.colId);
|
|
821
|
+
}
|
|
822
|
+
break;
|
|
823
|
+
case 'binary':
|
|
824
|
+
visit(n.left);
|
|
825
|
+
visit(n.right);
|
|
826
|
+
break;
|
|
827
|
+
case 'unary':
|
|
828
|
+
case 'percent':
|
|
829
|
+
visit(n.operand);
|
|
830
|
+
break;
|
|
831
|
+
case 'call':
|
|
832
|
+
for (const a of n.args)
|
|
833
|
+
visit(a);
|
|
834
|
+
break;
|
|
835
|
+
case 'range':
|
|
836
|
+
visitCellRef(n.start);
|
|
837
|
+
visitCellRef(n.end);
|
|
838
|
+
break;
|
|
839
|
+
case 'cell':
|
|
840
|
+
visitCellRef(n.ref);
|
|
841
|
+
break;
|
|
842
|
+
}
|
|
843
|
+
};
|
|
844
|
+
const visitCellRef = (ref) => {
|
|
845
|
+
if (!ref.shorthand && !seen.has(ref.colId)) {
|
|
846
|
+
seen.add(ref.colId);
|
|
847
|
+
out.push(ref.colId);
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
visit(node);
|
|
851
|
+
return out;
|
|
852
|
+
}
|
|
853
|
+
/** Every cell reference in the expression, in declaration order (cell mode). */
|
|
854
|
+
export function referencedCells(node) {
|
|
855
|
+
const out = [];
|
|
856
|
+
const visit = (n) => {
|
|
857
|
+
switch (n.kind) {
|
|
858
|
+
case 'cell':
|
|
859
|
+
out.push(n.ref);
|
|
860
|
+
break;
|
|
861
|
+
case 'range':
|
|
862
|
+
out.push(n.start, n.end);
|
|
863
|
+
break;
|
|
864
|
+
case 'binary':
|
|
865
|
+
visit(n.left);
|
|
866
|
+
visit(n.right);
|
|
867
|
+
break;
|
|
868
|
+
case 'unary':
|
|
869
|
+
case 'percent':
|
|
870
|
+
visit(n.operand);
|
|
871
|
+
break;
|
|
872
|
+
case 'call':
|
|
873
|
+
for (const a of n.args)
|
|
874
|
+
visit(a);
|
|
875
|
+
break;
|
|
876
|
+
}
|
|
877
|
+
};
|
|
878
|
+
visit(node);
|
|
879
|
+
return out;
|
|
880
|
+
}
|
|
881
|
+
// ---------------------------------------------------------------------------
|
|
882
|
+
// Serialisation, long-hand conversion and offset shifting (gap-plan A1)
|
|
883
|
+
// ---------------------------------------------------------------------------
|
|
884
|
+
/** Column letters for a 0-based column position (0 → `A`, 25 → `Z`, 26 → `AA`). */
|
|
885
|
+
export function columnLetters(position) {
|
|
886
|
+
if (!Number.isInteger(position) || position < 0)
|
|
887
|
+
throw new FormulaError('#REF!', 'invalid column position');
|
|
888
|
+
let out = '';
|
|
889
|
+
let n = position;
|
|
890
|
+
do {
|
|
891
|
+
out = String.fromCharCode(65 + (n % 26)) + out;
|
|
892
|
+
n = Math.floor(n / 26) - 1;
|
|
893
|
+
} while (n >= 0);
|
|
894
|
+
return out;
|
|
895
|
+
}
|
|
896
|
+
/** 0-based column position for column letters (`A` → 0, `AA` → 26). */
|
|
897
|
+
export function columnPosition(letters) {
|
|
898
|
+
if (!/^[A-Za-z]{1,3}$/.test(letters))
|
|
899
|
+
throw new FormulaError('#REF!', `invalid column letters "${letters}"`);
|
|
900
|
+
let n = 0;
|
|
901
|
+
for (const ch of letters.toUpperCase())
|
|
902
|
+
n = n * 26 + (ch.charCodeAt(0) - 64);
|
|
903
|
+
return n - 1;
|
|
904
|
+
}
|
|
905
|
+
function cellRefToLong(ref, format) {
|
|
906
|
+
if (!ref.shorthand)
|
|
907
|
+
return `[${ref.colId}:${ref.rowId}]`;
|
|
908
|
+
const colId = format.colIdAt(columnPosition(ref.letters));
|
|
909
|
+
const rowId = format.rowIdAt(ref.row - 1);
|
|
910
|
+
return `[${colId}:${rowId}]`;
|
|
911
|
+
}
|
|
912
|
+
/** Precedence ranking matching the parser grammar (higher binds tighter). */
|
|
913
|
+
function precedenceOf(node) {
|
|
914
|
+
switch (node.kind) {
|
|
915
|
+
case 'binary':
|
|
916
|
+
switch (node.op) {
|
|
917
|
+
case 'or':
|
|
918
|
+
return 1;
|
|
919
|
+
case 'and':
|
|
920
|
+
return 2;
|
|
921
|
+
case '=':
|
|
922
|
+
case '<>':
|
|
923
|
+
case '>':
|
|
924
|
+
case '<':
|
|
925
|
+
case '>=':
|
|
926
|
+
case '<=':
|
|
927
|
+
return 3;
|
|
928
|
+
case '+':
|
|
929
|
+
case '-':
|
|
930
|
+
case '&':
|
|
931
|
+
return 4;
|
|
932
|
+
case '*':
|
|
933
|
+
case '/':
|
|
934
|
+
return 5;
|
|
935
|
+
case '^':
|
|
936
|
+
return 6;
|
|
937
|
+
}
|
|
938
|
+
break;
|
|
939
|
+
case 'unary':
|
|
940
|
+
return 7;
|
|
941
|
+
case 'percent':
|
|
942
|
+
return 8;
|
|
943
|
+
default:
|
|
944
|
+
return 9;
|
|
945
|
+
}
|
|
946
|
+
return 9;
|
|
947
|
+
}
|
|
948
|
+
const LEFT_ASSOC = new Set(['or', 'and', '+', '-', '&', '*', '/', '=']);
|
|
949
|
+
function serializeCellRef(ref) {
|
|
950
|
+
if (ref.shorthand) {
|
|
951
|
+
return `${ref.absCol ? '$' : ''}${ref.letters}${ref.absRow ? '$' : ''}${ref.row}`;
|
|
952
|
+
}
|
|
953
|
+
// Long-hand refs are ID-pinned and serialise without a conversion context.
|
|
954
|
+
return `[${ref.colId}:${ref.rowId}]`;
|
|
955
|
+
}
|
|
956
|
+
/** Serialise a ref to shorthand, converting long-hand through `format` when available. */
|
|
957
|
+
function serializeShorthand(ref, format) {
|
|
958
|
+
if (ref.shorthand || !format)
|
|
959
|
+
return serializeCellRef(ref);
|
|
960
|
+
// Long-hand references carry no absolute anchors — they are ID-pinned.
|
|
961
|
+
return `${columnLetters(format.positionOf(ref.colId))}${format.indexOf(ref.rowId) + 1}`;
|
|
962
|
+
}
|
|
963
|
+
function serializeNode(node, parentPrec, parentOp, isRightOperand, format, longHand = false) {
|
|
964
|
+
const prec = precedenceOf(node);
|
|
965
|
+
const parenthesise = prec < parentPrec ||
|
|
966
|
+
// Same precedence: right operand of a left-assoc op, or either operand of
|
|
967
|
+
// the right-assoc `^`, needs its own parentheses to round-trip.
|
|
968
|
+
(prec === parentPrec && ((parentOp !== null && isRightOperand && LEFT_ASSOC.has(parentOp)) || parentOp === '^'));
|
|
969
|
+
const body = () => {
|
|
970
|
+
switch (node.kind) {
|
|
971
|
+
case 'number':
|
|
972
|
+
return String(node.value);
|
|
973
|
+
case 'string':
|
|
974
|
+
return `"${node.value}"`;
|
|
975
|
+
case 'boolean':
|
|
976
|
+
return node.value ? 'TRUE' : 'FALSE';
|
|
977
|
+
case 'ref':
|
|
978
|
+
return `[${node.colId}]`;
|
|
979
|
+
case 'cell':
|
|
980
|
+
return longHand ? cellRefToLong(node.ref, format) : serializeShorthand(node.ref, format);
|
|
981
|
+
case 'range': {
|
|
982
|
+
const a = longHand ? cellRefToLong(node.start, format) : serializeShorthand(node.start, format);
|
|
983
|
+
const b = longHand ? cellRefToLong(node.end, format) : serializeShorthand(node.end, format);
|
|
984
|
+
return longHand || (!node.start.shorthand && !format) ? `${a}..${b}` : `${a}:${b}`;
|
|
985
|
+
}
|
|
986
|
+
case 'binary':
|
|
987
|
+
return `${serializeNode(node.left, prec, node.op, false, format, longHand)} ${node.op} ${serializeNode(node.right, prec, node.op, true, format, longHand)}`;
|
|
988
|
+
case 'unary':
|
|
989
|
+
return `${node.op}${serializeNode(node.operand, prec, null, false, format, longHand)}`;
|
|
990
|
+
case 'percent':
|
|
991
|
+
return `${serializeNode(node.operand, prec, null, false, format, longHand)}%`;
|
|
992
|
+
case 'call':
|
|
993
|
+
return `${node.name}(${node.args.map((a) => serializeNode(a, 0, null, false, format, longHand)).join(', ')})`;
|
|
994
|
+
}
|
|
995
|
+
};
|
|
996
|
+
return parenthesise ? `(${body()})` : body();
|
|
997
|
+
}
|
|
998
|
+
/** Serialise an AST back to shorthand (A1) text, parenthesising to preserve precedence. */
|
|
999
|
+
export function stringifyCellFormula(node, format) {
|
|
1000
|
+
return serializeNode(node, 0, null, false, format, false);
|
|
1001
|
+
}
|
|
1002
|
+
/** Serialise an AST to the long-hand storage format (col/row IDs). */
|
|
1003
|
+
export function stringifyCellFormulaLong(node, format) {
|
|
1004
|
+
return serializeNode(node, 0, null, false, format, true);
|
|
1005
|
+
}
|
|
1006
|
+
/**
|
|
1007
|
+
* Shift a formula's relative references by row/column deltas (fill handle).
|
|
1008
|
+
* Absolute (`$`) anchors never move; long-hand references are already
|
|
1009
|
+
* ID-pinned and never move.
|
|
1010
|
+
*/
|
|
1011
|
+
export function shiftFormula(params) {
|
|
1012
|
+
const { value, rowDelta = 0, columnDelta = 0, useRefFormat, format } = params;
|
|
1013
|
+
if (rowDelta === 0 && columnDelta === 0)
|
|
1014
|
+
return value;
|
|
1015
|
+
const prefixed = value.startsWith('=');
|
|
1016
|
+
let ast;
|
|
1017
|
+
try {
|
|
1018
|
+
ast = parseCellFormula(value);
|
|
1019
|
+
}
|
|
1020
|
+
catch (e) {
|
|
1021
|
+
if (e instanceof FormulaError && e.code === '#PARSE!')
|
|
1022
|
+
return value;
|
|
1023
|
+
throw e;
|
|
1024
|
+
}
|
|
1025
|
+
const shift = (ref) => {
|
|
1026
|
+
if (!ref.shorthand)
|
|
1027
|
+
return ref;
|
|
1028
|
+
if (ref.absCol && ref.absRow)
|
|
1029
|
+
return ref;
|
|
1030
|
+
const position = columnPosition(ref.letters) + (ref.absCol ? 0 : columnDelta);
|
|
1031
|
+
const row = ref.row + (ref.absRow ? 0 : rowDelta);
|
|
1032
|
+
if (position < 0 || row < 1)
|
|
1033
|
+
throw new FormulaError('#REF!', 'shifted reference leaves the grid');
|
|
1034
|
+
return { shorthand: true, letters: columnLetters(position), row, absCol: ref.absCol, absRow: ref.absRow };
|
|
1035
|
+
};
|
|
1036
|
+
const shiftNode = (n) => {
|
|
1037
|
+
switch (n.kind) {
|
|
1038
|
+
case 'cell':
|
|
1039
|
+
return { kind: 'cell', ref: shift(n.ref) };
|
|
1040
|
+
case 'range':
|
|
1041
|
+
return { kind: 'range', start: shift(n.start), end: shift(n.end) };
|
|
1042
|
+
case 'binary':
|
|
1043
|
+
return { kind: 'binary', op: n.op, left: shiftNode(n.left), right: shiftNode(n.right) };
|
|
1044
|
+
case 'unary':
|
|
1045
|
+
return { kind: 'unary', op: n.op, operand: shiftNode(n.operand) };
|
|
1046
|
+
case 'percent':
|
|
1047
|
+
return { kind: 'percent', operand: shiftNode(n.operand) };
|
|
1048
|
+
case 'call':
|
|
1049
|
+
return { kind: 'call', name: n.name, args: n.args.map(shiftNode) };
|
|
1050
|
+
default:
|
|
1051
|
+
return n;
|
|
1052
|
+
}
|
|
1053
|
+
};
|
|
1054
|
+
const shifted = shiftNode(ast);
|
|
1055
|
+
const render = (text) => (prefixed ? `=${text}` : text);
|
|
1056
|
+
if (useRefFormat) {
|
|
1057
|
+
return render(serializeNode(shifted, 0, null, false));
|
|
1058
|
+
}
|
|
1059
|
+
// Default: rewrite everything to shorthand (long-hand needs a format context).
|
|
1060
|
+
const shorthandRef = (ref) => {
|
|
1061
|
+
if (ref.shorthand)
|
|
1062
|
+
return ref;
|
|
1063
|
+
return {
|
|
1064
|
+
shorthand: true,
|
|
1065
|
+
letters: columnLetters(format.positionOf(ref.colId)),
|
|
1066
|
+
row: format.indexOf(ref.rowId) + 1,
|
|
1067
|
+
absCol: false,
|
|
1068
|
+
absRow: false,
|
|
1069
|
+
};
|
|
1070
|
+
};
|
|
1071
|
+
const toShorthand = (n) => {
|
|
1072
|
+
switch (n.kind) {
|
|
1073
|
+
case 'cell':
|
|
1074
|
+
return { kind: 'cell', ref: shorthandRef(n.ref) };
|
|
1075
|
+
case 'range':
|
|
1076
|
+
return { kind: 'range', start: shorthandRef(n.start), end: shorthandRef(n.end) };
|
|
1077
|
+
case 'binary':
|
|
1078
|
+
return { kind: 'binary', op: n.op, left: toShorthand(n.left), right: toShorthand(n.right) };
|
|
1079
|
+
case 'unary':
|
|
1080
|
+
return { kind: 'unary', op: n.op, operand: toShorthand(n.operand) };
|
|
1081
|
+
case 'percent':
|
|
1082
|
+
return { kind: 'percent', operand: toShorthand(n.operand) };
|
|
1083
|
+
case 'call':
|
|
1084
|
+
return { kind: 'call', name: n.name, args: n.args.map(toShorthand) };
|
|
1085
|
+
default:
|
|
1086
|
+
return n;
|
|
1087
|
+
}
|
|
1088
|
+
};
|
|
1089
|
+
if (format)
|
|
1090
|
+
return render(stringifyCellFormula(toShorthand(shifted)));
|
|
1091
|
+
return render(serializeNode(shifted, 0, null, false));
|
|
1092
|
+
}
|
|
1093
|
+
/**
|
|
1094
|
+
* Convert a formula between shorthand (A1) and long-hand (col/row ID) forms.
|
|
1095
|
+
* `toLong: true` → long-hand storage form; `false` → shorthand display form.
|
|
1096
|
+
* The `=` value-form prefix is preserved.
|
|
1097
|
+
*/
|
|
1098
|
+
export function convertFormula(value, format, toLong) {
|
|
1099
|
+
const prefixed = value.startsWith('=');
|
|
1100
|
+
const ast = parseCellFormula(value);
|
|
1101
|
+
const out = toLong ? stringifyCellFormulaLong(ast, format) : stringifyCellFormula(ast, format);
|
|
1102
|
+
return prefixed ? `=${out}` : out;
|
|
1103
|
+
}
|
|
1104
|
+
// One-line human descriptions for the dialog's function picker.
|
|
1105
|
+
export const FORMULA_FUNCTION_DESCRIPTIONS = {
|
|
1106
|
+
AVERAGE: 'Average of all numeric arguments',
|
|
1107
|
+
AND: 'TRUE when every argument is true',
|
|
1108
|
+
CONCAT: 'Joins all arguments into one string',
|
|
1109
|
+
COUNT: 'Counts numeric arguments',
|
|
1110
|
+
COUNTA: 'Counts non-empty arguments',
|
|
1111
|
+
COUNTBLANK: 'Counts empty arguments',
|
|
1112
|
+
COUNTIF: 'Counts range values meeting a criteria (cell ranges: Formulas)',
|
|
1113
|
+
IF: 'value_if_true when the condition is true, else value_if_false',
|
|
1114
|
+
MAX: 'Largest numeric argument',
|
|
1115
|
+
MEDIAN: 'Median of numeric arguments',
|
|
1116
|
+
MIN: 'Smallest numeric argument',
|
|
1117
|
+
NOW: 'Current date and time',
|
|
1118
|
+
NOT: 'Negates the argument',
|
|
1119
|
+
OR: 'TRUE when any argument is true',
|
|
1120
|
+
POWER: 'Raises the first argument to the power of the second',
|
|
1121
|
+
PRODUCT: 'Product of all numeric arguments',
|
|
1122
|
+
RAND: 'Random number between 0 and 1',
|
|
1123
|
+
SUM: 'Sum of all numeric arguments',
|
|
1124
|
+
SUMIF: 'Sum of range values meeting a criteria (cell ranges: Formulas)',
|
|
1125
|
+
TODAY: 'Current date at midnight',
|
|
1126
|
+
};
|
|
1127
|
+
export const FORMULA_OPERATORS = [
|
|
1128
|
+
{ op: '+', description: 'Addition (or add days to a date)' },
|
|
1129
|
+
{ op: '-', description: 'Subtraction (or subtract days from a date)' },
|
|
1130
|
+
{ op: '*', description: 'Multiplication' },
|
|
1131
|
+
{ op: '/', description: 'Division' },
|
|
1132
|
+
{ op: '^', description: 'Exponentiation' },
|
|
1133
|
+
{ op: '&', description: 'String concatenation' },
|
|
1134
|
+
{ op: '=', description: 'Equal to' },
|
|
1135
|
+
{ op: '<>', description: 'Not equal to' },
|
|
1136
|
+
{ op: '>', description: 'Greater than' },
|
|
1137
|
+
{ op: '<', description: 'Less than' },
|
|
1138
|
+
{ op: '>=', description: 'Greater than or equal' },
|
|
1139
|
+
{ op: '<=', description: 'Less than or equal' },
|
|
1140
|
+
{ op: '%', description: 'Percentage (divides by 100)' },
|
|
1141
|
+
];
|
|
1142
|
+
//# sourceMappingURL=expression.js.map
|