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): treat non-canonical number literals as numbers (#7794)

FenjuFuda33e9c4901d
diff --git a/packages/engine-formula/src/engine/ast-node/__tests__/value-node.spec.ts b/packages/engine-formula/src/engine/ast-node/__tests__/value-node.spec.ts
new file mode 100644
index 0000000000..563ad15995
--- /dev/null
+++ b/packages/engine-formula/src/engine/ast-node/__tests__/value-node.spec.ts
@@ -0,0 +1,136 @@
+/**
+ * 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 { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { ErrorType } from '../../../basics/error-type';
+import { createFunctionTestBed } from '../../../functions/__tests__/create-function-test-bed';
+import { FUNCTION_NAMES_INFORMATION } from '../../../functions/information/function-names';
+import { Isnumber } from '../../../functions/information/isnumber';
+import { Compare } from '../../../functions/meta/compare';
+import { FUNCTION_NAMES_META } from '../../../functions/meta/function-names';
+import { Concatenate } from '../../../functions/text/concatenate';
+import { FUNCTION_NAMES_TEXT } from '../../../functions/text/function-names';
+import { getObjectValue } from '../../../functions/util';
+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 { LexerNode } from '../../analysis/lexer-node';
+import { AstTreeBuilder } from '../../analysis/parser';
+import { Interpreter } from '../../interpreter/interpreter';
+import { generateExecuteAstNodeData } from '../../utils/ast-node-tool';
+import { BaseAstNode } from '../base-ast-node';
+
+function createCalculate(testBed: ReturnType<typeof createFunctionTestBed>) {
+ const currentConfigService = testBed.get(IFormulaCurrentConfigService);
+ const runtimeService = testBed.get(IFormulaRuntimeService);
+ const lexer = testBed.get(Lexer);
+ const astTreeBuilder = testBed.get(AstTreeBuilder);
+ const interpreter = testBed.get(Interpreter);
+
+ currentConfigService.load({
+ formulaData: {},
+ arrayFormulaCellData: {},
+ arrayFormulaRange: {},
+ forceCalculate: false,
+ dirtyRanges: [],
+ dirtyNameMap: {},
+ dirtyDefinedNameMap: {},
+ dirtyUnitFeatureMap: {},
+ dirtyUnitOtherFormulaMap: {},
+ excludedCell: {},
+ allUnitData: { [testBed.unitId]: testBed.sheetData },
+ });
+ runtimeService.setCurrent(0, 0, 1, 1, testBed.sheetId, testBed.unitId);
+ testBed.get(IFunctionService).registerExecutors(
+ new Compare(FUNCTION_NAMES_META.COMPARE),
+ new Concatenate(FUNCTION_NAMES_TEXT.CONCATENATE),
+ new Isnumber(FUNCTION_NAMES_INFORMATION.ISNUMBER)
+ );
+
+ return (formula: string) => {
+ const lexerNode = lexer.treeBuilder(formula);
+ if (!(lexerNode instanceof LexerNode)) {
+ throw new TypeError(`Failed to parse formula: ${formula}`);
+ }
+ const astNode = astTreeBuilder.parse(lexerNode);
+ if (!(astNode instanceof BaseAstNode)) {
+ throw new TypeError(`Failed to build AST: ${formula}`);
+ }
+ return getObjectValue(interpreter.execute(generateExecuteAstNodeData(astNode)));
+ };
+}
+
+describe('ValueNode number literals', () => {
+ let testBed: ReturnType<typeof createFunctionTestBed>;
+
+ beforeEach(() => {
+ testBed = createFunctionTestBed();
+ });
+
+ afterEach(() => {
+ testBed.univer.dispose();
+ });
+
+ it('treats non-canonical number literals as numbers', () => {
+ const calculate = createCalculate(testBed);
+
+ expect(calculate('=12.50')).toBe(12.5);
+ expect(calculate('=.5')).toBe(0.5);
+ expect(calculate('=007')).toBe(7);
+ expect(calculate('=1E3')).toBe(1000);
+ expect(calculate('=1.5E+2')).toBe(150);
+ expect(calculate('=ISNUMBER(12.50)')).toBe(true);
+ expect(calculate('=ISNUMBER(.5)')).toBe(true);
+ expect(calculate('=12.50=12.5')).toBe(true);
+ });
+
+ it('converts number literals to canonical text', () => {
+ const calculate = createCalculate(testBed);
+
+ expect(calculate('=12.50&""')).toStrictEqual([['12.5']]);
+ expect(calculate('=1.0&"x"')).toStrictEqual([['1x']]);
+ expect(calculate('=1E3&""')).toStrictEqual([['1000']]);
+ expect(calculate('=.5&""')).toStrictEqual([['0.5']]);
+ expect(calculate('=-12.50&""')).toStrictEqual([['-12.5']]);
+ });
+
+ it('treats number literals in array constants as numbers', () => {
+ const calculate = createCalculate(testBed);
+
+ expect(calculate('={1.50,.5;007,1E3}')).toStrictEqual([[1.5, 0.5], [7, 1000]]);
+ });
+
+ it('keeps quoted number text as text', () => {
+ const calculate = createCalculate(testBed);
+
+ expect(calculate('="12.50"')).toBe('12.50');
+ expect(calculate('="007"&""')).toStrictEqual([['007']]);
+ expect(calculate('=ISNUMBER("12.50")')).toBe(false);
+ });
+
+ it('returns NUM errors for overflowing scalar and array number literals', () => {
+ const calculate = createCalculate(testBed);
+
+ expect(calculate('=1E309')).toBe(ErrorType.NUM);
+ expect(calculate('=-1E309')).toBe(ErrorType.NUM);
+ expect(calculate('=ISNUMBER(1E309)')).toBe(false);
+ expect(calculate('={1E309,-1E309;1.50,2}')).toStrictEqual([
+ [ErrorType.NUM, ErrorType.NUM],
+ [1.5, 2],
+ ]);
+ });
+});
diff --git a/packages/engine-formula/src/engine/ast-node/value-node.ts b/packages/engine-formula/src/engine/ast-node/value-node.ts
index cd90abc8bb..684508d56b 100644
--- a/packages/engine-formula/src/engine/ast-node/value-node.ts
+++ b/packages/engine-formula/src/engine/ast-node/value-node.ts
@@ -14,9 +14,9 @@
* limitations under the License.
*/
-import type { ErrorType } from '../../basics/error-type';
-import type { FunctionNode } from './';
import { DateSystem } from '@univerjs/core';
+import type { ErrorType } from '../../basics/error-type';
+import type { FunctionNode } from './function-node';
import { BooleanValue } from '../../basics/common';
import { ERROR_TYPE_SET } from '../../basics/error-type';
import { LexerNode } from '../analysis/lexer-node';
@@ -45,6 +45,12 @@ export class ValueNode extends BaseAstNode {
return;
}
+ const numberLiteral = ValueObjectFactory.createNumberLiteral(tokenTrim, dateSystem);
+ if (numberLiteral) {
+ this.setValue(numberLiteral);
+ return;
+ }
+
const parent = this.getParent();
let isIgnoreNumberPattern = true;
if (parent?.nodeType === NodeType.FUNCTION) {
diff --git a/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts b/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts
index 5cfad3ac4e..d7da6bbcfa 100644
--- a/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts
+++ b/packages/engine-formula/src/engine/value-object/__tests__/array-value-object.spec.ts
@@ -15,9 +15,9 @@
*/
import type { Nullable } from '@univerjs/core';
-import type { BaseValueObject } from '../base-value-object';
import { DateSystem } from '@univerjs/core';
import { describe, expect, it } from 'vitest';
+import type { BaseValueObject } from '../base-value-object';
import { ErrorType } from '../../../basics/error-type';
import { CELL_INVERTED_INDEX_CACHE } from '../../../basics/inverted-index-cache';
import { compareToken } from '../../../basics/token';
@@ -441,6 +441,43 @@ describe('arrayValueObject test', () => {
});
describe('ValueObjectFactory', () => {
+ it.each([
+ ['12.50', 12.5],
+ ['1.', 1],
+ ['+.5', 0.5],
+ ['007', 7],
+ ['1.5e-2', 0.015],
+ ])('parses decimal formula number literals: %s', (token, expected) => {
+ const value = ValueObjectFactory.createNumberLiteral(token, DateSystem.Date1904);
+
+ expect(value?.isNumber()).toBe(true);
+ expect(value?.getValue()).toBe(expected);
+ expect(value?.getDateSystem()).toBe(DateSystem.Date1904);
+ });
+
+ it.each(['', '0x10', '0b11', 'Infinity', '1e+', '1.2.3', '"12.50"'])(
+ 'rejects tokens outside decimal formula number syntax: %s',
+ (token) => {
+ expect(ValueObjectFactory.createNumberLiteral(token)).toBeNull();
+ }
+ );
+
+ it('rejects long malformed number literals', () => {
+ const token = `${'1'.repeat(32_000)}x`;
+
+ expect(ValueObjectFactory.createNumberLiteral(token)).toBeNull();
+ });
+
+ it.each(['000123456', '123456789123456789'])(
+ 'preserves numeric cell text when formula literals are parsed separately: %s',
+ (token) => {
+ const value = ValueObjectFactory.create(token, true);
+
+ expect(value.isString()).toBe(true);
+ expect(value.getValue()).toBe(token);
+ }
+ );
+
it('ValueObjectFactory create BooleanValueObject ', () => {
let booleanValueObject = ValueObjectFactory.create(true);
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 bab42b8721..051e2b32aa 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
@@ -15,8 +15,8 @@
*/
import type { Nullable } from '@univerjs/core';
-import type { callbackMapFnType, IArrayValueObject } from './base-value-object';
import { DateSystem, isRealNum } from '@univerjs/core';
+import type { callbackMapFnType, IArrayValueObject } from './base-value-object';
import { BooleanValue } from '../../basics/common';
import { ERROR_TYPE_SET, ErrorType } from '../../basics/error-type';
import { CELL_INVERTED_INDEX_CACHE } from '../../basics/inverted-index-cache';
@@ -1953,7 +1953,10 @@ export class ArrayValueObject extends BaseValueObject {
const row: BaseValueObject[] = [];
for (let c = 0; c < columnArrayCount; c++) {
const cellRaw = columnArray[c].trim();
- row.push(ValueObjectFactory.create(cellRaw, false, dateSystem));
+ row.push(
+ ValueObjectFactory.createNumberLiteral(cellRaw, dateSystem) ??
+ ValueObjectFactory.create(cellRaw, false, dateSystem)
+ );
}
result.push(row);
}
@@ -1991,6 +1994,8 @@ export class ArrayValueObject extends BaseValueObject {
}
}
+const NUMBER_LITERAL_REGEX = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;
+
export class ValueObjectFactory {
static create(
rawValue: string | number | boolean | null,
@@ -2042,6 +2047,23 @@ export class ValueObjectFactory {
}
return ErrorValueObject.create(ErrorType.VALUE);
}
+
+ /**
+ * Create a number from a number literal written in formula source, such as `12.50`, `.5`, `007` or `1E3`.
+ * Unlike cell text, where "000123456" must stay a string, a number literal in a formula is always a number.
+ *
+ * @param token The unquoted token from the formula source.
+ * @param dateSystem The workbook date system.
+ * @returns The number value object, a NUM error on overflow, or null when the token is not a number literal.
+ */
+ static createNumberLiteral(token: string, dateSystem: DateSystem = DateSystem.Date1900): Nullable<BaseValueObject> {
+ const tokenTrim = token.trim();
+ if (!NUMBER_LITERAL_REGEX.test(tokenTrim)) {
+ return null;
+ }
+
+ return createNumberValueObjectByRawValue(Number(tokenTrim)).withDateSystem(dateSystem);
+ }
}
function isStringWrappedByDoubleQuotes(input: string) {