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
feat(formula): defined name (#703)
Univer993bf4bf1fe9
diff --git a/apps/docs/docs/tutorial/architecture/web-worker.mdx b/apps/docs/docs/tutorial/architecture/web-worker.mdxindex 72f509c3e6..a18cf29214 100644--- a/apps/docs/docs/tutorial/architecture/web-worker.mdx+++ b/apps/docs/docs/tutorial/architecture/web-worker.mdx@@ -34,7 +34,7 @@ univer.registerPlugin(UniverRPCMainThreadPlugin, {在 Web Worker 的入口文件中实例化另一个 Univer 实例,并注册需要的插件:```ts-import { BaseFormulaEnginePlugin } from '@univerjs/engine-formula';+import { FormulaEnginePlugin } from '@univerjs/engine-formula';import { sheetsPlugin } from '@univerjs/sheets';import { LocaleType, Univer } from '@univerjs/core';import { UniverRPCWorkerThreadPlugin } from '@univerjs/rpc';@@ -44,7 +44,7 @@ const univer = new Univer();univer.registerPlugin(UniverRPCWorkerThreadPlugin);univer.registerPlugin(sheetsPlugin);-univer.registerPlugin(BaseFormulaEnginePlugin);+univer.registerPlugin(FormulaEnginePlugin);univer.registerPlugin(FormulaPlugin);```diff --git a/examples/sheets/src/main.ts b/examples/sheets/src/main.tsindex 8cd711eb4b..6aea113509 100644--- a/examples/sheets/src/main.ts+++ b/examples/sheets/src/main.ts@@ -1,7 +1,7 @@import { LocaleType, LogLevel, Univer } from '@univerjs/core';import { greenTheme } from '@univerjs/design';import { DocsPlugin, RichTextEditingMutation } from '@univerjs/docs';-import { BaseFormulaEnginePlugin } from '@univerjs/engine-formula';+import { FormulaEnginePlugin } from '@univerjs/engine-formula';import { RenderEngine } from '@univerjs/engine-render';import type { IUniverRPCMainThreadPluginConfig } from '@univerjs/rpc';import { UniverRPCMainThreadPlugin } from '@univerjs/rpc';@@ -53,7 +53,7 @@ univer.registerPlugin(SheetsUIPlugin);univer.registerPlugin(SheetsNumfmt);univer.registerPlugin(DebuggerPlugin);-univer.registerPlugin(BaseFormulaEnginePlugin, {+univer.registerPlugin(FormulaEnginePlugin, {notExecuteFormula: true,});univer.registerPlugin(FormulaUIPlugin);diff --git a/examples/sheets/src/worker.ts b/examples/sheets/src/worker.tsindex dbd9f45b51..7eee28c90e 100644--- a/examples/sheets/src/worker.ts+++ b/examples/sheets/src/worker.ts@@ -1,7 +1,7 @@// The entry of web worker scriptsimport { LocaleType, Univer } from '@univerjs/core';-import { BaseFormulaEnginePlugin } from '@univerjs/engine-formula';+import { FormulaEnginePlugin } from '@univerjs/engine-formula';import { UniverRPCWorkerThreadPlugin } from '@univerjs/rpc';import { SheetsPlugin } from '@univerjs/sheets';@@ -11,9 +11,8 @@ const univer = new Univer({});univer.registerPlugin(SheetsPlugin);-univer.registerPlugin(BaseFormulaEnginePlugin);+univer.registerPlugin(FormulaEnginePlugin);univer.registerPlugin(UniverRPCWorkerThreadPlugin);-// univer.registerPlugin(FormulaPlugin);declare let self: WorkerGlobalScope & typeof globalThis & { univer: Univer };self.univer = univer;diff --git a/packages/core/src/shared/blob.ts b/packages/core/src/shared/blob.tsnew file mode 100644index 0000000000..cfe25fb0c8--- /dev/null+++ b/packages/core/src/shared/blob.ts@@ -0,0 +1,5 @@+export function codeToBlob(code: string) {+ const blob = new Blob([code], { type: 'text/javascript' });+ const objectURL = window.URL.createObjectURL(blob);+ return objectURL;+}diff --git a/packages/core/src/shared/index.ts b/packages/core/src/shared/index.tsindex a8564e3f4b..9c51cc4b23 100644--- a/packages/core/src/shared/index.ts+++ b/packages/core/src/shared/index.ts@@ -1,4 +1,5 @@export * from './array-search';+export * from './blob';export * from './color/color';export * from './color/color-builder';export * from './command-enum';diff --git a/packages/engine-formula/src/basics/token.ts b/packages/engine-formula/src/basics/token.tsindex be071d972e..e0c67d34b9 100644--- a/packages/engine-formula/src/basics/token.ts+++ b/packages/engine-formula/src/basics/token.ts@@ -57,6 +57,8 @@ export enum matchToken {OPEN_BRACES = '{',CLOSE_BRACES = '}',COLON = ':',+ OPEN_SQUARE_BRACKET = '[',+ CLOSE_SQUARE_BRACKET = ']',}export enum suffixToken {diff --git a/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.ts b/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.tsnew file mode 100644index 0000000000..698a9fbce4--- /dev/null+++ b/packages/engine-formula/src/commands/mutations/set-defined-name.mutation.ts@@ -0,0 +1,26 @@+import type { IMutation } from '@univerjs/core';+import { CommandType } from '@univerjs/core';++export interface ISetDefinedNameMutationSearchParam {+ unitId: string;+ name: string;+}++export interface ISetDefinedNameMutationParam extends ISetDefinedNameMutationSearchParam {+ formulaOrRefString: string;+}+/**+ * In the formula engine, the mutation is solely responsible for communication between the worker and the main thread.+ * It requires setting local to true during execution.+ */+export const SetDefinedNameMutation: IMutation<ISetDefinedNameMutationParam> = {+ id: 'formula.mutation.set-defined-name',+ type: CommandType.MUTATION,+ handler: () => true,+};++export const RemoveDefinedNameMutation: IMutation<ISetDefinedNameMutationSearchParam> = {+ id: 'formula.mutation.remove-defined-name',+ type: CommandType.MUTATION,+ handler: () => true,+};diff --git a/packages/engine-formula/src/commands/mutations/set-feature-calculation.mutation.ts b/packages/engine-formula/src/commands/mutations/set-feature-calculation.mutation.tsnew file mode 100644index 0000000000..21846a6e9b--- /dev/null+++ b/packages/engine-formula/src/commands/mutations/set-feature-calculation.mutation.ts@@ -0,0 +1,24 @@+import type { IMutation } from '@univerjs/core';+import { CommandType } from '@univerjs/core';++import type { IFeatureCalculationManagerParam } from '../../services/feature-calculation-manager.service';++export interface ISetFeatureCalculationMutation {+ featureId: string;+ calculationParam: IFeatureCalculationManagerParam;+}+/**+ * In the formula engine, the mutation is solely responsible for communication between the worker and the main thread.+ * It requires setting local to true during execution.+ */+export const SetFeatureCalculationMutation: IMutation<ISetFeatureCalculationMutation> = {+ id: 'formula.mutation.set-feature-calculation',+ type: CommandType.MUTATION,+ handler: () => true,+};++export const RemoveFeatureCalculationMutation: IMutation<{ featureId: string }> = {+ id: 'formula.mutation.remove-feature-calculation',+ type: CommandType.MUTATION,+ handler: () => true,+};diff --git a/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts b/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.tsindex 0900839d6d..a31b755880 100644--- a/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts+++ b/packages/engine-formula/src/commands/mutations/set-formula-calculation.mutation.ts@@ -1,12 +1,18 @@-import type { ICommandInfo, IExecutionOptions, IMutation, Nullable } from '@univerjs/core';+import type { IExecutionOptions, IMutation, IUnitRange, Nullable } from '@univerjs/core';import { CommandType } from '@univerjs/core';-import type { IAccessor } from '@wendellhu/redi';-import type { IRuntimeOtherUnitDataType, IRuntimeUnitDataType } from '../../basics/common';+import type {+ IDirtyUnitFeatureMap,+ IDirtyUnitSheetNameMap,+ IRuntimeOtherUnitDataType,+ IRuntimeUnitDataType,+} from '../../basics/common';import type { FormulaExecutedStateType, IExecutionInProgressParams } from '../../services/runtime.service';export interface ISetFormulaCalculationStartMutation {- commands: ICommandInfo[];+ dirtyRanges: IUnitRange[];+ dirtyNameMap: IDirtyUnitSheetNameMap;+ dirtyUnitFeatureMap: IDirtyUnitFeatureMap;options: Nullable<IExecutionOptions>;forceCalculation?: boolean;}@@ -17,7 +23,7 @@ export interface ISetFormulaCalculationStartMutation {export const SetFormulaCalculationStartMutation: IMutation<ISetFormulaCalculationStartMutation> = {id: 'formula.mutation.set-formula-calculation-start',type: CommandType.MUTATION,- handler: (accessor: IAccessor, params: ISetFormulaCalculationStartMutation) => true,+ handler: () => true,};export interface ISetFormulaCalculationStopMutation {}@@ -25,7 +31,7 @@ export interface ISetFormulaCalculationStopMutation {}export const SetFormulaCalculationStopMutation: IMutation<ISetFormulaCalculationStopMutation> = {id: 'formula.mutation.set-formula-calculation-stop',type: CommandType.MUTATION,- handler: (accessor: IAccessor, params: ISetFormulaCalculationStopMutation) => true,+ handler: () => true,};export interface ISetFormulaCalculationNotificationMutation {@@ -36,7 +42,7 @@ export interface ISetFormulaCalculationNotificationMutation {export const SetFormulaCalculationNotificationMutation: IMutation<ISetFormulaCalculationNotificationMutation> = {id: 'formula.mutation.set-formula-calculation-notification',type: CommandType.MUTATION,- handler: (accessor: IAccessor, params: ISetFormulaCalculationNotificationMutation) => true,+ handler: () => true,};export interface ISetFormulaCalculationResultMutation {@@ -47,5 +53,5 @@ export interface ISetFormulaCalculationResultMutation {export const SetFormulaCalculationResultMutation: IMutation<ISetFormulaCalculationResultMutation> = {id: 'formula.mutation.set-formula-calculation-result',type: CommandType.MUTATION,- handler: (accessor: IAccessor, params: ISetFormulaCalculationResultMutation) => true,+ handler: () => true,};diff --git a/packages/engine-formula/src/commands/mutations/set-other-formula.mutation.ts b/packages/engine-formula/src/commands/mutations/set-other-formula.mutation.tsnew file mode 100644index 0000000000..79fbdfc728--- /dev/null+++ b/packages/engine-formula/src/commands/mutations/set-other-formula.mutation.ts@@ -0,0 +1,23 @@+import type { IMutation } from '@univerjs/core';+import { CommandType } from '@univerjs/core';++import type {+ IOtherFormulaManagerInsertParam,+ IOtherFormulaManagerSearchParam,+} from '../../services/other-formula-manager.service';++/**+ * In the formula engine, the mutation is solely responsible for communication between the worker and the main thread.+ * It requires setting local to true during execution.+ */+export const SetOtherFormulaMutation: IMutation<IOtherFormulaManagerInsertParam> = {+ id: 'formula.mutation.set-other-formula',+ type: CommandType.MUTATION,+ handler: () => true,+};++export const RemoveOtherFormulaMutation: IMutation<IOtherFormulaManagerSearchParam> = {+ id: 'formula.mutation.remove-other-formula',+ type: CommandType.MUTATION,+ handler: () => true,+};diff --git a/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts b/packages/engine-formula/src/commands/mutations/set-super-table.mutation.tsnew file mode 100644index 0000000000..755b5fd882--- /dev/null+++ b/packages/engine-formula/src/commands/mutations/set-super-table.mutation.ts@@ -0,0 +1,35 @@+import type { IMutation } from '@univerjs/core';+import { CommandType } from '@univerjs/core';++import type { ISuperTable } from '../../basics/common';+import type { ISuperTableOptionParam } from '../../services/super-table.service';++export interface ISetSuperTableMutationSearchParam {+ unitId: string;+ tableName: string;+}++export interface ISetSuperTableMutationParam extends ISetSuperTableMutationSearchParam {+ reference: ISuperTable;+}+/**+ * In the formula engine, the mutation is solely responsible for communication between the worker and the main thread.+ * It requires setting local to true during execution.+ */+export const SetSuperTableMutation: IMutation<ISetSuperTableMutationParam> = {+ id: 'formula.mutation.set-super-table',+ type: CommandType.MUTATION,+ handler: () => true,+};++export const RemoveSuperTableMutation: IMutation<ISetSuperTableMutationSearchParam> = {+ id: 'formula.mutation.remove-super-table',+ type: CommandType.MUTATION,+ handler: () => true,+};++export const SetSuperTableOptionMutation: IMutation<ISuperTableOptionParam> = {+ id: 'formula.mutation.set-super-table-option',+ type: CommandType.MUTATION,+ handler: () => true,+};diff --git a/packages/engine-formula/src/controller/calculate.controller.ts b/packages/engine-formula/src/controller/calculate.controller.tsindex 62f0ea83ac..79277a7c0e 100644--- a/packages/engine-formula/src/controller/calculate.controller.ts+++ b/packages/engine-formula/src/controller/calculate.controller.ts@@ -15,7 +15,6 @@ import {import type { ISetFormulaDataMutationParams } from '../commands/mutations/set-formula-data.mutation';import { SetFormulaDataMutation } from '../commands/mutations/set-formula-data.mutation';import { FormulaDataModel } from '../models/formula-data.model';-import { IActiveDirtyManagerService } from '../services/active-dirty-manager.service';import { CalculateFormulaService } from '../services/calculate-formula.service';import type { IAllRuntimeData } from '../services/runtime.service';import { FormulaExecutedStateType } from '../services/runtime.service';@@ -26,8 +25,7 @@ export class CalculateController extends Disposable {@ICommandService private readonly _commandService: ICommandService,@Inject(CalculateFormulaService) private readonly _calculateFormulaService: CalculateFormulaService,@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,- @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel,- @IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService+ @Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel) {super();@@ -55,7 +53,7 @@ export class CalculateController extends Disposable {if (params.forceCalculation === true) {this._calculate(true);} else {- const { dirtyRanges, dirtyNameMap, dirtyUnitFeatureMap } = this._generateDirty(params.commands);+ const { dirtyRanges, dirtyNameMap, dirtyUnitFeatureMap } = params;this._calculate(false, dirtyRanges, dirtyNameMap, dirtyUnitFeatureMap);}@@ -74,73 +72,6 @@ export class CalculateController extends Disposable {);}- private _generateDirty(commands: ICommandInfo[]) {- const allDirtyRanges: IUnitRange[] = [];- const allDirtyNameMap: IDirtyUnitSheetNameMap = {};- const allDirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};-- for (const command of commands) {- const conversion = this._activeDirtyManagerService.get(command.id);-- if (conversion == null) {- continue;- }-- const params = conversion.getDirtyData(command);-- const { dirtyRanges, dirtyNameMap, dirtyUnitFeatureMap } = params;-- if (dirtyRanges != null) {- allDirtyRanges.push(...dirtyRanges);- }-- if (dirtyNameMap != null) {- this._mergeDirtyNameMap(allDirtyNameMap, dirtyNameMap);- }-- if (dirtyUnitFeatureMap != null) {- this._mergeDirtyUnitFeatureMap(allDirtyUnitFeatureMap, dirtyUnitFeatureMap);- }- }-- return {- dirtyRanges: allDirtyRanges,- dirtyNameMap: allDirtyNameMap,- dirtyUnitFeatureMap: allDirtyUnitFeatureMap,- };- }-- private _mergeDirtyNameMap(allDirtyNameMap: IDirtyUnitSheetNameMap, dirtyNameMap: IDirtyUnitSheetNameMap) {- Object.keys(dirtyNameMap).forEach((unitId) => {- if (allDirtyNameMap[unitId] == null) {- allDirtyNameMap[unitId] = {};- }- Object.keys(dirtyNameMap[unitId]).forEach((sheetId) => {- allDirtyNameMap[unitId][sheetId] = dirtyNameMap[unitId][sheetId];- });- });- }-- private _mergeDirtyUnitFeatureMap(- allDirtyUnitFeatureMap: IDirtyUnitFeatureMap,- dirtyUnitFeatureMap: IDirtyUnitFeatureMap- ) {- Object.keys(dirtyUnitFeatureMap).forEach((unitId) => {- if (allDirtyUnitFeatureMap[unitId] == null) {- allDirtyUnitFeatureMap[unitId] = {};- }- Object.keys(dirtyUnitFeatureMap[unitId]).forEach((sheetId) => {- if (allDirtyUnitFeatureMap[unitId][sheetId] == null) {- allDirtyUnitFeatureMap[unitId][sheetId] = {};- }- Object.keys(dirtyUnitFeatureMap[unitId][sheetId]).forEach((featureId) => {- allDirtyUnitFeatureMap[unitId][sheetId][featureId] =- dirtyUnitFeatureMap[unitId][sheetId][featureId];- });- });- });- }-private async _calculate(forceCalculate: boolean = false,dirtyRanges: IUnitRange[] = [],diff --git a/packages/engine-formula/src/controller/formula.controller.ts b/packages/engine-formula/src/controller/formula.controller.tsindex c62be8f4aa..6c4ede27c1 100644--- a/packages/engine-formula/src/controller/formula.controller.ts+++ b/packages/engine-formula/src/controller/formula.controller.ts@@ -3,6 +3,11 @@ import type { Ctor } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';import { SetArrayFormulaDataMutation } from '../commands/mutations/set-array-formula-data.mutation';+import { RemoveDefinedNameMutation, SetDefinedNameMutation } from '../commands/mutations/set-defined-name.mutation';+import {+ RemoveFeatureCalculationMutation,+ SetFeatureCalculationMutation,+} from '../commands/mutations/set-feature-calculation.mutation';import {SetFormulaCalculationNotificationMutation,SetFormulaCalculationResultMutation,@@ -10,6 +15,12 @@ import {SetFormulaCalculationStopMutation,} from '../commands/mutations/set-formula-calculation.mutation';import { SetFormulaDataMutation } from '../commands/mutations/set-formula-data.mutation';+import { RemoveOtherFormulaMutation, SetOtherFormulaMutation } from '../commands/mutations/set-other-formula.mutation';+import {+ RemoveSuperTableMutation,+ SetSuperTableMutation,+ SetSuperTableOptionMutation,+} from '../commands/mutations/set-super-table.mutation';import { functionArray } from '../functions/array/function-map';import type { BaseFunction } from '../functions/base-function';import { functionCompatibility } from '../functions/compatibility/function-map';@@ -54,6 +65,17 @@ export class FormulaController extends Disposable {SetFormulaCalculationStopMutation,SetFormulaCalculationNotificationMutation,SetFormulaCalculationResultMutation,++ SetDefinedNameMutation,+ RemoveDefinedNameMutation,+ SetFeatureCalculationMutation,+ RemoveFeatureCalculationMutation,++ SetOtherFormulaMutation,+ RemoveOtherFormulaMutation,+ SetSuperTableMutation,+ RemoveSuperTableMutation,+ SetSuperTableOptionMutation,].forEach((command) => this.disposeWithMe(this._commandService.registerCommand(command)));}diff --git a/packages/engine-formula/src/controller/set-defined-name.controller.ts b/packages/engine-formula/src/controller/set-defined-name.controller.tsnew file mode 100644index 0000000000..d79e84d2de--- /dev/null+++ b/packages/engine-formula/src/controller/set-defined-name.controller.ts@@ -0,0 +1,47 @@+import type { ICommandInfo } from '@univerjs/core';+import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';++import type {+ ISetDefinedNameMutationParam,+ ISetDefinedNameMutationSearchParam,+} from '../commands/mutations/set-defined-name.mutation';+import { RemoveDefinedNameMutation, SetDefinedNameMutation } from '../commands/mutations/set-defined-name.mutation';+import { IDefinedNamesService } from '../services/defined-names.service';++@OnLifecycle(LifecycleStages.Ready, SetDefinedNameController)+export class SetDefinedNameController extends Disposable {+ constructor(+ @ICommandService private readonly _commandService: ICommandService,+ @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService+ ) {+ super();++ this._initialize();+ }++ private _initialize(): void {+ this._commandExecutedListener();+ }++ private _commandExecutedListener() {+ this.disposeWithMe(+ this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (command.id === SetDefinedNameMutation.id) {+ const params = command.params as ISetDefinedNameMutationParam;+ if (params == null) {+ return;+ }+ const { unitId, name, formulaOrRefString } = params;+ this._definedNamesService.registerDefinedName(unitId, name, formulaOrRefString);+ } else if (command.id === RemoveDefinedNameMutation.id) {+ const params = command.params as ISetDefinedNameMutationSearchParam;+ if (params == null) {+ return;+ }+ const { unitId, name } = params;+ this._definedNamesService.removeDefinedName(unitId, name);+ }+ })+ );+ }+}diff --git a/packages/engine-formula/src/controller/set-feature-calculation.controller.ts b/packages/engine-formula/src/controller/set-feature-calculation.controller.tsnew file mode 100644index 0000000000..6ddbe4459b--- /dev/null+++ b/packages/engine-formula/src/controller/set-feature-calculation.controller.ts@@ -0,0 +1,48 @@+import type { ICommandInfo } from '@univerjs/core';+import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';++import {+ type ISetFeatureCalculationMutation,+ RemoveFeatureCalculationMutation,+ SetFeatureCalculationMutation,+} from '../commands/mutations/set-feature-calculation.mutation';+import { IFeatureCalculationManagerService } from '../services/feature-calculation-manager.service';++@OnLifecycle(LifecycleStages.Ready, SetFeatureCalculationController)+export class SetFeatureCalculationController extends Disposable {+ constructor(+ @ICommandService private readonly _commandService: ICommandService,+ @IFeatureCalculationManagerService+ private readonly _featureCalculationManagerService: IFeatureCalculationManagerService+ ) {+ super();++ this._initialize();+ }++ private _initialize(): void {+ this._commandExecutedListener();+ }++ private _commandExecutedListener() {+ this.disposeWithMe(+ this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (command.id === SetFeatureCalculationMutation.id) {+ const params = command.params as ISetFeatureCalculationMutation;+ if (params == null) {+ return;+ }+ const { featureId, calculationParam } = params;+ this._featureCalculationManagerService.register(featureId, calculationParam);+ } else if (command.id === RemoveFeatureCalculationMutation.id) {+ const params = command.params as { featureId: string };+ if (params == null) {+ return;+ }+ const { featureId } = params;+ this._featureCalculationManagerService.remove(featureId);+ }+ })+ );+ }+}diff --git a/packages/engine-formula/src/controller/set-other-formula.controller.ts b/packages/engine-formula/src/controller/set-other-formula.controller.tsnew file mode 100644index 0000000000..bd863e67e8--- /dev/null+++ b/packages/engine-formula/src/controller/set-other-formula.controller.ts@@ -0,0 +1,47 @@+import type { ICommandInfo } from '@univerjs/core';+import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';++import { RemoveOtherFormulaMutation, SetOtherFormulaMutation } from '../commands/mutations/set-other-formula.mutation';+import {+ type IOtherFormulaManagerInsertParam,+ type IOtherFormulaManagerSearchParam,+ IOtherFormulaManagerService,+} from '../services/other-formula-manager.service';++@OnLifecycle(LifecycleStages.Ready, SetOtherFormulaController)+export class SetOtherFormulaController extends Disposable {+ constructor(+ @ICommandService private readonly _commandService: ICommandService,+ @IOtherFormulaManagerService private readonly _otherFormulaManagerService: IOtherFormulaManagerService+ ) {+ super();++ this._initialize();+ }++ private _initialize(): void {+ this._commandExecutedListener();+ }++ private _commandExecutedListener() {+ this.disposeWithMe(+ this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (command.id === SetOtherFormulaMutation.id) {+ const params = command.params as IOtherFormulaManagerInsertParam;+ if (params == null) {+ return;+ }++ this._otherFormulaManagerService.register(params);+ } else if (command.id === RemoveOtherFormulaMutation.id) {+ const params = command.params as IOtherFormulaManagerSearchParam;+ if (params == null) {+ return;+ }++ this._otherFormulaManagerService.remove(params);+ }+ })+ );+ }+}diff --git a/packages/engine-formula/src/controller/set-super-table.controller.ts b/packages/engine-formula/src/controller/set-super-table.controller.tsnew file mode 100644index 0000000000..11b23e0472--- /dev/null+++ b/packages/engine-formula/src/controller/set-super-table.controller.ts@@ -0,0 +1,56 @@+import type { ICommandInfo } from '@univerjs/core';+import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';++import { RemoveDefinedNameMutation, SetDefinedNameMutation } from '../commands/mutations/set-defined-name.mutation';+import {+ type ISetSuperTableMutationParam,+ type ISetSuperTableMutationSearchParam,+ SetSuperTableOptionMutation,+} from '../commands/mutations/set-super-table.mutation';+import type { ISuperTableOptionParam } from '../services/super-table.service';+import { ISuperTableService } from '../services/super-table.service';++@OnLifecycle(LifecycleStages.Ready, SetSuperTableController)+export class SetSuperTableController extends Disposable {+ constructor(+ @ICommandService private readonly _commandService: ICommandService,+ @ISuperTableService private readonly _superTableService: ISuperTableService+ ) {+ super();++ this._initialize();+ }++ private _initialize(): void {+ this._commandExecutedListener();+ }++ private _commandExecutedListener() {+ this.disposeWithMe(+ this._commandService.onCommandExecuted((command: ICommandInfo) => {+ if (command.id === SetDefinedNameMutation.id) {+ const params = command.params as ISetSuperTableMutationParam;+ if (params == null) {+ return;+ }+ const { unitId, tableName, reference } = params;+ this._superTableService.registerTable(unitId, tableName, reference);+ } else if (command.id === RemoveDefinedNameMutation.id) {+ const params = command.params as ISetSuperTableMutationSearchParam;+ if (params == null) {+ return;+ }+ const { unitId, tableName } = params;+ this._superTableService.remove(unitId, tableName);+ } else if (command.id === SetSuperTableOptionMutation.id) {+ const params = command.params as ISuperTableOptionParam;+ if (params == null) {+ return;+ }+ const { tableOption, tableOptionType } = params;+ this._superTableService.registerTableOptionMap(tableOption, tableOptionType);+ }+ })+ );+ }+}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 45c500d58f..876d9844c1 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@@ -3,6 +3,8 @@ import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, Plugimport type { Dependency } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';+import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from '../../../services/current-data.service';+import { DefinedNamesService, IDefinedNamesService } from '../../../services/defined-names.service';import { FormulaRuntimeService, IFormulaRuntimeService } from '../../../services/runtime.service';import { AstRootNodeFactory } from '../../ast-node/ast-root-node';import { FunctionNodeFactory } from '../../ast-node/function-node';@@ -14,6 +16,7 @@ import { ReferenceNodeFactory } from '../../ast-node/reference-node';import { SuffixNodeFactory } from '../../ast-node/suffix-node';import { UnionNodeFactory } from '../../ast-node/union-node';import { ValueNodeFactory } from '../../ast-node/value-node';+import { LexerTreeBuilder } from '../lexer-tree-builder';import { AstTreeBuilder } from '../parser';const TEST_WORKBOOK_DATA_DEMO: IWorkbookData = {@@ -60,7 +63,10 @@ export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencieoverride onStarting(injector: Injector): void {injector.add([AstTreeBuilder]);+ injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ injector.add([LexerTreeBuilder]);injector.add([AstRootNodeFactory]);injector.add([FunctionNodeFactory]);injector.add([LambdaNodeFactory]);diff --git a/packages/engine-formula/src/engine/analysis/__tests__/utils.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.tssimilarity index 80%rename from packages/engine-formula/src/engine/analysis/__tests__/utils.spec.tsrename to packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.tsindex bc7ea660e4..9537a255a2 100644--- a/packages/engine-formula/src/engine/analysis/__tests__/utils.spec.ts+++ b/packages/engine-formula/src/engine/analysis/__tests__/lexer-tree-builder.spec.ts@@ -1,25 +1,23 @@-import { afterEach, describe, expect, it } from 'vitest';+import { describe, expect, it } from 'vitest';-import { LexerTreeBuilder } from '../lexer';import type { LexerNode } from '../lexer-node';+import { LexerTreeBuilder } from '../lexer-tree-builder';-describe('utils test', () => {- const lexer = new LexerTreeBuilder();-- afterEach(() => {- lexer.dispose();- });+describe('lexer nodeMaker test', () => {+ const lexerTreeBuilder = new LexerTreeBuilder();describe('lexer', () => {it('lambda simple1', () => {- const node = lexer.treeBuilder(`=lambda(x,y, x*y*x)(sum(1,(1+2)*3),2)+1-max(100,200)`) as LexerNode;+ const node = lexerTreeBuilder.treeBuilder(+ `=lambda(x,y, x*y*x)(sum(1,(1+2)*3),2)+1-max(100,200)`+ ) as LexerNode;expect(JSON.stringify(node.serialize())).toStrictEqual(`{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"lambda","st":0,"ed":5,"children":[{"token":"L_1","st":14,"ed":16,"children":[{"token":"P_1","st":15,"ed":17,"children":[{"token":"sum","st":19,"ed":21,"children":[{"token":"P_1","st":19,"ed":21,"children":["1"]},{"token":"P_1","st":21,"ed":23,"children":["1","2","+","3","*"]}]}]},{"token":"P_1","st":30,"ed":32,"children":["2"]}]},{"token":"P_1","st":3,"ed":5,"children":["x"]},{"token":"P_1","st":5,"ed":7,"children":["y"]},{"token":"P_1","st":7,"ed":9,"children":[" x","y","x","*","*"]}]},"1",{"token":"max","st":39,"ed":41,"children":[{"token":"P_1","st":39,"ed":41,"children":["100"]},{"token":"P_1","st":43,"ed":45,"children":["200"]}]},"-","+"]}`);});it('lambda mixed2', () => {- const node = lexer.treeBuilder(+ const node = lexerTreeBuilder.treeBuilder(`=(-(1+2)--@A1:B2 + 5)/2 + -sum(indirect(A5):B10# + B6# + A1:offset(C5, 1, 1) , 100) + {1,2,3;4,5,6;7,8,10} + lambda(x,y,z, x*y*z)(sum(1,(1+2)*3),2,lambda(x,y, @offset(A1:B0,x#*y#))(1,2):C20) + sum((1+2%)*30%, 1+2)%`) as LexerNode;expect(JSON.stringify(node.serialize())).toStrictEqual(@@ -28,7 +26,7 @@ describe('utils test', () => {});it('normal', () => {- const node = lexer.treeBuilder(+ const node = lexerTreeBuilder.treeBuilder(`=(sum(max(B1:C10,10)*5-100,((1+1)*2+5)/2,10)+count(B1:C10,10*5-100))*5-100`) as LexerNode;expect(JSON.stringify(node.serialize())).toStrictEqual(@@ -37,7 +35,7 @@ describe('utils test', () => {});it('normal', () => {- const node = lexer.treeBuilder(+ const node = lexerTreeBuilder.treeBuilder(`=(sum(max(B1:C10,10)*5-100,((1+1)*2+5)/2,10, lambda(x,y, x*y*x)(sum(1,(1+2)*3),2))+lambda(x,y, x*y*x)(sum(1,(1+2)*3),2)+count(B1:C10,10*5-100))*5-100`) as LexerNode;expect(JSON.stringify(node.serialize())).toStrictEqual(@@ -46,45 +44,75 @@ describe('utils test', () => {});it('let', () => {- const node = lexer.treeBuilder(`=let(x,5,y,4,sum(x,y)+x)`) as LexerNode;+ const node = lexerTreeBuilder.treeBuilder(`=let(x,5,y,4,sum(x,y)+x)`) as LexerNode;expect(JSON.stringify(node.serialize())).toStrictEqual(`{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"let","st":0,"ed":2,"children":[{"token":"P_1","st":0,"ed":2,"children":["x"]},{"token":"P_1","st":2,"ed":4,"children":["5"]},{"token":"P_1","st":4,"ed":6,"children":["y"]},{"token":"P_1","st":6,"ed":8,"children":["4"]},{"token":"P_1","st":8,"ed":10,"children":[{"token":"sum","st":12,"ed":14,"children":[{"token":"P_1","st":12,"ed":14,"children":["x"]},{"token":"P_1","st":14,"ed":16,"children":["y"]}]},"x","+"]}]}]}`);});it('REDUCE', () => {- const node = lexer.treeBuilder(`=REDUCE(1, A1:C2, LAMBDA(a,b,a+b^2))`) as LexerNode;+ const node = lexerTreeBuilder.treeBuilder(`=REDUCE(1, A1:C2, LAMBDA(a,b,a+b^2))`) as LexerNode;expect(JSON.stringify(node.serialize())).toStrictEqual(`{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"REDUCE","st":0,"ed":5,"children":[{"token":"P_1","st":3,"ed":5,"children":["1"]},{"token":"P_1","st":5,"ed":7,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":" A1","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"C2","st":-1,"ed":-1,"children":[]}]}]}]},{"token":"P_1","st":12,"ed":14,"children":[{"token":" LAMBDA","st":16,"ed":22,"children":[{"token":"P_1","st":20,"ed":22,"children":["a"]},{"token":"P_1","st":22,"ed":24,"children":["b"]},{"token":"P_1","st":24,"ed":26,"children":["a","b","2","^","+"]}]}]}]}]}`);});it('missing default arguments', () => {- const node = lexer.treeBuilder(`=SUM(, A1:B1)`) as LexerNode;+ const node = lexerTreeBuilder.treeBuilder(`=SUM(, A1:B1)`) as LexerNode;expect(JSON.stringify(node.serialize())).toStrictEqual(`{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"SUM","st":0,"ed":2,"children":[{"token":"P_1","st":0,"ed":2,"children":[]},{"token":"P_1","st":1,"ed":3,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":" A1","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"B1","st":-1,"ed":-1,"children":[]}]}]}]}]}]}`);});it('negative and percentage', () => {- const node = lexer.treeBuilder(`=0.1 -- 0.2%`) as LexerNode;+ const node = lexerTreeBuilder.treeBuilder(`=0.1 -- 0.2%`) as LexerNode;expect(JSON.stringify(node.serialize())).toStrictEqual(`{"token":"R_1","st":-1,"ed":-1,"children":["0.1 ",{"token":"%","st":-1,"ed":-1,"children":["- 0.2"]},"-"]}`);});it('negative and percentage', () => {- const node = lexer.treeBuilder(`=1+(3*4=4)*5+1`) as LexerNode;+ const node = lexerTreeBuilder.treeBuilder(`=1+(3*4=4)*5+1`) as LexerNode;expect(JSON.stringify(node.serialize())).toStrictEqual(`{"token":"R_1","st":-1,"ed":-1,"children":["1","3","4","*","4","=","5","*","1","+","+"]}`);});it('prefixToken', () => {- const node = lexer.treeBuilder(`= -@A4:B5`) as LexerNode;+ const node = lexerTreeBuilder.treeBuilder(`= -@A4:B5`) as LexerNode;expect(JSON.stringify(node.serialize())).toStrictEqual(`{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"-","st":-1,"ed":-1,"children":[{"token":"@","st":-1,"ed":-1,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"A4","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"B5","st":-1,"ed":-1,"children":[]}]}]}]}]}]}`);});++ it('table', () => {+ const node = lexerTreeBuilder.treeBuilder(`=SUM(Table3[[#All],[Column1]:[Column2]])`) as LexerNode;+ expect(JSON.stringify(node.serialize())).toStrictEqual(+ `{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"SUM","st":0,"ed":2,"children":[{"token":"P_1","st":0,"ed":2,"children":["Table3[[#All],[Column1]:[Column2]]"]}]}]}`+ );+ });++ it('import range', () => {+ const node = lexerTreeBuilder.treeBuilder(`=[asdfasdfasdf]'sheet-1'!A3:B10`) as LexerNode;+ expect(JSON.stringify(node.serialize())).toStrictEqual(+ `{"token":"R_1","st":-1,"ed":-1,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"[asdfasdfasdf]'sheet-1'!A3","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"B10","st":-1,"ed":-1,"children":[]}]}]}]}`+ );+ });++ it('nodeMaker performance', () => {+ const start = performance.now();+ for (let i = 0; i < 1000; i++) {+ lexerTreeBuilder.nodeMakerTest(+ `=(-(1+2)--@A1:B2 + 5)/2 + -sum(indirect(A5):B10# + B6# + A1:offset(C5, 1, 1) , 100) + {1,2,3;4,5,6;7,8,10} + lambda(x,y,z, x*y*z)(sum(1,(1+2)*3),2,lambda(x,y, @offset(A1:B0,x#*y#))(1,2):C20) + sum((1+2%)*30%, 1+2)%`+ );+ }+ const end = performance.now();+ const elapsed = end - start; // 毫秒数++ console.log(`Elapsed time: ${elapsed} ms`);++ const expectedMaxTime = 3000; // 毫秒数+ expect(elapsed).toBeLessThan(expectedMaxTime);+ });});});diff --git a/packages/engine-formula/src/engine/analysis/__tests__/lexer.spec.ts b/packages/engine-formula/src/engine/analysis/__tests__/lexer.spec.tsnew file mode 100644index 0000000000..ddd6b55ca0--- /dev/null+++ b/packages/engine-formula/src/engine/analysis/__tests__/lexer.spec.ts@@ -0,0 +1,100 @@+import type { IWorkbookData, Univer, Workbook } from '@univerjs/core';+import { LocaleType } from '@univerjs/core';+import type { Injector } from '@wendellhu/redi';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { IDefinedNamesService } from '../../../services/defined-names.service';+import { IFormulaRuntimeService } from '../../../services/runtime.service';+import { Lexer } from '../lexer';+import type { LexerNode } from '../lexer-node';+import { LexerTreeBuilder } from '../lexer-tree-builder';+import { createCommandTestBed } from './create-command-test-bed';++const TEST_WORKBOOK_DATA: IWorkbookData = {+ id: 'test',+ appVersion: '3.0.0-alpha',+ sheets: {+ sheet1: {+ id: 'sheet1',+ cellData: {+ 0: {+ 0: {+ v: 1,+ },+ },+ 1: {+ 0: {+ v: 4,+ },+ },+ 2: {+ 0: {+ v: 44,+ },+ },+ 3: {+ 0: {+ v: 444,+ },+ },+ },+ },+ },+ locale: LocaleType.ZH_CN,+ name: '',+ sheetOrder: [],+ styles: {},+};++describe('lexer nodeMaker test', () => {+ let univer: Univer;+ let lexer: Lexer;+ let get: Injector['get'];+ let workbook: Workbook;+ let definedNamesService: IDefinedNamesService;+ let runtimeService: IFormulaRuntimeService;+ let lexerTreeBuilder: LexerTreeBuilder;++ beforeEach(() => {+ const testBed = createCommandTestBed(TEST_WORKBOOK_DATA);+ univer = testBed.univer;+ workbook = testBed.sheet;+ get = testBed.get;++ definedNamesService = get(IDefinedNamesService);++ runtimeService = get(IFormulaRuntimeService);++ lexerTreeBuilder = get(LexerTreeBuilder);++ runtimeService.setCurrent(0, 0, 'sheet1', 'test');++ lexer = new Lexer(definedNamesService, runtimeService, lexerTreeBuilder);+ });++ afterEach(() => {+ univer.dispose();+ });++ describe('lexer definedName', () => {+ it('simple', () => {+ definedNamesService.registerDefinedName('test', 'myName', '$A$10:$C$100');++ const node = lexer.treeBuilder(`=myName`) as LexerNode;++ expect(JSON.stringify(node.serialize())).toStrictEqual(+ `{"token":"R_1","st":-1,"ed":-1,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"$A$10","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"$C$100","st":-1,"ed":-1,"children":[]}]}]}]}`+ );+ });++ it('lambda', () => {+ definedNamesService.registerDefinedName('test', 'myName', 'lambda(x, y , x*x*y)');++ const node = lexer.treeBuilder(`=myName(1+sum(A1:B1), 100)`) as LexerNode;++ expect(JSON.stringify(node.serialize())).toStrictEqual(+ `{"token":"R_1","st":-1,"ed":-1,"children":[{"token":"lambda","st":0,"ed":5,"children":[{"token":"L_1","st":16,"ed":18,"children":[{"token":"P_1","st":17,"ed":19,"children":["1",{"token":"sum","st":23,"ed":25,"children":[{"token":"P_1","st":23,"ed":25,"children":[{"token":":","st":-1,"ed":-1,"children":[{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"A1","st":-1,"ed":-1,"children":[]}]},{"token":"P_1","st":-1,"ed":-1,"children":[{"token":"B1","st":-1,"ed":-1,"children":[]}]}]}]}]},"+"]},{"token":"P_1","st":30,"ed":32,"children":[" 100"]}]},{"token":"P_1","st":3,"ed":5,"children":["x"]},{"token":"P_1","st":5,"ed":7,"children":[" y "]},{"token":"P_1","st":9,"ed":11,"children":[" x","x","y","*","*"]}]}]}`+ );+ });+ });+});diff --git a/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts b/packages/engine-formula/src/engine/analysis/lexer-tree-builder.tsnew file mode 100644index 0000000000..4fe42acb33--- /dev/null+++ b/packages/engine-formula/src/engine/analysis/lexer-tree-builder.ts@@ -0,0 +1,1217 @@+import type { Nullable } from '@univerjs/core';+import { deserializeRangeWithSheet, Disposable, Rectangle, serializeRangeToRefString, Tools } from '@univerjs/core';++import { FormulaAstLRU } from '../../basics/cache-lru';+import { ErrorType } from '../../basics/error-type';+import { isFormulaLexerToken } from '../../basics/match-token';+import { isReferenceString, REFERENCE_SINGLE_RANGE_REGEX } from '../../basics/regex';+import {+ matchToken,+ OPERATOR_TOKEN_PRIORITY,+ OPERATOR_TOKEN_SET,+ operatorToken,+ prefixToken,+ SUFFIX_TOKEN_SET,+} from '../../basics/token';+import {+ DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER,+ DEFAULT_TOKEN_TYPE_PARAMETER,+ DEFAULT_TOKEN_TYPE_ROOT,+} from '../../basics/token-type';+import type { ISequenceArray, ISequenceNode } from '../utils/sequence';+import { generateStringWithSequence, sequenceNodeType } from '../utils/sequence';+import { LexerNode } from './lexer-node';++enum bracketType {+ NORMAL,+ FUNCTION,+ LAMBDA,+}++const FORMULA_CACHE_LRU_COUNT = 100000;++export const FormulaLexerNodeCache = new FormulaAstLRU<LexerNode>(FORMULA_CACHE_LRU_COUNT);++export const FormulaSequenceNodeCache = new FormulaAstLRU<Array<string | ISequenceNode>>(FORMULA_CACHE_LRU_COUNT);++export class LexerTreeBuilder extends Disposable {+ private _currentLexerNode: LexerNode = new LexerNode();++ private _upLevel = 0;++ private _segment = '';++ private _bracketState: bracketType[] = []; // ()++ private _squareBracketState: number = 0;++ private _bracesState = 0; // {}++ private _singleQuotationState = 0; // ''++ private _doubleQuotationState = 0; // ""++ private _lambdaState = false; // Lambda++ private _colonState = false; // :++ private _tableBracketState = false; // Table3[[#All],[Column1]:[Column2]]++ override dispose(): void {+ this._resetTemp();+ this._currentLexerNode.dispose();++ FormulaLexerNodeCache.clear();++ FormulaSequenceNodeCache.clear();+ }++ getUpLevel() {+ return this._upLevel;+ }++ isColonClose() {+ return this._colonState === false;+ }++ isColonOpen() {+ return this._colonState === true;+ }++ isDoubleQuotationClose() {+ return this._doubleQuotationState === 0;+ }++ isLambdaOpen() {+ return this._lambdaState === true;+ }++ isLambdaClose() {+ return this._lambdaState === false;+ }++ isSingleQuotationClose() {+ return this._singleQuotationState === 0;+ }++ isBracesClose() {+ return this._bracesState === 0;+ }++ isBracketClose() {+ return this._bracketState.length === 0;+ }++ isSquareBracketClose() {+ return this._squareBracketState === 0;+ }++ getCurrentLexerNode() {+ return this._currentLexerNode;+ }++ getFunctionAndParameter(formulaString: string, strIndex: number) {+ const current = this._getCurrentParamIndex(formulaString, strIndex);++ if (current == null || current === ErrorType.VALUE) {+ return;+ }++ const lexerNode = current[0];++ if (typeof lexerNode === 'string') {+ return;+ }++ let parent = lexerNode.getParent();++ let children = lexerNode;++ while (parent) {+ const token = parent.getToken();+ if (+ token !== DEFAULT_TOKEN_TYPE_PARAMETER &&+ !isFormulaLexerToken(token) &&+ parent.getStartIndex() !== -1+ ) {+ const paramIndex = parent.getChildren().indexOf(children);++ return {+ functionName: token,+ paramIndex,+ };+ }++ children = parent;+ parent = parent.getParent();+ }+ }++ moveFormulaRefOffset(formulaString: string, refOffsetX: number, refOffsetY: number) {+ const sequenceNodes = this.sequenceNodesBuilder(formulaString);++ if (sequenceNodes == null) {+ return formulaString;+ }++ const newSequenceNodes: Array<string | ISequenceNode> = [];++ for (let i = 0, len = sequenceNodes.length; i < len; i++) {+ const node = sequenceNodes[i];+ if (typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE) {+ newSequenceNodes.push(node);+ continue;+ }++ const { token } = node;++ const sequenceGrid = deserializeRangeWithSheet(token);++ const { range, sheetName, unitId: sequenceUnitId } = sequenceGrid;++ const newRange = Rectangle.moveOffset(range, refOffsetX, refOffsetY);++ newSequenceNodes.push({+ ...node,+ token: serializeRangeToRefString({+ range: newRange,+ unitId: sequenceUnitId,+ sheetName,+ }),+ });+ }++ return `=${generateStringWithSequence(newSequenceNodes)}`;+ }++ /**+ * Estimate the number of right brackets that need to be automatically added to the end of the formula.+ * @param formulaString+ * @returns+ */+ checkIfAddBracket(formulaString: string) {+ let lastBracketCount = 0;+ let lastIndex = formulaString.length - 1;+ let lastString = formulaString[lastIndex];+ /**+ * Determine how many close brackets are at the end, and estimate how many functions need to automatically add close brackets.+ */+ while (lastString === matchToken.CLOSE_BRACKET || lastString === ' ') {+ if (lastString === matchToken.CLOSE_BRACKET) {+ lastBracketCount++;+ }+ lastString = formulaString[--lastIndex];+ }++ const current = this._getCurrentParamIndex(formulaString, formulaString.length - 2);++ if (current == null || current === ErrorType.VALUE) {+ return 0;+ }++ const lexerNode = current[0];++ if (typeof lexerNode === 'string') {+ return 0;+ }++ let parent = lexerNode.getParent();+ let bracketCount = 0;++ /**+ * Perform an upward search on the syntax tree to see how many layers the function is nested.+ * For each layer passed, subtract the estimated number of right brackets,+ * ultimately obtaining the number of right brackets that need to be completed.+ */+ while (parent) {+ const token = parent.getToken();+ if (token !== DEFAULT_TOKEN_TYPE_PARAMETER && token !== matchToken.COLON && parent.getStartIndex() !== -1) {+ if (lastBracketCount === 0) {+ bracketCount += 1;+ } else {+ lastBracketCount--;+ }+ }++ parent = parent.getParent();+ }++ return bracketCount;+ }++ sequenceNodesBuilder(formulaString: string) {+ const sequenceNodesCache = FormulaSequenceNodeCache.get(formulaString);+ if (sequenceNodesCache) {+ return [...sequenceNodesCache];+ }++ const sequenceArray = this._getSequenceArray(formulaString);+ if (sequenceArray.length === 0) {+ return;+ }++ const newSequenceNodes = this.getSequenceNode(sequenceArray);++ // let sequenceString = '';+ // for (const node of newSequenceNodes) {+ // if (typeof node === 'string') {+ // sequenceString += node;+ // } else {+ // sequenceString += node.token;+ // }+ // }+ // console.log('sequenceString', sequenceString);++ FormulaSequenceNodeCache.set(formulaString, [...newSequenceNodes]);++ return newSequenceNodes;+ }++ getSequenceNode(sequenceArray: ISequenceArray[]) {+ const sequenceNodes: Array<ISequenceNode | string> = [];++ let maybeString = false;++ for (let i = 0, len = sequenceArray.length; i < len; i++) {+ const item = sequenceArray[i];++ const preItem = sequenceArray[i - 1];++ const { segment, currentString, cur } = item;++ if (currentString === matchToken.DOUBLE_QUOTATION) {+ maybeString = true;+ }++ if ((segment !== '' || i === 0) && i !== len - 1) {+ sequenceNodes.push(currentString);+ continue;+ }++ let preSegment = preItem?.segment || '';++ const startIndex = i - preSegment.length;++ let endIndex = i - 1;++ const deleteEndIndex = i - 1;++ if (i === len - 1 && this._isLastMergeString(currentString)) {+ preSegment += currentString;++ endIndex += 1;+ }++ if (preSegment === '' || OPERATOR_TOKEN_PRIORITY.has(preSegment)) {+ sequenceNodes.push(currentString);+ continue;+ }++ const preSegmentTrim = preSegment.trim();++ const preSegmentNotPrefixToken = this._replacePrefixString(preSegmentTrim);++ if (maybeString === true && preSegmentTrim[preSegmentTrim.length - 1] === matchToken.DOUBLE_QUOTATION) {+ maybeString = false;+ this._pushSequenceNode(+ sequenceNodes,+ {+ nodeType: sequenceNodeType.STRING,+ token: preSegment,+ startIndex,+ endIndex,+ },+ deleteEndIndex+ );+ } else if (new RegExp(REFERENCE_SINGLE_RANGE_REGEX).test(preSegmentNotPrefixToken)) {+ this._pushSequenceNode(+ sequenceNodes,+ {+ nodeType: sequenceNodeType.REFERENCE,+ token: preSegment,+ startIndex,+ endIndex,+ },+ deleteEndIndex+ );+ } else if (Tools.isStringNumber(preSegmentTrim)) {+ this._pushSequenceNode(+ sequenceNodes,+ {+ nodeType: sequenceNodeType.NUMBER,+ token: preSegment,+ startIndex,+ endIndex,+ },+ deleteEndIndex+ );+ } else if (preSegmentTrim.length > 0) {+ this._pushSequenceNode(+ sequenceNodes,+ {+ nodeType: sequenceNodeType.FUNCTION,+ token: preSegment,+ startIndex,+ endIndex,+ },+ deleteEndIndex+ );+ }++ if (i !== len - 1 || !this._isLastMergeString(currentString)) {+ sequenceNodes.push(currentString);+ }+ }++ return this._mergeSequenceNodeReference(sequenceNodes);+ }++ private _getCurrentParamIndex(formulaString: string, index: number) {+ return this._nodeMaker(formulaString, undefined, index);+ }++ private _isLastMergeString(str: string) {+ return str === matchToken.DOUBLE_QUOTATION || Tools.isStringNumber(str) || !isFormulaLexerToken(str);+ }++ /**+ * Merge array and handle ref operations+ *+ */+ private _mergeSequenceNodeReference(sequenceNodes: Array<string | ISequenceNode>) {+ const newSequenceNodes: Array<string | ISequenceNode> = [];++ const sequenceNodesCount = sequenceNodes.length;++ let i = 0;+ while (i < sequenceNodesCount) {+ const node = sequenceNodes[i];++ if (typeof node === 'string') {+ const preNode = sequenceNodes[i - 1];+ if (+ node.trim() === matchToken.CLOSE_BRACES &&+ preNode != null &&+ typeof preNode !== 'string' &&+ preNode.nodeType === sequenceNodeType.FUNCTION+ ) {+ /**+ * Solving the merging issue of ['{1,2,3;4,5,6;7,8,10', '}']+ */+ const firstChar = preNode.token.trim().substring(0, 1);++ if (firstChar === matchToken.OPEN_BRACES) {+ preNode.nodeType = sequenceNodeType.ARRAY;+ preNode.token += node;+ preNode.endIndex += node.length;+ i++;+ continue;+ }+ }+ newSequenceNodes.push(node);+ } else {+ const nextOneNode = sequenceNodes[i + 1];++ const nextTwoNode = sequenceNodes[i + 2];++ if (+ nextOneNode === matchToken.COLON &&+ typeof node !== 'string' &&+ nextTwoNode != null &&+ typeof nextTwoNode !== 'string' &&+ isReferenceString((node.token + nextOneNode + nextTwoNode.token).trim())+ ) {+ node.nodeType = sequenceNodeType.REFERENCE;+ node.token += nextOneNode + nextTwoNode.token;+ node.endIndex = nextTwoNode.endIndex;+ i += 2;+ }++ newSequenceNodes.push(node);+ }++ i++;+ }++ return newSequenceNodes;+ }++ private _pushSequenceNode(+ sequenceNodes: Array<ISequenceNode | string>,+ node: ISequenceNode,+ deleteEndIndex: number+ ) {+ const segmentCount = deleteEndIndex - node.startIndex + 1;+ sequenceNodes.splice(sequenceNodes.length - segmentCount, segmentCount, node);+ }++ private _replacePrefixString(token: string) {+ return token.replace(new RegExp(prefixToken.AT, 'g'), '').replace(new RegExp(prefixToken.MINUS, 'g'), '');+ }++ nodeMakerTest(formulaString: string) {+ return this._nodeMaker(formulaString);+ }++ treeBuilder(+ formulaString: string,+ transformSuffix = true,+ injectDefinedName?: (sequenceArray: ISequenceArray[]) => {+ sequenceString: string;+ hasDefinedName: boolean;+ }+ ) {+ if (transformSuffix === true) {+ const lexerNode = FormulaLexerNodeCache.get(formulaString);+ if (lexerNode) {+ return lexerNode;+ }+ }++ this._resetCurrentLexerNode();++ this._currentLexerNode.setToken(DEFAULT_TOKEN_TYPE_ROOT);++ const sequenceArray: ISequenceArray[] = [];++ let state = this._nodeMaker(formulaString, sequenceArray);++ if (state === ErrorType.VALUE || sequenceArray.length === 0) {+ return state;+ }++ let currentHasDefinedName = false;++ let currentSequenceString = '';++ if (injectDefinedName) {+ const { hasDefinedName, sequenceString } = injectDefinedName(sequenceArray);++ currentHasDefinedName = hasDefinedName;++ currentSequenceString = sequenceString;+ }++ /**+ * If there is a custom name in the formula string,+ * replace the custom name with the corresponding character content and rebuild the formula.+ */+ if (currentHasDefinedName) {+ this._resetCurrentLexerNode();++ this._currentLexerNode.setToken(DEFAULT_TOKEN_TYPE_ROOT);++ state = this._nodeMaker(`=${currentSequenceString}`);++ if (state === ErrorType.VALUE) {+ return state;+ }+ }++ const node = this._getTopNode(this._currentLexerNode);+ if (node) {+ this._currentLexerNode = node;+ }++ if (transformSuffix) {+ this._suffixExpressionHandler(this._currentLexerNode);++ FormulaLexerNodeCache.set(formulaString, this._currentLexerNode);+ }++ return this._currentLexerNode;+ }++ private _suffixExpressionHandler(lexerNode: LexerNode) {+ const children = lexerNode.getChildren();+ if (!children) {+ return;+ }+ const childrenCount = children.length;++ const baseStack: Array<string | LexerNode> = []; // S2+ const symbolStack: string[] = []; // S1+ for (let i = 0; i < childrenCount; i++) {+ const node = children[i];+ if (!(node instanceof LexerNode)) {+ const char = node.trim();+ if (char === '') {+ continue;+ }++ if (OPERATOR_TOKEN_SET.has(char)) {+ while (symbolStack.length > 0) {+ const lastSymbol = symbolStack[symbolStack.length - 1]?.trim();+ if (!lastSymbol || lastSymbol === matchToken.OPEN_BRACKET) {+ break;+ }++ const lastSymbolPriority = OPERATOR_TOKEN_PRIORITY.get(lastSymbol);+ const charPriority = OPERATOR_TOKEN_PRIORITY.get(char);++ if (!lastSymbolPriority || !charPriority) {+ break;+ }++ if (charPriority > lastSymbolPriority) {+ baseStack.push(symbolStack.pop()!);+ } else {+ break;+ }+ }+ symbolStack.push(node as string);+ } else if (char === matchToken.OPEN_BRACKET) {+ symbolStack.push(node as string);+ } else if (char === matchToken.CLOSE_BRACKET) {+ while (symbolStack.length > 0) {+ const lastSymbol = symbolStack[symbolStack.length - 1]?.trim();+ if (!lastSymbol) {+ break;+ }++ if (lastSymbol === matchToken.OPEN_BRACKET) {+ symbolStack.pop();+ break;+ }++ baseStack.push(symbolStack.pop()!);+ }+ } else {+ baseStack.push(node as string);+ }+ } else {+ this._suffixExpressionHandler(node as LexerNode);+ baseStack.push(node);+ }+ }+ while (symbolStack.length > 0) {+ baseStack.push(symbolStack.pop()!);+ }+ lexerNode.setChildren(baseStack);+ }++ private _resetCurrentLexerNode() {+ this._currentLexerNode = new LexerNode();+ }++ private _resetSegment() {+ this._segment = '';+ }++ private _openBracket(type: bracketType = bracketType.NORMAL) {+ this._bracketState.push(type);+ }++ private _closeBracket() {+ this._bracketState.pop();+ }++ private _openSquareBracket() {+ this._squareBracketState += 1;+ }++ private _closeSquareBracket() {+ this._squareBracketState -= 1;+ }++ private _getCurrentBracket() {+ const bracketState = this._bracketState;+ return bracketState[bracketState.length - 1];+ }++ private _openBraces() {+ this._bracesState += 1;+ }++ private _closeBraces() {+ this._bracesState -= 1;+ }++ private _openSingleQuotation() {+ this._singleQuotationState += 1;+ }++ private _closeSingleQuotation() {+ this._singleQuotationState -= 1;+ }++ private _openDoubleQuotation() {+ this._doubleQuotationState += 1;+ }++ private _closeDoubleQuotation() {+ this._doubleQuotationState -= 1;+ }++ private _openLambda() {+ this._lambdaState = true;+ }++ private _closeLambda() {+ this._lambdaState = false;+ }++ private _openColon(upLevel: number) {+ this._upLevel = upLevel;+ this._colonState = true;+ }++ private _closeColon() {+ this._upLevel = 0;+ this._colonState = false;+ }++ private _isTableBracket() {+ return this._tableBracketState;+ }++ private _openTableBracket() {+ this._tableBracketState = true;+ }++ private _closeTableBracket() {+ this._tableBracketState = false;+ }++ private _getLastChildCurrentLexerNode() {+ const children = this._currentLexerNode.getChildren();+ if (children && children.length > 0) {+ const lastNode = children[children.length - 1];+ if (lastNode instanceof LexerNode) {+ return lastNode;+ }+ }+ return false;+ }++ private _getLastChildCurrent() {+ const children = this._currentLexerNode.getChildren();+ if (children && children.length > 0) {+ const lastNode = children[children.length - 1];+ return lastNode;+ }+ return false;+ }++ private _setParentCurrentLexerNode() {+ const parent = this._currentLexerNode.getParent();+ if (parent) {+ this._currentLexerNode = parent;+ return true;+ }++ return false;+ }++ private _setAncestorCurrentLexerNode() {+ const parent = this._currentLexerNode?.getParent();+ let state = false;+ if (parent && parent.getToken() === DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER) {+ // lambda will skip to more one level+ if (parent?.getParent()?.getParent()) {+ const node = this._currentLexerNode.getParent()?.getParent()?.getParent();+ if (node) {+ this._currentLexerNode = node;+ }+ state = true;+ }+ } else {+ if (parent?.getParent()) {+ const node = this._currentLexerNode.getParent()?.getParent();+ if (node) {+ this._currentLexerNode = node;+ }+ state = true;+ }+ }++ for (let i = 0; i < this._upLevel; i++) {+ const node = this._currentLexerNode?.getParent();+ if (node) {+ this._currentLexerNode = node;+ }+ if (this._currentLexerNode) {+ state = true;+ } else {+ state = false;+ }+ }++ return state;+ }++ private _segmentCount() {+ return this._segment.trim().length;+ }++ private _pushSegment(value: string) {+ this._segment += value;+ }++ private _pushNodeToChildren(value: LexerNode | string, isUnshift = false) {+ if (value !== '') {+ const children = this._currentLexerNode.getChildren();+ if (!(value instanceof LexerNode) && this.isColonOpen()) {+ const subLexerNode_ref = new LexerNode();+ subLexerNode_ref.setToken(value);+ subLexerNode_ref.setParent(this._currentLexerNode);++ value = subLexerNode_ref;+ }+ if (isUnshift) {+ children.unshift(value);+ } else {+ children.push(value);+ }+ }++ if (this.isColonOpen()) {+ this._setAncestorCurrentLexerNode();+ this._closeColon(); /* */+ }+ }++ private _setCurrentLexerNode(subLexerNode: LexerNode, isUnshift = false) {+ this._pushNodeToChildren(subLexerNode, isUnshift);+ subLexerNode.setParent(this._currentLexerNode);+ this._currentLexerNode = subLexerNode;+ }++ private _newAndPushCurrentLexerNode(token: string, current: number, isUnshift = false) {+ const subLexerNode = new LexerNode();+ subLexerNode.setToken(token);+ subLexerNode.setIndex(current - token.length, current - 1);+ this._setCurrentLexerNode(subLexerNode, isUnshift);+ }++ private _getTopNode(lexerNode: LexerNode) {+ let parentNode: Nullable<LexerNode> = lexerNode;+ while (parentNode?.getParent()) {+ parentNode = parentNode.getParent();+ }+ return parentNode;+ }++ private _removeLastChild() {+ const children = this._currentLexerNode.getChildren();+ children.splice(-1);+ }++ private _findPreviousToken(data: string[], index: number) {+ while (index >= 0) {+ const token = data[index];+ if (token !== ' ') {+ return token;+ }+ index--;+ }+ }++ private _negativeCondition(prevString: string) {+ if (+ OPERATOR_TOKEN_SET.has(prevString) ||+ prevString === matchToken.OPEN_BRACKET ||+ prevString === matchToken.COMMA ||+ prevString === ''+ ) {+ return true;+ }+ return false;+ }++ private _getSequenceArray(formulaString: string) {+ const sequenceArray: ISequenceArray[] = [];++ this._nodeMaker(formulaString, sequenceArray);++ return sequenceArray;+ }++ private _resetTemp() {+ this._currentLexerNode = new LexerNode();++ this._upLevel = 0;++ this._segment = '';++ this._bracketState = []; // ()++ this._bracesState = 0; // {}++ this._singleQuotationState = 0; // ''++ this._doubleQuotationState = 0; // ""++ this._lambdaState = false; // Lambda++ this._colonState = false; // :+ }++ // eslint-disable-next-line max-lines-per-function+ private _nodeMaker(formulaString: string, sequenceArray?: ISequenceArray[], matchCurrentNodeIndex?: number) {+ if (formulaString.substring(0, 1) === operatorToken.EQUALS) {+ formulaString = formulaString.substring(1);+ }+ const formulaStringArray = formulaString.split('');+ const formulaStringArrayCount = formulaStringArray.length;+ let cur = 0;+ this._resetTemp();+ while (cur < formulaStringArrayCount) {+ const currentString = formulaStringArray[cur];++ if (matchCurrentNodeIndex === cur) {+ return [this._currentLexerNode, currentString];+ }++ if (+ currentString === matchToken.OPEN_BRACKET &&+ this.isSingleQuotationClose() &&+ this.isDoubleQuotationClose()+ ) {+ if (this._segmentCount() > 0 || this.isLambdaOpen()) {+ if (this.isLambdaClose()) {+ // const subLexerNode = new LexerNode();+ // subLexerNode.token = this._segment;+ // this.setCurrentLexerNode(subLexerNode);+ this._newAndPushCurrentLexerNode(this._segment, cur);+ this._resetSegment();+ }++ this._openBracket(bracketType.FUNCTION);+ this._closeLambda();++ const nextCurrentString = formulaStringArray[cur + 1];+ if (nextCurrentString && nextCurrentString === matchToken.CLOSE_BRACKET) {+ // when function has not parameter, return to parentNode , e.g. row()+ if (!this._setParentCurrentLexerNode() && cur !== formulaStringArrayCount - 1) {+ return ErrorType.VALUE;+ }+ cur++;+ } else if (nextCurrentString) {+ // const subLexerNode = new LexerNode();+ // subLexerNode.token = DEFAULT_TOKEN_TYPE_PARAMETER;+ // this.setCurrentLexerNode(subLexerNode);+ this._newAndPushCurrentLexerNode(DEFAULT_TOKEN_TYPE_PARAMETER, cur);++ // this._pushNodeToChildren(matchToken.OPEN_BRACKET);+ }+ } else {+ this._pushNodeToChildren(currentString);+ this._openBracket(bracketType.NORMAL);+ }+ } else if (+ currentString === matchToken.CLOSE_BRACKET &&+ this.isSingleQuotationClose() &&+ this.isDoubleQuotationClose()+ ) {+ this._pushNodeToChildren(this._segment);+ this._resetSegment();+ const currentBracket = this._getCurrentBracket();+ if (currentBracket === bracketType.NORMAL) {+ this._pushNodeToChildren(currentString);+ } else if (currentBracket === bracketType.FUNCTION) {+ // function close+ const nextCurrentString = formulaStringArray[cur + 1];+ if (nextCurrentString && nextCurrentString === matchToken.OPEN_BRACKET) {+ // lambda handler, e.g. =lambda(x,y, x*y*x)(1,2)+ if (!this._setParentCurrentLexerNode() && cur !== formulaStringArrayCount - 1) {+ return ErrorType.VALUE;+ }+ // const subLexerNode = new LexerNode();+ // subLexerNode.token = DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER;+ // this.setCurrentLexerNode(subLexerNode);+ this._newAndPushCurrentLexerNode(DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER, cur, true);+ this._openLambda();+ } else {+ if (!this._setAncestorCurrentLexerNode() && cur !== formulaStringArrayCount - 1) {+ return ErrorType.VALUE;+ }+ }+ } else {+ return ErrorType.VALUE;+ }+ this._closeBracket();+ } else if (+ currentString === matchToken.OPEN_BRACES &&+ this.isSingleQuotationClose() &&+ this.isDoubleQuotationClose()+ ) {+ this._pushSegment(currentString);+ this._openBraces();+ } else if (+ currentString === matchToken.CLOSE_BRACES &&+ this.isSingleQuotationClose() &&+ this.isDoubleQuotationClose()+ ) {+ this._pushSegment(currentString);+ this._pushNodeToChildren(this._segment);+ this._resetSegment();+ this._closeBraces();+ } else if (+ currentString === matchToken.OPEN_SQUARE_BRACKET &&+ this.isSingleQuotationClose() &&+ this.isDoubleQuotationClose()+ ) {+ if (this._segment.length > 0) {+ this._openTableBracket();+ }+ this._pushSegment(currentString);+ this._openSquareBracket();+ } else if (+ currentString === matchToken.CLOSE_SQUARE_BRACKET &&+ this.isSingleQuotationClose() &&+ this.isDoubleQuotationClose()+ ) {+ this._closeSquareBracket();+ if (this.isSquareBracketClose()) {+ this._pushSegment(currentString);+ if (this._isTableBracket()) {+ this._pushNodeToChildren(this._segment);+ this._resetSegment();+ }+ this._closeTableBracket();+ } else {+ this._pushSegment(currentString);+ }+ } else if (+ currentString === matchToken.DOUBLE_QUOTATION &&+ this.isSingleQuotationClose() &&+ this.isBracesClose() &&+ this.isSquareBracketClose()+ ) {+ if (this.isDoubleQuotationClose()) {+ this._openDoubleQuotation();+ } else {+ const nextCurrentString = formulaStringArray[cur + 1];+ if (nextCurrentString && nextCurrentString === matchToken.DOUBLE_QUOTATION) {+ cur++;+ } else {+ this._closeDoubleQuotation();+ }+ }+ // this._pushNodeToChildren(currentString);+ this._pushSegment(currentString);+ } else if (currentString === matchToken.SINGLE_QUOTATION && this.isDoubleQuotationClose()) {+ if (this.isSingleQuotationClose()) {+ this._openSingleQuotation();+ } else {+ const nextCurrentString = formulaStringArray[cur + 1];+ if (nextCurrentString && nextCurrentString === matchToken.SINGLE_QUOTATION) {+ cur++;+ } else {+ this._closeSingleQuotation();+ }+ }+ // this._pushNodeToChildren(currentString);+ this._pushSegment(currentString);+ } else if (+ currentString === matchToken.COMMA &&+ this.isSingleQuotationClose() &&+ this.isDoubleQuotationClose() &&+ this.isBracesClose() &&+ this.isSquareBracketClose()+ ) {+ const currentBracket = this._getCurrentBracket();+ /**+ * Handle the occurrence of commas, where in the formula,+ * the comma represents the parameters of the function+ * [currentBracket == null] is for the situation where [=A1:B1, B5:A10] occurs+ */+ if (currentBracket === bracketType.FUNCTION || currentBracket == null) {+ this._pushNodeToChildren(this._segment);+ this._resetSegment();+ if (+ !this._setParentCurrentLexerNode() &&+ cur !== formulaStringArrayCount - 1 &&+ currentBracket != null+ ) {+ return ErrorType.VALUE;+ }+ // const subLexerNode = new LexerNode();+ // subLexerNode.token = DEFAULT_TOKEN_TYPE_PARAMETER;+ // this.setCurrentLexerNode(subLexerNode);+ this._newAndPushCurrentLexerNode(DEFAULT_TOKEN_TYPE_PARAMETER, cur);+ } else {+ return ErrorType.VALUE;+ }+ } else if (+ currentString === matchToken.COLON &&+ this.isSingleQuotationClose() &&+ this.isDoubleQuotationClose() &&+ this.isBracesClose() &&+ this.isSquareBracketClose()+ ) {+ // const subLexerNode = new LexerNode();+ // subLexerNode.token = currentString;+ // this.setCurrentLexerNode(subLexerNode);+ // this.newAndPushCurrentLexerNode(currentString);+ // this._resetSegment();++ const subLexerNode_op = new LexerNode();+ subLexerNode_op.setToken(currentString);++ const subLexerNode_left = new LexerNode();+ subLexerNode_left.setToken(DEFAULT_TOKEN_TYPE_PARAMETER);+ subLexerNode_left.setParent(subLexerNode_op);++ const subLexerNode_right = new LexerNode();+ subLexerNode_right.setToken(DEFAULT_TOKEN_TYPE_PARAMETER);+ subLexerNode_right.setParent(subLexerNode_op);++ subLexerNode_op.getChildren().push(subLexerNode_left, subLexerNode_right);++ let subLexerNode_main = subLexerNode_op;+ let upLevel = 0;+ if (this._segmentCount() > 0) {+ // e.g. A1:B5+ // -@A4:B5+ let subLexerNode_minus: Nullable<LexerNode>;+ let subLexerNode_at: Nullable<LexerNode>;+ let sliceLength = 0;+ const segmentTrim = this._segment.trim();+ const lastString = segmentTrim[0];+ const twoLastString = segmentTrim[1];++ // new RegExp(prefixToken.MINUS, 'g').test(this._segment)+ if (lastString === prefixToken.MINUS) {+ subLexerNode_minus = new LexerNode();+ subLexerNode_minus.setToken(prefixToken.MINUS);+ sliceLength++;+ }++ // new RegExp(prefixToken.AT, 'g').test(this._segment)+ if (lastString === prefixToken.AT || twoLastString === prefixToken.AT) {+ subLexerNode_at = new LexerNode();+ subLexerNode_at.setToken(prefixToken.AT);++ if (subLexerNode_minus) {+ subLexerNode_minus.addChildren(subLexerNode_at);+ subLexerNode_at.setParent(subLexerNode_minus);+ }++ sliceLength++;+ }++ if (sliceLength > 0) {+ this._segment = segmentTrim.slice(sliceLength);+ }++ upLevel = sliceLength;++ if (subLexerNode_at) {+ subLexerNode_at.addChildren(subLexerNode_op);+ subLexerNode_op.setParent(subLexerNode_at);+ if (subLexerNode_at.getParent()) {+ const node = subLexerNode_at.getParent();+ if (node) {+ subLexerNode_main = node;+ }+ } else {+ subLexerNode_main = subLexerNode_at;+ }+ } else if (subLexerNode_minus) {+ subLexerNode_main = subLexerNode_minus;+ subLexerNode_minus.addChildren(subLexerNode_op);+ subLexerNode_op.setParent(subLexerNode_minus);+ }++ const subLexerNode_ref = new LexerNode();+ subLexerNode_ref.setToken(this._segment);+ subLexerNode_ref.setParent(subLexerNode_left);++ subLexerNode_left.getChildren().push(subLexerNode_ref);+ this._resetSegment();+ } else {+ // e.g. indirect("A5"):B10+ const lastChildNode = this._getLastChildCurrentLexerNode();+ if (lastChildNode) {+ lastChildNode.changeToParent(subLexerNode_left);+ }+ }++ this._setCurrentLexerNode(subLexerNode_main);+ this._currentLexerNode = subLexerNode_right;+ this._openColon(upLevel);+ } else if (+ SUFFIX_TOKEN_SET.has(currentString) &&+ this.isSingleQuotationClose() &&+ this.isDoubleQuotationClose() &&+ this.isSquareBracketClose()+ ) {+ this._pushNodeToChildren(this._segment);++ // this._pushNodeToChildren(currentString);++ const subLexerNode = new LexerNode();+ subLexerNode.setToken(currentString);++ const lastChildNode = this._getLastChildCurrent();+ if (lastChildNode instanceof LexerNode) {+ lastChildNode.changeToParent(subLexerNode);+ } else if (lastChildNode !== false) {+ subLexerNode.getChildren().push(lastChildNode);+ this._removeLastChild();+ }++ this._pushNodeToChildren(subLexerNode);+ subLexerNode.setParent(this._currentLexerNode);++ this._resetSegment();+ } else if (+ OPERATOR_TOKEN_SET.has(currentString) &&+ this.isSingleQuotationClose() &&+ this.isDoubleQuotationClose() &&+ this.isSquareBracketClose()+ ) {+ let trimSegment = this._segment.trim();++ if (currentString === operatorToken.MINUS && trimSegment === '') {+ // negative number+ const prevString = this._findPreviousToken(formulaStringArray, cur - 1) || '';+ if (this._negativeCondition(prevString)) {+ this._pushSegment(operatorToken.MINUS);++ sequenceArray?.push({+ segment: this._segment,+ currentString,+ cur,+ currentLexerNode: this._currentLexerNode,+ });+ cur++;+ continue;+ }+ } else if (this._segment.length > 0 && trimSegment === '') {+ trimSegment = this._segment;+ } else {+ this._pushNodeToChildren(this._segment);+ trimSegment = '';+ }++ if (currentString === operatorToken.LESS_THAN || currentString === operatorToken.GREATER_THAN) {+ const nextCurrentString = formulaStringArray[cur + 1];+ if (nextCurrentString && OPERATOR_TOKEN_SET.has(currentString + nextCurrentString)) {+ this._pushNodeToChildren(trimSegment + currentString + nextCurrentString);+ cur++;+ } else {+ this._pushNodeToChildren(trimSegment + currentString);+ }+ } else {+ this._pushNodeToChildren(trimSegment + currentString);+ }+ this._resetSegment();+ } else {+ this._pushSegment(currentString);+ }++ sequenceArray?.push({+ segment: this._segment,+ currentString,+ cur,+ currentLexerNode: this._currentLexerNode,+ });+ cur++;+ }++ this._pushNodeToChildren(this._segment);+ }+}diff --git a/packages/engine-formula/src/engine/analysis/lexer.ts b/packages/engine-formula/src/engine/analysis/lexer.tsindex 9a1ae874e5..b848847185 100644--- a/packages/engine-formula/src/engine/analysis/lexer.ts+++ b/packages/engine-formula/src/engine/analysis/lexer.ts@@ -1,1113 +1,64 @@-import type { Nullable } from '@univerjs/core';-import { deserializeRangeWithSheet, Disposable, Rectangle, serializeRangeToRefString, Tools } from '@univerjs/core';--import { FormulaAstLRU } from '../../basics/cache-lru';-import { ErrorType } from '../../basics/error-type';-import { isFormulaLexerToken } from '../../basics/match-token';-import { isReferenceString, REFERENCE_SINGLE_RANGE_REGEX } from '../../basics/regex';-import {- matchToken,- OPERATOR_TOKEN_PRIORITY,- OPERATOR_TOKEN_SET,- operatorToken,- prefixToken,- SUFFIX_TOKEN_SET,-} from '../../basics/token';-import {- DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER,- DEFAULT_TOKEN_TYPE_PARAMETER,- DEFAULT_TOKEN_TYPE_ROOT,-} from '../../basics/token-type';-import type { ISequenceArray, ISequenceNode } from '../utils/sequence';-import { generateStringWithSequence, sequenceNodeType } from '../utils/sequence';-import { LexerNode } from './lexer-node';--enum bracketType {- NORMAL,- FUNCTION,- LAMBDA,-}--const FORMULA_CACHE_LRU_COUNT = 100000;--export const FormulaLexerNodeCache = new FormulaAstLRU<LexerNode>(FORMULA_CACHE_LRU_COUNT);--export const FormulaSequenceNodeCache = new FormulaAstLRU<Array<string | ISequenceNode>>(FORMULA_CACHE_LRU_COUNT);--export class LexerTreeBuilder extends Disposable {- private _currentLexerNode: LexerNode = new LexerNode();-- private _upLevel = 0;-- private _segment = '';-- private _bracketState: bracketType[] = []; // ()-- private _bracesState = 0; // {}-- private _singleQuotationState = 0; // ''-- private _doubleQuotationState = 0; // ""-- private _lambdaState = false; // Lambda-- private _colonState = false; // :-- override dispose(): void {- this._resetTemp();- this._currentLexerNode.dispose();-- FormulaLexerNodeCache.clear();-- FormulaSequenceNodeCache.clear();- }-- getUpLevel() {- return this._upLevel;- }-- isColonClose() {- return this._colonState === false;- }-- isColonOpen() {- return this._colonState === true;- }-- isDoubleQuotationClose() {- return this._doubleQuotationState === 0;- }-- isLambdaOpen() {- return this._lambdaState === true;- }-- isLambdaClose() {- return this._lambdaState === false;- }-- isSingleQuotationClose() {- return this._singleQuotationState === 0;- }-- isBracesClose() {- return this._bracesState === 0;- }-- isBracketClose() {- return this._bracketState.length === 0;- }-- getCurrentLexerNode() {- return this._currentLexerNode;+import { Disposable } from '@univerjs/core';+import { Inject } from '@wendellhu/redi';++import { IDefinedNamesService } from '../../services/defined-names.service';+import { IFormulaRuntimeService } from '../../services/runtime.service';+import type { ISequenceArray } from '../utils/sequence';+import { sequenceNodeType } from '../utils/sequence';+import { LexerTreeBuilder } from './lexer-tree-builder';++export class Lexer extends Disposable {+ constructor(+ @IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService,+ @IFormulaRuntimeService private readonly _runtimeService: IFormulaRuntimeService,+ @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder+ ) {+ super();}- getFunctionAndParameter(formulaString: string, strIndex: number) {- const current = this._getCurrentParamIndex(formulaString, strIndex);-- if (current == null || current === ErrorType.VALUE) {- return;- }-- const lexerNode = current[0];-- if (typeof lexerNode === 'string') {- return;- }-- let parent = lexerNode.getParent();-- let children = lexerNode;-- while (parent) {- const token = parent.getToken();- if (- token !== DEFAULT_TOKEN_TYPE_PARAMETER &&- !isFormulaLexerToken(token) &&- parent.getStartIndex() !== -1- ) {- const paramIndex = parent.getChildren().indexOf(children);-- return {- functionName: token,- paramIndex,- };- }-- children = parent;- parent = parent.getParent();- }+ treeBuilder(formulaString: string, transformSuffix = true) {+ return this._lexerTreeBuilder.treeBuilder(formulaString, transformSuffix, this._injectDefinedName.bind(this));}- moveFormulaRefOffset(formulaString: string, refOffsetX: number, refOffsetY: number) {- const sequenceNodes = this.sequenceNodesBuilder(formulaString);+ private _injectDefinedName(sequenceArray: ISequenceArray[]) {+ const unitId = this._runtimeService.currentUnitId;- if (sequenceNodes == null) {- return formulaString;+ if (!this._definedNamesService.hasDefinedName(unitId)) {+ return {+ sequenceString: '',+ hasDefinedName: false,+ };}- const newSequenceNodes: Array<string | ISequenceNode> = [];+ const sequenceNodes = this._lexerTreeBuilder.getSequenceNode(sequenceArray);+ let sequenceString = '';+ let hasDefinedName = false;for (let i = 0, len = sequenceNodes.length; i < len; i++) {const node = sequenceNodes[i];- if (typeof node === 'string' || node.nodeType !== sequenceNodeType.REFERENCE) {- newSequenceNodes.push(node);- continue;- }-- const { token } = node;-- const sequenceGrid = deserializeRangeWithSheet(token);-- const { range, sheetName, unitId: sequenceUnitId } = sequenceGrid;-- const newRange = Rectangle.moveOffset(range, refOffsetX, refOffsetY);-- newSequenceNodes.push({- ...node,- token: serializeRangeToRefString({- range: newRange,- unitId: sequenceUnitId,- sheetName,- }),- });- }-- return `=${generateStringWithSequence(newSequenceNodes)}`;- }-- /**- * Estimate the number of right brackets that need to be automatically added to the end of the formula.- * @param formulaString- * @returns- */- checkIfAddBracket(formulaString: string) {- let lastBracketCount = 0;- let lastIndex = formulaString.length - 1;- let lastString = formulaString[lastIndex];- /**- * Determine how many close brackets are at the end, and estimate how many functions need to automatically add close brackets.- */- while (lastString === matchToken.CLOSE_BRACKET || lastString === ' ') {- if (lastString === matchToken.CLOSE_BRACKET) {- lastBracketCount++;- }- lastString = formulaString[--lastIndex];- }-- const current = this._getCurrentParamIndex(formulaString, formulaString.length - 2);-- if (current == null || current === ErrorType.VALUE) {- return 0;- }-- const lexerNode = current[0];-- if (typeof lexerNode === 'string') {- return 0;- }-- let parent = lexerNode.getParent();- let bracketCount = 0;-- /**- * Perform an upward search on the syntax tree to see how many layers the function is nested.- * For each layer passed, subtract the estimated number of right brackets,- * ultimately obtaining the number of right brackets that need to be completed.- */- while (parent) {- const token = parent.getToken();- if (token !== DEFAULT_TOKEN_TYPE_PARAMETER && token !== matchToken.COLON && parent.getStartIndex() !== -1) {- if (lastBracketCount === 0) {- bracketCount += 1;- } else {- lastBracketCount--;- }- }-- parent = parent.getParent();- }-- return bracketCount;- }-- sequenceNodesBuilder(formulaString: string) {- const sequenceNodesCache = FormulaSequenceNodeCache.get(formulaString);- if (sequenceNodesCache) {- return [...sequenceNodesCache];- }-- const sequenceArray = this._getSequenceArray(formulaString);- if (sequenceArray.length === 0) {- return;- }-- const sequenceNodes: Array<ISequenceNode | string> = [];-- let maybeString = false;-- for (let i = 0, len = sequenceArray.length; i < len; i++) {- const item = sequenceArray[i];-- const preItem = sequenceArray[i - 1];-- const { segment, currentString, cur } = item;-- if (currentString === matchToken.DOUBLE_QUOTATION) {- maybeString = true;- }-- if ((segment !== '' || i === 0) && i !== len - 1) {- sequenceNodes.push(currentString);- continue;- }-- let preSegment = preItem?.segment || '';-- const startIndex = i - preSegment.length;-- let endIndex = i - 1;-- const deleteEndIndex = i - 1;-- if (i === len - 1 && this._isLastMergeString(currentString)) {- preSegment += currentString;-- endIndex += 1;- }-- if (preSegment === '' || OPERATOR_TOKEN_PRIORITY.has(preSegment)) {- sequenceNodes.push(currentString);- continue;- }-- const preSegmentTrim = preSegment.trim();-- const preSegmentNotPrefixToken = this._replacePrefixString(preSegmentTrim);-- if (maybeString === true && preSegmentTrim[preSegmentTrim.length - 1] === matchToken.DOUBLE_QUOTATION) {- maybeString = false;- this._pushSequenceNode(- sequenceNodes,- {- nodeType: sequenceNodeType.STRING,- token: preSegment,- startIndex,- endIndex,- },- deleteEndIndex- );- } else if (new RegExp(REFERENCE_SINGLE_RANGE_REGEX).test(preSegmentNotPrefixToken)) {- this._pushSequenceNode(- sequenceNodes,- {- nodeType: sequenceNodeType.REFERENCE,- token: preSegment,- startIndex,- endIndex,- },- deleteEndIndex- );- } else if (Tools.isStringNumber(preSegmentTrim)) {- this._pushSequenceNode(- sequenceNodes,- {- nodeType: sequenceNodeType.NUMBER,- token: preSegment,- startIndex,- endIndex,- },- deleteEndIndex- );- } else if (preSegmentTrim.length > 0) {- this._pushSequenceNode(- sequenceNodes,- {- nodeType: sequenceNodeType.FUNCTION,- token: preSegment,- startIndex,- endIndex,- },- deleteEndIndex- );- }-- if (i !== len - 1 || !this._isLastMergeString(currentString)) {- sequenceNodes.push(currentString);- }- }-- const newSequenceNodes = this._mergeSequenceNodeReference(sequenceNodes);-- // let sequenceString = '';- // for (const node of newSequenceNodes) {- // if (typeof node === 'string') {- // sequenceString += node;- // } else {- // sequenceString += node.token;- // }- // }- // console.log('sequenceString', sequenceString);-- FormulaSequenceNodeCache.set(formulaString, [...newSequenceNodes]);-- return newSequenceNodes;- }-- private _getCurrentParamIndex(formulaString: string, index: number) {- return this._nodeMaker(formulaString, undefined, index);- }-- private _isLastMergeString(str: string) {- return str === matchToken.DOUBLE_QUOTATION || Tools.isStringNumber(str) || !isFormulaLexerToken(str);- }-- /**- * Merge array and handle ref operations- *- */- private _mergeSequenceNodeReference(sequenceNodes: Array<string | ISequenceNode>) {- const newSequenceNodes: Array<string | ISequenceNode> = [];-- const sequenceNodesCount = sequenceNodes.length;-- let i = 0;- while (i < sequenceNodesCount) {- const node = sequenceNodes[i];-if (typeof node === 'string') {- const preNode = sequenceNodes[i - 1];- if (- node.trim() === matchToken.CLOSE_BRACES &&- preNode != null &&- typeof preNode !== 'string' &&- preNode.nodeType === sequenceNodeType.FUNCTION- ) {- /**- * Solving the merging issue of ['{1,2,3;4,5,6;7,8,10', '}']- */- const firstChar = preNode.token.trim().substring(0, 1);-- if (firstChar === matchToken.OPEN_BRACES) {- preNode.nodeType = sequenceNodeType.ARRAY;- preNode.token += node;- preNode.endIndex += node.length;- i++;- continue;- }- }- newSequenceNodes.push(node);- } else {- const nextOneNode = sequenceNodes[i + 1];-- const nextTwoNode = sequenceNodes[i + 2];-- if (- nextOneNode === matchToken.COLON &&- typeof node !== 'string' &&- nextTwoNode != null &&- typeof nextTwoNode !== 'string' &&- isReferenceString((node.token + nextOneNode + nextTwoNode.token).trim())- ) {- node.nodeType = sequenceNodeType.REFERENCE;- node.token += nextOneNode + nextTwoNode.token;- node.endIndex = nextTwoNode.endIndex;- i += 2;- }-- newSequenceNodes.push(node);- }-- i++;- }-- return newSequenceNodes;- }-- private _pushSequenceNode(- sequenceNodes: Array<ISequenceNode | string>,- node: ISequenceNode,- deleteEndIndex: number- ) {- const segmentCount = deleteEndIndex - node.startIndex + 1;- sequenceNodes.splice(sequenceNodes.length - segmentCount, segmentCount, node);- }-- private _replacePrefixString(token: string) {- return token.replace(new RegExp(prefixToken.AT, 'g'), '').replace(new RegExp(prefixToken.MINUS, 'g'), '');- }-- treeBuilder(formulaString: string, transformSuffix = true) {- if (transformSuffix === true) {- const lexerNode = FormulaLexerNodeCache.get(formulaString);- if (lexerNode) {- return lexerNode;- }- }-- this._resetCurrentLexerNode();-- this._currentLexerNode.setToken(DEFAULT_TOKEN_TYPE_ROOT);-- const state = this._nodeMaker(formulaString);-- if (state === ErrorType.VALUE) {- return state;- }-- const node = this._getTopNode(this._currentLexerNode);- if (node) {- this._currentLexerNode = node;- }-- if (transformSuffix) {- this._suffixExpressionHandler(this._currentLexerNode);-- FormulaLexerNodeCache.set(formulaString, this._currentLexerNode);- }-- return this._currentLexerNode;- }-- private _suffixExpressionHandler(lexerNode: LexerNode) {- const children = lexerNode.getChildren();- if (!children) {- return;- }- const childrenCount = children.length;-- const baseStack: Array<string | LexerNode> = []; // S2- const symbolStack: string[] = []; // S1- for (let i = 0; i < childrenCount; i++) {- const node = children[i];- if (!(node instanceof LexerNode)) {- const char = node.trim();- if (char === '') {- continue;- }-- if (OPERATOR_TOKEN_SET.has(char)) {- while (symbolStack.length > 0) {- const lastSymbol = symbolStack[symbolStack.length - 1]?.trim();- if (!lastSymbol || lastSymbol === matchToken.OPEN_BRACKET) {- break;- }-- const lastSymbolPriority = OPERATOR_TOKEN_PRIORITY.get(lastSymbol);- const charPriority = OPERATOR_TOKEN_PRIORITY.get(char);-- if (!lastSymbolPriority || !charPriority) {- break;- }-- if (charPriority > lastSymbolPriority) {- baseStack.push(symbolStack.pop()!);- } else {- break;- }- }- symbolStack.push(node as string);- } else if (char === matchToken.OPEN_BRACKET) {- symbolStack.push(node as string);- } else if (char === matchToken.CLOSE_BRACKET) {- while (symbolStack.length > 0) {- const lastSymbol = symbolStack[symbolStack.length - 1]?.trim();- if (!lastSymbol) {- break;- }-- if (lastSymbol === matchToken.OPEN_BRACKET) {- symbolStack.pop();- break;- }-- baseStack.push(symbolStack.pop()!);- }- } else {- baseStack.push(node as string);- }- } else {- this._suffixExpressionHandler(node as LexerNode);- baseStack.push(node);- }- }- while (symbolStack.length > 0) {- baseStack.push(symbolStack.pop()!);- }- lexerNode.setChildren(baseStack);- }-- private _resetCurrentLexerNode() {- this._currentLexerNode = new LexerNode();- }-- private _resetSegment() {- this._segment = '';- }-- private _openBracket(type: bracketType = bracketType.NORMAL) {- this._bracketState.push(type);- }-- private _closeBracket() {- this._bracketState.pop();- }-- private _getCurrentBracket() {- const bracketState = this._bracketState;- return bracketState[bracketState.length - 1];- }-- private _openBraces() {- this._bracesState += 1;- }-- private _closeBraces() {- this._bracesState -= 1;- }-- private _openSingleQuotation() {- this._singleQuotationState += 1;- }-- private _closeSingleQuotation() {- this._singleQuotationState -= 1;- }-- private _openDoubleQuotation() {- this._doubleQuotationState += 1;- }-- private _closeDoubleQuotation() {- this._doubleQuotationState -= 1;- }-- private _openLambda() {- this._lambdaState = true;- }-- private _closeLambda() {- this._lambdaState = false;- }-- private _openColon(upLevel: number) {- this._upLevel = upLevel;- this._colonState = true;- }-- private _closeColon() {- this._upLevel = 0;- this._colonState = false;- }-- private _getLastChildCurrentLexerNode() {- const children = this._currentLexerNode.getChildren();- if (children && children.length > 0) {- const lastNode = children[children.length - 1];- if (lastNode instanceof LexerNode) {- return lastNode;- }- }- return false;- }-- private _getLastChildCurrent() {- const children = this._currentLexerNode.getChildren();- if (children && children.length > 0) {- const lastNode = children[children.length - 1];- return lastNode;- }- return false;- }-- private _setParentCurrentLexerNode() {- const parent = this._currentLexerNode.getParent();- if (parent) {- this._currentLexerNode = parent;- return true;- }-- return false;- }-- private _setAncestorCurrentLexerNode() {- const parent = this._currentLexerNode?.getParent();- let state = false;- if (parent && parent.getToken() === DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER) {- // lambda will skip to more one level- if (parent?.getParent()?.getParent()) {- const node = this._currentLexerNode.getParent()?.getParent()?.getParent();- if (node) {- this._currentLexerNode = node;- }- state = true;- }- } else {- if (parent?.getParent()) {- const node = this._currentLexerNode.getParent()?.getParent();- if (node) {- this._currentLexerNode = node;- }- state = true;- }- }-- for (let i = 0; i < this._upLevel; i++) {- const node = this._currentLexerNode?.getParent();- if (node) {- this._currentLexerNode = node;- }- if (this._currentLexerNode) {- state = true;- } else {- state = false;- }- }-- return state;- }-- private _segmentCount() {- return this._segment.trim().length;- }-- private _pushSegment(value: string) {- this._segment += value;- }-- private _pushNodeToChildren(value: LexerNode | string, isUnshift = false) {- if (value !== '') {- const children = this._currentLexerNode.getChildren();- if (!(value instanceof LexerNode) && this.isColonOpen()) {- const subLexerNode_ref = new LexerNode();- subLexerNode_ref.setToken(value);- subLexerNode_ref.setParent(this._currentLexerNode);-- value = subLexerNode_ref;- }- if (isUnshift) {- children.unshift(value);- } else {- children.push(value);- }- }-- if (this.isColonOpen()) {- this._setAncestorCurrentLexerNode();- this._closeColon(); /* */- }- }-- private _setCurrentLexerNode(subLexerNode: LexerNode, isUnshift = false) {- this._pushNodeToChildren(subLexerNode, isUnshift);- subLexerNode.setParent(this._currentLexerNode);- this._currentLexerNode = subLexerNode;- }-- private _newAndPushCurrentLexerNode(token: string, current: number, isUnshift = false) {- const subLexerNode = new LexerNode();- subLexerNode.setToken(token);- subLexerNode.setIndex(current - token.length, current - 1);- this._setCurrentLexerNode(subLexerNode, isUnshift);- }-- private _getTopNode(lexerNode: LexerNode) {- let parentNode: Nullable<LexerNode> = lexerNode;- while (parentNode?.getParent()) {- parentNode = parentNode.getParent();- }- return parentNode;- }-- private _removeLastChild() {- const children = this._currentLexerNode.getChildren();- children.splice(-1);- }-- private _findPreviousToken(data: string[], index: number) {- while (index >= 0) {- const token = data[index];- if (token !== ' ') {- return token;- }- index--;- }- }-- private _negativeCondition(prevString: string) {- if (- OPERATOR_TOKEN_SET.has(prevString) ||- prevString === matchToken.OPEN_BRACKET ||- prevString === matchToken.COMMA ||- prevString === ''- ) {- return true;- }- return false;- }-- private _getSequenceArray(formulaString: string) {- const sequenceArray: ISequenceArray[] = [];-- this._nodeMaker(formulaString, sequenceArray);-- return sequenceArray;- }-- private _resetTemp() {- this._currentLexerNode = new LexerNode();-- this._upLevel = 0;-- this._segment = '';-- this._bracketState = []; // ()-- this._bracesState = 0; // {}-- this._singleQuotationState = 0; // ''-- this._doubleQuotationState = 0; // ""-- this._lambdaState = false; // Lambda-- this._colonState = false; // :- }-- // eslint-disable-next-line max-lines-per-function- private _nodeMaker(formulaString: string, sequenceArray?: ISequenceArray[], matchCurrentNodeIndex?: number) {- if (formulaString.substring(0, 1) === operatorToken.EQUALS) {- formulaString = formulaString.substring(1);- }- const formulaStringArray = formulaString.split('');- const formulaStringArrayCount = formulaStringArray.length;- let cur = 0;- this._resetTemp();- while (cur < formulaStringArrayCount) {- const currentString = formulaStringArray[cur];-- if (matchCurrentNodeIndex === cur) {- return [this._currentLexerNode, currentString];+ sequenceString += node;+ continue;}- if (- currentString === matchToken.OPEN_BRACKET &&- this.isSingleQuotationClose() &&- this.isDoubleQuotationClose()- ) {- if (this._segmentCount() > 0 || this.isLambdaOpen()) {- if (this.isLambdaClose()) {- // const subLexerNode = new LexerNode();- // subLexerNode.token = this._segment;- // this.setCurrentLexerNode(subLexerNode);- this._newAndPushCurrentLexerNode(this._segment, cur);- this._resetSegment();- }-- this._openBracket(bracketType.FUNCTION);- this._closeLambda();-- const nextCurrentString = formulaStringArray[cur + 1];- if (nextCurrentString && nextCurrentString === matchToken.CLOSE_BRACKET) {- // when function has not parameter, return to parentNode , e.g. row()- if (!this._setParentCurrentLexerNode() && cur !== formulaStringArrayCount - 1) {- return ErrorType.VALUE;- }- cur++;- } else if (nextCurrentString) {- // const subLexerNode = new LexerNode();- // subLexerNode.token = DEFAULT_TOKEN_TYPE_PARAMETER;- // this.setCurrentLexerNode(subLexerNode);- this._newAndPushCurrentLexerNode(DEFAULT_TOKEN_TYPE_PARAMETER, cur);+ const { nodeType, token } = node;- // this._pushNodeToChildren(matchToken.OPEN_BRACKET);- }+ if (nodeType === sequenceNodeType.REFERENCE || nodeType === sequenceNodeType.FUNCTION) {+ const definedContent = this._definedNamesService.getDefinedNameMap(unitId)?.get(token);+ if (definedContent) {+ sequenceString += definedContent;+ hasDefinedName = true;} else {- this._pushNodeToChildren(currentString);- this._openBracket(bracketType.NORMAL);+ sequenceString += token;}- } else if (- currentString === matchToken.CLOSE_BRACKET &&- this.isSingleQuotationClose() &&- this.isDoubleQuotationClose()- ) {- this._pushNodeToChildren(this._segment);- this._resetSegment();- const currentBracket = this._getCurrentBracket();- if (currentBracket === bracketType.NORMAL) {- this._pushNodeToChildren(currentString);- } else if (currentBracket === bracketType.FUNCTION) {- // function close- const nextCurrentString = formulaStringArray[cur + 1];- if (nextCurrentString && nextCurrentString === matchToken.OPEN_BRACKET) {- // lambda handler, e.g. =lambda(x,y, x*y*x)(1,2)- if (!this._setParentCurrentLexerNode() && cur !== formulaStringArrayCount - 1) {- return ErrorType.VALUE;- }- // const subLexerNode = new LexerNode();- // subLexerNode.token = DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER;- // this.setCurrentLexerNode(subLexerNode);- this._newAndPushCurrentLexerNode(DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER, cur, true);- this._openLambda();- } else {- if (!this._setAncestorCurrentLexerNode() && cur !== formulaStringArrayCount - 1) {- return ErrorType.VALUE;- }- }- } else {- return ErrorType.VALUE;- }- this._closeBracket();- } else if (- currentString === matchToken.OPEN_BRACES &&- this.isSingleQuotationClose() &&- this.isDoubleQuotationClose()- ) {- this._pushSegment(currentString);- this._openBraces();- } else if (- currentString === matchToken.CLOSE_BRACES &&- this.isSingleQuotationClose() &&- this.isDoubleQuotationClose()- ) {- this._pushSegment(currentString);- this._pushNodeToChildren(this._segment);- this._resetSegment();- this._closeBraces();- } else if (- currentString === matchToken.DOUBLE_QUOTATION &&- this.isSingleQuotationClose() &&- this.isBracesClose()- ) {- if (this.isDoubleQuotationClose()) {- this._openDoubleQuotation();- } else {- const nextCurrentString = formulaStringArray[cur + 1];- if (nextCurrentString && nextCurrentString === matchToken.DOUBLE_QUOTATION) {- cur++;- } else {- this._closeDoubleQuotation();- }- }- // this._pushNodeToChildren(currentString);- this._pushSegment(currentString);- } else if (currentString === matchToken.SINGLE_QUOTATION && this.isDoubleQuotationClose()) {- if (this.isSingleQuotationClose()) {- this._openSingleQuotation();- } else {- const nextCurrentString = formulaStringArray[cur + 1];- if (nextCurrentString && nextCurrentString === matchToken.SINGLE_QUOTATION) {- cur++;- } else {- this._closeSingleQuotation();- }- }- // this._pushNodeToChildren(currentString);- this._pushSegment(currentString);- } else if (- currentString === matchToken.COMMA &&- this.isSingleQuotationClose() &&- this.isDoubleQuotationClose() &&- this.isBracesClose()- ) {- const currentBracket = this._getCurrentBracket();- /**- * Handle the occurrence of commas, where in the formula,- * the comma represents the parameters of the function- * [currentBracket == null] is for the situation where [=A1:B1, B5:A10] occurs- */- if (currentBracket === bracketType.FUNCTION || currentBracket == null) {- this._pushNodeToChildren(this._segment);- this._resetSegment();- if (- !this._setParentCurrentLexerNode() &&- cur !== formulaStringArrayCount - 1 &&- currentBracket != null- ) {- return ErrorType.VALUE;- }- // const subLexerNode = new LexerNode();- // subLexerNode.token = DEFAULT_TOKEN_TYPE_PARAMETER;- // this.setCurrentLexerNode(subLexerNode);- this._newAndPushCurrentLexerNode(DEFAULT_TOKEN_TYPE_PARAMETER, cur);- } else {- return ErrorType.VALUE;- }- } else if (- currentString === matchToken.COLON &&- this.isSingleQuotationClose() &&- this.isDoubleQuotationClose() &&- this.isBracesClose()- ) {- // const subLexerNode = new LexerNode();- // subLexerNode.token = currentString;- // this.setCurrentLexerNode(subLexerNode);- // this.newAndPushCurrentLexerNode(currentString);- // this._resetSegment();-- const subLexerNode_op = new LexerNode();- subLexerNode_op.setToken(currentString);-- const subLexerNode_left = new LexerNode();- subLexerNode_left.setToken(DEFAULT_TOKEN_TYPE_PARAMETER);- subLexerNode_left.setParent(subLexerNode_op);-- const subLexerNode_right = new LexerNode();- subLexerNode_right.setToken(DEFAULT_TOKEN_TYPE_PARAMETER);- subLexerNode_right.setParent(subLexerNode_op);-- subLexerNode_op.getChildren().push(subLexerNode_left, subLexerNode_right);-- let subLexerNode_main = subLexerNode_op;- let upLevel = 0;- if (this._segmentCount() > 0) {- // e.g. A1:B5- // -@A4:B5- let subLexerNode_minus: Nullable<LexerNode>;- let subLexerNode_at: Nullable<LexerNode>;- let sliceLength = 0;- const segmentTrim = this._segment.trim();- const lastString = segmentTrim[0];- const twoLastString = segmentTrim[1];-- // new RegExp(prefixToken.MINUS, 'g').test(this._segment)- if (lastString === prefixToken.MINUS) {- subLexerNode_minus = new LexerNode();- subLexerNode_minus.setToken(prefixToken.MINUS);- sliceLength++;- }-- // new RegExp(prefixToken.AT, 'g').test(this._segment)- if (lastString === prefixToken.AT || twoLastString === prefixToken.AT) {- subLexerNode_at = new LexerNode();- subLexerNode_at.setToken(prefixToken.AT);-- if (subLexerNode_minus) {- subLexerNode_minus.addChildren(subLexerNode_at);- subLexerNode_at.setParent(subLexerNode_minus);- }-- sliceLength++;- }-- if (sliceLength > 0) {- this._segment = segmentTrim.slice(sliceLength);- }-- upLevel = sliceLength;-- if (subLexerNode_at) {- subLexerNode_at.addChildren(subLexerNode_op);- subLexerNode_op.setParent(subLexerNode_at);- if (subLexerNode_at.getParent()) {- const node = subLexerNode_at.getParent();- if (node) {- subLexerNode_main = node;- }- } else {- subLexerNode_main = subLexerNode_at;- }- } else if (subLexerNode_minus) {- subLexerNode_main = subLexerNode_minus;- subLexerNode_minus.addChildren(subLexerNode_op);- subLexerNode_op.setParent(subLexerNode_minus);- }-- const subLexerNode_ref = new LexerNode();- subLexerNode_ref.setToken(this._segment);- subLexerNode_ref.setParent(subLexerNode_left);-- subLexerNode_left.getChildren().push(subLexerNode_ref);- this._resetSegment();- } else {- // e.g. indirect("A5"):B10- const lastChildNode = this._getLastChildCurrentLexerNode();- if (lastChildNode) {- lastChildNode.changeToParent(subLexerNode_left);- }- }-- this._setCurrentLexerNode(subLexerNode_main);- this._currentLexerNode = subLexerNode_right;- this._openColon(upLevel);- } else if (- SUFFIX_TOKEN_SET.has(currentString) &&- this.isSingleQuotationClose() &&- this.isDoubleQuotationClose()- ) {- this._pushNodeToChildren(this._segment);-- // this._pushNodeToChildren(currentString);-- const subLexerNode = new LexerNode();- subLexerNode.setToken(currentString);-- const lastChildNode = this._getLastChildCurrent();- if (lastChildNode instanceof LexerNode) {- lastChildNode.changeToParent(subLexerNode);- } else if (lastChildNode !== false) {- subLexerNode.getChildren().push(lastChildNode);- this._removeLastChild();- }-- this._pushNodeToChildren(subLexerNode);- subLexerNode.setParent(this._currentLexerNode);-- this._resetSegment();- } else if (- OPERATOR_TOKEN_SET.has(currentString) &&- this.isSingleQuotationClose() &&- this.isDoubleQuotationClose()- ) {- let trimSegment = this._segment.trim();-- if (currentString === operatorToken.MINUS && trimSegment === '') {- // negative number- const prevString = this._findPreviousToken(formulaStringArray, cur - 1) || '';- if (this._negativeCondition(prevString)) {- this._pushSegment(operatorToken.MINUS);-- sequenceArray?.push({- segment: this._segment,- currentString,- cur,- currentLexerNode: this._currentLexerNode,- });- cur++;- continue;- }- } else if (this._segment.length > 0 && trimSegment === '') {- trimSegment = this._segment;- } else {- this._pushNodeToChildren(this._segment);- trimSegment = '';- }-- if (currentString === operatorToken.LESS_THAN || currentString === operatorToken.GREATER_THAN) {- const nextCurrentString = formulaStringArray[cur + 1];- if (nextCurrentString && OPERATOR_TOKEN_SET.has(currentString + nextCurrentString)) {- this._pushNodeToChildren(trimSegment + currentString + nextCurrentString);- cur++;- } else {- this._pushNodeToChildren(trimSegment + currentString);- }- } else {- this._pushNodeToChildren(trimSegment + currentString);- }- this._resetSegment();} else {- this._pushSegment(currentString);+ sequenceString += token;}-- sequenceArray?.push({- segment: this._segment,- currentString,- cur,- currentLexerNode: this._currentLexerNode,- });- cur++;}- this._pushNodeToChildren(this._segment);+ return {+ sequenceString,+ hasDefinedName,+ };}}diff --git a/packages/engine-formula/src/engine/ast-node/reference-node.ts b/packages/engine-formula/src/engine/ast-node/reference-node.tsindex 92c430cd9b..b7141d38e0 100644--- a/packages/engine-formula/src/engine/ast-node/reference-node.ts+++ b/packages/engine-formula/src/engine/ast-node/reference-node.ts@@ -12,7 +12,7 @@ import { IFormulaCurrentConfigService } from '../../services/current-data.servicimport { IDefinedNamesService } from '../../services/defined-names.service';import { IFormulaRuntimeService } from '../../services/runtime.service';import { ISuperTableService } from '../../services/super-table.service';-import { LexerTreeBuilder } from '../analysis/lexer';+import { Lexer } from '../analysis/lexer';import { LexerNode } from '../analysis/lexer-node';import type { BaseReferenceObject } from '../reference-object/base-reference-object';import { CellReferenceObject } from '../reference-object/cell-reference-object';@@ -68,7 +68,8 @@ export class ReferenceNodeFactory extends BaseAstNodeFactory {constructor(@IDefinedNamesService private readonly _definedNamesService: IDefinedNamesService,@ISuperTableService private readonly _superTableService: ISuperTableService,- @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,+ @IFormulaRuntimeService private readonly _formulaRuntimeService: IFormulaRuntimeService,+ @Inject(Lexer) private readonly _lexer: Lexer,@Inject(Injector) private readonly _injector: Injector) {super();@@ -109,21 +110,22 @@ export class ReferenceNodeFactory extends BaseAstNodeFactory {return new ReferenceNode(this._injector, tokenTrim, new ColumnReferenceObject(tokenTrim));}- const nameMap = this._definedNamesService.getDefinedNameMap();+ const unitId = this._formulaRuntimeService.currentUnitId;+ const nameMap = this._definedNamesService.getDefinedNameMap(unitId);- if (!isLexerNode && nameMap.has(tokenTrim)) {+ if (!isLexerNode && nameMap?.has(tokenTrim)) {const nameString = nameMap.get(tokenTrim)!;- const lexerNode = this._lexerTreeBuilder.treeBuilder(nameString);+ const lexerNode = this._lexer.treeBuilder(nameString);/** todo */return new ErrorNode(ErrorType.VALUE);}// parserDataLoader.get- const tableMap = this._superTableService.getTableMap();+ const tableMap = this._superTableService.getTableMap(unitId);const $regex = $SUPER_TABLE_COLUMN_REGEX;const tableName = tokenTrim.replace($regex, '');- if (!isLexerNode && tableMap.has(tableName)) {+ if (!isLexerNode && tableMap?.has(tableName)) {const columnResult = $regex.exec(tokenTrim);let columnDataString = '';if (columnResult) {diff --git a/packages/engine-formula/src/engine/ast-node/suffix-node.ts b/packages/engine-formula/src/engine/ast-node/suffix-node.tsindex a422c64ecd..5a0e8b0783 100644--- a/packages/engine-formula/src/engine/ast-node/suffix-node.ts+++ b/packages/engine-formula/src/engine/ast-node/suffix-node.ts@@ -7,7 +7,7 @@ import type { BaseFunction } from '../../functions/base-function';import { FUNCTION_NAMES_META } from '../../functions/meta/function-names';import { IFormulaCurrentConfigService } from '../../services/current-data.service';import { IFunctionService } from '../../services/function.service';-import { LexerTreeBuilder } from '../analysis/lexer';+import { Lexer } from '../analysis/lexer';import { LexerNode } from '../analysis/lexer-node';import { ErrorValueObject } from '../other-object/error-value-object';import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';@@ -63,7 +63,7 @@ export class SuffixNode extends BaseAstNode {const currentConfigService = this._accessor.get(IFormulaCurrentConfigService);- const lexerTreeBuilder = this._accessor.get(LexerTreeBuilder);+ const lexer = this._accessor.get(Lexer);const cellValue = value as CellReferenceObject;const range = cellValue.getRangeData();@@ -77,7 +77,7 @@ export class SuffixNode extends BaseAstNode {return ErrorValueObject.create(ErrorType.VALUE);}- const lexerNode = lexerTreeBuilder.treeBuilder(formulaString);+ const lexerNode = lexer.treeBuilder(formulaString);return ErrorValueObject.create(ErrorType.VALUE);/** todo */diff --git a/packages/engine-formula/src/engine/dependency/formula-dependency.ts b/packages/engine-formula/src/engine/dependency/formula-dependency.tsindex bfc97110f1..1fd4929908 100644--- a/packages/engine-formula/src/engine/dependency/formula-dependency.ts+++ b/packages/engine-formula/src/engine/dependency/formula-dependency.ts@@ -7,13 +7,10 @@ import type { IDirtyUnitSheetNameMap, IFormulaData, IOtherFormulaData } from '..import { ErrorType } from '../../basics/error-type';import { prefixToken, suffixToken } from '../../basics/token';import { IFormulaCurrentConfigService } from '../../services/current-data.service';+import { IFeatureCalculationManagerService } from '../../services/feature-calculation-manager.service';import { IOtherFormulaManagerService } from '../../services/other-formula-manager.service';-import {- IPassiveDirtyManagerService,- type PassiveDirtyManagerService,-} from '../../services/passive-dirty-manager.service';import { IFormulaRuntimeService } from '../../services/runtime.service';-import { LexerTreeBuilder } from '../analysis/lexer';+import { Lexer } from '../analysis/lexer';import type { LexerNode } from '../analysis/lexer-node';import { AstTreeBuilder } from '../analysis/parser';import type { AstRootNode, FunctionNode, PrefixNode, SuffixNode } from '../ast-node';@@ -39,11 +36,11 @@ export class FormulaDependencyGenerator extends Disposable {@IFormulaCurrentConfigService private readonly _currentConfigService: IFormulaCurrentConfigService,@IFormulaRuntimeService private readonly _runtimeService: IFormulaRuntimeService,@IOtherFormulaManagerService private readonly _otherFormulaManagerService: IOtherFormulaManagerService,- @IPassiveDirtyManagerService- private readonly _passiveDirtyManagerService: PassiveDirtyManagerService,+ @IFeatureCalculationManagerService+ private readonly _featureCalculationManagerService: IFeatureCalculationManagerService,@Inject(Interpreter) private readonly _interpreter: Interpreter,@Inject(AstTreeBuilder) private readonly _astTreeBuilder: AstTreeBuilder,- @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder+ @Inject(Lexer) private readonly _lexer: Lexer) {super();}@@ -200,7 +197,7 @@ export class FormulaDependencyGenerator extends Disposable {* which can determine the execution timing of the external application* registration Executor based on the dependency relationship.*/- this._passiveDirtyManagerService.getReferenceExecutorMap().forEach((params, featureId) => {+ this._featureCalculationManagerService.getReferenceExecutorMap().forEach((params, featureId) => {const { unitId, subComponentId, dependencyRanges, getDirtyData } = params;const FDtree = new FormulaDependencyTree();@@ -265,7 +262,7 @@ export class FormulaDependencyGenerator extends Disposable {return astNode;}- const lexerNode = this._lexerTreeBuilder.treeBuilder(formulaString);+ const lexerNode = this._lexer.treeBuilder(formulaString);if ((lexerNode as ErrorType) in ErrorType) {return ErrorNode.create(lexerNode as ErrorType);diff --git a/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts b/packages/engine-formula/src/functions/__tests__/create-command-test-bed.tsindex 83652818f2..87be699d8d 100644--- a/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts+++ b/packages/engine-formula/src/functions/__tests__/create-command-test-bed.ts@@ -13,7 +13,7 @@ import type { Dependency } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';import type { ISheetData } from '../../basics/common';-import { LexerTreeBuilder } from '../../engine/analysis/lexer';+import { Lexer } from '../../engine/analysis/lexer';import { AstTreeBuilder } from '../../engine/analysis/parser';import { AstRootNodeFactory } from '../../engine/ast-node/ast-root-node';import { FunctionNodeFactory } from '../../engine/ast-node/function-node';@@ -79,7 +79,7 @@ export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencieoverride onStarting(injector: Injector): void {injector.add([CalculateFormulaService]);- injector.add([LexerTreeBuilder]);+ injector.add([Lexer]);injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);diff --git a/packages/engine-formula/src/index.ts b/packages/engine-formula/src/index.tsindex 5accedb448..7eea6ac206 100644--- a/packages/engine-formula/src/index.ts+++ b/packages/engine-formula/src/index.ts@@ -23,6 +23,11 @@ export {SetArrayFormulaDataMutation,SetArrayFormulaDataUndoMutationFactory,} from './commands/mutations/set-array-formula-data.mutation';+export { RemoveDefinedNameMutation, SetDefinedNameMutation } from './commands/mutations/set-defined-name.mutation';+export {+ RemoveFeatureCalculationMutation,+ SetFeatureCalculationMutation,+} from './commands/mutations/set-feature-calculation.mutation';export {type ISetFormulaCalculationNotificationMutation,type ISetFormulaCalculationResultMutation,@@ -36,8 +41,14 @@ export {type ISetFormulaDataMutationParams,SetFormulaDataMutation,} from './commands/mutations/set-formula-data.mutation';-export { LexerTreeBuilder } from './engine/analysis/lexer';+export { RemoveOtherFormulaMutation, SetOtherFormulaMutation } from './commands/mutations/set-other-formula.mutation';+export {+ RemoveSuperTableMutation,+ SetSuperTableMutation,+ SetSuperTableOptionMutation,+} from './commands/mutations/set-super-table.mutation';export { LexerNode } from './engine/analysis/lexer-node';+export { LexerTreeBuilder } from './engine/analysis/lexer-tree-builder';export { ErrorValueObject } from './engine/other-object/error-value-object';export { BaseReferenceObject, type FunctionVariantType } from './engine/reference-object/base-reference-object';export { RangeReferenceObject } from './engine/reference-object/range-reference-object';@@ -65,12 +76,14 @@ export { FUNCTION_NAMES_UNIVER } from './functions/univer/function-names';export { FUNCTION_NAMES_WEB } from './functions/web/function-names';export { FormulaDataModel } from './models/formula-data.model';export { initSheetFormulaData } from './models/formula-data.model';-export { BaseFormulaEnginePlugin } from './plugin';-export { IActiveDirtyManagerService } from './services/active-dirty-manager.service';+export { FormulaEnginePlugin } from './plugin';export { CalculateFormulaService } from './services/calculate-formula.service';+export {+ FeatureCalculationManagerService,+ IFeatureCalculationManagerService,+} from './services/feature-calculation-manager.service';export { FunctionService } from './services/function.service';export { IFunctionService } from './services/function.service';export { type IOtherFormulaManagerService, OtherFormulaManagerService } from './services/other-formula-manager.service';-export { IPassiveDirtyManagerService, PassiveDirtyManagerService } from './services/passive-dirty-manager.service';export { FormulaExecuteStageType, type IExecutionInProgressParams } from './services/runtime.service';export { FormulaExecutedStateType, type IAllRuntimeData } from './services/runtime.service';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 85a4fdc1ba..a050ad7e3c 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@@ -3,8 +3,11 @@ import { ILogService, IUniverInstanceService, LocaleType, LogLevel, Plugin, Plugimport type { Dependency } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';-import { LexerTreeBuilder } from '../../engine/analysis/lexer';+import { LexerTreeBuilder } from '../../engine/analysis/lexer-tree-builder';import { CalculateFormulaService } from '../../services/calculate-formula.service';+import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from '../../services/current-data.service';+import { DefinedNamesService, IDefinedNamesService } from '../../services/defined-names.service';+import { FormulaRuntimeService, IFormulaRuntimeService } from '../../services/runtime.service';import { FormulaDataModel } from '../formula-data.model';const TEST_WORKBOOK_DATA: IWorkbookData = {@@ -55,6 +58,10 @@ export function createCommandTestBed(workbookConfig?: IWorkbookData, dependencieinjector.add([CalculateFormulaService]);injector.add([FormulaDataModel]);injector.add([LexerTreeBuilder]);+ injector.add([IDefinedNamesService, { useClass: DefinedNamesService }]);+ injector.add([IFormulaRuntimeService, { useClass: FormulaRuntimeService }]);+ injector.add([IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }]);+dependencies?.forEach((d) => injector.add(d));}diff --git a/packages/engine-formula/src/models/formula-data.model.ts b/packages/engine-formula/src/models/formula-data.model.tsindex 4aa456fd46..2a8ba16a58 100644--- a/packages/engine-formula/src/models/formula-data.model.ts+++ b/packages/engine-formula/src/models/formula-data.model.ts@@ -12,7 +12,7 @@ import type {IUnitData,IUnitSheetNameMap,} from '../basics/common';-import { LexerTreeBuilder } from '../engine/analysis/lexer';+import { LexerTreeBuilder } from '../engine/analysis/lexer-tree-builder';export interface IFormulaIdMap {f: string;diff --git a/packages/engine-formula/src/plugin.ts b/packages/engine-formula/src/plugin.tsindex c42c0472cc..e8532a19ad 100644--- a/packages/engine-formula/src/plugin.ts+++ b/packages/engine-formula/src/plugin.ts@@ -4,7 +4,12 @@ import { Inject, Injector } from '@wendellhu/redi';import { CalculateController } from './controller/calculate.controller';import { FormulaController } from './controller/formula.controller';-import { LexerTreeBuilder } from './engine/analysis/lexer';+import { SetDefinedNameController } from './controller/set-defined-name.controller';+import { SetFeatureCalculationController } from './controller/set-feature-calculation.controller';+import { SetOtherFormulaController } from './controller/set-other-formula.controller';+import { SetSuperTableController } from './controller/set-super-table.controller';+import { Lexer } from './engine/analysis/lexer';+import { LexerTreeBuilder } from './engine/analysis/lexer-tree-builder';import { AstTreeBuilder } from './engine/analysis/parser';import { AstRootNodeFactory } from './engine/ast-node/ast-root-node';import { FunctionNodeFactory } from './engine/ast-node/function-node';@@ -19,25 +24,27 @@ import { ValueNodeFactory } from './engine/ast-node/value-node';import { FormulaDependencyGenerator } from './engine/dependency/formula-dependency';import { Interpreter } from './engine/interpreter/interpreter';import { FormulaDataModel } from './models/formula-data.model';-import { ActiveDirtyManagerService, IActiveDirtyManagerService } from './services/active-dirty-manager.service';import { CalculateFormulaService } from './services/calculate-formula.service';import { FormulaCurrentConfigService, IFormulaCurrentConfigService } from './services/current-data.service';import { DefinedNamesService, IDefinedNamesService } from './services/defined-names.service';+import {+ FeatureCalculationManagerService,+ IFeatureCalculationManagerService,+} from './services/feature-calculation-manager.service';import { FunctionService, IFunctionService } from './services/function.service';import { IOtherFormulaManagerService, OtherFormulaManagerService } from './services/other-formula-manager.service';-import { IPassiveDirtyManagerService, PassiveDirtyManagerService } from './services/passive-dirty-manager.service';import { FormulaRuntimeService, IFormulaRuntimeService } from './services/runtime.service';import { ISuperTableService, SuperTableService } from './services/super-table.service';const PLUGIN_NAME = 'base-formula-engine';-interface IBaseFormulaEnginePlugin {+interface IFormulaEnginePlugin {notExecuteFormula?: boolean;}-export class BaseFormulaEnginePlugin extends Plugin {+export class FormulaEnginePlugin extends Plugin {constructor(- private _config: IBaseFormulaEnginePlugin,+ private _config: IFormulaEnginePlugin,@Inject(Injector) protected override _injector: Injector) {super(PLUGIN_NAME);@@ -48,18 +55,22 @@ export class BaseFormulaEnginePlugin extends Plugin {}private _initialize() {- // this._formulaDataModel = this._injector.createInstance(FormulaDataModel);-+ // worker and main threadconst dependencies: Dependency[] = [// Services- [LexerTreeBuilder],[IFunctionService, { useClass: FunctionService }],- [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],+ [IFeatureCalculationManagerService, { useClass: FeatureCalculationManagerService }],+ [IDefinedNamesService, { useClass: DefinedNamesService }],+// Models[FormulaDataModel],+ // Engine+ [LexerTreeBuilder],+//Controllers[FormulaController],+ [SetFeatureCalculationController],];if (!this._config?.notExecuteFormula) {@@ -67,18 +78,22 @@ export class BaseFormulaEnginePlugin extends Plugin {dependencies.push(// Services[CalculateFormulaService],- [CalculateController],- [IPassiveDirtyManagerService, { useClass: PassiveDirtyManagerService }],[IOtherFormulaManagerService, { useClass: OtherFormulaManagerService }],[ISuperTableService, { useClass: SuperTableService }],- [IDefinedNamesService, { useClass: DefinedNamesService }],[IFormulaCurrentConfigService, { useClass: FormulaCurrentConfigService }],[IFormulaRuntimeService, { useClass: FormulaRuntimeService }],+ //Controller+ [CalculateController],+ [SetDefinedNameController],+ [SetOtherFormulaController],+ [SetSuperTableController],+// Calculation engine[FormulaDependencyGenerator],[Interpreter],[AstTreeBuilder],+ [Lexer],// AstNode factory[AstRootNodeFactory],diff --git a/packages/engine-formula/src/services/calculate-formula.service.ts b/packages/engine-formula/src/services/calculate-formula.service.tsindex 8cab32eb61..2ef363f40f 100644--- a/packages/engine-formula/src/services/calculate-formula.service.ts+++ b/packages/engine-formula/src/services/calculate-formula.service.ts@@ -18,7 +18,7 @@ import type {IUnitExcludedCell,} from '../basics/common';import { ErrorType } from '../basics/error-type';-import { LexerTreeBuilder } from '../engine/analysis/lexer';+import { Lexer } from '../engine/analysis/lexer';import type { LexerNode } from '../engine/analysis/lexer-node';import { AstTreeBuilder } from '../engine/analysis/parser';import { ErrorNode } from '../engine/ast-node/base-ast-node';@@ -51,7 +51,7 @@ export class CalculateFormulaService extends Disposable {constructor(@IConfigService private readonly _configService: IConfigService,- @Inject(LexerTreeBuilder) private readonly _lexerTreeBuilder: LexerTreeBuilder,+ @Inject(Lexer) private readonly _lexer: Lexer,@IFormulaCurrentConfigService private readonly _currentConfigService: IFormulaCurrentConfigService,@IFormulaRuntimeService private readonly _runtimeService: IFormulaRuntimeService,@Inject(FormulaDependencyGenerator) private readonly _formulaDependencyGenerator: FormulaDependencyGenerator,@@ -85,15 +85,6 @@ export class CalculateFormulaService extends Disposable {this._runtimeService.setRuntimeFeatureRange(featureId, featureRange);}- /**- *- * @param unitId- * @param formulaData- * @param interpreterDatasetConfig- * @param forceCalculate force calculate all formula, and ignore dependency relationship- * @param dirtyRanges input external unit data for multi workbook- * @returns- */async execute(formulaDatasetConfig: IFormulaDatasetConfig) {this._executionStartListener$.next(true);@@ -299,7 +290,7 @@ export class CalculateFormulaService extends Disposable {calculate(formulaString: string, transformSuffix: boolean = true) {// TODO how to observe @alex// this.getObserver('onBeforeFormulaCalculateObservable')?.notifyObservers(formulaString);- const lexerNode = this._lexerTreeBuilder.treeBuilder(formulaString, transformSuffix);+ const lexerNode = this._lexer.treeBuilder(formulaString, transformSuffix);if (Object.values(ErrorType).includes(lexerNode as ErrorType)) {return ErrorNode.create(lexerNode as ErrorType);diff --git a/packages/engine-formula/src/services/defined-names.service.ts b/packages/engine-formula/src/services/defined-names.service.tsindex 85b78c607a..14187d7aaa 100644--- a/packages/engine-formula/src/services/defined-names.service.ts+++ b/packages/engine-formula/src/services/defined-names.service.ts@@ -1,26 +1,52 @@+import type { Nullable } from '@univerjs/core';import { Disposable } from '@univerjs/core';import { createIdentifier } from '@wendellhu/redi';export interface IDefinedNamesService {- registerDefinedName(name: string, reference: string): void;+ registerDefinedName(unitId: string, name: string, formulaOrRefString: string): void;- getDefinedNameMap(): Map<string, string>;+ getDefinedNameMap(unitId: string): Nullable<Map<string, string>>;++ getValue(unitId: string, name: string): Nullable<string>;++ removeDefinedName(unitId: string, name: string): void;++ hasDefinedName(unitId: string): boolean;}export class DefinedNamesService extends Disposable implements IDefinedNamesService {// 18.2.6 definedNames (Defined Names)- private _definedNameMap: Map<string, string> = new Map();+ private _definedNameMap: Map<string, Map<string, string>> = new Map();override dispose(): void {this._definedNameMap.clear();}- registerDefinedName(name: string, reference: string) {- this._definedNameMap.set(name, reference);+ registerDefinedName(unitId: string, name: string, formulaOrRefString: string) {+ const unitMap = this._definedNameMap.get(unitId);++ if (unitMap == null) {+ this._definedNameMap.set(unitId, new Map());+ }++ this._definedNameMap.get(unitId)?.set(name, formulaOrRefString);+ }++ removeDefinedName(unitId: string, name: string) {+ this._definedNameMap.get(unitId)?.delete(name);+ }++ getDefinedNameMap(unitId: string) {+ return this._definedNameMap.get(unitId);+ }++ getValue(unitId: string, name: string) {+ return this._definedNameMap.get(unitId)?.get(name);}- getDefinedNameMap() {- return this._definedNameMap;+ hasDefinedName(unitId: string) {+ const size = this._definedNameMap.get(unitId)?.size || 0;+ return size !== 0;}}diff --git a/packages/engine-formula/src/services/passive-dirty-manager.service.ts b/packages/engine-formula/src/services/feature-calculation-manager.service.tssimilarity index 65%rename from packages/engine-formula/src/services/passive-dirty-manager.service.tsrename to packages/engine-formula/src/services/feature-calculation-manager.service.tsindex b006e72a4c..9d3f9eb96f 100644--- a/packages/engine-formula/src/services/passive-dirty-manager.service.ts+++ b/packages/engine-formula/src/services/feature-calculation-manager.service.ts@@ -5,7 +5,7 @@ import { createIdentifier } from '@wendellhu/redi';import type { IFeatureDirtyRangeType, IRuntimeUnitDataType } from '../basics/common';import type { FormulaDependencyTree } from '../engine/dependency/dependency-tree';-export interface IReferenceExecutorManagerParams {+export interface IFeatureCalculationManagerParam {unitId: string;subComponentId: string;dependencyRanges: IUnitRange[];@@ -15,18 +15,18 @@ export interface IReferenceExecutorManagerParams {};}-export interface IPassiveDirtyManagerService {+export interface IFeatureCalculationManagerService {dispose(): void;remove(featureId: string): void;- get(featureId: string): Nullable<IReferenceExecutorManagerParams>;+ get(featureId: string): Nullable<IFeatureCalculationManagerParam>;has(featureId: string): boolean;- register(featureId: string, referenceExecutor: IReferenceExecutorManagerParams): void;+ register(featureId: string, referenceExecutor: IFeatureCalculationManagerParam): void;- getReferenceExecutorMap(): Map<string, IReferenceExecutorManagerParams>;+ getReferenceExecutorMap(): Map<string, IFeatureCalculationManagerParam>;}/**@@ -35,8 +35,8 @@ export interface IPassiveDirtyManagerService {* causing the formula to be marked dirty again,* thereby completing the calculation of the entire dependency tree.*/-export class PassiveDirtyManagerService extends Disposable implements IPassiveDirtyManagerService {- private _referenceExecutorMap: Map<string, IReferenceExecutorManagerParams> = new Map();+export class FeatureCalculationManagerService extends Disposable implements IFeatureCalculationManagerService {+ private _referenceExecutorMap: Map<string, IFeatureCalculationManagerParam> = new Map();override dispose(): void {this._referenceExecutorMap.clear();@@ -54,7 +54,7 @@ export class PassiveDirtyManagerService extends Disposable implements IPassiveDireturn this._referenceExecutorMap.has(featureId);}- register(featureId: string, referenceExecutor: IReferenceExecutorManagerParams) {+ register(featureId: string, referenceExecutor: IFeatureCalculationManagerParam) {this._referenceExecutorMap.set(featureId, referenceExecutor);}@@ -63,6 +63,6 @@ export class PassiveDirtyManagerService extends Disposable implements IPassiveDi}}-export const IPassiveDirtyManagerService = createIdentifier<PassiveDirtyManagerService>(- 'univer.formula.passive-dirty-manager.service'+export const IFeatureCalculationManagerService = createIdentifier<FeatureCalculationManagerService>(+ 'univer.formula.feature-calculation-manager.service');diff --git a/packages/engine-formula/src/services/super-table.service.ts b/packages/engine-formula/src/services/super-table.service.tsindex bd6ddb8a2e..744d504d4e 100644--- a/packages/engine-formula/src/services/super-table.service.ts+++ b/packages/engine-formula/src/services/super-table.service.ts@@ -1,21 +1,29 @@+import type { Nullable } from '@univerjs/core';import { Disposable } from '@univerjs/core';import { createIdentifier } from '@wendellhu/redi';import type { ISuperTable, TableOptionType } from '../basics/common';+export interface ISuperTableOptionParam {+ tableOption: string;+ tableOptionType: TableOptionType;+}+export interface ISuperTableService {- getTableMap(): Map<string, ISuperTable>;+ getTableMap(unitId: string): Nullable<Map<string, ISuperTable>>;getTableOptionMap(): Map<string, TableOptionType>;- registerTable(tableName: string, reference: ISuperTable): void;+ registerTable(unitId: string, tableName: string, reference: ISuperTable): void;registerTableOptionMap(tableOption: string, tableOptionType: TableOptionType): void;++ remove(unitId: string, tableName: string): void;}export class SuperTableService extends Disposable implements ISuperTableService {// 18.5.1.2 table (Table)- private _tableMap: Map<string, ISuperTable> = new Map();+ private _tableMap: Map<string, Map<string, ISuperTable>> = new Map();// 18.5.1.2 table (Table) for I18Nprivate _tableOptionMap: Map<string, TableOptionType> = new Map();@@ -26,16 +34,23 @@ export class SuperTableService extends Disposable implements ISuperTableServicethis._tableOptionMap.clear();}- getTableMap() {- return this._tableMap;+ remove(unitId: string, tableName: string) {+ this._tableMap.get(unitId)?.delete(tableName);+ }++ getTableMap(unitId: string) {+ return this._tableMap.get(unitId);}getTableOptionMap() {return this._tableOptionMap;}- registerTable(tableName: string, reference: ISuperTable) {- this._tableMap.set(tableName, reference);+ registerTable(unitId: string, tableName: string, reference: ISuperTable) {+ if (this._tableMap.get(unitId) == null) {+ this._tableMap.set(unitId, new Map());+ }+ this._tableMap.get(unitId)?.set(tableName, reference);}registerTableOptionMap(tableOption: string, tableOptionType: TableOptionType) {diff --git a/packages/engine-render/src/components/docs/text-selection-render-manager.ts b/packages/engine-render/src/components/docs/text-selection-render-manager.tsindex a41e2197b8..bcfc3987ee 100644--- a/packages/engine-render/src/components/docs/text-selection-render-manager.ts+++ b/packages/engine-render/src/components/docs/text-selection-render-manager.ts@@ -373,7 +373,9 @@ export class TextSelectionRenderManager extends RxDisposable implements ITextSelthis._cursor.style.animation = 'univer_cursor_blinkStyle 1s steps(1) infinite';this._cursor.style.display = 'revert';- requestAnimationFrame(() => this.focus());+ this.focus();++ // requestAnimationFrame(() => this.focus());}focus(): void {diff --git a/packages/sheets/src/controllers/active-dirty.controller.ts b/packages/sheets-formula/src/controllers/active-dirty.controller.tssimilarity index 92%rename from packages/sheets/src/controllers/active-dirty.controller.tsrename to packages/sheets-formula/src/controllers/active-dirty.controller.tsindex 2fe03c393e..a4515ef554 100644--- a/packages/sheets/src/controllers/active-dirty.controller.ts+++ b/packages/sheets-formula/src/controllers/active-dirty.controller.ts@@ -8,32 +8,35 @@ import {OnLifecycle,} from '@univerjs/core';import type { IDirtyUnitSheetNameMap } from '@univerjs/engine-formula';-import { FormulaDataModel, IActiveDirtyManagerService } from '@univerjs/engine-formula';-import { Inject } from '@wendellhu/redi';-+import { FormulaDataModel } from '@univerjs/engine-formula';import type {IDeleteRangeMutationParams,IInsertRangeMutationParams,IInsertSheetMutationParams,+ IMoveColumnsMutationParams,+ IMoveRangeMutationParams,+ IMoveRowsMutationParams,IRemoveColMutationParams,IRemoveRowsMutationParams,IRemoveSheetMutationParams,-} from '../basics/interfaces/mutation-interface';-import { SetStyleCommand } from '../commands/commands/set-style.command';-import { DeleteRangeMutation } from '../commands/mutations/delete-range.mutation';-import { InsertRangeMutation } from '../commands/mutations/insert-range.mutation';-import { InsertSheetMutation } from '../commands/mutations/insert-sheet.mutation';-import type { IMoveRangeMutationParams } from '../commands/mutations/move-range.mutation';-import { MoveRangeMutation } from '../commands/mutations/move-range.mutation';-import type {- IMoveColumnsMutationParams,- IMoveRowsMutationParams,-} from '../commands/mutations/move-rows-cols.mutation';-import { MoveColsMutation, MoveRowsMutation } from '../commands/mutations/move-rows-cols.mutation';-import { RemoveColMutation, RemoveRowMutation } from '../commands/mutations/remove-row-col.mutation';-import { RemoveSheetMutation } from '../commands/mutations/remove-sheet.mutation';-import type { ISetRangeValuesMutationParams } from '../commands/mutations/set-range-values.mutation';-import { SetRangeValuesMutation } from '../commands/mutations/set-range-values.mutation';+ ISetRangeValuesMutationParams,+} from '@univerjs/sheets';+import {+ DeleteRangeMutation,+ InsertRangeMutation,+ InsertSheetMutation,+ MoveColsMutation,+ MoveRangeMutation,+ MoveRowsMutation,+ RemoveColMutation,+ RemoveRowMutation,+ RemoveSheetMutation,+ SetRangeValuesMutation,+ SetStyleCommand,+} from '@univerjs/sheets';+import { Inject } from '@wendellhu/redi';++import { IActiveDirtyManagerService } from '../services/active-dirty-manager.service';@OnLifecycle(LifecycleStages.Ready, ActiveDirtyController)export class ActiveDirtyController extends Disposable {diff --git a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts b/packages/sheets-formula/src/controllers/formula-editor-show.controller.tsindex ec1c494d58..000b6605e8 100644--- a/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts+++ b/packages/sheets-formula/src/controllers/formula-editor-show.controller.ts@@ -53,12 +53,7 @@ export class FormulaEditorShowController extends Disposable {this._removeArrayFormulaRangeShape();- if (- value == null ||- (value.v != null &&- value.v !== '' &&- arrayFormulaMatrixCell[workbookId]?.[worksheetId]?.[row]?.[col] == null)- ) {+ if (value == null) {return next(value);}@@ -102,6 +97,24 @@ export class FormulaEditorShowController extends Disposable {}}+ /**+ * If the display conditions for the array formula are not met, return the range directly.+ */+ if (+ value.v != null &&+ value.v !== '' &&+ arrayFormulaMatrixCell[workbookId]?.[worksheetId]?.[row]?.[col] == null+ ) {+ if (cellInfo) {+ return cellInfo;+ }++ return next(value);+ }++ /**+ * Mark the array formula for special display in subsequent processing+ */const matrixRange = arrayFormulaMatrixRange?.[workbookId]?.[worksheetId];if (matrixRange != null) {new ObjectMatrix(matrixRange).forValue((rowIndex, columnIndex, range) => {diff --git a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts b/packages/sheets-formula/src/controllers/trigger-calculation.controller.tsindex 18eb120d09..d4a9020bd7 100644--- a/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts+++ b/packages/sheets-formula/src/controllers/trigger-calculation.controller.ts@@ -1,15 +1,20 @@-import type { ICommandInfo } from '@univerjs/core';+import type { ICommandInfo, IUnitRange } from '@univerjs/core';import { Disposable, ICommandService, LifecycleStages, OnLifecycle } from '@univerjs/core';-import type { ISetFormulaCalculationNotificationMutation } from '@univerjs/engine-formula';+import type {+ IDirtyUnitFeatureMap,+ IDirtyUnitSheetNameMap,+ ISetFormulaCalculationNotificationMutation,+} from '@univerjs/engine-formula';import {FormulaExecutedStateType,- IActiveDirtyManagerService,SetFormulaCalculationNotificationMutation,SetFormulaCalculationStartMutation,} from '@univerjs/engine-formula';import type { ISetRangeValuesMutationParams } from '@univerjs/sheets';import { SetRangeValuesMutation, SetStyleCommand } from '@univerjs/sheets';+import { IActiveDirtyManagerService } from '../services/active-dirty-manager.service';+@OnLifecycle(LifecycleStages.Ready, TriggerCalculationController)export class TriggerCalculationController extends Disposable {private _waitingCommandQueue: ICommandInfo[] = [];@@ -72,7 +77,7 @@ export class TriggerCalculationController extends Disposable {this._commandService.executeCommand(SetFormulaCalculationStartMutation.id,{- commands: this._waitingCommandQueue,+ ...this._generateDirty(this._waitingCommandQueue),},{local: true,@@ -85,6 +90,73 @@ export class TriggerCalculationController extends Disposable {);}+ private _generateDirty(commands: ICommandInfo[]) {+ const allDirtyRanges: IUnitRange[] = [];+ const allDirtyNameMap: IDirtyUnitSheetNameMap = {};+ const allDirtyUnitFeatureMap: IDirtyUnitFeatureMap = {};++ for (const command of commands) {+ const conversion = this._activeDirtyManagerService.get(command.id);++ if (conversion == null) {+ continue;+ }++ const params = conversion.getDirtyData(command);++ const { dirtyRanges, dirtyNameMap, dirtyUnitFeatureMap } = params;++ if (dirtyRanges != null) {+ allDirtyRanges.push(...dirtyRanges);+ }++ if (dirtyNameMap != null) {+ this._mergeDirtyNameMap(allDirtyNameMap, dirtyNameMap);+ }++ if (dirtyUnitFeatureMap != null) {+ this._mergeDirtyUnitFeatureMap(allDirtyUnitFeatureMap, dirtyUnitFeatureMap);+ }+ }++ return {+ dirtyRanges: allDirtyRanges,+ dirtyNameMap: allDirtyNameMap,+ dirtyUnitFeatureMap: allDirtyUnitFeatureMap,+ };+ }++ private _mergeDirtyNameMap(allDirtyNameMap: IDirtyUnitSheetNameMap, dirtyNameMap: IDirtyUnitSheetNameMap) {+ Object.keys(dirtyNameMap).forEach((unitId) => {+ if (allDirtyNameMap[unitId] == null) {+ allDirtyNameMap[unitId] = {};+ }+ Object.keys(dirtyNameMap[unitId]).forEach((sheetId) => {+ allDirtyNameMap[unitId][sheetId] = dirtyNameMap[unitId][sheetId];+ });+ });+ }++ private _mergeDirtyUnitFeatureMap(+ allDirtyUnitFeatureMap: IDirtyUnitFeatureMap,+ dirtyUnitFeatureMap: IDirtyUnitFeatureMap+ ) {+ Object.keys(dirtyUnitFeatureMap).forEach((unitId) => {+ if (allDirtyUnitFeatureMap[unitId] == null) {+ allDirtyUnitFeatureMap[unitId] = {};+ }+ Object.keys(dirtyUnitFeatureMap[unitId]).forEach((sheetId) => {+ if (allDirtyUnitFeatureMap[unitId][sheetId] == null) {+ allDirtyUnitFeatureMap[unitId][sheetId] = {};+ }+ Object.keys(dirtyUnitFeatureMap[unitId][sheetId]).forEach((featureId) => {+ allDirtyUnitFeatureMap[unitId][sheetId][featureId] =+ dirtyUnitFeatureMap[unitId][sheetId][featureId];+ });+ });+ });+ }+private _initialExecuteFormulaProcessListener() {/*** Assignment operation after formula calculation.diff --git a/packages/sheets-formula/src/formula-ui-plugin.ts b/packages/sheets-formula/src/formula-ui-plugin.tsindex 1ed4316cc9..03dd8c7c0e 100644--- a/packages/sheets-formula/src/formula-ui-plugin.ts+++ b/packages/sheets-formula/src/formula-ui-plugin.ts@@ -4,6 +4,7 @@ import type { Dependency } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';import { FORMULA_UI_PLUGIN_NAME } from './common/plugin-name';+import { ActiveDirtyController } from './controllers/active-dirty.controller';import { ArrayFormulaDisplayController } from './controllers/array-formula-display.controller';import { FormulaAutoFillController } from './controllers/formula-auto-fill.controller';import { FormulaClipboardController } from './controllers/formula-clipboard.controller';@@ -14,6 +15,7 @@ import { PromptController } from './controllers/prompt.controller';import { TriggerCalculationController } from './controllers/trigger-calculation.controller';import { UpdateFormulaController } from './controllers/update-formula.controller';import { zhCN } from './locale';+import { ActiveDirtyManagerService, IActiveDirtyManagerService } from './services/active-dirty-manager.service';import { DescriptionService, IDescriptionService } from './services/description.service';import { FormulaInputService, IFormulaInputService } from './services/formula-input.service';import { FormulaPromptService, IFormulaPromptService } from './services/prompt.service';@@ -50,6 +52,7 @@ export class FormulaUIPlugin extends Plugin {this._injector.createInstance(DescriptionService, this._config?.description || []), // TODO@Dusuhir: initialize config with asynchronous method?},],+ [IActiveDirtyManagerService, { useClass: ActiveDirtyManagerService }],// controllers[FormulaUIController],[PromptController],@@ -60,6 +63,7 @@ export class FormulaUIPlugin extends Plugin {[TriggerCalculationController],[UpdateFormulaController],[FormulaEditorShowController],+ [ActiveDirtyController],];dependencies.forEach((dependency) => this._injector.add(dependency));diff --git a/packages/engine-formula/src/services/active-dirty-manager.service.ts b/packages/sheets-formula/src/services/active-dirty-manager.service.tssimilarity index 98%rename from packages/engine-formula/src/services/active-dirty-manager.service.tsrename to packages/sheets-formula/src/services/active-dirty-manager.service.tsindex c7d3fa3f52..6780403a23 100644--- a/packages/engine-formula/src/services/active-dirty-manager.service.ts+++ b/packages/sheets-formula/src/services/active-dirty-manager.service.ts@@ -1,9 +1,8 @@import type { ICommandInfo, IUnitRange, Nullable } from '@univerjs/core';import { Disposable } from '@univerjs/core';+import type { IDirtyUnitFeatureMap, IDirtyUnitSheetNameMap } from '@univerjs/engine-formula';import { createIdentifier } from '@wendellhu/redi';-import type { IDirtyUnitFeatureMap, IDirtyUnitSheetNameMap } from '../basics/common';-export interface IDirtyConversionManagerParams {commandId: string;getDirtyData: (command: ICommandInfo) => {diff --git a/packages/sheets/src/controllers/passive-dirty.controller.ts b/packages/sheets/src/controllers/feature-calculation.controller.tssimilarity index 79%rename from packages/sheets/src/controllers/passive-dirty.controller.tsrename to packages/sheets/src/controllers/feature-calculation.controller.tsindex de7130d35d..ac832544ef 100644--- a/packages/sheets/src/controllers/passive-dirty.controller.ts+++ b/packages/sheets/src/controllers/feature-calculation.controller.ts@@ -6,16 +6,15 @@ import {ObjectMatrix,OnLifecycle,} from '@univerjs/core';-import { FormulaDataModel, IActiveDirtyManagerService, IPassiveDirtyManagerService } from '@univerjs/engine-formula';+import { FormulaDataModel, IFeatureCalculationManagerService } from '@univerjs/engine-formula';import { Inject } from '@wendellhu/redi';-@OnLifecycle(LifecycleStages.Ready, PassiveDirtyController)-export class PassiveDirtyController extends Disposable {+@OnLifecycle(LifecycleStages.Ready, FeatureCalculationController)+export class FeatureCalculationController extends Disposable {constructor(@ICommandService private readonly _commandService: ICommandService,- @IPassiveDirtyManagerService- private readonly _passiveDirtyManagerService: IPassiveDirtyManagerService,- @IActiveDirtyManagerService private readonly _activeDirtyManagerService: IActiveDirtyManagerService,+ @IFeatureCalculationManagerService+ private readonly _featureCalculationManagerService: IFeatureCalculationManagerService,@IUniverInstanceService private readonly _currentUniverService: IUniverInstanceService,@Inject(FormulaDataModel) private readonly _formulaDataModel: FormulaDataModel) {@@ -57,7 +56,7 @@ export class PassiveDirtyController extends Disposable {},};- this._passiveDirtyManagerService.register(featureId, {+ this._featureCalculationManagerService.register(featureId, {unitId,subComponentId,dependencyRanges: [diff --git a/packages/sheets/src/sheets-plugin.ts b/packages/sheets/src/sheets-plugin.tsindex c84dd4d549..37b53131ac 100644--- a/packages/sheets/src/sheets-plugin.ts+++ b/packages/sheets/src/sheets-plugin.ts@@ -2,11 +2,10 @@ import { ICommandService, LocaleService, Plugin, PluginType } from '@univerjs/coimport type { Dependency } from '@wendellhu/redi';import { Inject, Injector } from '@wendellhu/redi';-import { ActiveDirtyController } from './controllers/active-dirty.controller';import { BasicWorksheetController } from './controllers/basic-worksheet.controller';import { CalculateResultApplyController } from './controllers/calculate-result-apply.controller';+import { FeatureCalculationController } from './controllers/feature-calculation.controller';import { MergeCellController } from './controllers/merge-cell.controller';-import { PassiveDirtyController } from './controllers/passive-dirty.controller';import { zhCN } from './locale';import { BorderStyleManagerService } from './services/border-style-manager.service';import { NumfmtService } from './services/numfmt/numfmt.service';@@ -58,11 +57,10 @@ export class SheetsPlugin extends Plugin {// controllers[BasicWorksheetController],[MergeCellController],- [ActiveDirtyController],];if (!this._config?.notExecuteFormula) {- dependencies.push([CalculateResultApplyController], [PassiveDirtyController]);+ dependencies.push([CalculateResultApplyController], [FeatureCalculationController]);}dependencies.forEach((d) => {