From 2fa0930bbdd39be56d366be247d2f9a612fa5035 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 10 Sep 2026 12:06:57 +0000 Subject: [PATCH 01/20] Fix HF-361: empty string no longer coerces to 0 `ArithmeticHelper#coerceNonDateScalarToMaybeNumber` special-cased an empty string ('') to coerce to 0, the same as a truly blank cell (EmptyValue). This is a different case from EmptyValue -- a cell or literal holding '' is text, not blank -- and it made HyperFormula diverge from Excel in two ways: - Arithmetic on '' returned 0 instead of #VALUE! (e.g. `=""+0`). - COUNT("") returned 1 instead of 0, since the literal argument was coerced to 0 (an ExtendedNumber) before COUNT's own isExtendedNumber predicate ever saw it. Root cause: - Interpreter.ts `plusOp`/`minusOp`/etc. call `ArithmeticHelper#coerceScalarToNumberOrError`, which returned 0 for '' before this fix. - NumericAggregationPlugin#reduce (used by COUNT, SUM, AVERAGE, PRODUCT, MIN, MAX) calls the same coercion for a literal/expression argument (as opposed to a direct cell reference, which uses the aggregation's own predicate without numeric coercion) -- so COUNT("") went through the same 0-producing bug before isExtendedNumber(0) counted it. This removes the `arg === ''` special case, letting '' fall through to the normal string-to-number parsing (which correctly fails for non-numeric text), matching how HyperFormula already treats any other non-numeric string literal (e.g. `SUM("abc")` already returned #VALUE!; `SUM("")` was the sole inconsistent exception). Not affected (verified with tests): blank cells (EmptyValue) still coerce to 0 in arithmetic and are still governed separately by `evaluateNullToZero`; a '' criterion in COUNTIF/SUMIF-style functions still matches only genuinely blank cells (Criterion.ts resolves that case before any numeric coercion runs). This is a breaking change. Co-Authored-By: Claude Sonnet 5 --- CHANGELOG.md | 1 + src/interpreter/ArithmeticHelper.ts | 13 +- test/hf-361-empty-string-coercion.spec.ts | 261 ++++++++++++++++++++++ 3 files changed, 271 insertions(+), 4 deletions(-) create mode 100644 test/hf-361-empty-string-coercion.spec.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index aeea8dd511..64544418d2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Fixed +- **Breaking change**: Fixed an empty string (`''`) being silently coerced to `0` in arithmetic operations and in any function argument that expects a number, which made results differ from Excel (e.g. `=""+0` returned `0` instead of the `#VALUE!` error, and `COUNT("")` returned `1` instead of `0`). This does not affect blank cells, which keep coercing to `0` as before. (HF-361) - Fixed the `AVERAGEIF` function returning a division-by-zero error when the calculated average was `0`. [#1733](https://github.com/handsontable/hyperformula/pull/1733) - Fixed the localized names of `VSTACK` and `HSTACK` in 14 language packs to match Microsoft Excel. [#1748](https://github.com/handsontable/hyperformula/pull/1748) - Fixed the MAXPOOL and MEDIANPOOL functions throwing an uncaught `TypeError` instead of returning the `#VALUE!` error when the range dimensions are not a whole multiple of the window size and the stride. [#1718](https://github.com/handsontable/hyperformula/pull/1718) diff --git a/src/interpreter/ArithmeticHelper.ts b/src/interpreter/ArithmeticHelper.ts index 73719a60fb..ff12344e46 100644 --- a/src/interpreter/ArithmeticHelper.ts +++ b/src/interpreter/ArithmeticHelper.ts @@ -222,14 +222,19 @@ 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). + * + * An empty string (`''`) is deliberately *not* coerced to `0` here: it is a text value, not a + * blank cell (that case is `EmptyValue`, handled above), so it is left for the caller to reject + * as non-numeric — matching how Excel treats `""` as text in arithmetic and numeric + * functions (`=""+0` and `=COUNT("")` both fail to find a number in Excel). + */ 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/test/hf-361-empty-string-coercion.spec.ts b/test/hf-361-empty-string-coercion.spec.ts new file mode 100644 index 0000000000..90404ac963 --- /dev/null +++ b/test/hf-361-empty-string-coercion.spec.ts @@ -0,0 +1,261 @@ +import {HyperFormula} from '../src' +import {ErrorType} from '../src/Cell' +import {DetailedCellError} from '../src/CellValue' + +/** + * HF-361: an empty string ('') must not be silently coerced to 0. + * + * Excel treats '' as ordinary text: it is not a valid number, so arithmetic on it fails with + * #VALUE! and COUNT (which only counts numbers) does not count it. HyperFormula used to special-case + * '' to 0 inside ArithmeticHelper#coerceNonDateScalarToMaybeNumber, which is a different code path + * from a genuinely blank cell (`EmptyValue`, governed separately by `evaluateNullToZero`). + */ +describe('HF-361: empty string is not coerced to 0', () => { + it('COUNT of a literal empty string does not count it as numeric', () => { + const hf = HyperFormula.buildFromArray([['=COUNT("")']], {licenseKey: 'gpl-v3'}) + + expect(hf.getCellValue({sheet: 0, col: 0, row: 0})).toBe(0) + + hf.destroy() + }) + + it('COUNT of a cell holding an empty string (via ="") does not count it as numeric', () => { + const hf = HyperFormula.buildFromArray([['=""', '=COUNT(A1)']], {licenseKey: 'gpl-v3'}) + + expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBe(0) + + hf.destroy() + }) + + it('COUNT of a cell holding a raw empty string (a text cell, not a blank one) does not count it', () => { + const hf = HyperFormula.buildFromArray([['', '=COUNT(A1)']], {licenseKey: 'gpl-v3'}) + + expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBe(0) + + hf.destroy() + }) + + it('adding a literal empty string to a number is #VALUE!, matching Excel', () => { + const hf = HyperFormula.buildFromArray([['=""+0']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('adding a number to an empty string is #VALUE!', () => { + const hf = HyperFormula.buildFromArray([['=""+1']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('subtracting a number from an empty string is #VALUE!', () => { + const hf = HyperFormula.buildFromArray([['=""-1']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('multiplying an empty string is #VALUE!', () => { + const hf = HyperFormula.buildFromArray([['=""*1']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('dividing an empty string is #VALUE!', () => { + const hf = HyperFormula.buildFromArray([['=""/1']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('negating an empty string is #VALUE!', () => { + const hf = HyperFormula.buildFromArray([['=-""']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('raising a number to the power of an empty string is #VALUE!', () => { + const hf = HyperFormula.buildFromArray([['=1^""']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('a text cell holding an empty string behaves the same as the literal in arithmetic', () => { + const hf = HyperFormula.buildFromArray([['', '=A1+0']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 1, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('SUM of a literal empty string is #VALUE!, consistent with other non-numeric text', () => { + const hf = HyperFormula.buildFromArray([['=SUM("")']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('AVERAGE of a literal empty string is #VALUE!', () => { + const hf = HyperFormula.buildFromArray([['=AVERAGE("")']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('PRODUCT of a literal empty string is #VALUE!', () => { + const hf = HyperFormula.buildFromArray([['=PRODUCT("")']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('MIN of a literal empty string is #VALUE!', () => { + const hf = HyperFormula.buildFromArray([['=MIN("")']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('MAX of a literal empty string is #VALUE!', () => { + const hf = HyperFormula.buildFromArray([['=MAX("")']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('SUM of other non-numeric literal text is #VALUE! too (baseline, unaffected by this fix)', () => { + const hf = HyperFormula.buildFromArray([['=SUM("abc")']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('ROUND rejects a literal empty string for its NUMBER-typed argument', () => { + const hf = HyperFormula.buildFromArray([['=ROUND("",1)']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) + + it('POWER rejects a literal empty string for its NUMBER-typed argument', () => { + const hf = HyperFormula.buildFromArray([['=POWER("",2)']], {licenseKey: 'gpl-v3'}) + + const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError + + expect(result.type).toBe(ErrorType.VALUE) + + hf.destroy() + }) +}) + +describe('HF-361: unaffected — blank cells (EmptyValue) keep their existing behavior', () => { + it('a truly blank cell still coerces to 0 in arithmetic (evaluateNullToZero: false)', () => { + const hf = HyperFormula.buildFromArray([[null, '=A1+1']], {licenseKey: 'gpl-v3', evaluateNullToZero: false}) + + expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBe(1) + + hf.destroy() + }) + + it('a truly blank cell still coerces to 0 in arithmetic (evaluateNullToZero: true)', () => { + const hf = HyperFormula.buildFromArray([[null, '=A1+1']], {licenseKey: 'gpl-v3', evaluateNullToZero: true}) + + expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBe(1) + + hf.destroy() + }) + + it('COUNT of a truly blank cell is still 0 (evaluateNullToZero: false)', () => { + const hf = HyperFormula.buildFromArray([[null, '=COUNT(A1)']], {licenseKey: 'gpl-v3', evaluateNullToZero: false}) + + expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBe(0) + + hf.destroy() + }) + + it('COUNT of a truly blank cell is still 0 (evaluateNullToZero: true)', () => { + const hf = HyperFormula.buildFromArray([[null, '=COUNT(A1)']], {licenseKey: 'gpl-v3', evaluateNullToZero: true}) + + expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBe(0) + + hf.destroy() + }) + + it('evaluateNullToZero: false leaves a formula that evaluates to EmptyValue as null', () => { + const hf = HyperFormula.buildFromArray([[null, '=A1']], {licenseKey: 'gpl-v3', evaluateNullToZero: false}) + + expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBeNull() + + hf.destroy() + }) + + it('evaluateNullToZero: true turns a formula that evaluates to EmptyValue into 0', () => { + const hf = HyperFormula.buildFromArray([[null, '=A1']], {licenseKey: 'gpl-v3', evaluateNullToZero: true}) + + expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBe(0) + + hf.destroy() + }) + + it('a "" COUNTIF criterion still matches only genuinely blank cells, not text cells holding ""', () => { + const hf = HyperFormula.buildFromArray([ + [1, null, ''], + ['=COUNTIF(A1:C1, "")'], + ], {licenseKey: 'gpl-v3'}) + + // Criterion.ts resolves a '' criterion to `cellValue === EmptyValue` *before* any numeric + // coercion happens, so it never went through the coerceNonDateScalarToMaybeNumber bug and + // this behavior (blank matches, a text "" cell does not) is unchanged by this fix. + expect(hf.getCellValue({sheet: 0, col: 0, row: 1})).toBe(1) + + hf.destroy() + }) +}) From 78b1c75bd354e4580437b5fe4eaf3da143d5193c Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 10 Sep 2026 13:58:26 +0000 Subject: [PATCH 02/20] HF-361: complete the Definition of Done for the empty-string change The fix itself was already in place; this adds what a breaking change owes the reader, and moves the tests where this repo keeps them. - Changelog: moved the entry from Fixed to Changed and rewrote it in the "A **breaking change**:" form the other 4.0 entries use, with a migration guide link and the PR number instead of an internal task id. - Migration guide: new docs/guide/migration-from-3.x-to-4.0.md (plus its sidebar entry) with a section on empty-string coercion. Every before/after value in it is measured, not assumed -- two rounds of probes across the unpatched and patched engine, plus the assertions the private suite already pinned. That caught two wrong claims: DATE("","","") returned #NUM! and not a computed date, and ACOT("") returned 1.5707963267949 -- a plausible number from an argument that was never numeric, which is the most useful example this change has. - Removed test/hf-361-empty-string-coercion.spec.ts. DEV_DOCS.md:129 is explicit that interpreter specs do not live in the public repo, because a copy here runs twice and leaves develop red if only one of the paired PRs lands. Those tests move to the paired hyperformula-tests branch of the same name. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 5 +- docs/.vuepress/config.js | 1 + docs/guide/migration-from-3.x-to-4.0.md | 84 +++++++ test/hf-361-empty-string-coercion.spec.ts | 261 ---------------------- 4 files changed, 89 insertions(+), 262 deletions(-) create mode 100644 docs/guide/migration-from-3.x-to-4.0.md delete mode 100644 test/hf-361-empty-string-coercion.spec.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 64544418d2..b664217e42 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,9 +7,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ## [Unreleased] +### Changed + +- A **breaking change**: an empty string (`""`) is no longer coerced to `0` in numeric contexts. As in Excel, `""` is text and is never a number, so `=""+0` now returns the `#VALUE!` error instead of `0`, and `=COUNT("")` returns `0` instead of `1`. This applies wherever a value reaches a number: the arithmetic operators, numeric aggregation (`SUM`, `AVERAGE`, `MIN`, `MAX`, `PRODUCT`, `COUNT`), and any function argument declared as a number. Blank cells are a different value and are unaffected — they still coerce to `0`, and the `evaluateNullToZero` option behaves exactly as before. See the [migration guide](https://hyperformula.handsontable.com/docs/guide/migration-from-3.x-to-4.0.html#changes-to-empty-string-coercion). [#1768](https://github.com/handsontable/hyperformula/pull/1768) + ### Fixed -- **Breaking change**: Fixed an empty string (`''`) being silently coerced to `0` in arithmetic operations and in any function argument that expects a number, which made results differ from Excel (e.g. `=""+0` returned `0` instead of the `#VALUE!` error, and `COUNT("")` returned `1` instead of `0`). This does not affect blank cells, which keep coercing to `0` as before. (HF-361) - Fixed the `AVERAGEIF` function returning a division-by-zero error when the calculated average was `0`. [#1733](https://github.com/handsontable/hyperformula/pull/1733) - Fixed the localized names of `VSTACK` and `HSTACK` in 14 language packs to match Microsoft Excel. [#1748](https://github.com/handsontable/hyperformula/pull/1748) - Fixed the MAXPOOL and MEDIANPOOL functions throwing an uncaught `TypeError` instead of returning the `#VALUE!` error when the range dimensions are not a whole multiple of the window size and the stride. [#1718](https://github.com/handsontable/hyperformula/pull/1718) diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 5caadb41a7..5d21d5fcc6 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -372,6 +372,7 @@ module.exports = { ['/guide/migration-from-0.6-to-1.0', 'Migrating from 0.6 to 1.0'], ['/guide/migration-from-1.x-to-2.0', 'Migrating from 1.x to 2.0'], ['/guide/migration-from-2.x-to-3.0', 'Migrating from 2.x to 3.0'], + ['/guide/migration-from-3.x-to-4.0', 'Migrating from 3.x to 4.0'], ] }, { diff --git a/docs/guide/migration-from-3.x-to-4.0.md b/docs/guide/migration-from-3.x-to-4.0.md new file mode 100644 index 0000000000..b0e529fd9f --- /dev/null +++ b/docs/guide/migration-from-3.x-to-4.0.md @@ -0,0 +1,84 @@ +--- +tags: + - migration + - migrate + - upgrade + - breaking changes + - v4.0 + - empty string + - coercion +--- + +# Migrating from 3.x to 4.0 + +To upgrade your HyperFormula version from 3.x.x to 4.0.0, follow this guide. + +## Changes to empty string coercion + +An empty string (`""`) used to be coerced to `0` wherever a number was expected. It no longer is: as in Excel, `""` is text, and text that is not a number produces the `#VALUE!` error. The Excel results quoted below were verified in Excel Online, so where this guide says "as in Excel", that is a measured result rather than an intention. + +Nothing in your code needs to change for this on its own. What may change are results in your sheets, and only where an empty string reaches a numeric context — see [When a cell holds an empty string](#when-a-cell-holds-an-empty-string) for the case that is easy to hit without writing `""` anywhere. + +### Every numeric context now rejects an empty string + +| Formula | 3.x | 4.0 | +| --- | --- | --- | +| `=""+0` | `0` | `#VALUE!` | +| `=1-""` | `1` | `#VALUE!` | +| `=""*2` | `0` | `#VALUE!` | +| `=""/1` | `0` | `#VALUE!` | +| `=-""` | `0` | `#VALUE!` | +| `=2^""` | `1` | `#VALUE!` | +| `=COUNT("")` | `1` | `0` | +| `=SUM("")` | `0` | `#VALUE!` | +| `=AVERAGE("")` | `0` | `#VALUE!` | +| `=MIN("")` / `=MAX("")` / `=PRODUCT("")` | `0` | `#VALUE!` | +| `=ROUND("", 0)` | `0` | `#VALUE!` | +| `=ACOT("")` | `1.5707963267949` | `#VALUE!` | +| `=LN("")` / `=LOG10("")` / `=LOG("", 42)` | `#NUM!` | `#VALUE!` | +| `=COT("")` / `=COTH("")` | `#DIV/0!` | `#VALUE!` | +| `=DATE("", "", "")` | `#NUM!` | `#VALUE!` | + +The `ACOT` row is the one worth looking at twice. `""` became `0`, and `ACOT(0)` is a perfectly good number, so the formula returned π/2 — a plausible result computed from an argument that was never a number. The rows below it are the milder shape of the same problem: an error, but one naming a domain violation discovered after the coercion rather than the coercion itself. + +`=SUM("abc")` returned `#VALUE!` in 3.x and still does. The point of this change is that `""` is no longer the one text value treated as a number. + +### Blank cells are not affected + +A blank cell is not an empty string, and nothing about it changes: + +| Case | 3.x | 4.0 | +| --- | --- | --- | +| `=A1+0` where `A1` is empty | `0` | `0` (unchanged) | +| `=COUNT(A1)` where `A1` is empty | `0` | `0` (unchanged) | +| [`evaluateNullToZero`](../api/interfaces/configparams.md#evaluatenulltozero) | — | behaves exactly as before | +| a `""` criterion in `COUNTIF`/`SUMIF` | matches blank cells only | unchanged | + +The `""` criterion row is worth reading twice: `=COUNTIF(A1:A3, "")` matched only genuinely blank cells before this change, and still does. It never matched text cells holding `""`. + +### When a cell holds an empty string + +This is the case to check in an application, because it can arise without any formula containing `""`. + +Writing an empty string into a cell produces a **text** cell, not a blank one: + +```js +hfInstance.setCellContents({ sheet: 0, col: 0, row: 0 }, ''); // a text cell holding '' +hfInstance.setCellContents({ sheet: 0, col: 0, row: 0 }, null); // a blank cell +``` + +The first is `#VALUE!`-producing input for a numeric formula from 4.0 on; the second is not, and never was. The same distinction applies to `buildFromArray([['']])` versus `buildFromArray([[null]])`. + +**How to migrate.** If your integration clears cells, make sure it writes `null` (or `undefined`), not `''`: + +```js +hfInstance.setCellContents(address, ''); -> hfInstance.setCellContents(address, null); +``` + +Two places worth auditing in a host application: + +- **A "clear cell" action.** If it hands the engine the empty value of a text input rather than `null`, it writes `''`. +- **Paste.** Clipboard content is text, so a blank cell inside a copied range parses to `''` rather than to `null` unless something maps it back. + +To find affected formulas rather than affected code, look for numeric formulas that reference cells your application can blank out, and for `IF(..., "")` used as a "leave it empty" branch feeding another calculation — for example +`=IF(SUM(A1:A2)>0, SUM(A1:A2), "")/1000`, which returned a number in 3.x and returns `#VALUE!` in 4.0. That pattern is Excel-correct in 4.0: Excel reports `#VALUE!` for it too. Where the intent is "treat the empty branch as zero", write `0` instead of `""` in the branch, or wrap the reference in [`N()`](built-in-functions.md) / `IFERROR`. diff --git a/test/hf-361-empty-string-coercion.spec.ts b/test/hf-361-empty-string-coercion.spec.ts deleted file mode 100644 index 90404ac963..0000000000 --- a/test/hf-361-empty-string-coercion.spec.ts +++ /dev/null @@ -1,261 +0,0 @@ -import {HyperFormula} from '../src' -import {ErrorType} from '../src/Cell' -import {DetailedCellError} from '../src/CellValue' - -/** - * HF-361: an empty string ('') must not be silently coerced to 0. - * - * Excel treats '' as ordinary text: it is not a valid number, so arithmetic on it fails with - * #VALUE! and COUNT (which only counts numbers) does not count it. HyperFormula used to special-case - * '' to 0 inside ArithmeticHelper#coerceNonDateScalarToMaybeNumber, which is a different code path - * from a genuinely blank cell (`EmptyValue`, governed separately by `evaluateNullToZero`). - */ -describe('HF-361: empty string is not coerced to 0', () => { - it('COUNT of a literal empty string does not count it as numeric', () => { - const hf = HyperFormula.buildFromArray([['=COUNT("")']], {licenseKey: 'gpl-v3'}) - - expect(hf.getCellValue({sheet: 0, col: 0, row: 0})).toBe(0) - - hf.destroy() - }) - - it('COUNT of a cell holding an empty string (via ="") does not count it as numeric', () => { - const hf = HyperFormula.buildFromArray([['=""', '=COUNT(A1)']], {licenseKey: 'gpl-v3'}) - - expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBe(0) - - hf.destroy() - }) - - it('COUNT of a cell holding a raw empty string (a text cell, not a blank one) does not count it', () => { - const hf = HyperFormula.buildFromArray([['', '=COUNT(A1)']], {licenseKey: 'gpl-v3'}) - - expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBe(0) - - hf.destroy() - }) - - it('adding a literal empty string to a number is #VALUE!, matching Excel', () => { - const hf = HyperFormula.buildFromArray([['=""+0']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('adding a number to an empty string is #VALUE!', () => { - const hf = HyperFormula.buildFromArray([['=""+1']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('subtracting a number from an empty string is #VALUE!', () => { - const hf = HyperFormula.buildFromArray([['=""-1']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('multiplying an empty string is #VALUE!', () => { - const hf = HyperFormula.buildFromArray([['=""*1']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('dividing an empty string is #VALUE!', () => { - const hf = HyperFormula.buildFromArray([['=""/1']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('negating an empty string is #VALUE!', () => { - const hf = HyperFormula.buildFromArray([['=-""']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('raising a number to the power of an empty string is #VALUE!', () => { - const hf = HyperFormula.buildFromArray([['=1^""']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('a text cell holding an empty string behaves the same as the literal in arithmetic', () => { - const hf = HyperFormula.buildFromArray([['', '=A1+0']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 1, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('SUM of a literal empty string is #VALUE!, consistent with other non-numeric text', () => { - const hf = HyperFormula.buildFromArray([['=SUM("")']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('AVERAGE of a literal empty string is #VALUE!', () => { - const hf = HyperFormula.buildFromArray([['=AVERAGE("")']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('PRODUCT of a literal empty string is #VALUE!', () => { - const hf = HyperFormula.buildFromArray([['=PRODUCT("")']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('MIN of a literal empty string is #VALUE!', () => { - const hf = HyperFormula.buildFromArray([['=MIN("")']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('MAX of a literal empty string is #VALUE!', () => { - const hf = HyperFormula.buildFromArray([['=MAX("")']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('SUM of other non-numeric literal text is #VALUE! too (baseline, unaffected by this fix)', () => { - const hf = HyperFormula.buildFromArray([['=SUM("abc")']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('ROUND rejects a literal empty string for its NUMBER-typed argument', () => { - const hf = HyperFormula.buildFromArray([['=ROUND("",1)']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) - - it('POWER rejects a literal empty string for its NUMBER-typed argument', () => { - const hf = HyperFormula.buildFromArray([['=POWER("",2)']], {licenseKey: 'gpl-v3'}) - - const result = hf.getCellValue({sheet: 0, col: 0, row: 0}) as DetailedCellError - - expect(result.type).toBe(ErrorType.VALUE) - - hf.destroy() - }) -}) - -describe('HF-361: unaffected — blank cells (EmptyValue) keep their existing behavior', () => { - it('a truly blank cell still coerces to 0 in arithmetic (evaluateNullToZero: false)', () => { - const hf = HyperFormula.buildFromArray([[null, '=A1+1']], {licenseKey: 'gpl-v3', evaluateNullToZero: false}) - - expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBe(1) - - hf.destroy() - }) - - it('a truly blank cell still coerces to 0 in arithmetic (evaluateNullToZero: true)', () => { - const hf = HyperFormula.buildFromArray([[null, '=A1+1']], {licenseKey: 'gpl-v3', evaluateNullToZero: true}) - - expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBe(1) - - hf.destroy() - }) - - it('COUNT of a truly blank cell is still 0 (evaluateNullToZero: false)', () => { - const hf = HyperFormula.buildFromArray([[null, '=COUNT(A1)']], {licenseKey: 'gpl-v3', evaluateNullToZero: false}) - - expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBe(0) - - hf.destroy() - }) - - it('COUNT of a truly blank cell is still 0 (evaluateNullToZero: true)', () => { - const hf = HyperFormula.buildFromArray([[null, '=COUNT(A1)']], {licenseKey: 'gpl-v3', evaluateNullToZero: true}) - - expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBe(0) - - hf.destroy() - }) - - it('evaluateNullToZero: false leaves a formula that evaluates to EmptyValue as null', () => { - const hf = HyperFormula.buildFromArray([[null, '=A1']], {licenseKey: 'gpl-v3', evaluateNullToZero: false}) - - expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBeNull() - - hf.destroy() - }) - - it('evaluateNullToZero: true turns a formula that evaluates to EmptyValue into 0', () => { - const hf = HyperFormula.buildFromArray([[null, '=A1']], {licenseKey: 'gpl-v3', evaluateNullToZero: true}) - - expect(hf.getCellValue({sheet: 0, col: 1, row: 0})).toBe(0) - - hf.destroy() - }) - - it('a "" COUNTIF criterion still matches only genuinely blank cells, not text cells holding ""', () => { - const hf = HyperFormula.buildFromArray([ - [1, null, ''], - ['=COUNTIF(A1:C1, "")'], - ], {licenseKey: 'gpl-v3'}) - - // Criterion.ts resolves a '' criterion to `cellValue === EmptyValue` *before* any numeric - // coercion happens, so it never went through the coerceNonDateScalarToMaybeNumber bug and - // this behavior (blank matches, a text "" cell does not) is unchanged by this fix. - expect(hf.getCellValue({sheet: 0, col: 0, row: 1})).toBe(1) - - hf.destroy() - }) -}) From c99427b3b17c7762ec3aaf15c0324b0d34be1801 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 10 Sep 2026 15:14:09 +0000 Subject: [PATCH 03/20] HF-361: correct the scope of the change in the changelog and migration guide Two independent reviews converged on the same defect: both documents implied that a cell holding an empty string breaks any numeric formula. It does not. Measured on both engines: SUM, AVERAGE, MIN, MAX and COUNT over a reference or a range are byte-identical before and after -- they have always ignored text found there, matching Excel -- because the aggregation path filters strings out before this coercion is reached. Only arithmetic, number-typed arguments, and an empty string written directly into an aggregation change. A reader with =SUM(A1:A100) would have been told to expect a break that cannot happen, in a document whose whole job is to predict breaks. Also corrected or added, all measured rather than read off a test: - =ACOT("") returned 1.5707963268, not 1.5707963267949. I had taken the digits from the private suite's toBeCloseTo(..., 10) assertion, which passes for both. Default config rounds to 10 significant digits. - =DATE(A1, 2, 3) over a text empty string silently returned 35 -- a date in 1900 -- which is the same "answered instead of failing" class as ACOT and a better example, because it is the reference form users actually write. - Added the contexts the table omitted while claiming to be exhaustive: =""%, =SUM(1, ""), =ABS, =INT, =SUMSQ, =MEDIAN, =STDEV. - Added the nested-expression class (=SUM(IF(TRUE,"",1)), =SUM(LEFT("abc",0))), where 3.x was wrong and 4.0 matches Excel, and the one class that moves away from Excel (an argument Excel evaluates as an array of only text), with the pre-existing non-array-aware IF that actually causes it. - Fixed the code blocks against DOCS_CONTENT_GUIDE: the mandated { sheet, row, col } key order, a snippet that actually runs as written (verified), and an untagged fence for the before/after pair that is not JavaScript. Pointed N() and IFERROR at their real category anchors. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 2 +- docs/guide/migration-from-3.x-to-4.0.md | 98 +++++++++++++++++++------ 2 files changed, 78 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b664217e42..869042e41d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Changed -- A **breaking change**: an empty string (`""`) is no longer coerced to `0` in numeric contexts. As in Excel, `""` is text and is never a number, so `=""+0` now returns the `#VALUE!` error instead of `0`, and `=COUNT("")` returns `0` instead of `1`. This applies wherever a value reaches a number: the arithmetic operators, numeric aggregation (`SUM`, `AVERAGE`, `MIN`, `MAX`, `PRODUCT`, `COUNT`), and any function argument declared as a number. Blank cells are a different value and are unaffected — they still coerce to `0`, and the `evaluateNullToZero` option behaves exactly as before. See the [migration guide](https://hyperformula.handsontable.com/docs/guide/migration-from-3.x-to-4.0.html#changes-to-empty-string-coercion). [#1768](https://github.com/handsontable/hyperformula/pull/1768) +- A **breaking change**: an empty string (`""`) is no longer coerced to `0` in numeric contexts. As in Excel, `""` is text and is never a number, so `=""+0` and `=A1+1` (where `A1` holds an empty string) now return the `#VALUE!` error instead of `0` and `1`. This affects the arithmetic operators and any function argument declared as a number (`=ROUND(A1, 0)`, `=ACOT(A1)`, `=DATE(A1, 2, 3)`), plus an empty string written directly into an aggregation (`=COUNT("")` returns `0` instead of `1`, `=SUM(1, "")` returns `#VALUE!` instead of `1`). Aggregation over a cell reference or a range is **not** affected: `SUM`, `AVERAGE`, `MIN`, `MAX` and `COUNT` have always ignored text found there and still do. Blank cells are a different value and are unaffected — they still coerce to `0`, and the `evaluateNullToZero` option behaves exactly as before. See the [migration guide](https://hyperformula.handsontable.com/docs/guide/migration-from-3.x-to-4.0.html#changes-to-empty-string-coercion). [#1768](https://github.com/handsontable/hyperformula/pull/1768) ### Fixed diff --git a/docs/guide/migration-from-3.x-to-4.0.md b/docs/guide/migration-from-3.x-to-4.0.md index b0e529fd9f..1395a74220 100644 --- a/docs/guide/migration-from-3.x-to-4.0.md +++ b/docs/guide/migration-from-3.x-to-4.0.md @@ -19,30 +19,81 @@ An empty string (`""`) used to be coerced to `0` wherever a number was expected. Nothing in your code needs to change for this on its own. What may change are results in your sheets, and only where an empty string reaches a numeric context — see [When a cell holds an empty string](#when-a-cell-holds-an-empty-string) for the case that is easy to hit without writing `""` anywhere. -### Every numeric context now rejects an empty string +### What changes: arithmetic and number-typed arguments + +This holds whether the empty string is written in the formula or read from a cell. In the tables below, `A1` is a cell holding an empty string — see [When a cell holds an empty string](#when-a-cell-holds-an-empty-string) for how one gets there. | Formula | 3.x | 4.0 | | --- | --- | --- | -| `=""+0` | `0` | `#VALUE!` | -| `=1-""` | `1` | `#VALUE!` | -| `=""*2` | `0` | `#VALUE!` | -| `=""/1` | `0` | `#VALUE!` | -| `=-""` | `0` | `#VALUE!` | -| `=2^""` | `1` | `#VALUE!` | -| `=COUNT("")` | `1` | `0` | -| `=SUM("")` | `0` | `#VALUE!` | -| `=AVERAGE("")` | `0` | `#VALUE!` | -| `=MIN("")` / `=MAX("")` / `=PRODUCT("")` | `0` | `#VALUE!` | -| `=ROUND("", 0)` | `0` | `#VALUE!` | -| `=ACOT("")` | `1.5707963267949` | `#VALUE!` | +| `=""+0` / `=A1+1` | `0` / `1` | `#VALUE!` | +| `=1-""` / `=A1-1` | `1` / `-1` | `#VALUE!` | +| `=""*2` / `=A1*2` | `0` | `#VALUE!` | +| `=""/1` / `=A1/1` | `0` | `#VALUE!` | +| `=-""` / `=-A1` | `0` | `#VALUE!` | +| `=2^""` / `=A1^2` | `1` / `0` | `#VALUE!` | +| `=""%` / `=A1%` | `0` | `#VALUE!` | +| `=ROUND("", 0)` / `=ROUND(A1, 0)` | `0` | `#VALUE!` | +| `=ABS("")` / `=INT("")` | `0` | `#VALUE!` | +| `=ACOT("")` / `=ACOT(A1)` | `1.5707963268` | `#VALUE!` | +| `=DATE(A1, 2, 3)` | `35` | `#VALUE!` | | `=LN("")` / `=LOG10("")` / `=LOG("", 42)` | `#NUM!` | `#VALUE!` | | `=COT("")` / `=COTH("")` | `#DIV/0!` | `#VALUE!` | | `=DATE("", "", "")` | `#NUM!` | `#VALUE!` | -The `ACOT` row is the one worth looking at twice. `""` became `0`, and `ACOT(0)` is a perfectly good number, so the formula returned π/2 — a plausible result computed from an argument that was never a number. The rows below it are the milder shape of the same problem: an error, but one naming a domain violation discovered after the coercion rather than the coercion itself. +The `ACOT` and `DATE` rows are the ones worth looking at twice, because they did not fail — they answered. `""` became `0`, and both `ACOT(0)` and `DATE(0, 2, 3)` are perfectly good inputs, so the formulas returned π/2 and a date in 1900 respectively: plausible results computed from an argument that was never a number. The rows below them are the milder shape of the same problem — an error, but one naming a domain violation discovered after the coercion rather than the coercion itself. + +### What changes: an empty string written directly into an aggregation + +| Formula | 3.x | 4.0 | +| --- | --- | --- | +| `=COUNT("")` | `1` | `0` | +| `=SUM("")` / `=AVERAGE("")` / `=MIN("")` / `=MAX("")` / `=PRODUCT("")` | `0` | `#VALUE!` | +| `=SUM(1, "")` | `1` | `#VALUE!` | +| `=SUMSQ("")` / `=MEDIAN("")` | `0` | `#VALUE!` | +| `=STDEV("")` | `#DIV/0!` | `#VALUE!` | + +`=SUM(1, "")` is the likeliest of these to appear in a real sheet, and it is also the sharpest illustration: one argument is a number, the other never was, and 3.x answered `1`. `=SUM("abc")` returned `#VALUE!` in 3.x and still does. The point of this change is that `""` is no longer the one text value treated as a number. +### What does NOT change: aggregations over a cell or a range + +This is the important half, and the one most likely to be misread. The aggregation functions have always ignored text found in a **cell reference or a range**, and they still do — nothing here changes, and all of it matches Excel: + +| Formula | 3.x | 4.0 | +| --- | --- | --- | +| `=SUM(A1)` / `=MIN(A1)` / `=MAX(A1)` | `0` | `0` (unchanged) | +| `=COUNT(A1)` | `0` | `0` (unchanged) | +| `=AVERAGE(A1)` | `#DIV/0!` | `#DIV/0!` (unchanged) | +| `=COUNTA(A1)` | `1` | `1` (unchanged) | +| `=SUM(A1:C1)` where the range is `1`, `""`, `2` | `3` | `3` (unchanged) | +| `=COUNT(A1:C1)` on the same range | `2` | `2` (unchanged) | + +So a sheet whose empty strings only ever reach `SUM`, `COUNT` and their relatives sees no change at all. What breaks is arithmetic and number-typed arguments, per the first table. + +### What changes for the better: an empty string produced mid-formula + +The most common real shape of this bug was never a literal `""` — it was an expression that produces one. 3.x got all of these wrong; 4.0 matches Excel: + +| Formula | Excel | 3.x | 4.0 | +| --- | --- | --- | --- | +| `=SUM(IF(TRUE,"",1))` | `#VALUE!` | `0` | `#VALUE!` | +| `=COUNT(IF(TRUE,"",1))` | `0` | `1` | `0` | +| `=SUM(LEFT("abc",0))` | `#VALUE!` | `0` | `#VALUE!` | +| `=LEFT("abc",0)+1` | `#VALUE!` | `1` | `#VALUE!` | + +### One case that moves away from Excel + +Where Excel evaluates an argument as an **array containing only text**, it ignores the text and 3.x happened to agree, by way of coercing `""` to `0`: + +| Formula | Excel | 3.x | 4.0 | +| --- | --- | --- | --- | +| `=SUM(IF(A1:A3>0,"",A1:A3))` | `0` | `0` | `#VALUE!` | +| `=SUM({""})` | `0` | `0` | `#VALUE!` | +| `=COUNT(IF({1,0},"",5))` | `1` | `1` | `0` | + +That agreement was a coincidence rather than support for the idiom: HyperFormula's `IF` is not array-aware, so it collapses such an argument to a single value regardless. `=SUM(IF(A1:A3>5,"",A1:A3))` over `1, 2, 3` is `6` in Excel and `1` in HyperFormula — in 3.x as much as in 4.0. What changes is only that the collapsed value is no longer silently read as `0`. Ranges and array literals with more than one element are unaffected: `=SUM({1,"",2})` is `3` and `=COUNT({1,"",2})` is `2`, before and after. + ### Blank cells are not affected A blank cell is not an empty string, and nothing about it changes: @@ -63,16 +114,21 @@ This is the case to check in an application, because it can arise without any fo Writing an empty string into a cell produces a **text** cell, not a blank one: ```js -hfInstance.setCellContents({ sheet: 0, col: 0, row: 0 }, ''); // a text cell holding '' -hfInstance.setCellContents({ sheet: 0, col: 0, row: 0 }, null); // a blank cell +const hfInstance = HyperFormula.buildFromArray([[]], { licenseKey: 'gpl-v3' }); + +hfInstance.setCellContents({ sheet: 0, row: 0, col: 0 }, ''); // a text cell holding '' +hfInstance.setCellContents({ sheet: 0, row: 1, col: 0 }, null); // a blank cell ``` -The first is `#VALUE!`-producing input for a numeric formula from 4.0 on; the second is not, and never was. The same distinction applies to `buildFromArray([['']])` versus `buildFromArray([[null]])`. +The same distinction applies to `buildFromArray([['']])` versus `buildFromArray([[null]])`. -**How to migrate.** If your integration clears cells, make sure it writes `null` (or `undefined`), not `''`: +Only the first one is affected by this change, and only in the contexts of the first table above: `=A1+1` and `=ROUND(A1, 0)` change, `=SUM(A1)` and `=COUNT(A1)` do not. So an application that writes `''` where it means "blank" is not automatically broken — it is exposed only where such a cell feeds arithmetic or a number-typed argument. -```js -hfInstance.setCellContents(address, ''); -> hfInstance.setCellContents(address, null); +**How to migrate.** If your integration clears cells, have it write `null` (or `undefined`) rather than `''`: + +``` +hfInstance.setCellContents(address, ''); // before +hfInstance.setCellContents(address, null); // after ``` Two places worth auditing in a host application: @@ -81,4 +137,4 @@ Two places worth auditing in a host application: - **Paste.** Clipboard content is text, so a blank cell inside a copied range parses to `''` rather than to `null` unless something maps it back. To find affected formulas rather than affected code, look for numeric formulas that reference cells your application can blank out, and for `IF(..., "")` used as a "leave it empty" branch feeding another calculation — for example -`=IF(SUM(A1:A2)>0, SUM(A1:A2), "")/1000`, which returned a number in 3.x and returns `#VALUE!` in 4.0. That pattern is Excel-correct in 4.0: Excel reports `#VALUE!` for it too. Where the intent is "treat the empty branch as zero", write `0` instead of `""` in the branch, or wrap the reference in [`N()`](built-in-functions.md) / `IFERROR`. +`=IF(SUM(A1:A2)>0, SUM(A1:A2), "")/1000`, which returned a number in 3.x and returns `#VALUE!` in 4.0. That pattern is Excel-correct in 4.0: Excel reports `#VALUE!` for it too. Where the intent is "treat the empty branch as zero", write `0` instead of `""` in the branch, or wrap the reference in [`N()`](built-in-functions.md#information) / [`IFERROR`](built-in-functions.md#logical). From a24a523dd85055b745981597c9303902e918e536 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Tue, 22 Sep 2026 16:35:50 +0000 Subject: [PATCH 04/20] HF-361: look through parentheses when checking for a reference in numeric aggregations Reported in review on this PR: with B1 holding ="", SUM(B1) correctly returns 0 (aggregation over a reference ignores non-numeric text, unchanged by this PR), but SUM((B1)) returned #VALUE!. Root cause: NumericAggregationPlugin#reduce decides how to treat an argument by checking arg.type against CELL_REFERENCE (and separately against CELL_RANGE/COLUMN_RANGE/ROW_RANGE) to tell "this is a reference, ignore its non-numeric text" apart from "this is a literal/computed value, coerce it to a number." A parenthesized argument reaches the reducer as a PARENTHESIS node wrapping the real expression, so neither check matched and (B1) fell through to the same coercion "" now correctly fails for as a literal. reduce() is the single shared implementation behind SUM, SUMSQ, COUNT, COUNTA, AVERAGE, AVERAGEA, MIN, MAX, MINA, MAXA, PRODUCT, VAR.S/P, VARA/VARPA and STDEV.S/P/A/PA (via doAverage/doCount/reduceAggregate(A)/doMax/doMin/ doSum/doProduct), so this was not SUM-specific: every one of those reproduced the same #VALUE! regression through a single extra pair of parentheses. Fix: unwrap PARENTHESIS nodes before either arg.type check, the same idiom already used in FunctionPlugin#runFunctionWithReferenceArgument and InformationPlugin. PARENTHESIS is a pure passthrough in Interpreter#evaluateAst, so this only changes which branch classifies the argument, not what evaluateAst(arg, state) itself returns. Verified against Excel Online via MS Graph: a parenthesized reference or range behaves identically to the bare one in every case tested (single and double parentheses, SUM/COUNT/AVERAGE/MIN/MAX/PRODUCT/SUMSQ/STDEV, a range containing an embedded empty string). Ranges wrapped in parentheses already worked before this fix -- they take a different path in reduce() that checks the evaluated value's runtime type (SimpleRangeValue) rather than the AST node type -- so this fix does not change range handling, only single-cell (and column/row) references. Paired failing-then-passing tests: handsontable/hyperformula-tests, same branch, "parentheses around a reference do not change numeric-aggregation behavior" in empty-string-coercion.spec.ts. Negative control: reverting this commit's source change while keeping those tests fails 5 of the 8 new specs (the 3 that also pass without the fix are pins on already-correct behavior: COUNT((A1)) and the two parenthesized-range cases). Co-Authored-By: Claude Opus 5 (1M context) --- src/interpreter/plugin/NumericAggregationPlugin.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/interpreter/plugin/NumericAggregationPlugin.ts b/src/interpreter/plugin/NumericAggregationPlugin.ts index 5a675e9360..88f3958197 100644 --- a/src/interpreter/plugin/NumericAggregationPlugin.ts +++ b/src/interpreter/plugin/NumericAggregationPlugin.ts @@ -553,6 +553,20 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function return acc } + // A parenthesized argument reaches this reducer as a PARENTHESIS node wrapping the actual + // expression (e.g. `(B1)` is `{type: PARENTHESIS, expression: {type: CELL_REFERENCE, ...}}`), + // not as a CELL_REFERENCE/CELL_RANGE/COLUMN_RANGE/ROW_RANGE node itself. Both type checks below + // key off `arg.type` to decide whether this argument is a reference (whose non-numeric values + // are ignored) or a literal/computed value (which is coerced to a number, erroring on non-numeric + // text). Unwrapping first -- the same idiom used in FunctionPlugin#runFunctionWithReferenceArgument + // and InformationPlugin -- makes a parenthesized reference behave exactly like the bare one, which + // is what Excel does (measured live: SUM((A1)), COUNT((A1)), AVERAGE((A1)), MIN((A1)), MAX((A1)) + // all equal their unparenthesized form). PARENTHESIS is a pure passthrough in evaluateAst, so this + // does not change what evaluateAst(arg, state) returns below -- only which branch handles it. + 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) { From 23fb194b8f3bab17035db424568eb5ff68c3aa0a Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 22 Oct 2026 17:31:47 +0000 Subject: [PATCH 05/20] docs: shorten the changelog entry to one sentence Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 869042e41d..3ade853084 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Changed -- A **breaking change**: an empty string (`""`) is no longer coerced to `0` in numeric contexts. As in Excel, `""` is text and is never a number, so `=""+0` and `=A1+1` (where `A1` holds an empty string) now return the `#VALUE!` error instead of `0` and `1`. This affects the arithmetic operators and any function argument declared as a number (`=ROUND(A1, 0)`, `=ACOT(A1)`, `=DATE(A1, 2, 3)`), plus an empty string written directly into an aggregation (`=COUNT("")` returns `0` instead of `1`, `=SUM(1, "")` returns `#VALUE!` instead of `1`). Aggregation over a cell reference or a range is **not** affected: `SUM`, `AVERAGE`, `MIN`, `MAX` and `COUNT` have always ignored text found there and still do. Blank cells are a different value and are unaffected — they still coerce to `0`, and the `evaluateNullToZero` option behaves exactly as before. See the [migration guide](https://hyperformula.handsontable.com/docs/guide/migration-from-3.x-to-4.0.html#changes-to-empty-string-coercion). [#1768](https://github.com/handsontable/hyperformula/pull/1768) +- A **breaking change**: an empty string (`""`) is no longer coerced to `0` in numeric contexts, so `=""+0` returns `#VALUE!` as in Excel; see the [migration guide](https://hyperformula.handsontable.com/docs/guide/migration-from-3.x-to-4.0.html#changes-to-empty-string-coercion). [#1768](https://github.com/handsontable/hyperformula/pull/1768) ### Fixed From 731a20f145055b14c1dccdc521282bb227137f59 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Fri, 23 Oct 2026 00:29:36 +0000 Subject: [PATCH 06/20] HF-361: Describe the parenthesized-reference change in the changelog and the migration guide Drop two search tags that repeat the page's own heading, and shorten the comment on the parenthesis unwrap to the behaviour it implements. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- docs/guide/migration-from-3.x-to-4.0.md | 13 +++++++++++-- .../interpreter/plugin/NumericAggregationPlugin.ts | 12 ++---------- 3 files changed, 14 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2b718abca3..91540b083d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Changed -- A **breaking change**: an empty string (`""`) is no longer coerced to `0` in numeric contexts, so `=""+0` returns `#VALUE!` as in Excel; see the [migration guide](https://hyperformula.handsontable.com/docs/guide/migration-from-3.x-to-4.0.html#changes-to-empty-string-coercion). [#1768](https://github.com/handsontable/hyperformula/pull/1768) +- **Breaking change**: Changed numeric contexts to read `""` as text, not `0` (`=""+0` returns `#VALUE!`), and `(A1)` as a reference; see the [migration guide](https://hyperformula.handsontable.com/docs/guide/migration-from-3.x-to-4.0.html#changes-to-empty-string-coercion). [#1768](https://github.com/handsontable/hyperformula/pull/1768) ### Fixed diff --git a/docs/guide/migration-from-3.x-to-4.0.md b/docs/guide/migration-from-3.x-to-4.0.md index 1395a74220..ac6bdd705f 100644 --- a/docs/guide/migration-from-3.x-to-4.0.md +++ b/docs/guide/migration-from-3.x-to-4.0.md @@ -5,8 +5,6 @@ tags: - upgrade - breaking changes - v4.0 - - empty string - - coercion --- # Migrating from 3.x to 4.0 @@ -71,6 +69,17 @@ This is the important half, and the one most likely to be misread. The aggregati So a sheet whose empty strings only ever reach `SUM`, `COUNT` and their relatives sees no change at all. What breaks is arithmetic and number-typed arguments, per the first table. +### A reference in parentheses now counts as a reference + +In 3.x, `SUM`, `COUNT`, `AVERAGE`, `MIN`, `MAX`, `PRODUCT` and `SUMSQ` treated a reference wrapped in parentheses, such as `(A1)`, like a value typed into the formula, not like a reference. In 4.0 a parenthesized reference behaves exactly like the bare one, whatever the cell holds: + +| Formula | 3.x | 4.0 | +| --- | --- | --- | +| `=SUM((A1))` where `A1` holds `abc` | `#VALUE!` | `0`, like `=SUM(A1)` | +| `=SUM((A1))` where `A1` holds `TRUE` | `1` | `0`, like `=SUM(A1)` | +| `=COUNT((A1))` where `A1` is empty | `1` | `0`, like `=COUNT(A1)` | +| `=AVERAGE((A1))` where `A1` is empty | `0` | `#DIV/0!`, like `=AVERAGE(A1)` | + ### What changes for the better: an empty string produced mid-formula The most common real shape of this bug was never a literal `""` — it was an expression that produces one. 3.x got all of these wrong; 4.0 matches Excel: diff --git a/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts b/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts index 9f19070bd6..9183f80162 100644 --- a/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts +++ b/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts @@ -517,16 +517,8 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function return acc } - // A parenthesized argument reaches this reducer as a PARENTHESIS node wrapping the actual - // expression (e.g. `(B1)` is `{type: PARENTHESIS, expression: {type: CELL_REFERENCE, ...}}`), - // not as a CELL_REFERENCE/CELL_RANGE/COLUMN_RANGE/ROW_RANGE node itself. Both type checks below - // key off `arg.type` to decide whether this argument is a reference (whose non-numeric values - // are ignored) or a literal/computed value (which is coerced to a number, erroring on non-numeric - // text). Unwrapping first -- the same idiom used in FunctionPlugin#runFunctionWithReferenceArgument - // and InformationPlugin -- makes a parenthesized reference behave exactly like the bare one, which - // is what Excel does (measured live: SUM((A1)), COUNT((A1)), AVERAGE((A1)), MIN((A1)), MAX((A1)) - // all equal their unparenthesized form). PARENTHESIS is a pure passthrough in evaluateAst, so this - // does not change what evaluateAst(arg, state) returns below -- only which branch handles it. + // 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 } From 761251fa07db10977a0b7fbb2c5a27b8f4f0b637 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Fri, 23 Oct 2026 00:41:48 +0000 Subject: [PATCH 07/20] HF-361: Write TRUE() in the migration guide's IF examples, which HyperFormula needs `=SUM(IF(TRUE,"",1))` returns #NAME? in HyperFormula, because TRUE is a function there, not a literal; the table's values hold for `TRUE()`. Co-Authored-By: Claude Opus 5.5 --- docs/guide/migration-from-3.x-to-4.0.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/guide/migration-from-3.x-to-4.0.md b/docs/guide/migration-from-3.x-to-4.0.md index ac6bdd705f..7f31497913 100644 --- a/docs/guide/migration-from-3.x-to-4.0.md +++ b/docs/guide/migration-from-3.x-to-4.0.md @@ -86,8 +86,8 @@ The most common real shape of this bug was never a literal `""` — it was an ex | Formula | Excel | 3.x | 4.0 | | --- | --- | --- | --- | -| `=SUM(IF(TRUE,"",1))` | `#VALUE!` | `0` | `#VALUE!` | -| `=COUNT(IF(TRUE,"",1))` | `0` | `1` | `0` | +| `=SUM(IF(TRUE(),"",1))` | `#VALUE!` | `0` | `#VALUE!` | +| `=COUNT(IF(TRUE(),"",1))` | `0` | `1` | `0` | | `=SUM(LEFT("abc",0))` | `#VALUE!` | `0` | `#VALUE!` | | `=LEFT("abc",0)+1` | `#VALUE!` | `1` | `#VALUE!` | From cc66c2aa88017865f5553125653c16acd67c4ce8 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Fri, 23 Oct 2026 08:21:19 +0000 Subject: [PATCH 08/20] HF-361: Keep only Excel values that were measured in the migration guide Co-Authored-By: Claude Opus 5.5 --- docs/guide/migration-from-3.x-to-4.0.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/docs/guide/migration-from-3.x-to-4.0.md b/docs/guide/migration-from-3.x-to-4.0.md index 7f31497913..84302e3f1a 100644 --- a/docs/guide/migration-from-3.x-to-4.0.md +++ b/docs/guide/migration-from-3.x-to-4.0.md @@ -13,7 +13,7 @@ To upgrade your HyperFormula version from 3.x.x to 4.0.0, follow this guide. ## Changes to empty string coercion -An empty string (`""`) used to be coerced to `0` wherever a number was expected. It no longer is: as in Excel, `""` is text, and text that is not a number produces the `#VALUE!` error. The Excel results quoted below were verified in Excel Online, so where this guide says "as in Excel", that is a measured result rather than an intention. +An empty string (`""`) used to be coerced to `0` wherever a number was expected. It no longer is: as in Excel, `""` is text, and text that is not a number produces the `#VALUE!` error. The Excel values in the tables below were measured in Excel Online. Nothing in your code needs to change for this on its own. What may change are results in your sheets, and only where an empty string reaches a numeric context — see [When a cell holds an empty string](#when-a-cell-holds-an-empty-string) for the case that is easy to hit without writing `""` anywhere. @@ -98,7 +98,6 @@ Where Excel evaluates an argument as an **array containing only text**, it ignor | Formula | Excel | 3.x | 4.0 | | --- | --- | --- | --- | | `=SUM(IF(A1:A3>0,"",A1:A3))` | `0` | `0` | `#VALUE!` | -| `=SUM({""})` | `0` | `0` | `#VALUE!` | | `=COUNT(IF({1,0},"",5))` | `1` | `1` | `0` | That agreement was a coincidence rather than support for the idiom: HyperFormula's `IF` is not array-aware, so it collapses such an argument to a single value regardless. `=SUM(IF(A1:A3>5,"",A1:A3))` over `1, 2, 3` is `6` in Excel and `1` in HyperFormula — in 3.x as much as in 4.0. What changes is only that the collapsed value is no longer silently read as `0`. Ranges and array literals with more than one element are unaffected: `=SUM({1,"",2})` is `3` and `=COUNT({1,"",2})` is `2`, before and after. @@ -146,4 +145,4 @@ Two places worth auditing in a host application: - **Paste.** Clipboard content is text, so a blank cell inside a copied range parses to `''` rather than to `null` unless something maps it back. To find affected formulas rather than affected code, look for numeric formulas that reference cells your application can blank out, and for `IF(..., "")` used as a "leave it empty" branch feeding another calculation — for example -`=IF(SUM(A1:A2)>0, SUM(A1:A2), "")/1000`, which returned a number in 3.x and returns `#VALUE!` in 4.0. That pattern is Excel-correct in 4.0: Excel reports `#VALUE!` for it too. Where the intent is "treat the empty branch as zero", write `0` instead of `""` in the branch, or wrap the reference in [`N()`](built-in-functions.md#information) / [`IFERROR`](built-in-functions.md#logical). +`=IF(SUM(A1:A2)>0, SUM(A1:A2), "")/1000`, which returned a number in 3.x and returns `#VALUE!` in 4.0. Where the intent is "treat the empty branch as zero", write `0` instead of `""` in the branch, or wrap the reference in [`N()`](built-in-functions.md#information) / [`IFERROR`](built-in-functions.md#logical). From 4c96a667555d13ab6fa13b5777efeb3ca7717cc7 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Fri, 30 Oct 2026 04:02:23 +0000 Subject: [PATCH 09/20] List the text-only array argument among the differences from Excel With the array arithmetic mode disabled, IF returns a single value, so =SUM(IF(A1:A3>0,"",A1:A3)) is #VALUE! and =COUNT(IF({1,0},"",5)) is 0, where Excel gives 0 and 1. With the mode enabled the results match. The migration guide now says the case depends on the mode and which cell the example sits in. Co-Authored-By: Claude Opus 5.5 --- docs/guide/list-of-differences.md | 1 + docs/guide/migration-from-3.x-to-4.0.md | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/guide/list-of-differences.md b/docs/guide/list-of-differences.md index 2317bb0008..b9d7737286 100644 --- a/docs/guide/list-of-differences.md +++ b/docs/guide/list-of-differences.md @@ -33,6 +33,7 @@ See a full list of differences between HyperFormula, Microsoft Excel, and Google | EOMONTH function | =EOMONTH(DATE(2019, 7, 31), 1) | Type of the returned value: `CellValueDetailedType.NUMBER_DATE`. This is non-compliant with the [OpenDocument](https://docs.oasis-open.org/office/OpenDocument/v1.3/os/part4-formula/OpenDocument-v1.3-os-part4-formula.html) standard, which defines the return type as a Number, while describing it as a Date serial number through the function summary. | Cell auto-formatted as **date** | Cell auto-formatted as **regular number** | | EDATE and EOMONTH results in February 1900 | =EDATE(DATE(1900, 1, 31), 1)

