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(engine-formula): align implicit intersection and PERCENTOF with Excel (#7438)

Univer994076619cc8
diff --git a/packages/engine-formula/src/engine/ast-node/function-node.ts b/packages/engine-formula/src/engine/ast-node/function-node.ts
index 6e2a200e65..99b30d5883 100644
--- a/packages/engine-formula/src/engine/ast-node/function-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/function-node.ts
@@ -206,6 +206,13 @@ export class FunctionNode extends BaseAstNode {
return result;
}
+ if (
+ this._runtimeService.hasFunctionRefInfoOverride() &&
+ (this._runtimeService.currentRowCount > 1 || this._runtimeService.currentColumnCount > 1)
+ ) {
+ return result;
+ }
+
return array.getFirstCell();
}
diff --git a/packages/engine-formula/src/engine/ast-node/prefix-node.ts b/packages/engine-formula/src/engine/ast-node/prefix-node.ts
index 7741e68ad3..db52f26ad9 100644
--- a/packages/engine-formula/src/engine/ast-node/prefix-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/prefix-node.ts
@@ -83,7 +83,7 @@ export class PrefixNode extends BaseAstNode {
const currentValue = value as BaseReferenceObject;
if (currentValue.isCell()) {
- return ErrorValueObject.create(ErrorType.VALUE);
+ return currentValue.getCellByPosition();
}
if (this._preserveAtRangeForFormula2LookupArray()) {
diff --git a/packages/engine-formula/src/engine/reference-object/__tests__/cell-reference-object.spec.ts b/packages/engine-formula/src/engine/reference-object/__tests__/cell-reference-object.spec.ts
index ac962419f6..32d69e5024 100644
--- a/packages/engine-formula/src/engine/reference-object/__tests__/cell-reference-object.spec.ts
+++ b/packages/engine-formula/src/engine/reference-object/__tests__/cell-reference-object.spec.ts
@@ -17,6 +17,7 @@
import { CellValueType, ObjectMatrix } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
import { CellReferenceObject } from '../cell-reference-object';
+import { RangeReferenceObject } from '../range-reference-object';
describe('CellReferenceObject', () => {
it('should allow blank cells inside the Excel grid even when they are outside snapshot row data', () => {
@@ -114,6 +115,45 @@ describe('CellReferenceObject', () => {
expect(reference.getCellByPosition(0, 0).getValue()).toBe(1);
});
+ it('should not apply a shared-formula offset twice when unioning a materialized reference', () => {
+ const sharedReference = new CellReferenceObject('$B$2');
+ const materializedReference = new CellReferenceObject('B3');
+ sharedReference.setRefOffset(0, 1);
+
+ const union = sharedReference.unionBy(materializedReference);
+
+ if (!(union instanceof RangeReferenceObject)) {
+ throw new TypeError('Expected a range reference');
+ }
+
+ expect(union.getRangePosition()).toEqual(expect.objectContaining({
+ startRow: 1,
+ endRow: 2,
+ startColumn: 1,
+ endColumn: 1,
+ }));
+ });
+
+ it('should apply matching shared-formula offsets once when unioning references', () => {
+ const startReference = new CellReferenceObject('A1');
+ const endReference = new CellReferenceObject('B1');
+ startReference.setRefOffset(0, 1);
+ endReference.setRefOffset(0, 1);
+
+ const union = startReference.unionBy(endReference);
+
+ if (!(union instanceof RangeReferenceObject)) {
+ throw new TypeError('Expected a range reference');
+ }
+
+ expect(union.getRangePosition()).toEqual(expect.objectContaining({
+ startRow: 1,
+ endRow: 1,
+ startColumn: 0,
+ endColumn: 1,
+ }));
+ });
+
it('should treat string enum number cell types as numeric cells', () => {
const reference = new CellReferenceObject('A1');
diff --git a/packages/engine-formula/src/engine/reference-object/cell-reference-object.ts b/packages/engine-formula/src/engine/reference-object/cell-reference-object.ts
index 76bab133be..09fb6ecd0f 100644
--- a/packages/engine-formula/src/engine/reference-object/cell-reference-object.ts
+++ b/packages/engine-formula/src/engine/reference-object/cell-reference-object.ts
@@ -59,7 +59,7 @@ export class CellReferenceObject extends BaseReferenceObject {
// return ErrorValueObject.create(ErrorType.REF);
// }
- const newRangeData = this.unionRange(this.getRangeData(), cellReferenceObject.getRangeData());
+ const newRangeData = this.unionRange(this.getRangePosition(), cellReferenceObject.getRangePosition());
return this._createRange(newRangeData);
}
@@ -126,10 +126,6 @@ export class CellReferenceObject extends BaseReferenceObject {
rangeReferenceObject.setRuntimeFeatureCellData(this.getRuntimeFeatureCellData());
- const { x, y } = this.getRefOffset();
-
- rangeReferenceObject.setRefOffset(x, y);
-
const forceSheetId = this.getForcedSheetId();
rangeReferenceObject.setForcedSheetName(this.getForcedSheetName());
diff --git a/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts b/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts
index 264d676d24..2dbaa397a9 100644
--- a/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts
+++ b/packages/engine-formula/src/functions/__tests__/nested-functions.spec.ts
@@ -917,6 +917,10 @@ describe('Test nested functions', () => {
expect(result).toStrictEqual([[3]]);
});
+ it('Nested INDEX returns its selected cell through explicit implicit intersection', () => {
+ expect(calculate('=@INDEX(C2:C4,2)')).toBe(3);
+ });
+
it('Nested functions MATCH keeps bare Formula2 at ranges scalar in lookup products', () => {
const result = calculate('=IFERROR(INDEX(C2:C4,MATCH(44928,(@B2:B4=B3)*(@A2:A4),0)),"")');
diff --git a/packages/engine-formula/src/functions/logical/percentof/__tests__/index.spec.ts b/packages/engine-formula/src/functions/logical/percentof/__tests__/index.spec.ts
new file mode 100644
index 0000000000..04adaf379f
--- /dev/null
+++ b/packages/engine-formula/src/functions/logical/percentof/__tests__/index.spec.ts
@@ -0,0 +1,60 @@
+/**
+ * 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 { describe, expect, it } from 'vitest';
+import { ErrorType } from '../../../../basics/error-type';
+import { ArrayValueObject, transformToValueObject } from '../../../../engine/value-object/array-value-object';
+import { NumberValueObject } from '../../../../engine/value-object/primitive-object';
+import { getObjectValue } from '../../../util';
+import { FUNCTION_NAMES_LOGICAL } from '../../function-names';
+import { Percentof } from '../index';
+
+describe('Test percentof function', () => {
+ const testFunction = new Percentof(FUNCTION_NAMES_LOGICAL.PERCENTOF);
+
+ it('returns the Excel-compatible ratio for scalar values', () => {
+ const result = testFunction.calculate(
+ NumberValueObject.create(185980),
+ NumberValueObject.create(229829)
+ );
+
+ expect(getObjectValue(result)).toBeCloseTo(0.8092103259379799, 15);
+ });
+
+ it('sums ranges before dividing and reports a zero denominator', () => {
+ const subset = ArrayValueObject.create({
+ calculateValueList: transformToValueObject([[10], [5]]),
+ rowCount: 2,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+ const all = ArrayValueObject.create({
+ calculateValueList: transformToValueObject([[10], [20], [5]]),
+ rowCount: 3,
+ columnCount: 1,
+ unitId: '',
+ sheetId: '',
+ row: 0,
+ column: 0,
+ });
+
+ expect(getObjectValue(testFunction.calculate(subset, all))).toBeCloseTo(15 / 35, 15);
+ expect(getObjectValue(testFunction.calculate(subset, NumberValueObject.create(0)))).toBe(ErrorType.DIV_BY_ZERO);
+ });
+});
diff --git a/packages/engine-formula/src/functions/logical/percentof/index.ts b/packages/engine-formula/src/functions/logical/percentof/index.ts
index 1a0cbf6a41..aa178accc5 100644
--- a/packages/engine-formula/src/functions/logical/percentof/index.ts
+++ b/packages/engine-formula/src/functions/logical/percentof/index.ts
@@ -15,20 +15,28 @@
*/
import type { BaseValueObject } from '../../../engine/value-object/base-value-object';
-import { ErrorType } from '../../../basics/error-type';
-import { ErrorValueObject } from '../../../engine/value-object/base-value-object';
-import { BaseFunction } from '../../base-function';
+import { Sum } from '../../math/sum';
/**
- * PERCENTOF is an Excel GROUPBY aggregator token. It is evaluated by GROUPBY's
- * AST path, not as a standalone scalar function.
+ * PERCENTOF is logically equivalent to SUM(dataSubset) / SUM(dataAll).
+ * GROUPBY also consumes the function name as an aggregator token through its AST path.
*/
-export class Percentof extends BaseFunction {
- override minParams = 0;
+export class Percentof extends Sum {
+ override minParams = 2;
- override maxParams = 0;
+ override maxParams = 2;
- override calculate(..._variants: BaseValueObject[]) {
- return ErrorValueObject.create(ErrorType.VALUE);
+ override calculate(dataSubset: BaseValueObject, dataAll: BaseValueObject) {
+ const subsetTotal = super.calculate(dataSubset);
+ if (subsetTotal.isError()) {
+ return subsetTotal;
+ }
+
+ const allTotal = super.calculate(dataAll);
+ if (allTotal.isError()) {
+ return allTotal;
+ }
+
+ return subsetTotal.divided(allTotal);
}
}
diff --git a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts b/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts
index f15edcbd33..3a05799a37 100644
--- a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts
+++ b/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts
@@ -149,6 +149,16 @@ describe('FormulaRuntimeService', () => {
expect(runtime.currentSubUnitId).toBe('sheet');
expect(runtime.currentUnitId).toBe('unit');
+ expect(runtime.hasFunctionRefInfoOverride()).toBe(false);
+ const restoreRefInfo = runtime.setFunctionRefInfoOverride(1, 2);
+ expect(runtime.hasFunctionRefInfoOverride()).toBe(true);
+ expect(runtime.currentRowCount).toBe(1);
+ expect(runtime.currentColumnCount).toBe(2);
+ restoreRefInfo();
+ expect(runtime.hasFunctionRefInfoOverride()).toBe(false);
+ expect(runtime.currentRowCount).toBe(99);
+ expect(runtime.currentColumnCount).toBe(88);
+
const lambdaVar = new Map<string, Nullable<BaseAstNode>>([['x', null]]);
runtime.registerFunctionDefinitionPrivacyVar('lambda-1', lambdaVar);
expect(runtime.getFunctionDefinitionPrivacyVar('lambda-1')).toBe(lambdaVar);
diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.ts
index 5267ea0e20..1860a5ca67 100644
--- a/packages/engine-formula/src/services/runtime.service.ts
+++ b/packages/engine-formula/src/services/runtime.service.ts
@@ -123,6 +123,8 @@ export interface IFormulaRuntimeService {
setFunctionRefInfoOverride(rowCount: number, columnCount: number): () => void;
+ hasFunctionRefInfoOverride(): boolean;
+
registerFunctionDefinitionPrivacyVar(lambdaId: string, lambdaVar: Map<string, Nullable<BaseAstNode>>): void;
getFunctionDefinitionPrivacyVar(lambdaId: string): Nullable<Map<string, Nullable<BaseAstNode>>>;
@@ -441,6 +443,10 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime
};
}
+ hasFunctionRefInfoOverride(): boolean {
+ return this._functionRefInfoOverrideStack.length > 0;
+ }
+
clearFunctionDefinitionPrivacyVar() {
this._functionDefinitionPrivacyVar.clear();
}