forked from handsontable/hyperformula
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctionPlugin.ts
More file actions
601 lines (514 loc) · 20.8 KB
/
Copy pathFunctionPlugin.ts
File metadata and controls
601 lines (514 loc) · 20.8 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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
/**
* @license
* Copyright (c) 2025 Handsoncode. All rights reserved.
*/
import {AbsoluteCellRange} from '../../AbsoluteCellRange'
import {ArraySize, ArraySizePredictor} from '../../ArraySize'
import {CellError, ErrorType, SimpleCellAddress} from '../../Cell'
import {Config} from '../../Config'
import {DateTimeHelper} from '../../DateTimeHelper'
import {DependencyGraph} from '../../DependencyGraph'
import {ErrorMessage} from '../../error-message'
import {SearchStrategy} from '../../Lookup/SearchStrategy'
import {Maybe} from '../../Maybe'
import {Ast, AstNodeType, ProcedureAst} from '../../parser'
import {Serialization} from '../../Serialization'
import {
ArithmeticHelper,
coerceRangeToScalar,
coerceScalarToBoolean,
coerceScalarToString,
coerceToRange,
complex
} from '../ArithmeticHelper'
import {Interpreter} from '../Interpreter'
import {InterpreterState} from '../InterpreterState'
import {
EmptyValue,
ExtendedNumber,
FormatInfo,
getRawValue,
InternalScalarValue,
InterpreterValue,
isExtendedNumber,
NumberType, RawInterpreterValue,
RawNoErrorScalarValue,
RawScalarValue
} from '../InterpreterValue'
import {SimpleRangeValue} from '../../SimpleRangeValue'
export interface ImplementedFunctions {
[formulaId: string]: FunctionMetadata,
}
export interface FunctionMetadata {
/**
* Internal and engine.
*/
parameters?: FunctionArgument[],
/**
* Internal.
*
* For functions with a variable number of arguments: sets how many last arguments can be repeated indefinitely.
*/
repeatLastArgs?: number,
/**
* Internal.
*
* If set to `true`, ranges in the function's arguments are inlined to (possibly multiple) scalar arguments.
*/
expandRanges?: boolean,
/**
* Internal.
*
* Return number value is packed into this subtype.
*/
returnNumberType?: NumberType,
/**
* Engine.
*/
method: string,
/**
* Engine.
*
* Name of the method that calculates the size of the result array. Not required for functions that never return an array.
*/
sizeOfResultArrayMethod?: string,
/**
* Engine.
*
* If set to `true`, the function is volatile.
*/
isVolatile?: boolean,
/**
* Engine.
*
* If set to `true`, the function gets recalculated with each sheet shape change
* (e.g., when adding/removing rows or columns).
*/
isDependentOnSheetStructureChange?: boolean,
/**
* Engine.
*
* If set to `true`, the function treats reference or range arguments as arguments that don't create dependency.
*
* Other arguments are properly evaluated.
*/
doesNotNeedArgumentsToBeComputed?: boolean,
/**
* Engine.
*
* If set to `true`, the function enables the array arithmetic mode in its arguments and nested expressions.
*/
enableArrayArithmeticForArguments?: boolean,
/**
* Internal.
*
* If set to `true`, prevents the function from ever being vectorized.
*
* Some functions do not allow vectorization: array-output, and special functions.
*/
vectorizationForbidden?: boolean,
/**
* Engine.
*
* @deprecated since 3.1.0; Use `enableArrayArithmeticForArguments` instead.
*/
arrayFunction?: boolean,
/**
* Engine.
*
* @deprecated since 3.1.0; Use `sizeOfResultArrayMethod` instead.
*/
arraySizeMethod?: string,
}
export interface FunctionPluginDefinition {
implementedFunctions: ImplementedFunctions,
aliases?: { [formulaId: string]: string },
new(interpreter: Interpreter): FunctionPlugin,
}
export enum FunctionArgumentType {
/**
* String type.
*/
STRING = 'STRING',
/**
* Floating point type.
*/
NUMBER = 'NUMBER',
/**
* Boolean type.
*/
BOOLEAN = 'BOOLEAN',
/**
* Any non-range value.
*/
SCALAR = 'SCALAR',
/**
* Any non-range, no-error type.
*/
NOERROR = 'NOERROR',
/**
* Range type.
*/
RANGE = 'RANGE',
/**
* Integer type.
*/
INTEGER = 'INTEGER',
/**
* String representing complex number.
*/
COMPLEX = 'COMPLEX',
/**
* Range or scalar.
*/
ANY = 'ANY',
}
export interface FunctionArgument {
argumentType: FunctionArgumentType,
/**
* If set to `true`, arguments need to be passed with full type information.
* (e.g., for numbers: `Date` or `DateTime` or `Time` or `Currency` or `Percentage`)
*/
passSubtype?: boolean,
/**
* If an argument is missing, its value defaults to `defaultValue`.
*/
defaultValue?: InternalScalarValue | RawScalarValue,
/**
* If set to `true`:
* if an argument is missing, and no `defaultValue` is set, the argument is `undefined` (instead of throwing an error).
*
* This is logically equivalent to setting `defaultValue` to `undefined`.
*/
optionalArg?: boolean,
/**
* If set, numerical arguments need to be greater than or equal to `minValue`.
*/
minValue?: number,
/**
* If set, numerical arguments need to be less than or equal to `maxValue`.
*/
maxValue?: number,
/**
* If set, numerical arguments need to be less than `lessThan`.
*/
lessThan?: number,
/**
* If set, numerical arguments need to be greater than `greaterThan`.
*/
greaterThan?: number,
}
export type PluginFunctionType = (ast: ProcedureAst, state: InterpreterState) => InterpreterValue
export type PluginArraySizeFunctionType = (ast: ProcedureAst, state: InterpreterState) => ArraySize
export type FunctionPluginTypecheck<T> = {
[K in keyof T]: T[K] extends PluginFunctionType | PluginArraySizeFunctionType ? T[K] : never
}
/**
* Abstract class representing interpreter function plugin.
* Plugin may contain multiple functions. Each function should be of type {@link PluginFunctionType} and needs to be
* included in {@link implementedFunctions}
*/
export abstract class FunctionPlugin implements FunctionPluginTypecheck<FunctionPlugin> {
/**
* Dictionary containing functions implemented by specific plugin, along with function name translations.
*/
public static implementedFunctions: ImplementedFunctions
public static aliases?: { [formulaId: string]: string }
protected readonly interpreter: Interpreter
protected readonly dependencyGraph: DependencyGraph
protected readonly columnSearch: SearchStrategy
protected readonly config: Config
protected readonly serialization: Serialization
protected readonly arraySizePredictor: ArraySizePredictor
protected readonly dateTimeHelper: DateTimeHelper
protected readonly arithmeticHelper: ArithmeticHelper
constructor(interpreter: Interpreter) {
this.interpreter = interpreter
this.dependencyGraph = interpreter.dependencyGraph
this.columnSearch = interpreter.columnSearch
this.config = interpreter.config
this.serialization = interpreter.serialization
this.arraySizePredictor = interpreter.arraySizePredictor
this.dateTimeHelper = interpreter.dateTimeHelper
this.arithmeticHelper = interpreter.arithmeticHelper
}
protected evaluateAst(ast: Ast, state: InterpreterState): InterpreterValue {
return this.interpreter.evaluateAst(ast, state)
}
protected arraySizeForAst(ast: Ast, state: InterpreterState): ArraySize {
return this.arraySizePredictor.checkArraySizeForAst(ast, state)
}
protected listOfScalarValues(asts: Ast[], state: InterpreterState): [InternalScalarValue, boolean][] {
const ret: [InternalScalarValue, boolean][] = []
for (const argAst of asts) {
const value = this.evaluateAst(argAst, state)
if (value instanceof SimpleRangeValue) {
for (const scalarValue of value.valuesFromTopLeftCorner()) {
ret.push([scalarValue, true])
}
} else {
ret.push([value, false])
}
}
return ret
}
protected coerceScalarToNumberOrError = (arg: InternalScalarValue): ExtendedNumber | CellError => this.arithmeticHelper.coerceScalarToNumberOrError(arg)
protected coerceToType(arg: InterpreterValue, coercedType: FunctionArgument, state: InterpreterState): Maybe<InterpreterValue | complex | RawNoErrorScalarValue> {
let ret
if (arg instanceof SimpleRangeValue) {
switch (coercedType.argumentType) {
case FunctionArgumentType.RANGE:
case FunctionArgumentType.ANY:
ret = arg
break
default: {
const coerce = coerceRangeToScalar(arg, state)
if (coerce === undefined) {
return undefined
}
arg = coerce
}
}
}
if (!(arg instanceof SimpleRangeValue)) {
switch (coercedType.argumentType) {
case FunctionArgumentType.INTEGER:
case FunctionArgumentType.NUMBER:
// eslint-disable-next-line no-case-declarations
const coerced = this.coerceScalarToNumberOrError(arg)
if (!isExtendedNumber(coerced)) {
ret = coerced
break
}
// eslint-disable-next-line no-case-declarations
const value = getRawValue(coerced)
if (coercedType.maxValue !== undefined && value > coercedType.maxValue) {
return new CellError(ErrorType.NUM, ErrorMessage.ValueLarge)
}
if (coercedType.minValue !== undefined && value < coercedType.minValue) {
return new CellError(ErrorType.NUM, ErrorMessage.ValueSmall)
}
if (coercedType.lessThan !== undefined && value >= coercedType.lessThan) {
return new CellError(ErrorType.NUM, ErrorMessage.ValueLarge)
}
if (coercedType.greaterThan !== undefined && value <= coercedType.greaterThan) {
return new CellError(ErrorType.NUM, ErrorMessage.ValueSmall)
}
if (coercedType.argumentType === FunctionArgumentType.INTEGER && !Number.isInteger(value)) {
return new CellError(ErrorType.NUM, ErrorMessage.IntegerExpected)
}
ret = coerced
break
case FunctionArgumentType.STRING:
ret = coerceScalarToString(arg)
break
case FunctionArgumentType.BOOLEAN:
ret = coerceScalarToBoolean(arg)
break
case FunctionArgumentType.SCALAR:
case FunctionArgumentType.NOERROR:
case FunctionArgumentType.ANY:
ret = arg
break
case FunctionArgumentType.RANGE:
if (arg instanceof CellError) {
return arg
}
ret = coerceToRange(arg)
break
case FunctionArgumentType.COMPLEX:
return this.arithmeticHelper.coerceScalarToComplex(getRawValue(arg))
}
}
if (coercedType.passSubtype || ret === undefined) {
return ret
} else {
return getRawValue(ret)
}
}
/**
* A method that should wrap the logic of every built-in function and custom function. It:
* - Evaluates the function's arguments.
* - Validates the number of arguments against the [`parameters` array](#function-options).
* - Coerces the argument values to types set in the [`parameters` array](#argument-validation-options).
* - Handles optional arguments and default values according to options set in the [`parameters` array](#argument-validation-options).
* - Validates the function's arguments against the [argument validation options](#argument-validation-options).
* - Duplicates the arguments according to the [`repeatLastArgs` option](#function-options).
* - Handles the [array arithmetic mode](arrays.md#array-arithmetic-mode).
* - Performs [function vectorization](arrays.md#passing-arrays-to-scalar-functions-vectorization).
* - Performs [argument broadcasting](arrays.md#broadcasting).
*/
protected runFunction = (
args: Ast[],
state: InterpreterState,
metadata: FunctionMetadata,
functionImplementation: (...arg: any) => InterpreterValue,
): RawInterpreterValue => {
const evaluatedArguments: [InterpreterValue, boolean][] = this.evaluateArguments(args, state, metadata)
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const argumentValues: InterpreterValue[] = evaluatedArguments.map(([value, _]: [InterpreterValue, boolean]) => value as InterpreterValue)
const argumentIgnorableFlags = evaluatedArguments.map(([_, ignorable]) => ignorable)
const argumentMetadata = this.buildMetadataForEachArgumentValue(argumentValues.length, metadata)
const isVectorizationOn = state.arraysFlag && !metadata.vectorizationForbidden
if (!this.isNumberOfArgumentValuesValid(argumentMetadata, argumentValues.length)) {
return new CellError(ErrorType.NA, ErrorMessage.WrongArgNumber)
}
const [ resultArrayHeight, resultArrayWidth ] = isVectorizationOn ? this.calculateSizeOfVectorizedResultArray(argumentValues, argumentMetadata) : [ 1, 1 ]
if (resultArrayHeight === 1 && resultArrayWidth === 1) {
const vectorizedArguments = this.vectorizeAndBroadcastArgumentsIfNecessary(isVectorizationOn, argumentValues, argumentMetadata, 0, 0)
return this.calculateSingleCellOfResultArray(state, vectorizedArguments, argumentMetadata, argumentIgnorableFlags, functionImplementation, metadata.returnNumberType)
}
const resultArray: InternalScalarValue[][] = [ ...Array(resultArrayHeight).keys() ].map(row =>
[ ...Array(resultArrayWidth).keys() ].map(col => {
const vectorizedArguments = this.vectorizeAndBroadcastArgumentsIfNecessary(isVectorizationOn, argumentValues, argumentMetadata, row, col)
const result = this.calculateSingleCellOfResultArray(state, vectorizedArguments, argumentMetadata, argumentIgnorableFlags, functionImplementation, metadata.returnNumberType)
if (result instanceof SimpleRangeValue) {
throw new Error('Function returning array cannot be vectorized.')
}
return result
})
)
return SimpleRangeValue.onlyValues(resultArray)
}
protected calculateSingleCellOfResultArray(
state: InterpreterState,
vectorizedArguments: Maybe<InterpreterValue>[],
argumentsMetadata: FunctionArgument[],
argumentIgnorableFlags: boolean[],
functionImplementation: (...arg: any) => InterpreterValue,
returnNumberType: NumberType | undefined,
): RawInterpreterValue {
const coercedArguments = this.coerceArgumentsToRequiredTypes(state, vectorizedArguments, argumentsMetadata, argumentIgnorableFlags)
if (coercedArguments instanceof CellError) {
return coercedArguments
}
const functionCalculationResult = functionImplementation(...(coercedArguments as any[]))
return this.returnNumberWrapper(functionCalculationResult, returnNumberType) as RawInterpreterValue
}
protected coerceArgumentsToRequiredTypes(
state: InterpreterState,
vectorizedArguments: Maybe<InterpreterValue>[],
argumentsMetadata: FunctionArgument[],
argumentIgnorableFlags: boolean[],
): CellError | Maybe<InterpreterValue | complex | RawNoErrorScalarValue>[] {
const coercedArguments: Maybe<InterpreterValue | complex | RawNoErrorScalarValue>[] = []
for (let i = 0; i < argumentsMetadata.length; i++) {
const argumentMetadata = argumentsMetadata[i]
const rawArg = vectorizedArguments[i]
const argumentValue = (rawArg === undefined)
? argumentMetadata?.defaultValue
: (rawArg === EmptyValue && argumentMetadata?.defaultValue !== undefined)
? argumentMetadata.defaultValue
: rawArg
if (argumentValue === undefined) {
coercedArguments.push(undefined)
continue
}
const coercedValue = this.coerceToType(argumentValue, argumentMetadata, state)
if (coercedValue === undefined && !argumentIgnorableFlags[i]) {
return new CellError(ErrorType.VALUE, ErrorMessage.WrongType)
}
if (coercedValue instanceof CellError && argumentMetadata.argumentType !== FunctionArgumentType.SCALAR) {
return coercedValue
}
coercedArguments.push(coercedValue)
}
return coercedArguments
}
protected vectorizeAndBroadcastArgumentsIfNecessary(isVectorizationOn: boolean, argumentValues: InterpreterValue[], argumentMetadata: FunctionArgument[], row: number, col: number): Maybe<InterpreterValue>[] {
return argumentValues.map((value, i) =>
isVectorizationOn && this.isRangePassedAsAScalarArgument(value, argumentMetadata[i])
? this.vectorizeAndBroadcastRangeArgument(value, row, col)
: value
)
}
protected vectorizeAndBroadcastRangeArgument(argumentValue: SimpleRangeValue, rowNum: number, colNum: number): Maybe<InterpreterValue> {
const targetRowNum = argumentValue.height() === 1 ? 0 : rowNum
const targetColNum = argumentValue.width() === 1 ? 0 : colNum
return argumentValue.data[targetRowNum]?.[targetColNum]
}
protected evaluateArguments(args: Ast[], state: InterpreterState, metadata: FunctionMetadata): [InterpreterValue, boolean][] {
return metadata.expandRanges ? this.listOfScalarValues(args, state) : args.map((ast) => [this.evaluateAst(ast, state), false])
}
protected buildMetadataForEachArgumentValue(numberOfArgumentValuesPassed: number, metadata: FunctionMetadata): FunctionArgument[] {
const argumentsMetadata: FunctionArgument[] = metadata.parameters ? [ ...metadata.parameters ] : []
const isRepeatLastArgsValid = metadata.repeatLastArgs !== undefined && Number.isInteger(metadata.repeatLastArgs) && metadata.repeatLastArgs > 0
if (isRepeatLastArgsValid) {
while (numberOfArgumentValuesPassed > argumentsMetadata.length) {
argumentsMetadata.push(...argumentsMetadata.slice(argumentsMetadata.length - metadata.repeatLastArgs!))
}
}
return argumentsMetadata
}
protected isNumberOfArgumentValuesValid(argumentsMetadata: FunctionArgument[], numberOfArgumentValuesPassed: number): boolean {
if (numberOfArgumentValuesPassed > argumentsMetadata.length) {
return false
}
if (numberOfArgumentValuesPassed < argumentsMetadata.length) {
const metadataForMissingArguments = argumentsMetadata.slice(numberOfArgumentValuesPassed)
const areMissingArgumentsOptional = metadataForMissingArguments.every(argMetadata => argMetadata?.optionalArg || argMetadata?.defaultValue !== undefined)
return areMissingArgumentsOptional
}
return true
}
protected calculateSizeOfVectorizedResultArray(argumentValues: InterpreterValue[], argumentMetadata: FunctionArgument[]): [ number, number ] {
const argumentsThatRequireVectorization = argumentValues
.filter((value, i) => this.isRangePassedAsAScalarArgument(value, argumentMetadata[i])) as SimpleRangeValue[]
const height = Math.max(1, ...argumentsThatRequireVectorization.map(val => val.height()))
const width = Math.max(1, ...argumentsThatRequireVectorization.map(val => val.width()))
return [ height, width ]
}
protected isRangePassedAsAScalarArgument(argumentValue: Maybe<InterpreterValue>, argumentMetadata: Maybe<FunctionArgument>): argumentValue is SimpleRangeValue {
if (argumentValue == null || argumentMetadata == null) {
return false
}
return argumentValue instanceof SimpleRangeValue
&& !([ FunctionArgumentType.RANGE, FunctionArgumentType.ANY ] as FunctionArgumentType[]).includes(argumentMetadata.argumentType)
}
protected runFunctionWithReferenceArgument = (
args: Ast[],
state: InterpreterState,
metadata: FunctionMetadata,
noArgCallback: () => InternalScalarValue,
referenceCallback: (reference: SimpleCellAddress) => InternalScalarValue,
nonReferenceCallback: (...arg: any) => InternalScalarValue = () => new CellError(ErrorType.NA, ErrorMessage.CellRefExpected)
) => {
if (args.length === 0) {
return this.returnNumberWrapper(noArgCallback(), metadata.returnNumberType)
} else if (args.length > 1) {
return new CellError(ErrorType.NA, ErrorMessage.WrongArgNumber)
}
let arg = args[0]
while (arg.type === AstNodeType.PARENTHESIS) {
arg = arg.expression
}
let cellReference: Maybe<SimpleCellAddress>
if (arg.type === AstNodeType.CELL_REFERENCE) {
cellReference = arg.reference.toSimpleCellAddress(state.formulaAddress)
} else if (arg.type === AstNodeType.CELL_RANGE || arg.type === AstNodeType.COLUMN_RANGE || arg.type === AstNodeType.ROW_RANGE) {
try {
cellReference = AbsoluteCellRange.fromAst(arg, state.formulaAddress).start
} catch (e) {
return new CellError(ErrorType.REF, ErrorMessage.CellRefExpected)
}
}
if (cellReference !== undefined) {
return this.returnNumberWrapper(referenceCallback(cellReference), metadata.returnNumberType)
}
return this.runFunction(args, state, metadata, nonReferenceCallback)
}
protected metadata(name: string): FunctionMetadata {
const params = (this.constructor as FunctionPluginDefinition).implementedFunctions[name]
if (params !== undefined) {
return params
}
throw new Error(`No metadata for function ${name}.`)
}
protected returnNumberWrapper<T>(val: T | ExtendedNumber, type?: NumberType, format?: FormatInfo): T | ExtendedNumber {
if (type !== undefined && isExtendedNumber(val)) {
return this.arithmeticHelper.ExtendedNumberFactory(getRawValue(val), {type, format})
} else {
return val
}
}
}