Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
154630c
Add description of the function argument types to the custom-function…
sequba Jan 10, 2023
fdfba73
Refactor the argument validation part of the runFunction method
sequba Jan 11, 2023
aa20522
Refactor FunctionPlugin.runFunction
sequba Jan 13, 2023
12da266
Improve formatting in file FormulaParser.ts
sequba Jan 25, 2023
937e383
Make description of MATCH function more accurate
sequba Jan 25, 2023
bd7297c
Adjust eslint jsdoc configuration
sequba Jan 26, 2023
57ea05a
Refactor runFunction
sequba Jan 27, 2023
91fe222
Refactor runFunction
sequba Feb 7, 2023
098a2c5
Make boolean functions handle empty values properly
sequba Feb 7, 2023
ef88986
Describe the features of the runFunction method in the custom-functio…
sequba Feb 7, 2023
bdd1adc
Add unit tests for handling strings by boolean functios
sequba Feb 8, 2023
a55ee51
Add typedoc strings to SimpleRangeValue class
sequba Feb 8, 2023
b90613c
Add unit test for vectorization of an array function
sequba Feb 8, 2023
f7c393c
Apply grammarly suggestions
sequba Feb 8, 2023
4185307
Fix cross-documentation references
sequba Feb 8, 2023
123fe32
Merge branch 'develop' into feature/issue-1123
sequba Feb 8, 2023
32c2c9b
Fix karma/chevrotain warnings
sequba Feb 8, 2023
f7d0670
Fix unit tests for karma
sequba Feb 8, 2023
543b469
Merge branch 'develop' into feature/issue-1123
sequba Mar 1, 2023
6d7e980
Mark MatchType argument as optional in the built-in-functions guide
sequba Mar 1, 2023
80107c0
Update custom-functions.md
sequba Mar 1, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/guide/built-in-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ Total number of functions: **{{ $page.functionsCount }}**
| FORMULATEXT | Returns a formula in a given cell as a string. | FORMULATEXT(Reference) |
| HLOOKUP | Searches horizontally with reference to adjacent cells to the bottom. | HLOOKUP(Search_Criterion, Array, Index, Sort_Order) |
| INDEX | Returns the contents of a cell specified by row and column number. The column number is optional and defaults to 1. | INDEX(Range, Row [, Column]) |
| MATCH | Returns the relative position of an item in an array that matches a specified value. | MATCH(Searchcriterion, Lookuparray, Type) |
| MATCH | Returns the relative position of an item in an array that matches a specified value. | MATCH(Searchcriterion, Lookuparray, MatchType) |

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is unrelated to this task. See: #1148 (comment)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it could be helpful to add more information about which values are accepted as MatchType and what each of them means. If MatchType is optional I think it should be mentioned as well, to keep is consistent with other functions. WDYT?

@sequba sequba Mar 1, 2023 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This description follows the general assumption that the functions work the same as in Microsoft Excel. I don't like this assumption, but currently, we do not have space for a more thorough documentation of the built-in functions.

So:

| OFFSET | Returns the value of a cell offset by a certain number of rows and columns from a given reference point. | OFFSET(Reference, Rows, Columns, Height, Width) |
| ROW | Returns row number of a given reference or formula reference if argument not provided. | ROW([Reference]) |
| ROWS | Returns the number of rows in the given reference. | ROWS(Array) |
Expand Down
18 changes: 16 additions & 2 deletions docs/guide/custom-functions.md
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,7 @@ You can set the following argument validation options:

