Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix(formula): fix CELL_INVERTED_INDEX_CACHE bug (#5118)

wpxp123456b823a88fdd40
diff --git a/packages/engine-formula/src/basics/inverted-index-cache.ts b/packages/engine-formula/src/basics/inverted-index-cache.ts
index 2e10d31f84..5d9062462b 100644
--- a/packages/engine-formula/src/basics/inverted-index-cache.ts
+++ b/packages/engine-formula/src/basics/inverted-index-cache.ts
@@ -34,8 +34,8 @@ export class InvertedIndexCache {
private _continueBuildingCache: Map<string, Map<string, Map<number, IntervalTree<NumericTuple>>>> = new Map();
- set(unitId: string, sheetId: string, column: number, value: string | number | boolean | null, row: number) {
- if (!this.shouldContinueBuildingCache(unitId, sheetId, column, row)) {
+ set(unitId: string, sheetId: string, column: number, value: string | number | boolean | null, row: number, isForceUpdate: boolean = false) {
+ if (!this.shouldContinueBuildingCache(unitId, sheetId, column, row) && !isForceUpdate) {
return;
}
@@ -57,6 +57,16 @@ export class InvertedIndexCache {
sheetMap.set(column, columnMap);
}
+ // If is force update, we need to remove the old value from the map
+ if (isForceUpdate) {
+ for (const [_, _cellList] of columnMap) {
+ if (_cellList.has(row)) {
+ _cellList.delete(row);
+ break;
+ }
+ }
+ }
+
let cellList = columnMap.get(value);
if (cellList == null) {
cellList = new Set<number>();
diff --git a/packages/engine-formula/src/engine/value-object/array-value-object.ts b/packages/engine-formula/src/engine/value-object/array-value-object.ts
index a48ea98232..ebcefa49f8 100644
--- a/packages/engine-formula/src/engine/value-object/array-value-object.ts
+++ b/packages/engine-formula/src/engine/value-object/array-value-object.ts
@@ -1472,7 +1472,14 @@ export class ArrayValueObject extends BaseValueObject {
for (let c = 0; c < columnCount; c++) {
const value = valueList[c];
- this._batchOperatorValue(value, c, result, batchOperatorType, operator, isCaseSensitive);
+ this._batchOperatorValue(
+ value,
+ c,
+ result,
+ batchOperatorType,
+ operator,
+ isCaseSensitive
+ );
}
const newArray = this._createNewArray(result, rowCount, columnCount);
diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.ts
index dd669f7269..c3b4bac291 100644
--- a/packages/engine-formula/src/services/runtime.service.ts
+++ b/packages/engine-formula/src/services/runtime.service.ts
@@ -28,6 +28,7 @@ import type { BaseValueObject } from '../engine/value-object/base-value-object';
import { createIdentifier, Disposable, ObjectMatrix } from '@univerjs/core';
import { isInDirtyRange } from '../basics/dirty';
import { ErrorType } from '../basics/error-type';
+import { CELL_INVERTED_INDEX_CACHE } from '../basics/inverted-index-cache';
import { isNullCellForFormula } from '../basics/is-null-cell';
import { getRuntimeFeatureCell } from '../engine/utils/get-runtime-feature-cell';
import { clearNumberFormatTypeCache, clearStringToNumberPatternCache } from '../engine/utils/numfmt-kit';
@@ -522,6 +523,16 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
sheetData.setValue(row, column, valueObject);
clearArrayUnitData.setValue(row, column, valueObject);
+ // Formula calculation results are saved to cache
+ CELL_INVERTED_INDEX_CACHE.set(
+ unitId,
+ sheetId,
+ column,
+ firstCell.getValue(),
+ row,
+ true
+ );
+
return;
}
@@ -543,6 +554,16 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
sheetData.setValue(row, column, errorObject);
clearArrayUnitData.setValue(row, column, errorObject);
+ // Formula calculation results are saved to cache
+ CELL_INVERTED_INDEX_CACHE.set(
+ unitId,
+ sheetId,
+ column,
+ ErrorType.SPILL,
+ row,
+ true
+ );
+
/**
* When there are values within the array formula range, the entire formula will result in an error.
* In this case, you need to clear the previous range data to prevent other formulas from referencing the old values.
@@ -570,6 +591,16 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
} else {
const spillError = ErrorValueObject.create(ErrorType.SPILL);
objectValueRefOrArray.iterator((valueObject, rowIndex, columnIndex) => {
+ // Formula calculation results are saved to cache
+ CELL_INVERTED_INDEX_CACHE.set(
+ unitId,
+ sheetId,
+ column - startColumn + columnIndex,
+ !valueObject ? 0 : valueObject.getValue(),
+ row - startRow + rowIndex,
+ true
+ );
+
const value = objectValueToCellValue(valueObject);
if (rowIndex === startRow && columnIndex === startColumn) {
/**
@@ -593,6 +624,17 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
} else {
const valueObject = objectValueToCellValue(functionVariant as BaseValueObject);
sheetData.setValue(row, column, valueObject);
+
+ // Formula calculation results are saved to cache
+ CELL_INVERTED_INDEX_CACHE.set(
+ unitId,
+ sheetId,
+ column,
+ (functionVariant as BaseValueObject).getValue(),
+ row,
+ true
+ );
+
clearArrayUnitData.setValue(row, column, valueObject);
}
}
diff --git a/packages/engine-formula/src/engine/value-object/__tests__/array-inverted-index-cache.spec.ts b/packages/sheets/src/controllers/__tests__/formula/array-inverted-index-cache.spec.ts
similarity index 70%
rename from packages/engine-formula/src/engine/value-object/__tests__/array-inverted-index-cache.spec.ts
rename to packages/sheets/src/controllers/__tests__/formula/array-inverted-index-cache.spec.ts
index f17be126fb..6f0afe951c 100644
--- a/packages/engine-formula/src/engine/value-object/__tests__/array-inverted-index-cache.spec.ts
+++ b/packages/sheets/src/controllers/__tests__/formula/array-inverted-index-cache.spec.ts
@@ -14,34 +14,43 @@
* limitations under the License.
*/
-import type { Injector, IWorkbookData } from '@univerjs/core';
-import type { LexerNode } from '../../analysis/lexer-node';
-
-import type { BaseAstNode } from '../../ast-node/base-ast-node';
-import { LocaleType } from '@univerjs/core';
+import type { CellValue, Ctor, Injector, IWorkbookData, Nullable, Worksheet } from '@univerjs/core';
+import type { BaseAstNode, BaseFunction, IFunctionNames, LexerNode } from '@univerjs/engine-formula';
+import type { FFormula } from '@univerjs/engine-formula/facade';
+import { ICommandService, LocaleType } from '@univerjs/core';
+import {
+ AstTreeBuilder,
+ functionLogical,
+ functionMath,
+ functionMeta,
+ generateExecuteAstNodeData,
+ IFormulaCurrentConfigService,
+ IFormulaRuntimeService,
+ IFunctionService,
+ Interpreter,
+ Lexer,
+ SetArrayFormulaDataMutation,
+ SetFormulaCalculationNotificationMutation,
+ SetFormulaCalculationResultMutation,
+ SetFormulaCalculationStartMutation,
+ SetFormulaCalculationStopMutation,
+} from '@univerjs/engine-formula';
import { beforeEach, describe, expect, it } from 'vitest';
-import { createFunctionTestBed, getObjectValue } from '../../../functions/__tests__/create-function-test-bed';
-import { FUNCTION_NAMES_LOGICAL } from '../../../functions/logical/function-names';
-import { If } from '../../../functions/logical/if';
-import { FUNCTION_NAMES_MATH } from '../../../functions/math/function-names';
-import { Sumif } from '../../../functions/math/sumif';
-import { Compare } from '../../../functions/meta/compare';
-import { FUNCTION_NAMES_META } from '../../../functions/meta/function-names';
-import { IFormulaCurrentConfigService } from '../../../services/current-data.service';
-import { IFunctionService } from '../../../services/function.service';
-import { IFormulaRuntimeService } from '../../../services/runtime.service';
-import { Lexer } from '../../analysis/lexer';
-import { AstTreeBuilder } from '../../analysis/parser';
-import { Interpreter } from '../../interpreter/interpreter';
-import { generateExecuteAstNodeData } from '../../utils/ast-node-tool';
+import { SetRangeValuesMutation } from '../../../commands/mutations/set-range-values.mutation';
+import { createFunctionTestBed, getObjectValue } from './create-function-test-bed';
+
+import '@univerjs/engine-formula/facade';
+
+const unitId = 'test';
+const subUnitId = 'sheet1';
const getFunctionsTestWorkbookData = (): IWorkbookData => {
return {
- id: 'test',
+ id: unitId,
appVersion: '3.0.0-alpha',
sheets: {
sheet1: {
- id: 'sheet1',
+ id: subUnitId,
cellData: {
0: {
0: {
@@ -161,6 +170,9 @@ const getFunctionsTestWorkbookData = (): IWorkbookData => {
2: {
f: '=C32/C33',
},
+ 3: {
+ f: '=IF(C8<0,IF(C31<1,1,0.8),IF(C31<1,0.95,1))',
+ },
},
31: {
2: {
@@ -187,21 +199,36 @@ const getFunctionsTestWorkbookData = (): IWorkbookData => {
styles: {},
};
};
+
describe('Test inverted index cache', () => {
let get: Injector['get'];
+ let worksheet: Worksheet;
+ let formulaEngine: FFormula;
let lexer: Lexer;
let astTreeBuilder: AstTreeBuilder;
let interpreter: Interpreter;
+ let commandService: ICommandService;
+ let getCellValue: (row: number, column: number) => Nullable<CellValue>;
let calculate: (formula: string) => (string | number | boolean | null)[][] | string | number | boolean;
- beforeEach(() => {
+ beforeEach(async () => {
const testBed = createFunctionTestBed(getFunctionsTestWorkbookData());
get = testBed.get;
+ worksheet = testBed.sheet.getSheetBySheetId(subUnitId) as Worksheet;
+ formulaEngine = testBed.api.getFormula() as FFormula;
lexer = get(Lexer);
astTreeBuilder = get(AstTreeBuilder);
interpreter = get(Interpreter);
+ commandService = get(ICommandService);
+
+ commandService.registerCommand(SetFormulaCalculationStartMutation);
+ commandService.registerCommand(SetFormulaCalculationStopMutation);
+ commandService.registerCommand(SetFormulaCalculationResultMutation);
+ commandService.registerCommand(SetFormulaCalculationNotificationMutation);
+ commandService.registerCommand(SetArrayFormulaDataMutation);
+ commandService.registerCommand(SetRangeValuesMutation);
const functionService = get(IFunctionService);
@@ -236,12 +263,29 @@ describe('Test inverted index cache', () => {
testBed.unitId
);
+ const functions = [
+ ...functionMath,
+ ...functionMeta,
+ ...functionLogical,
+ ]
+ .map((registerObject) => {
+ const Func = registerObject[0] as Ctor<BaseFunction>;
+ const name = registerObject[1] as IFunctionNames;
+
+ return new Func(name);
+ });
+
functionService.registerExecutors(
- new If(FUNCTION_NAMES_LOGICAL.IF),
- new Sumif(FUNCTION_NAMES_MATH.SUMIF),
- new Compare(FUNCTION_NAMES_META.COMPARE)
+ ...functions
);
+ formulaEngine.executeCalculation();
+ await formulaEngine.onCalculationEnd();
+
+ getCellValue = (row: number, column: number) => {
+ return worksheet.getCellRaw(row, column)?.v;
+ };
+
calculate = (formula: string) => {
const lexerNode = lexer.treeBuilder(formula);
@@ -254,9 +298,28 @@ describe('Test inverted index cache', () => {
});
describe('Test formula', () => {
- it('If formula test', () => {
- const result = calculate('=IF(C8<0,IF(C31<1,1,0.8),IF(C31<1,0.95,1))');
- expect(result).toBe(0.95);
+ it('If formula test', async () => {
+ // D31 is IF formula: =IF(C8<0,IF(C31<1,1,0.8),IF(C31<1,0.95,1))
+ expect(getCellValue(30, 3)).toBe(0.95);
+
+ // Update C24 value to 100
+ await commandService.executeCommand(SetRangeValuesMutation.id, {
+ unitId,
+ subUnitId,
+ cellValue: {
+ 23: {
+ 2: {
+ v: 100,
+ t: 2,
+ },
+ },
+ },
+ });
+ formulaEngine.executeCalculation();
+ await formulaEngine.onCalculationEnd();
+
+ // now result should be 1
+ expect(getCellValue(30, 3)).toBe(1);
});
it('Sumif formula test', () => {
diff --git a/packages/engine-formula/src/engine/value-object/__tests__/array-inverted-index-cache2.spec.ts b/packages/sheets/src/controllers/__tests__/formula/array-inverted-index-cache2.spec.ts
similarity index 79%
rename from packages/engine-formula/src/engine/value-object/__tests__/array-inverted-index-cache2.spec.ts
rename to packages/sheets/src/controllers/__tests__/formula/array-inverted-index-cache2.spec.ts
index eec624c8b9..f3fc77d402 100644
--- a/packages/engine-formula/src/engine/value-object/__tests__/array-inverted-index-cache2.spec.ts
+++ b/packages/sheets/src/controllers/__tests__/formula/array-inverted-index-cache2.spec.ts
@@ -14,34 +14,42 @@
* limitations under the License.
*/
-import type { Injector, IWorkbookData } from '@univerjs/core';
-import type { LexerNode } from '../../analysis/lexer-node';
-
-import type { BaseAstNode } from '../../ast-node/base-ast-node';
-import { LocaleType } from '@univerjs/core';
+import type { Ctor, Injector, IWorkbookData } from '@univerjs/core';
+import type { BaseAstNode, BaseFunction, IFunctionNames, LexerNode } from '@univerjs/engine-formula';
+import { ICommandService, LocaleType } from '@univerjs/core';
+import {
+ AstTreeBuilder,
+ functionLogical,
+ functionMath,
+ functionMeta,
+ generateExecuteAstNodeData,
+ IFormulaCurrentConfigService,
+ IFormulaRuntimeService,
+ IFunctionService,
+ Interpreter,
+ Lexer,
+ SetArrayFormulaDataMutation,
+ SetFormulaCalculationNotificationMutation,
+ SetFormulaCalculationResultMutation,
+ SetFormulaCalculationStartMutation,
+ SetFormulaCalculationStopMutation,
+} from '@univerjs/engine-formula';
import { beforeEach, describe, expect, it } from 'vitest';
-import { createFunctionTestBed, getObjectValue } from '../../../functions/__tests__/create-function-test-bed';
-import { FUNCTION_NAMES_LOGICAL } from '../../../functions/logical/function-names';
-import { If } from '../../../functions/logical/if';
-import { FUNCTION_NAMES_MATH } from '../../../functions/math/function-names';
-import { Sumif } from '../../../functions/math/sumif';
-import { Compare } from '../../../functions/meta/compare';
-import { FUNCTION_NAMES_META } from '../../../functions/meta/function-names';
-import { IFormulaCurrentConfigService } from '../../../services/current-data.service';
-import { IFunctionService } from '../../../services/function.service';
-import { IFormulaRuntimeService } from '../../../services/runtime.service';
-import { Lexer } from '../../analysis/lexer';
-import { AstTreeBuilder } from '../../analysis/parser';
-import { Interpreter } from '../../interpreter/interpreter';
-import { generateExecuteAstNodeData } from '../../utils/ast-node-tool';
+import { SetRangeValuesMutation } from '../../../commands/mutations/set-range-values.mutation';
+import { createFunctionTestBed, getObjectValue } from './create-function-test-bed';
+
+import '@univerjs/engine-formula/facade';
+
+const unitId = 'test';
+const subUnitId = 'sheet1';
const getFunctionsTestWorkbookData = (): IWorkbookData => {
return {
- id: 'test',
+ id: unitId,
appVersion: '3.0.0-alpha',
sheets: {
sheet1: {
- id: 'sheet1',
+ id: subUnitId,
cellData: {
7: {
1: {
@@ -150,14 +158,16 @@ const getFunctionsTestWorkbookData = (): IWorkbookData => {
styles: {},
};
};
+
describe('Test inverted index cache', () => {
let get: Injector['get'];
let lexer: Lexer;
let astTreeBuilder: AstTreeBuilder;
let interpreter: Interpreter;
+ let commandService: ICommandService;
let calculate: (formula: string) => (string | number | boolean | null)[][] | string | number | boolean;
- beforeEach(() => {
+ beforeEach(async () => {
const testBed = createFunctionTestBed(getFunctionsTestWorkbookData());
get = testBed.get;
@@ -165,6 +175,14 @@ describe('Test inverted index cache', () => {
lexer = get(Lexer);
astTreeBuilder = get(AstTreeBuilder);
interpreter = get(Interpreter);
+ commandService = get(ICommandService);
+
+ commandService.registerCommand(SetFormulaCalculationStartMutation);
+ commandService.registerCommand(SetFormulaCalculationStopMutation);
+ commandService.registerCommand(SetFormulaCalculationResultMutation);
+ commandService.registerCommand(SetFormulaCalculationNotificationMutation);
+ commandService.registerCommand(SetArrayFormulaDataMutation);
+ commandService.registerCommand(SetRangeValuesMutation);
const functionService = get(IFunctionService);
@@ -199,10 +217,20 @@ describe('Test inverted index cache', () => {
testBed.unitId
);
+ const functions = [
+ ...functionMath,
+ ...functionMeta,
+ ...functionLogical,
+ ]
+ .map((registerObject) => {
+ const Func = registerObject[0] as Ctor<BaseFunction>;
+ const name = registerObject[1] as IFunctionNames;
+
+ return new Func(name);
+ });
+
functionService.registerExecutors(
- new If(FUNCTION_NAMES_LOGICAL.IF),
- new Sumif(FUNCTION_NAMES_MATH.SUMIF),
- new Compare(FUNCTION_NAMES_META.COMPARE)
+ ...functions
);
calculate = (formula: string) => {
diff --git a/packages/sheets/src/controllers/__tests__/formula/array-inverted-index-cache3.spec.ts b/packages/sheets/src/controllers/__tests__/formula/array-inverted-index-cache3.spec.ts
new file mode 100644
index 0000000000..2b331d5997
--- /dev/null
+++ b/packages/sheets/src/controllers/__tests__/formula/array-inverted-index-cache3.spec.ts
@@ -0,0 +1,290 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { CellValue, Ctor, Injector, IWorkbookData, Nullable, Worksheet } from '@univerjs/core';
+import type { BaseFunction, IFunctionNames } from '@univerjs/engine-formula';
+import type { FFormula } from '@univerjs/engine-formula/facade';
+import { ICommandService, LocaleType } from '@univerjs/core';
+import {
+ functionLogical,
+ functionLookup,
+ functionMath,
+ functionMeta,
+ IFormulaCurrentConfigService,
+ IFormulaRuntimeService,
+ IFunctionService,
+ SetArrayFormulaDataMutation,
+ SetFormulaCalculationNotificationMutation,
+ SetFormulaCalculationResultMutation,
+ SetFormulaCalculationStartMutation,
+ SetFormulaCalculationStopMutation,
+} from '@univerjs/engine-formula';
+import { beforeEach, describe, expect, it } from 'vitest';
+import { SetRangeValuesMutation } from '../../../commands/mutations/set-range-values.mutation';
+import { createFunctionTestBed } from './create-function-test-bed';
+
+import '@univerjs/engine-formula/facade';
+
+const unitId = 'test';
+const subUnitId = 'sheet1';
+
+const getFunctionsTestWorkbookData = (): IWorkbookData => {
+ return {
+ id: unitId,
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: subUnitId,
+ cellData: {
+ 6: {
+ 0: {
+ v: 'aaa',
+ t: 1,
+ },
+ 1: {
+ f: '=ROW(A7)-ROW($A$6)',
+ },
+ 2: {
+ f: '=ROW(A7)-ROW($A$6)+3',
+ t: 2,
+ },
+ 3: {
+ f: '=XLOOKUP(B7,$B$7:$B$16,$A$7:$A$16)',
+ },
+ 4: {
+ f: '=XLOOKUP(C7,$C$7:$C$16,$A$7:$A$16)',
+ },
+ },
+ 7: {
+ 0: {
+ v: 'bbb',
+ t: 1,
+ },
+ 1: {
+ f: '=ROW(A8)-ROW($A$6)',
+ si: 'YKcfsr',
+ },
+ 2: {
+ f: '=ROW(A8)-ROW($A$6)+3',
+ si: 'Di7wtl',
+ },
+ 3: {
+ f: '=XLOOKUP(B8,$B$7:$B$16,$A$7:$A$16)',
+ },
+ 4: {
+ f: '=XLOOKUP(C8,$C$7:$C$16,$A$7:$A$16)',
+ },
+ },
+ 8: {
+ 0: {
+ v: 'ccc',
+ t: 1,
+ },
+ 1: {
+ si: 'YKcfsr',
+ t: 2,
+ },
+ 2: {
+ si: 'Di7wtl',
+ t: 2,
+ },
+ 3: {
+ f: '=XLOOKUP(B9,$B$7:$B$16,$A$7:$A$16)',
+ },
+ 4: {
+ f: '=XLOOKUP(C9,$C$7:$C$16,$A$7:$A$16)',
+ },
+ },
+ 9: {
+ 0: {
+ v: 'ddd',
+ t: 1,
+ },
+ 1: {
+ si: 'YKcfsr',
+ t: 2,
+ },
+ 2: {
+ si: 'Di7wtl',
+ t: 2,
+ },
+ 3: {
+ f: '=XLOOKUP(B10,$B$7:$B$16,$A$7:$A$16)',
+ },
+ 4: {
+ f: '=XLOOKUP(C10,$C$7:$C$16,$A$7:$A$16)',
+ },
+ },
+ 10: {
+ 0: {
+ v: 'eee',
+ t: 1,
+ },
+ 1: {
+ si: 'YKcfsr',
+ t: 2,
+ },
+ 2: {
+ si: 'Di7wtl',
+ t: 2,
+ },
+ 3: {
+ f: '=XLOOKUP(B11,$B$7:$B$16,$A$7:$A$16)',
+ },
+ 4: {
+ f: '=XLOOKUP(C11,$C$7:$C$16,$A$7:$A$16)',
+ },
+ },
+ 11: {
+ 0: {
+ v: 'fff',
+ t: 1,
+ },
+ 1: {
+ si: 'YKcfsr',
+ t: 2,
+ },
+ 2: {
+ si: 'Di7wtl',
+ t: 2,
+ },
+ 3: {
+ f: '=XLOOKUP(B12,$B$7:$B$16,$A$7:$A$16)',
+ },
+ 4: {
+ f: '=XLOOKUP(C12,$C$7:$C$16,$A$7:$A$16)',
+ },
+ },
+ },
+ },
+ },
+ locale: LocaleType.ZH_CN,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+ };
+};
+
+describe('Test inverted index cache', () => {
+ let get: Injector['get'];
+ let worksheet: Worksheet;
+ let formulaEngine: FFormula;
+ let commandService: ICommandService;
+ let getCellValue: (row: number, column: number) => Nullable<CellValue>;
+
+ beforeEach(async () => {
+ const testBed = createFunctionTestBed(getFunctionsTestWorkbookData());
+
+ get = testBed.get;
+ worksheet = testBed.sheet.getSheetBySheetId(subUnitId) as Worksheet;
+ formulaEngine = testBed.api.getFormula() as FFormula;
+
+ commandService = get(ICommandService);
+
+ commandService.registerCommand(SetFormulaCalculationStartMutation);
+ commandService.registerCommand(SetFormulaCalculationStopMutation);
+ commandService.registerCommand(SetFormulaCalculationResultMutation);
+ commandService.registerCommand(SetFormulaCalculationNotificationMutation);
+ commandService.registerCommand(SetArrayFormulaDataMutation);
+ commandService.registerCommand(SetRangeValuesMutation);
+
+ const functionService = get(IFunctionService);
+
+ const formulaCurrentConfigService = get(IFormulaCurrentConfigService);
+
+ const formulaRuntimeService = get(IFormulaRuntimeService);
+
+ formulaCurrentConfigService.load({
+ formulaData: {},
+ arrayFormulaCellData: {},
+ arrayFormulaRange: {},
+ forceCalculate: false,
+ dirtyRanges: [],
+ dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
+ dirtyUnitFeatureMap: {},
+ dirtyUnitOtherFormulaMap: {},
+ excludedCell: {},
+ allUnitData: {
+ [testBed.unitId]: testBed.sheetData,
+ },
+ });
+
+ const sheetItem = testBed.sheetData[testBed.sheetId];
+
+ formulaRuntimeService.setCurrent(
+ 0,
+ 0,
+ sheetItem.rowCount,
+ sheetItem.columnCount,
+ testBed.sheetId,
+ testBed.unitId
+ );
+
+ const functions = [
+ ...functionMath,
+ ...functionMeta,
+ ...functionLogical,
+ ...functionLookup,
+ ]
+ .map((registerObject) => {
+ const Func = registerObject[0] as Ctor<BaseFunction>;
+ const name = registerObject[1] as IFunctionNames;
+
+ return new Func(name);
+ });
+
+ functionService.registerExecutors(
+ ...functions
+ );
+
+ formulaEngine.executeCalculation();
+ await formulaEngine.onCalculationEnd();
+
+ getCellValue = (row: number, column: number) => {
+ return worksheet.getCellRaw(row, column)?.v;
+ };
+ });
+
+ describe('Test formula', () => {
+ it('Xlookup formula test', () => {
+ expect(getCellValue(6, 1)).toBe(1);
+ expect(getCellValue(6, 2)).toBe(4);
+ expect(getCellValue(6, 3)).toBe('aaa');
+ expect(getCellValue(6, 4)).toBe('aaa');
+ expect(getCellValue(7, 1)).toBe(2);
+ expect(getCellValue(7, 2)).toBe(5);
+ expect(getCellValue(7, 3)).toBe('bbb');
+ expect(getCellValue(7, 4)).toBe('bbb');
+ expect(getCellValue(8, 1)).toBe(3);
+ expect(getCellValue(8, 2)).toBe(6);
+ expect(getCellValue(8, 3)).toBe('ccc');
+ expect(getCellValue(8, 4)).toBe('ccc');
+ expect(getCellValue(9, 1)).toBe(4);
+ expect(getCellValue(9, 2)).toBe(7);
+ expect(getCellValue(9, 3)).toBe('ddd');
+ expect(getCellValue(9, 4)).toBe('ddd');
+ expect(getCellValue(10, 1)).toBe(5);
+ expect(getCellValue(10, 2)).toBe(8);
+ expect(getCellValue(10, 3)).toBe('eee');
+ expect(getCellValue(10, 4)).toBe('eee');
+ expect(getCellValue(11, 1)).toBe(6);
+ expect(getCellValue(11, 2)).toBe(9);
+ expect(getCellValue(11, 3)).toBe('fff');
+ expect(getCellValue(11, 4)).toBe('fff');
+ });
+ });
+});
diff --git a/packages/sheets/src/controllers/__tests__/formula/create-function-test-bed.ts b/packages/sheets/src/controllers/__tests__/formula/create-function-test-bed.ts
new file mode 100644
index 0000000000..bb24950343
--- /dev/null
+++ b/packages/sheets/src/controllers/__tests__/formula/create-function-test-bed.ts
@@ -0,0 +1,285 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* eslint-disable max-lines-per-function */
+
+import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';
+import type { ISheetData } from '@univerjs/engine-formula';
+import {
+ CellValueType,
+ ILogService,
+ Inject,
+ Injector,
+ IUniverInstanceService,
+ LocaleType,
+ LogLevel,
+ ObjectMatrix,
+ Plugin,
+ touchDependencies,
+ Univer,
+ UniverInstanceType,
+} from '@univerjs/core';
+import { FUniver } from '@univerjs/core/facade';
+import {
+ AstRootNodeFactory,
+ AstTreeBuilder,
+ CalculateController,
+ CalculateFormulaService,
+ DefinedNamesService,
+ DependencyManagerService,
+ FeatureCalculationManagerService,
+ FormulaCurrentConfigService,
+ FormulaDataModel,
+ FormulaDependencyGenerator,
+ FormulaRuntimeService,
+ FunctionNodeFactory,
+ FunctionService,
+ GlobalComputingStatusService,
+ ICalculateFormulaService,
+ IDefinedNamesService,
+ IDependencyManagerService,
+ IFeatureCalculationManagerService,
+ IFormulaCurrentConfigService,
+ IFormulaDependencyGenerator,
+ IFormulaRuntimeService,
+ IFunctionService,
+ Interpreter,
+ IOtherFormulaManagerService,
+ ISheetRowFilteredService,
+ ISuperTableService,
+ LambdaNodeFactory,
+ LambdaParameterNodeFactory,
+ Lexer,
+ LexerTreeBuilder,
+ OperatorNodeFactory,
+ OtherFormulaManagerService,
+ PrefixNodeFactory,
+ ReferenceNodeFactory,
+ SheetRowFilteredService,
+ stripErrorMargin,
+ SuffixNodeFactory,
+ SuperTableService,
+ UnionNodeFactory,
+ ValueNodeFactory,
+} from '@univerjs/engine-formula';
+import { CalculateResultApplyController } from '../../calculate-result-apply.controller';
+
+const getTestWorkbookData = (): IWorkbookData => {
+ return {
+ id: 'test',
+ appVersion: '3.0.0-alpha',
+ sheets: {
+ sheet1: {
+ id: 'sheet1',
+ cellData: {
+ 0: {
+ 0: {
+ v: 1,
+ t: CellValueType.NUMBER,
+ },
+ 1: {
+ v: 2,
+ t: CellValueType.NUMBER,
+ },
+ },
+ 1: {
+ 0: {
+ v: 3,
+ t: CellValueType.NUMBER,
+ },
+ 1: {
+ v: 4,
+ t: CellValueType.NUMBER,
+ },
+ 2: {
+ v: 'B2',
+ t: CellValueType.STRING,
+ },
+ 3: {
+ v: 'R2C2',
+ t: CellValueType.STRING,
+ },
+ },
+ 2: {
+ 0: {
+ v: 1,
+ t: CellValueType.NUMBER,
+ },
+ 1: {
+ v: ' ',
+ t: CellValueType.STRING,
+ },
+ 2: {
+ v: 1.23,
+ t: CellValueType.NUMBER,
+ },
+ 3: {
+ v: true,
+ t: CellValueType.BOOLEAN,
+ },
+ 4: {
+ v: false,
+ t: CellValueType.BOOLEAN,
+ },
+ },
+ 3: {
+ 0: {
+ v: 0,
+ t: CellValueType.NUMBER,
+ },
+ 1: {
+ v: '100',
+ t: CellValueType.STRING,
+ },
+ 2: {
+ v: '2.34',
+ t: CellValueType.STRING,
+ },
+ 3: {
+ v: 'test',
+ t: CellValueType.STRING,
+ },
+ 4: {
+ v: -3,
+ t: CellValueType.NUMBER,
+ },
+ },
+ },
+ },
+ },
+ locale: LocaleType.ZH_CN,
+ name: '',
+ sheetOrder: [],
+ styles: {},
+ };
+};
+
+export function createFunctionTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]) {
+ const univer = new Univer();
+ const injector = univer.__getInjector();
+ const get = injector.get.bind(injector);
+
+ /**
+ * This plugin hooks into Sheet's DI system to expose API to test scripts
+ */
+ class TestPlugin extends Plugin {
+ static override pluginName = 'test-plugin';
+ static override type = UniverInstanceType.UNIVER_SHEET;
+
+ private _formulaDataModel: FormulaDataModel | null = null;
+
+ constructor(
+ _config: undefined,
+ @Inject(Injector) override readonly _injector: Injector
+ ) {
+ super();
+ }
+
+ override onStarting(): void {
+ const injector = this._injector;
+ injector.add([ICalculateFormulaService, { useClass: CalculateFormulaService }]);
+ injector.add([Lexer]);
+ injector.add([LexerTreeBuilder]);
+
+ injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);
+ injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);
+ injector.add([IFunctionService, { useClass: FunctionService }]);
+ injector.add([IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }]);
+ injector.add([IFeatureCalculationManagerService, { useClass: FeatureCalculationManagerService }]);
+ injector.add([IDependencyManagerService, { useClass: DependencyManagerService }]);
+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);
+ injector.add([ISuperTableService, { useClass: SuperTableService }]);
+ injector.add([ISheetRowFilteredService, { useClass: SheetRowFilteredService }]);
+
+ injector.add([Interpreter]);
+ injector.add([AstTreeBuilder]);
+
+ injector.add([IFormulaDependencyGenerator, { useClass: FormulaDependencyGenerator }]);
+
+ injector.add([CalculateController]);
+
+ injector.add([AstRootNodeFactory]);
+ injector.add([FunctionNodeFactory]);
+ injector.add([LambdaNodeFactory]);
+ injector.add([LambdaParameterNodeFactory]);
+ injector.add([OperatorNodeFactory]);
+ injector.add([PrefixNodeFactory]);
+ injector.add([ReferenceNodeFactory]);
+ injector.add([SuffixNodeFactory]);
+ injector.add([UnionNodeFactory]);
+ injector.add([ValueNodeFactory]);
+ injector.add([FormulaDataModel]);
+
+ injector.add([GlobalComputingStatusService]);
+
+ injector.add([CalculateResultApplyController]);
+
+ dependencies?.forEach((d) => injector.add(d));
+ }
+
+ override onReady(): void {
+ touchDependencies(this._injector, [
+ [CalculateController],
+ [CalculateResultApplyController],
+ ]);
+ }
+ }
+
+ univer.registerPlugin(TestPlugin);
+ const sheet = univer.createUniverSheet(workbookData || getTestWorkbookData());
+
+ const univerInstanceService = get(IUniverInstanceService);
+ univerInstanceService.focusUnit('test');
+
+ const logService = get(ILogService);
+ logService.setLogLevel(LogLevel.SILENT); // change this to `true` to debug tests via logs
+
+ const sheetData: ISheetData = {};
+ const workbook = univerInstanceService.getCurrentUnitForType<Workbook>(UniverInstanceType.UNIVER_SHEET)!;
+ const unitId = workbook.getUnitId();
+ const sheetId = workbook.getActiveSheet()!.getSheetId();
+ workbook.getSheets().forEach((sheet) => {
+ const sheetConfig = sheet.getConfig();
+ sheetData[sheet.getSheetId()] = {
+ cellData: new ObjectMatrix(sheetConfig.cellData),
+ rowCount: sheetConfig.rowCount,
+ columnCount: sheetConfig.columnCount,
+ rowData: sheetConfig.rowData,
+ columnData: sheetConfig.columnData,
+ };
+ });
+
+ return {
+ univer,
+ api: FUniver.newAPI(univer),
+ get,
+ sheet,
+ unitId,
+ sheetId,
+ sheetData,
+ };
+}
+
+export function stripArrayValue(array: (string | number | boolean | null)[][]) {
+ return array.map((row) => row.map((cell) => {
+ if (typeof cell === 'number') {
+ return stripErrorMargin(cell);
+ }
+ return cell;
+ }));
+}
+
+export { getObjectValue } from '@univerjs/engine-formula';