diff --git a/CHANGELOG.md b/CHANGELOG.md index 114abd4838..3eb4250cf8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Changed - Changed `XLOOKUP` with `search_mode` 2 or -2 to find more exact matches in a range that is not sorted, e.g. 3 in 5, 1, 3, 2, 4, where it returned no match before. The result on unsorted data is still not guaranteed. [#1806](https://github.com/handsontable/hyperformula/pull/1806) -- Changed the cell errors produced while evaluating a formula to carry a message describing their cause. [#1547](https://github.com/handsontable/hyperformula/issues/1547) +- Changed the cell errors the engine produces, including invalidated references, circular references and error values typed into a formula, to carry a message describing their cause. [#1547](https://github.com/handsontable/hyperformula/issues/1547) ### Added @@ -24,6 +24,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Fixed the parser rejecting formulas with the function-name prefixes that Excel writes into `.xlsx` files (e.g. `_xlfn.XLOOKUP`), which are now ignored and left out of `getCellFormula()`. [#1655](https://github.com/handsontable/hyperformula/issues/1655) - Fixed approximate `MATCH`, `VLOOKUP` and `HLOOKUP`, and `XLOOKUP` with `search_mode` 2 or -2, misordering text that differs in letter case or accents, e.g. `=MATCH("é", A1:A3, 1)` over a, é, f now returns `2` instead of `1`. [#1806](https://github.com/handsontable/hyperformula/pull/1806) +- Fixed `DetailedCellError.address` for a typed-in error, an unparsable formula, or an overflow such as `=10^308*10`: the cell and every formula reading it now report the error's own cell, instead of none and each reader's own address. [#1547](https://github.com/handsontable/hyperformula/issues/1547) ## [4.0.0] - 2026-12-02 diff --git a/hyperformula/.eslintrc.js b/hyperformula/.eslintrc.js index 561735096e..899a1b091b 100644 --- a/hyperformula/.eslintrc.js +++ b/hyperformula/.eslintrc.js @@ -161,12 +161,14 @@ module.exports = { } }, { - files: ['**/src/interpreter/**/*.ts'], + files: ['**/src/**/*.ts'], rules: { // An engine-thrown cell error must always state its cause. // The public `CellError` constructor keeps `message` optional for custom // functions (docs/guide/custom-functions.md); this rule enforces the - // stricter contract on our own code only. + // stricter contract on our own code only. It is a syntactic floor, not a + // proof of completeness — see the comment at CellContentParser.ts's + // `CellContent.Error` constructor for a call site it cannot catch. 'no-restricted-syntax': ['error', { selector: "NewExpression[callee.name='CellError'][arguments.length<2]", diff --git a/hyperformula/dev-docs/INTERPRETER.md b/hyperformula/dev-docs/INTERPRETER.md index f99fa87f7b..99494371c7 100644 --- a/hyperformula/dev-docs/INTERPRETER.md +++ b/hyperformula/dev-docs/INTERPRETER.md @@ -20,6 +20,8 @@ - **Coerce through `ArithmeticHelper`.** Never write ad-hoc string-to-number or value-to-boolean conversion inside a function; the coercion rules are spreadsheet semantics, not JavaScript semantics, and they are already implemented once. - **Errors are values.** Return a `CellError` with a message from `hyperformula/src/error-message.ts`. Do not throw: a thrown error escapes the evaluation of one cell and takes the recalculation with it. +- **Read cell values through `DependencyGraph.getCellValue`.** It marks an error read from another cell as propagated, and stamps the address of a cell that holds a typed or unparsable error. Reading the address mapping directly skips both, and the reading cell is then reported as the error's origin. +- **Pass a read error on unchanged.** An error that came from an argument or another cell already names its origin; return that instance. `withOrigin` and `withArgumentIndex` keep the first value set and ignore a propagated error, so a function that only received an error never takes it over. Building a new `CellError` from a read error's type discards its origin and address. - **Never spread a range's values into a call.** `push(...values)` and `Math.max(...values)` pass one argument per value, and a range or array of about 125,000 values (Node 24, default stack size) throws `RangeError: Maximum call stack size exceeded` out of the recalculation. Append in a loop. - **The registry is keyed by id, not by implementation.** A custom plugin can be registered over a built-in id. Do not assume the plugin you are reading is the one that will answer for that id at run time. - **Evaluate each argument once.** Evaluating the same argument twice doubles its cost and, when it contains a volatile function such as `RAND`, can see two different values. diff --git a/hyperformula/src/Cell.ts b/hyperformula/src/Cell.ts index 7883cd5c28..00be92b25d 100644 --- a/hyperformula/src/Cell.ts +++ b/hyperformula/src/Cell.ts @@ -149,14 +149,155 @@ export const getCellValueFormat = (cellValue: InterpreterValue): string | undefi } } +/** + * The propagated copy of each error, made once. Every read of a cell that holds an error goes through + * `asPropagated`, and the evaluator reports a cell as changed when its new value is a different + * object, so a fresh copy per read would report an unchanged error as a change. A `WeakMap` rather + * than a field keeps the error's own properties, which equality checks compare, unchanged. + */ +const propagatedCopies = new WeakMap() + +/** The origin-locked copy of each error, made once, for the same reason as `propagatedCopies`. */ +const originLockedCopies = new WeakMap() + export class CellError { constructor( public readonly type: ErrorType, public readonly message?: string, - public readonly root?: FormulaVertex + public readonly root?: FormulaVertex, + public readonly originFunction?: string, + public readonly argumentIndex?: number, + /** @internal */ + public readonly propagated: boolean = false, + /** @internal */ + public readonly originAddress?: SimpleCellAddress, + /** @internal */ + public readonly originAddressVersion?: number, + /** @internal */ + public readonly originLocked: boolean = false, ) { } + /** + * Names the function or operator that produced this error. + * + * First occurrence wins, so an outer function that merely received the error back does not + * claim it: `=SUM(SQRT(-1))` keeps `SQRT`. Two kinds of error never acquire an origin they did + * not already have: + * - a propagated error, one read out of another cell rather than produced here; + * - an origin-locked error, one written into the formula itself (see {@link asOriginLocked}), so + * `=SUM(#N/A)`, `=#DIV/0!+1` and `=SUM(#REF!)` left by a removed column name no function. + * + * @param {string} functionName - the function or operator helper that produced the error + * + * @internal + */ + public withOrigin(functionName: string): CellError { + if (this.propagated || this.originLocked || this.originFunction !== undefined) { + return this + } + return new CellError(this.type, this.message, this.root, functionName, this.argumentIndex, this.propagated, this.originAddress, this.originAddressVersion, this.originLocked) + } + + /** + * Records which argument of the origin function was rejected. First occurrence wins, and a + * propagated error never acquires one: the reading function's own argument slot is not the + * offending argument. + * + * @param {number} index - zero-based index of the offending argument + * + * @internal + */ + public withArgumentIndex(index: number): CellError { + if (this.propagated || this.argumentIndex !== undefined) { + return this + } + return new CellError(this.type, this.message, this.root, this.originFunction, index, this.propagated, this.originAddress, this.originAddressVersion, this.originLocked) + } + + /** + * Marks this error as having all the origin it will ever have, so `withOrigin` leaves it alone. + * + * The interpreter applies it to the error an `ERROR` or `ERROR_WITH_RAW_INPUT` node evaluates + * to: an error value typed into the formula, the `#REF!` a reference turns into once its row or + * column is removed, or the error the parser puts in place of a reference it cannot resolve or + * one beyond the sheet size limits. A reference to a removed sheet stays a reference and is not + * such a node. No function or operator produced such an error, so the first one + * that receives it must not claim it. Unlike `asPropagated`, it leaves the root vertex to be + * attached as usual, so the error is still reported at the cell whose formula contains it. + * + * @internal + */ + public asOriginLocked(): CellError { + if (this.originLocked) { + return this + } + let copy = originLockedCopies.get(this) + if (copy === undefined) { + copy = new CellError(this.type, this.message, this.root, this.originFunction, this.argumentIndex, this.propagated, this.originAddress, this.originAddressVersion, true) + originLockedCopies.set(this, copy) + } + return copy + } + + /** + * Marks this error as read from another cell rather than produced by the current evaluation. + * + * This is what stops a cell from adopting an error it only read: `wrapperForRootVertex` in + * `Interpreter.ts` does not attach the evaluating cell as the root of a propagated error, so the + * reported address stays the one where the error actually appeared. + * + * @internal + */ + public asPropagated(): CellError { + if (this.propagated) { + return this + } + let copy = propagatedCopies.get(this) + if (copy === undefined) { + copy = new CellError(this.type, this.message, this.root, this.originFunction, this.argumentIndex, true, this.originAddress, this.originAddressVersion, this.originLocked) + propagatedCopies.set(this, copy) + } + return copy + } + + /** + * Records the address an otherwise rootless error appeared at, and the moment it was recorded. + * + * For vertices that hold a static error rather than computing one (a parse error, or an error + * value the user typed), there is no `FormulaVertex` to serve as a lazily-resolved `root`, so + * the address has to be recorded on the value itself. A recorded address is a snapshot and does + * go stale: the cell that read it caches this instance, and a later row or column change that + * merely shifts that cell does not recompute it. The `version` is what makes the snapshot + * repairable — it names the point in `LazilyTransformingAstService`'s history the address was + * true at, so `Exporter` can replay the intervening transformations over it and report where the + * origin sits now. See {@link LazilyTransformingAstService.applyTransformationsToAddress}. + * + * @param {SimpleCellAddress} address - the address the error was read from + * @param {number} version - the transformation version that address was current at + * + * @internal + */ + public withOriginAddress(address: SimpleCellAddress, version: number): CellError { + if (this.originAddress !== undefined) { + return this + } + return new CellError(this.type, this.message, this.root, this.originFunction, this.argumentIndex, this.propagated, address, version, this.originLocked) + } + + /** + * Replaces the recorded origin address with the same origin expressed at a later transformation + * version. Used before old transformations are discarded, so that a cached copy of a static + * error can still be moved by the transformations that follow. + * + * @param {SimpleCellAddress} address - the origin address as it is at `version` + * @param {number} version - the transformation version that address is current at + * @internal + */ + public withRebasedOriginAddress(address: SimpleCellAddress, version: number): CellError { + return new CellError(this.type, this.message, this.root, this.originFunction, this.argumentIndex, this.propagated, address, version, this.originLocked) + } + /** * Returns a CellError with a given message. * @param {string} detailedMessage - message to be displayed @@ -167,7 +308,7 @@ export class CellError { public attachRootVertex(vertex: FormulaVertex): CellError { if (this.root === undefined) { - return new CellError(this.type, this.message, vertex) + return new CellError(this.type, this.message, vertex, this.originFunction, this.argumentIndex, this.propagated, this.originAddress, this.originAddressVersion, this.originLocked) } else { return this } diff --git a/hyperformula/src/CellContentParser.ts b/hyperformula/src/CellContentParser.ts index 81552c66d9..00c25861d0 100644 --- a/hyperformula/src/CellContentParser.ts +++ b/hyperformula/src/CellContentParser.ts @@ -61,6 +61,15 @@ export namespace CellContent { export class Error { public readonly value: CellError + // `message` stays optional here on purpose. This constructor's only + // no-message caller is the `errorMapping` lookup below (a user typing e.g. + // `#REF!` literally into a cell) — the engine has no cause to state beyond + // "the user wrote this", so leaving it unset is honest, not an oversight. + // This is also the concrete case the cell-error ESLint rule (.eslintrc.js) cannot + // catch: the call `new CellError(errorType, message)` is syntactically a + // two-argument construction and passes the rule cleanly even when the + // caller passes no message, because the rule only inspects this call site, + // not who calls it. constructor(errorType: ErrorType, message?: string) { this.value = new CellError(errorType, message) } diff --git a/hyperformula/src/ContentChanges.ts b/hyperformula/src/ContentChanges.ts index da27b5f072..201769f226 100644 --- a/hyperformula/src/ContentChanges.ts +++ b/hyperformula/src/ContentChanges.ts @@ -3,7 +3,7 @@ * Copyright (c) Handsoncode sp. z o.o. All rights reserved. */ -import {addressKey, SimpleCellAddress} from './Cell' +import {addressKey, CellError, SimpleCellAddress} from './Cell' import {InterpreterValue} from './interpreter/InterpreterValue' import {SimpleRangeValue} from './SimpleRangeValue' @@ -58,6 +58,19 @@ export class ContentChanges { return this.changes.size === 0 } + /** + * Replaces each error value in the list with the result of `fn`. + * + * @param {function} fn - maps an error to the error the change should carry instead + */ + public mapErrorValues(fn: (error: CellError) => CellError): void { + for (const change of this.changes.values()) { + if (change.value instanceof CellError) { + change.value = fn(change.value) + } + } + } + private add(address: SimpleCellAddress, change: CellValueChange) { const value = change.value if (value instanceof SimpleRangeValue) { diff --git a/hyperformula/src/DependencyGraph/DependencyGraph.ts b/hyperformula/src/DependencyGraph/DependencyGraph.ts index 60bde5d541..9a16050a5c 100644 --- a/hyperformula/src/DependencyGraph/DependencyGraph.ts +++ b/hyperformula/src/DependencyGraph/DependencyGraph.ts @@ -6,7 +6,7 @@ import {AbsoluteCellRange, SimpleCellRange, simpleCellRange} from '../AbsoluteCellRange' import {absolutizeDependencies} from '../absolutizeDependencies' import {ArraySize} from '../ArraySize' -import {CellError, ErrorType, isSimpleCellAddress, simpleCellAddress, SimpleCellAddress} from '../Cell' +import {CellError, equalSimpleCellAddress, ErrorType, isSimpleCellAddress, simpleCellAddress, SimpleCellAddress} from '../Cell' import {RawCellContent} from '../CellContentParser' import {CellDependency} from '../CellDependency' import {Config} from '../Config' @@ -50,6 +50,13 @@ import {TopSortResult} from './TopSort' import { findBoundaries } from '../Sheet' export class DependencyGraph { + /** + * Per vertex that holds a static error, the error last read from it and its stamped, propagated + * copy (see `getCellValue`). Keyed by the vertex because a parsing-error vertex builds a new error + * on every read. + */ + private stampedStaticErrors = new WeakMap() + public readonly graph: Graph private changes: ContentChanges = ContentChanges.empty() public readonly sheetReferenceRegistrar: SheetReferenceRegistrar @@ -614,7 +621,57 @@ export class DependencyGraph { return new CellError(ErrorType.REF, ErrorMessage.SheetRef) } - return this.addressMapping.getCellValue(address) + const value = this.addressMapping.getCellValue(address) + if (!(value instanceof CellError)) { + return value + } + + // Every read of another cell's value funnels through here, which makes this the one place + // that can tell "this error was produced by the current evaluation" from "this error was + // read from somewhere else". Marking it propagated is what stops the reading cell from + // being reported as the origin. + // + // A vertex holding a STATIC error (a parse error, or an error value the user typed) has no + // FormulaVertex to act as a root, so the address is stamped here instead, together with the + // transformation version it is true at. The reading cell caches the stamped copy and is not + // recomputed by a row or column change that merely shifts it, so the address alone would go + // stale; the version lets Exporter replay the intervening transformations over it. + const vertex = this.addressMapping.getCell(address) + if (!(vertex instanceof ParsingErrorVertex || vertex instanceof ValueCellVertex)) { + return value.asPropagated() + } + // Reuse the stamped copy while the address and the version still hold: the evaluator reports a + // cell as changed when its new value is a different object, so a fresh copy per read would report + // a formula that reads the same error again as changed. + const version = this.lazilyTransformingAstService.version() + const cached = this.stampedStaticErrors.get(vertex) + if ( + cached !== undefined + && (vertex instanceof ParsingErrorVertex || cached.source === value) + && this.stampedAddressStillHolds(cached, address, version) + ) { + // Move the entry to the current version, so the next read compares it directly instead of + // replaying every pending transformation again. The stamped error keeps its own version, + // which Exporter replays from. + cached.address = address + cached.version = version + return cached.stamped + } + const stamped = value.withOriginAddress(address, version).asPropagated() + this.stampedStaticErrors.set(vertex, {source: value, stamped, address, version}) + return stamped + } + + /** + * Whether a stamp still names `address`: the address it was stamped with, carried through + * the transformations since its version, is `address`. Exporter carries it the same way, so the + * old stamp reports the right cell and can be reused across row and column changes. + */ + private stampedAddressStillHolds(stamp: { address: SimpleCellAddress, version: number }, address: SimpleCellAddress, version: number): boolean { + const current = stamp.version === version + ? stamp.address + : this.lazilyTransformingAstService.applyTransformationsToAddress(stamp.address, stamp.version) + return current !== undefined && equalSimpleCellAddress(current, address) } public getRawValue(address: SimpleCellAddress): RawCellContent { @@ -626,11 +683,9 @@ export class DependencyGraph { } public getScalarValue(address: SimpleCellAddress): InternalScalarValue { - if (this.isPlaceholder(address.sheet)) { - return new CellError(ErrorType.REF, ErrorMessage.SheetRef) - } - - const value = this.addressMapping.getCellValue(address) + // Delegates rather than reading the address mapping itself, so that every caller of this + // method inherits the propagated marking above instead of bypassing it. + const value = this.getCellValue(address) if (value instanceof SimpleRangeValue) { return new CellError(ErrorType.VALUE, ErrorMessage.ScalarExpected) } @@ -673,14 +728,51 @@ export class DependencyGraph { this.graph.markNodeAsChangingWithStructure(vertex) } + /** + * Brings every formula vertex up to the current transformation version, so that the stored + * transformations can be discarded. + * + * A cached error read from a static-error cell carries its origin address together with the + * version that address is true at (see {@link getCellValue}). Its address is moved to the current + * version here too; once the transformations are discarded it could no longer be moved. + * + * Range vertices cache aggregate results, which can be such an error, in shapes this method does + * not walk. Their caches are cleared instead, so the next read recomputes them from the cells. + */ public forceApplyPostponedTransformations() { + this.stampedStaticErrors = new WeakMap() for (const vertex of this.graph.getNodes()) { - if (vertex instanceof ScalarFormulaVertex) { + if (vertex instanceof RangeVertex) { + vertex.clearCache() + } else if (vertex instanceof ScalarFormulaVertex) { vertex.ensureRecentData(this.lazilyTransformingAstService) + const value = vertex.valueOrUndef() + if (value instanceof CellError) { + vertex.setCellValue(this.rebaseOriginAddress(value)) + } + } else if (vertex instanceof ArrayFormulaVertex) { + vertex.mapStoredErrors(error => this.rebaseOriginAddress(error)) } } } + /** + * Moves the origin address of an error read from a static-error cell to the current + * transformation version, so it can still be resolved once the stored transformations are + * discarded. Any other error is returned as is. + */ + public rebaseOriginAddress(error: CellError): CellError { + const {originAddress, originAddressVersion} = error + if (originAddress === undefined || originAddressVersion === undefined || originAddress.sheet === NamedExpressions.SHEET_FOR_WORKBOOK_EXPRESSIONS) { + return error + } + const currentAddress = this.lazilyTransformingAstService.applyTransformationsToAddress(originAddress, originAddressVersion) + if (currentAddress === undefined) { + return error + } + return error.withRebasedOriginAddress(currentAddress, this.lazilyTransformingAstService.version()) + } + public* rawValuesFromRange(range: AbsoluteCellRange): IterableIterator<[RawScalarValue, SimpleCellAddress]> { for (const address of range.addresses(this)) { const value = this.getScalarValue(address) @@ -968,7 +1060,7 @@ export class DependencyGraph { const oldValue = vertex.getArrayCellValue(address) if (this.getCell(address) === vertex) { if (vertex.isLeftCorner(address)) { - this.changes.addChange(new CellError(ErrorType.REF), address, oldValue) + this.changes.addChange(new CellError(ErrorType.REF, ErrorMessage.ArraySourceRemoved), address, oldValue) } else { this.addressMapping.removeCell(address) this.changes.addChange(EmptyValue, address, oldValue) diff --git a/hyperformula/src/DependencyGraph/FormulaVertex.ts b/hyperformula/src/DependencyGraph/FormulaVertex.ts index 2876c2dd39..704bde3b9a 100644 --- a/hyperformula/src/DependencyGraph/FormulaVertex.ts +++ b/hyperformula/src/DependencyGraph/FormulaVertex.ts @@ -161,7 +161,7 @@ export class ArrayFormulaVertex extends FormulaVertex { try { return this.array.get(col, row) } catch (e) { - return new CellError(ErrorType.REF) + return new CellError(ErrorType.REF, ErrorMessage.OutsideArrayResult) } } @@ -237,6 +237,25 @@ export class ArrayFormulaVertex extends FormulaVertex { return equalSimpleCellAddress(this.cellAddress, address) } + /** + * Replaces every error in the stored result with `transform(error)`, leaving other values as + * they are. + */ + public mapStoredErrors(transform: (error: CellError) => CellError): void { + if (this.array instanceof ErroredArray) { + this.array = new ErroredArray(transform(this.array.get(0, 0)), this.array.size) + } else if (this.array instanceof ArrayValue) { + for (const row of this.array.raw()) { + for (let col = 0; col < row.length; col++) { + const value = row[col] + if (value instanceof CellError) { + row[col] = transform(value) + } + } + } + } + } + private setErrorValue(error: CellError) { this.array = new ErroredArray(error, this.array.size) } diff --git a/hyperformula/src/Evaluator.ts b/hyperformula/src/Evaluator.ts index 3b8d4b7930..6ca11e599d 100644 --- a/hyperformula/src/Evaluator.ts +++ b/hyperformula/src/Evaluator.ts @@ -10,6 +10,7 @@ import {Config} from './Config' import {ContentChanges} from './ContentChanges' import {ArrayFormulaVertex, DependencyGraph, RangeVertex, Vertex} from './DependencyGraph' import {FormulaVertex} from './DependencyGraph/FormulaVertex' +import {ErrorMessage} from './error-message' import {Interpreter} from './interpreter/Interpreter' import {InterpreterState} from './interpreter/InterpreterState' import {EmptyValue, getRawValue, InterpreterValue} from './interpreter/InterpreterValue' @@ -105,7 +106,7 @@ export class Evaluator { } else if (vertex instanceof FormulaVertex) { const address = vertex.getAddress(this.lazilyTransformingAstService) this.columnSearch.remove(getRawValue(vertex.valueOrUndef()), address) - const error = new CellError(ErrorType.CYCLE, undefined, vertex) + const error = new CellError(ErrorType.CYCLE, ErrorMessage.CircularReference, vertex) vertex.setCellValue(error) changes.addChange(error, address) } @@ -117,7 +118,7 @@ export class Evaluator { private recomputeFormulas(cycled: Vertex[], sorted: Vertex[]): void { cycled.forEach((vertex: Vertex) => { if (vertex instanceof FormulaVertex) { - vertex.setCellValue(new CellError(ErrorType.CYCLE, undefined, vertex)) + vertex.setCellValue(new CellError(ErrorType.CYCLE, ErrorMessage.CircularReference, vertex)) } }) sorted.forEach((vertex: Vertex) => { diff --git a/hyperformula/src/Exporter.ts b/hyperformula/src/Exporter.ts index 4ffdaf3a69..e4f0954f76 100644 --- a/hyperformula/src/Exporter.ts +++ b/hyperformula/src/Exporter.ts @@ -11,6 +11,7 @@ import {ErrorMessage} from './error-message' import {EmptyValue, getRawValue, InterpreterValue, isExtendedNumber} from './interpreter/InterpreterValue' import {SimpleRangeValue} from './SimpleRangeValue' import {LazilyTransformingAstService} from './LazilyTransformingAstService' +import {Maybe} from './Maybe' import {NamedExpressions} from './NamedExpressions' import {simpleCellAddressToString} from './parser/addressRepresentationConverters' import { SheetMapping } from './DependencyGraph/SheetMapping' @@ -115,7 +116,7 @@ export class Exporter implements ChangeExporter { private detailedError(error: CellError): DetailedCellError { let address = undefined - const originAddress = error.root?.getAddress(this.lazilyTransformingService) + const originAddress = error.root?.getAddress(this.lazilyTransformingService) ?? this.currentOriginAddress(error) if (originAddress !== undefined) { if (originAddress.sheet === NamedExpressions.SHEET_FOR_WORKBOOK_EXPRESSIONS) { address = this.namedExpressions.namedExpressionInAddress(originAddress.row)?.displayName @@ -126,6 +127,28 @@ export class Exporter implements ChangeExporter { return new DetailedCellError(error, this.config.translationPackage.getErrorTranslation(error.type), address) } + /** + * Where a rootless error's origin sits now. + * + * An error produced by a formula resolves its address through its root vertex, which keeps + * itself current. An error read out of a cell that merely holds it — a parse error, or a value + * the user typed — has no such vertex, so it carries a snapshot address plus the transformation + * version that snapshot was true at, and the intervening transformations are replayed here. + * A named expression is exempt: its rows are handed out monotonically and never shifted. + * + * @param {CellError} error - the error being exported + */ + private currentOriginAddress(error: CellError): Maybe { + const {originAddress, originAddressVersion} = error + if (originAddress === undefined || originAddressVersion === undefined) { + return originAddress + } + if (originAddress.sheet === NamedExpressions.SHEET_FOR_WORKBOOK_EXPRESSIONS) { + return originAddress + } + return this.lazilyTransformingService.applyTransformationsToAddress(originAddress, originAddressVersion) + } + private cellValueRounding(value: number): number { if (value === 0) { return value diff --git a/hyperformula/src/HyperFormula.ts b/hyperformula/src/HyperFormula.ts index 5d9220bbe0..f1702ce3d8 100644 --- a/hyperformula/src/HyperFormula.ts +++ b/hyperformula/src/HyperFormula.ts @@ -18,6 +18,7 @@ import { SimpleCellAddress } from './Cell' import {CellContent, CellContentParser, RawCellContent} from './CellContentParser' +import {ContentChanges} from './ContentChanges' import {CellValue} from './CellValue' import {Config, getDefaultConfig} from './Config' import {ColumnRowIndex, CrudOperations} from './CrudOperations' @@ -5324,9 +5325,16 @@ export class HyperFormula implements TypedEmitter { * When enough transformations have accumulated, forces all formula vertices and * column index entries to apply pending lazy transformations, then compacts the * transformation history and cleans up orphaned undo oldData entries. + * + * The errors already waiting in `pendingChanges`, such as an error value typed into a cell + * earlier in a batch, are moved to the current version too, so their origin address can still + * be resolved when the changes are exported. + * + * @param {ContentChanges} pendingChanges - the changes collected so far and not yet exported */ - private compactLazyTransformationsIfNeeded(): void { + private compactLazyTransformationsIfNeeded(pendingChanges: ContentChanges): void { if (this._lazilyTransformingAstService.needsCompaction()) { + pendingChanges.mapErrorValues(error => this._dependencyGraph.rebaseOriginAddress(error)) this._dependencyGraph.forceApplyPostponedTransformations() this._columnSearch.forceApplyPostponedTransformations() this._lazilyTransformingAstService.compact() @@ -5349,7 +5357,7 @@ export class HyperFormula implements TypedEmitter { const verticesToRecomputeFrom = this.dependencyGraph.verticesToRecompute() this.dependencyGraph.clearDirtyVertices() - this.compactLazyTransformationsIfNeeded() + this.compactLazyTransformationsIfNeeded(changes) if (verticesToRecomputeFrom.length > 0) { changes.addAll(this.evaluator.partialRun(verticesToRecomputeFrom)) diff --git a/hyperformula/src/LazilyTransformingAstService.ts b/hyperformula/src/LazilyTransformingAstService.ts index 53f062f04a..330186c3ed 100644 --- a/hyperformula/src/LazilyTransformingAstService.ts +++ b/hyperformula/src/LazilyTransformingAstService.ts @@ -6,11 +6,18 @@ import {SimpleCellAddress} from './Cell' import {CombinedTransformer} from './dependencyTransformers/CombinedTransformer' import {FormulaTransformer} from './dependencyTransformers/Transformer' -import {Ast, ParserWithCaching} from './parser' +import {Maybe} from './Maybe' +import {Ast, AstNodeType, ParserWithCaching} from './parser' import {StatType} from './statistics' import {Statistics} from './statistics/Statistics' import {UndoRedo} from './UndoRedo' +/** + * Stand-in node for an address-only transformation. Every transformer leaves an EMPTY node + * untouched, so only the address it returns alongside it carries information. + */ +const ADDRESS_ONLY_NODE: Ast = {type: AstNodeType.EMPTY} + /** * Manages lazy application of formula AST transformations. * @@ -105,6 +112,39 @@ export class LazilyTransformingAstService { return [cachedAst, address, currentVersion] } + /** + * Replays stored transformations over a bare address that carries no formula. + * + * `applyTransformations` above does the same walk for a formula vertex, which owns an AST and so + * also records undo data as it goes. A value has no AST to record, and the vertex that owns the + * formula still writes its own undo entry when it catches up, so this walk deliberately records + * nothing. It reuses each transformation's own `transformSingleAst` with an empty node rather + * than reaching for `fixNodeAddress`, because two transformers do more than shift coordinates: + * `MoveCellsTransformer` only moves an address that lies inside the range being moved, and that + * decision lives in `transformSingleAst`, not in `fixNodeAddress`. + * + * Returns `undefined` when the stamp predates the last compaction. Before compacting, + * `DependencyGraph.forceApplyPostponedTransformations` moves the stamps of the errors cached in + * formula vertices to the current version, so this only happens to a stamp held anywhere else. + * The transformations needed to move such an address are gone, and naming some other cell is + * worse than naming none. + * + * @param {SimpleCellAddress} address - the address as it was at `version` + * @param {number} version - the version the address was current at + */ + public applyTransformationsToAddress(address: SimpleCellAddress, version: number): Maybe { + if (version < this.versionOffset) { + return undefined + } + + let transformed = address + const currentVersion = this.version() + for (let v = version; v < currentVersion; v++) { + transformed = this.transformations[v - this.versionOffset].transformSingleAst(ADDRESS_ONLY_NODE, transformed)[1] + } + return transformed + } + public* getTransformationsFrom(version: number, filter?: (transformation: FormulaTransformer) => boolean): IterableIterator { const currentVersion = this.version() for (let v = Math.max(version, this.versionOffset); v < currentVersion; v++) { diff --git a/hyperformula/src/Operations.ts b/hyperformula/src/Operations.ts index 38d6d5238a..d8d6fa3b66 100644 --- a/hyperformula/src/Operations.ts +++ b/hyperformula/src/Operations.ts @@ -6,7 +6,7 @@ import { AbsoluteCellRange } from './AbsoluteCellRange' import { absolutizeDependencies, filterDependenciesOutOfScope } from './absolutizeDependencies' import { ArraySize, ArraySizePredictor } from './ArraySize' -import { equalSimpleCellAddress, isColOrRowInvalid, simpleCellAddress, SimpleCellAddress } from './Cell' +import { CellError, equalSimpleCellAddress, isColOrRowInvalid, simpleCellAddress, SimpleCellAddress } from './Cell' import { CellContent, CellContentParser, RawCellContent } from './CellContentParser' import { ClipboardCell, ClipboardCellType } from './ClipboardOperations' import { Config } from './Config' @@ -653,7 +653,9 @@ export class Operations { this.columnSearch.applyChanges(arrayChanges.getChanges()) this.changes.addAll(arrayChanges) - this.changes.addChange(vertex.getCellValue(), address) + // Read back through the dependency graph so the change carries the same address that + // getCellValue() reports for this cell. + this.changes.addChange(this.dependencyGraph.getCellValue(address), address) } /** @@ -685,7 +687,9 @@ export class Operations { this.columnSearch.applyChanges(arrayChanges.getChanges().filter(change => !equalSimpleCellAddress(change.address, address))) this.changes.addAll(arrayChanges) - this.changes.addChange(value.parsedValue, address) + // A typed error value is read back through the dependency graph so the change carries the + // same address that getCellValue() reports for this cell. + this.changes.addChange(value.parsedValue instanceof CellError ? this.dependencyGraph.getCellValue(address) : value.parsedValue, address) } /** diff --git a/hyperformula/src/dependencyTransformers/CleanOutOfScopeDependenciesTransformer.ts b/hyperformula/src/dependencyTransformers/CleanOutOfScopeDependenciesTransformer.ts index d7b7fad97d..fbb818ebc4 100644 --- a/hyperformula/src/dependencyTransformers/CleanOutOfScopeDependenciesTransformer.ts +++ b/hyperformula/src/dependencyTransformers/CleanOutOfScopeDependenciesTransformer.ts @@ -3,7 +3,8 @@ * Copyright (c) Handsoncode sp. z o.o. All rights reserved. */ -import {ErrorType, SimpleCellAddress} from '../Cell' +import {CellError, ErrorType, SimpleCellAddress} from '../Cell' +import {ErrorMessage} from '../error-message' import {CellAddress} from '../parser' import {ColumnAddress} from '../parser/ColumnAddress' import {RowAddress} from '../parser/RowAddress' @@ -20,6 +21,14 @@ export class CleanOutOfScopeDependenciesTransformer extends Transformer { return true } + /** + * A reference this transformer invalidates was carried past the edge of the sheet, for example + * by pasting a formula with a relative reference; no row or column was removed. + */ + protected invalidReferenceError(): CellError { + return new CellError(ErrorType.REF, ErrorMessage.OutOfSheet) + } + protected fixNodeAddress(address: SimpleCellAddress): SimpleCellAddress { return address } diff --git a/hyperformula/src/dependencyTransformers/Transformer.ts b/hyperformula/src/dependencyTransformers/Transformer.ts index e9d8cf3fe3..ba84bc281d 100644 --- a/hyperformula/src/dependencyTransformers/Transformer.ts +++ b/hyperformula/src/dependencyTransformers/Transformer.ts @@ -5,6 +5,7 @@ import {CellError, ErrorType, SimpleCellAddress} from '../Cell' import {DependencyGraph} from '../DependencyGraph' +import {ErrorMessage} from '../error-message' import { Ast, AstNodeType, @@ -107,12 +108,19 @@ export abstract class Transformer implements FormulaTransformer { } } + /** + * The error a reference becomes when this transformation leaves it pointing at no cell. + */ + protected invalidReferenceError(): CellError { + return new CellError(ErrorType.REF, ErrorMessage.ReferenceRemoved) + } + protected transformCellReferenceAst(ast: CellReferenceAst, formulaAddress: SimpleCellAddress): Ast { const newCellAddress = this.transformCellAddress(ast.reference, formulaAddress) if (newCellAddress instanceof CellAddress) { return {...ast, reference: newCellAddress} } else if (newCellAddress === ErrorType.REF) { - return buildCellErrorAst(new CellError(ErrorType.REF)) + return buildCellErrorAst(this.invalidReferenceError()) } else { return ast } @@ -123,7 +131,7 @@ export abstract class Transformer implements FormulaTransformer { if (Array.isArray(newRange)) { return {...ast, start: newRange[0], end: newRange[1]} } else if (newRange === ErrorType.REF) { - return buildCellErrorAst(new CellError(ErrorType.REF)) + return buildCellErrorAst(this.invalidReferenceError()) } else { return ast } @@ -134,7 +142,7 @@ export abstract class Transformer implements FormulaTransformer { if (Array.isArray(newRange)) { return {...ast, start: newRange[0], end: newRange[1]} } else if (newRange === ErrorType.REF) { - return buildCellErrorAst(new CellError(ErrorType.REF)) + return buildCellErrorAst(this.invalidReferenceError()) } else { return ast } @@ -145,7 +153,7 @@ export abstract class Transformer implements FormulaTransformer { if (Array.isArray(newRange)) { return {...ast, start: newRange[0], end: newRange[1]} } else if (newRange === ErrorType.REF) { - return buildCellErrorAst(new CellError(ErrorType.REF)) + return buildCellErrorAst(this.invalidReferenceError()) } else { return ast } diff --git a/hyperformula/src/error-message.ts b/hyperformula/src/error-message.ts index 5eee530345..f466233994 100644 --- a/hyperformula/src/error-message.ts +++ b/hyperformula/src/error-message.ts @@ -21,6 +21,8 @@ export class ErrorMessage { public static NoBroadcastValue = 'Operand ranges cannot be broadcast to a common size, so this position has no value.' public static PoolDimensions = 'Range dimensions are not compatible with the window size and the stride.' public static NoSpaceForArrayResult = 'No space for array result.' + public static ArraySourceRemoved = 'Source cell of the array result was overwritten or removed.' + public static OutsideArrayResult = 'Position is outside the array result of this formula.' public static ValueSmall = 'Value too small.' public static ValueLarge = 'Value too large.' public static BadCriterion = 'Incorrect criterion.' @@ -40,6 +42,10 @@ export class ErrorMessage { public static OddPeriodLength = 'Odd first period has the length of a regular coupon period.' public static NoDaysToMaturity = 'No days from settlement to maturity under the day-count basis.' public static OutOfSheet = 'Resulting reference is out of the sheet.' + public static UnresolvedReference = 'Reference in the formula could not be resolved.' + public static ReferenceRemoved = 'Reference points to a row or column that was removed.' + public static ReferenceExceedsSheetSize = 'Reference exceeds the maximum row or column size of the sheet.' + public static CircularReference = 'Cell is part of a circular reference.' public static WrongType = 'Wrong type of argument.' public static NaN = 'NaN or infinite value encountered.' public static ProbabilitySum = 'Probabilities need to sum up to 1.' @@ -74,6 +80,7 @@ export class ErrorMessage { public static Formula = 'Expected formula.' public static NegativeCount = 'Count cannot be negative.' public static ParseError = 'Parsing error.' + public static ErrorLiteral = 'Error value was entered directly into the formula.' public static SheetRef = 'Sheet does not exist.' public static PeriodLong = 'Period number cannot exceed life length.' public static NonZeroPeriods = 'Number of periods cannot be 0 when the rate is -1.' diff --git a/hyperformula/src/interpreter/Interpreter.ts b/hyperformula/src/interpreter/Interpreter.ts index 34d51f4d34..78c3e509c9 100644 --- a/hyperformula/src/interpreter/Interpreter.ts +++ b/hyperformula/src/interpreter/Interpreter.ts @@ -82,7 +82,9 @@ export class Interpreter { let val = this.evaluateAstWithoutPostprocessing(ast, state) if (isExtendedNumber(val)) { if (isNumberOverflow(getRawValue(val))) { - return new CellError(ErrorType.NUM, ErrorMessage.NaN) + // Assigned rather than returned, so an overflow error reaches the same postprocessing + // as every other result below and gets an origin and a root like anything else. + val = new CellError(ErrorType.NUM, ErrorMessage.NaN) } else { val = cloneNumber(val, fixNegativeZero(getRawValue(val))) } @@ -90,6 +92,9 @@ export class Interpreter { if (val instanceof SimpleRangeValue && val.height() === 1 && val.width() === 1) { [[val]] = val.data } + if (val instanceof CellError) { + val = stampOriginForAstNode(val, ast) + } return wrapperForRootVertex(val, state.formulaVertex) } @@ -302,7 +307,8 @@ export class Interpreter { } case AstNodeType.ERROR_WITH_RAW_INPUT: case AstNodeType.ERROR: { - return ast.error + // Written into the formula rather than produced by a function, so it keeps no origin. + return ast.error.asOriginLocked() } } } @@ -514,7 +520,73 @@ function binaryErrorWrapper(op: (arg1: T, arg2: T) = function wrapperForRootVertex(val: InterpreterValue, vertex?: FormulaVertex): InterpreterValue { if (val instanceof CellError && vertex !== undefined) { - return val.attachRootVertex(vertex) + // A propagated error was read from another cell, so this cell is not its origin. + return val.propagated ? val : val.attachRootVertex(vertex) } return val } + +/** + * The name recorded as an error's `originFunction` when evaluating this AST node is what produced + * it: the canonical function name for a call, or the operator as it is written in a formula, such + * as `+`, `/`, `&` or `%`. Unary and binary minus are both `-`, and unary plus is `+`. Any other + * node type returns undefined and leaves whatever origin the value already carries untouched; + * an `ERROR` or `ERROR_WITH_RAW_INPUT` node instead locks its error with no origin at all. + * + * @param {Ast} ast - the node being evaluated + */ +function originNameForAstNode(ast: Ast): Maybe { + switch (ast.type) { + case AstNodeType.FUNCTION_CALL: + return ast.procedureName + case AstNodeType.CONCATENATE_OP: + return '&' + case AstNodeType.EQUALS_OP: + return '=' + case AstNodeType.NOT_EQUAL_OP: + return '<>' + case AstNodeType.GREATER_THAN_OP: + return '>' + case AstNodeType.LESS_THAN_OP: + return '<' + case AstNodeType.GREATER_THAN_OR_EQUAL_OP: + return '>=' + case AstNodeType.LESS_THAN_OR_EQUAL_OP: + return '<=' + case AstNodeType.PLUS_OP: + return '+' + case AstNodeType.MINUS_OP: + return '-' + case AstNodeType.TIMES_OP: + return '*' + case AstNodeType.POWER_OP: + return '^' + case AstNodeType.DIV_OP: + return '/' + case AstNodeType.PLUS_UNARY_OP: + return '+' + case AstNodeType.MINUS_UNARY_OP: + return '-' + case AstNodeType.PERCENT_OP: + return '%' + default: + return undefined + } +} + +/** + * Stamps the origin function on an error, once per evaluation. + * + * Placed in `evaluateAst`'s single postprocessing tail rather than in each `switch` case, so it + * also catches the overflow guard's freshly-minted error, and so no case can be forgotten. Every + * nested sub-expression runs its own `evaluateAst` first, so an inner error is always stamped + * before an outer function could overwrite it — and `withOrigin` is a no-op once set anyway, as + * it is for an error the formula contains as an error node, which is locked with no origin. + * + * @param {CellError} val - the error produced by this evaluation + * @param {Ast} ast - the node being evaluated + */ +function stampOriginForAstNode(val: CellError, ast: Ast): CellError { + const originName = originNameForAstNode(ast) + return originName === undefined ? val : val.withOrigin(originName) +} diff --git a/hyperformula/src/parser/FormulaParser.ts b/hyperformula/src/parser/FormulaParser.ts index 2431c3260c..133e7c98a0 100644 --- a/hyperformula/src/parser/FormulaParser.ts +++ b/hyperformula/src/parser/FormulaParser.ts @@ -213,11 +213,11 @@ export class FormulaParser extends EmbeddedActionsParser { const secondAddress = this.ACTION(() => columnAddressFromString(endImage, this.formulaAddress, this.resolveSheetReference)) if (firstAddress === undefined || secondAddress === undefined) { - return buildCellErrorAst(new CellError(ErrorType.REF)) + return buildCellErrorAst(new CellError(ErrorType.REF, ErrorMessage.UnresolvedReference)) } if (firstAddress.exceedsSheetSizeLimits(this.lexerConfig.maxColumns) || secondAddress.exceedsSheetSizeLimits(this.lexerConfig.maxColumns)) { - return buildErrorWithRawInputAst(range.image, new CellError(ErrorType.NAME), range.leadingWhitespace) + return buildErrorWithRawInputAst(range.image, new CellError(ErrorType.NAME, ErrorMessage.ReferenceExceedsSheetSize), range.leadingWhitespace) } if (firstAddress.sheet === undefined && secondAddress.sheet !== undefined) { @@ -239,11 +239,11 @@ export class FormulaParser extends EmbeddedActionsParser { const secondAddress = this.ACTION(() => rowAddressFromString(endImage, this.formulaAddress, this.resolveSheetReference)) if (firstAddress === undefined || secondAddress === undefined) { - return buildCellErrorAst(new CellError(ErrorType.REF)) + return buildCellErrorAst(new CellError(ErrorType.REF, ErrorMessage.UnresolvedReference)) } if (firstAddress.exceedsSheetSizeLimits(this.lexerConfig.maxRows) || secondAddress.exceedsSheetSizeLimits(this.lexerConfig.maxRows)) { - return buildErrorWithRawInputAst(range.image, new CellError(ErrorType.NAME), range.leadingWhitespace) + return buildErrorWithRawInputAst(range.image, new CellError(ErrorType.NAME, ErrorMessage.ReferenceExceedsSheetSize), range.leadingWhitespace) } if (firstAddress.sheet === undefined && secondAddress.sheet !== undefined) { @@ -265,9 +265,9 @@ export class FormulaParser extends EmbeddedActionsParser { }) if (address === undefined) { - return buildErrorWithRawInputAst(cell.image, new CellError(ErrorType.REF), cell.leadingWhitespace) + return buildErrorWithRawInputAst(cell.image, new CellError(ErrorType.REF, ErrorMessage.UnresolvedReference), cell.leadingWhitespace) } else if (address.exceedsSheetSizeLimits(this.lexerConfig.maxColumns, this.lexerConfig.maxRows)) { - return buildErrorWithRawInputAst(cell.image, new CellError(ErrorType.NAME), cell.leadingWhitespace) + return buildErrorWithRawInputAst(cell.image, new CellError(ErrorType.NAME, ErrorMessage.ReferenceExceedsSheetSize), cell.leadingWhitespace) } else { return buildCellReferenceAst(address, cell.leadingWhitespace) } @@ -288,12 +288,12 @@ export class FormulaParser extends EmbeddedActionsParser { if (startAddress === undefined || endAddress === undefined) { return this.ACTION(() => { - return buildErrorWithRawInputAst(`${start.image}:${end.image}`, new CellError(ErrorType.REF), start.leadingWhitespace) + return buildErrorWithRawInputAst(`${start.image}:${end.image}`, new CellError(ErrorType.REF, ErrorMessage.UnresolvedReference), start.leadingWhitespace) }) } else if (startAddress.exceedsSheetSizeLimits(this.lexerConfig.maxColumns, this.lexerConfig.maxRows) || endAddress.exceedsSheetSizeLimits(this.lexerConfig.maxColumns, this.lexerConfig.maxRows)) { return this.ACTION(() => { - return buildErrorWithRawInputAst(`${start.image}:${end.image}`, new CellError(ErrorType.NAME), start.leadingWhitespace) + return buildErrorWithRawInputAst(`${start.image}:${end.image}`, new CellError(ErrorType.NAME, ErrorMessage.ReferenceExceedsSheetSize), start.leadingWhitespace) }) } @@ -319,7 +319,7 @@ export class FormulaParser extends EmbeddedActionsParser { return cellAddressFromString(start.image, this.formulaAddress, this.resolveSheetReference) }) if (startAddress === undefined) { - return buildCellErrorAst(new CellError(ErrorType.REF)) + return buildCellErrorAst(new CellError(ErrorType.REF, ErrorMessage.UnresolvedReference)) } if (offsetProcedure.type === AstNodeType.CELL_REFERENCE) { return this.buildCellRange(startAddress, offsetProcedure.reference, start.leadingWhitespace?.image) @@ -352,7 +352,7 @@ export class FormulaParser extends EmbeddedActionsParser { if (endAddress === undefined) { return this.ACTION(() => { - return buildCellErrorAst(new CellError(ErrorType.REF)) + return buildCellErrorAst(new CellError(ErrorType.REF, ErrorMessage.UnresolvedReference)) }) } @@ -552,7 +552,7 @@ export class FormulaParser extends EmbeddedActionsParser { const errString = token.image.toUpperCase() const errorType = this.lexerConfig.errorMapping[errString] if (errorType) { - return buildCellErrorAst(new CellError(errorType), token.leadingWhitespace) + return buildCellErrorAst(new CellError(errorType, ErrorMessage.ErrorLiteral), token.leadingWhitespace) } else { return this.parsingError(ParsingErrorType.ParserError, 'Unknown error literal') } diff --git a/hyperformula/src/parser/ParserWithCaching.ts b/hyperformula/src/parser/ParserWithCaching.ts index bc09a68cec..c90e23966c 100644 --- a/hyperformula/src/parser/ParserWithCaching.ts +++ b/hyperformula/src/parser/ParserWithCaching.ts @@ -4,7 +4,8 @@ */ import {IToken, tokenMatcher, ILexingResult} from 'chevrotain' -import {ErrorType, SimpleCellAddress} from '../Cell' +import {CellError, ErrorType, SimpleCellAddress} from '../Cell' +import {ErrorMessage} from '../error-message' import {FunctionRegistry} from '../interpreter/FunctionRegistry' import {AstNodeType, buildParsingErrorAst, CellAddress, collectDependencies, RelativeDependency} from './' import { @@ -221,6 +222,20 @@ export class ParserWithCaching { return {ast: cachedAst, errors: [], hasVolatileFunction, hasStructuralChangeFunction, dependencies: relativeDependencies} } + /** + * Error nodes that print the same, such as `#REF!`, can stand for different errors: one typed into + * the formula, another left where a removed row or column was referenced. The suffix keeps their + * cache entries apart, so a cache hit never gives a formula the message of another formula's error. + * It is empty for an error typed into the formula, whose hash then equals the hash computed from + * the formula's tokens. + */ + private static errorMessageHashSuffix(error?: CellError): string { + if (error === undefined || error.message === ErrorMessage.ErrorLiteral) { + return '' + } + return `\u0000${error.message ?? ''}` + } + public computeHashFromTokens(tokens: IToken[], baseAddress: SimpleCellAddress): string { let hash = '' let idx = 0 @@ -315,7 +330,7 @@ export class ParserWithCaching { const image = this.config.translationPackage.getErrorTranslation( ast.error ? ast.error.type : ErrorType.ERROR ) - return imageWithWhitespace(image, ast.leadingWhitespace) + return imageWithWhitespace(image, ast.leadingWhitespace) + ParserWithCaching.errorMessageHashSuffix(ast.error) } case AstNodeType.ERROR_WITH_RAW_INPUT: { return imageWithWhitespace(ast.rawInput, ast.leadingWhitespace) diff --git a/hyperformula/test/_setupFiles/jest/toEqualError.ts b/hyperformula/test/_setupFiles/jest/toEqualError.ts index 80f274cfc2..1af55cb5f2 100644 --- a/hyperformula/test/_setupFiles/jest/toEqualError.ts +++ b/hyperformula/test/_setupFiles/jest/toEqualError.ts @@ -1,29 +1,22 @@ -type CustomMatcherResult = jest.CustomMatcherResult -type ExpectExtendMap = jest.ExpectExtendMap - -declare global { - namespace jest { - interface Matchers { - toEqualError(expected: any): CustomMatcherResult, - } - } -} - -export const toEqualError: ExpectExtendMap = { - toEqualError(received: any, expected: any): CustomMatcherResult { - let result = false - - if (typeof received === 'object' && typeof expected === 'object' && received.message != null && expected.message != null && received.message.includes(expected.message)) { - result = this.equals( - {...received, message: undefined, root: undefined, address: undefined}, - {...expected, message: undefined, root: undefined, address: undefined} - ) - } else { - result = this.equals(received, expected) - } - return { - pass: result, - message: () => (result ? '' : `Expected ${JSON.stringify(received, null, 2)} to match ${JSON.stringify(expected, null, 2)}.`) - } - } -} +import { cellErrorMismatchMessage, cellErrorsMatch } from '../matchers/cellErrorComparison' + +type CustomMatcherResult = jest.CustomMatcherResult +type ExpectExtendMap = jest.ExpectExtendMap + +declare global { + namespace jest { + interface Matchers { + toEqualError(expected: any): CustomMatcherResult, + } + } +} + +export const toEqualError: ExpectExtendMap = { + toEqualError(received: any, expected: any): CustomMatcherResult { + const result = cellErrorsMatch(received, expected, (a, b) => this.equals(a, b)) + return { + pass: result, + message: () => (result ? '' : cellErrorMismatchMessage(received, expected)) + } + } +} diff --git a/hyperformula/test/_setupFiles/matchers/cellErrorComparison.ts b/hyperformula/test/_setupFiles/matchers/cellErrorComparison.ts new file mode 100644 index 0000000000..8031214428 --- /dev/null +++ b/hyperformula/test/_setupFiles/matchers/cellErrorComparison.ts @@ -0,0 +1,79 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +/** + * The one definition of what `toEqualError` compares, shared by both runners. + * + * The suite runs under Jest AND Karma/Jasmine, and each has its own matcher wrapper + * (`_setupFiles/jest/toEqualError.ts`, `_setupFiles/matchers/toEqualError.ts`) because the + * two runners register matchers differently and hand in a different equality helper. Only + * the wrapper differs: the decision below used to be copy-pasted into both, and drifted — + * a field added to one strip list and not the other passes under Jest while the browser + * run reports hundreds of failures for a reason no diff explains. Keeping the decision here + * makes that class of bug impossible: there is exactly one strip list to extend. + */ + +/** Equality, supplied by whichever runner is active (`this.equals` in Jest, `util.equals` in Jasmine). */ +export type EqualsFn = (actual: unknown, expected: unknown) => boolean + +/** + * Fields excluded from the structural comparison. + * + * These are asserted explicitly by the specs that care about them, rather than implicitly by + * every error assertion in the suite. `message` is excluded because it is matched by substring + * above; `root`, `address`, `propagated`, `originLocked`, `originAddress` and `originAddressVersion` because an + * expectation built by the `detailedError` test helper cannot know the vertex, the address, or how + * far the engine had travelled when it recorded them. + * + * ADDING A FIELD TO `CellError` OR `DetailedCellError`? Add it here, once. Do not add it to a + * runner wrapper. + */ +const IGNORED_IN_STRUCTURAL_COMPARE = { + message: undefined, + root: undefined, + address: undefined, + originFunction: undefined, + argumentIndex: undefined, + propagated: undefined, + originAddress: undefined, + originAddressVersion: undefined, + originLocked: undefined, +} + +/** + * Whether a received error matches an expected one. + * + * When both sides carry a message, the expected message is treated as a substring of the + * received one and the remaining fields are compared structurally. Otherwise the two values + * are compared as-is — which is what makes an expectation on a raw, message-less `CellError` + * a strict, whole-object comparison. + * + * @param received - the value produced by the engine + * @param expected - the value the spec asserts + * @param equals - the active runner's deep-equality function + */ +export function cellErrorsMatch(received: any, expected: any, equals: EqualsFn): boolean { + const bothCarryAMessage = typeof received === 'object' && typeof expected === 'object' + && received.message != null && expected.message != null + + if (bothCarryAMessage && received.message.includes(expected.message)) { + return equals( + {...received, ...IGNORED_IN_STRUCTURAL_COMPARE}, + {...expected, ...IGNORED_IN_STRUCTURAL_COMPARE}, + ) + } + + return equals(received, expected) +} + +/** + * The failure text both runners print, so a mismatch reads identically whichever one found it. + * + * @param received - the value produced by the engine + * @param expected - the value the spec asserts + */ +export function cellErrorMismatchMessage(received: any, expected: any): string { + return `Expected ${JSON.stringify(received, null, 2)} to match ${JSON.stringify(expected, null, 2)}.` +} diff --git a/hyperformula/test/_setupFiles/matchers/toEqualError.ts b/hyperformula/test/_setupFiles/matchers/toEqualError.ts index 6c0b87bb56..65e3a171db 100644 --- a/hyperformula/test/_setupFiles/matchers/toEqualError.ts +++ b/hyperformula/test/_setupFiles/matchers/toEqualError.ts @@ -1,3 +1,5 @@ +import { cellErrorMismatchMessage, cellErrorsMatch } from './cellErrorComparison' + type CustomMatcher = jasmine.CustomMatcher type CustomMatcherFactories = jasmine.CustomMatcherFactories type CustomMatcherResult = jasmine.CustomMatcherResult @@ -15,18 +17,10 @@ export const toEqualErrorMatcher: CustomMatcherFactories = { toEqualError: function(util: MatchersUtil): CustomMatcher { return { compare: function(received: any, expected: any): CustomMatcherResult { - let result - if (typeof received === 'object' && typeof expected === 'object' && received.message != null && expected.message != null && received.message.includes(expected.message)) { - result = util.equals( - {...received, message: undefined, root: undefined, address: undefined}, - {...expected, message: undefined, root: undefined, address: undefined} - ) - } else { - result = util.equals(received, expected) - } + const result = cellErrorsMatch(received, expected, (a, b) => util.equals(a, b)) return { pass: result, - message: result ? '' : `Expected ${JSON.stringify(received, null, 2)} to match ${JSON.stringify(expected, null, 2)}.` + message: result ? '' : cellErrorMismatchMessage(received, expected) } }, }