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.
TypeScript boardcollaborationdocdocxexceloffce365officepdfpptpptxpresentationsdksheetslidesspreadsheetuniverwordwordprocessorworkspacexlsx
perf(formula): reduce memory and preserve Excel correctness (#8116)
Univer7e7ba63878a6
diff --git a/packages/engine-formula/README.md b/packages/engine-formula/README.mdindex 91b0f6ad2d..49fff628c6 100644--- a/packages/engine-formula/README.md+++ b/packages/engine-formula/README.md@@ -30,6 +30,68 @@ import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';univer.registerPlugin(UniverFormulaEnginePlugin);```+## Formula cache ownership++The formula plugin registers one `FormulaCacheService` per Univer injector. Parsed ASTs and expanded lexer trees belong to that instance. Range arrays and comparison indexes belong to a calculation context that is released on completion, failure, reset, or disposal. Closing a workbook invalidates only that workbook's entries. Disposing one Univer does not clear another instance's caches.++Registering, replacing, or unregistering a function invalidates its cached ASTs and expanded lexer trees using the parser's function-name normalization. Cached unknown-function errors are refreshed for names with whitespace, supported Excel prefixes, and aliases as well as ordinary names.++`FormulaCacheService` is internal and is not exported from the package root. Integrations and cross-package test fixtures initialize formula dependencies through `UniverFormulaEnginePlugin` or the corresponding Pro plugin, which registers the owning cache service. `Lexer` owns expanded-tree cache lookup and invalidation. `LexerTreeBuilder` has no service dependency and always builds a fresh tree. Standalone and editor callers can construct it directly. Custom runtime implementations may omit the optional calculation-cache hooks; references then compute without caching.++Range-array and comparison-index invalidation uses the owning runtime's `clearArrayObjectCache()` and `clearInvertedIndexCache()` hooks. The obsolete `FORMULA_REF_TO_ARRAY_CACHE` and `CELL_INVERTED_INDEX_CACHE` globals are removed. Facade usage, workbook IDs, snapshots, and collaboration changesets are unchanged.++## Calculation input and result ownership++Formula capture, load, and execution capabilities are internal interfaces shared by cooperating calculation engines, not application or Facade APIs. Their exports and type declarations remain available for cross-package integration; this does not make them stable public extension points. Validate the exact OSS, Pro, and engine versions together under the [API stability policy](../../docs/API_STABILITY.md).++`IFormulaDataSnapshot` captures ephemeral calculation input, not a persisted Workbook snapshot or a replacement for `IWorkbookData`. It preserves formula values even when the Workbook is edited later. `materialize()` returns an owned, mutable formula DTO and caches it for later reads. `FormulaCurrentConfigService` can defer materialization until `getFormulaData()`; another load, formula-data registration, or disposal replaces that deferred state.++Capture requires an engine to explicitly advertise `supportsFormulaDataSnapshot === true`, provide its execution method, and successfully prepare the input. Otherwise calculation retains the existing complete DTO and `execute()` route. A captured input contains a method and cannot be sent as an RPC payload. Worker and remote adapters retain serializable input unless their protocol explicitly supports another format; do not probe unknown methods through a generic RPC proxy.++Capture shares the ordinary Workbook, Worksheet, and ObjectMatrix traversal, array preparation, and formula-field read order. It does not inspect private model storage or qualify every cell accessor. Ordinary formulas use bounded coordinate/string-reference chunks instead of one DTO cell object each. Shared formulas, unusual values, or unsupported coordinates switch that sheet to ordinary DTO output using the captured entries, without rescanning the source. Base formulas retain their DTO preparation; materialization releases the compact chunks.++`IFormulaRuntimeService.beginCircularReferences()` preserves and validates previous cycle records for incremental Web/Pro calculation. An engine supplying the complete current cycle set can pass `true` to start an empty pending set without reading the formula DTO. Recording and completion still copy diagnostics, and stopped calculations do not replace the published set. An empty completed set clears resolved cycles; UI alerts and `FWorkbook.getCircularReferences()` continue to consume the published records.++Customized formula-model preparation or initially customized output-matrix methods and relevant Object.prototype properties retain the eager route. Output-matrix and DTO prototypes must remain stable during synchronous capture; prototype mutations inside source getters are outside this capability contract. Ordinary source methods and getters remain supported. An optional Proxy classifier can reject a proxied formula model before preparation.++`FormulaResultService` is the shared batch writer for Web, Pro, and native engines. It submits array/image/dependency metadata and cell results through the existing mutations. Web/Pro release calculation contexts after materializing results and before awaiting model application. Engines await the writer before publishing completion; `CalculateController` publishes the terminal notification without submitting results again. Native engines may submit intermediate dependency passes so feature callbacks reading Workbook values see the current pass. A completion remains an `IAllRuntimeData` snapshot; it is not a request to replay its values.++Custom calculation-service implementations must use the writer for their batches before emitting completion. Subclasses calling the base `CalculateFormulaService` constructor must inject and pass `FormulaResultService`. Upgrade cooperating OSS, Pro, and native Wrapper integrations together; no result-ownership capability probe or extra mutation field is required.++Delayed or absent application acknowledgements never cause an automatic duplicate submission. An integration that rejects delivery must retain and explicitly reapply its result through the shared writer; recalculation is not delivery retry because native output can omit unchanged cached cells. A thrown writer command rejects `execute()` and releases runtime data without announcing successful completion. Low-level callers must handle execution failures as well as completion events.++After all required acknowledgements, the session synchronously emits the complete `resultApplied$` payload, then releases its strong reference if that session and result are still current. Duplicate acknowledgements use weak identity bookkeeping. Reentrant listeners must not have their new session overwritten; subscribers retaining a payload own that reference.++Completion no longer adds a duplicate result mutation, including for arrays, multiple worksheets, other-formula grids, and pending acknowledgements. Result mutations carry `applyFormulaCalculationResult: true`. Engine-generated array metadata mutations carry `fromFormula: true` and `onlyLocal: true`; consumers must distinguish them from genuine edits without feeding formula output into another calculation. Public Workbook/Worksheet/ObjectMatrix models and persisted snapshot schemas remain unchanged. These controllers and session services are shared by browser and headless integrations.++### Consumer validation++- Compare OSS and Pro values, types, errors, formula text, formats, shared formulas, arrays, circular references, and incremental edits with the cooperating versions.+- Check Pro last-value persistence, external references, and other-formula results; persistence must run once for each applied result batch.+- Exercise formula replacement/removal, spill growth/shrinkage, blocked spills, undo/redo, and structural edits, checking mutation notifications as well as values.+- Verify delayed, early, duplicate, and reentrant acknowledgements, stopped/failed calculations, disposal, independent instances, worker/RPC fallbacks, and collaboration consumers of mutation options or counts.++Value comparisons alone do not establish notification, worker-protocol, or Pro compatibility. Each supported runtime must satisfy the result-application and event contracts.++## Formula reference compatibility++Formula reads convert rich-text paragraph separators to Excel's LF line breaks.+Saved rich-text documents and CRLF in plain string values remain unchanged. This+also corrects `LEN` and `SEARCH` over rich-text references; recalculate existing+formula caches to refresh affected results. Public models and mutations are unchanged.++`PV` uses integer compounding for whole periods with an absolute value no greater+than 2,147,483,647, taking the reciprocal for negative periods. This preserves the+factor before cancellation in small loan balances. Fractional and larger periods+retain floating exponentiation. Last digits may change; formulas,+Workbook models and snapshots require no migration. Pro and native integrations+must use the matching correction. XIRR retains its current numerical precision;+its result can differ from Excel's earlier stopping point.++Reference-form `INDEX` returns `#VALUE!` when its areas span different worksheets or workbooks. References that resolve to the same worksheet remain valid.++Use whole-span quoting for quoted 3D ranges, such as `'Jan:Mar'!B2:C3`. Separately quoted endpoints, such as `'Jan':'Mar'!B2:C3` and the Excel-saved `Jan:'Mar'!B2:C3` form, return `#NAME?` for both single-cell and rectangular references. Ordinary ranges such as `Jan!B2:'Jan'!C3` remain supported. Adjust formulas that depend on these invalid forms or their previous incorrect results. Workbook/Worksheet models, persisted snapshots, and mutation formats require no migration.+## Worker usageOn the main thread, import `UniverFormulaEnginePlugin` from `@univerjs/engine-formula`. Set `notExecuteFormula: true` to delegate calculation to the worker.diff --git a/packages/engine-formula/src/basics/function.ts b/packages/engine-formula/src/basics/function.tsindex 7e369a2394..ef59fb7b13 100644--- a/packages/engine-formula/src/basics/function.ts+++ b/packages/engine-formula/src/basics/function.ts@@ -28,9 +28,9 @@ import type { FUNCTION_NAMES_LOOKUP } from '../functions/lookup/function-names';import type { FUNCTION_NAMES_MATH } from '../functions/math/function-names';import type { FUNCTION_NAMES_META } from '../functions/meta/function-names';import type { FUNCTION_NAMES_STATISTICAL } from '../functions/statistical/function-names';-import type { FUNCTION_NAMES_TEXT } from '../functions/text/function-names';import type { FUNCTION_NAMES_UNIVER } from '../functions/univer/function-names';import type { FUNCTION_NAMES_WEB } from '../functions/web/function-names';+import { FUNCTION_NAMES_TEXT } from '../functions/text/function-names';/*** Function type, refer to https://support.microsoft.com/en-us/office/excel-functions-by-category-5f91f4e9-7b42-46d2-9bd1-63f26a86c0eb@@ -210,3 +210,17 @@ export type IFunctionNames =| FUNCTION_NAMES_TEXT| FUNCTION_NAMES_UNIVER| FUNCTION_NAMES_WEB;++export function normalizeFunctionToken(token: string): string {+ if (token === 'REGEXTEST' || token === '_XLFN.REGEXTEST') {+ return FUNCTION_NAMES_TEXT.REGEXMATCH;+ }++ for (const prefix of ['_XLFN.', '_XLWS.', '_XLETA.']) {+ if (token.startsWith(prefix)) {+ return token.slice(prefix.length);+ }+ }++ return token;+}diff --git a/packages/engine-formula/src/basics/inverted-index-cache.ts b/packages/engine-formula/src/basics/inverted-index-cache.tsindex d750ee5653..739d5c7526 100644--- a/packages/engine-formula/src/basics/inverted-index-cache.ts+++ b/packages/engine-formula/src/basics/inverted-index-cache.ts@@ -28,9 +28,7 @@ type ValueTypeWithSymbol = ValueType | symbol;// empty cell, empty string and null value share the same inverted index cache keyexport const DEFAULT_EMPTY_CELL_KEY = Symbol('EMPTY_CELL');-const normalizedValueMap: Map<ValueTypeWithNullUndefined, ValueTypeWithSymbol> = new Map();--function normalizeValue(value: ValueTypeWithNullUndefined): ValueTypeWithSymbol {+function normalizeValue(value: ValueTypeWithNullUndefined, normalizedValueMap: Map<ValueTypeWithNullUndefined, ValueTypeWithSymbol>): ValueTypeWithSymbol {if (normalizedValueMap.has(value)) {return normalizedValueMap.get(value) as ValueTypeWithSymbol;}@@ -54,6 +52,8 @@ function normalizeValue(value: ValueTypeWithNullUndefined): ValueTypeWithSymbol}export class InvertedIndexCache {+ private readonly _normalizedValueMap = new Map<ValueTypeWithNullUndefined, ValueTypeWithSymbol>();+/*** {* unitId:{@@ -136,7 +136,7 @@ export class InvertedIndexCache {}}- const _value = normalizeValue(value);+ const _value = normalizeValue(value, this._normalizedValueMap);let cellList = columnMap.get(_value);if (cellList == null) {@@ -168,7 +168,7 @@ export class InvertedIndexCache {matchingRows: [],};- const _value = normalizeValue(value);+ const _value = normalizeValue(value, this._normalizedValueMap);if (ERROR_TYPE_SET.has(_value as ErrorType)) {result.errorType = _value as ErrorType;@@ -303,10 +303,16 @@ export class InvertedIndexCache {};}+ deleteUnit(unitId: string): void {+ this._cache.delete(unitId);+ this._continueBuildingCache.delete(unitId);+ this._normalizedValueMap.clear();+ }+clear() {this._cache.clear();this._continueBuildingCache.clear();- normalizedValueMap.clear();+ this._normalizedValueMap.clear();}private _handleNewInterval(columnMap: IntervalTree<NumericTuple>, startRow: number, endRow: number) {@@ -339,5 +345,3 @@ export class InvertedIndexCache {columnMap.insert([min, max]);}}--export const CELL_INVERTED_INDEX_CACHE = new InvertedIndexCache();diff --git a/packages/engine-formula/src/controllers/__tests__/calculate.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/calculate.controller.spec.tsindex bc34870ce1..717a6ed324 100644--- a/packages/engine-formula/src/controllers/__tests__/calculate.controller.spec.ts+++ b/packages/engine-formula/src/controllers/__tests__/calculate.controller.spec.ts@@ -15,9 +15,13 @@*/import type { ICommandInfo } from '@univerjs/core';-import { ObjectMatrix } from '@univerjs/core';+import { ICommandService, Injector, ObjectMatrix } from '@univerjs/core';+import { fromModule, toModule } from '@univerjs/rpc';import { Subject } from 'rxjs';-import { describe, expect, it, vi } from 'vitest';+import { describe, expect, it, onTestFinished, vi } from 'vitest';+import type { IFormulaDatasetConfig } from '../../basics/common';+import type { IFormulaDataSnapshot } from '../../models/formula-data-snapshot';+import type { IAllRuntimeData, IExecutionInProgressParams } from '../../services/runtime.service';import { SetArrayFormulaDataMutation } from '../../commands/mutations/set-array-formula-data.mutation';import {SetCellFormulaDependencyCalculationMutation,@@ -35,7 +39,8 @@ import {SetQueryFormulaDependencyMutation,SetQueryFormulaDependencyResultMutation,} from '../../commands/mutations/set-formula-calculation.mutation';-import { SetImageFormulaDataMutation } from '../../commands/mutations/set-image-formula-data.mutation';+import { FormulaDataModel } from '../../models/formula-data.model';+import { ICalculateFormulaService } from '../../services/calculate-formula.service';import { FormulaExecutedStateType, FormulaExecuteStageType } from '../../services/runtime.service';import { CalculateController } from '../calculate.controller';@@ -61,6 +66,21 @@ function createCommandServiceMock(): ICommandServiceMock {};}+function createTestBed(+ commandService: ICommandServiceMock,+ calculateFormulaService: Pick<ICalculateFormulaService, 'execute' | 'executionCompleteListener$' | 'executionInProgressListener$'>,+ formulaDataModel: Pick<FormulaDataModel, 'getFormulaData' | 'getArrayFormulaCellData' | 'getArrayFormulaRange'>+) {+ const injector = new Injector([+ [ICommandService, { useValue: commandService }],+ [ICalculateFormulaService, { useValue: calculateFormulaService }],+ [FormulaDataModel, { useValue: formulaDataModel }],+ [CalculateController],+ ]);+ onTestFinished(() => injector.dispose());+ return injector;+}+describe('CalculateController', () => {it('should dispatch execute and stop events from commands', async () => {const commandService = createCommandServiceMock();@@ -89,12 +109,8 @@ describe('CalculateController', () => {mergeArrayFormulaRange: vi.fn(),};- // eslint-disable-next-line no-new- new CalculateController(- commandService as never,- calculateFormulaService as never,- formulaDataModel as never- );+ const injector = createTestBed(commandService, calculateFormulaService, formulaDataModel);+ injector.get(CalculateController);commandService.emit(SetFormulaCalculationStopMutation.id, {});expect(calculateFormulaService.stopFormulaExecution).toHaveBeenCalledTimes(1);@@ -147,12 +163,8 @@ describe('CalculateController', () => {mergeArrayFormulaRange: vi.fn(),};- // eslint-disable-next-line no-new- new CalculateController(- commandService as never,- calculateFormulaService as never,- formulaDataModel as never- );+ const injector = createTestBed(commandService, calculateFormulaService, formulaDataModel);+ injector.get(CalculateController);commandService.emit(SetFormulaStringBatchCalculationMutation.id, {formulas: {@@ -227,7 +239,7 @@ describe('CalculateController', () => {);});- it('should emit calculation progress and apply successful runtime result', async () => {+ it('emits one terminal notification without resubmitting results', async () => {const commandService = createCommandServiceMock();const executionCompleteListener$ = new Subject<any>();const executionInProgressListener$ = new Subject<any>();@@ -254,12 +266,8 @@ describe('CalculateController', () => {mergeArrayFormulaRange: vi.fn(),};- // eslint-disable-next-line no-new- new CalculateController(- commandService as never,- calculateFormulaService as never,- formulaDataModel as never- );+ const injector = createTestBed(commandService, calculateFormulaService, formulaDataModel);+ injector.get(CalculateController);executionInProgressListener$.next({totalFormulasToCalculate: 3,@@ -280,15 +288,13 @@ describe('CalculateController', () => {{ onlyLocal: true });- executionCompleteListener$.next({+ const unitMatrix = new ObjectMatrix({ 0: { 0: { v: 123 } } });+ const forValue = vi.spyOn(unitMatrix, 'forValue');+ const runtimeData = {functionsExecutedState: FormulaExecutedStateType.SUCCESS,unitData: {unit: {- sheet: new ObjectMatrix({- 0: {- 0: { v: 123 },- },- }),+ sheet: unitMatrix,},},unitOtherData: {},@@ -302,34 +308,20 @@ describe('CalculateController', () => {runtimeFeatureRange: {},runtimeFeatureCellData: {},dependencyTreeModelData: [{ treeId: 100 }],- });+ };+ executionCompleteListener$.next(runtimeData);await Promise.resolve();- expect(formulaDataModel.clearPreviousArrayFormulaCellData).toHaveBeenCalled();- expect(formulaDataModel.mergeArrayFormulaCellData).toHaveBeenCalled();- expect(formulaDataModel.mergeArrayFormulaRange).toHaveBeenCalled();- expect(commandService.executeCommand).toHaveBeenCalledWith(- SetArrayFormulaDataMutation.id,- expect.anything(),- { onlyLocal: true, fromFormula: true }- );- expect(commandService.executeCommand).toHaveBeenCalledWith(- SetImageFormulaDataMutation.id,- expect.objectContaining({- imageFormulaData: expect.any(Array),- }),- { onlyLocal: true }- );- expect(commandService.executeCommand).toHaveBeenCalledWith(- SetFormulaDependencyCalculationResultMutation.id,- { result: [{ treeId: 100 }] },- { onlyLocal: true }- );- expect(commandService.executeCommand).toHaveBeenCalledWith(- SetFormulaCalculationResultMutation.id,- expect.anything(),+ expect(commandService.executeCommand.mock.calls.filter(([id]) => id === SetFormulaCalculationResultMutation.id)).toHaveLength(0);+ expect(formulaDataModel.mergeArrayFormulaCellData).not.toHaveBeenCalled();+ expect(forValue).not.toHaveBeenCalled();+ expect(commandService.executeCommand).toHaveBeenLastCalledWith(+ SetFormulaCalculationNotificationMutation.id,+ { functionsExecutedState: FormulaExecutedStateType.SUCCESS },{ onlyLocal: true });+ expect(runtimeData.unitData.unit.sheet).toBe(unitMatrix);+ expect(unitMatrix.getValue(0, 0)).toEqual({ v: 123 });});it('should only apply tree result when no formula executed', async () => {@@ -359,12 +351,8 @@ describe('CalculateController', () => {mergeArrayFormulaRange: vi.fn(),};- // eslint-disable-next-line no-new- new CalculateController(- commandService as never,- calculateFormulaService as never,- formulaDataModel as never- );+ const injector = createTestBed(commandService, calculateFormulaService, formulaDataModel);+ injector.get(CalculateController);executionCompleteListener$.next({functionsExecutedState: FormulaExecutedStateType.NOT_EXECUTED,@@ -372,15 +360,156 @@ describe('CalculateController', () => {});await Promise.resolve();- expect(commandService.executeCommand).toHaveBeenCalledWith(- SetFormulaDependencyCalculationResultMutation.id,- { result: [{ treeId: 201 }] },- { onlyLocal: true }- );expect(commandService.executeCommand).toHaveBeenCalledWith(SetFormulaCalculationNotificationMutation.id,{ functionsExecutedState: FormulaExecutedStateType.NOT_EXECUTED },{ onlyLocal: true });+ for (const state of [FormulaExecutedStateType.STOP_EXECUTION, FormulaExecutedStateType.INITIAL]) {+ commandService.executeCommand.mockClear();+ executionCompleteListener$.next({ functionsExecutedState: state });+ await Promise.resolve();+ expect(commandService.executeCommand).toHaveBeenCalledTimes(1);+ expect(commandService.executeCommand).toHaveBeenCalledWith(+ SetFormulaCalculationNotificationMutation.id,+ { functionsExecutedState: state },+ { onlyLocal: true }+ );+ }+ });+});++describe('CalculateController formula snapshot capability', () => {+ it('captures before later metadata reads and passes no placeholder formula data', async () => {+ const commandService = createCommandServiceMock();+ let formula = '=1';+ const events: string[] = [];+ const service = {+ executionCompleteListener$: new Subject<IAllRuntimeData>(),+ executionInProgressListener$: new Subject<IExecutionInProgressParams>(),+ supportsFormulaDataSnapshot: true,+ prepareFormulaDataSnapshot: vi.fn(() => {+ events.push('capture');+ const captured = formula;+ return { materialize: () => ({ u: { s: { 0: { 1: { f: captured } } } } }) };+ }),+ execute: vi.fn(async () => {}),+ executeWithFormulaDataSnapshot: vi.fn(async function (+ this: unknown,+ config: Omit<IFormulaDatasetConfig, 'formulaData'>,+ snapshot: IFormulaDataSnapshot+ ) {+ expect(this).toBe(service);+ expect(Object.hasOwn(config, 'formulaData')).toBe(false);+ expect(config.dirtyReferenceUnits).toEqual(['u']);+ expect(snapshot.materialize()).toEqual({ u: { s: { 0: { 1: { f: '=1' } } } } });+ }),+ };+ const model = {+ getFormulaData: vi.fn(),+ getArrayFormulaCellData: () => {+ events.push('cells');+ formula = '=99';+ return {};+ },+ getArrayFormulaRange: () => {+ events.push('ranges');+ return {};+ },+ };+ const injector = createTestBed(commandService, service, model);+ injector.get(CalculateController);+ commandService.emit(SetFormulaCalculationStartMutation.id, { dirtyReferenceUnits: ['u'] });+ await Promise.resolve();+ expect(events).toEqual(['capture', 'cells', 'ranges']);+ expect(service.executeWithFormulaDataSnapshot).toHaveBeenCalledTimes(1);+ expect(service.execute).not.toHaveBeenCalled();+ expect(model.getFormulaData).not.toHaveBeenCalled();+ });++ it('uses the eager getter once when snapshot preparation declines', async () => {+ const commandService = createCommandServiceMock();+ const data = { u: {} };+ const service = {+ executionCompleteListener$: new Subject<IAllRuntimeData>(),+ executionInProgressListener$: new Subject<IExecutionInProgressParams>(),+ supportsFormulaDataSnapshot: true,+ prepareFormulaDataSnapshot: vi.fn(() => undefined),+ executeWithFormulaDataSnapshot: vi.fn(),+ execute: vi.fn(async (_config: IFormulaDatasetConfig) => {}),+ };+ const model = {+ getFormulaData: vi.fn(() => data),+ getArrayFormulaCellData: () => ({}),+ getArrayFormulaRange: () => ({}),+ };+ const injector = createTestBed(commandService, service, model);+ injector.get(CalculateController);+ commandService.emit(SetFormulaCalculationStartMutation.id, { dirtyReferenceUnits: ['u'] });+ await Promise.resolve();+ expect(model.getFormulaData).toHaveBeenCalledTimes(1);+ expect(service.execute.mock.calls[0][0].formulaData).toBe(data);+ expect(service.execute.mock.calls[0][0].dirtyReferenceUnits).toEqual(['u']);+ expect(service.executeWithFormulaDataSnapshot).not.toHaveBeenCalled();+ });++ it('does not opt in through dynamically generated RPC methods', async () => {+ const commandService = createCommandServiceMock();+ const data = { u: {} };+ const execute = vi.fn(async (_config: IFormulaDatasetConfig) => {});+ const unknownRpcCall = vi.fn();+ const service = new Proxy({+ execute,+ executionCompleteListener$: new Subject<IAllRuntimeData>(),+ executionInProgressListener$: new Subject<IExecutionInProgressParams>(),+ }, {+ get(target, key, receiver) {+ if (key === 'dispose') return undefined;+ return Reflect.has(target, key) ? Reflect.get(target, key, receiver) : unknownRpcCall;+ },+ });+ const model = {+ getFormulaData: vi.fn(() => data),+ getArrayFormulaCellData: () => ({}),+ getArrayFormulaRange: () => ({}),+ };+ const injector = createTestBed(commandService, service, model);+ injector.get(CalculateController);+ commandService.emit(SetFormulaCalculationStartMutation.id, {});+ await Promise.resolve();+ expect(unknownRpcCall).not.toHaveBeenCalled();+ expect(execute.mock.calls[0][0].formulaData).toBe(data);+ });++ it('keeps the complete formula DTO on the existing RPC channel without invoking optional capabilities', async () => {+ const commandService = createCommandServiceMock();+ const data = { u: {} };+ const channel = fromModule({ execute: vi.fn(async (_config: IFormulaDatasetConfig) => {}) });+ const call = vi.spyOn(channel, 'call');+ const subscribe = vi.spyOn(channel, 'subscribe');+ const remote = toModule<ICalculateFormulaService>(channel);+ // The controller consumes local observables; calculation methods retain the real channel proxy.+ const service = new Proxy({+ executionCompleteListener$: new Subject<IAllRuntimeData>(),+ executionInProgressListener$: new Subject<IExecutionInProgressParams>(),+ execute: remote.execute,+ }, {+ get(target, key, receiver) {+ return Reflect.has(target, key) ? Reflect.get(target, key, receiver) : Reflect.get(remote, key);+ },+ });+ const model = {+ getFormulaData: vi.fn(() => data),+ getArrayFormulaCellData: () => ({}),+ getArrayFormulaRange: () => ({}),+ };+ const injector = createTestBed(commandService, service, model);+ injector.get(CalculateController);+ commandService.emit(SetFormulaCalculationStartMutation.id, {});+ await Promise.resolve();+ expect(call).toHaveBeenCalledTimes(1);+ expect(call).toHaveBeenCalledWith('execute', [expect.objectContaining({ formulaData: data })]);+ expect(model.getFormulaData).toHaveBeenCalledTimes(1);+ expect(subscribe).not.toHaveBeenCalled();});});diff --git a/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.ts b/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.tsindex 397ecf8ad6..5a8118856d 100644--- a/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.ts+++ b/packages/engine-formula/src/controllers/__tests__/formula.controller.spec.ts@@ -29,6 +29,7 @@ import {import { describe, expect, it, vi } from 'vitest';import { OtherFormulaMarkDirty } from '../../commands/mutations/formula.mutation';import { ActiveDirtyManagerService, IActiveDirtyManagerService } from '../../services/active-dirty-manager.service';+import { FormulaCacheService } from '../../services/formula-cache.service';import { FunctionService, IFunctionService } from '../../services/function.service';import { RegisterOtherFormulaService } from '../../services/register-other-formula.service';import { FormulaController } from '../formula.controller';@@ -47,6 +48,7 @@ function createController(dataSyncPrimaryController?: FormulaDataSyncController)injector.add([ILogService, { useClass: DesktopLogService }]);injector.add([IConfigService, { useClass: ConfigService }]);injector.add([ICommandService, { useClass: CommandService }]);+ injector.add([FormulaCacheService]);injector.add([IFunctionService, { useClass: FunctionService }]);injector.add([IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }]);injector.add([LifecycleService]);diff --git a/packages/engine-formula/src/controllers/calculate.controller.ts b/packages/engine-formula/src/controllers/calculate.controller.tsindex 3a834d1e4c..123b5c4295 100644--- a/packages/engine-formula/src/controllers/calculate.controller.ts+++ b/packages/engine-formula/src/controllers/calculate.controller.ts@@ -29,14 +29,11 @@ import type {IFormulaDependentsAndInRangeResults,} from '../engine/dependency/dependency-tree';import type { IFormulaDirtyData } from '../services/current-data.service';-import type { IAllRuntimeData } from '../services/runtime.service';-import { convertRuntimeToUnitData } from '../basics/runtime';import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';import {SetCellFormulaDependencyCalculationMutation,SetCellFormulaDependencyCalculationResultMutation,SetFormulaCalculationNotificationMutation,- SetFormulaCalculationResultMutation,SetFormulaCalculationStartMutation,SetFormulaCalculationStopMutation,SetFormulaDependencyCalculationMutation,@@ -48,10 +45,8 @@ import {SetQueryFormulaDependencyMutation,SetQueryFormulaDependencyResultMutation,} from '../commands/mutations/set-formula-calculation.mutation';-import { SetImageFormulaDataMutation } from '../commands/mutations/set-image-formula-data.mutation';import { FormulaDataModel } from '../models/formula-data.model';import { ICalculateFormulaService } from '../services/calculate-formula.service';-import { FormulaExecutedStateType } from '../services/runtime.service';export class CalculateController extends Disposable {constructor(@@ -121,15 +116,21 @@ export class CalculateController extends Disposable {isCalculateTreeModel = false,} = formulaDirtyData;- const formulaData = this._formulaDataModel.getFormulaData();+ const snapshotExecutor = this._calculateFormulaService.supportsFormulaDataSnapshot === true+ ? this._calculateFormulaService.executeWithFormulaDataSnapshot+ : undefined;+ // Capture at the same point as the eager list, before any later config reads.+ const snapshot = typeof snapshotExecutor === 'function'+ ? this._calculateFormulaService.prepareFormulaDataSnapshot?.()+ : undefined;+ const formulaData = snapshot ? undefined : this._formulaDataModel.getFormulaData();const arrayFormulaCellData = this._formulaDataModel.getArrayFormulaCellData();// array formula range is used to check whether the newly added array formula conflicts with the existing array formulaconst arrayFormulaRange = this._formulaDataModel.getArrayFormulaRange();- this._calculateFormulaService.execute({+ const config = {dirtyIterationUnits,dirtyReferenceUnits,- formulaData,arrayFormulaCellData,arrayFormulaRange,forceCalculate,@@ -144,7 +145,12 @@ export class CalculateController extends Disposable {isCalculateTreeModel,rowData,externalReferences,- });+ };+ if (snapshot && typeof snapshotExecutor === 'function') {+ snapshotExecutor.call(this._calculateFormulaService, config, snapshot);+ } else {+ this._calculateFormulaService.execute({ ...config, formulaData: formulaData! });+ }}private async _queryFormulaDependencyJson(param: ISetQueryFormulaDependencyMutation) {@@ -156,6 +162,10 @@ export class CalculateController extends Disposable {result = await this._calculateFormulaService.getRangeDependents(unitRanges);}+ if (this._disposed) {+ return;+ }+this._commandService.executeCommand(SetQueryFormulaDependencyResultMutation.id,{@@ -170,6 +180,9 @@ export class CalculateController extends Disposable {private async _queryFormulaDependencyAllJson(param: ISetQueryFormulaDependencyAllMutation) {const { unitRanges } = param;const result: IFormulaDependentsAndInRangeResults = await this._calculateFormulaService.getDependentsAndInRangeFormulas(unitRanges);+ if (this._disposed) {+ return;+ }this._commandService.executeCommand(SetQueryFormulaDependencyAllResultMutation.id,{@@ -183,6 +196,9 @@ export class CalculateController extends Disposable {private async _generateAllDependencyTreeJson() {const result = await this._calculateFormulaService.getAllDependencyJson();+ if (this._disposed) {+ return;+ }this._commandService.executeCommand(SetFormulaDependencyCalculationResultMutation.id,@@ -198,6 +214,9 @@ export class CalculateController extends Disposable {private async _generateCellDependencyTreeJson(param: ISetFormulaDependencyCalculationMutation) {const { unitId, sheetId, row, column } = param;const result = await this._calculateFormulaService.getCellDependencyJson(unitId, sheetId, row, column);+ if (this._disposed) {+ return;+ }this._commandService.executeCommand(SetCellFormulaDependencyCalculationResultMutation.id,@@ -215,6 +234,9 @@ export class CalculateController extends Disposable {const result = await this._calculateFormulaService.executeFormulas(formulas);+ if (this._disposed) {+ return;+ }this._commandService.executeCommand(SetFormulaStringBatchCalculationResultMutation.id,@@ -232,21 +254,8 @@ export class CalculateController extends Disposable {/*** Assignment operation after formula calculation.*/- this._calculateFormulaService.executionCompleteListener$.subscribe((data) => {+ this.disposeWithMe(this._calculateFormulaService.executionCompleteListener$.subscribe((data) => {const functionsExecutedState = data.functionsExecutedState;- switch (functionsExecutedState) {- case FormulaExecutedStateType.NOT_EXECUTED:- this._applyTreeResult(data);- break;- case FormulaExecutedStateType.STOP_EXECUTION:- break;- case FormulaExecutedStateType.SUCCESS:- this._applyResult(data);- break;- case FormulaExecutedStateType.INITIAL:- break;- }-this._commandService.executeCommand(SetFormulaCalculationNotificationMutation.id,{@@ -257,12 +266,12 @@ export class CalculateController extends Disposable {onlyLocal: true,});- });+ }));/*** Assignment operation after formula calculation.*/- this._calculateFormulaService.executionInProgressListener$.subscribe((data) => {+ this.disposeWithMe(this._calculateFormulaService.executionInProgressListener$.subscribe((data) => {this._commandService.executeCommand(SetFormulaCalculationNotificationMutation.id,{@@ -272,86 +281,6 @@ export class CalculateController extends Disposable {onlyLocal: true,});- });- }-- private async _applyTreeResult(data: IAllRuntimeData) {- const { dependencyTreeModelData } = data;- if (dependencyTreeModelData.length > 0) {- this._commandService.executeCommand(- SetFormulaDependencyCalculationResultMutation.id,- {- result: dependencyTreeModelData,- },- {- onlyLocal: true,- }- );- }- }-- private async _applyResult(data: IAllRuntimeData) {- const {- unitData,- sourceFormulaData,- unitOtherData,- arrayFormulaRange,- arrayFormulaCellData,- clearArrayFormulaCellData,- arrayFormulaEmbedded,- imageFormulaData,- } = data;-- if (!unitData) {- this._applyTreeResult(data);- console.error('No sheetData from Formula Engine!');- return;- }-- if (arrayFormulaRange || arrayFormulaEmbedded) {- this._formulaDataModel.clearPreviousArrayFormulaCellData(clearArrayFormulaCellData);- this._formulaDataModel.mergeArrayFormulaCellData(arrayFormulaCellData);- this._formulaDataModel.mergeArrayFormulaRange(arrayFormulaRange);-- this._commandService.executeCommand(- SetArrayFormulaDataMutation.id,- {- arrayFormulaRange: this._formulaDataModel.getArrayFormulaRange(),- arrayFormulaCellData: this._formulaDataModel.getArrayFormulaCellData(),- arrayFormulaEmbedded,- },- {- onlyLocal: true,- fromFormula: true,- }- );- }-- // handle image formula data- if (imageFormulaData && imageFormulaData.length > 0) {- this._commandService.executeCommand(- SetImageFormulaDataMutation.id,- {- imageFormulaData,- },- {- onlyLocal: true,- }- );- }-- this._applyTreeResult(data);-- this._commandService.executeCommand(- SetFormulaCalculationResultMutation.id,- {- unitData: convertRuntimeToUnitData(unitData),- sourceFormulaData,- unitOtherData,- },- {- onlyLocal: true,- }- );+ }));}}diff --git a/packages/engine-formula/src/engine/analysis/__tests__/create-command-test-bed.ts b/packages/engine-formula/src/engine/analysis/__tests__/create-command-test-bed.tsindex 4119bcb552..9771d77bd3 100644--- a/packages/engine-formula/src/engine/analysis/__tests__/create-command-test-bed.ts+++ b/packages/engine-formula/src/engine/analysis/__tests__/create-command-test-bed.ts@@ -15,8 +15,6 @@*/import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';-import type { ISheetData } from '../../../basics/common';-import {CellValueType,ILogService,@@ -30,6 +28,7 @@ import {Univer,UniverInstanceType,} from '@univerjs/core';+import type { ISheetData } from '../../../basics/common';import { FormulaDataModel } from '../../../models/formula-data.model';import { CalculateFormulaService, ICalculateFormulaService } from '../../../services/calculate-formula.service';import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from '../../../services/current-data.service';@@ -43,6 +42,8 @@ import {FeatureCalculationManagerService,IFeatureCalculationManagerService,} from '../../../services/feature-calculation-manager.service';+import { FormulaCacheService } from '../../../services/formula-cache.service';+import { FormulaResultService } from '../../../services/formula-result.service';import { FunctionService, IFunctionService } from '../../../services/function.service';import {HyperlinkEngineFormulaService,@@ -300,8 +301,10 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?}function registerFormulaDependencies(injector: Injector) {+ injector.add([FormulaResultService, { useValue: { applyResult: async () => {}, applyTreeResult: async () => {} } } as never]);injector.add([ICalculateFormulaService, { useClass: CalculateFormulaService }]);injector.add([Lexer]);+ injector.add([FormulaCacheService]);injector.add([LexerTreeBuilder]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);diff --git a/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.tsindex c910529ddc..00a833d558 100644--- a/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts+++ b/packages/engine-formula/src/engine/analysis/__tests__/dependency.spec.ts@@ -15,8 +15,6 @@*/import type { ICellData, Injector } from '@univerjs/core';-import { ObjectMatrix, Styles } from '@univerjs/core';-import { beforeEach, describe, expect, it, vi } from 'vitest';import type {IDirtyUnitDefinedNameMap,IDirtyUnitSheetNameMap,@@ -26,6 +24,8 @@ import type {IUnitSheetIdToNameMap,} from '../../../basics/common';import type { FormulaDependencyTreeVirtual } from '../../dependency/dependency-tree';+import { ObjectMatrix, Styles } from '@univerjs/core';+import { beforeEach, describe, expect, it, vi } from 'vitest';import { ErrorType } from '../../../basics/error-type';import { FUNCTION_NAMES_LOOKUP } from '../../../functions/lookup/function-names';import { Index } from '../../../functions/lookup/index';@@ -42,13 +42,11 @@ import { IFormulaRuntimeService } from '../../../services/runtime.service';import { FormulaDependencyTree } from '../../dependency/dependency-tree';import { IFormulaDependencyGenerator } from '../../dependency/formula-dependency';import { Interpreter } from '../../interpreter/interpreter';-import { FORMULA_AST_CACHE } from '../../utils/generate-ast-node';import { ErrorValueObject } from '../../value-object/base-value-object';import { createCommandTestBed } from './create-command-test-bed';describe('value-dependent reference ranges', () => {it.each(['InputData', 'inputdata'])('rebinds %s after named-range expansion and later source edits', async (name) => {- FORMULA_AST_CACHE.clear();const bed = createCommandTestBed();try {bed.get(IFunctionService).registerExecutors(new Sum('SUM'));@@ -109,7 +107,6 @@ describe('value-dependent reference ranges', () => {['horizontal', false],['horizontal', true],] as const)('updates %s INDEX endpoints after a selector edit (forced: %s)', async (direction, forceSelector) => {- FORMULA_AST_CACHE.clear();const bed = createCommandTestBed();try {bed.get(IFunctionService).registerExecutors(new Index('INDEX'), new Sum('SUM'));diff --git a/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.tsindex 7eefde7b05..e0ff6b03fc 100644--- a/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts+++ b/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts@@ -14,12 +14,12 @@* limitations under the License.*/+import { AbsoluteRefType } from '@univerjs/core';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';import type { ISuperTable } from '../../../basics/common';import type { IFunctionNames } from '../../../basics/function';import type { IDefinedNamesServiceParam } from '../../../services/defined-names.service';import type { LexerNode } from '../lexer-node';-import { AbsoluteRefType } from '@univerjs/core';-import { describe, expect, it } from 'vitest';import { ErrorType } from '../../../basics/error-type';import { FUNCTION_NAMES_LOGICAL } from '../../../functions/logical/function-names';import { FUNCTION_NAMES_LOOKUP } from '../../../functions/lookup/function-names';@@ -28,7 +28,24 @@ import { FUNCTION_NAMES_STATISTICAL } from '../../../functions/statistical/functimport { LexerTreeBuilder } from '../lexer-tree-builder';describe('lexer nodeMaker test', () => {- const lexerTreeBuilder = new LexerTreeBuilder();+ it('parses standalone formulas without dependency injection', () => {+ const builder = new LexerTreeBuilder();+ try {+ const first = builder.treeBuilder('=SUM(1,2)') as LexerNode;+ const second = builder.treeBuilder('=SUM(1,2)') as LexerNode;+ expect(second.serialize()).toEqual(first.serialize());+ expect(second).not.toBe(first);+ expect(builder.sequenceNodesBuilder('SUM(A1:A2)')).toBeDefined();+ } finally {+ builder.dispose();+ }+ });++ let lexerTreeBuilder: LexerTreeBuilder;+ beforeEach(() => {+ lexerTreeBuilder = new LexerTreeBuilder();+ });+ afterEach(() => lexerTreeBuilder.dispose());describe('lexer', () => {it('preserves empty string comparison inside IF parameter', () => {@@ -830,8 +847,6 @@ describe('lexer nodeMaker test', () => {});describe('lexer nodeMaker test', () => {- const lexerTreeBuilder = new LexerTreeBuilder();-describe('getNewFormulaWithPrefix', () => {const hasFunction = (functionToken: IFunctionNames) => {const functionList = [diff --git a/packages/engine-formula/src/engine/analysis/__tests__/lexer.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/lexer.spec.tsindex 43efc5878c..cb23700735 100644--- a/packages/engine-formula/src/engine/analysis/__tests__/lexer.spec.ts+++ b/packages/engine-formula/src/engine/analysis/__tests__/lexer.spec.ts@@ -141,6 +141,35 @@ describe('lexer test', () => {}});+ it('reuses calculation trees without sharing them with direct builder calls', () => {+ const formula = '=SUM(1,2)';+ const builder = get(LexerTreeBuilder);+ const cached = lexer.treeBuilder(formula) as LexerNode;+ expect(lexer.treeBuilder(formula)).toBe(cached);++ const direct = builder.treeBuilder(formula) as LexerNode;+ expect(direct).not.toBe(cached);+ expect(direct.serialize()).toEqual(cached.serialize());+ expect(builder.treeBuilder(formula)).not.toBe(direct);+ expect(lexer.treeBuilder(formula)).toBe(cached);+ });++ it('keeps untransformed trees separate from cached suffix trees', () => {+ const formula = '=1+2*3';+ const cached = lexer.treeBuilder(formula) as LexerNode;+ const direct = lexer.treeBuilder(formula, false) as LexerNode;+ expect(direct.serialize()).not.toEqual(cached.serialize());+ expect(lexer.treeBuilder(formula, false)).not.toBe(direct);+ expect(lexer.treeBuilder(formula)).toBe(cached);+ });++ it.each(['=LET(x,1,x+1)', '=LAMBDA(x,x+1)(2)'])('does not reuse mutable bindings in %s', (formula) => {+ const first = lexer.treeBuilder(formula) as LexerNode;+ const second = lexer.treeBuilder(formula) as LexerNode;+ expect(second).not.toBe(first);+ expect(second.serialize()).toEqual(first.serialize());+ });+describe('lexer definedName', () => {it('simple', () => {definedNamesService.registerDefinedName('test', {diff --git a/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.tsindex 88d949d58a..153b1e1fbc 100644--- a/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts+++ b/packages/engine-formula/src/engine/analysis/__tests__/parser.spec.ts@@ -139,7 +139,10 @@ describe('Test indirect', () => {},});formulaCurrentConfigService.registerSheetNameMap({- [testBed.unitId]: { Sheet1: testBed.sheetId },+ [testBed.unitId]: {+ ...Object.fromEntries(testBed.sheet.getSheets().map((sheet) => [sheet.getName(), sheet.getSheetId()])),+ Sheet1: testBed.sheetId,+ },'sales-source': { Data: 'source-sheet' },'base-source': { Records: 'base-table-sheet' },});@@ -640,6 +643,18 @@ describe('Test indirect', () => {expect((result as BaseValueObject).getValue()).toStrictEqual(4);});+ it('does not reuse a valid range cache for an unresolved sheet, or poison the valid range', () => {+ for (const [formula, expected] of [+ ['=SUM(A1:A2)', 4],+ ['=SUM(Missing!A1:A2)', ErrorType.REF],+ ['=SUM(A1:A2)', 4],+ ] as const) {+ const node = astTreeBuilder.parse(lexer.treeBuilder(formula) as LexerNode)!;+ const result = interpreter.execute(generateExecuteAstNodeData(node));+ expect((result as BaseValueObject).getValue()).toBe(expected);+ }+ });+it('Reference column', async () => {const lexerNode = lexer.treeBuilder('=sum(A:A)');diff --git a/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts b/packages/engine-formula/src/engine/analysis/lexer-tree-builder.tsindex 606ac083b2..53cf28cd11 100644--- a/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts+++ b/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts@@ -15,7 +15,15 @@*/import type { IRange, Nullable } from '@univerjs/core';-import { AbsoluteRefType, Disposable, isValidRange, MAX_COLUMN_COUNT, MAX_ROW_COUNT, moveRangeByOffset, Tools } from '@univerjs/core';+import {+ AbsoluteRefType,+ Disposable,+ isValidRange,+ MAX_COLUMN_COUNT,+ MAX_ROW_COUNT,+ moveRangeByOffset,+ Tools,+} from '@univerjs/core';import type { IDirtyUnitDefinedNameMap, IExprTreeNode, ISuperTable } from '../../basics/common';import type { IFunctionNames } from '../../basics/function';import type { IDefinedNamesServiceParam } from '../../services/defined-names.service';@@ -81,8 +89,6 @@ enum NewExcelFunctionNodeType {const FORMULA_CACHE_LRU_COUNT = 2000;-export const FormulaLexerNodeCache = new FormulaAstLRU<LexerNode>(FORMULA_CACHE_LRU_COUNT);-export const FormulaSequenceNodeCache = new FormulaAstLRU<Array<string | ISequenceNode>>(FORMULA_CACHE_LRU_COUNT);interface IInjectDefinedNameParam {@@ -144,10 +150,6 @@ export class LexerTreeBuilder extends Disposable {this._resetTemp();this._currentLexerNode.dispose();-- FormulaLexerNodeCache.clear();-- FormulaSequenceNodeCache.clear();}getUpLevel() {@@ -714,21 +716,6 @@ export class LexerTreeBuilder extends Disposable {transformSuffix = true,injectDefinedNameParam?: IInjectDefinedNameParam) {- // Parsing LET/LAMBDA rewrites the lexer tree with runtime parameter bindings.- // Reusing that mutated tree would bind the next AST to the previous AST's nodes.- const isCacheable = !/\b(?:LET|LAMBDA)\s*\(/iu.test(formulaString);- const cacheKey = injectDefinedNameParam == null- ? formulaString- : `${injectDefinedNameParam.unitId ?? ''}\0${injectDefinedNameParam.sheetId ?? ''}\0${injectDefinedNameParam.refOffsetX}\0${injectDefinedNameParam.refOffsetY}\0${formulaString}`;- if (transformSuffix === true && isCacheable) {- const lexerNode = FormulaLexerNodeCache.get(cacheKey);- const simpleCheckDefinedNameResult = injectDefinedNameParam- && this._simpleCheckDefinedName(formulaString, injectDefinedNameParam, lexerNode);- if (lexerNode && !simpleCheckDefinedNameResult) {- return lexerNode;- }- }-this._resetCurrentLexerNode();this._currentLexerNode.setToken(DEFAULT_TOKEN_TYPE_ROOT);const sequenceArray: ISequenceArray[] = [];@@ -775,9 +762,6 @@ export class LexerTreeBuilder extends Disposable {if (!isValid) {return ErrorType.VALUE;}- if (isCacheable) {- FormulaLexerNodeCache.set(cacheKey, this._currentLexerNode);- }}if (currentHasDefinedName) {@@ -945,27 +929,6 @@ export class LexerTreeBuilder extends Disposable {return this._handleDefinedName(sequenceArray, param);}- private _simpleCheckDefinedName(- formulaString: string,- injectDefinedNameParam: IInjectDefinedNameParam,- lexerNode?: LexerNode- ) {- const { getDirtyDefinedNameMap, unitId } = injectDefinedNameParam;- const definedNameMap = getDirtyDefinedNameMap();- const executeUnitId = unitId;- if (executeUnitId != null && definedNameMap[executeUnitId] != null) {- const names = Object.keys(definedNameMap[executeUnitId]!);- for (let i = 0, len = names.length; i < len; i++) {- const name = names[i];- if (formulaString.indexOf(name) > -1 || lexerNode?.getDefinedNames().includes(name)) {- return true;- }- }- }-- return false;- }-private _checkDefinedNameDirty(token: string, injectDefinedNameParam: IInjectDefinedNameParam) {const { getDirtyDefinedNameMap, unitId } = injectDefinedNameParam;const definedNameMap = getDirtyDefinedNameMap();diff --git a/packages/engine-formula/src/engine/analysis/lexer.ts b/packages/engine-formula/src/engine/analysis/lexer.tsindex 825b4aea00..67c070add8 100644--- a/packages/engine-formula/src/engine/analysis/lexer.ts+++ b/packages/engine-formula/src/engine/analysis/lexer.ts@@ -18,7 +18,9 @@ import type { Nullable } from '@univerjs/core';import { Disposable, Inject } from '@univerjs/core';import { IFormulaCurrentConfigService } from '../../services/current-data.service';import { IDefinedNamesService } from '../../services/defined-names.service';+import { FormulaCacheService } from '../../services/formula-cache.service';import { IFunctionService } from '../../services/function.service';+import { LexerNode } from './lexer-node';import { LexerTreeBuilder } from './lexer-tree-builder';export class Lexer extends Disposable {@@ -26,25 +28,55 @@ export class Lexer extends Disposable {@IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService,@Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,@IFormulaCurrentConfigService private readonly _formulaCurrentConfigService: IFormulaCurrentConfigService,- @IFunctionService private readonly _functionService: IFunctionService+ @IFunctionService private readonly _functionService: IFunctionService,+ @Inject(FormulaCacheService) private readonly _cacheService: FormulaCacheService) {super();}treeBuilder(formulaString: string, transformSuffix = true, unitId?: Nullable<string>, refOffsetX = 0, refOffsetY = 0) {- if (this._definedNamesService.getAllDefinedNamesIsEmpty()) {- return this._lexerTreeBuilder.treeBuilder(formulaString, transformSuffix);+ const injectDefinedNameParam = this._definedNamesService.getAllDefinedNamesIsEmpty()+ ? undefined+ : {+ unitId: unitId ?? this._formulaCurrentConfigService.getExecuteUnitId(),+ sheetId: this._formulaCurrentConfigService.getExecuteSubUnitId(),+ refOffsetX,+ refOffsetY,+ hasFunction: this._functionService.hasExecutor.bind(this._functionService),+ getValueByName: this._definedNamesService.getValueByName.bind(this._definedNamesService),+ getDirtyDefinedNameMap: this._formulaCurrentConfigService.getDirtyDefinedNameMap.bind(this._formulaCurrentConfigService),+ getSheetName: this._formulaCurrentConfigService.getSheetName.bind(this._formulaCurrentConfigService),+ };+ // LET/LAMBDA trees are rewritten with AST-specific runtime parameter bindings.+ const isCacheable = transformSuffix === true && !/\b(?:LET|LAMBDA)\s*\(/iu.test(formulaString);+ const cacheKey = injectDefinedNameParam == null+ ? formulaString+ : `${injectDefinedNameParam.unitId ?? ''}\0${injectDefinedNameParam.sheetId ?? ''}\0${refOffsetX}\0${refOffsetY}\0${formulaString}`;+ if (isCacheable) {+ const lexerNode = this._cacheService.getLexerTree(cacheKey);+ if (lexerNode && (!injectDefinedNameParam || !this._isDefinedNameDirty(formulaString, injectDefinedNameParam.unitId, lexerNode))) {+ return lexerNode;+ }}- return this._lexerTreeBuilder.treeBuilder(formulaString, transformSuffix, {- unitId: unitId ?? this._formulaCurrentConfigService.getExecuteUnitId(),- sheetId: this._formulaCurrentConfigService.getExecuteSubUnitId(),- refOffsetX,- refOffsetY,- hasFunction: this._functionService.hasExecutor.bind(this._functionService),- getValueByName: this._definedNamesService.getValueByName.bind(this._definedNamesService),- getDirtyDefinedNameMap: this._formulaCurrentConfigService.getDirtyDefinedNameMap.bind(this._formulaCurrentConfigService),- getSheetName: this._formulaCurrentConfigService.getSheetName.bind(this._formulaCurrentConfigService),- });+ const lexerNode = this._lexerTreeBuilder.treeBuilder(formulaString, transformSuffix, injectDefinedNameParam);+ if (isCacheable && lexerNode instanceof LexerNode) {+ this._cacheService.setLexerTree(cacheKey, lexerNode, injectDefinedNameParam?.unitId ?? undefined);+ }+ return lexerNode;+ }++ private _isDefinedNameDirty(formulaString: string, unitId: Nullable<string>, lexerNode: LexerNode): boolean {+ const definedNameMap = this._formulaCurrentConfigService.getDirtyDefinedNameMap();+ if (unitId != null && definedNameMap[unitId] != null) {+ const names = Object.keys(definedNameMap[unitId]!);+ for (let i = 0, len = names.length; i < len; i++) {+ const name = names[i];+ if (formulaString.indexOf(name) > -1 || lexerNode.getDefinedNames().includes(name)) {+ return true;+ }+ }+ }+ return false;}}diff --git a/packages/engine-formula/src/engine/analysis/parser.ts b/packages/engine-formula/src/engine/analysis/parser.tsindex 882622f81b..d7915fd4d2 100644--- a/packages/engine-formula/src/engine/analysis/parser.ts+++ b/packages/engine-formula/src/engine/analysis/parser.ts@@ -26,6 +26,7 @@ import {DEFAULT_TOKEN_TYPE_ROOT,FORCED_RECALCULATION_FUNCTION_NAME,} from '../../basics/token-type';+import { FormulaCacheService } from '../../services/formula-cache.service';import { IFormulaRuntimeService } from '../../services/runtime.service';import { AstRootNode, AstRootNodeFactory } from '../ast-node/ast-root-node';import { BaseAstNode, ErrorNode } from '../ast-node/base-ast-node';@@ -49,6 +50,7 @@ export class AstTreeBuilder extends Disposable {private _astNodeFactoryList: AstRootNodeFactory[] = [];constructor(+ @Inject(FormulaCacheService) readonly cacheService: FormulaCacheService,@IFormulaRuntimeService private readonly _runtimeService: IFormulaRuntimeService,@Inject(AstRootNodeFactory) private readonly _astRootNodeFactory: AstRootNodeFactory,@Inject(FunctionNodeFactory) private readonly _functionNodeFactory: FunctionNodeFactory,diff --git a/packages/engine-formula/src/engine/ast-node/__tests__/reference-node.spec.ts b/packages/engine-formula/src/engine/ast-node/__tests__/reference-node.spec.tsindex 8197d25f1b..da97eab694 100644--- a/packages/engine-formula/src/engine/ast-node/__tests__/reference-node.spec.ts+++ b/packages/engine-formula/src/engine/ast-node/__tests__/reference-node.spec.ts@@ -14,11 +14,13 @@* limitations under the License.*/-import type { IFormulaCurrentConfigService } from '../../../services/current-data.service';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import type { IFormulaUnitReferenceResolver } from '../../../services/unit-reference-resolver.service';-import type { BaseValueObject } from '../../value-object/base-value-object';-import { describe, expect, it, vi } from 'vitest';import { ErrorType } from '../../../basics/error-type';+import { createFunctionTestBed } from '../../../functions/__tests__/create-function-test-bed';+import { IFormulaCurrentConfigService } from '../../../services/current-data.service';+import { IFormulaRuntimeService } from '../../../services/runtime.service';+import { ISuperTableService } from '../../../services/super-table.service';import { ReferenceObjectType } from '../../utils/value-object';import { ErrorValueObject } from '../../value-object/base-value-object';import { BaseAstNode } from '../base-ast-node';@@ -26,26 +28,31 @@ import { ReferenceNode, ReferenceNodeFactory } from '../reference-node';import { UnionNode } from '../union-node';describe('ReferenceNode external range loading', () => {+ let testBed: ReturnType<typeof createFunctionTestBed>;++ beforeEach(() => {+ testBed = createFunctionTestBed();+ testBed.get(IFormulaCurrentConfigService).load({+ allUnitData: { [testBed.unitId]: testBed.sheetData },+ formulaData: {},+ arrayFormulaCellData: {},+ arrayFormulaRange: {},+ forceCalculate: false,+ dirtyRanges: [],+ dirtyNameMap: {},+ dirtyDefinedNameMap: {},+ dirtyUnitFeatureMap: {},+ dirtyUnitOtherFormulaMap: {},+ });+ testBed.get(IFormulaRuntimeService).setCurrent(0, 0, 100, 100, testBed.sheetId, testBed.unitId);+ });++ afterEach(() => {+ testBed.univer.dispose();+ });+it('loads the full colon range from the qualified left reference', async () => {const load = vi.fn(async () => undefined);- const currentConfig = {- getSheetNameMap: () => ({}),- getUnitData: () => ({}),- getArrayFormulaCellData: () => ({}),- getArrayFormulaRange: () => ({}),- getUnitStylesData: () => ({}),- };- const runtime = {- markExternalReferenceUnavailable: vi.fn(),- currentUnitId: 'host',- currentSubUnitId: 'host-sheet',- currentRow: 0,- currentColumn: 0,- getUnitData: () => ({}),- getRuntimeArrayFormulaCellData: () => ({}),- getUnitArrayFormula: () => ({}),- getRuntimeFeatureCellData: () => ({}),- };const resolver = {resolve: () => ({unitId: 'source',@@ -56,27 +63,19 @@ describe('ReferenceNode external range loading', () => {},}),} satisfies IFormulaUnitReferenceResolver;- const superTableService = {- getTableMap: () => null,- getTableOptionMap: () => new Map(),- };+ const currentConfig = testBed.get(IFormulaCurrentConfigService);const left = new ReferenceNode(currentConfig,- runtime,+ testBed.get(IFormulaRuntimeService),"'[Sales]Data'!A1",ReferenceObjectType.CELL,resolver,- superTableService,+ testBed.get(ISuperTableService),{ load },true);const right = new BaseAstNode('B2');- const union = new UnionNode(':', {- getSheetsInfo: () => ({- sheetNameMap: {},- sheetOrder: [],- }),- } satisfies Pick<IFormulaCurrentConfigService, 'getSheetsInfo'>);+ const union = new UnionNode(':', currentConfig);left.setParent(union);right.setParent(union);@@ -88,72 +87,17 @@ describe('ReferenceNode external range loading', () => {});it('returns REF for a missing local structured table reference', () => {- const currentConfig = {- getSheetNameMap: () => ({}),- getUnitData: () => ({}),- getArrayFormulaCellData: () => ({}),- getArrayFormulaRange: () => ({}),- getUnitStylesData: () => ({}),- };- const runtime = {- markExternalReferenceUnavailable: vi.fn(),- currentUnitId: 'host',- currentSubUnitId: 'host-sheet',- currentRow: 0,- currentColumn: 0,- getUnitData: () => ({}),- getRuntimeArrayFormulaCellData: () => ({}),- getUnitArrayFormula: () => ({}),- getRuntimeFeatureCellData: () => ({}),- };- const factory = new ReferenceNodeFactory(- currentConfig as never,- runtime as never,- {} as never,- {- getTableMap: () => null,- getTableOptionMap: () => new Map(),- } as never,- { resolve: () => ({ unitId: 'host' }) } as IFormulaUnitReferenceResolver,- { load: vi.fn() } as never- );+ const factory = testBed.get(ReferenceNodeFactory);const node = factory.checkAndCreateNodeType('Tout[Quantity]');expect(node).toBeInstanceOf(ReferenceNode);node?.execute();- expect((node?.getValue() as BaseValueObject).getValue()).toBe(ErrorType.REF);+ const value = node?.getValue();+ expect(value instanceof ErrorValueObject && value.getValue()).toBe(ErrorType.REF);});it('keeps ordinary cell references out of the structured-table path', () => {- const currentConfig = {- getSheetNameMap: () => ({}),- getUnitData: () => ({}),- getArrayFormulaCellData: () => ({}),- getArrayFormulaRange: () => ({}),- getUnitStylesData: () => ({}),- };- const runtime = {- markExternalReferenceUnavailable: vi.fn(),- currentUnitId: 'host',- currentSubUnitId: 'host-sheet',- currentRow: 0,- currentColumn: 0,- getUnitData: () => ({}),- getRuntimeArrayFormulaCellData: () => ({}),- getUnitArrayFormula: () => ({}),- getRuntimeFeatureCellData: () => ({}),- };- const factory = new ReferenceNodeFactory(- currentConfig as never,- runtime as never,- {} as never,- {- getTableMap: () => null,- getTableOptionMap: () => new Map(),- } as never,- { resolve: () => ({ unitId: 'host' }) } as IFormulaUnitReferenceResolver,- { load: vi.fn() } as never- );+ const factory = testBed.get(ReferenceNodeFactory);const node = factory.checkAndCreateNodeType('G2');expect(node).toBeInstanceOf(ReferenceNode);diff --git a/packages/engine-formula/src/engine/ast-node/__tests__/union-node.spec.ts b/packages/engine-formula/src/engine/ast-node/__tests__/union-node.spec.tsindex 0eb2f52f50..1c02082e9b 100644--- a/packages/engine-formula/src/engine/ast-node/__tests__/union-node.spec.ts+++ b/packages/engine-formula/src/engine/ast-node/__tests__/union-node.spec.ts@@ -15,11 +15,11 @@*/import type { IUnitRange, IWorkbookData } from '@univerjs/core';-import type { ISheetData } from '../../../basics/common';-import type { IFormulaDependencyTree } from '../../dependency/dependency-tree';-import { CellValueType, LocaleType } from '@univerjs/core';import { beforeEach, describe, expect, it } from 'vitest';+import type { ISheetData } from '../../../basics/common';+import type { IFormulaDependencyTree } from '../../dependency/dependency-tree';+import { ErrorType } from '../../../basics/error-type';import { createFunctionTestBed } from '../../../functions/__tests__/create-function-test-bed';import { FUNCTION_NAMES_LOGICAL } from '../../../functions/logical/function-names';import { Let } from '../../../functions/logical/let';@@ -213,13 +213,32 @@ describe('three-dimensional sheet reference', () => {it('sums the same cell from every sheet in the inclusive range', () => {expect(calculate('=SUM(Jan:Mar!B2)')).toBe(111);- expect(calculate("=SUM('Jan':'Mar'!B2)")).toBe(111);+ expect(calculate("=SUM('Jan:Mar'!B2)")).toBe(111);});it('sums every cell from every sheet instead of only each area first cell', () => {expect(calculate('=SUM(Jan:Mar!B2:C3)')).toBe(1110);});+ it('accepts a quoted sheet span and rejects individually quoted endpoints', () => {+ expect(calculate("=SUM('Jan:Mar'!B2)")).toBe(111);+ expect(calculate("=SUM('Jan:Mar'!B2:C3)")).toBe(1110);+ expect(calculate("=SUM('Jan':'Mar'!B2)")).toBe(ErrorType.NAME);+ expect(calculate("=SUM(Jan:'Mar'!B2)")).toBe(ErrorType.NAME);+ expect(calculate("=SUM(Jan:'Mar'!B2:C3)")).toBe(ErrorType.NAME);+ expect(calculate("=SUM('Jan:Feb:Mar'!B2)")).toBe(ErrorType.NAME);+ });++ it('preserves ordinary ranges with quoted worksheet qualifiers', () => {+ expect(calculate("=SUM(Jan!B2:'Jan'!C3)")).toBe(10);+ expect(calculate("=SUM('Jan'!B2:'Jan'!C3)")).toBe(10);+ });++ it('returns the internal name error when either quoted sheet span endpoint is missing', () => {+ expect(calculate("=SUM('Missing:Mar'!B2)")).toBe(ErrorType.NAME);+ expect(calculate("=SUM('Jan:Missing'!B2:C3)")).toBe(ErrorType.NAME);+ });+it('calculates the combine-data sample formula with all 12 source rows', () => {expect(calculate('=LET(data,VSTACK(Sheet1:Sheet3!B5:E16),FILTER(data,CHOOSECOLS(data,1)<>""))')).toEqual([[45148, 'Red', 1, 9],diff --git a/packages/engine-formula/src/engine/ast-node/function-node.ts b/packages/engine-formula/src/engine/ast-node/function-node.tsindex 0c5b3d5316..df13f9b247 100644--- a/packages/engine-formula/src/engine/ast-node/function-node.ts+++ b/packages/engine-formula/src/engine/ast-node/function-node.ts@@ -28,9 +28,9 @@ import type { BaseValueObject } from '../value-object/base-value-object';import type { FormulaFunctionResultValueType } from '../value-object/primitive-object';import { AstNodePromiseType } from '../../basics/common';import { ErrorType } from '../../basics/error-type';+import { normalizeFunctionToken } from '../../basics/function';import { matchToken } from '../../basics/token';import { COLUMN_LIKE_FUNCTION_NAMES } from '../../functions/column-like-functions';-import { FUNCTION_NAMES_TEXT } from '../../functions/text/function-names';import { FormulaDataModel } from '../../models/formula-data.model';import { IFormulaCurrentConfigService } from '../../services/current-data.service';import { IDefinedNamesService } from '../../services/defined-names.service';@@ -431,6 +431,7 @@ export class FunctionNode extends BaseAstNode {referenceObject.setArrayFormulaRange(this._currentConfigService.getArrayFormulaRange());referenceObject.setRuntimeData(this._runtimeService.getUnitData());+ referenceObject.setCalculationCache(this._runtimeService.getCalculationCache?.());referenceObject.setRuntimeArrayFormulaCellData(this._runtimeService.getRuntimeArrayFormulaCellData());@@ -554,17 +555,3 @@ export class FunctionNodeFactory extends BaseAstNodeFactory {return param.getParent()?.getParent()?.getToken() === matchToken.COLON;}}--function normalizeFunctionToken(token: string): string {- if (token === 'REGEXTEST' || token === '_XLFN.REGEXTEST') {- return FUNCTION_NAMES_TEXT.REGEXMATCH;- }-- for (const prefix of ['_XLFN.', '_XLWS.', '_XLETA.']) {- if (token.startsWith(prefix)) {- return token.slice(prefix.length);- }- }-- return token;-}diff --git a/packages/engine-formula/src/engine/ast-node/reference-node.ts b/packages/engine-formula/src/engine/ast-node/reference-node.tsindex aaecd43d84..58aa2d3743 100644--- a/packages/engine-formula/src/engine/ast-node/reference-node.ts+++ b/packages/engine-formula/src/engine/ast-node/reference-node.ts@@ -38,6 +38,7 @@ import { LexerNode } from '../analysis/lexer-node';import { TableReferenceObject } from '../reference-object/table-reference-object';import { prefixHandler } from '../utils/prefix-handler';import { splitTableStructuredRef } from '../utils/reference';+import { expandSheetSpan } from '../utils/three-dimensional-reference';import { getReferenceObjectFromCache, ReferenceObjectType } from '../utils/value-object';import { ErrorValueObject } from '../value-object/base-value-object';import { BaseAstNode } from './base-ast-node';@@ -50,40 +51,17 @@ interface ITableReferenceDescriptor {columnStruct: string | undefined;}-type ReferenceNodeCurrentConfigService = Pick<- IFormulaCurrentConfigService,- 'getArrayFormulaCellData' | 'getArrayFormulaRange' | 'getSheetNameMap' | 'getUnitData' | 'getUnitStylesData'->;--type ReferenceNodeRuntimeService = Pick<- IFormulaRuntimeService,- | 'markExternalReferenceUnavailable'- | 'currentColumn'- | 'currentRow'- | 'currentSubUnitId'- | 'currentUnitId'- | 'getRuntimeArrayFormulaCellData'- | 'getRuntimeFeatureCellData'- | 'getUnitArrayFormula'- | 'getUnitData'->;--type ReferenceNodeSuperTableService = Pick<- ISuperTableService,- 'getTableMap' | 'getTableOptionMap'->;-export class ReferenceNode extends BaseAstNode {private _refOffsetX = 0;private _refOffsetY = 0;constructor(- private _currentConfigService: ReferenceNodeCurrentConfigService,- private _runtimeService: ReferenceNodeRuntimeService,+ private _currentConfigService: IFormulaCurrentConfigService,+ private _runtimeService: IFormulaRuntimeService,operatorString: string,private _referenceObjectType: ReferenceObjectType,private _unitReferenceResolver: IFormulaUnitReferenceResolver,- private _superTableService: ReferenceNodeSuperTableService,+ private _superTableService: ISuperTableService,private _externalReferenceDataLoader: IFormulaExternalReferenceDataLoader,private _isPrepareMerge: boolean = false,private _tableReference?: ITableReferenceDescriptor@@ -152,6 +130,14 @@ export class ReferenceNode extends BaseAstNode {this._configureReferenceObject(referenceObject, currentConfigService, runtimeService);+ if (!this._isPrepareMerge) {+ const sheetRange = expandSheetSpan(referenceObject, currentConfigService);+ if (sheetRange) {+ this.setValue(sheetRange);+ return;+ }+ }+if (!this._isPrepareMerge && referenceObject.isExceedRange()) {this.setValue(ErrorValueObject.create(ErrorType.NAME));} else {@@ -224,8 +210,8 @@ export class ReferenceNode extends BaseAstNode {private _configureReferenceObject(referenceObject: BaseReferenceObject,- currentConfigService: ReferenceNodeCurrentConfigService,- runtimeService: ReferenceNodeRuntimeService+ currentConfigService: IFormulaCurrentConfigService,+ runtimeService: IFormulaRuntimeService): void {referenceObject.setDefaultUnitId(runtimeService.currentUnitId);referenceObject.setDefaultSheetId(runtimeService.currentSubUnitId);@@ -234,6 +220,7 @@ export class ReferenceNode extends BaseAstNode {referenceObject.setArrayFormulaCellData(currentConfigService.getArrayFormulaCellData());referenceObject.setArrayFormulaRange(currentConfigService.getArrayFormulaRange());referenceObject.setRuntimeData(runtimeService.getUnitData());+ referenceObject.setCalculationCache(runtimeService.getCalculationCache?.());referenceObject.setUnitStylesData(currentConfigService.getUnitStylesData());referenceObject.setRuntimeArrayFormulaCellData(runtimeService.getRuntimeArrayFormulaCellData());referenceObject.setRuntimeArrayFormulaRange(runtimeService.getUnitArrayFormula());diff --git a/packages/engine-formula/src/engine/ast-node/union-node.ts b/packages/engine-formula/src/engine/ast-node/union-node.tsindex 055edabf93..a33d77df03 100644--- a/packages/engine-formula/src/engine/ast-node/union-node.ts+++ b/packages/engine-formula/src/engine/ast-node/union-node.ts@@ -15,14 +15,14 @@*/import type { FunctionVariantType } from '../reference-object/base-reference-object';+import type { MultiAreaReferenceObject } from '../reference-object/multi-area-reference-object';import { ErrorType } from '../../basics/error-type';import { matchToken } from '../../basics/token';import { IFormulaCurrentConfigService } from '../../services/current-data.service';import { IFunctionService } from '../../services/function.service';import { LexerNode } from '../analysis/lexer-node';import { BaseReferenceObject } from '../reference-object/base-reference-object';-import { MultiAreaArrayMode, MultiAreaReferenceObject } from '../reference-object/multi-area-reference-object';-import { RangeReferenceObject } from '../reference-object/range-reference-object';+import { createThreeDimensionalReference, expandSheetSpan } from '../utils/three-dimensional-reference';import { getRangeReferenceObjectFromCache } from '../utils/value-object';import { ErrorValueObject } from '../value-object/base-value-object';import { BaseAstNode } from './base-ast-node';@@ -34,7 +34,7 @@ import { NODE_ORDER_MAP, NodeType } from './node-type';export class UnionNode extends BaseAstNode {constructor(operatorString: string,- private readonly _currentConfigService: Pick<IFormulaCurrentConfigService, 'getSheetsInfo'>+ private readonly _currentConfigService: IFormulaCurrentConfigService) {super(operatorString);}@@ -58,87 +58,49 @@ export class UnionNode extends BaseAstNode {let result: FunctionVariantType;if (this.getToken() === matchToken.COLON) {- result = this._createThreeDimensionalReference(leftChild.getToken(), rightNode)+ result = this._createThreeDimensionalReference(leftChild.getToken(), rightChild)?? this._unionFunction(leftNode, rightNode);} else {result = ErrorValueObject.create(ErrorType.NAME);}+ if (result instanceof BaseReferenceObject) {+ result = expandSheetSpan(result, this._currentConfigService) ?? result;+ }this.setValue(result);}private _createThreeDimensionalReference(firstSheetToken: string,- rightNode: FunctionVariantType- ): MultiAreaReferenceObject | undefined {+ rightChild: BaseAstNode+ ): MultiAreaReferenceObject | ErrorValueObject | undefined {+ const rightNode = rightChild.getValue();if (!(rightNode instanceof BaseReferenceObject)) {return;}const source = rightNode;- const firstSheetName = this._normalizeSheetName(firstSheetToken);- const lastSheetName = this._normalizeSheetName(source.getForcedSheetName());- if (!firstSheetName || !lastSheetName) {- return;+ // Merged rectangular references lose their tokens; inspect the original endpoint.+ let lastSheetNode = rightChild;+ while (lastSheetNode.getToken() === matchToken.COLON) {+ lastSheetNode = lastSheetNode.getChildren()[0];}-- const { sheetOrder, sheetNameMap } = this._currentConfigService.getSheetsInfo(source.getUnitId());- const sheetIdsByName = new Map(- Object.entries(sheetNameMap).map(([sheetId, sheetName]) => [sheetName.toLocaleLowerCase(), sheetId])- );- const firstSheetId = sheetIdsByName.get(firstSheetName.toLocaleLowerCase());- const lastSheetId = sheetIdsByName.get(lastSheetName.toLocaleLowerCase());- const firstIndex = firstSheetId == null ? -1 : sheetOrder.indexOf(firstSheetId);- const lastIndex = lastSheetId == null ? -1 : sheetOrder.indexOf(lastSheetId);- if (firstIndex < 0 || lastIndex < 0) {- return;+ if (firstSheetToken.trim().startsWith("'") && firstSheetToken.trim().endsWith("'")) {+ return ErrorValueObject.create(ErrorType.NAME);}-- const startIndex = Math.min(firstIndex, lastIndex);- const endIndex = Math.max(firstIndex, lastIndex);- const areas = sheetOrder.slice(startIndex, endIndex + 1).map((sheetId) => {- const reference = new RangeReferenceObject(source.getRangeData(), sheetId, source.getUnitId());- this._copyReferenceContext(source, reference);- reference.setForcedSheetIdDirect(sheetId);- reference.setForcedSheetName(sheetNameMap[sheetId] ?? '');- return [reference];- });-- return new MultiAreaReferenceObject(- `${firstSheetToken}:${source.getToken()}`,- areas,- MultiAreaArrayMode.STACK_AREAS- );- }-- private _normalizeSheetName(token: string): string {- const trimmed = token.trim();- if (trimmed.startsWith("'") && trimmed.endsWith("'")) {- return trimmed.slice(1, -1).replace(/''/g, "'");+ const firstSheetName = firstSheetToken.trim();+ const lastSheetName = source.getForcedSheetName();+ if (!firstSheetName || !lastSheetName) {+ return;}- return trimmed;- }- private _copyReferenceContext(source: BaseReferenceObject, target: BaseReferenceObject): void {- target.setDefaultUnitId(source.getDefaultUnitId());- target.setDefaultSheetId(source.getDefaultSheetId());- target.setUnitData(source.getUnitData());- target.setUnitStylesData(source.getUnitStylesData());- target.setFilteredOutRows(source.getFilteredOutRows());- target.setRuntimeData(source.getRuntimeData());- target.setArrayFormulaCellData(source.getArrayFormulaCellData());- target.setArrayFormulaRange(source.getArrayFormulaRange());- target.setRuntimeArrayFormulaCellData(source.getRuntimeArrayFormulaCellData());- target.setRuntimeArrayFormulaRange(source.getRuntimeArrayFormulaRange());- target.setRuntimeFeatureCellData(source.getRuntimeFeatureCellData());-- const currentRow = source.getCurrentRow();- const currentColumn = source.getCurrentColumn();- if (currentRow != null && currentColumn != null) {- target.setCurrentRowAndColumn(currentRow, currentColumn);+ const sheetsInfo = this._currentConfigService.getSheetsInfo(source.getUnitId());+ if (+ lastSheetNode.getToken().trim().startsWith("'") &&+ Object.values(sheetsInfo.sheetNameMap).some((name) => name.toLocaleLowerCase() === firstSheetName.toLocaleLowerCase())+ ) {+ return ErrorValueObject.create(ErrorType.NAME);}-- const { x, y } = source.getRefOffset();- target.setRefOffset(x, y);+ return createThreeDimensionalReference(firstSheetName, lastSheetName, source, sheetsInfo);}private _unionFunction(diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.tsindex b98e44c883..a088d9e1f4 100644--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts@@ -69,7 +69,7 @@ import { AstTreeBuilder } from '../analysis/parser';import { NodeType } from '../ast-node/node-type';import { Interpreter } from '../interpreter/interpreter';import { BaseReferenceObject } from '../reference-object/base-reference-object';-import { FORMULA_AST_CACHE, generateAstNode, includeDefinedName } from '../utils/generate-ast-node';+import { generateAstNode, includeDefinedName } from '../utils/generate-ast-node';import { getDependencyGroups } from './dependency-groups';import {FormulaDependencyTree,@@ -142,7 +142,6 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDethis._updateRangeFlattenCache.clear();this._dependencyRTreeCacheForAddressFunction.clear();- FORMULA_AST_CACHE.clear();}private _initUnitDispose() {@@ -154,11 +153,7 @@ export class FormulaDependencyGenerator extends Disposable implements IFormulaDe}private _disposeByUnitId(unitId: string) {- FORMULA_AST_CACHE.forEach((_, key) => {- if (key.startsWith(unitId)) {- FORMULA_AST_CACHE.delete(key);- }- });+ this._astTreeBuilder.cacheService.clearUnit(unitId);}async generate(isCalculateTreeModel = false) {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.tsindex 2e99d9c694..8989948947 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@@ -21,6 +21,20 @@ import { CellReferenceObject } from '../cell-reference-object';import { RangeReferenceObject } from '../range-reference-object';describe('CellReferenceObject', () => {+ it('resolves sheet names without case sensitivity while preserving exact identities', () => {+ const reference = new CellReferenceObject('JAN!A1');+ reference.setDefaultUnitId('book');+ reference.setDefaultSheetId('summary');+ reference.setForcedSheetId({ book: { Jan: 'sheet-jan' } });+ expect(reference.getSheetId()).toBe('sheet-jan');++ reference.setForcedSheetId({ book: { Jan: 'sheet-jan', JAN: 'exact-sheet' } });+ expect(reference.getSheetId()).toBe('exact-sheet');++ reference.setForcedSheetId({ book: { Other: 'sheet-other' } });+ expect(reference.getForcedSheetId()).toBeUndefined();+ });+it('distinguishes forced error-looking text from a calculated error', () => {const reference = new CellReferenceObject('A1');const text = reference.getCellValueObject({ v: '#REF!', t: CellValueType.FORCE_STRING });diff --git a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts b/packages/engine-formula/src/engine/reference-object/base-reference-object.tsindex 9aff4efad2..6248f34d4a 100644--- a/packages/engine-formula/src/engine/reference-object/base-reference-object.ts+++ b/packages/engine-formula/src/engine/reference-object/base-reference-object.ts@@ -15,6 +15,15 @@*/import type { ICellData, IRange, IUnitRange, Nullable } from '@univerjs/core';+import type {+ IArrayFormulaRangeType,+ IRuntimeUnitDataType,+ IUnitData,+ IUnitSheetNameMap,+ IUnitStylesData,+} from '../../basics/common';+import type { FormulaCalculationCache } from '../../services/formula-cache.service';+import type { BaseValueObject, IArrayValueObject } from '../value-object/base-value-object';import {CellValueType,DateSystem,@@ -25,9 +34,6 @@ import {moveRangeByOffset,ObjectMatrix,} from '@univerjs/core';-import type { IArrayFormulaRangeType, IRuntimeUnitDataType, IUnitData, IUnitSheetNameMap, IUnitStylesData } from '../../basics/common';-import type { BaseValueObject, IArrayValueObject } from '../value-object/base-value-object';-import { FormulaAstLRU } from '../../basics/cache-lru';import { ERROR_TYPE_SET, ErrorType } from '../../basics/error-type';import { ObjectClassType } from '../../basics/object-class-type';import { getCellValue } from '../utils/cell';@@ -46,10 +52,17 @@ export type NodeValueType = BaseValueObject | BaseReferenceObject | AsyncObjectexport type FunctionVariantType = BaseValueObject | BaseReferenceObject;-const FORMULA_CACHE_LRU_COUNT = 10000;--export const FORMULA_REF_TO_ARRAY_CACHE = new FormulaAstLRU<ArrayValueObject>(FORMULA_CACHE_LRU_COUNT);export class BaseReferenceObject extends ObjectClassType {+ private _calculationCache: FormulaCalculationCache | undefined;++ setCalculationCache(cache: FormulaCalculationCache | undefined): void {+ this._calculationCache = cache;+ }++ getCalculationCache(): FormulaCalculationCache | undefined {+ return this._calculationCache;+ }+private _dateSystem = DateSystem.Date1900;private _forcedSheetId: Nullable<string> = '';@@ -102,6 +115,7 @@ export class BaseReferenceObject extends ObjectClassType {}override dispose(): void {+ this._calculationCache = undefined;this._unitData = {};this._unitStylesData = {};@@ -291,7 +305,13 @@ export class BaseReferenceObject extends ObjectClassType {if (!this._forcedSheetName) {return;}- this._forcedSheetId = sheetNameMap[this.getUnitId()]?.[this._forcedSheetName];+ const names = sheetNameMap[this.getUnitId()];+ this._forcedSheetId = names?.[this._forcedSheetName];+ if (names && this._forcedSheetId == null) {+ const name = this._forcedSheetName.toLocaleLowerCase();+ const matchedName = Object.keys(names).find((candidate) => candidate.toLocaleLowerCase() === name);+ this._forcedSheetId = matchedName == null ? undefined : names[matchedName];+ }}setForcedSheetIdDirect(sheetId: string) {@@ -685,7 +705,8 @@ export class BaseReferenceObject extends ObjectClassType {// A cached range can be reused only when its string and formatted-number interpretation matches.const key = `${this.getUnitId()}_${this.getSheetId()}_${startRow}_${endRow}_${startColumn}_${endColumn}_${this._dateSystem}`;- const array = FORMULA_REF_TO_ARRAY_CACHE.get(key);+ const cache = this._checkIfWorksheetMiss() ? undefined : this._calculationCache;+ const array = cache && !cache.closed ? cache.references.get(key) : undefined;if (array && useCache) {return array;@@ -724,9 +745,11 @@ export class BaseReferenceObject extends ObjectClassType {useInvertedIndexCache: true,};- const arrayValueObject = ArrayValueObject.create(arrayValueObjectData, this._dateSystem);+ const arrayValueObject = ArrayValueObject.create(arrayValueObjectData, this._dateSystem).withCalculationCache(this._calculationCache);- useCache && FORMULA_REF_TO_ARRAY_CACHE.set(key, arrayValueObject);+ if (useCache && cache && !cache.closed) {+ cache.references.set(key, arrayValueObject);+ }return arrayValueObject;}@@ -761,7 +784,7 @@ export class BaseReferenceObject extends ObjectClassType {column: 0,};- return ArrayValueObject.create(arrayValueObjectData, this._dateSystem);+ return ArrayValueObject.create(arrayValueObjectData, this._dateSystem).withCalculationCache(this._calculationCache);}}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.tsindex 191d643f39..3a2f044915 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@@ -108,6 +108,7 @@ export class CellReferenceObject extends BaseReferenceObject {this.getForcedUnitId());+ rangeReferenceObject.setCalculationCache(this.getCalculationCache());rangeReferenceObject.setUnitData(this.getUnitData());rangeReferenceObject.setDefaultSheetId(this.getDefaultSheetId());diff --git a/packages/engine-formula/src/engine/utils/__tests__/cell.spec.ts b/packages/engine-formula/src/engine/utils/__tests__/cell.spec.tsindex f3f0a06c86..febdfd35d8 100644--- a/packages/engine-formula/src/engine/utils/__tests__/cell.spec.ts+++ b/packages/engine-formula/src/engine/utils/__tests__/cell.spec.ts@@ -55,7 +55,9 @@ describe('Test cell', () => {},};- expect(getCellValue(cell)).toBe('line 1\r\nline 2');+ expect(getCellValue(cell)).toBe('line 1\nline 2');+ expect(cell.p?.body?.dataStream).toBe('line 1\rline 2\r\n');+ expect(getCellValue({ v: 'line 1\r\nline 2' })).toBe('line 1\r\nline 2');});it('Function extractFormulaError', () => {diff --git a/packages/engine-formula/src/engine/utils/__tests__/generate-ast-node.spec.ts b/packages/engine-formula/src/engine/utils/__tests__/generate-ast-node.spec.tsindex ffc9dc22a1..d59489d271 100644--- a/packages/engine-formula/src/engine/utils/__tests__/generate-ast-node.spec.ts+++ b/packages/engine-formula/src/engine/utils/__tests__/generate-ast-node.spec.ts@@ -14,12 +14,63 @@* limitations under the License.*/-import { beforeEach, describe, expect, it } from 'vitest';-import { FORMULA_AST_CACHE, generateAstNode } from '../generate-ast-node';+import type { BaseReferenceObject } from '../../reference-object/base-reference-object';+import { Injector, ObjectMatrix } from '@univerjs/core';+import { afterEach, describe, expect, it } from 'vitest';+import { IFormulaCurrentConfigService } from '../../../services/current-data.service';+import { FormulaCacheService } from '../../../services/formula-cache.service';+import { IFormulaRuntimeService } from '../../../services/runtime.service';+import { createCommandTestBed } from '../../analysis/__tests__/create-command-test-bed';+import { Lexer } from '../../analysis/lexer';+import { AstTreeBuilder } from '../../analysis/parser';+import { Interpreter } from '../../interpreter/interpreter';+import { generateExecuteAstNodeData } from '../ast-node-tool';+import { generateAstNode } from '../generate-ast-node';describe('generateAstNode defined name cache invalidation', () => {- beforeEach(() => {- FORMULA_AST_CACHE.clear();+ const injectors: Injector[] = [];+ afterEach(() => injectors.splice(0).forEach((injector) => injector.dispose()));++ it('keeps cached references bound to their own engine when document IDs match', () => {+ const clients = [createCommandTestBed(), createCommandTestBed()];+ try {+ const nodes = clients.map((client, index) => {+ const config = client.get(IFormulaCurrentConfigService);+ config.registerUnitData({+ [client.unitId]: {+ [client.sheetId]: {+ ...client.sheetData[client.sheetId],+ cellData: new ObjectMatrix({ 0: { 0: { v: index + 1 } } }),+ },+ },+ });+ client.get(IFormulaRuntimeService).setCurrent(0, 1, 1, 1, client.sheetId, client.unitId);+ return generateAstNode(+ client.unitId,+ '=A1',+ client.get(Lexer),+ client.get(AstTreeBuilder),+ config,+ client.sheetId+ );+ });++ expect(nodes[0]).not.toBe(nodes[1]);+ clients.forEach((client, index) => {+ const value = client.get(Interpreter).execute(generateExecuteAstNodeData(nodes[index]));+ expect((value as BaseReferenceObject).getCellByPosition().getValue()).toBe(index + 1);+ expect(generateAstNode(+ client.unitId,+ '=A1',+ client.get(Lexer),+ client.get(AstTreeBuilder),+ client.get(IFormulaCurrentConfigService),+ client.sheetId+ )).toBe(nodes[index]);+ });+ } finally {+ clients.forEach((client) => client.univer.dispose());+ }});function createHarness(@@ -36,7 +87,10 @@ describe('generateAstNode defined name cache invalidation', () => {const lexer = {treeBuilder: (formula: string) => formula,};+ const injector = new Injector([[FormulaCacheService]]);+ injectors.push(injector);const astTreeBuilder = {+ cacheService: injector.get(FormulaCacheService),parse: () => {parseCount++;return node;diff --git a/packages/engine-formula/src/engine/utils/cell.ts b/packages/engine-formula/src/engine/utils/cell.tsindex 7c3bc6a1d1..cd52302381 100644--- a/packages/engine-formula/src/engine/utils/cell.ts+++ b/packages/engine-formula/src/engine/utils/cell.ts@@ -41,7 +41,7 @@ export function getCellValue(cell: Nullable<ICellData>) {}function normalizeRichTextFormulaValue(value: string) {- return value.replace(/\r\n|\r|\n/g, '\r\n');+ return value.replace(/\r\n|\r/g, '\n');}/**diff --git a/packages/engine-formula/src/engine/utils/generate-ast-node.ts b/packages/engine-formula/src/engine/utils/generate-ast-node.tsindex 5cd75674cd..1797af1693 100644--- a/packages/engine-formula/src/engine/utils/generate-ast-node.ts+++ b/packages/engine-formula/src/engine/utils/generate-ast-node.ts@@ -24,14 +24,9 @@ import type { AstRootNode } from '../ast-node/ast-root-node';import type { BaseAstNode } from '../ast-node/base-ast-node';import type { IFormulaDependencyTree } from '../dependency/dependency-tree';import { regexp } from '@univerjs/core';-import { FormulaAstLRU } from '../../basics/cache-lru';import { ERROR_TYPE_SET } from '../../basics/error-type';import { ErrorNode } from '../ast-node/base-ast-node';-const FORMULA_CACHE_LRU_COUNT = 5000;--export const FORMULA_AST_CACHE = new FormulaAstLRU<AstRootNode>(FORMULA_CACHE_LRU_COUNT);-type IDirtyStringMap = Record<string, string>;const DIRTY_DEFINED_NAME_SET_CACHE = new WeakMap<IDirtyStringMap, Set<string>>();@@ -53,9 +48,10 @@ export function generateAstNode(}const executeSubUnitId = subUnitId ?? currentConfigService.getExecuteSubUnitId() ?? '';+ const cache = astTreeBuilder.cacheService;const cacheKey = `${unitId}:${executeSubUnitId}:${definedNameRefOffsetX}:${definedNameRefOffsetY}:${formulaString}`;// refOffsetX and refOffsetY are separated by -, otherwise x:1 y:10 will be repeated with x:11 y:0- let astNode: Nullable<AstRootNode> = FORMULA_AST_CACHE.get(cacheKey);+ let astNode: Nullable<AstRootNode> = cache.getAst(cacheKey);// Dirty registry metadata invalidates the cached AST for this calculation because// defined names and SuperTable references are resolved while the AST is built.@@ -88,7 +84,7 @@ export function generateAstNode(// the old AST, while the newly parsed AST reflects the current registry and must// replace it. Otherwise, after the dirty map is cleared, an ordinary range// recalculation can fall back to the stale pre-registration AST.- FORMULA_AST_CACHE.set(cacheKey, astNode);+ cache.setAst(cacheKey, unitId, astNode);return astNode;}diff --git a/packages/engine-formula/src/engine/utils/three-dimensional-reference.ts b/packages/engine-formula/src/engine/utils/three-dimensional-reference.tsnew file mode 100644index 0000000000..4dc8b3c965--- /dev/null+++ b/packages/engine-formula/src/engine/utils/three-dimensional-reference.ts@@ -0,0 +1,98 @@+/**+ * 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 { IFormulaCurrentConfigService } from '../../services/current-data.service';+import type { BaseReferenceObject } from '../reference-object/base-reference-object';+import { ErrorType } from '../../basics/error-type';+import { MultiAreaArrayMode, MultiAreaReferenceObject } from '../reference-object/multi-area-reference-object';+import { RangeReferenceObject } from '../reference-object/range-reference-object';+import { ErrorValueObject } from '../value-object/base-value-object';++export function expandSheetSpan(+ source: BaseReferenceObject,+ currentConfig: IFormulaCurrentConfigService+): MultiAreaReferenceObject | ErrorValueObject | undefined {+ const span = source.getForcedSheetName();+ if (!span?.includes(':') || source.getForcedSheetId()) {+ return;+ }+ const endpoints = span.split(':');+ if (endpoints.length !== 2) {+ return ErrorValueObject.create(ErrorType.NAME);+ }+ const [first, last] = endpoints;+ return createThreeDimensionalReference(first, last, source, currentConfig.getSheetsInfo(source.getUnitId()))+ ?? ErrorValueObject.create(ErrorType.NAME);+}++export function createThreeDimensionalReference(+ firstSheetName: string,+ lastSheetName: string,+ source: BaseReferenceObject,+ sheetsInfo: ReturnType<IFormulaCurrentConfigService['getSheetsInfo']>+): MultiAreaReferenceObject | undefined {+ const { sheetOrder, sheetNameMap } = sheetsInfo;+ const sheetIdsByName = new Map(+ Object.entries(sheetNameMap).map(([sheetId, sheetName]) => [sheetName.toLocaleLowerCase(), sheetId])+ );+ const firstSheetId = sheetIdsByName.get(firstSheetName.toLocaleLowerCase());+ const lastSheetId = sheetIdsByName.get(lastSheetName.toLocaleLowerCase());+ const firstIndex = firstSheetId == null ? -1 : sheetOrder.indexOf(firstSheetId);+ const lastIndex = lastSheetId == null ? -1 : sheetOrder.indexOf(lastSheetId);+ if (firstIndex < 0 || lastIndex < 0) {+ return;+ }++ const startIndex = Math.min(firstIndex, lastIndex);+ const endIndex = Math.max(firstIndex, lastIndex);+ const areas = sheetOrder.slice(startIndex, endIndex + 1).map((sheetId) => {+ const reference = new RangeReferenceObject(source.getRangeData(), sheetId, source.getUnitId());+ copyReferenceContext(source, reference);+ reference.setForcedSheetIdDirect(sheetId);+ reference.setForcedSheetName(sheetNameMap[sheetId] ?? '');+ return [reference];+ });++ return new MultiAreaReferenceObject(+ `${firstSheetName}:${source.getToken()}`,+ areas,+ MultiAreaArrayMode.STACK_AREAS+ );+}++function copyReferenceContext(source: BaseReferenceObject, target: BaseReferenceObject): void {+ target.setDefaultUnitId(source.getDefaultUnitId());+ target.setDefaultSheetId(source.getDefaultSheetId());+ target.setCalculationCache(source.getCalculationCache());+ target.setUnitData(source.getUnitData());+ target.setUnitStylesData(source.getUnitStylesData());+ target.setFilteredOutRows(source.getFilteredOutRows());+ target.setRuntimeData(source.getRuntimeData());+ target.setArrayFormulaCellData(source.getArrayFormulaCellData());+ target.setArrayFormulaRange(source.getArrayFormulaRange());+ target.setRuntimeArrayFormulaCellData(source.getRuntimeArrayFormulaCellData());+ target.setRuntimeArrayFormulaRange(source.getRuntimeArrayFormulaRange());+ target.setRuntimeFeatureCellData(source.getRuntimeFeatureCellData());++ const currentRow = source.getCurrentRow();+ const currentColumn = source.getCurrentColumn();+ if (currentRow != null && currentColumn != null) {+ target.setCurrentRowAndColumn(currentRow, currentColumn);+ }++ const { x, y } = source.getRefOffset();+ target.setRefOffset(x, y);+}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.tsindex d7da6bbcfa..f827e36b44 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,13 +15,13 @@*/import type { Nullable } from '@univerjs/core';-import { DateSystem } from '@univerjs/core';-import { describe, expect, it } from 'vitest';import type { BaseValueObject } from '../base-value-object';+import { DateSystem, Injector } from '@univerjs/core';+import { describe, expect, it } from 'vitest';import { ErrorType } from '../../../basics/error-type';-import { CELL_INVERTED_INDEX_CACHE } from '../../../basics/inverted-index-cache';import { compareToken } from '../../../basics/token';import { getObjectValue } from '../../../functions/util';+import { FormulaCacheService } from '../../../services/formula-cache.service';import { ArrayValueObject, transformToValueObject, ValueObjectFactory } from '../array-value-object';import { ErrorValueObject } from '../base-value-object';import { BooleanValueObject, NumberValueObject, StringValueObject } from '../primitive-object';@@ -29,6 +29,8 @@ import { BooleanValueObject, NumberValueObject, StringValueObject } from '../pridescribe('arrayValueObject test', () => {it('matches uncached comparisons after repeated formula-result updates', () => {const values = [[1], [3], [5], [7], [9]];+ const injector = new Injector([[FormulaCacheService]]);+ const context = injector.get(FormulaCacheService).createCalculation()!;const createArray = (useInvertedIndexCache: boolean): ArrayValueObject => ArrayValueObject.create({calculateValueList: transformToValueObject(values),rowCount: values.length,@@ -38,14 +40,14 @@ describe('arrayValueObject test', () => {row: 10,column: 2,useInvertedIndexCache,- });- CELL_INVERTED_INDEX_CACHE.clear();+ }).withCalculationCache(context);try {+ expect(createArray(true).usesInvertedIndexCache()).toBe(true);createArray(true).compare(NumberValueObject.create(3), compareToken.EQUALS);for (let update = 0; update < 100; update++) {const row = update % values.length;values[row][0] = (update * 7) % 11;- CELL_INVERTED_INDEX_CACHE.set('updated-formulas', 'sheet', 2, values[row][0], row + 10, true);+ context.invertedIndex.set('updated-formulas', 'sheet', 2, values[row][0], row + 10, true);for (const operator of Object.values(compareToken)) {const criterion = NumberValueObject.create(update % 11);const cached = createArray(true).compare(criterion, operator);@@ -56,7 +58,7 @@ describe('arrayValueObject test', () => {}}} finally {- CELL_INVERTED_INDEX_CACHE.clear();+ injector.dispose();}});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.tsindex 051e2b32aa..ce9d8a157d 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,11 +15,11 @@*/import type { Nullable } from '@univerjs/core';-import { DateSystem, isRealNum } from '@univerjs/core';+import type { FormulaCalculationCache } from '../../services/formula-cache.service';import type { callbackMapFnType, IArrayValueObject } from './base-value-object';+import { DateSystem, isRealNum } from '@univerjs/core';import { BooleanValue } from '../../basics/common';import { ERROR_TYPE_SET, ErrorType } from '../../basics/error-type';-import { CELL_INVERTED_INDEX_CACHE } from '../../basics/inverted-index-cache';import { regexTestArrayValue } from '../../basics/regex';import { compareToken } from '../../basics/token';import { ArrayBinarySearchType, ArrayOrderSearchType, getCompare, isWildcard } from '../utils/compare';@@ -109,6 +109,13 @@ export function transformToValue(array: Nullable<BaseValueObject>[][] = []) {}export class ArrayValueObject extends BaseValueObject {+ private _calculationCache: FormulaCalculationCache | undefined;++ withCalculationCache(cache: FormulaCalculationCache | undefined): this {+ this._calculationCache = cache;+ return this;+ }+/*** Create an array value object based on the string or IArrayValueObject data.* @param rawValue@@ -185,6 +192,7 @@ export class ArrayValueObject extends BaseValueObject {// });// });+ this._calculationCache = undefined;this._values = [];this._defaultValue = null;@@ -246,7 +254,7 @@ export class ArrayValueObject extends BaseValueObject {}usesInvertedIndexCache() {- return this._useInvertedIndexCache;+ return this._useInvertedIndexCache && this._calculationCache != null && !this._calculationCache.closed;}usesLegacyImplicitForAggregate() {@@ -1552,8 +1560,8 @@ export class ArrayValueObject extends BaseValueObject {* If comparison operations are conducted for a single numerical value,* then retrieve the judgment from the inverted index. This enhances performance.*/- if (batchOperatorType === BatchOperatorType.COMPARE && this._useInvertedIndexCache && !isWildcardComparison) {- const { rowsInCache, rowsNotInCache } = CELL_INVERTED_INDEX_CACHE.canUseCache(+ if (batchOperatorType === BatchOperatorType.COMPARE && this.usesInvertedIndexCache() && !isWildcardComparison) {+ const { rowsInCache, rowsNotInCache } = this._calculationCache!.invertedIndex.canUseCache(unitId,sheetId,column + startColumn,@@ -1563,7 +1571,7 @@ export class ArrayValueObject extends BaseValueObject {if (rowsInCache.length > 0) {if (operator === compareToken.EQUALS && !(valueObject.isString() && isWildcard(valueObject.getValue() as string))) {- const rowPositions = CELL_INVERTED_INDEX_CACHE.getCellPositions(+ const rowPositions = this._calculationCache!.invertedIndex.getCellPositions(unitId,sheetId,column + startColumn,@@ -1585,7 +1593,7 @@ export class ArrayValueObject extends BaseValueObject {});}} else {- const rowValuePositions = CELL_INVERTED_INDEX_CACHE.getCellValuePositions(+ const rowValuePositions = this._calculationCache!.invertedIndex.getCellValuePositions(unitId,sheetId,column + startColumn@@ -1646,8 +1654,8 @@ export class ArrayValueObject extends BaseValueObject {);}- if (this._useInvertedIndexCache) {- CELL_INVERTED_INDEX_CACHE.setContinueBuildingCache(+ if (this.usesInvertedIndexCache()) {+ this._calculationCache!.invertedIndex.setContinueBuildingCache(unitId,sheetId,column + startColumn,@@ -1678,8 +1686,8 @@ export class ArrayValueObject extends BaseValueObject {);}- if (this._useInvertedIndexCache) {- CELL_INVERTED_INDEX_CACHE.setContinueBuildingCache(+ if (this.usesInvertedIndexCache()) {+ this._calculationCache!.invertedIndex.setContinueBuildingCache(unitId,sheetId,column + startColumn,@@ -1766,8 +1774,8 @@ export class ArrayValueObject extends BaseValueObject {result[r][column] = ErrorValueObject.create(ErrorType.NA);}- if (this._useInvertedIndexCache) {- CELL_INVERTED_INDEX_CACHE.set(+ if (this.usesInvertedIndexCache()) {+ this._calculationCache!.invertedIndex.set(unitId,sheetId,column + startColumn,@@ -1990,7 +1998,7 @@ export class ArrayValueObject extends BaseValueObject {column,};- return ArrayValueObject.create(arrayValueObjectData, this.getDateSystem());+ return ArrayValueObject.create(arrayValueObjectData, this.getDateSystem()).withCalculationCache(this._calculationCache);}}diff --git a/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts b/packages/engine-formula/src/functions/__tests__/create-function-test-bed.tsindex 55e09826c3..7cf9385f48 100644--- a/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts+++ b/packages/engine-formula/src/functions/__tests__/create-function-test-bed.ts@@ -17,7 +17,6 @@/* eslint-disable max-lines-per-function */import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';-import type { ISheetData } from '../../basics/common';import {CellValueType,ILogService,@@ -31,6 +30,7 @@ import {Univer,UniverInstanceType,} from '@univerjs/core';+import type { ISheetData } from '../../basics/common';import { Lexer } from '../../engine/analysis/lexer';import { LexerTreeBuilder } from '../../engine/analysis/lexer-tree-builder';import { AstTreeBuilder } from '../../engine/analysis/parser';@@ -54,6 +54,8 @@ import {IFormulaExternalReferenceDataLoader,NoopFormulaExternalReferenceDataLoader,} from '../../services/external-reference-data-loader.service';+import { FormulaCacheService } from '../../services/formula-cache.service';+import { FormulaResultService } from '../../services/formula-result.service';import { FunctionService, IFunctionService } from '../../services/function.service';import { HyperlinkEngineFormulaService, IHyperlinkEngineFormulaService } from '../../services/hyperlink-engine-formula.service';import { IOtherFormulaManagerService, OtherFormulaManagerService } from '../../services/other-formula-manager.service';@@ -176,8 +178,10 @@ export function createFunctionTestBed(workbookData?: IWorkbookData, dependenciesoverride onStarting(): void {const injector = this._injector;+ injector.add([FormulaResultService, { useValue: { applyResult: async () => {}, applyTreeResult: async () => {} } } as never]);injector.add([ICalculateFormulaService, { useClass: CalculateFormulaService }]);injector.add([Lexer]);+ injector.add([FormulaCacheService]);injector.add([LexerTreeBuilder]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);diff --git a/packages/engine-formula/src/functions/base-function.ts b/packages/engine-formula/src/functions/base-function.tsindex 125d5606c5..cdb1ff9cb2 100644--- a/packages/engine-formula/src/functions/base-function.ts+++ b/packages/engine-formula/src/functions/base-function.ts@@ -679,6 +679,7 @@ export class BaseFunction {object.setForcedSheetName(reference.getForcedSheetName());+ object.setCalculationCache(reference.getCalculationCache());object.setUnitData(reference.getUnitData());object.setRuntimeData(reference.getRuntimeData());object.setArrayFormulaCellData(reference.getArrayFormulaCellData());diff --git a/packages/engine-formula/src/functions/financial/pv/__tests__/index.spec.ts b/packages/engine-formula/src/functions/financial/pv/__tests__/index.spec.tsindex 4ab9034def..3d969e1bec 100644--- a/packages/engine-formula/src/functions/financial/pv/__tests__/index.spec.ts+++ b/packages/engine-formula/src/functions/financial/pv/__tests__/index.spec.ts@@ -41,6 +41,30 @@ describe('Test pv function', () => {expect(getObjectValue(result2, true)).toBe(-6017566.01568624);});+ it('preserves Excel integer-period compounding before loan balance cancellation', () => {+ const result = testFunction.calculate(+ NumberValueObject.create(0.05 / 12),+ NumberValueObject.create(4),+ NumberValueObject.create(-3000)+ );+ expect(result.getValue()).toBe(11876.03412150258);+ });++ it.each([+ [0.05 / 12, -4, 1, -12227.199031605747],+ [0.05 / 12, 1.5, 0, 4377.29766121263],+ [0, 4, 1, 11900],+ ])('preserves negative, fractional and zero-rate Excel cases: %s, %s', (rate, periods, type, expected) => {+ const result = testFunction.calculate(+ NumberValueObject.create(rate),+ NumberValueObject.create(periods),+ NumberValueObject.create(-3000),+ NumberValueObject.create(100),+ NumberValueObject.create(type)+ );+ expect(result.getValue()).toBe(expected);+ });+it('Value is error', () => {const rate = ErrorValueObject.create(ErrorType.NAME);const nper = NumberValueObject.create(20 * 12);diff --git a/packages/engine-formula/src/functions/financial/pv/index.ts b/packages/engine-formula/src/functions/financial/pv/index.tsindex 41f4dd42e7..8d72f49df1 100644--- a/packages/engine-formula/src/functions/financial/pv/index.ts+++ b/packages/engine-formula/src/functions/financial/pv/index.ts@@ -78,9 +78,26 @@ export class Pv extends BaseFunction {let typeValue = +_typeObject.getValue();typeValue = typeValue ? 1 : 0;+ let term: number;+ if (Number.isInteger(nperValue) && Math.abs(nperValue) <= 0x7FFF_FFFF) {+ // Integer multiplication preserves the compounding factor in loan balances.+ term = 1;+ let factor = 1 + rateValue;+ for (let periods = Math.abs(nperValue); periods > 0; periods = Math.floor(periods / 2)) {+ if (periods % 2 === 1) {+ term *= factor;+ }+ factor *= factor;+ }+ if (nperValue < 0) {+ term = 1 / term;+ }+ } else {+ term = (1 + rateValue) ** nperValue;+ }const result = rateValue === 0? -pmtValue * nperValue - fvValue- : (((1 - (1 + rateValue) ** nperValue) / rateValue) * pmtValue * (1 + rateValue * typeValue) - fvValue) / (1 + rateValue) ** nperValue;+ : (((1 - term) / rateValue) * pmtValue * (1 + rateValue * typeValue) - fvValue) / term;if (Number.isNaN(result) || !Number.isFinite(result)) {return ErrorValueObject.create(ErrorType.NUM);diff --git a/packages/engine-formula/src/functions/lookup/index/__tests__/index.spec.ts b/packages/engine-formula/src/functions/lookup/index/__tests__/index.spec.tsindex 3a402498c5..c6fe7b53d5 100644--- a/packages/engine-formula/src/functions/lookup/index/__tests__/index.spec.ts+++ b/packages/engine-formula/src/functions/lookup/index/__tests__/index.spec.ts@@ -24,7 +24,10 @@ import { ErrorType } from '../../../../basics/error-type';import { Lexer } from '../../../../engine/analysis/lexer';import { AstTreeBuilder } from '../../../../engine/analysis/parser';import { Interpreter } from '../../../../engine/interpreter/interpreter';+import { MultiAreaReferenceObject } from '../../../../engine/reference-object/multi-area-reference-object';+import { RangeReferenceObject } from '../../../../engine/reference-object/range-reference-object';import { generateExecuteAstNodeData } from '../../../../engine/utils/ast-node-tool';+import { NumberValueObject } from '../../../../engine/value-object/primitive-object';import { IFormulaCurrentConfigService } from '../../../../services/current-data.service';import { IFunctionService } from '../../../../services/function.service';import { IFormulaRuntimeService } from '../../../../services/runtime.service';@@ -133,6 +136,13 @@ const getTestWorkbookData = (): IWorkbookData => {},},},+ sheet2: {+ id: 'sheet2',+ name: 'Other',+ rowCount: 10,+ columnCount: 10,+ cellData: { 0: { 0: { v: 30, t: CellValueType.NUMBER } }, 1: { 0: { v: 31, t: CellValueType.NUMBER } } },+ },},locale: LocaleType.ZH_CN,name: '',@@ -141,6 +151,22 @@ const getTestWorkbookData = (): IWorkbookData => {};};describe('Test index', () => {+ it.each(['another-sheet', 'another-workbook'])('rejects reference areas from %s', (different) => {+ const first = new RangeReferenceObject({ startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 }, 's1', 'book');+ const second = new RangeReferenceObject(+ { startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 },+ different === 'another-sheet' ? 's2' : 's1',+ different === 'another-workbook' ? 'other' : 'book'+ );+ const reference = new MultiAreaReferenceObject('(A1:A2,A1:A2)', [[first, second]]);+ const result = new Index(FUNCTION_NAMES_LOOKUP.INDEX).calculate(+ reference,+ NumberValueObject.create(1),+ NumberValueObject.create(1),+ NumberValueObject.create(2)+ );+ expect(getObjectValue(result)).toBe(ErrorType.VALUE);+ });let get: Injector['get'];let lexer: Lexer;let astTreeBuilder: AstTreeBuilder;@@ -556,6 +582,15 @@ describe('Test index', () => {});});+ it('resolves case variants of the same source sheet through the formula parser', () => {+ expect(calculate('=INDEX((Other!A1:A2,OTHER!A1:A2),2,1,2)')).toStrictEqual([[31]]);+ });++ it('rejects cross-sheet reference form through the formula parser', async () => {+ expect(await calculate('=INDEX((A1:A2,Other!A1:A2),2,1,2)')).toBe(ErrorType.VALUE);+ expect(await calculate('=INDEX((A1:A2,A1:A2),2,1,2)')).toEqual([[3]]);+ });+describe('Multi rows and columns', () => {it('Row number null, different column parameters', async () => {// nulldiff --git a/packages/engine-formula/src/functions/lookup/index/index.ts b/packages/engine-formula/src/functions/lookup/index/index.tsindex 1fb18c40b4..0fcc4bf36b 100644--- a/packages/engine-formula/src/functions/lookup/index/index.ts+++ b/packages/engine-formula/src/functions/lookup/index/index.ts@@ -52,6 +52,24 @@ export class Index extends BaseFunction {return reference;}+ let areas: (BaseReferenceObject | ErrorValueObject)[] | undefined;+ if (reference.isReferenceObject()) {+ if ((reference as BaseReferenceObject).isMultiArea()) {+ areas = (reference as MultiAreaReferenceObject).getAreas().flat();+ }+ } else if ((reference as BaseValueObject).isCube()) {+ areas = (reference as CubeValueObject).getCubeReferences();+ }+ if (areas) {+ const first = areas.find((area) => area.isReferenceObject()) as BaseReferenceObject | undefined;+ if (first && areas.some((area) => area.isReferenceObject() && (+ (area as BaseReferenceObject).getUnitId() !== first.getUnitId() ||+ (area as BaseReferenceObject).getSheetId() !== first.getSheetId()+ ))) {+ return ErrorValueObject.create(ErrorType.VALUE);+ }+ }+const referenceRowColumnCounts = this._getReferenceCounts(reference);let _rowNum = rowNum;diff --git a/packages/engine-formula/src/functions/meta/compare/__tests__/index.spec.ts b/packages/engine-formula/src/functions/meta/compare/__tests__/index.spec.tsindex 8eb7b83273..b139604667 100644--- a/packages/engine-formula/src/functions/meta/compare/__tests__/index.spec.ts+++ b/packages/engine-formula/src/functions/meta/compare/__tests__/index.spec.ts@@ -14,9 +14,8 @@* limitations under the License.*/-import { beforeEach, describe, expect, it } from 'vitest';+import { describe, expect, it } from 'vitest';import { ErrorType } from '../../../../basics/error-type';-import { CELL_INVERTED_INDEX_CACHE } from '../../../../basics/inverted-index-cache';import { compareToken } from '../../../../basics/token';import { ArrayValueObject, transformToValueObject } from '../../../../engine/value-object/array-value-object';import { BooleanValueObject, NullValueObject, NumberValueObject, StringValueObject } from '../../../../engine/value-object/primitive-object';@@ -27,11 +26,6 @@ import { Compare } from '../index';describe('Test compare function', () => {const testFunction = new Compare(FUNCTION_NAMES_META.COMPARE);- beforeEach(() => {- // Cache will affect the calculation results- CELL_INVERTED_INDEX_CACHE.clear();- });-describe('Compare', () => {it('Comparing Boolean and number', () => {const value1 = BooleanValueObject.create(false);diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.tsindex 9cd880f7e9..59b749fabf 100644--- a/packages/engine-formula/src/index.ts+++ b/packages/engine-formula/src/index.ts@@ -52,7 +52,6 @@ export { type ISheetFormulaError } from './basics/error-type';export { FunctionType } from './basics/function';export type { IFunctionInfo, IFunctionParam } from './basics/function';export { type IFunctionNames } from './basics/function';-export { CELL_INVERTED_INDEX_CACHE } from './basics/inverted-index-cache';export { includeFormulaLexerToken, isFormulaLexerToken, normalizeSheetName } from './basics/match-token';export { matchRefDrawToken } from './basics/match-token';export { isReferenceString } from './basics/regex';@@ -170,11 +169,7 @@ export { generateRandomDependencyTreeId } from './engine/dependency/formula-depeexport { Interpreter } from './engine/interpreter/interpreter';export { BaseReferenceObject } from './engine/reference-object/base-reference-object';export type { FunctionVariantType } from './engine/reference-object/base-reference-object';-export {- AsyncArrayObject,- AsyncObject,- FORMULA_REF_TO_ARRAY_CACHE,-} from './engine/reference-object/base-reference-object';+export { AsyncArrayObject, AsyncObject } from './engine/reference-object/base-reference-object';export { RangeReferenceObject } from './engine/reference-object/range-reference-object';export { generateExecuteAstNodeData } from './engine/utils/ast-node-tool';export { extractFormulaError } from './engine/utils/cell';@@ -277,6 +272,7 @@ export { FUNCTION_NAMES_UNIVER } from './functions/univer/function-names';export { getObjectValue } from './functions/util';export { functionWeb } from './functions/web/function-map';export { FUNCTION_NAMES_WEB } from './functions/web/function-names';+export type { IFormulaDataSnapshot } from './models/formula-data-snapshot';export { FormulaDataModel } from './models/formula-data.model';export type { IRangeChange } from './models/formula-data.model';export { UniverFormulaEnginePlugin } from './plugin';@@ -308,6 +304,7 @@ export { FormulaCalculationTriggerService, mergeDirtyData } from './services/forexport { IFormulaChangesetCalculationService } from './services/formula-changeset-calculation.service';export type { IFormulaInfo, IOtherFormulaResult } from './services/formula-common';export { FormulaResultStatus } from './services/formula-common';+export { FormulaResultService } from './services/formula-result.service';export { DescriptionService, IDescriptionService } from './services/formula/description.service';export type { ISearchItem, ISearchItemWithType } from './services/formula/description.service';export {@@ -368,6 +365,7 @@ export {IFormulaUnitReferenceResolver,normalizeFormulaUnitName,} from './services/unit-reference-resolver.service';+export type {FormulaUnitReferenceKind,IFormulaUnitReferenceResolution,diff --git a/packages/engine-formula/src/models/__tests__/create-command-test-bed.ts b/packages/engine-formula/src/models/__tests__/create-command-test-bed.tsindex cffa4f8819..989b45a29c 100644--- a/packages/engine-formula/src/models/__tests__/create-command-test-bed.ts+++ b/packages/engine-formula/src/models/__tests__/create-command-test-bed.ts@@ -31,6 +31,8 @@ import { LexerTreeBuilder } from '../../engine/analysis/lexer-tree-builder';import { CalculateFormulaService, ICalculateFormulaService } from '../../services/calculate-formula.service';import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from '../../services/current-data.service';import { DefinedNamesService, IDefinedNamesService } from '../../services/defined-names.service';+import { FormulaCacheService } from '../../services/formula-cache.service';+import { FormulaResultService } from '../../services/formula-result.service';import {HyperlinkEngineFormulaService,IHyperlinkEngineFormulaService,@@ -83,8 +85,10 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?override onStarting(): void {const injector = this._injector;+ injector.add([FormulaResultService, { useValue: { applyResult: async () => {}, applyTreeResult: async () => {} } } as never]);injector.add([ICalculateFormulaService, { useClass: CalculateFormulaService }]);injector.add([FormulaDataModel]);+ injector.add([FormulaCacheService]);injector.add([LexerTreeBuilder]);injector.add([Lexer]);injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);diff --git a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.tsindex 8fc7041c09..136b0a4b47 100644--- a/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts+++ b/packages/engine-formula/src/models/__tests__/formula-data.model.spec.ts@@ -14,8 +14,7 @@* limitations under the License.*/-import type { IBaseSnapshot, ICellData, Injector, IWorkbookData, Nullable, Univer, Workbook } from '@univerjs/core';-import type { IFormulaData } from '../../basics/common';+import type { IBaseSnapshot, ICellData, Injector, IObjectMatrixPrimitiveType, IWorkbookData, Nullable, Univer, Workbook } from '@univerjs/core';import {BASE_RECORD_ID_FIELD_ID,BaseDataModel,@@ -23,6 +22,8 @@ import {BooleanNumber,CellValueType,createBaseRecordIdField,+ isFormulaId,+ isFormulaString,IUniverInstanceService,LocaleType,ObjectMatrix,@@ -30,7 +31,9 @@ import {Tools,UniverInstanceType,} from '@univerjs/core';+import { types as nodeUtilTypes } from 'node:util';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { IFormulaData } from '../../basics/common';import { FormulaDataModel } from '../formula-data.model';import { createCommandTestBed } from './create-command-test-bed';@@ -186,6 +189,837 @@ const TEST_BASE_DATA: Partial<IBaseSnapshot> = {},};+function createCompactFormulaTestBed(cellData: IObjectMatrixPrimitiveType<Nullable<ICellData>>) {+ const data = Tools.deepClone(TEST_WORKBOOK_DATA_EXTRA);+ data.sheetOrder = ['sheet1', 'empty'];+ // These fixtures include runtime null/undefined slots, which the public cell matrix supports.+ // Keep their exact descriptors and prototypes when passing through the narrower snapshot type.+ data.sheets.sheet1.cellData = cellData as IObjectMatrixPrimitiveType<ICellData>;+ data.sheets.empty = { id: 'empty', name: 'Empty', rowCount: 2, columnCount: 2, cellData: {} };+ const testBed = createCommandTestBed(data);+ const worksheet = testBed.get(IUniverInstanceService).getUnit<Workbook>('test')!.getSheetBySheetId('sheet1')!;+ return { ...testBed, worksheet, model: testBed.get(FormulaDataModel) };+}++function readFormulaInput(model: FormulaDataModel, compact: boolean): IFormulaData {+ if (!compact) return model.getFormulaData();+ const snapshot = model.tryCreateFormulaDataSnapshot(nodeUtilTypes.isProxy);+ expect(snapshot).toBeDefined();+ return snapshot!.materialize();+}++describe('compact execution formula snapshots', () => {+ it('captures and materializes formulas when Object.hasOwn is unavailable', () => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=SUM(A1:A2)' } } });+ try {+ const expected = testBed.model.getFormulaData();+ const descriptor = Object.getOwnPropertyDescriptor(Object, 'hasOwn')!;+ let actual: IFormulaData | undefined;+ try {+ Object.defineProperty(Object, 'hasOwn', { ...descriptor, value: undefined });+ actual = testBed.model.tryCreateFormulaDataSnapshot(nodeUtilTypes.isProxy)?.materialize();+ } finally { Object.defineProperty(Object, 'hasOwn', descriptor); }+ expect(actual).toEqual(expected);+ } finally { testBed.univer.dispose(); }+ });++ it('declines an own getFormulaData override before calling it, then preserves the legacy result', () => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=BEFORE()' } } });+ const customData = { custom: { sheet: { 0: { 0: { f: '=CUSTOM()' } } } } };+ const override = vi.spyOn(testBed.model, 'getFormulaData').mockImplementation(() => {+ testBed.worksheet.getCellMatrix().getValue(0, 0)!.f = '=AFTER()';+ return customData;+ });+ try {+ expect(testBed.model.tryCreateFormulaDataSnapshot(nodeUtilTypes.isProxy)).toBeUndefined();+ expect(override).not.toHaveBeenCalled();+ expect(testBed.worksheet.getCellMatrix().getValue(0, 0)?.f).toBe('=BEFORE()');+ expect(testBed.model.getFormulaData()).toBe(customData);+ expect(override).toHaveBeenCalledTimes(1);+ } finally {+ override.mockRestore();+ testBed.univer.dispose();+ }+ });++ it('declines a subclass formula getter without executing it during qualification', () => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=1+2' } } });+ let calls = 0;+ class CustomFormulaDataModel extends FormulaDataModel {+ override getFormulaData(): IFormulaData {+ calls++;+ return { custom: {} };+ }+ }+ Object.setPrototypeOf(testBed.model, CustomFormulaDataModel.prototype);+ try {+ expect(testBed.model.tryCreateFormulaDataSnapshot(nodeUtilTypes.isProxy)).toBeUndefined();+ expect(calls).toBe(0);+ expect(testBed.model.getFormulaData()).toEqual({ custom: {} });+ expect(calls).toBe(1);+ } finally {+ Object.setPrototypeOf(testBed.model, FormulaDataModel.prototype);+ testBed.univer.dispose();+ }+ });++ it('declines a changed prototype formula getter before legacy execution', () => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=BEFORE()' } } });+ const customData = { custom: {} };+ const override = vi.spyOn(FormulaDataModel.prototype, 'getFormulaData').mockReturnValue(customData);+ try {+ expect(testBed.model.tryCreateFormulaDataSnapshot(nodeUtilTypes.isProxy)).toBeUndefined();+ expect(override).not.toHaveBeenCalled();+ expect(testBed.model.getFormulaData()).toBe(customData);+ expect(override).toHaveBeenCalledTimes(1);+ } finally {+ override.mockRestore();+ testBed.univer.dispose();+ }+ });++ it.each(['initSheetFormulaData', '_initSheetArrayFormulaData'] as const)('declines a custom %s method before observing its getter', (name) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=A1' } } });+ const original = Object.getOwnPropertyDescriptor(FormulaDataModel.prototype, name)!.value;+ let reads = 0;+ Object.defineProperty(testBed.model, name, {+ configurable: true,+ get: () => {+ reads++;+ return original;+ },+ });+ try {+ expect(testBed.model.tryCreateFormulaDataSnapshot(nodeUtilTypes.isProxy)).toBeUndefined();+ expect(reads).toBe(0);+ expect(testBed.model.getFormulaData().test!.sheet1![0][0]?.f).toBe('=A1');+ expect(reads).toBe(2);+ } finally {+ Reflect.deleteProperty(testBed.model, name);+ testBed.univer.dispose();+ }+ });++ it('keeps the eager route when output matrix writes have been customized', () => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=A1' } } });+ const writes = vi.spyOn(ObjectMatrix.prototype, 'setValue');+ try {+ expect(testBed.model.tryCreateFormulaDataSnapshot(nodeUtilTypes.isProxy)).toBeUndefined();+ expect(writes).not.toHaveBeenCalled();+ expect(testBed.model.getFormulaData().test!.sheet1![0][0]?.f).toBe('=A1');+ expect(writes).toHaveBeenCalledTimes(1);+ } finally {+ writes.mockRestore();+ testBed.univer.dispose();+ }+ });++ it('preserves Sheets-then-Base callback order and captures before later edits', () => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=BEFORE()' } } });+ const service = testBed.get(IUniverInstanceService);+ const getUnits = service.getAllUnitsForType.bind(service);+ const events: UniverInstanceType[] = [];+ const override = vi.spyOn(service, 'getAllUnitsForType').mockImplementation(<T>(type: UniverInstanceType): T[] => {+ events.push(type);+ if (type === UniverInstanceType.UNIVER_BASE) {+ testBed.worksheet.getCellMatrix().getValue(0, 0)!.f = '=AFTER()';+ }+ return getUnits<T>(type);+ });+ try {+ return {+ data: readFormulaInput(testBed.model, compact),+ events,+ current: testBed.worksheet.getCellMatrix().getValue(0, 0)?.f,+ };+ } finally {+ override.mockRestore();+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(expected.events).toEqual([UniverInstanceType.UNIVER_SHEET, UniverInstanceType.UNIVER_BASE]);+ expect(expected.data.test!.sheet1![0][0]?.f).toBe('=BEFORE()');+ expect(expected.current).toBe('=AFTER()');+ expect(run(true)).toStrictEqual(expected);+ });++ it.each(['custom', 'proxy'] as const)('preserves a %s unit service without repeating its callbacks', (kind) => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=BEFORE()' } } });+ const original = testBed.get(IUniverInstanceService);+ const getUnits = original.getAllUnitsForType.bind(original);+ const events: UniverInstanceType[] = [];+ const custom = {+ getAllUnitsForType: (type: UniverInstanceType) => {+ events.push(type);+ return getUnits(type);+ },+ };+ const proxy = new Proxy(original, {+ get: (target, key, receiver) => key === 'getAllUnitsForType'+ ? custom.getAllUnitsForType+ : Reflect.get(target, key, receiver),+ });+ Object.assign(testBed.model, { _univerInstanceService: kind === 'custom' ? custom : proxy });+ try {+ return { data: readFormulaInput(testBed.model, compact), events };+ } finally {+ Object.assign(testBed.model, { _univerInstanceService: original });+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(expected.events).toEqual([UniverInstanceType.UNIVER_SHEET, UniverInstanceType.UNIVER_BASE]);+ expect(run(true)).toStrictEqual(expected);+ });++ it.each(['getMatrix', 'getValue'] as const)('does not read an ObjectMatrix.%s method the source traversal does not use', (name) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=A1' } } });+ const matrix = testBed.worksheet.getCellMatrix();+ let calls = 0;+ Object.defineProperty(matrix, name, {+ configurable: true,+ get: () => {+ calls++;+ throw new Error('unexpected matrix method');+ },+ });+ try {+ const expected = testBed.model.getFormulaData();+ expect(readFormulaInput(testBed.model, true)).toStrictEqual(expected);+ expect(calls).toBe(0);+ } finally {+ Reflect.deleteProperty(matrix, name);+ testBed.univer.dispose();+ }+ });++ it('propagates an original forValue getter failure once, without falling back and rereading it', () => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=A1' } } });+ const matrix = testBed.worksheet.getCellMatrix();+ let calls = 0;+ const error = new Error('custom source traversal');+ Object.defineProperty(matrix, 'forValue', {+ configurable: true,+ get: () => {+ calls++;+ throw error;+ },+ });+ try {+ expect(() => readFormulaInput(testBed.model, compact)).toThrow(error);+ return calls;+ } finally {+ Reflect.deleteProperty(matrix, 'forValue');+ testBed.univer.dispose();+ }+ };+ expect(run(false)).toBe(1);+ expect(run(true)).toBe(1);+ });++ it('keeps private snapshot arrays independent of later global iterator callbacks', () => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=A1' } } });+ const iterator = Object.getOwnPropertyDescriptor(Array.prototype, Symbol.iterator)!;+ let calls = 0;+ let result: IFormulaData | undefined;+ let captured = false;+ try {+ // eslint-disable-next-line no-extend-native -- This adversarial fixture restores the native descriptor in finally.+ Object.defineProperty(Array.prototype, Symbol.iterator, {+ configurable: true,+ get: () => {+ calls++;+ throw new Error('unexpected iterator');+ },+ });+ const snapshot = testBed.model.tryCreateFormulaDataSnapshot(nodeUtilTypes.isProxy);+ captured = snapshot != null;+ result = snapshot?.materialize();+ } finally {+ // eslint-disable-next-line no-extend-native -- Restore the native descriptor changed by this adversarial fixture.+ Object.defineProperty(Array.prototype, Symbol.iterator, iterator);+ testBed.univer.dispose();+ }+ expect(captured).toBe(true);+ expect(result?.test?.sheet1?.[0]?.[0]?.f).toBe('=A1');+ expect(calls).toBe(0);+ });++ it('captures formula values independently of subsequent cell edits and preserves exact DTO structure', () => {+ const testBed = createCompactFormulaTestBed({+ 0: { 0: { f: '=A1+1', v: 4 }, 2: { f: '=B1+2' }, 3: { f: '=' } },+ 1: { 1: { f: '=C2', s: 'style' } },+ 5: { 0: { v: 9 } },+ });+ try {+ const expected = testBed.model.getFormulaData();+ const snapshot = testBed.model.tryCreateFormulaDataSnapshot(nodeUtilTypes.isProxy);+ expect(snapshot).toBeDefined();+ const matrix = testBed.worksheet.getCellMatrix();+ matrix.getValue(0, 0)!.f = '=99';+ matrix.realDeleteValue(0, 2);+ matrix.setValue(1, 1, { f: '=REPLACED()' });+ matrix.setValue(7, 0, { f: '=NEW()' });+ const actual = snapshot!.materialize();++ expect(actual).toStrictEqual(expected);+ expect(snapshot!.materialize()).toBe(actual);+ expect(Object.getPrototypeOf(actual)).toBeNull();+ expect(Object.getPrototypeOf(actual.test!)).toBeNull();+ expect(Object.getPrototypeOf(actual.test!.sheet1!)).toBeNull();+ expect(Object.getPrototypeOf(actual.test!.sheet1![0])).toBe(Object.prototype);+ expect(Object.getPrototypeOf(actual.test!.sheet1![0][0])).toBe(Object.prototype);+ expect(Object.getOwnPropertyDescriptors(actual.test!.sheet1![0][0]!))+ .toEqual(Object.getOwnPropertyDescriptors(expected.test!.sheet1![0][0]!));+ expect(Object.keys(actual.test!.sheet1![0][0]!)).toEqual(['f']);+ expect(actual.test!.empty).toEqual({});+ actual.test!.sheet1![0][0]!.f = '=LOCAL()';+ expect(matrix.getValue(0, 0)?.f).toBe('=99');+ expect(testBed.model.getFormulaData().test!.sheet1![0][0]?.f).toBe('=99');+ } finally {+ testBed.univer.dispose();+ }+ });++ it('keeps captured data alive after workbook disposal without observing later prototype setters', () => {+ const column = 90_000_001;+ const testBed = createCompactFormulaTestBed({ 7: { [column]: { f: '=1+2' } } });+ const snapshot = testBed.model.tryCreateFormulaDataSnapshot(nodeUtilTypes.isProxy);+ expect(snapshot).toBeDefined();+ testBed.univer.dispose();+ let calls = 0;+ try {+ // eslint-disable-next-line no-extend-native -- This adversarial fixture restores the native descriptor in finally.+ Object.defineProperty(Object.prototype, String(column), {+ configurable: true,+ set: () => { calls++; },+ });+ const result = snapshot!.materialize();+ expect(result.test!.sheet1![7][column]).toEqual({ f: '=1+2' });+ expect(Object.getOwnPropertyDescriptor(result.test!.sheet1![7], String(column)))+ .toMatchObject({ enumerable: true, writable: true, configurable: true });+ expect(calls).toBe(0);+ } finally {+ Reflect.deleteProperty(Object.prototype, String(column));+ }+ });++ it('accepts null-prototype data and ignores cell fields the old formula builder never reads', () => {+ let reads = 0;+ const cell = Object.assign(Object.create(null), { f: '=SUM(A1)' });+ Object.defineProperty(cell, 'unrelated', {+ enumerable: true,+ get: () => {+ reads++;+ return 9;+ },+ });+ const data = Object.create(null);+ data[0] = Object.assign(Object.create(null), { 0: cell });+ const testBed = createCompactFormulaTestBed(data);+ try {+ reads = 0;+ const snapshot = testBed.model.tryCreateFormulaDataSnapshot(nodeUtilTypes.isProxy);+ expect(snapshot?.materialize()).toStrictEqual(testBed.model.getFormulaData());+ expect(reads).toBe(0);+ } finally {+ testBed.univer.dispose();+ }+ });++ it('uses unit-array indices without observing an iterator the old getter does not read', () => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=1+2' } } });+ const units = testBed.get(IUniverInstanceService).getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET);+ let calls = 0;+ Object.defineProperty(units, Symbol.iterator, {+ configurable: true,+ get: () => {+ calls++;+ throw new Error('iterator must not be observed');+ },+ });+ try {+ const snapshot = testBed.model.tryCreateFormulaDataSnapshot(nodeUtilTypes.isProxy);+ expect(snapshot?.materialize()).toStrictEqual(testBed.model.getFormulaData());+ expect(calls).toBe(0);+ } finally {+ Reflect.deleteProperty(units, Symbol.iterator);+ testBed.univer.dispose();+ }+ });++ it('reads an own sheet-order constructor exactly as the eager getter does', () => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=1+2' } } });+ const workbook = testBed.get(IUniverInstanceService).getUnit<Workbook>('test')!;+ const order = workbook.getSnapshot().sheetOrder;+ let calls = 0;+ Object.defineProperty(order, 'constructor', {+ configurable: true,+ get: () => {+ calls++;+ return Array;+ },+ });+ try {+ return { data: readFormulaInput(testBed.model, compact), calls };+ } finally {+ Reflect.deleteProperty(order, 'constructor');+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(expected.calls).toBe(1);+ expect(run(true)).toStrictEqual(expected);+ });++ it('preserves custom array species without probing it or repeating getSheets', () => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=1+2' } } });+ const original = Object.getOwnPropertyDescriptor(Array, Symbol.species)!;+ let calls = 0;+ let data: IFormulaData;+ try {+ Object.defineProperty(Array, Symbol.species, {+ configurable: true,+ get: () => {+ calls++;+ return Array;+ },+ });+ data = readFormulaInput(testBed.model, compact);+ } finally {+ Object.defineProperty(Array, Symbol.species, original);+ testBed.univer.dispose();+ }+ return { data, calls };+ };+ const expected = run(false);+ expect(expected.calls).toBe(1);+ expect(run(true)).toStrictEqual(expected);+ });++ it.each(['f', 'si', 'ref'] as const)('reads a %s accessor the same number of times and in the same phase as eager capture', (key) => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=A1' } } });+ const cell = testBed.worksheet.getCellMatrix().getValue(0, 0)!;+ const reads: string[] = [];+ const original = Object.getOwnPropertyDescriptor(cell, key);+ Object.defineProperty(cell, key, {+ configurable: true,+ get: () => {+ reads.push(key);+ return key === 'f' ? '=A1' : key === 'si' ? 'shared' : 'A1';+ },+ });+ try {+ return { data: readFormulaInput(testBed.model, compact), reads };+ } finally {+ if (original) Object.defineProperty(cell, key, original);+ else Reflect.deleteProperty(cell, key);+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(expected.reads).toHaveLength(key === 'ref' ? 1 : 3);+ expect(run(true)).toStrictEqual(expected);+ });++ it.each(['matrix', 'row', 'cell'] as const)('preserves a %s Proxy trap sequence through the original traversal', (kind) => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=A1' } } });+ const matrix = testBed.worksheet.getCellMatrix();+ const raw = matrix.getMatrix();+ const row = raw[0];+ const cell = row[0];+ const traps: string[] = [];+ const proxy = new Proxy(kind === 'matrix' ? raw : kind === 'row' ? row : cell!, {+ get: (target, key, receiver) => {+ traps.push(`get:${String(key)}`);+ return Reflect.get(target, key, receiver);+ },+ ownKeys: (target) => {+ traps.push('ownKeys');+ return Reflect.ownKeys(target);+ },+ getOwnPropertyDescriptor: (target, key) => {+ traps.push(`descriptor:${String(key)}`);+ return Reflect.getOwnPropertyDescriptor(target, key);+ },+ getPrototypeOf: (target) => {+ traps.push('prototype');+ return Reflect.getPrototypeOf(target);+ },+ });+ if (kind === 'matrix') Object.assign(matrix, { _matrix: proxy });+ else if (kind === 'row') raw[0] = proxy as typeof row;+ else row[0] = proxy as ICellData;+ try {+ return { data: readFormulaInput(testBed.model, compact), traps };+ } finally {+ Object.assign(matrix, { _matrix: raw });+ raw[0] = row;+ row[0] = cell;+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(expected.traps.length).toBeGreaterThan(0);+ expect(run(true)).toStrictEqual(expected);+ });++ it('captures shared formulas and array metadata without replaying source reads', () => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({+ 0: { 0: { f: '=1' }, 1: { si: 'late' }, 2: { si: 'missing' } },+ 1: { 1: { f: '=A2+1', si: 'late' } },+ 3: { 0: { f: '={1;2}', ref: 'A4:A5', v: 1 } as ICellData, 1: { f: '=4' } },+ 4: { 0: { v: 2 } },+ });+ try {+ const data = readFormulaInput(testBed.model, compact);+ return {+ data,+ anchors: Object.getOwnPropertyDescriptor(testBed.model, '_formulaIdMapData')!.value,+ arrays: testBed.model.getArrayFormulaRange(),+ arrayCells: testBed.model.getArrayFormulaCellData(),+ };+ } finally {+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(expected.data.test!.sheet1![0][1]).toEqual({ f: '=A2+1', si: 'late', x: 0, y: -1 });+ expect(expected.data.test!.sheet1![0][2]).toBeUndefined();+ expect(expected.arrays.test?.sheet1?.[3]?.[0]).toMatchObject({ startRow: 3, endRow: 4 });+ expect(expected.arrayCells.test?.sheet1?.[4]?.[0]?.v).toBe(2);+ expect(run(true)).toStrictEqual(expected);+ });++ it('does not reread getter values when a late shared formula changes the output representation', () => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=PREFIX()' }, 1: {} } });+ const cell = testBed.worksheet.getCellMatrix().getValue(0, 1)!;+ const reads: string[] = [];+ let formulaReads = 0;+ let idReads = 0;+ Object.defineProperties(cell, {+ f: {+ configurable: true,+ get: () => {+ reads.push('f');+ return `=${++formulaReads}`;+ },+ },+ si: {+ configurable: true,+ get: () => {+ reads.push('si');+ return ++idReads === 3 ? 'late' : '';+ },+ },+ ref: {+ configurable: true,+ get: () => {+ reads.push('ref');+ return undefined;+ },+ },+ });+ try {+ return { data: readFormulaInput(testBed.model, compact), reads };+ } finally {+ Reflect.deleteProperty(cell, 'f');+ Reflect.deleteProperty(cell, 'si');+ Reflect.deleteProperty(cell, 'ref');+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(expected.reads).toEqual(['si', 'f', 'ref', 'f', 'si', 'f', 'si']);+ expect(expected.data.test!.sheet1![0][1]).toEqual({ f: '=3', si: 'late' });+ expect(run(true)).toStrictEqual(expected);+ });++ it('preserves getter edits to cells later in each traversal pass', () => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: {}, 1: {} } });+ const row = testBed.worksheet.getCellMatrix().getMatrix()[0];+ const reads: string[] = [];+ let laterFormula = '=0';+ let changes = 0;+ Object.defineProperty(row[0], 'f', {+ configurable: true,+ get: () => {+ reads.push('first');+ laterFormula = `=${++changes}`;+ return '=FIRST()';+ },+ });+ Object.defineProperty(row[1], 'f', {+ configurable: true,+ get: () => {+ reads.push(`later:${laterFormula}`);+ return laterFormula;+ },+ });+ try {+ return { data: readFormulaInput(testBed.model, compact), reads };+ } finally {+ Reflect.deleteProperty(row[0]!, 'f');+ Reflect.deleteProperty(row[1]!, 'f');+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(expected.reads).toEqual(['first', 'later:=1', 'first', 'later:=2', 'first', 'later:=3']);+ expect(expected.data.test!.sheet1![0][1]?.f).toBe('=3');+ expect(run(true)).toStrictEqual(expected);+ });++ it('preserves earlier values when duplicate sheet ids merge a later partial traversal', () => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=SOURCE()' } } });+ const workbook = testBed.get(IUniverInstanceService).getUnit<Workbook>('test')!;+ workbook.getSnapshot().sheetOrder.splice(1, 0, 'sheet1');+ const matrix = testBed.worksheet.getCellMatrix();+ let calls = 0;+ const override = vi.spyOn(matrix, 'forValue').mockImplementation((callback) => {+ const capture = Math.floor(calls++ / 3);+ callback(0, 0, { f: `=${capture + 1}` });+ if (capture === 0) callback(0, 1, { f: '=KEEP()' });+ return matrix;+ });+ try {+ return { data: readFormulaInput(testBed.model, compact), calls };+ } finally {+ override.mockRestore();+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(expected.calls).toBe(6);+ expect(expected.data.test!.sheet1![0]).toEqual({ 0: { f: '=2' }, 1: { f: '=KEEP()' } });+ expect(run(true)).toStrictEqual(expected);+ });++ it.each(['repeated', 'reversed', 'outside-uint32'] as const)('preserves %s coordinates from a custom source traversal', (kind) => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=SOURCE()' } } });+ const matrix = testBed.worksheet.getCellMatrix();+ const events: number[] = [];+ const coordinates = kind === 'repeated'+ ? [[0, 0], [0, 0]]+ : kind === 'reversed' ? [[1, 1], [0, 0]] : [[0, 0], [0x1_0000_0000, 1]];+ const override = vi.spyOn(matrix, 'forValue').mockImplementation((callback) => {+ events.push(events.length);+ for (let index = 0; index < coordinates.length; index++) {+ const [row, column] = coordinates[index];+ if (callback(row, column, { f: `=${index + 1}` }) === false) break;+ }+ return matrix;+ });+ try {+ return { data: readFormulaInput(testBed.model, compact), events };+ } finally {+ override.mockRestore();+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(expected.events).toEqual([0, 1, 2]);+ expect(run(true)).toStrictEqual(expected);+ });++ it.each(['initial', 'during-capture'] as const)('preserves String tag classification when customized %s', (timing) => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=1' }, 1: {} } });+ const cell = testBed.worksheet.getCellMatrix().getValue(0, 1)!;+ const original = Object.getOwnPropertyDescriptor(String.prototype, Symbol.toStringTag);+ const classifications: string[] = [];+ let reads = 0;+ let data: IFormulaData | undefined;+ const installTag = () => {+ // eslint-disable-next-line no-extend-native -- Restore this classification fixture before assertions and disposal.+ Object.defineProperty(String.prototype, Symbol.toStringTag, {+ configurable: true,+ get() {+ classifications.push(String.prototype.valueOf.call(this));+ return 'String';+ },+ });+ };+ Object.defineProperty(cell, 'f', {+ configurable: true,+ get: () => {+ reads++;+ if (timing === 'during-capture' && reads === 3) installTag();+ return '=2';+ },+ });+ try {+ if (timing === 'initial') installTag();+ data = compact+ ? testBed.model.tryCreateFormulaDataSnapshot(nodeUtilTypes.isProxy)?.materialize()+ : testBed.model.getFormulaData();+ } finally {+ // eslint-disable-next-line no-extend-native -- Restore the original global descriptor before assertions and disposal.+ if (original) Object.defineProperty(String.prototype, Symbol.toStringTag, original);+ else Reflect.deleteProperty(String.prototype, Symbol.toStringTag);+ Reflect.deleteProperty(cell, 'f');+ testBed.univer.dispose();+ }+ return { data, reads, classifications };+ };+ const expected = run(false);+ expect(expected.data!.test!.sheet1![0][1]).toEqual({ f: '=2' });+ expect(expected.reads).toBe(3);+ expect(expected.classifications).toEqual(timing === 'initial'+ ? ['=1', '=2', '=1', '=2', '=1', '', '=2', '', '', '']+ : ['=2', '', '', '']);+ expect(run(true)).toStrictEqual(expected);+ });++ it('preserves boxed formula strings after a compact prefix', () => {+ const run = (compact: boolean) => {+ const boxedFormula = new Object('=BOXED()') as string;+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=PREFIX()' }, 1: { f: boxedFormula } } });+ try {+ return readFormulaInput(testBed.model, compact);+ } finally {+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(typeof expected.test!.sheet1![0][1]?.f).toBe('object');+ expect(run(true)).toStrictEqual(expected);+ });++ it('preserves formulas across chunk boundaries and multiple sheets after edits and disposal', () => {+ const cellData: IObjectMatrixPrimitiveType<ICellData> = {};+ for (let index = 0; index < 8_193; index++) {+ const row = Math.floor(index / 3);+ cellData[row] ??= {};+ cellData[row][index % 3] = { f: `=${index}+1` };+ }+ const testBed = createCompactFormulaTestBed(cellData);+ const secondMatrix = testBed.get(IUniverInstanceService).getUnit<Workbook>('test')!.getSheetBySheetId('empty')!.getCellMatrix();+ secondMatrix.setValue(2, 2, { f: '=SECOND()' });+ const expected = testBed.model.getFormulaData();+ const snapshot = testBed.model.tryCreateFormulaDataSnapshot(nodeUtilTypes.isProxy);+ expect(snapshot).toBeDefined();+ testBed.worksheet.getCellMatrix().realDeleteValue(0, 0);+ secondMatrix.setValue(2, 2, { f: '=EDITED()' });+ testBed.univer.dispose();+ expect(snapshot!.materialize()).toStrictEqual(expected);+ expect(snapshot!.materialize()).toBe(snapshot!.materialize());+ });++ it('preserves numeric enumeration order when draining captured chunks, including the Uint32 boundary', () => {+ const last = 0xFFFF_FFFF;+ const testBed = createCompactFormulaTestBed({+ 0: { 0: { f: '=1' }, [last]: { f: '=2' } },+ [last]: { 0: { f: '=3' }, [last]: { f: '=4' } },+ });+ try {+ const expected = testBed.model.getFormulaData();+ const actual = readFormulaInput(testBed.model, true);+ expect(actual).toStrictEqual(expected);+ expect(JSON.stringify(actual)).toBe(JSON.stringify(expected));+ } finally {+ testBed.univer.dispose();+ }+ });++ it('uses normal instance methods in their original order without requiring a proxy classifier', () => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=1+2' } } });+ const worksheet = testBed.worksheet;+ const getMatrix = worksheet.getCellMatrix.bind(worksheet);+ const getId = worksheet.getSheetId.bind(worksheet);+ const events: string[] = [];+ const matrixMethod = vi.spyOn(worksheet, 'getCellMatrix').mockImplementation(() => {+ events.push('matrix');+ return getMatrix();+ });+ const idMethod = vi.spyOn(worksheet, 'getSheetId').mockImplementation(() => {+ events.push('id');+ return getId();+ });+ try {+ const snapshot = compact ? testBed.model.tryCreateFormulaDataSnapshot() : undefined;+ if (compact) expect(snapshot).toBeDefined();+ return { data: compact ? snapshot!.materialize() : testBed.model.getFormulaData(), events };+ } finally {+ matrixMethod.mockRestore();+ idMethod.mockRestore();+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(expected.events).toEqual(['matrix', 'id']);+ expect(run(true)).toStrictEqual(expected);+ });++ it('preserves the original numeric-key coercion for noncanonical source keys', () => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 1: { 0: { f: '=CANONICAL()' } } });+ const raw = testBed.worksheet.getCellMatrix().getMatrix();+ Object.assign(raw, { '01': { 0: { f: '=ALIAS()' } } });+ try {+ return readFormulaInput(testBed.model, compact);+ } finally {+ Reflect.deleteProperty(raw, '01');+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(expected.test!.sheet1![1][0]?.f).toBe('=CANONICAL()');+ expect(run(true)).toStrictEqual(expected);+ });++ it('keeps mixed Sheets and Base formula inputs unchanged', () => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=1+2' } } });+ testBed.get(IUniverInstanceService).registerCtorForType(UniverInstanceType.UNIVER_BASE, BaseDataModel);+ testBed.univer.createUnit(UniverInstanceType.UNIVER_BASE, Tools.deepClone(TEST_BASE_DATA));+ try {+ return readFormulaInput(testBed.model, compact);+ } finally {+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(expected['base-test']!['table-main']![0][7]?.si).toBe('total');+ expect(run(true)).toStrictEqual(expected);+ });++ it('keeps existing array metadata when capturing subsequent calculations', () => {+ const run = (compact: boolean) => {+ const testBed = createCompactFormulaTestBed({ 0: { 0: { f: '=A1' } } });+ const arrays = { test: { sheet1: { 0: { 0: { startRow: 0, endRow: 1, startColumn: 0, endColumn: 0 } } } } };+ testBed.model.setArrayFormulaRange(arrays);+ testBed.model.setArrayFormulaCellData({ test: { sheet1: { 1: { 0: { v: 7 } } } } });+ try {+ return {+ data: readFormulaInput(testBed.model, compact),+ arrays: testBed.model.getArrayFormulaRange(),+ arrayCells: testBed.model.getArrayFormulaCellData(),+ };+ } finally {+ testBed.univer.dispose();+ }+ };+ const expected = run(false);+ expect(expected.arrayCells.test?.sheet1?.[1]?.[0]?.v).toBe(7);+ expect(run(true)).toStrictEqual(expected);+ });+});+describe('Test formula data model', () => {describe('formulaDataModel function', () => {let univer: Univer;@@ -1267,6 +2101,127 @@ describe('Test formula data model', () => {univer.dispose();});+ it('preserves empty and whitespace semantics when scanning formulas and shared ids', () => {+ const result = formulaDataModel.initSheetFormulaData({}, 'unit', 'sheet', new ObjectMatrix<ICellData>({+ 0: {+ 0: { f: '=1', si: '' },+ 1: { f: '=' },+ 2: { f: ' =1' },+ 3: { f: '', si: '' },+ 4: { f: '=2', si: ' ' },+ 5: { si: ' ' },+ 6: { f: '=3', si: '0' },+ 7: { si: '0' },+ 8: { v: 1 },+ },+ }));+ expect(result.unit?.sheet?.[0]).toEqual({+ 0: { f: '=1' },+ 4: { f: '=2', si: ' ' },+ 5: { f: '=2', si: ' ', x: 1, y: 0 },+ 6: { f: '=3', si: '0' },+ 7: { f: '=3', si: '0', x: 1, y: 0 },+ });+ });++ it('keeps core formula predicate behavior for nonprimitive values', () => {+ const values: unknown[] = [+ new Object('=A1'),+ new Object('='),+ Symbol('=A1'),+ 1,+ null,+ Object.assign(Object.create(null), { [Symbol.toStringTag]: 'Other' }),+ {+ [Symbol.toStringTag]: 'String',+ length: 3,+ substring: (start: number, end: number) => '=A1'.substring(start, end),+ },+ new Proxy({ [Symbol.toStringTag]: 'Other' }, {}),+ ];+ for (const value of values) {+ const expected = isFormulaString(value || '');+ const result = formulaDataModel.initSheetFormulaData({}, 'unit', 'sheet', new ObjectMatrix<ICellData>({+ 0: { 0: { f: value } as ICellData },+ }));+ if (expected) {+ expect(result.unit?.sheet?.[0]?.[0]?.f).toBe(value);+ } else {+ expect(result.unit?.sheet?.[0]).toBeUndefined();+ }+ }+ });++ it('keeps core shared id predicate behavior for nonprimitive values', () => {+ const values: unknown[] = [+ new Object('shared'),+ new Object(''),+ Symbol('shared'),+ 1,+ null,+ { [Symbol.toStringTag]: 'String', length: 1, toString: () => 'tagged-id' },+ new Proxy({ [Symbol.toStringTag]: 'Other' }, {}),+ ];+ for (const value of values) {+ const expected = isFormulaId(value || '');+ const result = formulaDataModel.initSheetFormulaData({}, 'unit', 'sheet', new ObjectMatrix<ICellData>({+ 0: { 0: { f: '=1', si: value } as ICellData },+ }));+ const cell = result.unit?.sheet?.[0]?.[0];+ expect(cell?.f).toBe('=1');+ expect(cell?.si).toBe(expected ? value : undefined);+ }+ });++ it('preserves errors raised by nonprimitive formula and id predicates', () => {+ const failure = new Error('tag getter');+ const throwing = new Proxy({}, {+ get(target, key, receiver) {+ if (key === Symbol.toStringTag) throw failure;+ return Reflect.get(target, key, receiver);+ },+ });+ const invalidStringProxy = new Proxy(new Object('=1'), {+ get(target, key, receiver) {+ return key === Symbol.toStringTag ? 'String' : Reflect.get(target, key, receiver);+ },+ });+ expect(() => isFormulaString(invalidStringProxy)).toThrow(TypeError);+ expect(() => formulaDataModel.initSheetFormulaData({}, 'unit', 'sheet', new ObjectMatrix<ICellData>({+ 0: { 0: { f: invalidStringProxy } as ICellData },+ }))).toThrow(TypeError);+ for (const cell of [{ f: throwing }, { f: '=1', si: throwing }]) {+ expect(() => formulaDataModel.initSheetFormulaData({}, 'unit', 'sheet', new ObjectMatrix<ICellData>({+ 0: { 0: cell as ICellData },+ }))).toThrow(failure);+ }+ });++ it('falls back when primitive strings have a custom prototype tag', () => {+ const previous = Object.getOwnPropertyDescriptor(String.prototype, Symbol.toStringTag);+ let result: IFormulaData;+ let tagReads = 0;+ try {+ // eslint-disable-next-line no-extend-native -- This adversarial fixture restores the native descriptor in finally.+ Object.defineProperty(String.prototype, Symbol.toStringTag, {+ configurable: true,+ get() {+ tagReads += 1;+ return 'CustomString';+ },+ });+ result = formulaDataModel.initSheetFormulaData({}, 'unit', 'sheet', new ObjectMatrix<ICellData>({+ 0: { 0: { f: '=1', si: 'shared' } },+ }));+ } finally {+ // eslint-disable-next-line no-extend-native -- Restore the native descriptor changed by this adversarial fixture.+ if (previous) Object.defineProperty(String.prototype, Symbol.toStringTag, previous);+ else Reflect.deleteProperty(String.prototype, Symbol.toStringTag);+ }+ expect(result!.unit?.sheet?.[0]).toBeUndefined();+ expect(tagReads).toBe(2);+ });+it('propagates explicit implicit intersection to shared formula followers', () => {const formula = '=RANK(E2,IF(@A$2:A$4=A2,E$2:E$4),0)';const result = formulaDataModel.initSheetFormulaData(diff --git a/packages/engine-formula/src/models/formula-data-snapshot.ts b/packages/engine-formula/src/models/formula-data-snapshot.tsnew file mode 100644index 0000000000..bf375b3000--- /dev/null+++ b/packages/engine-formula/src/models/formula-data-snapshot.ts@@ -0,0 +1,26 @@+/**+ * 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 { IFormulaData } from '../basics/common';++/**+ * Internal calculation-engine input; not an application or Facade API.+ * Ephemeral calculation input, not a serialized Workbook snapshot.+ * Materialization returns an owned, mutable formula DTO cached for subsequent reads.+ */+export interface IFormulaDataSnapshot {+ materialize(): IFormulaData;+}diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.tsindex 03f69289e2..b0ab70e5cc 100644--- a/packages/engine-formula/src/models/formula-data.model.ts+++ b/packages/engine-formula/src/models/formula-data.model.ts@@ -15,6 +15,7 @@*/import type { BaseCellValue, BaseDataModel, IBaseCellData, IBaseSnapshot, ICellData, IFieldSnapshot, IObjectArrayPrimitiveType, IObjectMatrixPrimitiveType, IRange, IRowData, ITableSnapshot, IUnitRange, Nullable, Workbook } from '@univerjs/core';+import { BooleanNumber, CellValueType, createBaseFormulaTableNameMap, Disposable, getBaseFormulaTableName, Inject, isFormulaId, isFormulaString, IUniverInstanceService, ObjectMatrix, RANGE_TYPE, Styles, UniverInstanceType } from '@univerjs/core';import type {IArrayFormulaRangeType,IArrayFormulaUnitCellType,@@ -33,7 +34,7 @@ import type {} from '../basics/common';import type { IImageFormulaInfo } from '../engine/value-object/primitive-object';import type { ICircularReference } from '../services/runtime.service';-import { BooleanNumber, CellValueType, createBaseFormulaTableNameMap, Disposable, getBaseFormulaTableName, Inject, isFormulaId, isFormulaString, IUniverInstanceService, ObjectMatrix, RANGE_TYPE, Styles, UniverInstanceType } from '@univerjs/core';+import type { IFormulaDataSnapshot } from './formula-data-snapshot';import { copyUnitData } from '../basics/runtime';import { LexerTreeBuilder } from '../engine/analysis/lexer-tree-builder';import { deserializeRangeWithSheet } from '../engine/utils/reference';@@ -44,6 +45,104 @@ export interface IRangeChange {newCell: IRange | null;}+const COMPACT_FORMULA_CHUNK_SIZE = 4096;+const SNAPSHOT_OUTPUT_METHODS = [+ 'getMatrix',+ 'forValue',+ 'setValue',+ 'getRowOrCreate',+ 'getRow',+ 'realDeleteValue',+ '_setOriginValue',+].map((name) => [name, Object.getOwnPropertyDescriptor(ObjectMatrix.prototype, name)?.value] as const);++interface ICompactFormulaChunk {+ coordinates: Uint32Array;+ formulas: string[];+}++type CompactFormulaData = Record<string, Record<string, ICompactFormulaChunk[]>>;++function materializeCompactFormulaSheet(+ chunks: ICompactFormulaChunk[],+ matrix: IObjectMatrixPrimitiveType<Nullable<IFormulaDataItem>>+): void {+ let previousRow: number | undefined;+ let row: Record<number, Nullable<IFormulaDataItem>> | undefined;+ // Numeric coordinates retain their enumeration order while consumed chunks can be released.+ while (chunks.length > 0) {+ const chunk = chunks.pop()!;+ for (let index = chunk.formulas.length - 1; index >= 0; index--) {+ const rowNumber = chunk.coordinates[index * 2];+ if (previousRow !== rowNumber) {+ if (row) Object.setPrototypeOf(row, Object.prototype);+ row = Object.create(null);+ matrix[rowNumber] = row!;+ previousRow = rowNumber;+ }+ row![chunk.coordinates[index * 2 + 1]] = { f: chunk.formulas[index] };+ }+ }+ // Captured coordinates were own data properties before any later prototype setters.+ if (row) Object.setPrototypeOf(row, Object.prototype);+}++class CompactFormulaDataSnapshot implements IFormulaDataSnapshot {+ constructor(+ private _data: IFormulaData,+ private _compactData: CompactFormulaData | undefined+ ) {}++ materialize(): IFormulaData {+ const compactData = this._compactData;+ if (compactData) {+ for (const unitId in compactData) {+ for (const sheetId in compactData[unitId]) {+ materializeCompactFormulaSheet(compactData[unitId][sheetId], this._data[unitId]![sheetId]!);+ }+ }+ this._compactData = undefined;+ }+ return this._data;+ }+}++function supportsCompactFormulaSnapshot(model: FormulaDataModel, isProxy?: (value: unknown) => boolean): boolean {+ if (+ isProxy?.(model) || Object.getPrototypeOf(model) !== FormulaDataModel.prototype ||+ Object.getPrototypeOf(ObjectMatrix.prototype) !== Object.prototype+ ) {+ return false;+ }+ for (let index = 0; index < SNAPSHOT_MODEL_METHODS.length; index++) {+ const name = SNAPSHOT_MODEL_METHODS[index][0];+ const method = SNAPSHOT_MODEL_METHODS[index][1];+ if (+ typeof method !== 'function' || Object.prototype.hasOwnProperty.call(model, name) ||+ Object.getOwnPropertyDescriptor(FormulaDataModel.prototype, name)?.value !== method+ ) {+ return false;+ }+ }+ // Compact output replaces ordinary DTO writes, not customized output-matrix behavior.+ for (let index = 0; index < SNAPSHOT_OUTPUT_METHODS.length; index++) {+ const name = SNAPSHOT_OUTPUT_METHODS[index][0];+ const method = SNAPSHOT_OUTPUT_METHODS[index][1];+ if (typeof method !== 'function' || Object.getOwnPropertyDescriptor(ObjectMatrix.prototype, name)?.value !== method) return false;+ }+ const prototypeKeys = Object.getOwnPropertyNames(Object.prototype);+ for (let index = 0; index < prototypeKeys.length; index++) {+ const key = prototypeKeys[index];+ if (+ !Number.isNaN(Number(key)) || key === 'f' || key === 'si' ||+ Object.getOwnPropertyDescriptor(Object.prototype, key)?.enumerable+ ) {+ return false;+ }+ }+ return true;+}+export class FormulaDataModel extends Disposable {private _circularReferences = new Map<string, ICircularReference>();@@ -200,12 +299,17 @@ export class FormulaDataModel extends Disposable {}getFormulaData(): IFormulaData {+ return this._collectFormulaData();+ }++ private _collectFormulaData(compactData?: CompactFormulaData): IFormulaData {const formulaData: IFormulaData = Object.create(null);const allSheets = this._univerInstanceService.getAllUnitsForType<Workbook>(UniverInstanceType.UNIVER_SHEET);for (let i = 0; i < allSheets.length; i++) {const workbook = allSheets[i];const unitId = workbook.getUnitId();formulaData[unitId] = Object.create(null);+ if (compactData) compactData[unitId] = Object.create(null);const worksheets = workbook.getSheets();for (let j = 0; j < worksheets.length; j++) {@@ -213,8 +317,25 @@ export class FormulaDataModel extends Disposable {const cellMatrix = worksheet.getCellMatrix();const sheetId = worksheet.getSheetId();+ const previousChunks = compactData?.[unitId][sheetId];+ if (previousChunks) {+ materializeCompactFormulaSheet(previousChunks, formulaData[unitId]![sheetId]!);+ delete compactData![unitId][sheetId];+ }this._initSheetArrayFormulaData(unitId, sheetId, cellMatrix);- this.initSheetFormulaData(formulaData, unitId, sheetId, cellMatrix);+ if (compactData) {+ const compact = !Object.prototype.hasOwnProperty.call(formulaData[unitId]!, sheetId);+ const result = buildSheetFormulaData(formulaData, unitId, sheetId, cellMatrix, compact);+ this._formulaIdMapData[unitId] ??= Object.create(null);+ this._formulaIdMapData[unitId]![sheetId] = result.formulaIdMap;+ if (result.compactChunks) {+ compactData[unitId][sheetId] = result.compactChunks;+ } else {+ delete compactData[unitId][sheetId];+ }+ } else {+ this.initSheetFormulaData(formulaData, unitId, sheetId, cellMatrix);+ }}}@@ -224,6 +345,7 @@ export class FormulaDataModel extends Disposable {const snapshot = base.getSnapshot();const unitId = base.getUnitId();formulaData[unitId] = Object.create(null);+ if (compactData) delete compactData[unitId];const tables = Object.values(snapshot.tables);const formulaTableNames = createBaseFormulaTableNameMap(snapshot);@@ -271,6 +393,18 @@ export class FormulaDataModel extends Disposable {return formulaData;}+ /**+ * Internal calculation-engine capture; customized model methods retain the eager DTO path.+ * Reuse ordinary model traversal and metadata preparation, deferring per-formula DTO objects where possible.+ * The optional classifier is retained for cooperating engines that reject a proxied model before capture.+ */+ tryCreateFormulaDataSnapshot(isProxy?: (value: unknown) => boolean): IFormulaDataSnapshot | undefined {+ if (!supportsCompactFormulaSnapshot(this, isProxy)) return undefined;+ const compactData: CompactFormulaData = Object.create(null);+ const formulaData = this._collectFormulaData(compactData);+ return new CompactFormulaDataSnapshot(formulaData, compactData);+ }+initSheetFormulaData(formulaData: IFormulaData,unitId: string,@@ -939,11 +1073,16 @@ export class FormulaDataModel extends Disposable {}}+const SNAPSHOT_MODEL_METHODS = ['getFormulaData', 'initSheetFormulaData', '_initSheetArrayFormulaData'].map((name) =>+ [name, Object.getOwnPropertyDescriptor(FormulaDataModel.prototype, name)?.value] as const+);+function buildSheetFormulaData(formulaData: IFormulaData,unitId: string,sheetId: string,- cellMatrix: ObjectMatrix<Nullable<ICellData>>+ cellMatrix: ObjectMatrix<Nullable<ICellData>>,+ compact = false) {const unitData = Object.assign(Object.create(null),@@ -956,6 +1095,9 @@ function buildSheetFormulaData(const formulaIdMap: Record<string, IFormulaIdMap> = Object.create(null); // Connect the formula and IDconst sheetFormulaDataMatrix = new ObjectMatrix<Nullable<IFormulaDataItem>>(unitData[sheetId]);+ let compactChunks: ICompactFormulaChunk[] | undefined = compact ? [] : undefined;+ let previousRow = -1;+ let previousColumn = -1;cellMatrix.forValue((r, c, cell) => {const formulaString = cell?.f || '';@@ -964,6 +1106,35 @@ function buildSheetFormulaData(const checkFormulaString = isFormulaString(formulaString);const checkFormulaId = isFormulaId(formulaId);+ if (compactChunks) {+ const ordinaryFormula = typeof formulaString === 'string' && formulaId === '';+ const orderedCoordinates = r > previousRow || (r === previousRow && c > previousColumn);+ if (+ ordinaryFormula && orderedCoordinates &&+ Number.isInteger(r) && r >= 0 && r <= 0xFFFF_FFFF &&+ Number.isInteger(c) && c >= 0 && c <= 0xFFFF_FFFF+ ) {+ previousRow = r;+ previousColumn = c;+ if (checkFormulaString) {+ let chunk = compactChunks[compactChunks.length - 1];+ if (!chunk || chunk.formulas.length * 2 === chunk.coordinates.length) {+ const size = compactChunks.length === 0 ? 128 : COMPACT_FORMULA_CHUNK_SIZE;+ chunk = { coordinates: new Uint32Array(size * 2), formulas: [] };+ compactChunks.push(chunk);+ }+ const index = chunk.formulas.length;+ chunk.coordinates[index * 2] = r;+ chunk.coordinates[index * 2 + 1] = c;+ chunk.formulas.push(formulaString);+ }+ return;+ }+ // Continue from captured values; rereading the source would repeat getters and callbacks.+ materializeCompactFormulaSheet(compactChunks, sheetFormulaDataMatrix.getMatrix());+ compactChunks = undefined;+ }+if (checkFormulaString && checkFormulaId) {sheetFormulaDataMatrix.setValue(r, c, { f: formulaString, si: formulaId });const formulaInfo = { f: formulaString, r, c };@@ -975,29 +1146,39 @@ function buildSheetFormulaData(}});- sheetFormulaDataMatrix.forValue((r, c, cell) => {- const formulaString = cell?.f || '';- const formulaId = cell?.si || '';+ if (+ compactChunks &&+ (Object.getPrototypeOf(String.prototype) !== Object.prototype || Symbol.toStringTag in String.prototype)+ ) {+ materializeCompactFormulaSheet(compactChunks, sheetFormulaDataMatrix.getMatrix());+ compactChunks = undefined;+ }- if (isFormulaId(formulaId) && !isFormulaString(formulaString)) {- const formulaInfo = formulaIdMap[formulaId];- if (formulaInfo) {- const x = c - formulaInfo.c;- const y = r - formulaInfo.r;- const f = formulaInfo.f;- sheetFormulaDataMatrix.setValue(r, c, {- f,- si: formulaId,- x,- y,- });- } else {- // If the formula ID is not found in the formula ID map, delete the formula ID.- // Prevent IDs without corresponding formulas from appearing- sheetFormulaDataMatrix.realDeleteValue(r, c);+ if (!compactChunks) {+ sheetFormulaDataMatrix.forValue((r, c, cell) => {+ const formulaString = cell?.f || '';+ const formulaId = cell?.si || '';++ if (isFormulaId(formulaId) && !isFormulaString(formulaString)) {+ const formulaInfo = formulaIdMap[formulaId];+ if (formulaInfo) {+ const x = c - formulaInfo.c;+ const y = r - formulaInfo.r;+ const f = formulaInfo.f;+ sheetFormulaDataMatrix.setValue(r, c, {+ f,+ si: formulaId,+ x,+ y,+ });+ } else {+ // If the formula ID is not found in the formula ID map, delete the formula ID.+ // Prevent IDs without corresponding formulas from appearing+ sheetFormulaDataMatrix.realDeleteValue(r, c);+ }}- }- });+ });+ }const newSheetFormulaData = sheetFormulaDataMatrix.getMatrix(); // Don't use clone, otherwise it will cause performance problems@@ -1008,6 +1189,7 @@ function buildSheetFormulaData(},},formulaIdMap,+ compactChunks,};}diff --git a/packages/engine-formula/src/plugin.ts b/packages/engine-formula/src/plugin.tsindex 8934a0c626..49b7447dc4 100644--- a/packages/engine-formula/src/plugin.ts+++ b/packages/engine-formula/src/plugin.ts@@ -14,8 +14,17 @@* limitations under the License.*/-import type { Dependency } from '@univerjs/core';-import { IConfigService, Inject, Injector, merge, Plugin, touchDependencies } from '@univerjs/core';+import type { Dependency, Workbook } from '@univerjs/core';+import {+ IConfigService,+ Inject,+ Injector,+ IUniverInstanceService,+ merge,+ Plugin,+ touchDependencies,+ UniverInstanceType,+} from '@univerjs/core';import type { IUniverEngineFormulaConfig } from './config/config';import pkg from '../package.json';import { defaultPluginConfig, ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from './config/config';@@ -58,7 +67,9 @@ import {FeatureCalculationManagerService,IFeatureCalculationManagerService,} from './services/feature-calculation-manager.service';+import { FormulaCacheService } from './services/formula-cache.service';import { FormulaCalculationTriggerService } from './services/formula-calculation-trigger.service';+import { FormulaResultService } from './services/formula-result.service';import { DescriptionService, IDescriptionService } from './services/formula/description.service';import { FormulaCalculationSessionService } from './services/formula/formula-calculation-session.service';import { IRegisterFunctionService, RegisterFunctionService } from './services/formula/register-function.service';@@ -73,7 +84,10 @@ import { RegisterOtherFormulaService } from './services/register-other-formula.simport { FormulaRuntimeService, IFormulaRuntimeService } from './services/runtime.service';import { ISheetRowFilteredService, SheetRowFilteredService } from './services/sheet-row-filtered.service';import { ISuperTableService, SuperTableService } from './services/super-table.service';-import { FormulaUnitReferenceResolver, IFormulaUnitReferenceResolver } from './services/unit-reference-resolver.service';+import {+ FormulaUnitReferenceResolver,+ IFormulaUnitReferenceResolver,+} from './services/unit-reference-resolver.service';export class UniverFormulaEnginePlugin extends Plugin {static override pluginName = 'UNIVER_ENGINE_FORMULA_PLUGIN';@@ -130,6 +144,11 @@ export class UniverFormulaEnginePlugin extends Plugin {}private _initialize() {+ this._injector.add([FormulaCacheService]);+ const cacheService = this._injector.get(FormulaCacheService);+ cacheService.disposeWithMe(this._injector.get(IUniverInstanceService)+ .getTypeOfUnitDisposed$<Workbook>(UniverInstanceType.UNIVER_SHEET)+ .subscribe((workbook) => cacheService.clearUnit(workbook.getUnitId())));const shouldPerformComputing = !this._config.notExecuteFormula;// worker and main threadconst dependencies: Dependency[] = [@@ -160,6 +179,7 @@ export class UniverFormulaEnginePlugin extends Plugin {if (shouldPerformComputing) {dependencies.push(// Services+ [FormulaResultService],[IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }],[IFormulaRuntimeService, { useClass: FormulaRuntimeService }],[IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }],diff --git a/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts b/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.tsindex fbb7db3325..4b3747fda9 100644--- a/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/calculate-formula.service.spec.ts@@ -15,8 +15,8 @@*/import type { ICellData } from '@univerjs/core';-import { IConfigService, Injector, ObjectMatrix } from '@univerjs/core';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { IConfigService, Inject, Injector, ObjectMatrix } from '@univerjs/core';+import { describe, expect, it, vi } from 'vitest';import type { IFormulaDatasetConfig } from '../../basics/common';import type { IAllRuntimeData } from '../runtime.service';import { ErrorType } from '../../basics/error-type';@@ -25,13 +25,14 @@ import { Lexer } from '../../engine/analysis/lexer';import { AstTreeBuilder } from '../../engine/analysis/parser';import { IFormulaDependencyGenerator } from '../../engine/dependency/formula-dependency';import { Interpreter } from '../../engine/interpreter/interpreter';-import { FORMULA_REF_TO_ARRAY_CACHE } from '../../engine/reference-object/base-reference-object';import { createFunctionTestBed } from '../../functions/__tests__/create-function-test-bed';import { AsyncCustomFunction } from '../../functions/custom-function';import { CalculateFormulaService, ICalculateFormulaService } from '../calculate-formula.service';import { IFormulaCurrentConfigService } from '../current-data.service';import { DependencyManagerService, IDependencyManagerService } from '../dependency-manager.service';import { FeatureCalculationManagerService, IFeatureCalculationManagerService } from '../feature-calculation-manager.service';+import { FormulaCacheService } from '../formula-cache.service';+import { FormulaResultService } from '../formula-result.service';import { IFunctionService } from '../function.service';import { FormulaExecutedStateType, FormulaExecuteStageType, IFormulaRuntimeService } from '../runtime.service';@@ -184,10 +185,14 @@ function createService() {}class TestAstTreeBuilder {+ constructor(@Inject(FormulaCacheService) readonly cacheService: FormulaCacheService) {}parse = astTreeBuilder.parse;}const injector = new Injector();+ injector.add([FormulaCacheService]);+ const formulaResultService = { applyResult: vi.fn(), applyTreeResult: vi.fn() };+ injector.add([FormulaResultService, { useValue: formulaResultService } as never]);injector.add([IConfigService, { useClass: TestConfigService as never }]);injector.add([Lexer, { useClass: TestLexer as never }]);injector.add([IFormulaCurrentConfigService, { useClass: TestCurrentConfigService as never }]);@@ -208,6 +213,7 @@ function createService() {return {service,mocks: {+ formulaResultService,configService,lexer,currentConfigService,@@ -220,8 +226,30 @@ function createService() {}describe('CalculateFormulaService', () => {- beforeEach(() => {- FORMULA_REF_TO_ARRAY_CACHE.clear();+ it('releases runtime data and rejects without a false completion when writeback throws, then calculates again', async () => {+ const { service, mocks } = createService();+ vi.spyOn(service as unknown as { _executeStep(): Promise<void> }, '_executeStep').mockResolvedValue();+ const data = { ...mocks.runtimeService.getAllRuntimeData(), functionsExecutedState: FormulaExecutedStateType.SUCCESS };+ mocks.runtimeService.getAllRuntimeData.mockReturnValue(data);+ mocks.formulaResultService.applyResult.mockRejectedValueOnce(new Error('Writeback failed'));+ const completed: IAllRuntimeData[] = [];+ service.executionCompleteListener$.subscribe((value) => completed.push(value));+ await expect(service.execute({} as never)).rejects.toThrow('Writeback failed');+ expect(completed).toHaveLength(0);+ expect(mocks.runtimeService.reset).toHaveBeenCalledTimes(2);+ await service.execute({} as never);+ expect(completed).toHaveLength(1);+ expect(mocks.formulaResultService.applyResult).toHaveBeenCalledTimes(2);+ });++ it('applies only dependency metadata for a NOT_EXECUTED completion', async () => {+ const { service, mocks } = createService();+ vi.spyOn(service as unknown as { _executeStep(): Promise<void> }, '_executeStep').mockResolvedValue();+ const data = { ...mocks.runtimeService.getAllRuntimeData(), functionsExecutedState: FormulaExecutedStateType.NOT_EXECUTED };+ mocks.runtimeService.getAllRuntimeData.mockReturnValue(data);+ await service.execute({} as never);+ expect(mocks.formulaResultService.applyResult).not.toHaveBeenCalled();+ expect(mocks.formulaResultService.applyTreeResult).toHaveBeenCalledExactlyOnceWith(data);});it('retains a queued scalar source when a preceding asynchronous dependency allows its cell to be cleared', async () => {diff --git a/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts b/packages/engine-formula/src/services/__tests__/current-data.service.spec.tsindex 28cc46c52e..3b907a7a73 100644--- a/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/current-data.service.spec.ts@@ -24,9 +24,10 @@ import {UniverInstanceType,} from '@univerjs/core';import { describe, expect, it, vi } from 'vitest';+import type { IFormulaDatasetConfig } from '../../basics/common';import { createFunctionTestBed } from '../../functions/__tests__/create-function-test-bed';import { FormulaDataModel } from '../../models/formula-data.model';-import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from '../current-data.service';+import { FormulaCurrentConfigService, hasDeferredFormulaDataSnapshot, IFormulaCurrentConfigService } from '../current-data.service';import { ISheetRowFilteredService } from '../sheet-row-filtered.service';function createService(withCurrentWorkbook = true) {@@ -107,7 +108,115 @@ function createService(withCurrentWorkbook = true) {};}+function createSnapshotDataset(): Omit<IFormulaDatasetConfig, 'formulaData'> {+ return {+ allUnitData: {},+ unitStylesData: {},+ unitSheetNameMap: {},+ arrayFormulaCellData: {},+ arrayFormulaRange: {},+ forceCalculate: false,+ dirtyRanges: [],+ dirtyNameMap: {},+ dirtyDefinedNameMap: {},+ dirtyUnitFeatureMap: {},+ dirtyUnitOtherFormulaMap: {},+ };+}+describe('FormulaCurrentConfigService', () => {+ it('materializes captured formulas only for a formula read and caches their mutable owned root', () => {+ const { service, formulaDataModel } = createService();+ const data = { unit: { sheet: { 0: { 1: { f: '=A1+2' } } } } };+ const materialize = vi.fn(() => data);+ expect(hasDeferredFormulaDataSnapshot(service)).toBe(false);+ service.loadWithFormulaDataSnapshot(createSnapshotDataset(), { materialize });+ expect(hasDeferredFormulaDataSnapshot(service)).toBe(true);+ service.getUnitData();+ service.getDirtyData();+ service.getArrayFormulaRange();+ expect(materialize).not.toHaveBeenCalled();+ expect(formulaDataModel.getFormulaData).not.toHaveBeenCalled();+ expect(service.getCalculationGeneration()).toBe(1);+ expect(service.getFormulaData()).toBe(data);+ expect(hasDeferredFormulaDataSnapshot(service)).toBe(false);+ data.unit.sheet[0][1].f = '=LOCAL()';+ expect(service.getFormulaData().unit?.sheet?.[0]?.[1]?.f).toBe('=LOCAL()');+ expect(materialize).toHaveBeenCalledTimes(1);+ });++ it('retires pending snapshots on replacement, explicit registration, lite load and disposal', () => {+ const { service, formulaDataModel } = createService();+ const first = { materialize: vi.fn(() => ({ old: {} })) };+ const secondData = { current: {} };+ const second = { materialize: vi.fn(() => secondData) };+ const config = createSnapshotDataset();+ service.loadWithFormulaDataSnapshot(config, first);+ service.loadWithFormulaDataSnapshot(config, second);+ expect(hasDeferredFormulaDataSnapshot(service)).toBe(true);+ expect(service.getFormulaData()).toBe(secondData);+ expect(hasDeferredFormulaDataSnapshot(service)).toBe(false);+ expect(first.materialize).not.toHaveBeenCalled();+ expect(service.getCalculationGeneration()).toBe(2);++ const unused = { materialize: vi.fn(() => ({ unused: {} })) };+ const registered = { registered: {} };+ service.loadWithFormulaDataSnapshot(config, unused);+ service.registerFormulaData(registered);+ expect(hasDeferredFormulaDataSnapshot(service)).toBe(false);+ expect(service.getFormulaData()).toBe(registered);+ service.loadWithFormulaDataSnapshot(config, unused);+ const explicit = { explicit: {} };+ service.load({ ...config, formulaData: explicit });+ expect(hasDeferredFormulaDataSnapshot(service)).toBe(false);+ expect(service.getFormulaData()).toBe(explicit);+ service.loadWithFormulaDataSnapshot(config, unused);+ service.loadDataLite();+ expect(hasDeferredFormulaDataSnapshot(service)).toBe(false);+ expect(service.getFormulaData()).toEqual({ unitLite: { sheetLite: {} } });+ expect(formulaDataModel.getFormulaData).toHaveBeenCalledTimes(1);+ service.loadWithFormulaDataSnapshot(config, unused);+ service.dispose();+ expect(hasDeferredFormulaDataSnapshot(service)).toBe(false);+ expect(service.getFormulaData()).toEqual({});+ expect(unused.materialize).not.toHaveBeenCalled();+ });++ it('keeps the captured source available if materialization fails before producing a root', () => {+ const { service } = createService();+ const data = { unit: { sheet: {} } };+ const materialize = vi.fn()+ .mockImplementationOnce(() => { throw new Error('materialization failed'); })+ .mockReturnValue(data);+ service.loadWithFormulaDataSnapshot(createSnapshotDataset(), { materialize });+ expect(() => service.getFormulaData()).toThrow('materialization failed');+ expect(hasDeferredFormulaDataSnapshot(service)).toBe(true);+ expect(service.getFormulaData()).toBe(data);+ expect(hasDeferredFormulaDataSnapshot(service)).toBe(false);+ expect(service.getFormulaData()).toBe(data);+ expect(materialize).toHaveBeenCalledTimes(2);+ });++ it('queries deferred ownership without observing a service Proxy or non-object values', () => {+ const { service } = createService();+ let calls = 0;+ const proxy = new Proxy(service, {+ get: () => {+ calls++;+ throw new Error('unexpected get');+ },+ getPrototypeOf: () => {+ calls++;+ throw new Error('unexpected prototype');+ },+ });+ expect(hasDeferredFormulaDataSnapshot(proxy)).toBe(false);+ expect(hasDeferredFormulaDataSnapshot(undefined)).toBe(false);+ expect(hasDeferredFormulaDataSnapshot(null)).toBe(false);+ expect(hasDeferredFormulaDataSnapshot(1)).toBe(false);+ expect(calls).toBe(0);+ });+it('keeps conservative feature invalidation separate from ordinary formula calculation', () => {const bed = createFunctionTestBed();try {@@ -120,6 +229,30 @@ describe('FormulaCurrentConfigService', () => {} finally { bed.univer.dispose(); }});+ it('keeps reference invalidation independent of deferred formula materialization', () => {+ const { service, formulaDataModel } = createService();+ const materialize = vi.fn(() => ({ unit: { sheet: {} } }));+ service.loadWithFormulaDataSnapshot({+ ...createSnapshotDataset(),+ dirtyReferenceUnits: ['unit'],+ }, { materialize });++ expect(service.getDirtyData().dirtyReferenceUnits).toEqual(['unit']);+ expect(service.getDirtyData().forceCalculation).toBe(false);+ expect(service.getDirtyData(true).forceCalculation).toBe(true);+ expect(hasDeferredFormulaDataSnapshot(service)).toBe(true);+ expect(materialize).not.toHaveBeenCalled();+ expect(formulaDataModel.getFormulaData).not.toHaveBeenCalled();++ service.loadDirtyRangesAndExcludedCell([]);+ expect(service.getDirtyData().dirtyReferenceUnits).toEqual([]);+ expect(service.getDirtyData().forceCalculation).toBe(false);+ expect(service.getDirtyData(true).forceCalculation).toBe(false);+ expect(hasDeferredFormulaDataSnapshot(service)).toBe(true);+ expect(materialize).not.toHaveBeenCalled();+ service.dispose();+ });+it('distinguishes transported filter exclusions from manual hiding and clears stale exclusions', () => {const testBed = createFunctionTestBed();try {diff --git a/packages/engine-formula/src/services/__tests__/formula-cache.service.spec.ts b/packages/engine-formula/src/services/__tests__/formula-cache.service.spec.tsnew file mode 100644index 0000000000..12c1b8f462--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/formula-cache.service.spec.ts@@ -0,0 +1,434 @@+/**+ * 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 { ICommandService, Inject, Injector, LocaleService, LocaleType, ObjectMatrix, Plugin } from '@univerjs/core';+import { describe, expect, it } from 'vitest';+import type { IFormulaDatasetConfig } from '../../basics/common';+import type { BaseValueObject } from '../../engine/value-object/base-value-object';+import type { IAllRuntimeData } from '../runtime.service';+import { SetArrayFormulaDataMutation } from '../../commands/mutations/set-array-formula-data.mutation';+import {+ SetFormulaCalculationNotificationMutation,+ SetFormulaCalculationResultMutation,+ SetFormulaDependencyCalculationResultMutation,+} from '../../commands/mutations/set-formula-calculation.mutation';+import { CalculateController } from '../../controllers/calculate.controller';+import { createCommandTestBed } from '../../engine/analysis/__tests__/create-command-test-bed';+import { Lexer } from '../../engine/analysis/lexer';+import { AstTreeBuilder } from '../../engine/analysis/parser';+import { AstRootNode } from '../../engine/ast-node/ast-root-node';+import { BaseAstNode } from '../../engine/ast-node/base-ast-node';+import { Interpreter } from '../../engine/interpreter/interpreter';+import { generateExecuteAstNodeData } from '../../engine/utils/ast-node-tool';+import { generateAstNode } from '../../engine/utils/generate-ast-node';+import { AsyncCustomFunction, CustomFunction } from '../../functions/custom-function';+import { Sum } from '../../functions/math/sum';+import { Minus } from '../../functions/meta/minus';+import { ICalculateFormulaService } from '../calculate-formula.service';+import { IFormulaCurrentConfigService } from '../current-data.service';+import { IDefinedNamesService } from '../defined-names.service';+import { FormulaCacheService } from '../formula-cache.service';+import { DescriptionService, IDescriptionService } from '../formula/description.service';+import { IRegisterFunctionService, RegisterFunctionService } from '../formula/register-function.service';+import { IFunctionService } from '../function.service';+import { IFormulaRuntimeService } from '../runtime.service';++function dataset(client: ReturnType<typeof createCommandTestBed>, values: number[] = [1, 2], formula = '=SUM(A1:A2)'): IFormulaDatasetConfig {+ return {+ allUnitData: { [client.unitId]: { [client.sheetId]: {+ ...client.sheetData[client.sheetId],+ cellData: new ObjectMatrix({ 0: { 0: { v: values[0] }, 2: { f: formula } }, 1: { 0: { v: values[1] } } }),+ } } },+ unitSheetNameMap: { [client.unitId]: { [client.sheetId]: 'Main' } },+ unitStylesData: {},+ formulaData: { [client.unitId]: { [client.sheetId]: { 0: { 2: { f: formula } } } } },+ arrayFormulaCellData: {},+ arrayFormulaRange: {},+ forceCalculate: true,+ dirtyRanges: [],+ dirtyNameMap: {},+ dirtyDefinedNameMap: {},+ dirtyUnitFeatureMap: {},+ dirtyUnitOtherFormulaMap: {},+ };+}++function initialize(client: ReturnType<typeof createCommandTestBed>) {+ client.get(IFormulaCurrentConfigService).load(dataset(client));+ client.get(IFormulaRuntimeService).setCurrent(0, 2, 1, 1, client.sheetId, client.unitId);+}++function evaluate(client: ReturnType<typeof createCommandTestBed>, formula: string) {+ const node = generateAstNode(client.unitId, formula, client.get(Lexer), client.get(AstTreeBuilder), client.get(IFormulaCurrentConfigService), client.sheetId);+ const value = client.get(Interpreter).execute(generateExecuteAstNodeData(node));+ return (value as BaseValueObject).getValue();+}++async function calculate(client: ReturnType<typeof createCommandTestBed>, values: number[], formula = '=SUM(A1:A2)') {+ const service = client.get(ICalculateFormulaService);+ let result: IAllRuntimeData | undefined;+ const sub = service.executionCompleteListener$.subscribe((data) => {+ result = data;+ });+ try {+ await service.execute(dataset(client, values, formula));+ return result?.unitData[client.unitId]?.[client.sheetId]?.getValue(0, 2)?.v;+ } finally { sub.unsubscribe(); }+}++function registerCustom(client: ReturnType<typeof createCommandTestBed>, value: number) {+ const executor = new CustomFunction('CUSTOM');+ executor.calculateCustom = () => value;+ client.get(IFunctionService).registerExecutors(executor);+}++describe('FormulaCacheService calculation isolation', () => {+ it.each([+ ['=CUSTOM(0)', 'CUSTOM', 42],+ ['=CUSTOM (0)', 'CUSTOM', 42],+ ['=_xlfn.CUSTOM(0)', 'CUSTOM', 42],+ ['=_xlws.CUSTOM(0)', 'CUSTOM', 42],+ ['=_xleta.CUSTOM(0)', 'CUSTOM', 42],+ ['=_XlFn.cUsToM (0)', 'CUSTOM', 42],+ ['=-_xlfn.CUSTOM(0)', 'CUSTOM', -42],+ ['=@_xlws.CUSTOM(0)', 'CUSTOM', 42],+ ['=REGEXTEST(0)', 'REGEXMATCH', 42],+ ['=_xlfn.REGEXTEST(0)', 'REGEXMATCH', 42],+ ] as const)('refreshes a cached unknown function through registration: %s', (formula, name, expected) => {+ const client = createCommandTestBed(undefined, [+ [IDescriptionService, { useClass: DescriptionService }],+ [IRegisterFunctionService, { useClass: RegisterFunctionService }],+ ]);+ try {+ initialize(client);+ client.get(LocaleService).load({ [LocaleType.ZH_CN]: {}, [LocaleType.EN_US]: {} });+ const functions = client.get(IFunctionService);+ functions.registerExecutors(new Minus('MINUS'));+ const registration = client.get(IRegisterFunctionService);+ expect(evaluate(client, formula)).toBe('#NAME?');+ const disposable = registration.registerFunction({ name, func: () => 42, description: 'Cache recovery' });+ functions.deleteFormulaAstCacheKey(name);+ expect(evaluate(client, formula)).toBe(expected);+ disposable.dispose();+ expect(evaluate(client, formula)).toBe('#NAME?');+ registration.registerFunction({ name, func: () => 84, description: 'Replacement executor' });+ expect(evaluate(client, formula)).toBe(expected * 2);+ } finally { client.univer.dispose(); }+ });++ it('single instance recalculates aggregates after source values change', async () => {+ const client = createCommandTestBed();+ client.get(IFunctionService).registerExecutors(new Sum('SUM'));+ try {+ expect(await calculate(client, [1, 2])).toBe(3);+ expect(await calculate(client, [10, 20])).toBe(30);+ expect(await calculate(client, [1, 2])).toBe(3);+ } finally { client.univer.dispose(); }+ });++ it('sequential independent engines calculate the same document with different data', async () => {+ const clients = [createCommandTestBed(), createCommandTestBed()];+ clients.forEach((client) => client.get(IFunctionService).registerExecutors(new Sum('SUM')));+ try {+ expect(await calculate(clients[0], [1, 2])).toBe(3);+ expect(await calculate(clients[1], [10, 20])).toBe(30);+ } finally { clients.forEach((client) => client.univer.dispose()); }+ });++ it('concurrent independent engines isolate range array caches', async () => {+ const clients = [createCommandTestBed(), createCommandTestBed()];+ clients.forEach((client) => client.get(IFunctionService).registerExecutors(new Sum('SUM')));+ try {+ const values = await Promise.all([calculate(clients[0], [1, 2]), calculate(clients[1], [10, 20])]);+ expect(values).toEqual([3, 30]);+ } finally { clients.forEach((client) => client.univer.dispose()); }+ });++ it('independent engines isolate expanded defined names with matching document IDs', () => {+ const clients = [createCommandTestBed(), createCommandTestBed()];+ try {+ const values = clients.map((client, index) => {+ initialize(client);+ client.get(IDefinedNamesService).registerDefinedName(client.unitId, {+ id: 'rate',+ name: 'LocalRate',+ formulaOrRefString: String((index + 1) * 10),+ });+ return evaluate(client, '=LocalRate');+ });+ expect(values).toEqual([10, 20]);+ } finally { clients.forEach((client) => client.univer.dispose()); }+ });++ it('single instance refreshes a defined name with its dirty metadata', () => {+ const client = createCommandTestBed();+ try {+ initialize(client);+ const names = client.get(IDefinedNamesService);+ names.registerDefinedName(client.unitId, { id: 'rate', name: 'LocalRate', formulaOrRefString: '10' });+ expect(evaluate(client, '=LocalRate')).toBe(10);+ names.registerDefinedName(client.unitId, { id: 'rate', name: 'LocalRate', formulaOrRefString: '20' });+ client.get(IFormulaCurrentConfigService).load({ ...dataset(client), dirtyDefinedNameMap: { [client.unitId]: { LocalRate: 'LocalRate' } } });+ expect(evaluate(client, '=LocalRate')).toBe(20);+ } finally { client.univer.dispose(); }+ });++ it('refreshes a nested defined name absent from the outer formula text', () => {+ const client = createCommandTestBed();+ try {+ initialize(client);+ const names = client.get(IDefinedNamesService);+ names.registerDefinedName(client.unitId, { id: 'inner', name: 'InnerRate', formulaOrRefString: '10' });+ names.registerDefinedName(client.unitId, { id: 'outer', name: 'OuterRate', formulaOrRefString: 'InnerRate' });+ expect(evaluate(client, '=OuterRate')).toBe(10);+ names.registerDefinedName(client.unitId, { id: 'inner', name: 'InnerRate', formulaOrRefString: '20' });+ client.get(IFormulaCurrentConfigService).load({ ...dataset(client), dirtyDefinedNameMap: { [client.unitId]: { InnerRate: 'InnerRate' } } });+ expect(evaluate(client, '=OuterRate')).toBe(20);+ client.get(IFormulaCurrentConfigService).load(dataset(client));+ expect(evaluate(client, '=OuterRate')).toBe(20);+ } finally { client.univer.dispose(); }+ });++ for (const length of ['short', 'boundary', 'long'] as const) {+ it(`single instance replaces a custom executor with ${length} cache key`, () => {+ const client = createCommandTestBed();+ try {+ initialize(client);+ const originalPrefix = `${client.unitId}:${client.sheetId}:0:0:`;+ const targetLength = length === 'boundary' ? 64 - originalPrefix.length : length === 'long' ? 80 : 9;+ const formula = `=CUSTOM(${'0'.repeat(Math.max(0, targetLength - 9))})`;+ registerCustom(client, 1);+ expect(evaluate(client, formula)).toBe(1);+ const functions = client.get(IFunctionService);+ functions.unregisterExecutors('CUSTOM');+ functions.deleteFormulaAstCacheKey('CUSTOM');+ registerCustom(client, 2);+ expect(evaluate(client, formula)).toBe(2);+ } finally { client.univer.dispose(); }+ });+ }+});++describe('FormulaCacheService lifecycle', () => {+ it('retries a resized reference after an interrupted calculation and releases its context', async () => {+ const client = createCommandTestBed();+ const service = client.get(ICalculateFormulaService);+ let release!: (value: number) => void;+ let started!: () => void;+ let shouldWait = false;+ const pending = new Promise<number>((resolve) => {+ release = resolve;+ });+ const ready = new Promise<void>((resolve) => {+ started = resolve;+ });+ const executor = new AsyncCustomFunction('WAITFORVALUE');+ executor.calculateCustom = async () => {+ if (shouldWait) {+ started();+ return pending;+ }+ return 0;+ };+ client.get(IFunctionService).registerExecutors(new Sum('SUM'), executor);+ const config = dataset(client, [1, 2], '=SUM(A:A,WAITFORVALUE())');+ const sheet = config.allUnitData![client.unitId][client.sheetId];+ sheet.rowCount = 2;+ sheet.cellData.setValue(2, 0, { v: 10 });+ const run = async (forceCalculate: boolean) => {+ let value: unknown;+ const subscription = service.executionCompleteListener$.subscribe((data) => {+ value = data.unitData[client.unitId]?.[client.sheetId]?.getValue(0, 2)?.v;+ });+ try {+ await service.execute({ ...config, forceCalculate });+ return value;+ } finally {+ subscription.unsubscribe();+ }+ };+ try {+ expect(await run(true)).toBe(3);+ sheet.rowCount = 3;+ shouldWait = true;+ const interrupted = run(false);+ await ready;+ const context = client.get(IFormulaRuntimeService).getCalculationCache?.();+ expect(context?.closed).toBe(false);+ service.stopFormulaExecution();+ shouldWait = false;+ release(0);+ await interrupted;+ expect(context?.closed).toBe(true);+ expect(await run(false)).toBe(13);+ } finally {+ release(0);+ client.univer.dispose();+ }+ });++ it('releases an initialized cache when a later plugin constructor fails', () => {+ const client = createCommandTestBed();+ const cache = client.get(FormulaCacheService);+ const context = cache.createCalculation();+ class FailingPlugin extends Plugin {+ static override pluginName = 'formula-cache-failing-initialization';++ constructor(+ _config: undefined,+ @Inject(Injector) protected override readonly _injector: Injector,+ @Inject(FormulaCacheService) ownedCache: FormulaCacheService+ ) {+ super();+ ownedCache.setAst('partial', client.unitId, new AstRootNode('partial'));+ throw new Error('Expected initialization failure');+ }+ }+ try {+ expect(() => client.univer.registerPlugin(FailingPlugin)).toThrow('Expected initialization failure');+ expect(cache.getAst('partial')).toBeDefined();+ } finally {+ client.univer.dispose();+ }+ expect(context?.closed).toBe(true);+ expect(cache.closed).toBe(true);+ expect(cache.getAst('partial')).toBeUndefined();+ });++ it('detaches calculation result and progress forwarding when the controller is disposed', async () => {+ const client = createCommandTestBed(undefined, [[CalculateController]]);+ client.get(IFunctionService).registerExecutors(new Sum('SUM'));+ const commands = client.get(ICommandService);+ [SetArrayFormulaDataMutation, SetFormulaCalculationNotificationMutation, SetFormulaCalculationResultMutation, SetFormulaDependencyCalculationResultMutation]+ .forEach((mutation) => commands.registerCommand(mutation));+ const seen: string[] = [];+ const listener = commands.onCommandExecuted((command) => seen.push(command.id));+ const controller = client.get(CalculateController);+ try {+ expect(await calculate(client, [1, 2])).toBe(3);+ expect(seen).toContain(SetFormulaCalculationNotificationMutation.id);+ controller.dispose();+ seen.length = 0;+ expect(await calculate(client, [10, 20])).toBe(30);+ expect(seen).toEqual([]);+ } finally {+ listener.dispose();+ client.univer.dispose();+ }+ });++ it('releases cached references across 100 create/dispose cycles without evicting another engine', async () => {+ const survivor = createCommandTestBed();+ survivor.get(IFunctionService).registerExecutors(new Sum('SUM'));+ try {+ expect(await calculate(survivor, [10, 20])).toBe(30);+ const survivorCache = survivor.get(FormulaCacheService);+ const survivorAst = new AstRootNode('survivor');+ survivorCache.setAst('survivor', survivor.unitId, survivorAst);+ for (let round = 0; round < 100; round++) {+ const client = createCommandTestBed();+ client.get(IFunctionService).registerExecutors(new Sum('SUM'));+ const cache = client.get(FormulaCacheService);+ expect(await calculate(client, [1, 2])).toBe(3);+ const context = client.get(IFormulaRuntimeService).getCalculationCache?.();+ cache.setAst('late', client.unitId, new AstRootNode('late'));+ client.univer.dispose();+ cache.dispose();+ expect(context?.closed).toBe(true);+ expect(cache.closed).toBe(true);+ expect(cache.getAst('late')).toBeUndefined();+ expect(cache.createCalculation()).toBeUndefined();+ cache.setAst('late', 'new', new AstRootNode('must not survive'));+ expect(cache.getAst('late')).toBeUndefined();+ expect(survivorCache.getAst('survivor')).toBe(survivorAst);+ }+ expect(await calculate(survivor, [20, 40])).toBe(60);+ } finally { survivor.univer.dispose(); }+ });++ it('invalidates only the closed workbook, including long cache keys', () => {+ const client = createCommandTestBed();+ try {+ const cache = client.get(FormulaCacheService);+ const first = new AstRootNode('first');+ const second = new AstRootNode('second');+ const longKey = 'formula'.repeat(30);+ cache.setAst(longKey, 'closed', first);+ cache.setAst('remaining', 'open', second);+ cache.clearUnit('closed');+ expect(cache.getAst(longKey)).toBeUndefined();+ expect(cache.getAst('remaining')).toBe(second);+ } finally { client.univer.dispose(); }+ });++ it('invalidates expanded custom functions by AST tokens, not by a shortened cache key', () => {+ const client = createCommandTestBed();+ try {+ const cache = client.get(FormulaCacheService);+ const ast = new AstRootNode('ROOT');+ new BaseAstNode('CUSTOM').setParent(ast);+ const key = 'LocalRate'.repeat(20);+ cache.setAst(key, client.unitId, ast);+ cache.clearFunctions(['custom']);+ expect(cache.getAst(key)).toBeUndefined();+ } finally { client.univer.dispose(); }+ });++ it('discards a late async result and queued executions after disposal, while a replacement engine works', async () => {+ const client = createCommandTestBed();+ let release!: (value: number) => void;+ let started!: () => void;+ const pending = new Promise<number>((resolve) => {+ release = resolve;+ });+ const ready = new Promise<void>((resolve) => {+ started = resolve;+ });+ const executor = new AsyncCustomFunction('WAITFORVALUE');+ executor.calculateCustom = () => {+ started();+ return pending;+ };+ client.get(IFunctionService).registerExecutors(executor);+ const service = client.get(ICalculateFormulaService);+ const cache = client.get(FormulaCacheService);+ const runtime = client.get(IFormulaRuntimeService);+ let emitted = 0;+ const subscription = service.executionCompleteListener$.subscribe(() => {+ emitted++;+ });+ const first = service.execute(dataset(client, [1, 2], '=WAITFORVALUE()'));+ await ready;+ const queued = service.execute(dataset(client, [9, 9]));+ client.univer.dispose();+ const replacement = createCommandTestBed();+ replacement.get(IFunctionService).registerExecutors(new Sum('SUM'));+ try {+ expect(await calculate(replacement, [10, 20])).toBe(30);+ release(123);+ await Promise.all([first, queued]);+ expect(emitted).toBe(0);+ expect(Object.keys(runtime.getUnitData())).toHaveLength(0);+ expect(Object.keys(runtime.getRuntimeOtherData())).toHaveLength(0);+ expect(cache.closed).toBe(true);+ expect(cache.createCalculation()).toBeUndefined();+ } finally {+ release(123);+ subscription.unsubscribe();+ replacement.univer.dispose();+ }+ });+});diff --git a/packages/engine-formula/src/services/__tests__/formula-result.service.spec.ts b/packages/engine-formula/src/services/__tests__/formula-result.service.spec.tsnew file mode 100644index 0000000000..2ea9a794a0--- /dev/null+++ b/packages/engine-formula/src/services/__tests__/formula-result.service.spec.ts@@ -0,0 +1,116 @@+/**+ * 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 { ICommandService, Injector, ObjectMatrix } from '@univerjs/core';+import { describe, expect, it, onTestFinished, vi } from 'vitest';+import type { ISetFormulaCalculationResultMutation } from '../../commands/mutations/set-formula-calculation.mutation';+import type { IAllRuntimeData } from '../runtime.service';+import { SetArrayFormulaDataMutation } from '../../commands/mutations/set-array-formula-data.mutation';+import { SetFormulaCalculationResultMutation, SetFormulaDependencyCalculationResultMutation } from '../../commands/mutations/set-formula-calculation.mutation';+import { SetImageFormulaDataMutation } from '../../commands/mutations/set-image-formula-data.mutation';+import { FormulaDataModel } from '../../models/formula-data.model';+import { FormulaResultService } from '../formula-result.service';+import { FormulaExecutedStateType, IFormulaRuntimeService } from '../runtime.service';++function createTestBed() {+ const command = { executeCommand: vi.fn<ICommandService['executeCommand']>().mockResolvedValue(true) };+ const model = {+ clearPreviousArrayFormulaCellData: vi.fn(),+ mergeArrayFormulaCellData: vi.fn(),+ mergeArrayFormulaRange: vi.fn(),+ getArrayFormulaRange: () => ({}),+ getArrayFormulaCellData: () => ({}),+ } satisfies Pick<FormulaDataModel, 'clearPreviousArrayFormulaCellData' | 'mergeArrayFormulaCellData' | 'mergeArrayFormulaRange' | 'getArrayFormulaRange' | 'getArrayFormulaCellData'>;+ const runtime = { isStopExecution: vi.fn(() => false) } satisfies Pick<IFormulaRuntimeService, 'isStopExecution'>;+ const injector = new Injector([+ [ICommandService, { useValue: command }],+ [FormulaDataModel, { useValue: model }],+ [IFormulaRuntimeService, { useValue: runtime }],+ [FormulaResultService],+ ]);+ onTestFinished(() => injector.dispose());+ const cell = { v: 42 };+ const matrix = new ObjectMatrix({ 0: { 1: cell } });+ const data: IAllRuntimeData = {+ unitData: { book: { sheet: matrix } },+ unitOtherData: {},+ sourceFormulaData: {},+ arrayFormulaRange: {},+ arrayFormulaEmbedded: {},+ arrayFormulaCellData: {},+ clearArrayFormulaCellData: {},+ imageFormulaData: [],+ dependencyTreeModelData: [],+ functionsExecutedState: FormulaExecutedStateType.SUCCESS,+ runtimeFeatureRange: {},+ runtimeFeatureCellData: {},+ };+ return { command, model, runtime, injector, data, matrix, cell };+}++describe('FormulaResultService', () => {+ it('orders array, image, dependency and cell results through the same writer', async () => {+ const { injector, command, data } = createTestBed();+ const writer = injector.get(FormulaResultService);+ data.imageFormulaData = [{ unitId: 'book', sheetId: 'sheet', row: 0, column: 1, imageId: 'image' }] as never;+ data.dependencyTreeModelData = [{ treeId: 7 }] as never;+ await writer.applyResult(data);+ expect(command.executeCommand.mock.calls.map(([id]) => id)).toEqual([+ SetArrayFormulaDataMutation.id,+ SetImageFormulaDataMutation.id,+ SetFormulaDependencyCalculationResultMutation.id,+ SetFormulaCalculationResultMutation.id,+ ]);+ });++ it('submits Web runtime rows once, after metadata, with independent row containers and shared cells', async () => {+ const { injector, command, data, matrix, cell } = createTestBed();+ const writer = injector.get(FormulaResultService);+ await writer.applyResult(data);+ expect(command.executeCommand.mock.calls.map(([id]) => id)).toEqual([+ SetArrayFormulaDataMutation.id,+ SetFormulaCalculationResultMutation.id,+ ]);+ const [, result, options] = command.executeCommand.mock.calls[1] as unknown as [string, ISetFormulaCalculationResultMutation, object];+ expect(options).toEqual({ onlyLocal: true, applyFormulaCalculationResult: true });+ expect(result.unitData.book!.sheet[0]).not.toBe(matrix.getRow(0));+ expect(result.unitData.book!.sheet[0][1]).toBe(cell);+ result.unitData.book!.sheet[0][1] = { v: 99 };+ expect(matrix.getValue(0, 1)).toBe(cell);+ });++ it('submits an already prepared batch without materializing or copying runtime rows', async () => {+ const { injector, command, data, matrix, cell } = createTestBed();+ const writer = injector.get(FormulaResultService);+ const forValue = vi.spyOn(matrix, 'forValue');+ const result = { unitData: { book: { sheet: { 0: { 1: cell } } } }, unitOtherData: {} };+ await writer.applyResult(data, result);+ expect(command.executeCommand.mock.calls[1][1]).toBe(result);+ expect(forValue).not.toHaveBeenCalled();+ });++ it.each(['stop', 'dispose'])('does not submit values after %s during metadata application', async (action) => {+ const { injector, command, data, runtime } = createTestBed();+ const writer = injector.get(FormulaResultService);+ command.executeCommand.mockImplementationOnce(async () => {+ if (action === 'stop') runtime.isStopExecution.mockReturnValue(true);+ else writer.dispose();+ return true;+ });+ await writer.applyResult(data);+ expect(command.executeCommand.mock.calls.map(([id]) => id)).toEqual([SetArrayFormulaDataMutation.id]);+ });+});diff --git a/packages/engine-formula/src/services/__tests__/function.service.spec.ts b/packages/engine-formula/src/services/__tests__/function.service.spec.tsindex b5ba77c001..2190a3990d 100644--- a/packages/engine-formula/src/services/__tests__/function.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/function.service.spec.ts@@ -17,18 +17,21 @@import { Injector } from '@univerjs/core';import { describe, expect, it } from 'vitest';import { FunctionType } from '../../basics/function';-import { FORMULA_AST_CACHE } from '../../engine/utils/generate-ast-node';+import { AstRootNode } from '../../engine/ast-node/ast-root-node';+import { BaseAstNode } from '../../engine/ast-node/base-ast-node';+import { FormulaCacheService } from '../formula-cache.service';import { FunctionService } from '../function.service';-function createService(): FunctionService {+function createService() {const injector = new Injector();+ injector.add([FormulaCacheService]);injector.add([FunctionService]);- return injector.get(FunctionService);+ return { service: injector.get(FunctionService), cache: injector.get(FormulaCacheService) };}describe('FunctionService', () => {it('makes registered formula executors available until they are unregistered', () => {- const service = createService();+ const { service } = createService();const sumExecutor = { name: 'SUM' };const avgExecutor = { name: 'AVERAGE' };@@ -43,7 +46,7 @@ describe('FunctionService', () => {});it('removes formula descriptions when a feature disposes its registration', () => {- const service = createService();+ const { service } = createService();const sumDescription = {functionName: 'SUM',functionType: FunctionType.Math,@@ -70,7 +73,7 @@ describe('FunctionService', () => {});it('removes formula metadata and invalidates AST cache entries for unregistered function names', () => {- const service = createService();+ const { service, cache } = createService();service.registerDescriptions({functionName: 'SUM',functionType: FunctionType.Math,@@ -82,18 +85,20 @@ describe('FunctionService', () => {service.unregisterDescriptions('SUM');expect(service.hasDescription('SUM')).toBe(false);- FORMULA_AST_CACHE.clear();- FORMULA_AST_CACHE.set('unit_sheet_SUM_expr', {} as never);- const textAst = { token: 'TEXT' };- FORMULA_AST_CACHE.set('unit_sheet_TEXT_expr', textAst as never);+ const sumAst = new AstRootNode('ROOT');+ new BaseAstNode('SUM').setParent(sumAst);+ const textAst = new AstRootNode('ROOT');+ new BaseAstNode('TEXT').setParent(textAst);+ cache.setAst('unit_sheet_SUM_expr', 'unit', sumAst);+ cache.setAst('unit_sheet_TEXT_expr', 'unit', textAst);service.deleteFormulaAstCacheKey('SUM');- expect(FORMULA_AST_CACHE.get('unit_sheet_SUM_expr')).toBeUndefined();- expect(FORMULA_AST_CACHE.get('unit_sheet_TEXT_expr')).toBe(textAst);+ expect(cache.getAst('unit_sheet_SUM_expr')).toBeUndefined();+ expect(cache.getAst('unit_sheet_TEXT_expr')).toBe(textAst);});it('drops registered formula executors and descriptions when the formula runtime is disposed', () => {- const service = createService();+ const { service } = createService();service.registerExecutors({ name: 'SUM' } as never);service.registerDescriptions({functionName: 'SUM',diff --git a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts b/packages/engine-formula/src/services/__tests__/runtime.service.spec.tsindex 5022398be9..76dd041a52 100644--- a/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts+++ b/packages/engine-formula/src/services/__tests__/runtime.service.spec.ts@@ -15,7 +15,6 @@*/import type { ICellData, Nullable } from '@univerjs/core';-import type { BaseAstNode } from '../../engine/ast-node/base-ast-node';import {CellValueType,ContextService,@@ -28,14 +27,15 @@ import {ObjectMatrix,UniverInstanceService,} from '@univerjs/core';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';+import type { BaseAstNode } from '../../engine/ast-node/base-ast-node';import { ErrorType } from '../../basics/error-type';-import { CELL_INVERTED_INDEX_CACHE } from '../../basics/inverted-index-cache';import { LexerTreeBuilder } from '../../engine/analysis/lexer-tree-builder';import { createNewArray } from '../../engine/utils/array-object';import { NullValueObject, NumberValueObject, StringValueObject } from '../../engine/value-object/primitive-object';import { FormulaDataModel } from '../../models/formula-data.model';import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from '../current-data.service';+import { FormulaCacheService } from '../formula-cache.service';import { HyperlinkEngineFormulaService, IHyperlinkEngineFormulaService } from '../hyperlink-engine-formula.service';import { FormulaExecutedStateType, FormulaExecuteStageType, FormulaRuntimeService, IFormulaRuntimeService } from '../runtime.service';import { ISheetRowFilteredService, SheetRowFilteredService } from '../sheet-row-filtered.service';@@ -53,6 +53,7 @@ function createRuntimeService() {injector.add([IContextService, { useClass: ContextService }]);injector.add([IUniverInstanceService, { useClass: UniverInstanceService }]);injector.add([LocaleService]);+ injector.add([FormulaCacheService]);injector.add([LexerTreeBuilder]);injector.add([FormulaDataModel]);injector.add([ISheetRowFilteredService, { useClass: SheetRowFilteredService }]);@@ -96,6 +97,88 @@ function createRuntimeService() {}describe('FormulaRuntimeService', () => {+ it('replaces authoritative circular diagnostics without reading formula input and preserves stopped state', () => {+ const { injector, runtime } = createRuntimeService();+ const config = injector.get(IFormulaCurrentConfigService) as FormulaCurrentConfigService;+ const previous = { unitId: 'unit', sheetId: 'sheet', row: 2, column: 3, groupId: 'old', iterations: 1 };+ const current = { ...previous, row: 4, groupId: 'native', iterations: 5, converged: true };+ runtime.recordCircularReferences([previous]);+ runtime.completeCircularReferences();+ const getter = vi.spyOn(config, 'getFormulaData');+ try {+ runtime.beginCircularReferences(true);+ runtime.recordCircularReferences([current]);+ runtime.completeCircularReferences();+ expect(runtime.getRuntimeState().circularReferences).toEqual([current]);+ current.iterations = 99;+ expect(runtime.getRuntimeState().circularReferences?.[0].iterations).toBe(5);++ runtime.beginCircularReferences(true);+ runtime.recordCircularReferences([previous]);+ runtime.stopExecution();+ runtime.completeCircularReferences();+ expect(runtime.getRuntimeState().circularReferences?.[0].groupId).toBe('native');++ runtime.reset();+ runtime.beginCircularReferences(true);+ runtime.completeCircularReferences();+ expect(runtime.getRuntimeState().circularReferences).toEqual([]);+ expect(getter).not.toHaveBeenCalled();+ } finally {+ getter.mockRestore();+ injector.dispose();+ }+ });++ it('preserves legacy empty-circle reads while deferring unused snapshots and filtering deleted formulas', () => {+ const { injector, runtime } = createRuntimeService();+ const config = injector.get(IFormulaCurrentConfigService) as FormulaCurrentConfigService;+ const formulaData = { unit: { sheet: { 2: { 3: { f: '=D3' } } } } };+ const materialize = vi.fn(() => formulaData);+ const getter = vi.spyOn(config, 'getFormulaData');+ const current = { unitId: 'unit', sheetId: 'sheet', row: 2, column: 3, groupId: 'cycle', iterations: 1 };+ const deleted = { ...current, row: 4, column: 5 };+ try {+ runtime.beginCircularReferences();+ expect(getter).toHaveBeenCalledTimes(1);+ getter.mockClear();+ config.loadWithFormulaDataSnapshot({+ allUnitData: config.getUnitData(),+ unitStylesData: config.getUnitStylesData(),+ unitSheetNameMap: config.getSheetNameMap(),+ arrayFormulaCellData: {},+ arrayFormulaRange: {},+ forceCalculate: false,+ dirtyRanges: [],+ dirtyNameMap: {},+ dirtyDefinedNameMap: {},+ dirtyUnitFeatureMap: {},+ dirtyUnitOtherFormulaMap: {},+ }, { materialize });+ runtime.beginCircularReferences();+ expect(getter).not.toHaveBeenCalled();+ expect(materialize).not.toHaveBeenCalled();+ runtime.recordCircularReferences([current, deleted]);+ runtime.completeCircularReferences();+ runtime.beginCircularReferences();+ runtime.completeCircularReferences();+ expect(getter).toHaveBeenCalledTimes(1);+ expect(materialize).toHaveBeenCalledTimes(1);+ expect(runtime.getRuntimeState().circularReferences).toEqual([current]);+ runtime.beginCircularReferences();+ runtime.clearCircularReferenceCells([{ unitId: 'unit', subUnitId: 'sheet', row: 2, column: 3 }]);+ runtime.completeCircularReferences();+ getter.mockClear();+ runtime.beginCircularReferences();+ expect(getter).toHaveBeenCalledTimes(1);+ expect(materialize).toHaveBeenCalledTimes(1);+ expect(runtime.getRuntimeState().circularReferences).toEqual([]);+ } finally {+ getter.mockRestore();+ injector.dispose();+ }+ });+it('keeps the scalar result source from before an asynchronous formula replacement and clears it on reset', () => {const { injector, runtime, unitDataMatrix } = createRuntimeService();try {@@ -131,19 +214,19 @@ describe('FormulaRuntimeService', () => {it('indexes scalar and spilled null results as blanks, consistently with reference scans', () => {const { injector, runtime } = createRuntimeService();- CELL_INVERTED_INDEX_CACHE.clear();+ const index = runtime.getCalculationCache()!.invertedIndex;try {runtime.setCurrent(2, 3, 20, 20, 'sheet', 'unit');runtime.setRuntimeData(NumberValueObject.create(7));- CELL_INVERTED_INDEX_CACHE.setContinueBuildingCache('unit', 'sheet', 3, 0, 19);+ index.setContinueBuildingCache('unit', 'sheet', 3, 0, 19);runtime.setRuntimeData(NullValueObject.create());expect(runtime.getUnitData().unit?.sheet?.getValue(2, 3)?.v).toBeNull();- expect(CELL_INVERTED_INDEX_CACHE.getCellPositions('unit', 'sheet', 3, '', [[0, 19]])?.matchingRows).toEqual([2]);+ expect(index.getCellPositions('unit', 'sheet', 3, '', [[0, 19]])?.matchingRows).toEqual([2]);runtime.setCurrent(4, 3, 20, 20, 'sheet', 'unit');runtime.setRuntimeData(createNewArray([[NullValueObject.create()], [NumberValueObject.create(1)]], 2, 1));- expect(CELL_INVERTED_INDEX_CACHE.getCellPositions('unit', 'sheet', 3, '', [[0, 19]])?.matchingRows).toEqual([2, 4]);+ expect(index.getCellPositions('unit', 'sheet', 3, '', [[0, 19]])?.matchingRows).toEqual([2, 4]);} finally {- CELL_INVERTED_INDEX_CACHE.clear();+ index.clear();injector.dispose();}});diff --git a/packages/engine-formula/src/services/calculate-formula.service.ts b/packages/engine-formula/src/services/calculate-formula.service.tsindex 42607fa99f..7eb728b2cf 100644--- a/packages/engine-formula/src/services/calculate-formula.service.ts+++ b/packages/engine-formula/src/services/calculate-formula.service.ts@@ -52,27 +52,31 @@ import type {import type { BaseReferenceObject, FunctionVariantType } from '../engine/reference-object/base-reference-object';import type { ArrayValueObject } from '../engine/value-object/array-value-object';import type { BaseValueObject } from '../engine/value-object/base-value-object';+import type { IFormulaDataSnapshot } from '../models/formula-data-snapshot';import type { IAllRuntimeData, IExecutionInProgressParams } from './runtime.service';import { ErrorType } from '../basics/error-type';-import { CELL_INVERTED_INDEX_CACHE } from '../basics/inverted-index-cache';import { ENGINE_FORMULA_PLUGIN_CONFIG_KEY } from '../config/config';import { Lexer } from '../engine/analysis/lexer';import { AstTreeBuilder } from '../engine/analysis/parser';import { IFormulaDependencyGenerator } from '../engine/dependency/formula-dependency';import { Interpreter } from '../engine/interpreter/interpreter';-import { FORMULA_REF_TO_ARRAY_CACHE } from '../engine/reference-object/base-reference-object';import { generateAstNode } from '../engine/utils/generate-ast-node';-import { ErrorValueObjectCache } from '../engine/value-object/base-value-object';-import { StringValueObjectCache } from '../engine/value-object/primitive-object';import { FUNCTION_NAMES_LOOKUP } from '../functions/lookup/function-names';import { IFormulaCurrentConfigService } from './current-data.service';-import { FormulaExecuteStageType, IFormulaRuntimeService } from './runtime.service';+import { FormulaResultService } from './formula-result.service';+import { FormulaExecutedStateType, FormulaExecuteStageType, IFormulaRuntimeService } from './runtime.service';export const DEFAULT_INTERVAL_COUNT = 500;export const EVERY_N_FUNCTION_EXECUTION_PAUSE = 100;export interface ICalculateFormulaService {+ /** Internal engine opt-in; engines without this capability and RPC proxies keep the complete formula DTO input. */+ readonly supportsFormulaDataSnapshot?: boolean;+ /** Internal engine capability to capture formula values in the same runtime. */+ prepareFormulaDataSnapshot?(): IFormulaDataSnapshot | undefined;+ /** Internal engine capability to execute the captured formula input. */+ executeWithFormulaDataSnapshot?(config: Omit<IFormulaDatasetConfig, 'formulaData'>, snapshot: IFormulaDataSnapshot): Promise<void>;readonly executionInProgressListener$: Observable<IExecutionInProgressParams>;readonly executionCompleteListener$: Observable<IAllRuntimeData>;setRuntimeFeatureCellData(featureId: string, featureData: IRuntimeUnitDataType): void;@@ -169,7 +173,7 @@ export class CalculateFormulaService extends Disposable implements ICalculateForfor (let i = 0; i < group.length; i++) {if (iteration < (settings[i].iterativeCalculation ? settings[i].maxIterations : 1)) {// Each member can change a range read by the next member in this round.- FORMULA_REF_TO_ARRAY_CACHE.clear();+ this._runtimeService.getCalculationCache?.()?.references.clear();yield { tree: group[i], preserve: !settings[i].iterativeCalculation, iteration };}}@@ -190,7 +194,7 @@ export class CalculateFormulaService extends Disposable implements ICalculateForbreak;}}- FORMULA_REF_TO_ARRAY_CACHE.clear();+ this._runtimeService.getCalculationCache?.()?.references.clear();this._runtimeService.recordCircularReferences(group.map((item, i) => ({unitId: item.unitId,sheetId: item.subUnitId,@@ -224,20 +228,22 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor@IFormulaRuntimeService protected readonly _runtimeService: IFormulaRuntimeService,@IFormulaDependencyGenerator protected readonly _formulaDependencyGenerator: IFormulaDependencyGenerator,@Inject(Interpreter) protected readonly _interpreter: Interpreter,- @Inject(AstTreeBuilder) protected readonly _astTreeBuilder: AstTreeBuilder+ @Inject(AstTreeBuilder) protected readonly _astTreeBuilder: AstTreeBuilder,+ @Inject(FormulaResultService) protected readonly _formulaResultService: FormulaResultService) {super();}override dispose() {+ if (this._disposed) {+ return;+ }+ this._runtimeService.stopExecution();+ this._runtimeService.releaseCalculationCache?.();super.dispose();this._executionInProgressListener$.complete();this._executionCompleteListener$.complete();- FORMULA_REF_TO_ARRAY_CACHE.clear();- CELL_INVERTED_INDEX_CACHE.clear();- ErrorValueObjectCache.clear();- StringValueObjectCache.clear();}/**@@ -263,7 +269,13 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor}async execute(formulaDatasetConfig: IFormulaDatasetConfig) {+ if (this._disposed) {+ return;+ }return this._executeLock.acquire('FORMULA_EXECUTION_LOCK', async () => {+ if (this._disposed) {+ return;+ }this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.START);this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());@@ -275,22 +287,42 @@ export class CalculateFormulaService extends Disposable implements ICalculateForthis._preserveCircularUnits = new Set(formulaDatasetConfig.preserveCircularUnits);this._runtimeService.beginCircularReferences();this._isCalculateTreeModel = formulaDatasetConfig.isCalculateTreeModel || false;- let completed = false;try {- await this._executeStep();- completed = !this._runtimeService.isStopExecution();+ let completed = false;+ try {+ await this._executeStep();+ completed = !this._runtimeService.isStopExecution();+ } finally {+ this._formulaDependencyGenerator.finishReferenceContext?.(completed);+ }+ if (this._disposed) {+ return;+ }+ this._runtimeService.completeCircularReferences();+ this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.CALCULATION_COMPLETED);+ this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());+ await this._completeExecution();} finally {- this._formulaDependencyGenerator.finishReferenceContext?.(completed);+ this._runtimeService.clearInvertedIndexCache?.();+ this._runtimeService.reset();+ this._runtimeService.releaseCalculationCache?.();}- this._runtimeService.completeCircularReferences();- this._runtimeService.setFormulaExecuteStage(FormulaExecuteStageType.CALCULATION_COMPLETED);- this._executionInProgressListener$.next(this._runtimeService.getRuntimeState());- this._executionCompleteListener$.next(this._runtimeService.getAllRuntimeData());- CELL_INVERTED_INDEX_CACHE.clear();- this._runtimeService.reset();});}+ protected async _completeExecution(): Promise<void> {+ const data = this._runtimeService.getAllRuntimeData();+ // Materialized results no longer need calculation caches while model application awaits.+ this._runtimeService.releaseCalculationCache?.();+ if (data.functionsExecutedState === FormulaExecutedStateType.SUCCESS) {+ await this._formulaResultService.applyResult(data);+ } else if (data.functionsExecutedState === FormulaExecutedStateType.NOT_EXECUTED) {+ await this._formulaResultService.applyTreeResult(data);+ }+ if (this._runtimeService.isStopExecution()) data.functionsExecutedState = FormulaExecutedStateType.STOP_EXECUTION;+ if (!this._disposed) this._executionCompleteListener$.next(data);+ }+protected async _executeStep() {const executeState = await this._apply();@@ -309,7 +341,7 @@ export class CalculateFormulaService extends Disposable implements ICalculateForreturn true;}- FORMULA_REF_TO_ARRAY_CACHE.clear();+ this._runtimeService.getCalculationCache?.()?.references.clear();this._currentConfigService.loadDirtyRangesAndExcludedCell(dirtyRanges, excludedCell);@@ -407,6 +439,9 @@ export class CalculateFormulaService extends Disposable implements ICalculateForthis._executionInProgressListener$.next(this._runtimeService.getRuntimeState());const treeList = await this._formulaDependencyGenerator.generate(this._isCalculateTreeModel);+ if (this._disposed) {+ return;+ }const interpreter = this._interpreter;@@ -514,6 +549,11 @@ export class CalculateFormulaService extends Disposable implements ICalculateForvalue = interpreter.execute(nodeData);}+ if (this._disposed) {+ node.resetCalculationState();+ return;+ }+if (tree.formulaId != null) {this._runtimeService.setRuntimeOtherData(tree.formulaId, tree.refOffsetX, tree.refOffsetY, value);} else {@@ -541,106 +581,116 @@ export class CalculateFormulaService extends Disposable implements ICalculateFor}async executeFormulas(formulas: IFormulaStringMap, rowData?: IUnitRowData) {- this._currentConfigService.loadDataLite(- rowData- );+ if (this._disposed) {+ return Object.create(null) as IFormulaExecuteResultMap;+ }+ try {+ this._currentConfigService.loadDataLite(+ rowData+ );- const unitData = this._currentConfigService.getUnitData();+ const unitData = this._currentConfigService.getUnitData();- this._runtimeService.reset();+ this._runtimeService.reset();- const result: IFormulaExecuteResultMap = Object.create(null);+ const result: IFormulaExecuteResultMap = Object.create(null);- for (const unitId of Object.keys(formulas)) {- const sheetFormulas = formulas[unitId];- if (sheetFormulas == null) continue;+ for (const unitId of Object.keys(formulas)) {+ const sheetFormulas = formulas[unitId];+ if (sheetFormulas == null) continue;- result[unitId] = Object.create(null);+ result[unitId] = Object.create(null);- for (const sheetId of Object.keys(sheetFormulas)) {- const rowFormulas = sheetFormulas[sheetId];- if (rowFormulas == null) continue;+ for (const sheetId of Object.keys(sheetFormulas)) {+ const rowFormulas = sheetFormulas[sheetId];+ if (rowFormulas == null) continue;- const sheetItem = unitData[unitId]?.[sheetId];+ const sheetItem = unitData[unitId]?.[sheetId];- if (sheetItem == null) continue;+ if (sheetItem == null) continue;- result[unitId]![sheetId] = Object.create(null);+ result[unitId]![sheetId] = Object.create(null);- for (const rowString of Object.keys(rowFormulas)) {- const row = Number.parseInt(rowString);- result[unitId]![sheetId]![row] = Object.create(null);+ for (const rowString of Object.keys(rowFormulas)) {+ const row = Number.parseInt(rowString);+ result[unitId]![sheetId]![row] = Object.create(null);- const cellData = rowFormulas[row];- if (!cellData) continue;+ const cellData = rowFormulas[row];+ if (!cellData) continue;- for (const columnString of Object.keys(cellData)) {- const column = Number.parseInt(columnString);- const formulaStrings = cellData[column];- if (!formulaStrings) continue;+ for (const columnString of Object.keys(cellData)) {+ const column = Number.parseInt(columnString);+ const formulaStrings = cellData[column];+ if (!formulaStrings) continue;- const rowCount = sheetItem.rowCount || 0;- const columnCount = sheetItem.columnCount || 0;+ const rowCount = sheetItem.rowCount || 0;+ const columnCount = sheetItem.columnCount || 0;- this._runtimeService.setCurrent(- row,- column,- rowCount,- columnCount,- sheetId,- unitId- );+ this._runtimeService.setCurrent(+ row,+ column,+ rowCount,+ columnCount,+ sheetId,+ unitId+ );- const item: IFormulaExecuteResultItem[] = [];+ const item: IFormulaExecuteResultItem[] = [];- for (const formulaString of formulaStrings) {- let resultCell = await this.calculate(formulaString);- if (!resultCell) {- item.push({- value: null,- formula: formulaString,- });+ for (const formulaString of formulaStrings) {+ let resultCell = await this.calculate(formulaString);+ if (this._disposed) {+ return Object.create(null) as IFormulaExecuteResultMap;+ }+ if (!resultCell) {+ item.push({+ value: null,+ formula: formulaString,+ });- continue;- }+ continue;+ }- if (resultCell.isReferenceObject()) {- resultCell = (resultCell as BaseReferenceObject).toArrayValueObject();- }+ if (resultCell.isReferenceObject()) {+ resultCell = (resultCell as BaseReferenceObject).toArrayValueObject();+ }++ const resultRefObject = resultCell as BaseValueObject;- const resultRefObject = resultCell as BaseValueObject;+ if (resultRefObject.isArray()) {+ const resultRefArrayObject = resultRefObject as ArrayValueObject;+ if (resultRefArrayObject.getRowCount() === 1 && resultRefArrayObject.getColumnCount() === 1) {+ item.push({+ value: resultRefArrayObject.getFirstCell().getValue(),+ formula: formulaString,+ });+ continue;+ }- if (resultRefObject.isArray()) {- const resultRefArrayObject = resultRefObject as ArrayValueObject;- if (resultRefArrayObject.getRowCount() === 1 && resultRefArrayObject.getColumnCount() === 1) {item.push({- value: resultRefArrayObject.getFirstCell().getValue(),+ value: resultRefArrayObject.toValue(),formula: formulaString,});+continue;}item.push({- value: resultRefArrayObject.toValue(),+ value: resultRefObject.getValue(),formula: formulaString,});-- continue;}- item.push({- value: resultRefObject.getValue(),- formula: formulaString,- });+ result[unitId]![sheetId]![row]![column] = item;}-- result[unitId]![sheetId]![row]![column] = item;}}}- }- return result;+ return result;+ } finally {+ this._runtimeService.releaseCalculationCache?.();+ }}async calculate(formulaString: string, transformSuffix = true, unitId?: string) {diff --git a/packages/engine-formula/src/services/current-data.service.ts b/packages/engine-formula/src/services/current-data.service.tsindex 5cdacfa5d1..2592441974 100644--- a/packages/engine-formula/src/services/current-data.service.ts+++ b/packages/engine-formula/src/services/current-data.service.ts@@ -44,10 +44,21 @@ import type {IUnitSheetNameMap,IUnitStylesData,} from '../basics/common';+import type { IFormulaDataSnapshot } from '../models/formula-data-snapshot';import { convertUnitDataToRuntime, copyUnitData } from '../basics/runtime';import { FormulaDataModel } from '../models/formula-data.model';import { ISheetRowFilteredService } from './sheet-row-filtered.service';+const DEFERRED_FORMULA_DATA_SNAPSHOTS = new WeakSet<object>();++/**+ * Internal implementation bookkeeping, not an application integration API.+ * Query deferred-input bookkeeping without observing service Proxy properties or getters.+ */+export function hasDeferredFormulaDataSnapshot(service: unknown): boolean {+ return DEFERRED_FORMULA_DATA_SNAPSHOTS.has(service as object);+}+export interface IFormulaDirtyData {dirtyReferenceUnits?: string[];dirtyIterationUnits?: string[];@@ -67,6 +78,8 @@ export interface IFormulaDirtyData {export interface IFormulaCurrentConfigService {load(config: IFormulaDatasetConfig): void;+ /** Internal engine capability to defer formula DTO materialization. */+ loadWithFormulaDataSnapshot?(config: Omit<IFormulaDatasetConfig, 'formulaData'>, snapshot: IFormulaDataSnapshot): void;getUnitData(): IUnitData;@@ -156,6 +169,7 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaCprivate _arrayFormulaRange: IArrayFormulaRangeType = Object.create(null);private _formulaData: IFormulaData = Object.create(null);+ private _formulaDataSnapshot: IFormulaDataSnapshot | undefined;private _sheetNameMap: IUnitSheetNameMap = Object.create(null);@@ -206,6 +220,8 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaCthis._arrayFormulaCellData = Object.create(null);this._arrayFormulaRange = Object.create(null);this._formulaData = Object.create(null);+ this._formulaDataSnapshot = undefined;+ DEFERRED_FORMULA_DATA_SNAPSHOTS.delete(this);this._sheetNameMap = Object.create(null);this._unitNameMap = Object.create(null);this._externalReferences = Object.create(null);@@ -249,7 +265,13 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaCreturn this._unitStylesData;}- getFormulaData() {+ getFormulaData(): IFormulaData {+ if (this._formulaDataSnapshot) {+ const data = this._formulaDataSnapshot.materialize();+ this._formulaData = data;+ this._formulaDataSnapshot = undefined;+ DEFERRED_FORMULA_DATA_SNAPSHOTS.delete(this);+ }return this._formulaData;}@@ -380,6 +402,15 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaC}load(config: IFormulaDatasetConfig) {+ this._loadFormulaDataset(config);+ }++ /** Internal engine capability to defer formula DTO materialization. */+ loadWithFormulaDataSnapshot(config: Omit<IFormulaDatasetConfig, 'formulaData'>, snapshot: IFormulaDataSnapshot): void {+ this._loadFormulaDataset(config, snapshot);+ }++ private _loadFormulaDataset(config: IFormulaDatasetConfig | Omit<IFormulaDatasetConfig, 'formulaData'>, snapshot?: IFormulaDataSnapshot): void {this._calculationGeneration++;this._calculationRowData = Object.create(null);if (config.allUnitData && config.unitSheetNameMap && config.unitStylesData) {@@ -404,7 +435,10 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaCthis._applyUnitRowData(config.rowData);}- this._formulaData = config.formulaData;+ this._formulaData = snapshot ? Object.create(null) : (config as IFormulaDatasetConfig).formulaData;+ this._formulaDataSnapshot = snapshot;+ if (snapshot) DEFERRED_FORMULA_DATA_SNAPSHOTS.add(this);+ else DEFERRED_FORMULA_DATA_SNAPSHOTS.delete(this);this._dirtyIterationUnits = config.dirtyIterationUnits ?? [];this._dirtyReferenceUnits = config.dirtyReferenceUnits ?? [];@@ -447,6 +481,8 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaCthis._unitNameMap = unitNameMap;this._formulaData = this._formulaDataModel.getFormulaData();+ this._formulaDataSnapshot = undefined;+ DEFERRED_FORMULA_DATA_SNAPSHOTS.delete(this);this._arrayFormulaCellData = convertUnitDataToRuntime(this._formulaDataModel.getArrayFormulaCellData());this._arrayFormulaRange = this._formulaDataModel.getArrayFormulaRange();@@ -490,6 +526,8 @@ export class FormulaCurrentConfigService extends Disposable implements IFormulaCregisterFormulaData(formulaData: IFormulaData) {this._formulaData = formulaData;+ this._formulaDataSnapshot = undefined;+ DEFERRED_FORMULA_DATA_SNAPSHOTS.delete(this);}registerSheetNameMap(sheetNameMap: IUnitSheetNameMap) {diff --git a/packages/engine-formula/src/services/formula-cache.service.ts b/packages/engine-formula/src/services/formula-cache.service.tsnew file mode 100644index 0000000000..18bf03a53e--- /dev/null+++ b/packages/engine-formula/src/services/formula-cache.service.ts@@ -0,0 +1,143 @@+/**+ * 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 { Disposable, LRUMap } from '@univerjs/core';+import type { IFunctionNames } from '../basics/function';+import type { LexerNode } from '../engine/analysis/lexer-node';+import type { AstRootNode } from '../engine/ast-node/ast-root-node';+import type { BaseAstNode } from '../engine/ast-node/base-ast-node';+import type { ArrayValueObject } from '../engine/value-object/array-value-object';+import { FormulaAstLRU } from '../basics/cache-lru';+import { normalizeFunctionToken } from '../basics/function';+import { InvertedIndexCache } from '../basics/inverted-index-cache';+import { prefixToken } from '../basics/token';++function usesFunction(node: BaseAstNode | LexerNode, names: Set<string>): boolean {+ let token = node.getToken().trim().toUpperCase();+ if (token[0] === prefixToken.MINUS || token[0] === prefixToken.AT) token = token.slice(1);+ return names.has(normalizeFunctionToken(token)) || node.getChildren().some((child) =>+ typeof child !== 'string' && usesFunction(child, names));+}++/** Runtime-only context. Values may outlive a calculation, but must not revive its caches. */+export class FormulaCalculationCache extends Disposable {+ readonly references = new FormulaAstLRU<ArrayValueObject>(10000);+ readonly invertedIndex = new InvertedIndexCache();++ get closed(): boolean {+ return this._disposed;+ }++ clearUnit(unitId: string): void {+ this.references.forEach((value, key) => {+ if (value.getUnitId() === unitId) {+ this.references.delete(key);+ }+ });+ this.invertedIndex.deleteUnit(unitId);+ }++ override dispose(): void {+ super.dispose();+ this.references.clear();+ this.invertedIndex.clear();+ }+}++/** One owner per Univer injector; no dependency on the parser, calculator or function registry. */+export class FormulaCacheService extends Disposable {+ private readonly _asts = new LRUMap<string, { unitId: string; node: AstRootNode }>(5000);+ private readonly _lexerTrees = new LRUMap<string, { unitId?: string | null; node: LexerNode }>(2000);+ private readonly _calculations = new Set<FormulaCalculationCache>();++ get closed(): boolean {+ return this._disposed;+ }++ getAst(key: string): AstRootNode | undefined {+ return this._asts.get(key)?.node;+ }++ setAst(key: string, unitId: string, node: AstRootNode): void {+ if (!this._disposed) {+ this._asts.set(key, { unitId, node });+ }+ }++ getLexerTree(key: string): LexerNode | undefined {+ return this._lexerTrees.get(key)?.node;+ }++ setLexerTree(key: string, node: LexerNode, unitId?: string | null): void {+ if (!this._disposed) {+ this._lexerTrees.set(key, { unitId, node });+ }+ }++ clearCompiled(): void {+ this._asts.clear();+ this._lexerTrees.clear();+ }++ clearFunctions(functionNames: IFunctionNames[]): void {+ const names = new Set(functionNames.map((name) => String(name).toUpperCase()));+ this._asts.forEach((entry, key) => {+ if (usesFunction(entry.node, names)) {+ this._asts.delete(key);+ }+ });+ this._lexerTrees.forEach((entry, key) => {+ if (usesFunction(entry.node, names)) {+ this._lexerTrees.delete(key);+ }+ });+ }++ clearUnit(unitId: string): void {+ this._asts.forEach((entry, key) => {+ if (entry.unitId === unitId) {+ this._asts.delete(key);+ }+ });+ this._lexerTrees.forEach((entry, key) => {+ if (entry.unitId === unitId) {+ this._lexerTrees.delete(key);+ }+ });+ this._calculations.forEach((context) => context.clearUnit(unitId));+ }++ createCalculation(): FormulaCalculationCache | undefined {+ if (this._disposed) {+ return;+ }+ const context = new FormulaCalculationCache();+ this._calculations.add(context);+ return context;+ }++ releaseCalculation(context: FormulaCalculationCache): void {+ context.dispose();+ this._calculations.delete(context);+ }++ override dispose(): void {+ super.dispose();+ this.clearCompiled();+ this._calculations.forEach((context) => context.dispose());+ this._calculations.clear();+ }+}diff --git a/packages/engine-formula/src/services/formula-result.service.ts b/packages/engine-formula/src/services/formula-result.service.tsnew file mode 100644index 0000000000..154c5d2675--- /dev/null+++ b/packages/engine-formula/src/services/formula-result.service.ts@@ -0,0 +1,120 @@+/**+ * 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 { Disposable, ICommandService, Inject } from '@univerjs/core';+import type { ISetFormulaCalculationResultMutation } from '../commands/mutations/set-formula-calculation.mutation';+import type { IAllRuntimeData } from './runtime.service';+import { convertRuntimeToUnitData } from '../basics/runtime';+import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';+import { SetFormulaCalculationResultMutation, SetFormulaDependencyCalculationResultMutation } from '../commands/mutations/set-formula-calculation.mutation';+import { SetImageFormulaDataMutation } from '../commands/mutations/set-image-formula-data.mutation';+import { FormulaDataModel } from '../models/formula-data.model';+import { IFormulaRuntimeService } from './runtime.service';++/** Applies calculation batches for every engine; completion notifications never resubmit them. */+export class FormulaResultService extends Disposable {+ constructor(+ @ICommandService private readonly _commandService: ICommandService,+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,+ @IFormulaRuntimeService private readonly _runtimeService: IFormulaRuntimeService+ ) { super(); }++ async applyTreeResult(data: IAllRuntimeData): Promise<void> {+ if (this._disposed || this._runtimeService.isStopExecution()) return;+ const { dependencyTreeModelData } = data;+ if (dependencyTreeModelData.length > 0) {+ await this._commandService.executeCommand(+ SetFormulaDependencyCalculationResultMutation.id,+ {+ result: dependencyTreeModelData,+ },+ {+ onlyLocal: true,+ }+ );+ }+ }++ async applyResult(data: IAllRuntimeData, result?: ISetFormulaCalculationResultMutation): Promise<void> {+ if (this._disposed || this._runtimeService.isStopExecution()) return;+ const {+ unitData,+ sourceFormulaData,+ unitOtherData,+ arrayFormulaRange,+ arrayFormulaCellData,+ clearArrayFormulaCellData,+ arrayFormulaEmbedded,+ imageFormulaData,+ } = data;++ if (!unitData) {+ await this.applyTreeResult(data);+ console.error('No sheetData from Formula Engine!');+ return;+ }++ if (arrayFormulaRange || arrayFormulaEmbedded) {+ this._formulaDataModel.clearPreviousArrayFormulaCellData(clearArrayFormulaCellData);+ this._formulaDataModel.mergeArrayFormulaCellData(arrayFormulaCellData);+ this._formulaDataModel.mergeArrayFormulaRange(arrayFormulaRange);++ await this._commandService.executeCommand(+ SetArrayFormulaDataMutation.id,+ {+ arrayFormulaRange: this._formulaDataModel.getArrayFormulaRange(),+ arrayFormulaCellData: this._formulaDataModel.getArrayFormulaCellData(),+ arrayFormulaEmbedded,+ },+ {+ onlyLocal: true,+ fromFormula: true,+ }+ );+ }++ if (this._disposed || this._runtimeService.isStopExecution()) return;++ // handle image formula data+ if (imageFormulaData && imageFormulaData.length > 0) {+ await this._commandService.executeCommand(+ SetImageFormulaDataMutation.id,+ {+ imageFormulaData,+ },+ {+ onlyLocal: true,+ }+ );+ }++ await this.applyTreeResult(data);+ if (this._disposed || this._runtimeService.isStopExecution()) return;++ await this._commandService.executeCommand(+ SetFormulaCalculationResultMutation.id,+ result ?? {+ unitData: convertRuntimeToUnitData(unitData),+ sourceFormulaData,+ unitOtherData,+ },+ {+ onlyLocal: true,+ applyFormulaCalculationResult: true,+ }+ );+ }+}diff --git a/packages/engine-formula/src/services/formula/__tests__/description.service.spec.ts b/packages/engine-formula/src/services/formula/__tests__/description.service.spec.tsindex 6d1a639bfc..7c88f4cfa1 100644--- a/packages/engine-formula/src/services/formula/__tests__/description.service.spec.ts+++ b/packages/engine-formula/src/services/formula/__tests__/description.service.spec.ts@@ -19,6 +19,7 @@ import { LocaleService, LocaleType, Univer } from '@univerjs/core';import { FunctionService, FunctionType, IFunctionService } from '@univerjs/engine-formula';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import formulaEnUS from '../../../locale/en-US';+import { FormulaCacheService } from '../../formula-cache.service';import { DescriptionService, IDescriptionService } from '../description.service';function createFunctionInfo(overrides: Partial<IFunctionInfo> = {}): IFunctionInfo {@@ -66,6 +67,7 @@ describe('DescriptionService', () => {},});+ injector.add([FormulaCacheService]);injector.add([IFunctionService, { useClass: FunctionService }]);injector.add([IDescriptionService, { useClass: DescriptionService }]);diff --git a/packages/engine-formula/src/services/formula/__tests__/formula-calculation-session.service.spec.ts b/packages/engine-formula/src/services/formula/__tests__/formula-calculation-session.service.spec.tsindex 560ce6965c..5e8a9375cb 100644--- a/packages/engine-formula/src/services/formula/__tests__/formula-calculation-session.service.spec.ts+++ b/packages/engine-formula/src/services/formula/__tests__/formula-calculation-session.service.spec.ts@@ -31,6 +31,143 @@ describe('FormulaCalculationSessionService', () => {vi.useRealTimers();});+ it.skipIf(typeof (globalThis as { gc?: () => void }).gc !== 'function')(+ 'releases the completed result after every model acknowledges it',+ async () => {+ const service = createService();+ service.initialize();+ service.start();+ let applications = 0;+ const subscription = service.resultApplied$.subscribe(() => applications++);+ const reference = (() => {+ const result = { unitData: { book: { sheet: { 0: { 0: { v: 42 } } } } }, unitOtherData: {} };+ const reference = new WeakRef(result);+ service.markResultEmitted(result, [+ FormulaResultApplicationType.SHEET,+ FormulaResultApplicationType.BASE,+ FormulaResultApplicationType.OTHER_FORMULA,+ ]);+ service.markResultApplied(FormulaResultApplicationType.SHEET, result);+ service.markResultApplied(FormulaResultApplicationType.BASE, result);+ expect(applications).toBe(0);+ expect(service.state.resultApplied).toBe(false);+ service.markResultApplied(FormulaResultApplicationType.OTHER_FORMULA, result);+ return reference;+ })();+ expect(applications).toBe(1);+ expect(service.state.resultApplied).toBe(true);+ const collect = (globalThis as { gc?: () => void }).gc;+ expect(collect).toBeTypeOf('function');+ for (let attempt = 0; attempt < 20; attempt++) {+ await new Promise((resolve) => setTimeout(resolve, 0));+ collect!();+ if (reference.deref() == null) break;+ }+ expect(reference.deref()).toBeUndefined();+ expect(applications).toBe(1);+ expect(service.state.resultApplied).toBe(true);+ subscription.unsubscribe();+ service.dispose();+ }+ );++ it('ignores repeated acknowledgements without pre-applying a later result', () => {+ const service = createService();+ const first = { unitData: {}, unitOtherData: {} };+ const second = { unitData: {}, unitOtherData: {} };+ let applications = 0;+ const subscription = service.resultApplied$.subscribe(() => applications++);+ service.start();+ service.markResultEmitted(first, true);+ service.markResultApplied(FormulaResultApplicationType.SHEET, first);+ service.markResultApplied();+ service.markResultApplied(FormulaResultApplicationType.SHEET, first);+ service.markResultEmitted(first, true);+ service.markResultApplied(FormulaResultApplicationType.SHEET, first);+ expect(applications).toBe(1);+ service.markResultEmitted(second, true);+ expect(service.state.resultApplied).toBe(false);+ service.markResultApplied(FormulaResultApplicationType.SHEET, second);+ expect(applications).toBe(2);+ subscription.unsubscribe();+ });++ it('keeps a reentrant next session pending when the previous result is released', () => {+ const service = createService();+ const first = { unitData: {}, unitOtherData: {} };+ const second = { unitData: {}, unitOtherData: {} };+ const applied: ISetFormulaCalculationResultMutation[] = [];+ const subscription = service.resultApplied$.subscribe((result) => {+ applied.push(result);+ if (result === first) {+ service.start();+ service.markResultEmitted(second, true);+ }+ });+ service.start();+ service.markResultEmitted(first, true);+ service.markResultApplied(FormulaResultApplicationType.SHEET, first);+ expect(service.state.id).toBe(2);+ expect(service.state.resultApplied).toBe(false);+ service.markResultApplied(FormulaResultApplicationType.SHEET, first);+ expect(service.state.resultApplied).toBe(false);+ service.markResultApplied(FormulaResultApplicationType.SHEET, second);+ expect(applied).toEqual([first, second]);+ expect(service.state.resultApplied).toBe(true);+ subscription.unsubscribe();+ });++ it.each(['emit', 'ack'] as const)('keeps a session started by the %s state notification pending', (phase) => {+ const service = createService();+ const first = { unitData: {}, unitOtherData: {} };+ const second = { unitData: {}, unitOtherData: {} };+ const applied: ISetFormulaCalculationResultMutation[] = [];+ const resultSubscription = service.resultApplied$.subscribe((result) => applied.push(result));+ service.start();+ let restarted = false;+ const stateSubscription = service.state$.subscribe((state) => {+ if (!restarted && state.id === 1 && state.resultEmitted && state.resultApplied) {+ restarted = true;+ service.start();+ service.markResultEmitted(second, true);+ }+ });+ service.markResultEmitted(first, phase === 'ack');+ if (phase === 'ack') service.markResultApplied(FormulaResultApplicationType.SHEET, first);+ expect(restarted).toBe(true);+ expect(service.state.id).toBe(2);+ expect(service.state.resultApplied).toBe(false);+ expect(applied).toEqual([]);+ service.markResultApplied(FormulaResultApplicationType.SHEET, second);+ expect(applied).toEqual([second]);+ expect(service.state.resultApplied).toBe(true);+ stateSubscription.unsubscribe();+ resultSubscription.unsubscribe();+ service.dispose();+ });++ it('keeps a different result emitted reentrantly in the same session pending', () => {+ const service = createService();+ const first = { unitData: {}, unitOtherData: {} };+ const second = { unitData: {}, unitOtherData: {} };+ const applied: ISetFormulaCalculationResultMutation[] = [];+ const subscription = service.resultApplied$.subscribe((result) => {+ applied.push(result);+ if (result === first) service.markResultEmitted(second, true);+ });+ service.start();+ service.markResultEmitted(first, true);+ service.markResultApplied(FormulaResultApplicationType.SHEET, first);+ expect(service.state.id).toBe(1);+ expect(service.state.resultApplied).toBe(false);+ expect(applied).toEqual([first]);+ service.markResultApplied(FormulaResultApplicationType.SHEET, second);+ expect(applied).toEqual([first, second]);+ expect(service.state.resultApplied).toBe(true);+ subscription.unsubscribe();+ service.dispose();+ });+it('waits for the latest restarted session to be applied', async () => {vi.useFakeTimers();diff --git a/packages/engine-formula/src/services/formula/__tests__/register-function.service.spec.ts b/packages/engine-formula/src/services/formula/__tests__/register-function.service.spec.tsindex f73577f495..01ff25e21d 100644--- a/packages/engine-formula/src/services/formula/__tests__/register-function.service.spec.ts+++ b/packages/engine-formula/src/services/formula/__tests__/register-function.service.spec.ts@@ -17,6 +17,7 @@import { LocaleService, LocaleType, Univer } from '@univerjs/core';import { FunctionService, FunctionType, IFunctionService } from '@univerjs/engine-formula';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { FormulaCacheService } from '../../formula-cache.service';import { DescriptionService, IDescriptionService } from '../description.service';import { IRegisterFunctionService, RegisterFunctionService } from '../register-function.service';@@ -31,6 +32,7 @@ describe('RegisterFunctionService', () => {[LocaleType.ZH_CN]: {},[LocaleType.EN_US]: {},});+ injector.add([FormulaCacheService]);injector.add([IFunctionService, { useClass: FunctionService }]);injector.add([IDescriptionService, { useClass: DescriptionService }]);});diff --git a/packages/engine-formula/src/services/formula/formula-calculation-session.service.ts b/packages/engine-formula/src/services/formula/formula-calculation-session.service.tsindex 54a9c17430..66819f8f55 100644--- a/packages/engine-formula/src/services/formula/formula-calculation-session.service.ts+++ b/packages/engine-formula/src/services/formula/formula-calculation-session.service.ts@@ -15,10 +15,10 @@*/import type { Subscription } from 'rxjs';-import type { ISetFormulaCalculationResultMutation } from '../../commands/mutations/set-formula-calculation.mutation';-import type { IExecutionInProgressParams } from '../runtime.service';import { Disposable } from '@univerjs/core';import { BehaviorSubject, Subject } from 'rxjs';+import type { ISetFormulaCalculationResultMutation } from '../../commands/mutations/set-formula-calculation.mutation';+import type { IExecutionInProgressParams } from '../runtime.service';import { FormulaExecutedStateType, FormulaExecuteStageType } from '../runtime.service';export interface IFormulaCalculationSessionState {@@ -56,6 +56,8 @@ export class FormulaCalculationSessionService extends Disposable {private _currentResult: ISetFormulaCalculationResultMutation | null = null;+ private _lastAppliedResult = new WeakSet<ISetFormulaCalculationResultMutation>();+private _hasEmittedCurrentResultApplied = false;private _pendingResultApplicationTypes = new Set<FormulaResultApplicationType>();@@ -100,6 +102,7 @@ export class FormulaCalculationSessionService extends Disposable {resultApplied: false,});this._currentResult = null;+ this._lastAppliedResult = new WeakSet();this._hasEmittedCurrentResultApplied = false;this._pendingResultApplicationTypes.clear();this._preAppliedSessionTypes.clear();@@ -146,8 +149,9 @@ export class FormulaCalculationSessionService extends Disposable {result: ISetFormulaCalculationResultMutation,pendingApplications: boolean | Iterable<FormulaResultApplicationType>): void {- if (this._currentResult !== result) {+ if (this._currentResult !== result && !(this._currentResult == null && this._lastAppliedResult.has(result))) {this._hasEmittedCurrentResultApplied = false;+ this._lastAppliedResult = new WeakSet();}this._currentResult = result;@@ -159,13 +163,14 @@ export class FormulaCalculationSessionService extends Disposable {preAppliedTypes?.forEach((type) => this._pendingResultApplicationTypes.delete(type));this._preAppliedSessionTypes.clear();const resultApplied = this._pendingResultApplicationTypes.size === 0;+ const sessionId = this.state.id;this._emit({...this.state,resultEmitted: true,resultApplied,});- if (resultApplied) {+ if (resultApplied && this.state.id === sessionId && this._currentResult === result) {this._emitResultApplied();}}@@ -174,6 +179,12 @@ export class FormulaCalculationSessionService extends Disposable {type = FormulaResultApplicationType.SHEET,result?: ISetFormulaCalculationResultMutation): void {+ if (+ this._currentResult == null && this._hasEmittedCurrentResultApplied &&+ (result == null || this._lastAppliedResult.has(result))+ ) {+ return;+ }if (result && this._currentResult !== result) {const types = this._preAppliedResultTypes.get(result) ?? new Set<FormulaResultApplicationType>();types.add(type);@@ -191,11 +202,15 @@ export class FormulaCalculationSessionService extends Disposable {return;}+ const currentResult = this._currentResult;+ const sessionId = this.state.id;this._emit({...this.state,resultApplied: true,});- this._emitResultApplied();+ if (this.state.id === sessionId && this._currentResult === currentResult) {+ this._emitResultApplied();+ }}// eslint-disable-next-line max-lines-per-function@@ -332,12 +347,21 @@ export class FormulaCalculationSessionService extends Disposable {}private _emitResultApplied(): void {- if (this._currentResult == null || this._hasEmittedCurrentResultApplied) {+ if (this._currentResult == null || this._pendingResultApplicationTypes.size > 0) {return;}- this._hasEmittedCurrentResultApplied = true;- this._resultApplied$.next(this._currentResult);+ const result = this._currentResult;+ const sessionId = this.state.id;+ if (!this._hasEmittedCurrentResultApplied) {+ this._hasEmittedCurrentResultApplied = true;+ this._resultApplied$.next(result);+ }+ if (this.state.id === sessionId && this._currentResult === result && this._pendingResultApplicationTypes.size === 0) {+ // Keep duplicate-ACK identity without retaining the completed workbook result.+ this._lastAppliedResult = new WeakSet([result]);+ this._currentResult = null;+ }}private _isAppliedTerminalState(state: IFormulaCalculationSessionState): boolean {diff --git a/packages/engine-formula/src/services/function.service.ts b/packages/engine-formula/src/services/function.service.tsindex c3e6063e34..25582ecdff 100644--- a/packages/engine-formula/src/services/function.service.ts+++ b/packages/engine-formula/src/services/function.service.ts@@ -17,8 +17,8 @@import type { IDisposable, Nullable } from '@univerjs/core';import type { IFunctionInfo, IFunctionNames } from '../basics/function';import type { BaseFunction } from '../functions/base-function';-import { createIdentifier, Disposable, toDisposable } from '@univerjs/core';-import { FORMULA_AST_CACHE } from '../engine/utils/generate-ast-node';+import { createIdentifier, Disposable, Inject, toDisposable } from '@univerjs/core';+import { FormulaCacheService } from './formula-cache.service';export interface IFunctionService {/**@@ -65,6 +65,10 @@ export class FunctionService extends Disposable implements IFunctionService {private _functionDescriptions: Map<IFunctionNames, IFunctionInfo> = new Map();+ constructor(@Inject(FormulaCacheService) private readonly _cacheService: FormulaCacheService) {+ super();+ }+override dispose(): void {super.dispose();this._functionExecutors.clear();@@ -72,6 +76,7 @@ export class FunctionService extends Disposable implements IFunctionService {}registerExecutors(...functions: BaseFunction[]) {+ this._cacheService.clearFunctions(functions.map((executor) => executor.name));for (let i = 0; i < functions.length; i++) {const func = functions[i];this._functionExecutors.set(func.name, func);@@ -91,6 +96,7 @@ export class FunctionService extends Disposable implements IFunctionService {}unregisterExecutors(...functionTokens: IFunctionNames[]) {+ this._cacheService.clearFunctions(functionTokens);for (let i = 0; i < functionTokens.length; i++) {const functionToken = functionTokens[i];this._functionExecutors.delete(functionToken);@@ -135,12 +141,6 @@ export class FunctionService extends Disposable implements IFunctionService {}deleteFormulaAstCacheKey(...functionToken: IFunctionNames[]) {- FORMULA_AST_CACHE.forEach((_, key) => {- functionToken.forEach((token) => {- if (key.includes(token as string)) {- FORMULA_AST_CACHE.delete(key);- }- });- });+ this._cacheService.clearFunctions(functionToken);}}diff --git a/packages/engine-formula/src/services/runtime.service.ts b/packages/engine-formula/src/services/runtime.service.tsindex b9431bf6da..718b63ef3c 100644--- a/packages/engine-formula/src/services/runtime.service.ts+++ b/packages/engine-formula/src/services/runtime.service.ts@@ -31,18 +31,28 @@ import type { BaseReferenceObject, FunctionVariantType } from '../engine/referenimport type { ArrayValueObject } from '../engine/value-object/array-value-object';import type { BaseValueObject } from '../engine/value-object/base-value-object';import type { StringValueObject } from '../engine/value-object/primitive-object';-import { CellValueType, createIdentifier, Disposable, isNullCell, isRealNum, IUniverInstanceService, ObjectMatrix, UniverInstanceType } from '@univerjs/core';+import type { FormulaCalculationCache } from './formula-cache.service';+import {+ CellValueType,+ createIdentifier,+ Disposable,+ Inject,+ isNullCell,+ isRealNum,+ IUniverInstanceService,+ ObjectMatrix,+ UniverInstanceType,+} 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 { FORMULA_REF_TO_ARRAY_CACHE } from '../engine/reference-object/base-reference-object';import { getRuntimeFeatureCell } from '../engine/utils/get-runtime-feature-cell';import { clearNumberFormatTypeCache, clearStringToNumberPatternCache } from '../engine/utils/numfmt-kit';import { clearReferenceToRangeCache } from '../engine/utils/reference-cache';import { objectValueToCellValue } from '../engine/utils/value-object';import { ErrorValueObject } from '../engine/value-object/base-value-object';import { NumberValueObject } from '../engine/value-object/primitive-object';-import { IFormulaCurrentConfigService } from './current-data.service';+import { hasDeferredFormulaDataSnapshot, IFormulaCurrentConfigService } from './current-data.service';+import { FormulaCacheService } from './formula-cache.service';import { IHyperlinkEngineFormulaService } from './hyperlink-engine-formula.service';/**@@ -125,7 +135,12 @@ export interface IFormulaRuntimeService {dispose(): void;reset(): void;- beginCircularReferences(): void;+ /** Custom runtimes without cache hooks continue to compute uncached values. */+ getCalculationCache?(): FormulaCalculationCache | undefined;+ clearInvertedIndexCache?(): void;+ releaseCalculationCache?(): void;+ /** Start empty when the engine will supply the complete current cycle set. */+ beginCircularReferences(clearPrevious?: boolean): void;clearCircularReferenceCells(cells: { unitId: string; subUnitId: string; row: number; column: number }[]): void;recordCircularReferences(cells: ICircularReference[]): void;completeCircularReferences(): void;@@ -230,6 +245,7 @@ export interface IFormulaRuntimeService {}export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeService {+ private _calculationCache: FormulaCalculationCache | undefined;private _formulaExecuteStage: FormulaExecuteStageType = FormulaExecuteStageType.IDLE;private _circularReferences = new Map<string, ICircularReference>();@@ -289,6 +305,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeprivate _dependencyTreeModelData: IFormulaDependencyTreeJson[] = [];constructor(+ @Inject(FormulaCacheService) private readonly _cacheService: FormulaCacheService,@IFormulaCurrentConfigService private readonly _currentConfigService: IFormulaCurrentConfigService,@IHyperlinkEngineFormulaService private readonly _hyperlinkEngineFormulaService: IHyperlinkEngineFormulaService,@IUniverInstanceService private readonly _univerInstanceService: IUniverInstanceService@@ -420,7 +437,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime}isStopExecution() {- return this._stopState;+ return this._stopState || this._disposed;}setFormulaExecuteStage(type: FormulaExecuteStageType) {@@ -431,7 +448,26 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimereturn this._formulaExecuteStage;}+ getCalculationCache(): FormulaCalculationCache | undefined {+ if (this._disposed || this._cacheService.closed) {+ return;+ }+ return this._calculationCache ??= this._cacheService.createCalculation();+ }++ clearInvertedIndexCache(): void {+ this._calculationCache?.invertedIndex.clear();+ }++ releaseCalculationCache(): void {+ if (this._calculationCache) {+ this._cacheService.releaseCalculation(this._calculationCache);+ this._calculationCache = undefined;+ }+ }+reset() {+ this.releaseCalculationCache();this._formulaExecuteStage = FormulaExecuteStageType.IDLE;this._runtimeData = Object.create(null);this._sourceFormulaData = Object.create(null);@@ -463,8 +499,10 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeclearReferenceToRangeCache();}- beginCircularReferences(): void {- this._pendingCircularReferences = new Map(this._circularReferences);+ beginCircularReferences(clearPrevious = false): void {+ this._pendingCircularReferences = clearPrevious ? new Map() : new Map(this._circularReferences);+ if (clearPrevious) return;+ if (this._pendingCircularReferences.size === 0 && hasDeferredFormulaDataSnapshot(this._currentConfigService)) return;const formulaData = this._currentConfigService.getFormulaData();for (const [key, cell] of this._pendingCircularReferences) {if (!formulaData[cell.unitId]?.[cell.sheetId]?.[cell.row]?.[cell.column]) {@@ -573,6 +611,9 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime}setRuntimeOtherData(formulaId: string, x: number, y: number, functionVariant: FunctionVariantType) {+ if (this._disposed) {+ return;+ }const subUnitId = this._currentSubUnitId;const unitId = this._currentUnitId;@@ -629,6 +670,9 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime// eslint-disable-next-line max-lines-per-functionsetRuntimeData(functionVariant: FunctionVariantType) {+ if (this._disposed) {+ return;+ }if (this._externalReferenceUnavailable) {const cell = this._currentConfigService.getUnitData()[this._currentUnitId]?.[this._currentSubUnitId]?.cellData@@ -722,7 +766,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeclearArrayUnitData.setValue(row, column, valueObject);// Formula calculation results are saved to cache- CELL_INVERTED_INDEX_CACHE.set(+ this.getCalculationCache()?.invertedIndex.set(unitId,sheetId,column,@@ -740,7 +784,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeclearArrayUnitData.setValue(row, column, errorObject);runtimeArrayUnitData.setValue(row, column, errorObject);- CELL_INVERTED_INDEX_CACHE.set(+ this.getCalculationCache()?.invertedIndex.set(unitId,sheetId,column,@@ -771,7 +815,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeclearArrayUnitData.setValue(row, column, errorObject);// Formula calculation results are saved to cache- CELL_INVERTED_INDEX_CACHE.set(+ this.getCalculationCache()?.invertedIndex.set(unitId,sheetId,column,@@ -815,7 +859,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeconst spillError = ErrorValueObject.create(ErrorType.SPILL);objectValueRefOrArray.iterator((valueObject, rowIndex, columnIndex) => {// Formula calculation results are saved to cache- CELL_INVERTED_INDEX_CACHE.set(+ this.getCalculationCache()?.invertedIndex.set(unitId,sheetId,column - startColumn + columnIndex,@@ -869,7 +913,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime}// Formula calculation results are saved to cache- CELL_INVERTED_INDEX_CACHE.set(+ this.getCalculationCache()?.invertedIndex.set(unitId,sheetId,column,@@ -1005,7 +1049,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntime}clearArrayObjectCache() {- FORMULA_REF_TO_ARRAY_CACHE.clear();+ this._calculationCache?.references.clear();}private _checkIfArrayFormulaRangeHasData(diff --git a/packages/sheets-conditional-formatting/src/facade/__tests__/create-test-bed.ts b/packages/sheets-conditional-formatting/src/facade/__tests__/create-test-bed.tsindex 4d6901c6a0..b3ff34225e 100644--- a/packages/sheets-conditional-formatting/src/facade/__tests__/create-test-bed.ts+++ b/packages/sheets-conditional-formatting/src/facade/__tests__/create-test-bed.ts@@ -14,44 +14,21 @@* limitations under the License.*/-import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';+import type { Dependency, Injector, IWorkbookData, UnitModel } from '@univerjs/core';import type { IRender } from '@univerjs/engine-render';import {ILogService,- Inject,- Injector,IUniverInstanceService,LocaleService,LocaleType,LogLevel,- Plugin,set,ThemeService,Univer,UniverInstanceType,} from '@univerjs/core';import { FUniver } from '@univerjs/core/facade';-import {- ActiveDirtyManagerService,- DefinedNamesService,- DescriptionService,- FormulaCalculationSessionController,- FormulaCalculationSessionService,- FormulaDataModel,- FunctionService,- IActiveDirtyManagerService,- IDefinedNamesService,- IDescriptionService,- IFunctionService,- IRegisterFunctionService,- ISheetRowFilteredService,- ISuperTableService,- LexerTreeBuilder,- RegisterFunctionService,- RegisterOtherFormulaService,- SheetRowFilteredService,- SuperTableService,-} from '@univerjs/engine-formula';+import { FormulaCalculationSessionController, UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { Engine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import {RefRangeService,@@ -145,33 +122,18 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:const univer = new Univer();const injector = univer.__getInjector();- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();const injector = this._injector;injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);injector.add([IRenderManagerService, { useClass: RenderManagerServiceTestBed }]);injector.add([SheetSkeletonService]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder]);injector.add([RefRangeService]);- injector.add([IFunctionService, { useClass: FunctionService }]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);- injector.add([ISuperTableService, { useClass: SuperTableService }]);- injector.add([IDescriptionService, { useClass: DescriptionService }]);- injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);- injector.add([FormulaCalculationSessionService]);- injector.add([FormulaCalculationSessionController]);// register feature modules([@@ -183,14 +145,11 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:[ConditionalFormattingRuleModel],[ConditionalFormattingRangeIndexModel],[ConditionalFormattingViewModel],- [RegisterOtherFormulaService],- [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],- [ISheetRowFilteredService, { useClass: SheetRowFilteredService }],] as Dependency[]).forEach((d) => {injector.add(d);});- dependencies?.forEach((d) => injector.add(d));+ dependencies?.forEach((d) => injector.replace(d.length === 1 ? [d[0], { useClass: d[0] }] : d));this._injector.get(SheetInterceptorService);this._injector.get(FormulaCalculationSessionController);@@ -214,7 +173,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:// register builtin plugins// note that UI plugins are not registered here, because the unit test environment does not have a UI- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, workbookData || getTestWorkbookDataDemo());const univerInstanceService = injector.get(IUniverInstanceService);diff --git a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting.service.spec.ts b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting.service.spec.tsindex c133b399fb..2d9d74c400 100644--- a/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting.service.spec.ts+++ b/packages/sheets-conditional-formatting/src/services/__tests__/conditional-formatting.service.spec.ts@@ -165,7 +165,26 @@ describe('ConditionalFormattingService', () => {expect(clearCache).toHaveBeenCalled();});+ it.each(['missing', 'empty', 'other-sheet'])('does not scan changed cells without sheet rules (%s)', (rules) => {+ if (rules === 'empty') {+ unitRules = new Map([['sheet-1', []]]);+ } else if (rules === 'other-sheet') {+ unitRules = new Map([['sheet-2', [{ cfId: 'cf-1', ranges: [] }]]]);+ }+ const readRow = vi.fn(() => ({ 2: { v: 10 } }));+ const cellValue = Object.defineProperty({}, '1', { enumerable: true, get: readRow });++ commandListener({+ id: SetRangeValuesMutation.id,+ params: { unitId: 'book-1', subUnitId: 'sheet-1', cellValue },+ });++ expect(readRow).not.toHaveBeenCalled();+ expect(markRuleDirty).not.toHaveBeenCalled();+ });+it('marks affected conditional-formatting rules dirty after cell value and reorder mutations', () => {+ unitRules = new Map([['sheet-1', [{ cfId: 'cf-1', ranges: [] }]]]);commandListener({id: SetRangeValuesMutation.id,params: {diff --git a/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts b/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.tsindex 73d18b6018..35b45347a3 100644--- a/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts+++ b/packages/sheets-conditional-formatting/src/services/conditional-formatting.service.ts@@ -230,6 +230,9 @@ export class ConditionalFormattingService extends Disposable {case SetRangeValuesMutation.id: {const params = commandInfo.params as ISetRangeValuesMutationParams;const { subUnitId, unitId, cellValue } = params;+ if (!this._conditionalFormattingRuleModel.getSubunitRules(unitId, subUnitId)?.length) {+ break;+ }const ranges: IRange[] = [];new ObjectMatrix(cellValue).forValue((row, col, value) => {// When P and V are involveddiff --git a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsx b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsxindex a337e1d2d7..f87bff5d4f 100644--- a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsx+++ b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationDetail.spec.tsx@@ -33,12 +33,9 @@ import {DataValidationType,ICommandService,ILogService,- Inject,- Injector,LocaleService,LocaleType,LogLevel,- Plugin,set,ThemeService,toDisposable,@@ -46,21 +43,7 @@ import {UniverInstanceType,} from '@univerjs/core';import { AddDataValidationMutation, DataValidationModel, DataValidatorRegistryService, UniverDataValidationPlugin } from '@univerjs/data-validation';-import {- ActiveDirtyManagerService,- DefinedNamesService,- FormulaDataModel,- FunctionService,- IActiveDirtyManagerService,- IDefinedNamesService,- IFunctionService,- ISheetRowFilteredService,- ISuperTableService,- LexerTreeBuilder,- RegisterOtherFormulaService,- SheetRowFilteredService,- SuperTableService,-} from '@univerjs/engine-formula';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { CanvasColorService, ICanvasColorService, IRenderManagerService } from '@univerjs/engine-render';import {RangeProtectionRuleModel,@@ -402,18 +385,13 @@ function createDetailTestBed(rule: ISheetDataValidationRule) {const univer = new Univer();const injector = univer.__getInjector();- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'sheets-data-validation-ui-detail-behavior-test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();+ this._injector.replace([IDescriptionService, { useClass: TestDescriptionService }]);([[SheetsSelectionsService],[SheetInterceptorService],@@ -421,7 +399,6 @@ function createDetailTestBed(rule: ISheetDataValidationRule) {[ComponentManager],[IDialogService, { useClass: TestDialogService }],[IEditorService, { useClass: TestEditorService }],- [IDescriptionService, { useClass: TestDescriptionService }],[ICanvasColorService, { useClass: CanvasColorService }],[IRenderManagerService, { useClass: TestRenderManagerService as never }],[IPlatformService, { useClass: PlatformService }],@@ -433,20 +410,12 @@ function createDetailTestBed(rule: ISheetDataValidationRule) {[WorksheetProtectionPointModel],[WorksheetProtectionRuleModel],[RangeProtectionRuleModel],- [FormulaDataModel],- [LexerTreeBuilder],[RefRangeService],- [IFunctionService, { useClass: FunctionService }],- [IDefinedNamesService, { useClass: DefinedNamesService }],- [ISuperTableService, { useClass: SuperTableService }],[DataValidationCacheService],[DataValidationListCacheService],[DataValidationFormulaService],[DataValidationCustomFormulaService],[DataValidationFormulaController],- [RegisterOtherFormulaService],- [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],- [ISheetRowFilteredService, { useClass: SheetRowFilteredService }],[SheetsDataValidationValidatorService],[SheetDataValidationModel],[IMarkSelectionService, { useClass: TestMarkSelectionService as never }],@@ -457,6 +426,8 @@ function createDetailTestBed(rule: ISheetDataValidationRule) {this._injector.get(WorkbookPermissionService);this._injector.get(WorksheetPermissionService);}++ override onReady(): void {}}injector.get(LocaleService).load({@@ -520,7 +491,7 @@ function createDetailTestBed(rule: ISheetDataValidationRule) {themeService.setTheme(set(themeService.getCurrentTheme(), 'gray.1000', '#35322b'));univer.registerPlugin(UniverDataValidationPlugin);- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());injector.get(ILogService).setLogLevel(LogLevel.SILENT);diff --git a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsx b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsxindex c602d5d372..47ab54e21c 100644--- a/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsx+++ b/packages/sheets-data-validation-ui/src/views/components/__tests__/DataValidationItem.spec.tsx@@ -30,14 +30,11 @@ import {DataValidationType,ICommandService,ILogService,- Inject,- Injector,IPermissionService,IUniverInstanceService,LocaleService,LocaleType,LogLevel,- Plugin,set,ThemeService,toDisposable,@@ -50,21 +47,7 @@ import {DataValidatorRegistryService,UniverDataValidationPlugin,} from '@univerjs/data-validation';-import {- ActiveDirtyManagerService,- DefinedNamesService,- FormulaDataModel,- FunctionService,- IActiveDirtyManagerService,- IDefinedNamesService,- IFunctionService,- ISheetRowFilteredService,- ISuperTableService,- LexerTreeBuilder,- RegisterOtherFormulaService,- SheetRowFilteredService,- SuperTableService,-} from '@univerjs/engine-formula';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { CanvasColorService, ICanvasColorService, IRenderManagerService } from '@univerjs/engine-render';import {RangeProtectionRuleModel,@@ -369,25 +352,19 @@ function createItemTestBed(rule: ISheetDataValidationRule = createCheckboxRule()const univer = new Univer();const injector = univer.__getInjector();- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'sheets-data-validation-ui-item-test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();+ this._injector.replace([IDescriptionService, { useClass: TestDescriptionService }]);([[SheetsSelectionsService],[SheetInterceptorService],[SheetSkeletonService],[ComponentManager],[IEditorService, { useClass: TestEditorService }],- [IDescriptionService, { useClass: TestDescriptionService }],[ICanvasColorService, { useClass: CanvasColorService }],[IRenderManagerService, { useClass: TestRenderManagerService as never }],[IPlatformService, { useClass: PlatformService }],@@ -399,19 +376,11 @@ function createItemTestBed(rule: ISheetDataValidationRule = createCheckboxRule()[WorksheetProtectionPointModel],[WorksheetProtectionRuleModel],[RangeProtectionRuleModel],- [FormulaDataModel],- [LexerTreeBuilder],[RefRangeService],- [IFunctionService, { useClass: FunctionService }],- [IDefinedNamesService, { useClass: DefinedNamesService }],- [ISuperTableService, { useClass: SuperTableService }],[DataValidationCacheService],[DataValidationListCacheService],[DataValidationFormulaService],[DataValidationCustomFormulaService],- [RegisterOtherFormulaService],- [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],- [ISheetRowFilteredService, { useClass: SheetRowFilteredService }],[SheetsDataValidationValidatorService],[SheetDataValidationModel],[IMarkSelectionService, { useClass: TestMarkSelectionService as never }],@@ -448,7 +417,7 @@ function createItemTestBed(rule: ISheetDataValidationRule = createCheckboxRule()themeService.setTheme(set(themeService.getCurrentTheme(), 'gray.1000', '#35322b'));univer.registerPlugin(UniverDataValidationPlugin);- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const workbook = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());injector.get(IUniverInstanceService).focusUnit(UNIT_ID);diff --git a/packages/sheets-data-validation/src/facade/__tests__/create-test-bed.ts b/packages/sheets-data-validation/src/facade/__tests__/create-test-bed.tsindex 047f61aff0..dc76c4cd1e 100644--- a/packages/sheets-data-validation/src/facade/__tests__/create-test-bed.ts+++ b/packages/sheets-data-validation/src/facade/__tests__/create-test-bed.ts@@ -14,16 +14,13 @@* limitations under the License.*/-import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';+import type { Dependency, Injector, IWorkbookData, UnitModel } from '@univerjs/core';import {ILogService,- Inject,- Injector,IUniverInstanceService,LocaleService,LocaleType,LogLevel,- Plugin,set,ThemeService,Univer,@@ -31,27 +28,7 @@ import {} from '@univerjs/core';import { FUniver } from '@univerjs/core/facade';import { UniverDataValidationPlugin } from '@univerjs/data-validation';-import {- ActiveDirtyManagerService,- DefinedNamesService,- DescriptionService,- FormulaCalculationSessionController,- FormulaCalculationSessionService,- FormulaDataModel,- FunctionService,- IActiveDirtyManagerService,- IDefinedNamesService,- IDescriptionService,- IFunctionService,- IRegisterFunctionService,- ISheetRowFilteredService,- ISuperTableService,- LexerTreeBuilder,- RegisterFunctionService,- RegisterOtherFormulaService,- SheetRowFilteredService,- SuperTableService,-} from '@univerjs/engine-formula';+import { FormulaCalculationSessionController, UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import {RefRangeService,SheetInterceptorService,@@ -131,32 +108,17 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:const univer = new Univer();const injector = univer.__getInjector();- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();const injector = this._injector;injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);injector.add([SheetSkeletonService]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder]);injector.add([RefRangeService]);- injector.add([IFunctionService, { useClass: FunctionService }]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);- injector.add([ISuperTableService, { useClass: SuperTableService }]);- injector.add([IDescriptionService, { useClass: DescriptionService }]);- injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);- injector.add([FormulaCalculationSessionService]);- injector.add([FormulaCalculationSessionController]);// register feature modules([@@ -165,9 +127,6 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:[DataValidationListCacheService],[DataValidationFormulaService],[DataValidationCustomFormulaService],- [RegisterOtherFormulaService],- [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],- [ISheetRowFilteredService, { useClass: SheetRowFilteredService }],[SheetsDataValidationValidatorService],[SheetDataValidationModel],[DataValidationController],@@ -175,7 +134,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:injector.add(d);});- dependencies?.forEach((d) => injector.add(d));+ dependencies?.forEach((d) => injector.replace(d.length === 1 ? [d[0], { useClass: d[0] }] : d));this._injector.get(SheetInterceptorService);this._injector.get(FormulaCalculationSessionController);@@ -199,7 +158,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:// register builtin plugins// note that UI plugins are not registered here, because the unit test environment does not have a UIuniver.registerPlugin(UniverDataValidationPlugin);- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, workbookData || getTestWorkbookDataDemo());const univerInstanceService = injector.get(IUniverInstanceService);diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/create-command-test-bed.ts b/packages/sheets-formula-ui/src/controllers/__tests__/create-command-test-bed.tsindex efede9fc99..b2375b736d 100644--- a/packages/sheets-formula-ui/src/controllers/__tests__/create-command-test-bed.ts+++ b/packages/sheets-formula-ui/src/controllers/__tests__/create-command-test-bed.ts@@ -14,34 +14,18 @@* limitations under the License.*/-import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';+import type { Dependency, Injector, IWorkbookData, Workbook } from '@univerjs/core';import {ILogService,- Inject,- Injector,IUniverInstanceService,LocaleType,LogLevel,- Plugin,Univer,UniverInstanceType,} from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';import { EditorService, IEditorService } from '@univerjs/docs-ui';-import {- CalculateFormulaService,- DefinedNamesService,- FormulaCurrentConfigService,- FormulaDataModel,- FormulaRuntimeService,- HyperlinkEngineFormulaService,- ICalculateFormulaService,- IDefinedNamesService,- IFormulaCurrentConfigService,- IFormulaRuntimeService,- IHyperlinkEngineFormulaService,- LexerTreeBuilder,-} from '@univerjs/engine-formula';+import { CalculateFormulaService, FormulaCurrentConfigService, FormulaDataModel, FormulaResultService, FormulaRuntimeService, ICalculateFormulaService, IFormulaCurrentConfigService, IFormulaRuntimeService, UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import {DefinedNameDataController,@@ -114,20 +98,14 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?const get = injector.get.bind(injector);const has = injector.has.bind(injector);- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {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 {+ super.onStarting();const injector = this._injector;injector.add([WorksheetPermissionService]);injector.add([WorksheetProtectionPointModel]);@@ -137,13 +115,10 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);injector.add([SheetSkeletonService]);+ injector.add([FormulaResultService]);injector.add([ICalculateFormulaService, { useClass: CalculateFormulaService }]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder]);injector.add([DocSelectionManagerService]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);injector.add([DefinedNameDataController]);- injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);const hasSheetSkeletonManagerService = dependencies?.some((dependency) =>@@ -157,7 +132,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?injector.add([IRenderManagerService, { useClass: RenderManagerService }]);injector.add([IRefSelectionsService, { useClass: SheetsSelectionsService }]);- dependencies?.forEach((d) => injector.add(d));+ dependencies?.forEach((d) => injector.replace(d.length === 1 ? [d[0], { useClass: d[0] }] : d));this._injector.get(SheetInterceptorService);this._injector.get(WorkbookPermissionService);@@ -170,7 +145,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?}}- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookData || TEST_WORKBOOK_DATA_DEMO);const univerInstanceService = injector.get(IUniverInstanceService);diff --git a/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts b/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.tsindex 6a90a3475d..9cec3dc9b0 100644--- a/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts+++ b/packages/sheets-formula-ui/src/controllers/__tests__/formula-clipboard.controller.spec.ts@@ -23,35 +23,18 @@ import {FormulaType,ICommandService,ILogService,- Inject,Injector,IUniverInstanceService,LocaleService,LocaleType,LogLevel,ObjectMatrix,- Plugin,RANGE_TYPE,UndoCommand,Univer,UniverInstanceType,} from '@univerjs/core';-import {- CalculateFormulaService,- DefinedNamesService,- FormulaCurrentConfigService,- FormulaDataModel,- FormulaRuntimeService,- HyperlinkEngineFormulaService,- ICalculateFormulaService,- IDefinedNamesService,- IFormulaCurrentConfigService,- IFormulaRuntimeService,- IHyperlinkEngineFormulaService,- LexerTreeBuilder,- SetArrayFormulaDataMutation,- SetFormulaDataMutation,-} from '@univerjs/engine-formula';+import { CalculateFormulaService, FormulaCurrentConfigService, FormulaDataModel, FormulaResultService, FormulaRuntimeService, ICalculateFormulaService, IFormulaCurrentConfigService, IFormulaRuntimeService, LexerTreeBuilder, SetArrayFormulaDataMutation, SetFormulaDataMutation, UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import {discreteRangeToRange,@@ -258,18 +241,12 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: De/*** This plugin hooks into Sheet's DI system to expose API to test scripts*/- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();const injector = this._injector;injector.add([IUIPartsService, { useClass: UIPartsService }]);injector.add([SheetsSelectionsService]);@@ -287,25 +264,24 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: Deinjector.add([SheetClipboardController, { useValue: sheetClipboardController }]);injector.add([SheetInterceptorService]);+ injector.add([FormulaResultService]);injector.add([ICalculateFormulaService, { useClass: CalculateFormulaService }]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);- injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);injector.add([SheetSkeletonService]);- dependencies?.forEach((d) => injector.add(d));+ dependencies?.forEach((d) => injector.replace(d.length === 1 ? [d[0], { useClass: d[0] }] : d));const localeService = injector.get(LocaleService);localeService.load({});injector.get(IUIPartsService);}++ override onReady(): void {}}- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookData || {});const univerInstanceService = get(IUniverInstanceService);diff --git a/packages/sheets-formula-ui/src/facade/__tests__/create-formula-test-bed.ts b/packages/sheets-formula-ui/src/facade/__tests__/create-formula-test-bed.tsindex 75992d68bb..a8d4da0e5a 100644--- a/packages/sheets-formula-ui/src/facade/__tests__/create-formula-test-bed.ts+++ b/packages/sheets-formula-ui/src/facade/__tests__/create-formula-test-bed.ts@@ -14,69 +14,18 @@* limitations under the License.*/-import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';+import type { Dependency, Injector, IWorkbookData, Workbook } from '@univerjs/core';import {ILogService,- Inject,- Injector,IUniverInstanceService,LocaleService,LocaleType,LogLevel,- Plugin,Univer,UniverInstanceType,} from '@univerjs/core';import { FUniver } from '@univerjs/core/facade';-import {- ActiveDirtyManagerService,- AstRootNodeFactory,- AstTreeBuilder,- CalculateController,- CalculateFormulaService,- DefinedNamesService,- DependencyManagerService,- DescriptionService,- FeatureCalculationManagerService,- FormulaCurrentConfigService,- FormulaDataModel,- FormulaDependencyGenerator,- FormulaRuntimeService,- FunctionNodeFactory,- FunctionService,- HyperlinkEngineFormulaService,- IActiveDirtyManagerService,- ICalculateFormulaService,- IDefinedNamesService,- IDependencyManagerService,- IDescriptionService,- IFeatureCalculationManagerService,- IFormulaCurrentConfigService,- IFormulaExternalReferenceDataLoader,- IFormulaRuntimeService,- IFunctionService,- IHyperlinkEngineFormulaService,- Interpreter,- IOtherFormulaManagerService,- IRegisterFunctionService,- ISheetRowFilteredService,- ISuperTableService,- LambdaNodeFactory,- LambdaParameterNodeFactory,- Lexer,- LexerTreeBuilder,- NoopFormulaExternalReferenceDataLoader,- OperatorNodeFactory,- OtherFormulaManagerService,- PrefixNodeFactory,- ReferenceNodeFactory,- RegisterFunctionService,- SheetRowFilteredService,- SuffixNodeFactory,- SuperTableService,- UnionNodeFactory,- ValueNodeFactory,-} from '@univerjs/engine-formula';+import { AstRootNodeFactory, AstTreeBuilder, CalculateController, CalculateFormulaService, DependencyManagerService, DescriptionService, FeatureCalculationManagerService, FormulaCurrentConfigService, FormulaDependencyGenerator, FormulaResultService, FormulaRuntimeService, FunctionNodeFactory, ICalculateFormulaService, IDependencyManagerService, IDescriptionService, IFeatureCalculationManagerService, IFormulaCurrentConfigService, IFormulaExternalReferenceDataLoader, IFormulaRuntimeService, Interpreter, IOtherFormulaManagerService, LambdaNodeFactory, LambdaParameterNodeFactory, Lexer, NoopFormulaExternalReferenceDataLoader, OperatorNodeFactory, OtherFormulaManagerService, PrefixNodeFactory, ReferenceNodeFactory, SuffixNodeFactory, UnionNodeFactory, UniverFormulaEnginePlugin, ValueNodeFactory } from '@univerjs/engine-formula';import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';import enUS from '@univerjs/sheets-formula-ui/locale/en-US';@@ -137,18 +86,12 @@ export function createFormulaTestBed(workbookData?: IWorkbookData, dependencies?const univer = new Univer();const injector = univer.__getInjector();- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();const injector = this._injector;injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);@@ -156,13 +99,15 @@ export function createFormulaTestBed(workbookData?: IWorkbookData, dependencies?registerFormulaDependencies(injector);- dependencies?.forEach((d) => injector.add(d));+ dependencies?.forEach((d) => injector.replace(d.length === 1 ? [d[0], { useClass: d[0] }] : d));}++ override onReady(): void {}}injector.get(LocaleService).load({ zhCN, enUS });- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookData || getTestWorkbookDataDemo());const univerInstanceService = injector.get(IUniverInstanceService);@@ -182,31 +127,22 @@ export function createFormulaTestBed(workbookData?: IWorkbookData, dependencies?}function registerFormulaDependencies(injector: Injector) {- injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);- injector.add([+ injector.replace([IDescriptionService,{useFactory: () => injector.createInstance(DescriptionService),},]);- injector.add([FormulaDataModel]);- injector.add([IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }]);- injector.add([ISheetRowFilteredService, { useClass: SheetRowFilteredService }]);-+ injector.add([FormulaResultService]);injector.add([ICalculateFormulaService, { useClass: CalculateFormulaService }]);injector.add([Lexer]);- injector.add([LexerTreeBuilder]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);injector.add([IFormulaExternalReferenceDataLoader, { useClass: NoopFormulaExternalReferenceDataLoader }]);- injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);injector.add([IDependencyManagerService, { useClass: DependencyManagerService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);- injector.add([IFunctionService, { useClass: FunctionService }]);injector.add([IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);- injector.add([ISuperTableService, { useClass: SuperTableService }]);injector.add([CalculateController]);injector.add([IFeatureCalculationManagerService, { useClass: FeatureCalculationManagerService }]);diff --git a/packages/sheets-formula/src/facade/__tests__/create-test-bed.ts b/packages/sheets-formula/src/facade/__tests__/create-test-bed.tsindex e2499a2dea..7f7e5287f6 100644--- a/packages/sheets-formula/src/facade/__tests__/create-test-bed.ts+++ b/packages/sheets-formula/src/facade/__tests__/create-test-bed.ts@@ -14,31 +14,21 @@* limitations under the License.*/-import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';+import type { Dependency, Injector, IWorkbookData, UnitModel } from '@univerjs/core';import type { IRender } from '@univerjs/engine-render';import {ILogService,- Inject,- Injector,IUniverInstanceService,LocaleService,LocaleType,LogLevel,- Plugin,set,ThemeService,Univer,UniverInstanceType,} from '@univerjs/core';import { FUniver } from '@univerjs/core/facade';-import {- DefinedNamesService,- FormulaDataModel,- FunctionService,- IDefinedNamesService,- IFunctionService,- LexerTreeBuilder,-} from '@univerjs/engine-formula';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { Engine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import {RangeProtectionRuleModel,@@ -123,36 +113,26 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:const univer = new Univer();const injector = univer.__getInjector();- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();const injector = this._injector;injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);- injector.add([IFunctionService, { useClass: FunctionService }]);injector.add([IRenderManagerService, { useClass: RenderManagerServiceTestBed }]);injector.add([SheetSkeletonService]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder]);injector.add([RefRangeService]);injector.add([WorksheetPermissionService]);injector.add([WorkbookPermissionService]);injector.add([WorksheetProtectionPointModel]);injector.add([RangeProtectionRuleModel]);injector.add([WorksheetProtectionRuleModel]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);- dependencies?.forEach((d) => injector.add(d));+ dependencies?.forEach((d) => injector.replace(d.length === 1 ? [d[0], { useClass: d[0] }] : d));this._injector.get(SheetInterceptorService);this._injector.get(WorkbookPermissionService);@@ -175,7 +155,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:// register builtin plugins// note that UI plugins are not registered here, because the unit test environment does not have a UI- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, workbookData || getTestWorkbookDataDemo());const univerInstanceService = injector.get(IUniverInstanceService);diff --git a/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts b/packages/sheets-formula/src/facade/__tests__/f-formula.spec.tsindex 9fe1a9277f..64d215d72a 100644--- a/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts+++ b/packages/sheets-formula/src/facade/__tests__/f-formula.spec.ts@@ -18,24 +18,16 @@ import type { Injector } from '@univerjs/core';import type { FUniver } from '@univerjs/core/facade';import { ICommandService, IConfigService, LifecycleService, LifecycleStages } from '@univerjs/core';import {- ActiveDirtyManagerService,- DescriptionService,FormulaCalculationSessionController,FormulaCalculationSessionService,FormulaExecutedStateType,FormulaExecuteStageType,- IActiveDirtyManagerService,- IDescriptionService,IFunctionService,IRegisterFunctionService,- ISuperTableService,- RegisterFunctionService,- RegisterOtherFormulaService,SetFormulaCalculationNotificationMutation,SetFormulaCalculationResultMutation,SetFormulaCalculationStartMutation,SetTriggerFormulaCalculationStartMutation,- SuperTableService,} from '@univerjs/engine-formula';import { SetRangeValuesMutation } from '@univerjs/sheets';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -59,13 +51,6 @@ describe('sheets-formula facade mixins', () => {beforeEach(() => {const testBed = createFacadeTestBed();- testBed.injector.add([IDescriptionService, { useClass: DescriptionService }]);- testBed.injector.add([ISuperTableService, { useClass: SuperTableService }]);- testBed.injector.add([IRegisterFunctionService, { useClass: RegisterFunctionService }]);- testBed.injector.add([IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }]);- testBed.injector.add([RegisterOtherFormulaService]);- testBed.injector.add([FormulaCalculationSessionService]);- testBed.injector.add([FormulaCalculationSessionController]);testBed.injector.add([SheetFormulaCalculationResultApplyController]);testBed.injector.get(FormulaCalculationSessionService);testBed.injector.get(FormulaCalculationSessionController);diff --git a/packages/sheets-formula/src/services/__tests__/util.ts b/packages/sheets-formula/src/services/__tests__/util.tsindex b418050c97..7b76232b4f 100644--- a/packages/sheets-formula/src/services/__tests__/util.ts+++ b/packages/sheets-formula/src/services/__tests__/util.ts@@ -14,10 +14,10 @@* limitations under the License.*/-import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';-import { ICommandService, ILogService, Inject, Injector, IUniverInstanceService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';+import type { Dependency, Injector, IWorkbookData, Workbook } from '@univerjs/core';+import { ICommandService, ILogService, IUniverInstanceService, LocaleType, LogLevel, Univer, UniverInstanceType } from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';-import { CalculateFormulaService, DefinedNamesService, FormulaCurrentConfigService, FormulaDataModel, FormulaRuntimeService, ICalculateFormulaService, IDefinedNamesService, IFormulaCurrentConfigService, IFormulaRuntimeService, LexerTreeBuilder } from '@univerjs/engine-formula';+import { CalculateFormulaService, FormulaCurrentConfigService, FormulaDataModel, FormulaResultService, FormulaRuntimeService, ICalculateFormulaService, IFormulaCurrentConfigService, IFormulaRuntimeService, UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { DefinedNameDataController, InsertColByRangeCommand, InsertColCommand, InsertRowByRangeCommand, IRefSelectionsService, MoveColsCommand, MoveRangeCommand, RangeProtectionRuleModel, RefRangeService, RemoveColByRangeCommand, RemoveColCommand, RemoveRowByRangeCommand, SheetInterceptorService, SheetsSelectionsService, WorkbookPermissionService, WorksheetPermissionService, WorksheetProtectionPointModel, WorksheetProtectionRuleModel } from '@univerjs/sheets';import { FormulaRefRangeService } from '../formula-ref-range.service';@@ -56,26 +56,19 @@ export interface ITestBed {sheet: Workbook;}-// eslint-disable-next-line max-lines-per-functionexport function createCommandTestBed(workbookData?: IWorkbookData, dependencies?: Dependency[]): ITestBed {const univer = new Univer();const injector = univer.__getInjector();const get = injector.get.bind(injector);- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {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 {+ super.onStarting();const injector = this._injector;// injector.add([ICommandService, { useClass: CommandService }]);injector.add([WorksheetPermissionService]);@@ -85,11 +78,9 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?injector.add([WorksheetProtectionRuleModel]);injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);+ injector.add([FormulaResultService]);injector.add([ICalculateFormulaService, { useClass: CalculateFormulaService }]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder]);injector.add([DocSelectionManagerService]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);injector.add([DefinedNameDataController]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);@@ -97,7 +88,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?injector.add([RefRangeService]);injector.add([FormulaRefRangeService]);- dependencies?.forEach((d) => injector.add(d));+ dependencies?.forEach((d) => injector.replace(d.length === 1 ? [d[0], { useClass: d[0] }] : d));this._injector.get(SheetInterceptorService);this._injector.get(WorkbookPermissionService);@@ -123,7 +114,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?}}- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookData || TEST_WORKBOOK_DATA_DEMO);const univerInstanceService = injector.get(IUniverInstanceService);diff --git a/packages/sheets-formula/src/services/remote/__tests__/remote-register-function.service.spec.ts b/packages/sheets-formula/src/services/remote/__tests__/remote-register-function.service.spec.tsindex 0036fe023f..ffc243930b 100644--- a/packages/sheets-formula/src/services/remote/__tests__/remote-register-function.service.spec.ts+++ b/packages/sheets-formula/src/services/remote/__tests__/remote-register-function.service.spec.ts@@ -14,14 +14,21 @@* limitations under the License.*/-import { Injector } from '@univerjs/core';-import { FunctionService, IFunctionService } from '@univerjs/engine-formula';-import { describe, expect, it } from 'vitest';+import { Univer } from '@univerjs/core';+import { IFunctionService, UniverFormulaEnginePlugin } from '@univerjs/engine-formula';+import { afterEach, describe, expect, it } from 'vitest';import { IRemoteRegisterFunctionService, RemoteRegisterFunctionService } from '../remote-register-function.service';+const univers: Univer[] = [];+afterEach(() => {+ univers.splice(0).forEach((univer) => univer.dispose());+});+function createService(): { service: IRemoteRegisterFunctionService; functionService: IFunctionService } {- const injector = new Injector();- injector.add([IFunctionService, { useClass: FunctionService }]);+ const univer = new Univer();+ univers.push(univer);+ univer.registerPlugin(UniverFormulaEnginePlugin, { notExecuteFormula: true });+ const injector = univer.__getInjector();injector.add([IRemoteRegisterFunctionService, { useClass: RemoteRegisterFunctionService }]);return {service: injector.get(IRemoteRegisterFunctionService),diff --git a/packages/sheets-hyper-link-ui/src/facade/__tests__/f-workbook.spec.ts b/packages/sheets-hyper-link-ui/src/facade/__tests__/f-workbook.spec.tsindex c39c0813c5..08f1e19bdd 100644--- a/packages/sheets-hyper-link-ui/src/facade/__tests__/f-workbook.spec.ts+++ b/packages/sheets-hyper-link-ui/src/facade/__tests__/f-workbook.spec.ts@@ -19,26 +19,14 @@ import type { IMessageProps } from '@univerjs/design';import {ICommandService,ILogService,- Inject,- Injector,IUniverInstanceService,LocaleType,LogLevel,- Plugin,Univer,UniverInstanceType,} from '@univerjs/core';import { FUniver } from '@univerjs/core/facade';-import {- DefinedNamesService,- FormulaDataModel,- FunctionService,- IDefinedNamesService,- IFunctionService,- ISuperTableService,- LexerTreeBuilder,- SuperTableService,-} from '@univerjs/engine-formula';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import {RefRangeService,SetWorksheetActiveOperation,@@ -92,35 +80,26 @@ function createHyperLinkFacadeTestBed(workbookData: IWorkbookData, dependencies:const univer = new Univer();const injector = univer.__getInjector();- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();const injector = this._injector;injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);- injector.add([IFunctionService, { useClass: FunctionService }]);injector.add([SheetSkeletonService]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder]);injector.add([RefRangeService]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);- injector.add([ISuperTableService, { useClass: SuperTableService }]);dependencies.forEach((dependency) => injector.add(dependency));this._injector.get(SheetInterceptorService);}++ override onReady(): void {}}- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, workbookData);injector.get(IUniverInstanceService).focusUnit(sheet.getUnitId());injector.get(ILogService).setLogLevel(LogLevel.SILENT);diff --git a/packages/sheets-note/src/facade/__tests__/sheets-note.facade.spec.ts b/packages/sheets-note/src/facade/__tests__/sheets-note.facade.spec.tsindex f68eaea4f1..d9b91f2d8e 100644--- a/packages/sheets-note/src/facade/__tests__/sheets-note.facade.spec.ts+++ b/packages/sheets-note/src/facade/__tests__/sheets-note.facade.spec.ts@@ -14,32 +14,22 @@* limitations under the License.*/-import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';+import type { Dependency, Injector, IWorkbookData, UnitModel } from '@univerjs/core';import type { ISelectionWithStyle } from '@univerjs/sheets';import {ICommandService,ILogService,- Inject,- Injector,IUndoRedoService,IUniverInstanceService,LocaleType,LogLevel,- Plugin,RANGE_TYPE,touchDependencies,Univer,UniverInstanceType,} from '@univerjs/core';import { FUniver } from '@univerjs/core/facade';-import {- DefinedNamesService,- FormulaDataModel,- FunctionService,- IDefinedNamesService,- IFunctionService,- LexerTreeBuilder,-} from '@univerjs/engine-formula';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import { ISocketService, WebSocketService } from '@univerjs/network';import {@@ -89,38 +79,28 @@ function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?: Dependconst univer = new Univer();const injector = univer.__getInjector();- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();// Ensure undo/redo exists.this._injector.get(IUndoRedoService);- (dependencies ?? []).forEach((d) => this._injector.add(d));+ (dependencies ?? []).forEach((d) => this._injector.replace(d.length === 1 ? [d[0], { useClass: d[0] }] : d));// Minimal set of dependencies required by Sheets facade classes.this._injector.add([SheetsSelectionsService]);this._injector.add([SheetInterceptorService]);- this._injector.add([IFunctionService, { useClass: FunctionService }]);this._injector.add([ISocketService, { useClass: WebSocketService }]);this._injector.add([IRenderManagerService, { useClass: RenderManagerService }]);- this._injector.add([FormulaDataModel]);- this._injector.add([LexerTreeBuilder]);this._injector.add([RefRangeService]);this._injector.add([WorksheetPermissionService]);this._injector.add([WorkbookPermissionService]);this._injector.add([WorksheetProtectionPointModel]);this._injector.add([RangeProtectionRuleModel]);this._injector.add([WorksheetProtectionRuleModel]);- this._injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);this._injector.add([SheetLazyExecuteScheduleService]);([@@ -135,9 +115,11 @@ function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?: Depend[SheetsNoteController],]);}++ override onReady(): void {}}- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, workbookData ?? TEST_WORKBOOK_DATA);const univerInstanceService = injector.get(IUniverInstanceService);univerInstanceService.focusUnit(unitId);diff --git a/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts b/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.tsindex 929c6dcb89..617e6971ea 100644--- a/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts+++ b/packages/sheets-numfmt/src/controllers/__tests__/numfmt-cell-content.controller.spec.ts@@ -28,6 +28,7 @@ import {IUniverInstanceService,LocaleType,LogLevel,+ ObjectMatrix,Plugin,ThemeService,Univer,@@ -42,7 +43,7 @@ import {SetRangeValuesMutation,SheetInterceptorService,} from '@univerjs/sheets';-import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { SHEETS_NUMFMT_PLUGIN_CONFIG_KEY } from '../../config/config';import { SheetsNumfmtCellContentController } from '../numfmt-cell-content.controller';@@ -218,6 +219,44 @@ describe('SheetsNumfmtCellContentController', () => {expect(workbook.getStyles().getStyleByCell(worksheet.getCellRaw(1, 6))?.n?.pattern).toBe('0.00');});+ it('does not scan changed cells when the number-format render cache is empty', async () => {+ get(SheetsNumfmtCellContentController);+ const forValue = vi.spyOn(ObjectMatrix.prototype, 'forValue');+ try {+ await commandService.executeCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: { 1: { 1: { v: 42, t: CellValueType.NUMBER } } },+ }, { onlyLocal: true, fromFormula: true });++ expect(workbook.getSheetBySheetId('sheet1')?.getCellRaw(1, 1)?.v).toBe(42);+ // The worksheet mutation still scans its payload; empty-cache invalidation adds no scan.+ expect(forValue).toHaveBeenCalledTimes(1);+ } finally {+ forValue.mockRestore();+ }+ });++ it('still invalidates populated render-cache entries during ordinary value edits', async () => {+ get(SheetsNumfmtCellContentController);+ const worksheet = workbook.getSheetBySheetId('sheet1')!;+ numfmtService.setValues('test', 'sheet1', [{ pattern: '0.00', ranges: [cellToRange(1, 1)] }]);+ expect(getInterceptedCell(worksheet, workbook, 1, 1, get)).toMatchObject({ v: '1234.50' });++ const forValue = vi.spyOn(ObjectMatrix.prototype, 'forValue');+ try {+ await commandService.executeCommand(SetRangeValuesMutation.id, {+ unitId: 'test',+ subUnitId: 'sheet1',+ cellValue: { 1: { 1: { v: 42, t: CellValueType.NUMBER } } },+ });+ expect(forValue).toHaveBeenCalledTimes(2);+ expect(getInterceptedCell(worksheet, workbook, 1, 1, get)).toMatchObject({ v: '42.00' });+ } finally {+ forValue.mockRestore();+ }+ });+it('skips unsupported cells and handles text format markers', () => {get(SheetsNumfmtCellContentController);const worksheet = workbook.getSheetBySheetId('sheet1')!;diff --git a/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts b/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.tsindex e261442f11..718d87f993 100644--- a/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts+++ b/packages/sheets-numfmt/src/controllers/numfmt-cell-content.controller.ts@@ -33,6 +33,7 @@ import {ObjectMatrix,Range,ThemeService,+ Tools,UniverInstanceType,} from '@univerjs/core';import { stripErrorMargin } from '@univerjs/engine-formula';@@ -104,6 +105,7 @@ export class SheetsNumfmtCellContentController extends Disposable {});});} else if (commandInfo.id === SetRangeValuesMutation.id) {+ if (Tools.isEmptyObject(this._renderCache.getMatrix())) return;const params = commandInfo.params as ISetRangeValuesMutationParams;new ObjectMatrix(params.cellValue).forValue((row, col) => {this._renderCache.realDeleteValue(row, col);diff --git a/packages/sheets-sort-ui/src/commands/commands/__tests__/create-command-test-bed.ts b/packages/sheets-sort-ui/src/commands/commands/__tests__/create-command-test-bed.tsindex ac060a05f5..8fe0849cd6 100644--- a/packages/sheets-sort-ui/src/commands/commands/__tests__/create-command-test-bed.ts+++ b/packages/sheets-sort-ui/src/commands/commands/__tests__/create-command-test-bed.ts@@ -14,9 +14,9 @@* limitations under the License.*/-import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';-import { ILogService, Inject, Injector, IUniverInstanceService, LocaleService, LocaleType, LogLevel, Plugin, Tools, Univer, UniverInstanceType } from '@univerjs/core';-import { FormulaCurrentConfigService, FormulaDataModel, FormulaRuntimeService, HyperlinkEngineFormulaService, IFormulaCurrentConfigService, IFormulaRuntimeService, IHyperlinkEngineFormulaService, LexerTreeBuilder } from '@univerjs/engine-formula';+import type { Dependency, Injector, IWorkbookData, Workbook } from '@univerjs/core';+import { ILogService, IUniverInstanceService, LocaleService, LocaleType, LogLevel, Tools, Univer, UniverInstanceType } from '@univerjs/core';+import { FormulaCurrentConfigService, FormulaRuntimeService, IFormulaCurrentConfigService, IFormulaRuntimeService, UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';import { FormulaReorderController } from '@univerjs/sheets-formula';import { SheetsSortService } from '@univerjs/sheets-sort';@@ -133,24 +133,15 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?const univer = new Univer();const injector = univer.__getInjector();- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();const injector = this._injector;injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder]);- injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);injector.add([SheetsSortController]);@@ -158,7 +149,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?injector.add([SheetsSortUIService]);injector.add([FormulaReorderController]);- dependencies?.forEach((d) => injector.add(d));+ dependencies?.forEach((d) => injector.replace(d.length === 1 ? [d[0], { useClass: d[0] }] : d));}override onReady(): void {@@ -167,7 +158,7 @@ export function createCommandTestBed(workbookData?: IWorkbookData, dependencies?}}- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, Tools.deepClone(workbookData ?? TEST_WORKBOOK_DATA_DEMO));const univerInstanceService = injector.get(IUniverInstanceService);diff --git a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-selection.controller.spec.ts b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-selection.controller.spec.tsindex d9315a6c22..bbfdd9036d 100644--- a/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-selection.controller.spec.ts+++ b/packages/sheets-table-ui/src/controllers/__tests__/sheet-table-selection.controller.spec.ts@@ -27,28 +27,7 @@ import {Univer,UniverInstanceType,} from '@univerjs/core';-import {- ActiveDirtyManagerService,- CalculateFormulaService,- DefinedNamesService,- FormulaCurrentConfigService,- FormulaDataModel,- FormulaRuntimeService,- HyperlinkEngineFormulaService,- IActiveDirtyManagerService,- ICalculateFormulaService,- IDefinedNamesService,- IFormulaCurrentConfigService,- IFormulaRuntimeService,- IHyperlinkEngineFormulaService,- ISheetRowFilteredService,- ISuperTableService,- LexerTreeBuilder,- RemoveSuperTableMutation,- SetSuperTableMutation,- SheetRowFilteredService,- SuperTableService,-} from '@univerjs/engine-formula';+import { CalculateFormulaService, FormulaCurrentConfigService, FormulaResultService, FormulaRuntimeService, ICalculateFormulaService, IFormulaCurrentConfigService, IFormulaRuntimeService, RemoveSuperTableMutation, SetSuperTableMutation, UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import {AddWorksheetMergeMutation,@@ -203,6 +182,11 @@ function createClipboardTestBed() {};const univer = new Univer();const injector = univer.__getInjector();++ class TestPlugin extends UniverFormulaEnginePlugin {+ override onReady(): void {}+ }+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);injector.add([RangeProtectionRuleModel]);@@ -216,14 +200,8 @@ function createClipboardTestBed() {injector.add([SheetRangeThemeModel]);injector.add([SheetRangeThemeService]);injector.add([ZebraCrossingCacheController]);- injector.add([ISheetRowFilteredService, { useClass: SheetRowFilteredService }]);- injector.add([IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }]);- injector.add([ISuperTableService, { useClass: SuperTableService }]);+ injector.add([FormulaResultService]);injector.add([ICalculateFormulaService, { useClass: CalculateFormulaService }]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);- injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);injector.add([IRenderManagerService, { useClass: RenderManagerService }]);diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.tsindex 7c9b100ea9..68a18e8eba 100644--- a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.controller.spec.ts@@ -34,12 +34,14 @@ describe('SheetTableFormulaController', () => {getTableInfo: () => ({name: 'Orders',subUnitId: 's1',- range: { startRow: 0, endRow: 5, startColumn: 0, endColumn: 2 },+ range: { startRow: 0, endRow: 5, startColumn: 3, endColumn: 4 },columns: [{ displayName: 'id' },{ displayName: 'amount' },],}),+ isShowHeader: vi.fn(() => true),+ isShowFooter: vi.fn(() => true),};const tableManager = {@@ -73,7 +75,7 @@ describe('SheetTableFormulaController', () => {dirtyRanges: [{unitId: 'u1',sheetId: 's1',- range: { startRow: 0, endRow: 5, startColumn: 0, endColumn: 2 },+ range: { startRow: 0, endRow: 5, startColumn: 3, endColumn: 4 },}],clearDependencyTreeCache: { u1: { s1: '1' } },});@@ -85,7 +87,9 @@ describe('SheetTableFormulaController', () => {tableName: 'Orders',reference: expect.objectContaining({sheetId: 's1',- range: { startRow: 0, endRow: 5, startColumn: 0, endColumn: 2 },+ range: { startRow: 0, endRow: 5, startColumn: 3, endColumn: 4 },+ showHeader: true,+ showFooter: true,}),}), { onlyLocal: true });@@ -93,8 +97,17 @@ describe('SheetTableFormulaController', () => {expect(params.reference.titleMap).toEqual({ id: 0, amount: 1 });expect(JSON.parse(JSON.stringify(params))).toEqual(params);+ table.isShowHeader.mockReturnValue(false);+ table.isShowFooter.mockReturnValue(false);tableRangeChanged$.next({ unitId: 'u1', tableId: 't1' });expect(executeCommand).toHaveBeenCalledTimes(2);+ expect(executeCommand.mock.calls[1][1].reference).toEqual({+ range: { startRow: 0, endRow: 5, startColumn: 3, endColumn: 4 },+ sheetId: 's1',+ titleMap: { id: 0, amount: 1 },+ showHeader: false,+ showFooter: false,+ });tableNameChanged$.next({ unitId: 'u1', tableId: 't1', oldTableName: 'Orders_Old' });expect(executeCommand).toHaveBeenNthCalledWith(3, RemoveSuperTableMutation.id, {diff --git a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.tsindex df41bb28b5..89030f6e53 100644--- a/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts+++ b/packages/sheets-table/src/controllers/__tests__/sheet-table-formula.integration.spec.ts@@ -14,21 +14,18 @@* limitations under the License.*/-import type { Dependency, ICellData, IWorkbookData, Nullable, UnitModel, Workbook } from '@univerjs/core';+import type { Dependency, ICellData, Injector, IWorkbookData, Nullable, UnitModel, Workbook } from '@univerjs/core';import type { BaseAstNode, BaseFunction, IUnitData } from '@univerjs/engine-formula';import type { IRender } from '@univerjs/engine-render';import {CellValueType,ICommandService,ILogService,- Inject,- Injector,IUniverInstanceService,LocaleService,LocaleType,LogLevel,ObjectMatrix,- Plugin,RANGE_TYPE,RedoCommand,set,@@ -37,57 +34,7 @@ import {Univer,UniverInstanceType,} from '@univerjs/core';-import {- ActiveDirtyManagerService,- AstRootNodeFactory,- AstTreeBuilder,- CalculateFormulaService,- DefinedNamesService,- FormulaCurrentConfigService,- FormulaDataModel,- FormulaDependencyGenerator,- FormulaRuntimeService,- FormulaUnitReferenceResolver,- functionMath,- FunctionNodeFactory,- FunctionService,- generateExecuteAstNodeData,- getObjectValue,- HyperlinkEngineFormulaService,- IActiveDirtyManagerService,- ICalculateFormulaService,- IDefinedNamesService,- IFormulaCurrentConfigService,- IFormulaDependencyGenerator,- IFormulaExternalReferenceDataLoader,- IFormulaRuntimeService,- IFormulaUnitReferenceResolver,- IFunctionService,- IHyperlinkEngineFormulaService,- Interpreter,- IOtherFormulaManagerService,- ISheetRowFilteredService,- ISuperTableService,- LambdaNodeFactory,- LambdaParameterNodeFactory,- Lexer,- LexerNode,- LexerTreeBuilder,- NoopFormulaExternalReferenceDataLoader,- OperatorNodeFactory,- OtherFormulaManagerService,- PrefixNodeFactory,- ReferenceNodeFactory,- RemoveSuperTableMutation,- SetArrayFormulaDataMutation,- SetFormulaDataMutation,- SetSuperTableMutation,- SheetRowFilteredService,- SuffixNodeFactory,- SuperTableService,- UnionNodeFactory,- ValueNodeFactory,-} from '@univerjs/engine-formula';+import { AstRootNodeFactory, AstTreeBuilder, CalculateFormulaService, FormulaCurrentConfigService, FormulaDataModel, FormulaDependencyGenerator, FormulaResultService, FormulaRuntimeService, FormulaUnitReferenceResolver, functionMath, FunctionNodeFactory, generateExecuteAstNodeData, getObjectValue, ICalculateFormulaService, IFormulaCurrentConfigService, IFormulaDependencyGenerator, IFormulaExternalReferenceDataLoader, IFormulaRuntimeService, IFormulaUnitReferenceResolver, IFunctionService, Interpreter, IOtherFormulaManagerService, LambdaNodeFactory, LambdaParameterNodeFactory, Lexer, LexerNode, LexerTreeBuilder, NoopFormulaExternalReferenceDataLoader, OperatorNodeFactory, OtherFormulaManagerService, PrefixNodeFactory, ReferenceNodeFactory, RemoveSuperTableMutation, SetArrayFormulaDataMutation, SetFormulaDataMutation, SetSuperTableMutation, SuffixNodeFactory, UnionNodeFactory, UniverFormulaEnginePlugin, ValueNodeFactory } from '@univerjs/engine-formula';import { Engine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import {InsertColMutation,@@ -151,33 +98,23 @@ function createFacadeTestBed(workbookData: IWorkbookData, dependencies: Dependenconst univer = new Univer();const injector = univer.__getInjector();- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();const injector = this._injector;injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);- injector.add([IFunctionService, { useClass: FunctionService }]);injector.add([IRenderManagerService, { useClass: RenderManagerServiceTestBed }]);injector.add([SheetSkeletonService]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder]);injector.add([RefRangeService]);injector.add([WorksheetPermissionService]);injector.add([WorkbookPermissionService]);injector.add([WorksheetProtectionPointModel]);injector.add([RangeProtectionRuleModel]);injector.add([WorksheetProtectionRuleModel]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);dependencies.forEach((d) => injector.add(d));@@ -185,6 +122,8 @@ function createFacadeTestBed(workbookData: IWorkbookData, dependencies: Dependenthis._injector.get(WorkbookPermissionService);this._injector.get(WorksheetPermissionService);}++ override onReady(): void {}}injector.get(LocaleService).load({ zhCN, enUS });@@ -194,7 +133,7 @@ function createFacadeTestBed(workbookData: IWorkbookData, dependencies: Dependenconst newTheme = set(theme, 'gray.1000', '#35322b');themeService.setTheme(newTheme);- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, workbookData);injector.get(IUniverInstanceService).focusUnit('test');@@ -280,16 +219,14 @@ function createWorkbookData(): IWorkbookData {function createControllerTestBed() {const dependencies: Dependency[] = [+ [FormulaResultService],[ICalculateFormulaService, { useClass: CalculateFormulaService }],- [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],[Lexer],[IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }],[IFormulaUnitReferenceResolver, { useClass: FormulaUnitReferenceResolver }],[IFormulaExternalReferenceDataLoader, { useClass: NoopFormulaExternalReferenceDataLoader }],- [IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }],[IFormulaRuntimeService, { useClass: FormulaRuntimeService }],[IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }],- [ISheetRowFilteredService, { useClass: SheetRowFilteredService }],[IFormulaDependencyGenerator, { useClass: FormulaDependencyGenerator }],[Interpreter],[AstTreeBuilder],@@ -303,7 +240,6 @@ function createControllerTestBed() {[SuffixNodeFactory],[UnionNodeFactory],[ValueNodeFactory],- [ISuperTableService, { useClass: SuperTableService }],[TableManager],[SheetTableService],[SheetTableFormulaController],diff --git a/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts b/packages/sheets-table/src/controllers/sheet-table-formula.controller.tsindex 7478f597a6..2943c5a80a 100644--- a/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts+++ b/packages/sheets-table/src/controllers/sheet-table-formula.controller.ts@@ -121,6 +121,8 @@ export class SheetTableFormulaController extends Disposable {range: tableInfo.range,sheetId: tableInfo.subUnitId,titleMap,+ showHeader: table.isShowHeader(),+ showFooter: table.isShowFooter(),},}, { onlyLocal: true });}diff --git a/packages/sheets-table/src/facade/__tests__/f-table.spec.ts b/packages/sheets-table/src/facade/__tests__/f-table.spec.tsindex 63f919b241..c6cd075432 100644--- a/packages/sheets-table/src/facade/__tests__/f-table.spec.ts+++ b/packages/sheets-table/src/facade/__tests__/f-table.spec.ts@@ -18,27 +18,15 @@ import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';import {ICommandService,ILogService,- Inject,- Injector,IUniverInstanceService,LocaleService,LocaleType,LogLevel,- Plugin,Univer,UniverInstanceType,} from '@univerjs/core';import { FUniver } from '@univerjs/core/facade';-import {- DefinedNamesService,- FormulaDataModel,- FunctionService,- IDefinedNamesService,- IFunctionService,- ISuperTableService,- LexerTreeBuilder,- SuperTableService,-} from '@univerjs/engine-formula';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import {AddRangeThemeMutation,RefRangeService,@@ -93,29 +81,18 @@ function createTableFacadeTestBed(dependencies: Dependency[]) {const univer = new Univer();const injector = univer.__getInjector();- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();const injector = this._injector;injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);- injector.add([IFunctionService, { useClass: FunctionService }]);injector.add([SheetSkeletonService]);injector.add([SheetRangeThemeModel]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder]);injector.add([RefRangeService]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);- injector.add([ISuperTableService, { useClass: SuperTableService }]);dependencies.forEach((dependency) => injector.add(dependency));const localeService = injector.get(LocaleService);@@ -124,9 +101,11 @@ function createTableFacadeTestBed(dependencies: Dependency[]) {this._injector.get(SheetInterceptorService);}++ override onReady(): void {}}- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, createWorkbookData());injector.get(IUniverInstanceService).focusUnit(sheet.getUnitId());injector.get(ILogService).setLogLevel(LogLevel.SILENT);diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/create-test-bed.ts b/packages/sheets-ui/src/controllers/editor/__tests__/create-test-bed.tsindex bdb83a05b6..dddef38936 100644--- a/packages/sheets-ui/src/controllers/editor/__tests__/create-test-bed.ts+++ b/packages/sheets-ui/src/controllers/editor/__tests__/create-test-bed.ts@@ -14,8 +14,9 @@* limitations under the License.*/-import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';-import { ILogService, Inject, Injector, IUniverInstanceService, LocaleType, LogLevel, Plugin, Univer, UniverInstanceType } from '@univerjs/core';+import type { Dependency, Injector, IWorkbookData, Workbook } from '@univerjs/core';+import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Univer, UniverInstanceType } from '@univerjs/core';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { SheetInterceptorService, SheetsSelectionsService } from '@univerjs/sheets';function getTestWorkbookDataDemo(): IWorkbookData {@@ -45,26 +46,22 @@ export function createTestBed(workbookData?: IWorkbookData, dependencies?: Depenconst univer = new Univer();const injector = univer.__getInjector();- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();const injector = this._injector;injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);- dependencies?.forEach((d) => injector.add(d));+ dependencies?.forEach((d) => injector.replace(d.length === 1 ? [d[0], { useClass: d[0] }] : d));}++ override onReady(): void {}}- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookData ?? getTestWorkbookDataDemo());const univerInstanceService = injector.get(IUniverInstanceService);diff --git a/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts b/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.tsindex 27ecc4625c..3f479e812e 100644--- a/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts+++ b/packages/sheets-ui/src/controllers/editor/__tests__/editing.render-controller.spec.ts@@ -48,7 +48,7 @@ import {} from '@univerjs/core';import { DocSelectionManagerService, DocSkeletonManagerService, DocStateChangeManagerService, DocStateEmitService, InsertTextCommand, RichTextEditingMutation } from '@univerjs/docs';import { DocSelectionRenderService, IEditorService, InnerPasteCommand, MoveCursorOperation, MoveSelectionOperation, SetDocInputStyleCommand, VIEWPORT_KEY } from '@univerjs/docs-ui';-import { FunctionService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';+import { IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';import { DeviceInputEventType, IRenderManagerService, NORMAL_TEXT_SELECTION_PLUGIN_STYLE } from '@univerjs/engine-render';import {SetRangeValuesCommand,@@ -74,7 +74,7 @@ afterEach(() => {describe('imported formula metadata when editing', () => {it.each([BooleanNumber.FALSE, BooleanNumber.TRUE])('clears copied metadata on edits and keeps unchanged formulas (fd=%s)', (fd) => {- const testBed = createTestBed(undefined, [[LexerTreeBuilder], [IFunctionService, { useClass: FunctionService }]]);+ const testBed = createTestBed();try {const localeService = testBed.get(LocaleService);localeService.setLocale(LocaleType.EN_US);@@ -116,7 +116,7 @@ describe('clearing cell editor content', () => {];it.each(cases)('clears $name without removing cell formatting', ({ cell, body }) => {- const testBed = createTestBed(undefined, [[LexerTreeBuilder], [IFunctionService, { useClass: FunctionService }]]);+ const testBed = createTestBed();try {const worksheet = testBed.sheet.getSheetBySheetId('sheet1')!;const previous: ICellData = { s: { bl: 1, n: { pattern: '0.00' } }, ...cell };@@ -150,7 +150,7 @@ describe('clearing cell editor content', () => {});it('restores a styled value on Undo and clears it again on Redo', async () => {- const testBed = createTestBed(undefined, [[LexerTreeBuilder], [IFunctionService, { useClass: FunctionService }]]);+ const testBed = createTestBed();try {const worksheet = testBed.sheet.getSheetBySheetId('sheet1')!;const previous: ICellData = { v: 2, t: CellValueType.NUMBER, s: { bl: 1 } };@@ -194,7 +194,7 @@ describe('clearing cell editor content', () => {{ name: 'explicit empty text', input: "'", expected: { v: '', t: CellValueType.FORCE_STRING } },{ name: 'whitespace', input: ' ', expected: { v: ' ' } },])('preserves $name', ({ input, expected }) => {- const testBed = createTestBed(undefined, [[LexerTreeBuilder], [IFunctionService, { useClass: FunctionService }]]);+ const testBed = createTestBed();try {const incoming = getCellDataByInput({ v: 1, t: CellValueType.NUMBER },@@ -212,7 +212,7 @@ describe('clearing cell editor content', () => {});it('preserves an in-cell image with no text', () => {- const testBed = createTestBed(undefined, [[LexerTreeBuilder], [IFunctionService, { useClass: FunctionService }]]);+ const testBed = createTestBed();try {const snapshot: IDocumentData = { id: 'editor', body: { dataStream: '\r\n' }, documentStyle: {}, drawingsOrder: ['image'] };const incoming = getCellDataByInput(diff --git a/packages/sheets-ui/src/controllers/render-controllers/__tests__/editor-bridge.render-controller.spec.ts b/packages/sheets-ui/src/controllers/render-controllers/__tests__/editor-bridge.render-controller.spec.tsindex 38ba92c131..8cf38de5f3 100644--- a/packages/sheets-ui/src/controllers/render-controllers/__tests__/editor-bridge.render-controller.spec.ts+++ b/packages/sheets-ui/src/controllers/render-controllers/__tests__/editor-bridge.render-controller.spec.ts@@ -18,7 +18,7 @@ import type { Dependency, DocumentDataModel, IDocumentData } from '@univerjs/corimport { CanceledError, DOCS_NORMAL_EDITOR_UNIT_ID_KEY, SheetTypes, UniverInstanceType } from '@univerjs/core';import { DocStateChangeManagerService, DocStateEmitService, RichTextEditingMutation } from '@univerjs/docs';import { ReplaceSnapshotCommand } from '@univerjs/docs-ui';-import { FunctionService, IFunctionService, LexerTreeBuilder } from '@univerjs/engine-formula';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { DeviceInputEventType } from '@univerjs/engine-render';import {SetRangeValuesCommand,@@ -43,6 +43,11 @@ import { EditorBridgeRenderController } from '../editor-bridge.render-controllerimport { SheetsScrollRenderController } from '../scroll.render-controller';import { createChartRenderTestBed } from './chart-render-test-bed';+class TestFormulaEnginePlugin extends UniverFormulaEnginePlugin {+ // This render fixture needs formula providers without starting formula controllers.+ override onReady(): void {}+}+describe('Chart activation with a real pending Grid edit', () => {it.each([{ rangePicking: false, refuseRestore: false },@@ -64,11 +69,10 @@ describe('Chart activation with a real pending Grid edit', () => {[SheetsScrollRenderController],[EditorBridgeRenderController],]);+ univer.registerPlugin(TestFormulaEnginePlugin, { notExecuteFormula: true });const providers: Dependency[] = [[ILayoutService, { useClass: DesktopLayoutService }],[ICellEditorManagerService, { useClass: CellEditorManagerService }],- [IFunctionService, { useClass: FunctionService }],- [LexerTreeBuilder],[DocStateEmitService],[DocStateChangeManagerService],[SheetCellEditorResizeService],diff --git a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.tsindex c8a377d9ce..7c92943ddf 100644--- a/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts+++ b/packages/sheets-ui/src/services/clipboard/__tests__/clipboard-test-bed.ts@@ -20,33 +20,15 @@ import type { Dependency, IDisposable, IWorkbookData, Workbook } from '@univerjsimport {DisposableCollection,ILogService,- Inject,- Injector,IUniverInstanceService,LocaleService,LocaleType,LogLevel,- Plugin,Tools,Univer,UniverInstanceType,} from '@univerjs/core';-import {- CalculateFormulaService,- DefinedNamesService,- FormulaCurrentConfigService,- FormulaDataModel,- FormulaRuntimeService,- FunctionService,- HyperlinkEngineFormulaService,- ICalculateFormulaService,- IDefinedNamesService,- IFormulaCurrentConfigService,- IFormulaRuntimeService,- IFunctionService,- IHyperlinkEngineFormulaService,- LexerTreeBuilder,-} from '@univerjs/engine-formula';+import { CalculateFormulaService, FormulaCurrentConfigService, FormulaResultService, FormulaRuntimeService, ICalculateFormulaService, IFormulaCurrentConfigService, IFormulaRuntimeService, UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import {AutoFillService,@@ -570,18 +552,12 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: De/*** This plugin hooks into Sheet's DI system to expose API to test scripts*/- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();const injector = this._injector;injector.add([IUIPartsService, { useClass: UIPartsService }]);injector.add([SheetsSelectionsService]);@@ -610,26 +586,24 @@ export function clipboardTestBed(workbookData?: IWorkbookData, dependencies?: Deinjector.add([SheetClipboardController, { useValue: sheetClipboardController }]);injector.add([SheetInterceptorService]);+ injector.add([FormulaResultService]);injector.add([ICalculateFormulaService, { useClass: CalculateFormulaService }]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);- injector.add([IFunctionService, { useClass: FunctionService }]);- injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);injector.add([SheetSkeletonService]);- dependencies?.forEach((d) => injector.add(d));+ dependencies?.forEach((d) => injector.replace(d.length === 1 ? [d[0], { useClass: d[0] }] : d));const localeService = injector.get(LocaleService);localeService.load({});injector.get(IUIPartsService);}++ override onReady(): void {}}- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET,Tools.deepClone(workbookData || TEST_WORKBOOK_DATA_DEMO)diff --git a/packages/sheets-ui/src/views/defined-name/__tests__/DefinedNameInput.spec.tsx b/packages/sheets-ui/src/views/defined-name/__tests__/DefinedNameInput.spec.tsxindex 2fc3b2954c..e7b2622f4e 100644--- a/packages/sheets-ui/src/views/defined-name/__tests__/DefinedNameInput.spec.tsx+++ b/packages/sheets-ui/src/views/defined-name/__tests__/DefinedNameInput.spec.tsx@@ -25,15 +25,7 @@ import {Univer,UniverInstanceType,} from '@univerjs/core';-import {- DefinedNamesService,- FunctionService,- IDefinedNamesService,- IFunctionService,- ISuperTableService,- LexerTreeBuilder,- SuperTableService,-} from '@univerjs/engine-formula';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { SCOPE_WORKBOOK_VALUE_DEFINED_NAME } from '@univerjs/sheets';import sheetsEnUS from '@univerjs/sheets/locale/en-US';import { ComponentManager, ISidebarService, RediContext } from '@univerjs/ui';@@ -139,10 +131,11 @@ function createDefinedNameInputTestBed() {const univer = new Univer();const injector = univer.__getInjector();- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);- injector.add([ISuperTableService, { useClass: SuperTableService }]);- injector.add([IFunctionService, { useClass: FunctionService }]);- injector.add([LexerTreeBuilder, { useClass: LexerTreeBuilder }]);+ class TestPlugin extends UniverFormulaEnginePlugin {+ override onReady(): void {}+ }+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });+injector.add([ComponentManager, { useClass: ComponentManager }]);injector.add([ISidebarService, { useClass: TestSidebarService as never }]);diff --git a/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx b/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsxindex 69c3f7fd40..dc114e824f 100644--- a/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx+++ b/packages/sheets-ui/src/views/formula-bar/__tests__/FormulaBar.spec.tsx@@ -32,16 +32,7 @@ import {} from '@univerjs/core';import { DocSelectionManagerService } from '@univerjs/docs';import { EditorService, IEditorService } from '@univerjs/docs-ui';-import {- DefinedNamesService,- FormulaDataModel,- FunctionService,- IDefinedNamesService,- IFunctionService,- ISuperTableService,- LexerTreeBuilder,- SuperTableService,-} from '@univerjs/engine-formula';+import { IDefinedNamesService, UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { DeviceInputEventType, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import {AutoFillService,@@ -281,14 +272,14 @@ function createFormulaBarTestBed(cellStyle?: IStyleData, realEditorServices = faconst univer = new Univer();const injector = univer.__getInjector();+ class TestPlugin extends UniverFormulaEnginePlugin {+ override onReady(): void {}+ }+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });+injector.get(LocaleService).load({ [LocaleType.EN_US]: enUS });injector.get(LocaleService).setLocale(LocaleType.EN_US);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);- injector.add([ISuperTableService, { useClass: SuperTableService }]);- injector.add([IFunctionService, { useClass: FunctionService }]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder, { useClass: LexerTreeBuilder }]);injector.add([ComponentManager, { useClass: ComponentManager }]);injector.add([IUIPartsService, { useClass: UIPartsService }]);injector.add([SheetsSelectionsService, { useClass: SheetsSelectionsService }]);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.tsindex f029f352cd..39a529c299 100644--- a/packages/sheets/src/controllers/__tests__/formula/create-function-test-bed.ts+++ b/packages/sheets/src/controllers/__tests__/formula/create-function-test-bed.ts@@ -17,71 +17,21 @@/* eslint-disable max-lines-per-function */import type { Dependency, IWorkbookData, Workbook } from '@univerjs/core';-import type { ISheetData } from '@univerjs/engine-formula';+import type { FormulaDataModel, ISheetData } from '@univerjs/engine-formula';import type { FFormula } from '@univerjs/engine-formula/facade';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,- FormulaUnitReferenceResolver,- FunctionNodeFactory,- FunctionService,- GlobalComputingStatusService,- HyperlinkEngineFormulaService,- ICalculateFormulaService,- IDefinedNamesService,- IDependencyManagerService,- IFeatureCalculationManagerService,- IFormulaCurrentConfigService,- IFormulaDependencyGenerator,- IFormulaExternalReferenceDataLoader,- IFormulaRuntimeService,- IFormulaUnitReferenceResolver,- IFunctionService,- IHyperlinkEngineFormulaService,- Interpreter,- IOtherFormulaManagerService,- ISheetRowFilteredService,- ISuperTableService,- LambdaNodeFactory,- LambdaParameterNodeFactory,- Lexer,- LexerTreeBuilder,- NoopFormulaExternalReferenceDataLoader,- OperatorNodeFactory,- OtherFormulaManagerService,- PrefixNodeFactory,- ReferenceNodeFactory,- SheetRowFilteredService,- stripErrorMargin,- SuffixNodeFactory,- SuperTableService,- UnionNodeFactory,- ValueNodeFactory,-} from '@univerjs/engine-formula';+import { AstRootNodeFactory, AstTreeBuilder, CalculateController, CalculateFormulaService, DependencyManagerService, FeatureCalculationManagerService, FormulaCurrentConfigService, FormulaDependencyGenerator, FormulaResultService, FormulaRuntimeService, FormulaUnitReferenceResolver, FunctionNodeFactory, ICalculateFormulaService, IDependencyManagerService, IFeatureCalculationManagerService, IFormulaCurrentConfigService, IFormulaDependencyGenerator, IFormulaExternalReferenceDataLoader, IFormulaRuntimeService, IFormulaUnitReferenceResolver, Interpreter, IOtherFormulaManagerService, LambdaNodeFactory, LambdaParameterNodeFactory, Lexer, NoopFormulaExternalReferenceDataLoader, OperatorNodeFactory, OtherFormulaManagerService, PrefixNodeFactory, ReferenceNodeFactory, stripErrorMargin, SuffixNodeFactory, UnionNodeFactory, UniverFormulaEnginePlugin, ValueNodeFactory } from '@univerjs/engine-formula';import { CalculateResultApplyController } from '../../calculate-result-apply.controller';const getTestWorkbookData = (): IWorkbookData => {@@ -182,37 +132,26 @@ export function createFunctionTestBed(workbookData?: IWorkbookData, dependencies/*** This plugin hooks into Sheet's DI system to expose API to test scripts*/- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {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 {+ super.onStarting();const injector = this._injector;+ injector.add([FormulaResultService]);injector.add([ICalculateFormulaService, { useClass: CalculateFormulaService }]);injector.add([Lexer]);- injector.add([LexerTreeBuilder]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);injector.add([IFormulaExternalReferenceDataLoader, { useClass: NoopFormulaExternalReferenceDataLoader }]);- injector.add([IHyperlinkEngineFormulaService, { useClass: HyperlinkEngineFormulaService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);injector.add([IFormulaUnitReferenceResolver, { useClass: FormulaUnitReferenceResolver }]);- 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]);@@ -231,13 +170,10 @@ export function createFunctionTestBed(workbookData?: IWorkbookData, dependenciesinjector.add([SuffixNodeFactory]);injector.add([UnionNodeFactory]);injector.add([ValueNodeFactory]);- injector.add([FormulaDataModel]);-- injector.add([GlobalComputingStatusService]);injector.add([CalculateResultApplyController]);- dependencies?.forEach((d) => injector.add(d));+ dependencies?.forEach((d) => injector.replace(d.length === 1 ? [d[0], { useClass: d[0] }] : d));}override onReady(): void {@@ -248,7 +184,7 @@ export function createFunctionTestBed(workbookData?: IWorkbookData, dependencies}}- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, Workbook>(UniverInstanceType.UNIVER_SHEET, workbookData || getTestWorkbookData());const univerInstanceService = get(IUniverInstanceService);diff --git a/packages/sheets/src/facade/__tests__/create-test-bed.ts b/packages/sheets/src/facade/__tests__/create-test-bed.tsindex c843218f48..dee5c469ff 100644--- a/packages/sheets/src/facade/__tests__/create-test-bed.ts+++ b/packages/sheets/src/facade/__tests__/create-test-bed.ts@@ -14,24 +14,21 @@* limitations under the License.*/-import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';+import type { Dependency, Injector, IWorkbookData, UnitModel } from '@univerjs/core';import type { IRender } from '@univerjs/engine-render';import {ILogService,- Inject,- Injector,IUniverInstanceService,LocaleService,LocaleType,LogLevel,- Plugin,set,ThemeService,Univer,UniverInstanceType,} from '@univerjs/core';import { FUniver } from '@univerjs/core/facade';-import { DefinedNamesService, FormulaDataModel, FunctionService, IDefinedNamesService, IFunctionService, ISuperTableService, LexerTreeBuilder, SuperTableService } from '@univerjs/engine-formula';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { Engine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import { ISocketService, WebSocketService } from '@univerjs/network';import {@@ -49,7 +46,6 @@ import {} from '@univerjs/sheets';import enUS from '@univerjs/sheets/locale/en-US';import zhCN from '@univerjs/sheets/locale/zh-CN';-import '@univerjs/sheets/facade';function getTestWorkbookDataDemo(): IWorkbookData {@@ -118,28 +114,19 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:const univer = new Univer();const injector = univer.__getInjector();- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();const injector = this._injector;injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);- injector.add([IFunctionService, { useClass: FunctionService }]);injector.add([ISocketService, { useClass: WebSocketService }]);injector.add([IRenderManagerService, { useClass: RenderManagerServiceTestBed }]);injector.add([SheetSkeletonService]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder]);injector.add([RefRangeService]);injector.add([WorksheetPermissionService]);injector.add([WorkbookPermissionService]);@@ -147,11 +134,9 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:injector.add([RangeProtectionRuleModel]);injector.add([WorksheetProtectionRuleModel]);injector.add([SheetPermissionInitController]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);- injector.add([ISuperTableService, { useClass: SuperTableService }]);injector.add([SheetLazyExecuteScheduleService]);- dependencies?.forEach((d) => injector.add(d));+ dependencies?.forEach((d) => injector.replace(d.length === 1 ? [d[0], { useClass: d[0] }] : d));this._injector.get(SheetInterceptorService);this._injector.get(WorkbookPermissionService);@@ -174,7 +159,7 @@ export function createFacadeTestBed(workbookData?: IWorkbookData, dependencies?:// register builtin plugins// note that UI plugins are not registered here, because the unit test environment does not have a UI- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, workbookData || getTestWorkbookDataDemo());const univerInstanceService = injector.get(IUniverInstanceService);diff --git a/packages/sheets/src/facade/__tests__/create-worksheet-test-bed.ts b/packages/sheets/src/facade/__tests__/create-worksheet-test-bed.tsindex 94dbb45f91..84cb75e71e 100644--- a/packages/sheets/src/facade/__tests__/create-worksheet-test-bed.ts+++ b/packages/sheets/src/facade/__tests__/create-worksheet-test-bed.ts@@ -14,24 +14,21 @@* limitations under the License.*/-import type { Dependency, IWorkbookData, UnitModel } from '@univerjs/core';+import type { Dependency, Injector, IWorkbookData, UnitModel } from '@univerjs/core';import type { IRender } from '@univerjs/engine-render';import {ILogService,- Inject,- Injector,IUniverInstanceService,LocaleService,LocaleType,LogLevel,- Plugin,set,ThemeService,Univer,UniverInstanceType,} from '@univerjs/core';import { FUniver } from '@univerjs/core/facade';-import { ActiveDirtyManagerService, DefinedNamesService, FormulaDataModel, FunctionService, IActiveDirtyManagerService, IDefinedNamesService, IFunctionService, ISheetRowFilteredService, LexerTreeBuilder, SheetRowFilteredService } from '@univerjs/engine-formula';+import { UniverFormulaEnginePlugin } from '@univerjs/engine-formula';import { Engine, IRenderManagerService, RenderManagerService } from '@univerjs/engine-render';import { ISocketService, WebSocketService } from '@univerjs/network';import {@@ -47,7 +44,6 @@ import {} from '@univerjs/sheets';import enUS from '@univerjs/sheets/locale/en-US';import zhCN from '@univerjs/sheets/locale/zh-CN';-import '@univerjs/sheets/facade';function getTestWorkbookDataDemo(): IWorkbookData {@@ -110,45 +106,33 @@ export function createWorksheetTestBed(workbookData?: IWorkbookData, dependencieconst univer = new Univer();const injector = univer.__getInjector();- class TestPlugin extends Plugin {+ class TestPlugin extends UniverFormulaEnginePlugin {static override pluginName = 'test-plugin';static override type = UniverInstanceType.UNIVER_SHEET;- constructor(- _config: undefined,- @Inject(Injector) override readonly _injector: Injector- ) {- super();- }-override onStarting(): void {+ super.onStarting();const injector = this._injector;injector.add([SheetsSelectionsService]);injector.add([SheetInterceptorService]);- injector.add([IFunctionService, { useClass: FunctionService }]);injector.add([ISocketService, { useClass: WebSocketService }]);injector.add([IRenderManagerService, { useClass: RenderManagerServiceTestBed }]);injector.add([SheetSkeletonService]);- injector.add([FormulaDataModel]);- injector.add([LexerTreeBuilder]);injector.add([RefRangeService]);injector.add([WorksheetPermissionService]);injector.add([WorkbookPermissionService]);injector.add([WorksheetProtectionPointModel]);injector.add([RangeProtectionRuleModel]);injector.add([WorksheetProtectionRuleModel]);- injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);// register feature modules([- [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],- [ISheetRowFilteredService, { useClass: SheetRowFilteredService }],] as Dependency[]).forEach((d) => {injector.add(d);});- dependencies?.forEach((d) => injector.add(d));+ dependencies?.forEach((d) => injector.replace(d.length === 1 ? [d[0], { useClass: d[0] }] : d));}override onReady(): void {@@ -167,7 +151,7 @@ export function createWorksheetTestBed(workbookData?: IWorkbookData, dependencie// register builtin plugins// note that UI plugins are not registered here, because the unit test environment does not have a UI- univer.registerPlugin(TestPlugin);+ univer.registerPlugin(TestPlugin, { notExecuteFormula: true });const sheet = univer.createUnit<IWorkbookData, UnitModel<IWorkbookData>>(UniverInstanceType.UNIVER_SHEET, workbookData || getTestWorkbookDataDemo());const univerInstanceService = injector.get(IUniverInstanceService);