diff --git a/CHANGELOG.md b/CHANGELOG.md
index 25fa6cdf9..3faad4f8e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -50,6 +50,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
- Fixed functions such as `MATCH`, `INDEX` and `COUNTIF` throwing an uncaught `Unknown array` error when they read a range that exactly matches the area of an array formula returning an error, for example `=MATCH(2, B1:B3, 0)` next to `=SORT(A1:A3)` whose source contains `#DIV/0!`. They now read the range cell by cell. [#1876](https://github.com/handsontable/hyperformula/pull/1876)
- Fixed unbounded parser cache growth in long-running instances that process many distinct formulas, including when undo is disabled. [#1635](https://github.com/handsontable/hyperformula/issues/1635)
- Fixed array formulas spilling past the `maxRows` and `maxColumns` limits: they now return `#SPILL!` when their result extends beyond the sheet edge. [#1774](https://github.com/handsontable/hyperformula/pull/1774)
+- Fixed numeric contexts reading an empty string (`""`) as `0` instead of as text (e.g. `=""+0` now returns `#VALUE!` instead of `0`), and numeric aggregations treating a parenthesized reference such as `(A1)` differently from `A1`. [#1768](https://github.com/handsontable/hyperformula/pull/1768)
+- Fixed numeric aggregations such as `SUM`, `AVERAGE` and `MAX` reading a cell reached through `INDEX`, `CHOOSE`, `IF`, `IFS`, `SWITCH`, `XLOOKUP` or a named expression as a value: as with a direct reference, its text, booleans and blanks are now ignored. [#1768](https://github.com/handsontable/hyperformula/pull/1768)
- Fixed the `ADDRESS` function adding the sheet separator (`!`) when the `sheetName` argument is an empty argument slot (e.g. `=ADDRESS(2,3,1,FALSE(),)` now returns `R2C3` instead of `!R2C3`), while an explicit `""` still adds it. [#1641](https://github.com/handsontable/hyperformula/issues/1641)
- Fixed `IMSUM`, `IMPRODUCT` and `TEXTJOIN` throwing an uncaught `RangeError` for very large ranges, such as `=IMSUM(A1:D40000)`, which stopped the recalculation; they now return a result or an error value in the cell. [#1901](https://github.com/handsontable/hyperformula/pull/1901)
diff --git a/docs/guide/list-of-differences.md b/docs/guide/list-of-differences.md
index a91ad6763..23973780c 100644
--- a/docs/guide/list-of-differences.md
+++ b/docs/guide/list-of-differences.md
@@ -39,7 +39,6 @@ A single cell that holds an error, passed as `known_x` or `new_x`, returns that
| Named expression names | ProductPrice1:=42 | A name must be distinctive from a cell reference (case-insensitive), so `ProductPrice1` is invalid. See [complete naming rules](named-expressions.md#name-rules). | A name that is a valid cell reference is allowed if the column address is at least 4-letter long, so `ProductPrice1` is valid. | A name that is a valid cell reference is allowed if the column address is at least 4-letter long, so `ProductPrice1` is valid. |
| Applying a scalar value to a function taking range | COLUMNS(A1) | `CellRangeExpected` error. | Treats the element as length-1 range. Returns 1 for the example. | Same as Google Sheets. |
| Coercion of explicit arguments | VARP(2, 3, 4, TRUE(), FALSE(), "1",) | 1.9592, based on the behavior of Microsoft Excel. | GoogleSheets implementation is not consistent with the standard (see also `VAR.S`, `STDEV.P`, and `STDEV.S` function.) | 1.9592 |
-| Empty text used as a number | =""+1
=ABS("")
=SEQUENCE("") | Empty text is converted to `0`: the examples return `1`, `0` and `#CALC!` (`SEQUENCE` with 0 rows). | Not checked. | `#VALUE!` for all three examples. |
| Ranges created with `:` | A1:A2
A$1:$A$2
A:C
1:2
Sheet1!A1:A2 | Allowed ranges consist of two addresses (A1:B5), columns (A:C) or rows (3:5).
They cannot be mixed or contain named expressions. | Everything allowed. | Same as Google Sheets. |
| Formatting inside the TEXT function | TEXT(A1,"dd-mm-yy")
TEXT(A1,"###.###”) | To support all date, time and currency formats, set [`stringifyDateTime`](compatibility-with-microsoft-excel.md#date-and-time-formats) and [`stringifyCurrency`](currency-handling.md) configuration options. | A wide variety of options for string formatting is supported. | Same as Google Sheets. |
| Cell references inside inline arrays | ={A1, A2} | The array's value is calculated but not updated when the cells' values change. | The array's value is calculated and updated when the cells' values change. | ERROR: invalid array |
@@ -58,6 +57,7 @@ A single cell that holds an error, passed as `known_x` or `new_x`, returns that
| Booleans converted to text | =CONCAT(TRUE())
=VALUETOTEXT(FALSE())
=TRUE()&"" | `TRUE` and `FALSE` in every language, in `CONCAT`, `CONCATENATE`, `TEXTJOIN`, `VALUETOTEXT` and `&`. | Not checked. | The boolean names of the Excel language, for example `PRAWDA` and `FAŁSZ` in Polish. |
| Array size limits | =SUM(VSTACK(SEQUENCE(1048576), SEQUENCE(1))) | An array computed inside a formula is not limited in either dimension, so the example returns the sum when [`maxRows`](../api/interfaces/configparams.md#maxrows) is at least 1,048,576. With the default `maxRows` (40,000), `SEQUENCE(1048576)` returns `#VALUE!`, because `SEQUENCE` is limited by the `maxRows` and [`maxColumns`](../api/interfaces/configparams.md#maxcolumns) configuration options. | In-memory arrays are not limited in either dimension. Returns `549756338177`. | In-memory arrays are limited to 1,048,576 rows and 1,048,576 columns. Returns `#NUM!`. |
| FILTER and UNIQUE near the sheet edge | =FILTER(A1:A10, A1:A10>8)
in the second-to-last row, where A1:A10 = 1 to 10 | Returns `#SPILL!`: the area reserved for the result has the height of the source, and it does not fit before the sheet edge. See [Known limitations](known-limitations.md). | Not checked. | Spills `9` and `10` into the last two rows. |
+| Text-only array argument in numeric aggregations | B1: =SUM(IF(A1:A3>0,"",A1:A3))
where A1:A3 = 1, 2, 3
=COUNT(IF({1,0},"",5)) | With the [array arithmetic mode](arrays.md#array-arithmetic-mode) disabled (the default), `IF` returns a single value, here the empty string, which is text: `SUM` returns `#VALUE!` and `COUNT` returns `0`. With the mode enabled, `IF` returns an array, and the results are `0` and `1`. | Not checked. | `IF` returns an array, and the aggregations ignore the text in it: `SUM` returns `0` and `COUNT` returns `1`. |
| TYPE of ROW or COLUMN in an expression | =TYPE(ROW(A1:A2)+0) | `ROW` over more than one row and `COLUMN` over more than one column count as arrays only when passed to `TYPE` directly, so the example gives `1`. | Not checked. | Returns `64`. |
| TYPE of a one-by-one array | =TYPE({1}+0)
=TYPE(IF(TRUE(), {1}))
=TYPE(VSTACK(A1))
where A1 holds an error | An array that holds a single value counts as an array (`64`) only when it is the argument itself: an array constant, a call to a function that returns arrays, such as `FILTER`, `SEQUENCE` or `VSTACK`, or `TRANSPOSE` of such an array. Passed through an operator or another function first, it is reduced to its value, so the first two examples give `1`. When such a function call has an error as its single value, `TYPE` gives `16`, as in the third example. | Not checked. | Returns `64` for all three examples. |
| ERROR.TYPE function | =ERROR.TYPE(#NULL!)
=ERROR.TYPE(#GETTING_DATA) | HyperFormula has no `#NULL!` or `#GETTING_DATA` error, so the codes 1 and 8 are never returned and the literals do not parse. `#CYCLE!`, `#ERROR!` and `#LIC!`, which are HyperFormula's own errors, have no code and give `#N/A`. | Not checked. | Returns `1` for `#NULL!` and `8` for `#GETTING_DATA`. |
@@ -156,8 +156,6 @@ To remove the differences, create [custom implementations](custom-functions.md)
| RANK | =RANK(2, {1, 2, 3}) | 2 | Not checked | Not accepted |
| RANK.EQ | =RANK.EQ(5, 5) | 1 | Not checked | Not accepted |
| RANK.EQ | =RANK.EQ(10, A1:A3*1)
where A1:A3: 10, 30, 20; `useArrayArithmetic: true` | 3 | Not checked | Not accepted |
-| RANK.EQ | =RANK.EQ("", A1:B2, 0)
where A1:B2: 1, 3, 2, 4 | N/A | Not checked | VALUE |
-| RANK.EQ | =RANK.EQ(2, A1:B2, "")
where A1:B2: 1, 3, 2, 4 | 3 | Not checked | VALUE |
| RANK.EQ | =RANK.EQ(2, A1:B2, "12")
where A1:B2: 1, 3, 2, 4 | 2 | Not checked | VALUE |
A few of the rows above share a root cause worth stating once:
diff --git a/docs/guide/types-of-values.md b/docs/guide/types-of-values.md
index a602176aa..8f6ad3ca2 100644
--- a/docs/guide/types-of-values.md
+++ b/docs/guide/types-of-values.md
@@ -41,6 +41,8 @@ When you pass JavaScript values directly (not as strings):
- `Date` object → **Date/DateTime type** (converted to internal numeric representation)
- `null` or `undefined` → **Empty cell**
+To empty a cell, pass `null`, not an empty string: `''` is stored as Text, so `=A1+1` returns `#VALUE!` when `A1` holds it.
+
```js
const hf = HyperFormula.buildFromArray([
[42], // Number
diff --git a/hyperformula/src/interpreter/ArithmeticHelper.ts b/hyperformula/src/interpreter/ArithmeticHelper.ts
index 2b81df42f..446f1f03e 100644
--- a/hyperformula/src/interpreter/ArithmeticHelper.ts
+++ b/hyperformula/src/interpreter/ArithmeticHelper.ts
@@ -233,14 +233,17 @@ export class ArithmeticHelper {
)
}
+ /**
+ * Coerces a scalar value to a number for use in arithmetic and numeric aggregation, without
+ * attempting date-string parsing (see {@link coerceToMaybeNumber} for that extra step).
+ *
+ * A blank cell (`EmptyValue`) reads as `0`. An empty string is text, so like any non-numeric
+ * string it returns `undefined`.
+ */
public coerceNonDateScalarToMaybeNumber(arg: InternalScalarValue): Maybe {
if (arg === EmptyValue) {
return 0
} else if (typeof arg === 'string') {
- if (arg === '') {
- return 0
- }
-
const maybePercentNumber = this.coerceStringToMaybePercentNumber(arg)
if (maybePercentNumber !== undefined) {
return maybePercentNumber
diff --git a/hyperformula/src/interpreter/plugin/BooleanPlugin.ts b/hyperformula/src/interpreter/plugin/BooleanPlugin.ts
index 38236c51d..e872f5b16 100644
--- a/hyperformula/src/interpreter/plugin/BooleanPlugin.ts
+++ b/hyperformula/src/interpreter/plugin/BooleanPlugin.ts
@@ -5,10 +5,12 @@
import {CellError, ErrorType} from '../../Cell'
import {ErrorMessage} from '../../error-message'
-import {ProcedureAst} from '../../parser'
+import {Ast, ProcedureAst} from '../../parser'
import {InterpreterState} from '../InterpreterState'
import {InternalNoErrorScalarValue, InternalScalarValue, InterpreterValue} from '../InterpreterValue'
-import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck, ImplementedFunctions} from './FunctionPlugin'
+import {SimpleRangeValue} from '../../SimpleRangeValue'
+import {FunctionArgumentType, FunctionMetadata, FunctionPlugin, FunctionPluginTypecheck, ImplementedFunctions} from './FunctionPlugin'
+import {forgetSelectedArgument, recordSelectedArgument} from './SelectedArgument'
/**
* Interpreter plugin containing boolean functions
@@ -102,6 +104,11 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec
},
}
+ /**
+ * The values of the arguments that {@link evaluateArguments} evaluated last.
+ */
+ private lastEvaluatedArguments: InterpreterValue[] = []
+
/**
* Corresponds to TRUE()
*
@@ -135,9 +142,12 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec
* @param state
*/
public conditionalIf(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
- return this.runFunction(ast.args, state, this.metadata('IF'), (condition, arg2, arg3) => {
+ forgetSelectedArgument(ast)
+ const result = this.runFunction(ast.args, state, this.metadata('IF'), (condition, arg2, arg3) => {
+ recordSelectedArgument(ast, condition ? 1 : 2)
return condition ? arg2 : arg3
})
+ return this.keepSelectionOnlyForScalarSelectors(ast, result, [0])
}
/**
@@ -147,14 +157,17 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec
* @param state
*/
public ifs(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
- return this.runFunction(ast.args, state, this.metadata('IFS'), (...args) => {
+ forgetSelectedArgument(ast)
+ const result = this.runFunction(ast.args, state, this.metadata('IFS'), (...args) => {
for (let idx = 0; idx < args.length; idx += 2) {
if (args[idx]) {
+ recordSelectedArgument(ast, idx + 1)
return args[idx+1]
}
}
return new CellError(ErrorType.NA, ErrorMessage.NoConditionMet)
})
+ return this.keepSelectionOnlyForScalarSelectors(ast, result, ast.args.map((_, i) => i).filter(i => i % 2 === 0))
}
/**
@@ -202,7 +215,8 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec
}
public switch(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
- return this.runFunction(ast.args, state, this.metadata('SWITCH'), (selector, ...args) => {
+ forgetSelectedArgument(ast)
+ const result = this.runFunction(ast.args, state, this.metadata('SWITCH'), (selector, ...args) => {
const n = args.length
let i = 0
for (; i + 1 < n; i += 2) {
@@ -210,15 +224,18 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec
continue
}
if (this.arithmeticHelper.eq(selector, args[i] as InternalNoErrorScalarValue)) {
+ recordSelectedArgument(ast, i + 2)
return args[i + 1]
}
}
if (i < n) {
+ recordSelectedArgument(ast, i + 1)
return args[i]
} else {
return new CellError(ErrorType.NA, ErrorMessage.NoDefault)
}
})
+ return this.keepSelectionOnlyForScalarSelectors(ast, result, ast.args.map((_, i) => i).filter(i => i === 0 || (i % 2 === 1 && i + 1 < ast.args.length)))
}
public iferror(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
@@ -242,11 +259,47 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec
}
public choose(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
- return this.runFunction(ast.args, state, this.metadata('CHOOSE'), (selector, ...args) => {
+ forgetSelectedArgument(ast)
+ const result = this.runFunction(ast.args, state, this.metadata('CHOOSE'), (selector: number, ...args) => {
if (selector > args.length) {
return new CellError(ErrorType.NUM, ErrorMessage.Selector)
}
+ recordSelectedArgument(ast, selector)
return args[selector - 1]
})
+ return this.keepSelectionOnlyForScalarSelectors(ast, result, [0])
+ }
+
+ /**
+ * Evaluates the arguments as {@link FunctionPlugin} does, and keeps their values until the call that evaluated
+ * them has finished, so that `IF`, `IFS`, `SWITCH` and `CHOOSE` can tell which of them were arrays without
+ * evaluating them again.
+ *
+ * @param {Ast[]} args - the arguments of the call
+ * @param {InterpreterState} state - interpreter state
+ * @param {FunctionMetadata} metadata - metadata of the function
+ * @returns {[InterpreterValue, boolean, boolean][]} what {@link FunctionPlugin} returns
+ */
+ protected evaluateArguments(args: Ast[], state: InterpreterState, metadata: FunctionMetadata): [InterpreterValue, boolean, boolean][] {
+ const evaluated = super.evaluateArguments(args, state, metadata)
+ this.lastEvaluatedArguments = evaluated.map(([value]) => value)
+ return evaluated
+ }
+
+ /**
+ * Removes the record of a call that returned an array built cell by cell, where each cell can come from a
+ * different argument: one whose condition, selector or case value is an array. An array returned from a single
+ * argument, such as `IF(TRUE(), A1:A3)` in array arithmetic mode, keeps the record of that argument.
+ *
+ * @param {ProcedureAst} ast - the call, just evaluated
+ * @param {InterpreterValue} result - what the call returned
+ * @param {number[]} selectingPositions - the positions in `ast.args` of the condition, selector and case values
+ * @returns {InterpreterValue} `result`, unchanged
+ */
+ private keepSelectionOnlyForScalarSelectors(ast: ProcedureAst, result: InterpreterValue, selectingPositions: number[]): InterpreterValue {
+ if (result instanceof SimpleRangeValue && selectingPositions.some(i => this.lastEvaluatedArguments[i] instanceof SimpleRangeValue)) {
+ forgetSelectedArgument(ast)
+ }
+ return result
}
}
diff --git a/hyperformula/src/interpreter/plugin/LookupPlugin.ts b/hyperformula/src/interpreter/plugin/LookupPlugin.ts
index 7f0b3226a..09e805696 100644
--- a/hyperformula/src/interpreter/plugin/LookupPlugin.ts
+++ b/hyperformula/src/interpreter/plugin/LookupPlugin.ts
@@ -15,6 +15,7 @@ import { InterpreterState } from '../InterpreterState'
import { EmptyValue, InternalScalarValue, InterpreterValue, RawNoErrorScalarValue } from '../InterpreterValue'
import { SimpleRangeValue } from '../../SimpleRangeValue'
import { FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck, ImplementedFunctions } from './FunctionPlugin'
+import { forgetSelectedArgument, recordSelectedArgument } from './SelectedArgument'
import { ArraySize } from '../../ArraySize'
export class LookupPlugin extends FunctionPlugin implements FunctionPluginTypecheck {
@@ -136,7 +137,10 @@ export class LookupPlugin extends FunctionPlugin implements FunctionPluginTypech
* @param state
*/
public xlookup(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
- return this.runFunction(ast.args, state, this.metadata('XLOOKUP'), (key: RawNoErrorScalarValue, lookupRangeValue: SimpleRangeValue, returnRangeValue: SimpleRangeValue, notFoundFlag: any, matchMode: number, searchMode: number) => {
+ forgetSelectedArgument(ast)
+ let lookups = 0
+ const result = this.runFunction(ast.args, state, this.metadata('XLOOKUP'), (key: RawNoErrorScalarValue, lookupRangeValue: SimpleRangeValue, returnRangeValue: SimpleRangeValue, notFoundFlag: any, matchMode: number, searchMode: number) => {
+ lookups++
if (![0, -1, 1, 2].includes(matchMode)) {
return new CellError(ErrorType.VALUE, ErrorMessage.BadMode)
}
@@ -159,8 +163,12 @@ export class LookupPlugin extends FunctionPlugin implements FunctionPluginTypech
: 'returnNotFound'
}
- return this.doXlookup(zeroIfEmpty(key), lookupRange, returnRange, notFoundFlag, isWildcardMatchMode, searchOptions)
+ return this.doXlookup(ast, zeroIfEmpty(key), lookupRange, returnRange, notFoundFlag, isWildcardMatchMode, searchOptions)
})
+ if (lookups > 1) {
+ forgetSelectedArgument(ast)
+ }
+ return result
}
public xlookupArraySize(ast: ProcedureAst): ArraySize {
@@ -282,7 +290,11 @@ export class LookupPlugin extends FunctionPlugin implements FunctionPluginTypech
return value === EmptyValue ? 0 : value
}
- private doXlookup(key: RawNoErrorScalarValue, lookupRange: SimpleRangeValue, returnRange: SimpleRangeValue, notFoundFlag: any, isWildcardMatchMode: boolean, searchOptions: SearchOptions): InterpreterValue {
+ /**
+ * Looks the key up for XLOOKUP and records which argument the result comes from: `return_array` when the key is
+ * found, `if_not_found` when it isn't and that argument is given.
+ */
+ private doXlookup(ast: ProcedureAst, key: RawNoErrorScalarValue, lookupRange: SimpleRangeValue, returnRange: SimpleRangeValue, notFoundFlag: any, isWildcardMatchMode: boolean, searchOptions: SearchOptions): InterpreterValue {
const isVerticalSearch = lookupRange.width() === 1 && returnRange.height() === lookupRange.height()
const isHorizontalSearch = lookupRange.height() === 1 && returnRange.width() === lookupRange.width()
@@ -294,9 +306,15 @@ export class LookupPlugin extends FunctionPlugin implements FunctionPluginTypech
const indexFound = this.searchInRange(key, lookupRange, isWildcardMatchMode, searchOptions, searchStrategy)
if (indexFound === -1) {
- return (notFoundFlag == ErrorType.NA) ? new CellError(ErrorType.NA, ErrorMessage.ValueNotFound) : notFoundFlag
+ if (notFoundFlag == ErrorType.NA) {
+ return new CellError(ErrorType.NA, ErrorMessage.ValueNotFound)
+ }
+ recordSelectedArgument(ast, 3)
+ return notFoundFlag
}
+ recordSelectedArgument(ast, 2)
+
const returnValues: InternalScalarValue[][] = isVerticalSearch ? [returnRange.data[indexFound]] : returnRange.data.map((row) => [row[indexFound]])
const coerced = returnValues.map((row) => row.map((value) => this.zeroIfEmptyResult(value)))
return SimpleRangeValue.onlyValues(coerced)
diff --git a/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts b/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts
index ded40f39d..83383d85f 100644
--- a/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts
+++ b/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts
@@ -16,8 +16,13 @@ import {EmptyValue, ExtendedNumber, getRawValue, InternalScalarValue, isExtended
import {SimpleRangeValue} from '../../SimpleRangeValue'
import {AverageResult} from './AverageResult'
import {MomentsAggregate} from './MomentsAggregate'
-import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck, ImplementedFunctions} from './FunctionPlugin'
+import {FunctionArgumentType, FunctionPlugin, FunctionPluginDefinition, FunctionPluginTypecheck, ImplementedFunctions} from './FunctionPlugin'
import {RangeVertex} from '../../DependencyGraph'
+import {FormulaVertex} from '../../DependencyGraph/FormulaVertex'
+import {BooleanPlugin} from './BooleanPlugin'
+import {InformationPlugin} from './InformationPlugin'
+import {LookupPlugin} from './LookupPlugin'
+import {selectedArgument} from './SelectedArgument'
export type BinaryOperation = (left: T, right: T) => T
@@ -517,6 +522,12 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function
return acc
}
+ // A parenthesized argument such as `(A1)` arrives as a PARENTHESIS node wrapping the reference.
+ // Unwrap it so that the checks below see the reference and ignore its non-numeric values.
+ while (arg.type === AstNodeType.PARENTHESIS) {
+ arg = arg.expression
+ }
+
if (arg.type === AstNodeType.CELL_RANGE || arg.type === AstNodeType.COLUMN_RANGE || arg.type === AstNodeType.ROW_RANGE) {
const val = this.evaluateRange(arg, state, initialAccValue, functionName, reducingFunction, mapFunction, coercionFunction)
if (val instanceof CellError) {
@@ -549,7 +560,7 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function
return reducingFunction(left, right)
}
}, acc)
- } else if (arg.type === AstNodeType.CELL_REFERENCE) {
+ } else if (arg.type === AstNodeType.CELL_REFERENCE || this.evaluatesToReference(arg, state)) {
value = coercionFunction(value)
if (value === undefined) {
return acc
@@ -570,6 +581,118 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function
}, initialAccValue)
}
+ /**
+ * Tells whether an argument other than a bare reference or range, which has just been evaluated,
+ * returned the content of a referenced cell, so that the aggregation ignores its non-numeric values
+ * as it does for `A1`.
+ *
+ * That holds for a parenthesized reference, a named expression defined as a reference, `INDEX`
+ * over a reference, and `IF`, `IFS`, `SWITCH`, `CHOOSE` or `XLOOKUP` whose evaluation returned one of these.
+ * These five report the argument they returned, so no argument is evaluated a second time. `XLOOKUP` returns
+ * from its `return_array`, or from `if_not_found` when nothing matches. `IFERROR` and `IFNA` are not among them:
+ * they return the value of the cell, as in Excel. `INDEX`, `IF`, `IFS`, `SWITCH`, `CHOOSE` and `XLOOKUP` count
+ * only while the built-in implementation answers for them, not a custom plugin registered over their ids.
+ *
+ * @param {Ast} arg - the argument of the aggregation, already evaluated
+ * @param {InterpreterState} state - interpreter state
+ * @returns {boolean} whether the value of `arg` is the content of a referenced cell
+ */
+ private evaluatesToReference(arg: Ast, state: InterpreterState): boolean {
+ switch (arg.type) {
+ case AstNodeType.PARENTHESIS:
+ return this.evaluatesToReference(arg.expression, state)
+ case AstNodeType.CELL_REFERENCE:
+ case AstNodeType.CELL_RANGE:
+ case AstNodeType.COLUMN_RANGE:
+ case AstNodeType.ROW_RANGE:
+ return true
+ case AstNodeType.NAMED_EXPRESSION:
+ return this.namedExpressionIsReference(arg.expressionName, state)
+ case AstNodeType.FUNCTION_CALL:
+ return this.functionCallEvaluatesToReference(arg, state)
+ default:
+ return false
+ }
+ }
+
+ /**
+ * The function-call case of {@link evaluatesToReference}: `INDEX` over a reference, and `IF`, `IFS`,
+ * `SWITCH`, `CHOOSE` or `XLOOKUP` that returned a reference.
+ *
+ * @param {ProcedureAst} ast - the function call passed to the aggregation, already evaluated
+ * @param {InterpreterState} state - interpreter state
+ * @returns {boolean} whether the function call returned the content of a referenced cell
+ */
+ private functionCallEvaluatesToReference(ast: ProcedureAst, state: InterpreterState): boolean {
+ switch (ast.procedureName) {
+ case 'INDEX':
+ return this.isBuiltIn('INDEX', InformationPlugin)
+ && ast.args.length >= 1
+ && this.evaluatesToReference(ast.args[0], state)
+ case 'IF':
+ case 'IFS':
+ case 'SWITCH':
+ case 'CHOOSE':
+ return this.isBuiltIn(ast.procedureName, BooleanPlugin) && this.selectedArgumentIsReference(ast, state)
+ case 'XLOOKUP':
+ return this.isBuiltIn('XLOOKUP', LookupPlugin) && this.selectedArgumentIsReference(ast, state)
+ default:
+ return false
+ }
+ }
+
+ /**
+ * Tells whether the argument that a call to `IF`, `IFS`, `SWITCH`, `CHOOSE` or `XLOOKUP` returned, as its
+ * plugin recorded it, evaluates to a reference.
+ *
+ * @param {ProcedureAst} ast - the function call, already evaluated
+ * @param {InterpreterState} state - interpreter state
+ * @returns {boolean} whether the call returned a reference
+ */
+ private selectedArgumentIsReference(ast: ProcedureAst, state: InterpreterState): boolean {
+ const returnedArgument = selectedArgument(ast)
+ return returnedArgument !== undefined && this.evaluatesToReference(returnedArgument, state)
+ }
+
+ /**
+ * Tells whether the built-in plugin answers for a function id, rather than a custom plugin
+ * registered over it.
+ *
+ * @param {string} functionId - the function id
+ * @param {FunctionPluginDefinition} builtInPlugin - the plugin that implements the id by default
+ * @returns {boolean} whether `builtInPlugin` is registered for `functionId`
+ */
+ private isBuiltIn(functionId: string, builtInPlugin: FunctionPluginDefinition): boolean {
+ return this.dependencyGraph.functionRegistry.getFunctionPlugin(functionId) === builtInPlugin
+ }
+
+ /**
+ * Tells whether a named expression, as seen from the formula being evaluated, is defined as a
+ * reference or a range, optionally in parentheses. Other definitions, such as `=""`, are values.
+ *
+ * @param {string} expressionName - the name used in the formula
+ * @param {InterpreterState} state - interpreter state
+ * @returns {boolean} whether the named expression is a reference
+ */
+ private namedExpressionIsReference(expressionName: string, state: InterpreterState): boolean {
+ const namedExpression = this.dependencyGraph.namedExpressions.nearestNamedExpression(expressionName, state.formulaAddress.sheet)
+ if (namedExpression === undefined) {
+ return false
+ }
+ const vertex = this.dependencyGraph.getCell(namedExpression.address)
+ if (!(vertex instanceof FormulaVertex)) {
+ return false
+ }
+ let definition = vertex.getFormula(this.dependencyGraph.lazilyTransformingAstService)
+ while (definition.type === AstNodeType.PARENTHESIS) {
+ definition = definition.expression
+ }
+ return definition.type === AstNodeType.CELL_REFERENCE
+ || definition.type === AstNodeType.CELL_RANGE
+ || definition.type === AstNodeType.COLUMN_RANGE
+ || definition.type === AstNodeType.ROW_RANGE
+ }
+
/**
* Performs range operation on given range
*
diff --git a/hyperformula/src/interpreter/plugin/SelectedArgument.ts b/hyperformula/src/interpreter/plugin/SelectedArgument.ts
new file mode 100644
index 000000000..ddc068890
--- /dev/null
+++ b/hyperformula/src/interpreter/plugin/SelectedArgument.ts
@@ -0,0 +1,51 @@
+/**
+ * @license
+ * Copyright (c) Handsoncode sp. z o.o. All rights reserved.
+ */
+
+import {Maybe} from '../../Maybe'
+import {Ast, ProcedureAst} from '../../parser'
+
+/**
+ * For a call to `IF`, `IFS`, `SWITCH`, `CHOOSE` or `XLOOKUP`, the argument that its last evaluation returned. A
+ * call that returned none of its arguments, such as one whose selector is an error or out of range, one where no
+ * condition, case or lookup value matched and no fallback was given, one that returned the default value of an
+ * omitted argument, or one that built an array cell by cell from different arguments, has no entry.
+ */
+const selectedArguments = new WeakMap()
+
+/**
+ * Returns the argument that the call to `IF`, `IFS`, `SWITCH`, `CHOOSE` or `XLOOKUP` returned when it was last
+ * evaluated, so that a function that has just evaluated the call can tell whether its result is the content of a
+ * referenced cell.
+ *
+ * @param {ProcedureAst} ast - a call to one of these functions, evaluated by its built-in plugin
+ * @returns {Maybe} the returned argument, or `undefined` when the call returned none of its arguments
+ */
+export function selectedArgument(ast: ProcedureAst): Maybe {
+ return selectedArguments.get(ast)
+}
+
+/**
+ * Removes the record of a call, before it is evaluated again or when its result comes from none of its arguments.
+ *
+ * @param {ProcedureAst} ast - the call
+ */
+export function forgetSelectedArgument(ast: ProcedureAst): void {
+ selectedArguments.delete(ast)
+}
+
+/**
+ * Records that a call returned its argument at the given position.
+ *
+ * @param {ProcedureAst} ast - the call
+ * @param {number} position - the position of the returned argument in `ast.args`
+ */
+export function recordSelectedArgument(ast: ProcedureAst, position: number): void {
+ const argument = ast.args[position]
+ if (argument === undefined) {
+ selectedArguments.delete(ast)
+ } else {
+ selectedArguments.set(ast, argument)
+ }
+}