=EOMONTH(DATE(1900, 1, 31), 1) | With the [`leapYear1900`](/api/interfaces/configparams.md#leapyear1900) option set to `true`, February 1900 has 29 days, so both examples return 29 February 1900 (serial `60` with `nullDate` set to 1899-12-31). With the default `false`, both return 28 February 1900. | 28 February 1900 for both examples. Google Sheets does not treat 1900 as a leap year. | 28 February 1900 (serial `59`) for both examples. Excel keeps the 1900 leap day only in the serial-to-date mapping (`DAY(60)` is `29`); its month arithmetic treats February 1900 as having 28 days, so no `EDATE` or `EOMONTH` result is ever serial `60`. | | Empty cells in lookup search | =XLOOKUP(3, A1:A4, A1:A4, "NF", 0, 2)
where A1:A4 = 1, 2, (empty), 3 | Empty cells are skipped during the search. A value that is present is found even when it sits past an interspersed empty cell (exact match is gap-independent), and approximate `MATCH`/`VLOOKUP`/`HLOOKUP`/`XLOOKUP` skip empty cells — but not empty strings — when finding the lower/upper bound. Returns `3`. On an all-empty range in a binary search mode, HyperFormula returns the `if_not_found` result (never row 1). | Skips empty cells in approximate search (parity with HyperFormula). | With binary search modes (`search_mode` ±2), a range with interspersed empty cells is not strictly sorted; per Excel's documentation the result may be invalid, so a value past an empty cell is not reliably found. On an all-empty range in a binary mode, Excel returns the first row's value. | +| 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`. | ## Built-in functions diff --git a/docs/guide/migration-from-3.x-to-4.0.md b/docs/guide/migration-from-3.x-to-4.0.md index 7f80e5e5cb..d6eae5ae7a 100644 --- a/docs/guide/migration-from-3.x-to-4.0.md +++ b/docs/guide/migration-from-3.x-to-4.0.md @@ -99,7 +99,7 @@ Where Excel evaluates an argument as an **array containing only text**, it ignor | `=SUM(IF(A1:A3>0,"",A1:A3))` | `0` | `0` | `#VALUE!` | | `=COUNT(IF({1,0},"",5))` | `1` | `1` | `0` | -That agreement was a coincidence rather than support for the idiom: HyperFormula's `IF` is not array-aware, so it collapses such an argument to a single value regardless. `=SUM(IF(A1:A3>5,"",A1:A3))` over `1, 2, 3` is `6` in Excel and `1` in HyperFormula — in 3.x as much as in 4.0. What changes is only that the collapsed value is no longer silently read as `0`. Ranges and array literals with more than one element are unaffected: `=SUM({1,"",2})` is `3` and `=COUNT({1,"",2})` is `2`, before and after. +That agreement was a coincidence rather than support for the idiom: with the [array arithmetic mode](arrays.md#array-arithmetic-mode) disabled (the default), HyperFormula's `IF` collapses such an argument to a single value regardless. `=SUM(IF(A1:A3>5,"",A1:A3))` entered in `B1`, with `1, 2, 3` in `A1:A3`, is `6` in Excel and `1` in HyperFormula — in 3.x as much as in 4.0. What changes is only that the collapsed value is no longer silently read as `0`. With the array arithmetic mode enabled, `IF` returns an array, and all three formulas in this section give the same results as in Excel. Ranges and array literals with more than one element are unaffected: `=SUM({1,"",2})` is `3` and `=COUNT({1,"",2})` is `2`, before and after. ### Blank cells are not affected From 8bc9db8f512ccc487c457439b45843129b4bc631 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Tue, 3 Nov 2026 04:50:17 +0000 Subject: [PATCH 10/20] HF-361: Ship the empty-string change as a fix: move the entry to Fixed and drop the migration guide Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 +- docs/astro.config.mjs | 1 - docs/guide/migration-from-3.x-to-4.0.md | 147 ------------------------ 3 files changed, 1 insertion(+), 152 deletions(-) delete mode 100644 docs/guide/migration-from-3.x-to-4.0.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 1dd098c147..b648f15f2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,13 +7,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ## [Unreleased] -### Changed - -- **Breaking change**: Changed numeric contexts to read `""` as text, not `0` (`=""+0` returns `#VALUE!`), and `(A1)` as a reference; see the [migration guide](https://hyperformula.handsontable.com/docs/guide/migration-from-3.x-to-4.0.html#changes-to-empty-string-coercion). [#1768](https://github.com/handsontable/hyperformula/pull/1768) - ### Fixed - Fixed the `EDATE` function returning the 28th of February instead of the 29th when the shifted date falls in February of a leap year (e.g. `=EDATE(DATE(2028, 1, 31), 1)` now returns `2028-02-29` instead of `2028-02-28`). [#1781](https://github.com/handsontable/hyperformula/pull/1781) +- 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) ## [3.5.0] - 2026-10-09 diff --git a/docs/astro.config.mjs b/docs/astro.config.mjs index d10286cfe2..4b2a1d3a28 100644 --- a/docs/astro.config.mjs +++ b/docs/astro.config.mjs @@ -215,7 +215,6 @@ j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= { label: 'Migrating from 0.6 to 1.0', slug: 'guide/migration-from-0.6-to-1.0' }, { label: 'Migrating from 1.x to 2.0', slug: 'guide/migration-from-1.x-to-2.0' }, { label: 'Migrating from 2.x to 3.0', slug: 'guide/migration-from-2.x-to-3.0' }, - { label: 'Migrating from 3.x to 4.0', slug: 'guide/migration-from-3.x-to-4.0' }, ], }, { diff --git a/docs/guide/migration-from-3.x-to-4.0.md b/docs/guide/migration-from-3.x-to-4.0.md deleted file mode 100644 index d6eae5ae7a..0000000000 --- a/docs/guide/migration-from-3.x-to-4.0.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: "Migrating from 3.x to 4.0" -tags: - - migration - - migrate - - upgrade - - breaking changes - - v4.0 ---- - -To upgrade your HyperFormula version from 3.x.x to 4.0.0, follow this guide. - -## Changes to empty string coercion - -An empty string (`""`) used to be coerced to `0` wherever a number was expected. It no longer is: as in Excel, `""` is text, and text that is not a number produces the `#VALUE!` error. The Excel values in the tables below were measured in Excel Online. - -Nothing in your code needs to change for this on its own. What may change are results in your sheets, and only where an empty string reaches a numeric context — see [When a cell holds an empty string](#when-a-cell-holds-an-empty-string) for the case that is easy to hit without writing `""` anywhere. - -### What changes: arithmetic and number-typed arguments - -This holds whether the empty string is written in the formula or read from a cell. In the tables below, `A1` is a cell holding an empty string — see [When a cell holds an empty string](#when-a-cell-holds-an-empty-string) for how one gets there. - -| Formula | 3.x | 4.0 | -| --- | --- | --- | -| `=""+0` / `=A1+1` | `0` / `1` | `#VALUE!` | -| `=1-""` / `=A1-1` | `1` / `-1` | `#VALUE!` | -| `=""*2` / `=A1*2` | `0` | `#VALUE!` | -| `=""/1` / `=A1/1` | `0` | `#VALUE!` | -| `=-""` / `=-A1` | `0` | `#VALUE!` | -| `=2^""` / `=A1^2` | `1` / `0` | `#VALUE!` | -| `=""%` / `=A1%` | `0` | `#VALUE!` | -| `=ROUND("", 0)` / `=ROUND(A1, 0)` | `0` | `#VALUE!` | -| `=ABS("")` / `=INT("")` | `0` | `#VALUE!` | -| `=ACOT("")` / `=ACOT(A1)` | `1.5707963268` | `#VALUE!` | -| `=DATE(A1, 2, 3)` | `35` | `#VALUE!` | -| `=LN("")` / `=LOG10("")` / `=LOG("", 42)` | `#NUM!` | `#VALUE!` | -| `=COT("")` / `=COTH("")` | `#DIV/0!` | `#VALUE!` | -| `=DATE("", "", "")` | `#NUM!` | `#VALUE!` | - -The `ACOT` and `DATE` rows are the ones worth looking at twice, because they did not fail — they answered. `""` became `0`, and both `ACOT(0)` and `DATE(0, 2, 3)` are perfectly good inputs, so the formulas returned π/2 and a date in 1900 respectively: plausible results computed from an argument that was never a number. The rows below them are the milder shape of the same problem — an error, but one naming a domain violation discovered after the coercion rather than the coercion itself. - -### What changes: an empty string written directly into an aggregation - -| Formula | 3.x | 4.0 | -| --- | --- | --- | -| `=COUNT("")` | `1` | `0` | -| `=SUM("")` / `=AVERAGE("")` / `=MIN("")` / `=MAX("")` / `=PRODUCT("")` | `0` | `#VALUE!` | -| `=SUM(1, "")` | `1` | `#VALUE!` | -| `=SUMSQ("")` / `=MEDIAN("")` | `0` | `#VALUE!` | -| `=STDEV("")` | `#DIV/0!` | `#VALUE!` | - -`=SUM(1, "")` is the likeliest of these to appear in a real sheet, and it is also the sharpest illustration: one argument is a number, the other never was, and 3.x answered `1`. - -`=SUM("abc")` returned `#VALUE!` in 3.x and still does. The point of this change is that `""` is no longer the one text value treated as a number. - -### What does NOT change: aggregations over a cell or a range - -This is the important half, and the one most likely to be misread. The aggregation functions have always ignored text found in a **cell reference or a range**, and they still do — nothing here changes, and all of it matches Excel: - -| Formula | 3.x | 4.0 | -| --- | --- | --- | -| `=SUM(A1)` / `=MIN(A1)` / `=MAX(A1)` | `0` | `0` (unchanged) | -| `=COUNT(A1)` | `0` | `0` (unchanged) | -| `=AVERAGE(A1)` | `#DIV/0!` | `#DIV/0!` (unchanged) | -| `=COUNTA(A1)` | `1` | `1` (unchanged) | -| `=SUM(A1:C1)` where the range is `1`, `""`, `2` | `3` | `3` (unchanged) | -| `=COUNT(A1:C1)` on the same range | `2` | `2` (unchanged) | - -So a sheet whose empty strings only ever reach `SUM`, `COUNT` and their relatives sees no change at all. What breaks is arithmetic and number-typed arguments, per the first table. - -### A reference in parentheses now counts as a reference - -In 3.x, `SUM`, `COUNT`, `AVERAGE`, `MIN`, `MAX`, `PRODUCT` and `SUMSQ` treated a reference wrapped in parentheses, such as `(A1)`, like a value typed into the formula, not like a reference. In 4.0 a parenthesized reference behaves exactly like the bare one, whatever the cell holds: - -| Formula | 3.x | 4.0 | -| --- | --- | --- | -| `=SUM((A1))` where `A1` holds `abc` | `#VALUE!` | `0`, like `=SUM(A1)` | -| `=SUM((A1))` where `A1` holds `TRUE` | `1` | `0`, like `=SUM(A1)` | -| `=COUNT((A1))` where `A1` is empty | `1` | `0`, like `=COUNT(A1)` | -| `=AVERAGE((A1))` where `A1` is empty | `0` | `#DIV/0!`, like `=AVERAGE(A1)` | - -### What changes for the better: an empty string produced mid-formula - -The most common real shape of this bug was never a literal `""` — it was an expression that produces one. 3.x got all of these wrong; 4.0 matches Excel: - -| Formula | Excel | 3.x | 4.0 | -| --- | --- | --- | --- | -| `=SUM(IF(TRUE(),"",1))` | `#VALUE!` | `0` | `#VALUE!` | -| `=COUNT(IF(TRUE(),"",1))` | `0` | `1` | `0` | -| `=SUM(LEFT("abc",0))` | `#VALUE!` | `0` | `#VALUE!` | -| `=LEFT("abc",0)+1` | `#VALUE!` | `1` | `#VALUE!` | - -### One case that moves away from Excel - -Where Excel evaluates an argument as an **array containing only text**, it ignores the text and 3.x happened to agree, by way of coercing `""` to `0`: - -| Formula | Excel | 3.x | 4.0 | -| --- | --- | --- | --- | -| `=SUM(IF(A1:A3>0,"",A1:A3))` | `0` | `0` | `#VALUE!` | -| `=COUNT(IF({1,0},"",5))` | `1` | `1` | `0` | - -That agreement was a coincidence rather than support for the idiom: with the [array arithmetic mode](arrays.md#array-arithmetic-mode) disabled (the default), HyperFormula's `IF` collapses such an argument to a single value regardless. `=SUM(IF(A1:A3>5,"",A1:A3))` entered in `B1`, with `1, 2, 3` in `A1:A3`, is `6` in Excel and `1` in HyperFormula — in 3.x as much as in 4.0. What changes is only that the collapsed value is no longer silently read as `0`. With the array arithmetic mode enabled, `IF` returns an array, and all three formulas in this section give the same results as in Excel. Ranges and array literals with more than one element are unaffected: `=SUM({1,"",2})` is `3` and `=COUNT({1,"",2})` is `2`, before and after. - -### Blank cells are not affected - -A blank cell is not an empty string, and nothing about it changes: - -| Case | 3.x | 4.0 | -| --- | --- | --- | -| `=A1+0` where `A1` is empty | `0` | `0` (unchanged) | -| `=COUNT(A1)` where `A1` is empty | `0` | `0` (unchanged) | -| [`evaluateNullToZero`](../api/interfaces/configparams.md#evaluatenulltozero) | — | behaves exactly as before | -| a `""` criterion in `COUNTIF`/`SUMIF` | matches blank cells only | unchanged | - -The `""` criterion row is worth reading twice: `=COUNTIF(A1:A3, "")` matched only genuinely blank cells before this change, and still does. It never matched text cells holding `""`. - -### When a cell holds an empty string - -This is the case to check in an application, because it can arise without any formula containing `""`. - -Writing an empty string into a cell produces a **text** cell, not a blank one: - -```js -const hfInstance = HyperFormula.buildFromArray([[]], { licenseKey: 'gpl-v3' }); - -hfInstance.setCellContents({ sheet: 0, row: 0, col: 0 }, ''); // a text cell holding '' -hfInstance.setCellContents({ sheet: 0, row: 1, col: 0 }, null); // a blank cell -``` - -The same distinction applies to `buildFromArray([['']])` versus `buildFromArray([[null]])`. - -Only the first one is affected by this change, and only in the contexts of the first table above: `=A1+1` and `=ROUND(A1, 0)` change, `=SUM(A1)` and `=COUNT(A1)` do not. So an application that writes `''` where it means "blank" is not automatically broken — it is exposed only where such a cell feeds arithmetic or a number-typed argument. - -**How to migrate.** If your integration clears cells, have it write `null` (or `undefined`) rather than `''`: - -``` -hfInstance.setCellContents(address, ''); // before -hfInstance.setCellContents(address, null); // after -``` - -Two places worth auditing in a host application: - -- **A "clear cell" action.** If it hands the engine the empty value of a text input rather than `null`, it writes `''`. -- **Paste.** Clipboard content is text, so a blank cell inside a copied range parses to `''` rather than to `null` unless something maps it back. - -To find affected formulas rather than affected code, look for numeric formulas that reference cells your application can blank out, and for `IF(..., "")` used as a "leave it empty" branch feeding another calculation — for example -`=IF(SUM(A1:A2)>0, SUM(A1:A2), "")/1000`, which returned a number in 3.x and returns `#VALUE!` in 4.0. Where the intent is "treat the empty branch as zero", write `0` instead of `""` in the branch, or wrap the reference in [`N()`](built-in-functions.md#information) / [`IFERROR`](built-in-functions.md#logical). From d4766602c9ca325d21a96f7cd5131d813cc9bfcc Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Tue, 3 Nov 2026 05:12:56 +0000 Subject: [PATCH 11/20] HF-361: Say in the types-of-values guide that an empty string is Text, not an empty cell Co-Authored-By: Claude Opus 5.5 --- docs/guide/types-of-values.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/guide/types-of-values.md b/docs/guide/types-of-values.md index 09f6b90eff..cb9420ef23 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 From fe2b028b8578ce0f076ac16e360d296d808efeb8 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 12 Nov 2026 04:30:56 +0000 Subject: [PATCH 12/20] HF-361: State what coerceNonDateScalarToMaybeNumber returns for a blank cell and an empty string Co-Authored-By: Claude Opus 5.5 --- hyperformula/src/interpreter/ArithmeticHelper.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/hyperformula/src/interpreter/ArithmeticHelper.ts b/hyperformula/src/interpreter/ArithmeticHelper.ts index ff12344e46..dba750fc5e 100644 --- a/hyperformula/src/interpreter/ArithmeticHelper.ts +++ b/hyperformula/src/interpreter/ArithmeticHelper.ts @@ -226,10 +226,8 @@ 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). * - * An empty string (`''`) is deliberately *not* coerced to `0` here: it is a text value, not a - * blank cell (that case is `EmptyValue`, handled above), so it is left for the caller to reject - * as non-numeric — matching how Excel treats `""` as text in arithmetic and numeric - * functions (`=""+0` and `=COUNT("")` both fail to find a number in Excel). + * 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) { From 32191615785654a7f5a3021480d570383e49eb6f Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 12 Nov 2026 04:30:56 +0000 Subject: [PATCH 13/20] HF-361: List text returned by INDEX, CHOOSE, IF or a name among the differences from Excel Co-Authored-By: Claude Opus 5.5 --- docs/guide/list-of-differences.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/guide/list-of-differences.md b/docs/guide/list-of-differences.md index 94312c53c5..76f3e38578 100644 --- a/docs/guide/list-of-differences.md +++ b/docs/guide/list-of-differences.md @@ -51,6 +51,7 @@ Very large or very small input scales can also cause substantial differences in | 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`. | +| Text returned by a function or a name in numeric aggregations | A2: =""
myName: =Sheet1!$A$2

=SUM(INDEX(A1:A3,2))

=SUM(CHOOSE(1,A2))

=SUM(IF(TRUE(),A2,0))

=SUM(myName,5) | Text is ignored only in a reference or a range written as the argument, with or without parentheses. A value returned by `INDEX`, `CHOOSE` or `IF`, or read through a named expression, is read like a literal, so text, including an empty string, makes `SUM`, `AVERAGE`, `MIN` and `MAX` return `#VALUE!`. | Not checked. | The text is ignored: the examples return `0`, `0`, `0` and `5`. | ## Built-in functions From 19eeb5b90bdf2155caec3619ea1cca008e1f4d2d Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Sun, 15 Nov 2026 20:55:50 +0000 Subject: [PATCH 14/20] HF-361: Ignore text read through INDEX, CHOOSE, IF or a name in aggregations The numeric aggregations ignored non-numeric values only in an argument written as a reference or a range. A value that INDEX, CHOOSE or IF returned from a cell, or that a named expression defined as a reference read, was coerced like a literal, so text made SUM, AVERAGE, MIN and MAX return #VALUE!, and an empty string started to do the same once it was no longer read as 0. An argument is now read as a reference when its formula can only evaluate to the content of a referenced cell: INDEX over a reference, a named expression defined as a reference, or IF and CHOOSE whose result arguments are all references or number literals. The decision looks at the formula only, so no argument is evaluated twice. A literal such as IF(TRUE(),"",1) is still read as a value. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/guide/list-of-differences.md | 1 - .../plugin/NumericAggregationPlugin.ts | 118 +++++++++++++++++- 3 files changed, 118 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6fd6128fdf..2fed9b1a6a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - 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`, `MIN` and `MAX` returning `#VALUE!` for text read from a cell through `INDEX`, `CHOOSE`, `IF` or a named expression, which they now ignore as they do for a direct reference. [#1768](https://github.com/handsontable/hyperformula/pull/1768) ## [3.5.0] - 2026-10-09 diff --git a/docs/guide/list-of-differences.md b/docs/guide/list-of-differences.md index 76f3e38578..94312c53c5 100644 --- a/docs/guide/list-of-differences.md +++ b/docs/guide/list-of-differences.md @@ -51,7 +51,6 @@ Very large or very small input scales can also cause substantial differences in | 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`. | -| Text returned by a function or a name in numeric aggregations | A2: =""
myName: =Sheet1!$A$2

=SUM(INDEX(A1:A3,2))

=SUM(CHOOSE(1,A2))

=SUM(IF(TRUE(),A2,0))

=SUM(myName,5) | Text is ignored only in a reference or a range written as the argument, with or without parentheses. A value returned by `INDEX`, `CHOOSE` or `IF`, or read through a named expression, is read like a literal, so text, including an empty string, makes `SUM`, `AVERAGE`, `MIN` and `MAX` return `#VALUE!`. | Not checked. | The text is ignored: the examples return `0`, `0`, `0` and `5`. | ## Built-in functions diff --git a/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts b/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts index 9183f80162..c9c0245ef8 100644 --- a/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts +++ b/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts @@ -18,6 +18,9 @@ import {AverageResult} from './AverageResult' import {MomentsAggregate} from './MomentsAggregate' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck, ImplementedFunctions} from './FunctionPlugin' import {RangeVertex} from '../../DependencyGraph' +import {FormulaVertex} from '../../DependencyGraph/FormulaVertex' +import {BooleanPlugin} from './BooleanPlugin' +import {InformationPlugin} from './InformationPlugin' export type BinaryOperation = (left: T, right: T) => T @@ -555,7 +558,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 @@ -576,6 +579,99 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function }, initialAccValue) } + /** + * Tells whether an argument other than a bare reference or range evaluates to 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` or `CHOOSE` whose every result argument is one of these or a number + * literal. A number reads the same whether it comes from a cell or not, so a number literal does + * not change how the result is read. `INDEX`, `IF` and `CHOOSE` count only while the built-in + * implementation answers for them, not a custom plugin registered over their ids. The check looks + * only at the formula, so no argument is evaluated a second time. + * + * @param {Ast} arg - the argument of the aggregation + * @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` with + * three arguments or `CHOOSE` whose result arguments are all references or number literals. + * + * @param {ProcedureAst} ast - the function call passed to the aggregation + * @param {InterpreterState} state - interpreter state + * @returns {boolean} whether the function call returns the content of a referenced cell + */ + private functionCallEvaluatesToReference(ast: ProcedureAst, state: InterpreterState): boolean { + const resultArgumentIsReferenceOrNumber = (resultArg: Ast) => isNumberLiteral(resultArg) || this.evaluatesToReference(resultArg, state) + const plugin = this.dependencyGraph.functionRegistry.getFunctionPlugin(ast.procedureName) + + switch (ast.procedureName) { + case 'INDEX': + if (plugin !== InformationPlugin) { + return false + } + return ast.args.length >= 1 && this.evaluatesToReference(ast.args[0], state) + case 'IF': + if (plugin !== BooleanPlugin) { + return false + } + return ast.args.length === 3 && ast.args.slice(1).every(resultArgumentIsReferenceOrNumber) + case 'CHOOSE': + if (plugin !== BooleanPlugin) { + return false + } + return ast.args.length >= 2 && ast.args.slice(1).every(resultArgumentIsReferenceOrNumber) + default: + return false + } + } + + /** + * 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 * @@ -685,6 +781,26 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function } } +/** + * Tells whether an AST is a number literal, optionally signed or in parentheses, such as `0` or `-1`. + * + * @param {Ast} ast - the AST to check + * @returns {boolean} whether the AST always evaluates to the same number + */ +function isNumberLiteral(ast: Ast): boolean { + switch (ast.type) { + case AstNodeType.NUMBER: + return true + case AstNodeType.PARENTHESIS: + return isNumberLiteral(ast.expression) + case AstNodeType.MINUS_UNARY_OP: + case AstNodeType.PLUS_UNARY_OP: + return isNumberLiteral(ast.value) + default: + return false + } +} + function strictlyNumbers(arg: InternalScalarValue): Maybe { if (isExtendedNumber(arg) || arg instanceof CellError) { return arg From 05f0a5271b5ade9d73790129d503083c4961af96 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Sun, 15 Nov 2026 21:11:53 +0000 Subject: [PATCH 15/20] HF-361: Order the Unreleased changelog sections as Keep a Changelog does Added comes before Changed in the Unreleased section, as on develop. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fed9b1a6a..f37a764fe3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,16 +7,16 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ## [Unreleased] -### Changed - -- **Breaking change**: Changed the license from GPLv3 to a proprietary license. HyperFormula is no longer available under GPLv3; see [`LICENSE.txt`](LICENSE.txt) for the new terms. Versions 3.x and earlier remain available under GPLv3. [#1885](https://github.com/handsontable/hyperformula/pull/1885) - ### Added - Added `LINEST` for simple and multiple linear regression, with optional intercept and regression statistics. The `stats` argument must be constant because result dimensions are determined before evaluation. [#1769](https://github.com/handsontable/hyperformula/pull/1769) - Added the `CONCAT` function, which joins text from values, ranges, and arrays, and the `VALUETOTEXT` function, which returns a value as text in a concise or a strict format. [#1816](https://github.com/handsontable/hyperformula/pull/1816) - Added the `maxParserCacheSize` configuration option to control the number of cached formulas. [#1635](https://github.com/handsontable/hyperformula/issues/1635) +### Changed + +- **Breaking change**: Changed the license from GPLv3 to a proprietary license. HyperFormula is no longer available under GPLv3; see [`LICENSE.txt`](LICENSE.txt) for the new terms. Versions 3.x and earlier remain available under GPLv3. [#1885](https://github.com/handsontable/hyperformula/pull/1885) + ### Fixed - Fixed the `EDATE` function returning the 28th of February instead of the 29th when the shifted date falls in February of a leap year (e.g. `=EDATE(DATE(2028, 1, 31), 1)` now returns `2028-02-29` instead of `2028-02-28`). [#1781](https://github.com/handsontable/hyperformula/pull/1781) From 2061f1571c45b31070521fdeb2322571befab5a1 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Sun, 15 Nov 2026 21:20:17 +0000 Subject: [PATCH 16/20] HF-361: Check the built-in plugin only for INDEX, IF and CHOOSE arguments The registry lookup now runs only for these three function calls. The changelog entry states the rule: a cell reached through INDEX, CHOOSE, IF or a named expression is read like a direct reference, so its text, booleans and blanks are ignored. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- .../plugin/NumericAggregationPlugin.ts | 36 +++++++++++-------- 2 files changed, 23 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f37a764fe3..9798664922 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,7 +30,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - 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`, `MIN` and `MAX` returning `#VALUE!` for text read from a cell through `INDEX`, `CHOOSE`, `IF` or a named expression, which they now ignore as they do for a direct reference. [#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` 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) ## [3.5.0] - 2026-10-09 diff --git a/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts b/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts index c9c0245ef8..0344be074a 100644 --- a/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts +++ b/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts @@ -16,7 +16,7 @@ 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' @@ -622,29 +622,37 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function */ private functionCallEvaluatesToReference(ast: ProcedureAst, state: InterpreterState): boolean { const resultArgumentIsReferenceOrNumber = (resultArg: Ast) => isNumberLiteral(resultArg) || this.evaluatesToReference(resultArg, state) - const plugin = this.dependencyGraph.functionRegistry.getFunctionPlugin(ast.procedureName) switch (ast.procedureName) { case 'INDEX': - if (plugin !== InformationPlugin) { - return false - } - return ast.args.length >= 1 && this.evaluatesToReference(ast.args[0], state) + return this.isBuiltIn('INDEX', InformationPlugin) + && ast.args.length >= 1 + && this.evaluatesToReference(ast.args[0], state) case 'IF': - if (plugin !== BooleanPlugin) { - return false - } - return ast.args.length === 3 && ast.args.slice(1).every(resultArgumentIsReferenceOrNumber) + return this.isBuiltIn('IF', BooleanPlugin) + && ast.args.length === 3 + && ast.args.slice(1).every(resultArgumentIsReferenceOrNumber) case 'CHOOSE': - if (plugin !== BooleanPlugin) { - return false - } - return ast.args.length >= 2 && ast.args.slice(1).every(resultArgumentIsReferenceOrNumber) + return this.isBuiltIn('CHOOSE', BooleanPlugin) + && ast.args.length >= 2 + && ast.args.slice(1).every(resultArgumentIsReferenceOrNumber) default: return false } } + /** + * 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. From 7afdb5732ae1d9873d5655e1364b09de4c5109f3 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Mon, 16 Nov 2026 09:04:31 +0000 Subject: [PATCH 17/20] HF-361: Read IF and CHOOSE by the argument they returned in aggregations The built-in IF and CHOOSE record which argument they returned, and the numeric aggregations read that record after evaluating the argument. An empty string or other text reached through the selected reference is then ignored even when another result argument is a text literal, as in =SUM(IF(TRUE(),A2,"")), =SUM(IF(TRUE(),A2)) and =SUM(CHOOSE(1,A2,"")). No argument is evaluated a second time. Co-Authored-By: Claude Opus 5.5 --- .../src/interpreter/plugin/BooleanPlugin.ts | 62 ++++++++++++++++++- .../plugin/NumericAggregationPlugin.ts | 62 ++++++------------- 2 files changed, 79 insertions(+), 45 deletions(-) diff --git a/hyperformula/src/interpreter/plugin/BooleanPlugin.ts b/hyperformula/src/interpreter/plugin/BooleanPlugin.ts index a11c269b25..2a1b8b4c33 100644 --- a/hyperformula/src/interpreter/plugin/BooleanPlugin.ts +++ b/hyperformula/src/interpreter/plugin/BooleanPlugin.ts @@ -5,11 +5,32 @@ import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' -import {ProcedureAst} from '../../parser' +import {Maybe} from '../../Maybe' +import {Ast, ProcedureAst} from '../../parser' import {InterpreterState} from '../InterpreterState' import {InternalNoErrorScalarValue, InternalScalarValue, InterpreterValue} from '../InterpreterValue' +import {SimpleRangeValue} from '../../SimpleRangeValue' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck, ImplementedFunctions} from './FunctionPlugin' +/** + * For a call to `IF` or `CHOOSE`, 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 that returned the + * default value of an omitted argument, or one that returned an array, has no entry. + */ +const selectedArguments = new WeakMap() + +/** + * Returns the argument that the call to `IF` or `CHOOSE` 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 `IF` or `CHOOSE` evaluated by this 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) +} + /** * Interpreter plugin containing boolean functions */ @@ -135,9 +156,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) => { + selectedArguments.delete(ast) + const result = this.runFunction(ast.args, state, this.metadata('IF'), (condition, arg2, arg3) => { + recordSelectedArgument(ast, condition ? 1 : 2) return condition ? arg2 : arg3 }) + return forgetSelectionUnlessScalar(ast, result) } /** @@ -242,11 +266,43 @@ 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) => { + selectedArguments.delete(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 forgetSelectionUnlessScalar(ast, result) + } +} + +/** + * Records that a call to `IF` or `CHOOSE` returned its argument at the given position. + * + * @param {ProcedureAst} ast - the call + * @param {number} position - the position of the returned argument in `ast.args` + */ +function recordSelectedArgument(ast: ProcedureAst, position: number): void { + const argument = ast.args[position] + if (argument === undefined) { + selectedArguments.delete(ast) + } else { + selectedArguments.set(ast, argument) + } +} + +/** + * Removes the record of a call that returned an array, where each cell can come from a different argument. + * + * @param {ProcedureAst} ast - the call + * @param {InterpreterValue} result - what the call returned + * @returns {InterpreterValue} `result`, unchanged + */ +function forgetSelectionUnlessScalar(ast: ProcedureAst, result: InterpreterValue): InterpreterValue { + if (result instanceof SimpleRangeValue) { + selectedArguments.delete(ast) } + return result } diff --git a/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts b/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts index 0344be074a..6710344872 100644 --- a/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts +++ b/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts @@ -19,7 +19,7 @@ import {MomentsAggregate} from './MomentsAggregate' import {FunctionArgumentType, FunctionPlugin, FunctionPluginDefinition, FunctionPluginTypecheck, ImplementedFunctions} from './FunctionPlugin' import {RangeVertex} from '../../DependencyGraph' import {FormulaVertex} from '../../DependencyGraph/FormulaVertex' -import {BooleanPlugin} from './BooleanPlugin' +import {BooleanPlugin, selectedArgument} from './BooleanPlugin' import {InformationPlugin} from './InformationPlugin' export type BinaryOperation = (left: T, right: T) => T @@ -580,17 +580,17 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function } /** - * Tells whether an argument other than a bare reference or range evaluates to the content of a - * referenced cell, so that the aggregation ignores its non-numeric values as it does for `A1`. + * 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` or `CHOOSE` whose every result argument is one of these or a number - * literal. A number reads the same whether it comes from a cell or not, so a number literal does - * not change how the result is read. `INDEX`, `IF` and `CHOOSE` count only while the built-in - * implementation answers for them, not a custom plugin registered over their ids. The check looks - * only at the formula, so no argument is evaluated a second time. + * over a reference, and `IF` or `CHOOSE` whose evaluation returned one of these. `IF` and `CHOOSE` + * report the argument they returned, so no argument is evaluated a second time. `INDEX`, `IF` and + * `CHOOSE` 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 + * @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 */ @@ -613,29 +613,27 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function } /** - * The function-call case of {@link evaluatesToReference}: `INDEX` over a reference, and `IF` with - * three arguments or `CHOOSE` whose result arguments are all references or number literals. + * The function-call case of {@link evaluatesToReference}: `INDEX` over a reference, and `IF` or + * `CHOOSE` that returned a reference. * - * @param {ProcedureAst} ast - the function call passed to the aggregation + * @param {ProcedureAst} ast - the function call passed to the aggregation, already evaluated * @param {InterpreterState} state - interpreter state - * @returns {boolean} whether the function call returns the content of a referenced cell + * @returns {boolean} whether the function call returned the content of a referenced cell */ private functionCallEvaluatesToReference(ast: ProcedureAst, state: InterpreterState): boolean { - const resultArgumentIsReferenceOrNumber = (resultArg: Ast) => isNumberLiteral(resultArg) || this.evaluatesToReference(resultArg, state) - switch (ast.procedureName) { case 'INDEX': return this.isBuiltIn('INDEX', InformationPlugin) && ast.args.length >= 1 && this.evaluatesToReference(ast.args[0], state) case 'IF': - return this.isBuiltIn('IF', BooleanPlugin) - && ast.args.length === 3 - && ast.args.slice(1).every(resultArgumentIsReferenceOrNumber) - case 'CHOOSE': - return this.isBuiltIn('CHOOSE', BooleanPlugin) - && ast.args.length >= 2 - && ast.args.slice(1).every(resultArgumentIsReferenceOrNumber) + case 'CHOOSE': { + if (!this.isBuiltIn(ast.procedureName, BooleanPlugin)) { + return false + } + const returnedArgument = selectedArgument(ast) + return returnedArgument !== undefined && this.evaluatesToReference(returnedArgument, state) + } default: return false } @@ -789,26 +787,6 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function } } -/** - * Tells whether an AST is a number literal, optionally signed or in parentheses, such as `0` or `-1`. - * - * @param {Ast} ast - the AST to check - * @returns {boolean} whether the AST always evaluates to the same number - */ -function isNumberLiteral(ast: Ast): boolean { - switch (ast.type) { - case AstNodeType.NUMBER: - return true - case AstNodeType.PARENTHESIS: - return isNumberLiteral(ast.expression) - case AstNodeType.MINUS_UNARY_OP: - case AstNodeType.PLUS_UNARY_OP: - return isNumberLiteral(ast.value) - default: - return false - } -} - function strictlyNumbers(arg: InternalScalarValue): Maybe { if (isExtendedNumber(arg) || arg instanceof CellError) { return arg From afb1cfb19c2997dab9362601e9d459e0cf1371ef Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Mon, 16 Nov 2026 09:35:20 +0000 Subject: [PATCH 18/20] HF-361: Read IFS and SWITCH by the argument they returned in aggregations Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- .../src/interpreter/plugin/BooleanPlugin.ts | 28 ++++++++++++------- .../plugin/NumericAggregationPlugin.ts | 15 ++++++---- 3 files changed, 28 insertions(+), 17 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9798664922..d9171b5aa2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,7 +30,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - 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` 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 numeric aggregations such as `SUM`, `AVERAGE` and `MAX` reading a cell reached through `INDEX`, `CHOOSE`, `IF`, `IFS`, `SWITCH` 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) ## [3.5.0] - 2026-10-09 diff --git a/hyperformula/src/interpreter/plugin/BooleanPlugin.ts b/hyperformula/src/interpreter/plugin/BooleanPlugin.ts index 2a1b8b4c33..06f3066264 100644 --- a/hyperformula/src/interpreter/plugin/BooleanPlugin.ts +++ b/hyperformula/src/interpreter/plugin/BooleanPlugin.ts @@ -13,18 +13,19 @@ import {SimpleRangeValue} from '../../SimpleRangeValue' import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck, ImplementedFunctions} from './FunctionPlugin' /** - * For a call to `IF` or `CHOOSE`, 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 that returned the - * default value of an omitted argument, or one that returned an array, has no entry. + * For a call to `IF`, `IFS`, `SWITCH` or `CHOOSE`, 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 or case matched, one that returned the default value of an omitted argument, or one that + * returned an array, has no entry. */ const selectedArguments = new WeakMap() /** - * Returns the argument that the call to `IF` or `CHOOSE` 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. + * Returns the argument that the call to `IF`, `IFS`, `SWITCH` or `CHOOSE` 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 `IF` or `CHOOSE` evaluated by this plugin + * @param {ProcedureAst} ast - a call to `IF`, `IFS`, `SWITCH` or `CHOOSE` evaluated by this plugin * @returns {Maybe} the returned argument, or `undefined` when the call returned none of its arguments */ export function selectedArgument(ast: ProcedureAst): Maybe { @@ -171,14 +172,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) => { + selectedArguments.delete(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 forgetSelectionUnlessScalar(ast, result) } /** @@ -226,7 +230,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) => { + selectedArguments.delete(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) { @@ -234,15 +239,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 forgetSelectionUnlessScalar(ast, result) } public iferror(ast: ProcedureAst, state: InterpreterState): InterpreterValue { @@ -279,7 +287,7 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec } /** - * Records that a call to `IF` or `CHOOSE` returned its argument at the given position. + * Records that a call to `IF`, `IFS`, `SWITCH` or `CHOOSE` returned its argument at the given position. * * @param {ProcedureAst} ast - the call * @param {number} position - the position of the returned argument in `ast.args` diff --git a/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts b/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts index 6710344872..9abdf20396 100644 --- a/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts +++ b/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts @@ -585,10 +585,11 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function * as it does for `A1`. * * That holds for a parenthesized reference, a named expression defined as a reference, `INDEX` - * over a reference, and `IF` or `CHOOSE` whose evaluation returned one of these. `IF` and `CHOOSE` - * report the argument they returned, so no argument is evaluated a second time. `INDEX`, `IF` and - * `CHOOSE` count only while the built-in implementation answers for them, not a custom plugin - * registered over their ids. + * over a reference, and `IF`, `IFS`, `SWITCH` or `CHOOSE` whose evaluation returned one of these. + * These four report the argument they returned, so no argument is evaluated a second time. `IFERROR` + * and `IFNA` are not among them: they return the value of the cell, as in Excel. `INDEX`, `IF`, `IFS`, + * `SWITCH` and `CHOOSE` 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 @@ -613,8 +614,8 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function } /** - * The function-call case of {@link evaluatesToReference}: `INDEX` over a reference, and `IF` or - * `CHOOSE` that returned a reference. + * The function-call case of {@link evaluatesToReference}: `INDEX` over a reference, and `IF`, `IFS`, + * `SWITCH` or `CHOOSE` that returned a reference. * * @param {ProcedureAst} ast - the function call passed to the aggregation, already evaluated * @param {InterpreterState} state - interpreter state @@ -627,6 +628,8 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function && ast.args.length >= 1 && this.evaluatesToReference(ast.args[0], state) case 'IF': + case 'IFS': + case 'SWITCH': case 'CHOOSE': { if (!this.isBuiltIn(ast.procedureName, BooleanPlugin)) { return false From 0dcb98691d517039f0d8184f921e83d91cf2c80b Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 19 Nov 2026 10:20:27 +0000 Subject: [PATCH 19/20] Read XLOOKUP results and IF or CHOOSE ranges as references in numeric aggregations (HF-361) XLOOKUP records whether it returned from return_array or from if_not_found, in the same record that IF, IFS, SWITCH and CHOOSE use, so SUM, AVERAGE and the other numeric aggregations ignore text it returns from a reference, as in Excel. In array arithmetic mode, IF, IFS, SWITCH and CHOOSE keep the record when they return a range from a single argument, so INDEX over them reads a reference; an array built cell by cell from an array condition, selector or case value still has no record. No argument is evaluated twice. Empty text used as a number now returns #VALUE!, so the list of differences no longer lists it. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- docs/guide/list-of-differences.md | 1 - .../src/interpreter/plugin/BooleanPlugin.ts | 99 +++++++++---------- .../src/interpreter/plugin/LookupPlugin.ts | 26 ++++- .../plugin/NumericAggregationPlugin.ts | 40 +++++--- .../interpreter/plugin/SelectedArgument.ts | 51 ++++++++++ 6 files changed, 144 insertions(+), 75 deletions(-) create mode 100644 hyperformula/src/interpreter/plugin/SelectedArgument.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f566eb1da4..ca983e41de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,7 +40,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - 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` 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 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) ## [3.5.0] - 2026-10-09 diff --git a/docs/guide/list-of-differences.md b/docs/guide/list-of-differences.md index c7087b98d1..8fadba615f 100644 --- a/docs/guide/list-of-differences.md +++ b/docs/guide/list-of-differences.md @@ -31,7 +31,6 @@ Very large or very small input scales can also cause substantial differences in | 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 | diff --git a/hyperformula/src/interpreter/plugin/BooleanPlugin.ts b/hyperformula/src/interpreter/plugin/BooleanPlugin.ts index 3b0268796d..e872f5b162 100644 --- a/hyperformula/src/interpreter/plugin/BooleanPlugin.ts +++ b/hyperformula/src/interpreter/plugin/BooleanPlugin.ts @@ -5,32 +5,12 @@ import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' -import {Maybe} from '../../Maybe' import {Ast, ProcedureAst} from '../../parser' import {InterpreterState} from '../InterpreterState' import {InternalNoErrorScalarValue, InternalScalarValue, InterpreterValue} from '../InterpreterValue' import {SimpleRangeValue} from '../../SimpleRangeValue' -import {FunctionArgumentType, FunctionPlugin, FunctionPluginTypecheck, ImplementedFunctions} from './FunctionPlugin' - -/** - * For a call to `IF`, `IFS`, `SWITCH` or `CHOOSE`, 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 or case matched, one that returned the default value of an omitted argument, or one that - * returned an array, has no entry. - */ -const selectedArguments = new WeakMap() - -/** - * Returns the argument that the call to `IF`, `IFS`, `SWITCH` or `CHOOSE` 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 `IF`, `IFS`, `SWITCH` or `CHOOSE` evaluated by this 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) -} +import {FunctionArgumentType, FunctionMetadata, FunctionPlugin, FunctionPluginTypecheck, ImplementedFunctions} from './FunctionPlugin' +import {forgetSelectedArgument, recordSelectedArgument} from './SelectedArgument' /** * Interpreter plugin containing boolean functions @@ -124,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() * @@ -157,12 +142,12 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec * @param state */ public conditionalIf(ast: ProcedureAst, state: InterpreterState): InterpreterValue { - selectedArguments.delete(ast) + 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 forgetSelectionUnlessScalar(ast, result) + return this.keepSelectionOnlyForScalarSelectors(ast, result, [0]) } /** @@ -172,7 +157,7 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec * @param state */ public ifs(ast: ProcedureAst, state: InterpreterState): InterpreterValue { - selectedArguments.delete(ast) + 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]) { @@ -182,7 +167,7 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec } return new CellError(ErrorType.NA, ErrorMessage.NoConditionMet) }) - return forgetSelectionUnlessScalar(ast, result) + return this.keepSelectionOnlyForScalarSelectors(ast, result, ast.args.map((_, i) => i).filter(i => i % 2 === 0)) } /** @@ -230,7 +215,7 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec } public switch(ast: ProcedureAst, state: InterpreterState): InterpreterValue { - selectedArguments.delete(ast) + forgetSelectedArgument(ast) const result = this.runFunction(ast.args, state, this.metadata('SWITCH'), (selector, ...args) => { const n = args.length let i = 0 @@ -250,7 +235,7 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec return new CellError(ErrorType.NA, ErrorMessage.NoDefault) } }) - return forgetSelectionUnlessScalar(ast, result) + 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 { @@ -274,7 +259,7 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec } public choose(ast: ProcedureAst, state: InterpreterState): InterpreterValue { - selectedArguments.delete(ast) + 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) @@ -282,35 +267,39 @@ export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypec recordSelectedArgument(ast, selector) return args[selector - 1] }) - return forgetSelectionUnlessScalar(ast, result) + return this.keepSelectionOnlyForScalarSelectors(ast, result, [0]) } -} -/** - * Records that a call to `IF`, `IFS`, `SWITCH` or `CHOOSE` returned its argument at the given position. - * - * @param {ProcedureAst} ast - the call - * @param {number} position - the position of the returned argument in `ast.args` - */ -function recordSelectedArgument(ast: ProcedureAst, position: number): void { - const argument = ast.args[position] - if (argument === undefined) { - selectedArguments.delete(ast) - } else { - selectedArguments.set(ast, argument) + /** + * 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, where each cell can come from a different argument. - * - * @param {ProcedureAst} ast - the call - * @param {InterpreterValue} result - what the call returned - * @returns {InterpreterValue} `result`, unchanged - */ -function forgetSelectionUnlessScalar(ast: ProcedureAst, result: InterpreterValue): InterpreterValue { - if (result instanceof SimpleRangeValue) { - selectedArguments.delete(ast) + /** + * 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 } - return result } diff --git a/hyperformula/src/interpreter/plugin/LookupPlugin.ts b/hyperformula/src/interpreter/plugin/LookupPlugin.ts index 7f0b3226aa..09e805696b 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 b06e44702f..83383d85fc 100644 --- a/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts +++ b/hyperformula/src/interpreter/plugin/NumericAggregationPlugin.ts @@ -19,8 +19,10 @@ import {MomentsAggregate} from './MomentsAggregate' import {FunctionArgumentType, FunctionPlugin, FunctionPluginDefinition, FunctionPluginTypecheck, ImplementedFunctions} from './FunctionPlugin' import {RangeVertex} from '../../DependencyGraph' import {FormulaVertex} from '../../DependencyGraph/FormulaVertex' -import {BooleanPlugin, selectedArgument} from './BooleanPlugin' +import {BooleanPlugin} from './BooleanPlugin' import {InformationPlugin} from './InformationPlugin' +import {LookupPlugin} from './LookupPlugin' +import {selectedArgument} from './SelectedArgument' export type BinaryOperation = (left: T, right: T) => T @@ -585,11 +587,11 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function * 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` or `CHOOSE` whose evaluation returned one of these. - * These four report the argument they returned, so no argument is evaluated a second time. `IFERROR` - * and `IFNA` are not among them: they return the value of the cell, as in Excel. `INDEX`, `IF`, `IFS`, - * `SWITCH` and `CHOOSE` count only while the built-in implementation answers for them, not a custom - * plugin registered over their ids. + * 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 @@ -615,7 +617,7 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function /** * The function-call case of {@link evaluatesToReference}: `INDEX` over a reference, and `IF`, `IFS`, - * `SWITCH` or `CHOOSE` that returned a reference. + * `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 @@ -630,18 +632,28 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function case 'IF': case 'IFS': case 'SWITCH': - case 'CHOOSE': { - if (!this.isBuiltIn(ast.procedureName, BooleanPlugin)) { - return false - } - const returnedArgument = selectedArgument(ast) - return returnedArgument !== undefined && this.evaluatesToReference(returnedArgument, state) - } + 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. diff --git a/hyperformula/src/interpreter/plugin/SelectedArgument.ts b/hyperformula/src/interpreter/plugin/SelectedArgument.ts new file mode 100644 index 0000000000..ddc068890e --- /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) + } +} From c4c3ad86f5ceae7b06edfd47470fe025fddbe2aa Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 19 Nov 2026 14:35:19 +0000 Subject: [PATCH 20/20] Remove the RANK.EQ empty-string rows from the list of differences An empty string given as RANK.EQ's number or order now returns #VALUE!, as in Excel. Co-Authored-By: Claude Opus 5.5 --- docs/guide/list-of-differences.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/docs/guide/list-of-differences.md b/docs/guide/list-of-differences.md index ab099f291a..23973780c6 100644 --- a/docs/guide/list-of-differences.md +++ b/docs/guide/list-of-differences.md @@ -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: