-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathformula.js
More file actions
525 lines (477 loc) · 12.9 KB
/
formula.js
File metadata and controls
525 lines (477 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import { functions } from "./formula-functions.svelte.js";
import {
sum as arraySum,
reshape,
undefinedArgsToIdentity,
} from "./lib/helpers.js";
import {
str,
regex,
num,
seq,
alt,
forwardDeclaration,
lex,
whitespace,
EOF,
anyChar,
} from "./lib/parsers.js";
class Expression {
// Return a concrete value from an expression given the values in the other
// rows and columns.
/* v8 ignore next 3 */
compute(globals, sheet, r, c) {
throw new Error("Not yet implemented");
}
}
class ExpressionValue {
thunk;
refs;
numRefArgs;
// Everything except for ranges should pass thunks that return a singleton
// array. This is to prevent accidental flattening of list arguments while the
// reference tree is being flattened.
constructor(thunk, refs, numRefArgs = undefined) {
this.thunk = thunk;
this.refs = refs;
this.numRefArgs = numRefArgs;
if (this.numRefArgs == null) {
this.numRefArgs = arraySum(refs.map(({ numRefArgs: n }) => n));
}
}
flattenArgs() {
if (this?.refs == null) {
return this.value;
}
return (
this.refs
// Using `this` here is a hack for calling this method on arguments that
// may not be instances of ExpressionValue. `r.flattenArgs()` would be
// more correct, but does not always apply.
.map((r) => this.flattenArgs.call(r))
.flat()
// Hack for detecting stores instead of primitive values
.filter((r) => r?.subscribe != null)
);
}
flattenComputedToFunction(formulaFunctionThis) {
const computed = this;
if (computed?.refs == null) {
return (...args) => args;
}
let thunk = computed.thunk ?? ((...args) => args);
let refArgsCounts = computed.refs.map((r) => r?.numRefArgs ?? 1);
return async (...args) => {
let offset = 0;
// Call the thunk with the correct args from the flattened list. Use
// `.call` and `.apply` to pass the correct `this` value.
return await thunk.apply(
formulaFunctionThis,
(
await Promise.all(
computed.refs.map((r, i) => {
const oldOffset = offset;
offset += refArgsCounts[i];
// Recurse with the relevant portion of the flattened arguments
// list. Using `this` here is a hack for calling this method on
// arguments that may not be instances of ExpressionValue. See
// flattenArgs above as well.
return this.flattenComputedToFunction.call(
r,
formulaFunctionThis,
)(...args.slice(oldOffset, offset));
}),
)
).flat(),
);
};
}
}
function singleton(f) {
return async function (...args) {
return [await f.apply(this, args)];
};
}
class Function extends Expression {
name;
args;
constructor(name, args) {
super();
this.name = name;
this.args = Array.from(args);
}
compute(globals, sheet, r, c) {
const name = this.name.toLocaleLowerCase();
const f = functions[name];
if (f == null) {
throw new Error(`"${name}" is not a function`);
}
const refs = this.args.map((a) => a.compute(globals, sheet, r, c));
return new ExpressionValue(singleton(f), refs);
}
}
class BinaryOperation extends Expression {
static operations = {
// Arithmetic
"+": (x, y) => x + y,
"-": (x, y) => x - y,
"*": (x, y) => x * y,
"/": (x, y) => x / y,
"%": (x, y) => x % y,
"**": Math.pow,
// Logical
"!=": (x, y) => x !== y,
"==": (x, y) => x === y,
">=": (x, y) => x >= y,
">": (x, y) => x > y,
"<=": (x, y) => x <= y,
"<": (x, y) => x < y,
"&&": (x, y) => x && y,
"||": (x, y) => x || y,
"<>": (x, y) => x !== y,
"=": (x, y) => x === y,
// Bitwise
"&": (x, y) => (x >>> 0) & (y >>> 0),
"|": (x, y) => (x >>> 0) | (y >>> 0),
"^": (x, y) => (x >>> 0) ^ (y >>> 0),
">>": (x, y) => x >> y,
">>>": (x, y) => x >>> y,
"<<": (x, y) => x << y,
};
ast;
constructor(ast) {
super();
this.ast = Array.from(ast);
}
compute(globals, sheet, r, c) {
const thunk = (...args) => {
this.ast
.filter((x) => typeof x === "string")
.forEach((op) => {
const x = args.shift();
const y = args.shift();
if (typeof x[op] === "function") {
args.unshift(x[op](y));
} else if (typeof x[op]?.forward === "function") {
args.unshift(x[op].forward(y));
} else if (typeof y[op]?.reverse === "function") {
args.unshift(y[op].reverse(x));
} else {
args.unshift(BinaryOperation.operations[op](x, y));
}
});
// Note that args is a singleton list
return args;
};
const refs = this.ast
.filter((x) => x?.compute)
.map((x) => x.compute(globals, sheet, r, c));
return new ExpressionValue(undefinedArgsToIdentity(thunk), refs);
}
}
class UnaryOperation extends Expression {
static operations = {
"!": (x) => !x,
"~": (x) => ~x,
"-": (x) => -x,
};
operator;
operand;
constructor(operator, operand) {
super();
this.operator = operator;
this.operand = operand;
}
compute(globals, sheet, r, c) {
const thunk = (x) => {
if (typeof x[this.operator] === "function") {
return [x[this.operator]()];
} else {
return [UnaryOperation.operations[this.operator](x)];
}
};
const refs = [this.operand.compute(globals, sheet, r, c)];
return new ExpressionValue(undefinedArgsToIdentity(thunk), refs);
}
}
class Ref extends Expression {
s;
r;
c;
constructor(s, r, c) {
super();
this.s = s;
this.r = r;
this.c = c;
}
compute(globals, s, r, c) {
let sheet;
if (this.s == null) {
sheet = s;
} else if (this.s.relative == null) {
if (this.s.absolute < 0) {
sheet =
(this.s.absolute + globals.sheets.length) % globals.sheets.length;
} else {
sheet = this.s.absolute;
}
} else {
sheet = s + this.s.relative;
}
const rows = globals.sheets[sheet].cells;
let row;
if (this.r == null) {
row = r;
} else if (this.r.relative == null) {
if (this.r.absolute < 0) {
row = (this.r.absolute + rows.length) % rows.length;
} else {
row = this.r.absolute;
}
} else {
row = r + this.r.relative;
}
let col;
if (this.c == null) {
col = c;
} else if (this.c.relative == null) {
if (this.c.absolute < 0) {
col = (this.c.absolute + rows[0].length) % rows[0].length;
} else {
col = this.c.absolute;
}
} else {
col = c + this.c.relative;
}
return new ExpressionValue((x) => [x], [rows[row][col]], 1);
}
}
class Range extends Expression {
s;
r1;
c1;
r2;
c2;
constructor(s, r1, c1, r2, c2) {
super();
this.s = s;
this.r1 = r1;
this.c1 = c1;
this.r2 = r2;
this.c2 = c2;
}
compute(globals, s, r, c) {
let sheet;
if (this.s == null) {
sheet = s;
} else if (this.s.relative == null) {
if (this.s.absolute < 0) {
sheet =
(this.s.absolute + globals.sheets.length) % globals.sheets.length;
} else {
sheet = this.s.absolute;
}
} else {
sheet = s + this.s.relative;
}
const rows = globals.sheets[sheet].cells;
let startRow;
if (this.r1 == null) {
startRow = r;
} else if (this.r1.relative == null) {
if (this.r1.absolute < 0) {
startRow = (this.r1.absolute + rows.length) % rows.length;
} else {
startRow = this.r1.absolute;
}
} else {
startRow = r + this.r1.relative;
}
let startCol;
if (this.c1 == null) {
startCol = c;
} else if (this.c1.relative == null) {
if (this.c1.absolute < 0) {
startCol = (this.c1.absolute + rows[0].length) % rows[0].length;
} else {
startCol = this.c1.absolute;
}
} else {
startCol = c + this.c1.relative;
}
let endRow;
if (this.r2 == null) {
endRow = r;
} else if (this.r2.relative == null) {
if (this.r2.absolute < 0) {
endRow = (this.r2.absolute + rows.length) % rows.length;
} else {
endRow = this.r2.absolute;
}
} else {
endRow = r + this.r2.relative;
}
let endCol;
if (this.c2 == null) {
endCol = c;
} else if (this.c2.relative == null) {
if (this.c2.absolute < 0) {
endCol = (this.c2.absolute + rows[0].length) % rows[0].length;
} else {
endCol = this.c2.absolute;
}
} else {
endCol = c + this.c2.relative;
}
const height = Math.abs(startRow - endRow) + 1;
const width = Math.abs(startCol - endCol) + 1;
// Reshape ranges that have more than one row and column
const thunk = (...args) => [
height > 1 && width > 1 ? reshape(args, height, width) : args,
];
const refs = rows
.slice(startRow, endRow + 1)
.map((r) => r.slice(startCol, endCol + 1))
.flat();
return new ExpressionValue(thunk, refs, refs.length);
}
}
class Primitive extends Expression {
value;
constructor(n) {
super();
this.value = n;
}
compute() {
return new ExpressionValue(() => [this.value], []);
}
}
class Num extends Primitive {}
class Str extends Primitive {}
class Bool extends Primitive {}
function leftAssociativeBinOp(subparser, cls, operations) {
return lex(
seq(
subparser,
seq(alt(...operations.map(lex)), subparser)
.many()
.map((l) => l.flat()),
).map(([first, last]) => (last.length ? new cls([first, ...last]) : first)),
);
}
function rightAssociativeBinOp(subparser, cls, operations) {
let result = forwardDeclaration();
result.become(
lex(
alt(
seq(subparser, alt(...operations.map(lex)), result).map(
(x) => new cls(x),
),
subparser,
),
),
);
return result;
}
const expression = forwardDeclaration();
const name = regex(/[a-zA-Z_][a-zA-Z0-9_]*/);
const fun = seq(
name,
str("(")
.then(expression.sep_by(lex(",")).optional([]))
.skip(str(")")),
).map((args) => new Function(...args));
const cellDigits = regex(/-?\d[_\d]*/).map((x) =>
parseInt(x.replaceAll("_", "")),
);
const relNum = str("[")
.then(cellDigits)
.skip(str("]"))
.map((n) => ({ relative: n }));
const absNum = cellDigits.map((n) => ({ absolute: n }));
const cellNum = relNum.or(absNum).optional();
const r = regex(/[rR]/);
const c = regex(/[cC]/);
const s = regex(/[sS]/);
const ref = seq(
s.then(cellNum).skip(regex(/!?/)).optional(),
r.then(cellNum),
c.then(cellNum),
).map((args) => new Ref(...args));
const range = seq(
s.then(cellNum).skip(regex(/!?/)).optional(),
r.then(cellNum),
c.then(cellNum).skip(lex(":")),
r.then(cellNum),
c.then(cellNum),
).map((args) => new Range(...args));
const number = num.map((args) => new Num(args));
const stringChar = alt(
str("\\\\").map((_) => "\\"),
str('\\"').map((_) => '"'),
str("\\'").map((_) => "'"),
str("\\t").map((_) => "\t"),
str("\\n").map((_) => "\n"),
anyChar,
);
const string = alt(
whitespace
.then(str('"'))
.then(stringChar.until(str('"')).optional([]).concat())
.skip(str('"'))
.skip(whitespace)
.map((args) => new Str(args)),
whitespace
.then(str("'"))
.then(stringChar.until(str("'")).optional([]).concat())
.skip(str("'"))
.skip(whitespace)
.map((args) => new Str(args)),
);
const logic = forwardDeclaration();
const value = lex(
alt(
lex(number),
lex(string),
lex(fun),
lex(ref),
lex("true").map((_) => new Bool(true)),
lex("false").map((_) => new Bool(false)),
lex("(").then(logic).skip(lex(")")),
),
);
const unary = forwardDeclaration();
unary.become(
lex(
alt(
seq(alt(...Object.keys(UnaryOperation.operations).map(lex)), unary).map(
(args) => new UnaryOperation(...args),
),
value,
),
),
);
const power = rightAssociativeBinOp(unary, BinaryOperation, ["**"]);
const product = leftAssociativeBinOp(power, BinaryOperation, ["*", "/", "%"]);
const sum = leftAssociativeBinOp(product, BinaryOperation, ["+", "-"]);
const shift = leftAssociativeBinOp(sum, BinaryOperation, ["<<", ">>>", ">>"]);
const relational = leftAssociativeBinOp(shift, BinaryOperation, [
"<=",
"<",
">=",
">",
]);
const equality = leftAssociativeBinOp(relational, BinaryOperation, [
"==",
"!=",
"=",
"<>",
]);
const bitwiseAnd = leftAssociativeBinOp(equality, BinaryOperation, ["&"]);
const bitwiseXor = leftAssociativeBinOp(bitwiseAnd, BinaryOperation, ["^"]);
const bitwiseOr = leftAssociativeBinOp(bitwiseXor, BinaryOperation, ["|"]);
const logicalAnd = leftAssociativeBinOp(bitwiseOr, BinaryOperation, ["&&"]);
const logicalOr = leftAssociativeBinOp(logicalAnd, BinaryOperation, ["||"]);
logic.become(logicalOr);
expression.become(alt(lex(range), logic));
export const formula = alt(str("=").then(expression), number).skip(EOF);