| Option | Type | Description |
|---------------------------|-------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `argumentType` (required) | `FunctionArgumentType` | Expected type of the argument. Possible values: `STRING`, `NUMBER`, `BOOLEAN`, `SCALAR`, `NOERROR`, `RANGE`, `INTEGER`, `COMPLEX`, `ANY`. |
| `argumentType` (required) | `FunctionArgumentType` | Expected type of the function argument. See [possible values](#types-of-the-function-argument). |
| `defaultValue` | `InternalScalarValue` or `RawScalarValue` | If set: if an argument is missing, its value defaults to `defaultValue`. |
| `passSubtype` | Boolean | `true`: arguments are passed with full type information (e.g., for numbers: `Date` or `DateTime` or `Time` or `Currency` or `Percentage`).<br/>Default: `false` |
| `optionalArg` | Boolean | `true`: if an argument is missing, and no `defaultValue` is set, the argument defaults to `undefined` (instead of throwing an error).<br/>Default: `false`<br/>Setting this option to `true` is the same as setting `defaultValue` to `undefined`. |
Expand Down Expand Up @@ -395,7 +395,21 @@ MyCustomPlugin.implementedFunctions = {
};
```

#### Handling missing arguments
### Types of the function argument

| Type | Description | Example |
|-----------|----------------------------------------------------------------------------------------------------------|----------------------------------------------|
| `NUMBER` | A general numeric value such as floating-point number, date/time value, currency value or percent value. | `3`, `3.14`, `$100`, `1939/09/01`, `4:45 AM` |
| `INTEGER` | An integer. | `42` |
| `COMPLEX` | A text representing a complex value. | `"-3+4i"` |
| `STRING` | A text value. | `"aaa"` |
| `BOOLEAN` | A logical value. | `=TRUE()` |
| `NOERROR` | Any non-range and non-error value. | All of the above |
| `SCALAR` | Any non-range value. | All of the above |
| `RANGE` | Multiple values as a range of cells or an inline array. | `A1:B100`, `{1, 2}` |
| `ANY` | Any value. | All of the above |

### Handling missing arguments

Both the `defaultValue` and `optionalArg` options let you decide what happens when a user doesn't pass enough valid arguments to your custom function.

Expand Down
148 changes: 98 additions & 50 deletions src/interpreter/plugin/FunctionPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,101 +355,149 @@ export abstract class FunctionPlugin implements FunctionPluginTypecheck<Function
}
}

/**
* A method that should wrap the implementation logic for every built-in function and custom function. It:
* - evaluates the function arguments
* - validates the number of function arguments
* - performs function vectorization if necessary
* - performs argument broadcasting if necessary
* - automatic coersions
*/
protected runFunction = (
args: Ast[],
state: InterpreterState,
metadata: FunctionMetadata,
fn: (...arg: any) => InterpreterValue,
) => {
let argumentDefinitions: FunctionArgument[] = metadata.parameters || []
let argValues: [InterpreterValue, boolean][]
const evaluatedArguments: [InterpreterValue, boolean][] = this.evaluateArguments(args, state, metadata)
const argumentValues = evaluatedArguments.map(([value, _]) => value)
const argumentIgnorableFlags = evaluatedArguments.map(([_, ignorable]) => ignorable)
const argumentMetadata = this.buildMetadataForEachArgumentValue(argumentValues.length, metadata)

if (metadata.expandRanges) {
argValues = this.listOfScalarValues(args, state)
} else {
argValues = args.map((ast) => [this.evaluateAst(ast, state), false])
}

if (metadata.repeatLastArgs === undefined && argumentDefinitions.length < argValues.length) {
return new CellError(ErrorType.NA, ErrorMessage.WrongArgNumber)
}
if (metadata.repeatLastArgs !== undefined && argumentDefinitions.length < argValues.length &&
(argValues.length - argumentDefinitions.length) % metadata.repeatLastArgs !== 0) {
if (!this.isNumberOfArgumentValuesValid(argumentMetadata, argumentValues.length)) {
return new CellError(ErrorType.NA, ErrorMessage.WrongArgNumber)
}
argumentDefinitions = [...argumentDefinitions]
while (argumentDefinitions.length < argValues.length) {
argumentDefinitions.push(...argumentDefinitions.slice(argumentDefinitions.length - metadata.repeatLastArgs!))
}

let maxWidth = 1
let maxHeight = 1
if (!metadata.vectorizationForbidden && state.arraysFlag) {
for (let i = 0; i < argValues.length; i++) {
const [val] = argValues[i]
if (val instanceof SimpleRangeValue && argumentDefinitions[i].argumentType !== FunctionArgumentType.RANGE && argumentDefinitions[i].argumentType !== FunctionArgumentType.ANY) {
maxHeight = Math.max(maxHeight, val.height())
maxWidth = Math.max(maxWidth, val.width())
}
}
}

for (let i = argValues.length; i < argumentDefinitions.length; i++) {
if (argumentDefinitions[i]?.defaultValue === undefined) {
if (!argumentDefinitions[i]?.optionalArg) {
//not enough values passed as arguments, and there was no default value and argument was not optional
return new CellError(ErrorType.NA, ErrorMessage.WrongArgNumber)
}
}
}
const isVectorizationOn = state.arraysFlag && !metadata.vectorizationForbidden
const [ maxHeight, maxWidth ] = isVectorizationOn ? this.calculateSizeOfVectorizedResultArray(argumentValues, argumentMetadata) : [ 1, 1 ]

const retArr: InternalScalarValue[][] = []
for (let row = 0; row < maxHeight; row++) {
const rowArr: InternalScalarValue[] = []
for (let col = 0; col < maxWidth; col++) {

let argCoerceFailure: Maybe<CellError> = undefined
const coercedArguments: Maybe<InterpreterValue | complex | RawNoErrorScalarValue>[] = []
for (let i = 0; i < argumentDefinitions.length; i++) {
// eslint-disable-next-line prefer-const
let [val, ignorable] = argValues[i] ?? [undefined, undefined]
if (val instanceof SimpleRangeValue && argumentDefinitions[i].argumentType !== FunctionArgumentType.RANGE && argumentDefinitions[i].argumentType !== FunctionArgumentType.ANY) {
if (!metadata.vectorizationForbidden && state.arraysFlag) {
val = val.data[val.height() !== 1 ? row : 0]?.[val.width() !== 1 ? col : 0]
}
}
const arg = val ?? argumentDefinitions[i]?.defaultValue

const vectorizedArguments = this.vectorizeAndbroadcastArgumentsIfNecessary(isVectorizationOn, argumentValues, argumentMetadata, row, col)

// COERCIONS ?
for (let i = 0; i < argumentMetadata.length; i++) {
const argumentValue = vectorizedArguments[i]
const arg = argumentValue ?? argumentMetadata[i]?.defaultValue
if (arg === undefined) {
coercedArguments.push(undefined) //we verified in previous loop that this arg is optional
} else {
//we apply coerce only to non-default values
const coercedArg = val !== undefined ? this.coerceToType(arg, argumentDefinitions[i], state) : arg
const coercedArg = argumentValue !== undefined ? this.coerceToType(arg, argumentMetadata[i], state) : arg
if (coercedArg !== undefined) {
if (coercedArg instanceof CellError && argumentDefinitions[i].argumentType !== FunctionArgumentType.SCALAR) {
if (coercedArg instanceof CellError && argumentMetadata[i].argumentType !== FunctionArgumentType.SCALAR) {
//if this is first error encountered, store it
argCoerceFailure = argCoerceFailure ?? coercedArg
}
coercedArguments.push(coercedArg)
} else if (!ignorable) {
} else if (!argumentIgnorableFlags[i]) {
//if this is first error encountered, store it
argCoerceFailure = argCoerceFailure ?? (new CellError(ErrorType.VALUE, ErrorMessage.WrongType))
}
}
}

// EVALUATION
const ret = argCoerceFailure ?? this.returnNumberWrapper(fn(...coercedArguments), metadata.returnNumberType)

if (maxHeight === 1 && maxWidth === 1) {
return ret
}

if (ret instanceof SimpleRangeValue) {
throw 'Function returning array cannot be vectorized.'
throw 'Function returning array cannot be vectorized.' // test it
}

rowArr.push(ret)
}

retArr.push(rowArr)
}

return SimpleRangeValue.onlyValues(retArr)
}

private 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
)
}

private 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 ].includes(argumentMetadata.argumentType)
}

protected runFunctionWithReferenceArgument = (
args: Ast[],
state: InterpreterState,
Expand Down
Loading