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): support cycle Lambda and Let (#427)
Univer92b1e2c90a4c
diff --git a/packages/base-formula-engine/src/analysis/lexer-node.ts b/packages/base-formula-engine/src/analysis/lexer-node.tsindex 5a92892476..ce7ac0d6a9 100644--- a/packages/base-formula-engine/src/analysis/lexer-node.ts+++ b/packages/base-formula-engine/src/analysis/lexer-node.ts@@ -22,17 +22,21 @@ export class LexerNode {private _lambdaId: Nullable<string>;- private _lambdaPrivacyVar: Nullable<LambdaPrivacyVarType>;+ private _functionDefinitionPrivacyVar: Nullable<LambdaPrivacyVarType>;private _lambdaParameter: string = '';+ private _startIndex: number = -1;++ private _endIndex: number = -1;+dispose() {this._children.forEach((node) => {if (!(typeof node === 'string')) {node.dispose();}});- this._lambdaPrivacyVar?.clear();+ this._functionDefinitionPrivacyVar?.clear();this._parent = null;}@@ -45,12 +49,12 @@ export class LexerNode {this._lambdaId = lambdaId;}- getLambdaPrivacyVar() {- return this._lambdaPrivacyVar;+ getFunctionDefinitionPrivacyVar() {+ return this._functionDefinitionPrivacyVar;}setLambdaPrivacyVar(lambdaPrivacyVar: LambdaPrivacyVarType) {- this._lambdaPrivacyVar = lambdaPrivacyVar;+ this._functionDefinitionPrivacyVar = lambdaPrivacyVar;}getLambdaParameter() {@@ -81,6 +85,10 @@ export class LexerNode {this._children.push(children);}+ addChildrenFirst(children: LexerNode | string) {+ this._children.unshift(children);+ }+getToken() {return this._token;}@@ -89,6 +97,23 @@ export class LexerNode {this._token = token;}+ setIndex(st: number, ed: number) {+ this._startIndex = st;+ this._endIndex = ed;+ }++ replaceChild(lexerNode: LexerNode, newLexerNode: LexerNode) {+ const i = this._getIndexInParent(lexerNode);++ if (i == null) {+ return;+ }++ this.getChildren().splice(i, 1, newLexerNode);++ newLexerNode.setParent(this);+ }+changeToParent(newParentLexerNode: LexerNode) {const parentNode = this.getParent();if (parentNode) {@@ -100,15 +125,21 @@ export class LexerNode {}removeChild(lexerNode: LexerNode) {- const childrenNode = this.getChildren();- const childrenCount = childrenNode.length;- for (let i = 0; i < childrenCount; i++) {- const child = childrenNode[i];- if (child === lexerNode) {- childrenNode.splice(i, 1);- return;- }+ const i = this._getIndexInParent(lexerNode);++ if (i == null) {+ return;}++ this.getChildren().splice(i, 1);+ // const childrenCount = childrenNode.length;+ // for (let i = 0; i < childrenCount; i++) {+ // const child = childrenNode[i];+ // if (child === lexerNode) {+ // childrenNode.splice(i, 1);+ // return;+ // }+ // }}serialize() {@@ -127,7 +158,20 @@ export class LexerNode {}return {token,+ st: this._startIndex,+ ed: this._endIndex,children: childrenSerialization,};}++ private _getIndexInParent(lexerNode: LexerNode) {+ const childrenNode = this.getChildren();+ const childrenCount = childrenNode.length;+ for (let i = 0; i < childrenCount; i++) {+ const child = childrenNode[i];+ if (child === lexerNode) {+ return i;+ }+ }+ }}diff --git a/packages/base-formula-engine/src/analysis/lexer.ts b/packages/base-formula-engine/src/analysis/lexer.tsindex 6c576fcf06..2c969b12f5 100644--- a/packages/base-formula-engine/src/analysis/lexer.ts+++ b/packages/base-formula-engine/src/analysis/lexer.ts@@ -86,7 +86,7 @@ export class LexerTreeBuilder extends Disposable {return this._currentLexerNode;}- treeBuilder(formulaString: string) {+ treeBuilder(formulaString: string, transformSuffix = true) {this._resetCurrentLexerNode();this._currentLexerNode.setToken(DEFAULT_TOKEN_TYPE_ROOT);@@ -100,7 +100,9 @@ export class LexerTreeBuilder extends Disposable {this._currentLexerNode = node;}- this._suffixExpressionHandler(this._currentLexerNode);+ if (transformSuffix) {+ this._suffixExpressionHandler(this._currentLexerNode);+ }return this._currentLexerNode;}@@ -340,9 +342,10 @@ export class LexerTreeBuilder extends Disposable {this._currentLexerNode = subLexerNode;}- private _newAndPushCurrentLexerNode(token: string, isUnshift = false) {+ private _newAndPushCurrentLexerNode(token: string, current: number, isUnshift = false) {const subLexerNode = new LexerNode();subLexerNode.setToken(token);+ subLexerNode.setIndex(current - token.length + 1, current);this._setCurrentLexerNode(subLexerNode, isUnshift);}@@ -401,7 +404,7 @@ export class LexerTreeBuilder extends Disposable {// const subLexerNode = new LexerNode();// subLexerNode.token = this._segment;// this.setCurrentLexerNode(subLexerNode);- this._newAndPushCurrentLexerNode(this._segment);+ this._newAndPushCurrentLexerNode(this._segment, cur);this._resetSegment();}@@ -419,7 +422,7 @@ export class LexerTreeBuilder extends Disposable {// const subLexerNode = new LexerNode();// subLexerNode.token = DEFAULT_TOKEN_TYPE_PARAMETER;// this.setCurrentLexerNode(subLexerNode);- this._newAndPushCurrentLexerNode(DEFAULT_TOKEN_TYPE_PARAMETER);+ this._newAndPushCurrentLexerNode(DEFAULT_TOKEN_TYPE_PARAMETER, cur);}} else {this._pushNodeToChildren(currentString);@@ -446,7 +449,7 @@ export class LexerTreeBuilder extends Disposable {// const subLexerNode = new LexerNode();// subLexerNode.token = DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER;// this.setCurrentLexerNode(subLexerNode);- this._newAndPushCurrentLexerNode(DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER, true);+ this._newAndPushCurrentLexerNode(DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER, cur, true);this._openLambda();} else {if (!this._setAncestorCurrentLexerNode() && cur !== formulaStringArrayCount - 1) {@@ -519,7 +522,7 @@ export class LexerTreeBuilder extends Disposable {// const subLexerNode = new LexerNode();// subLexerNode.token = DEFAULT_TOKEN_TYPE_PARAMETER;// this.setCurrentLexerNode(subLexerNode);- this._newAndPushCurrentLexerNode(DEFAULT_TOKEN_TYPE_PARAMETER);+ this._newAndPushCurrentLexerNode(DEFAULT_TOKEN_TYPE_PARAMETER, cur);} else {return ErrorType.VALUE;}diff --git a/packages/base-formula-engine/src/analysis/parser.ts b/packages/base-formula-engine/src/analysis/parser.tsindex e9ec230a32..203b4a471e 100644--- a/packages/base-formula-engine/src/analysis/parser.ts+++ b/packages/base-formula-engine/src/analysis/parser.ts@@ -7,6 +7,7 @@ import { FunctionNodeFactory } from '../ast-node/function-node';import { LambdaNode, LambdaNodeFactory } from '../ast-node/lambda-node';import { LambdaParameterNodeFactory } from '../ast-node/lambda-parameter-node';import { NodeType } from '../ast-node/node-type';+import { NullNode } from '../ast-node/null-node';import { OperatorNodeFactory } from '../ast-node/operator-node';import { PrefixNodeFactory } from '../ast-node/prefix-node';import { ReferenceNodeFactory } from '../ast-node/reference-node';@@ -14,7 +15,10 @@ import { SuffixNodeFactory } from '../ast-node/suffix-node';import { UnionNodeFactory } from '../ast-node/union-node';import { ValueNodeFactory } from '../ast-node/value-node';import { ErrorType } from '../basics/error-type';+import { isChildRunTimeParameter, isFirstChildParameter } from '../basics/function-definition';import {+ DEFAULT_TOKEN_LAMBDA_FUNCTION_NAME,+ DEFAULT_TOKEN_LET_FUNCTION_NAME,DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER,DEFAULT_TOKEN_TYPE_PARAMETER,DEFAULT_TOKEN_TYPE_ROOT,@@ -60,10 +64,11 @@ export class AstTreeBuilder extends Disposable {private _lambdaParameterHandler(lexerNode: LexerNode, parent: LambdaNode) {const lambdaId = parent.getLambdaId();+const parentAstNode = new AstRootNode(DEFAULT_TOKEN_TYPE_ROOT);// const lambdaRuntime = this._parserDataLoader.getLambdaRuntime();- const currentLambdaPrivacyVar = this._runtimeService.getLambdaPrivacyVar(lambdaId);+ const currentLambdaPrivacyVar = this._runtimeService.getFunctionDefinitionPrivacyVar(lambdaId);if (!currentLambdaPrivacyVar) {return false;@@ -99,6 +104,48 @@ export class AstTreeBuilder extends Disposable {return parent;}+ private _changeLetToLambda(letLexerNode: LexerNode) {+ const letChildren = letLexerNode.getChildren();++ const letChildrenCount = letChildren.length;+ if (letChildrenCount % 2 !== 1 || letChildrenCount === 0) {+ return;+ }++ const newLambdaNode = new LexerNode();+ newLambdaNode.setToken(DEFAULT_TOKEN_LAMBDA_FUNCTION_NAME);++ const newLambdaParameterNode = new LexerNode();+ newLambdaParameterNode.setToken(DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER);++ // const lastLetChild = letChildren[letChildrenCount - 1];++ const copyChildren = [...letChildren];++ for (let i = 0; i < letChildrenCount; i++) {+ const child = copyChildren[i];+ if (!(child instanceof LexerNode)) {+ return;+ }++ if (i % 2 === 0) {+ child.changeToParent(newLambdaNode);+ } else {+ child.changeToParent(newLambdaParameterNode);+ }+ }++ newLambdaNode.addChildrenFirst(newLambdaParameterNode);++ newLambdaParameterNode.setParent(newLambdaNode);++ const parent = letLexerNode.getParent();++ parent?.replaceChild(letLexerNode, newLambdaNode);++ return newLambdaNode;+ }+private _getTopParent(node: BaseAstNode) {let parent: Nullable<BaseAstNode> = node;while (parent?.getParent()) {@@ -114,10 +161,36 @@ export class AstTreeBuilder extends Disposable {const calculateStack: BaseAstNode[] = [];let currentAstNode: Nullable<BaseAstNode> = null;// console.log('lexerNode', lexerNode, children);- if (lexerNode.getToken() === DEFAULT_TOKEN_TYPE_PARAMETER) {+ const token = lexerNode.getToken().trim().toUpperCase();+ if (token === DEFAULT_TOKEN_LET_FUNCTION_NAME) {+ /**+ * Since the let function performs the same as lambda expressions,+ * here we make a conversion to use only lambda expressions for calculations.+ */+ const resultNode: Nullable<LexerNode> = this._changeLetToLambda(lexerNode);+ if (resultNode != null) {+ return this._parse(resultNode, parent);+ }++ console.log('errorLet', resultNode, currentAstNode, lexerNode);+ return ErrorNode.create(ErrorType.ERROR);+ }+ if (token === DEFAULT_TOKEN_TYPE_PARAMETER) {currentAstNode = parent;++ if (childrenCount === 0) {+ const nullNode = new NullNode(DEFAULT_TOKEN_TYPE_ROOT);++ nullNode.setParent(parent);++ return currentAstNode;+ }} else {- if (lexerNode.getToken() === DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER) {+ /**+ * Process the parameters of the lambda expression, create an execution environment,+ * allowing parameters to correspond to variables.+ */+ if (token === DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER) {let resultNode: BaseAstNode | false = this._lambdaParameterHandler(lexerNode, parent as LambdaNode);if (resultNode === false) {console.log('error1', resultNode, currentAstNode, lexerNode);@@ -137,17 +210,31 @@ export class AstTreeBuilder extends Disposable {// parent.addChildren(currentAstNode);}console.log('currentAstNode', currentAstNode.nodeType, currentAstNode, lexerNode);+ const firstChild = children[0];+ // let isSkipFirstInLambda = false;+ // if (+ // currentAstNode.getToken().trim().toUpperCase() === DEFAULT_TOKEN_LAMBDA_FUNCTION_NAME &&+ // !isFirstChildParameter(firstChild)+ // ) {+ // isSkipFirstInLambda = true;+ // }for (let i = 0; i < childrenCount; i++) {- if (- currentAstNode.nodeType === NodeType.LAMBDA &&- parent.nodeType !== NodeType.LAMBDA &&- i !== 0 &&- i !== childrenCount - 1- ) {- continue;+ const item = children[i];+ /**+ * If it is a lambda expression, by default, only the first and last child nodes are valid.+ * The intermediate nodes have already been processed during the conversion of lambda parameters,+ * so they need to be skipped here.+ */+ if (isFirstChildParameter(firstChild)) {+ if (i !== 0 && i !== childrenCount - 1) {+ continue;+ }+ } else if (isChildRunTimeParameter(item)) {+ if (i !== childrenCount - 1) {+ continue;+ }}- const item = children[i];let astNode: Nullable<BaseAstNode> = null;if (item instanceof LexerNode) {astNode = this._parse(item, currentAstNode);diff --git a/packages/base-formula-engine/src/ast-node/lambda-node.ts b/packages/base-formula-engine/src/ast-node/lambda-node.tsindex 49dd28da67..cef192b0b3 100644--- a/packages/base-formula-engine/src/ast-node/lambda-node.ts+++ b/packages/base-formula-engine/src/ast-node/lambda-node.ts@@ -2,7 +2,12 @@ import { Nullable, Tools } from '@univerjs/core';import { LexerNode } from '../analysis/lexer-node';import { ErrorType } from '../basics/error-type';-import { DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER, DEFAULT_TOKEN_TYPE_LAMBDA_RUNTIME_PARAMETER } from '../basics/token-type';+import { isFirstChildParameter } from '../basics/function-definition';+import {+ DEFAULT_TOKEN_TYPE_LAMBDA_OMIT_PARAMETER,+ DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER,+ DEFAULT_TOKEN_TYPE_LAMBDA_RUNTIME_PARAMETER,+} from '../basics/token-type';import { IFormulaRuntimeService } from '../services/runtime.service';import { BaseAstNode, ErrorNode, LambdaPrivacyVarType } from './base-ast-node';import { BaseAstNodeFactory, DEFAULT_AST_NODE_FACTORY_Z_INDEX } from './base-ast-node-factory';@@ -22,6 +27,10 @@ export class LambdaNode extends BaseAstNode {return NodeType.LAMBDA;}+ isFunctionParameter() {+ return this._lambdaId === null;+ }+getLambdaId() {return this._lambdaId;}@@ -45,20 +54,20 @@ export class LambdaNodeFactory extends BaseAstNodeFactory {override create(param: LexerNode): BaseAstNode {const children = param.getChildren();const lambdaVar = children[0];- const parameterArray = children.slice(1, -1);+ let parameterArray = children.slice(1, -1);const functionStatementNode = children[children.length - 1];if (!(lambdaVar instanceof LexerNode && functionStatementNode instanceof LexerNode)) {return ErrorNode.create(ErrorType.NAME);}- if (lambdaVar.getToken() !== DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER) {- return ErrorNode.create(ErrorType.NAME);- }-- const lambdaVarChildren = lambdaVar.getChildren();+ if (lambdaVar.getToken() === DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER) {+ const lambdaVarChildren = lambdaVar.getChildren();- if (parameterArray.length !== lambdaVarChildren.length) {- return ErrorNode.create(ErrorType.VALUE);+ if (parameterArray.length !== lambdaVarChildren.length) {+ return ErrorNode.create(ErrorType.VALUE);+ }+ } else {+ parameterArray = children.slice(0, -1);}// const lambdaId = nanoid(8);@@ -71,13 +80,14 @@ export class LambdaNodeFactory extends BaseAstNodeFactory {const parameter = parameterArray[i];if (parameter instanceof LexerNode) {const variant = parameter.getChildren()[0] as string;- currentLambdaPrivacyVar.set(variant, null);+ parameter.setToken(DEFAULT_TOKEN_TYPE_LAMBDA_OMIT_PARAMETER);+ currentLambdaPrivacyVar.set(variant.trim(), undefined);} else {return ErrorNode.create(ErrorType.VALUE);}}- this._runtimeService.registerLambdaPrivacyVar(lambdaId, currentLambdaPrivacyVar);+ this._runtimeService.registerFunctionDefinitionPrivacyVar(lambdaId, currentLambdaPrivacyVar);this._updateLambdaStatement(functionStatementNode, lambdaId, currentLambdaPrivacyVar);@@ -112,8 +122,12 @@ export class LambdaNodeFactory extends BaseAstNodeFactory {) {const children = functionStatementNode.getChildren();const childrenCount = children.length;+ const firstChild = children[0];for (let i = 0; i < childrenCount; i++) {const node = children[i];+ if (isFirstChildParameter(firstChild) && i !== 0) {+ continue;+ }if (node instanceof LexerNode) {this._updateTree(node, lambdaId, currentLambdaPrivacyVar);} else {diff --git a/packages/base-formula-engine/src/ast-node/lambda-parameter-node.ts b/packages/base-formula-engine/src/ast-node/lambda-parameter-node.tsindex d546d1350d..d7cf570295 100644--- a/packages/base-formula-engine/src/ast-node/lambda-parameter-node.ts+++ b/packages/base-formula-engine/src/ast-node/lambda-parameter-node.ts@@ -1,3 +1,5 @@+import { Nullable } from '@univerjs/core';+import { LexerNode } from '../analysis/lexer-node';import { ErrorType } from '../basics/error-type';import { DEFAULT_TOKEN_TYPE_LAMBDA_RUNTIME_PARAMETER } from '../basics/token-type';@@ -15,18 +17,45 @@ export class LambdaParameterNode extends BaseAstNode {super(token);}+ getLambdaParameter() {+ return this._lambdaParameter;+ }++ getCurrentLambdaPrivacyVar() {+ return this._currentLambdaPrivacyVar;+ }+override get nodeType() {return NodeType.LAMBDA_PARAMETER;}override execute() {- const node = this._currentLambdaPrivacyVar.get(this._lambdaParameter);+ const node = this._getRootLexerNode(this._currentLambdaPrivacyVar.get(this._lambdaParameter));if (!node) {this.setValue(ErrorValueObject.create(ErrorType.SPILL));} else {this.setValue(node.getValue());}}++ private _getRootLexerNode(node: Nullable<BaseAstNode>): Nullable<BaseAstNode> {+ if (!node) {+ return;+ }+ if (node.getToken() !== DEFAULT_TOKEN_TYPE_LAMBDA_RUNTIME_PARAMETER) {+ return node;+ }++ const parameterNode = node as LambdaParameterNode;+ const currentLambdaPrivacyVar = parameterNode.getCurrentLambdaPrivacyVar();+ const lambdaParameter = parameterNode.getLambdaParameter();++ if (!currentLambdaPrivacyVar) {+ return;+ }++ return this._getRootLexerNode(currentLambdaPrivacyVar.get(lambdaParameter));+ }}export class LambdaParameterNodeFactory extends BaseAstNodeFactory {@@ -36,7 +65,7 @@ export class LambdaParameterNodeFactory extends BaseAstNodeFactory {override create(param: LexerNode): BaseAstNode {// const lambdaId = param.getLambdaId();- const currentLambdaPrivacyVar = param.getLambdaPrivacyVar();+ const currentLambdaPrivacyVar = param.getFunctionDefinitionPrivacyVar();const lambdaParameter = param.getLambdaParameter();if (!currentLambdaPrivacyVar) {diff --git a/packages/base-formula-engine/src/ast-node/node-type.ts b/packages/base-formula-engine/src/ast-node/node-type.tsindex 34af168727..04d336b014 100644--- a/packages/base-formula-engine/src/ast-node/node-type.ts+++ b/packages/base-formula-engine/src/ast-node/node-type.ts@@ -11,6 +11,7 @@ export enum NodeType {UNION = 'UnionNode',PREFIX = 'PrefixNode',SUFFIX = 'SuffixNode',+ NULL = 'NullNode',}export const NODE_ORDER_MAP = new Map([diff --git a/packages/base-formula-engine/src/ast-node/null-node.ts b/packages/base-formula-engine/src/ast-node/null-node.tsnew file mode 100644index 0000000000..16f7c4c47d--- /dev/null+++ b/packages/base-formula-engine/src/ast-node/null-node.ts@@ -0,0 +1,17 @@+import { NullValueObject } from '../value-object/primitive-object';+import { BaseAstNode } from './base-ast-node';+import { NodeType } from './node-type';++export class NullNode extends BaseAstNode {+ constructor(private _operatorString: string) {+ super(_operatorString);+ }++ override get nodeType() {+ return NodeType.NULL;+ }++ override execute() {+ this.setValue(new NullValueObject(0));+ }+}diff --git a/packages/base-formula-engine/src/ast-node/operator-node.ts b/packages/base-formula-engine/src/ast-node/operator-node.tsindex 87c9f0015b..a693228eff 100644--- a/packages/base-formula-engine/src/ast-node/operator-node.ts+++ b/packages/base-formula-engine/src/ast-node/operator-node.ts@@ -10,20 +10,6 @@ import { BaseAstNode, ErrorNode } from './base-ast-node';import { BaseAstNodeFactory, DEFAULT_AST_NODE_FACTORY_Z_INDEX } from './base-ast-node-factory';import { NODE_ORDER_MAP, NodeType } from './node-type';-const PLUS_EXECUTOR_NAME = 'PLUS';--const MINUS_EXECUTOR_NAME = 'MINUS';--const MULTIPLY_EXECUTOR_NAME = 'MULTIPLY';--const DIVIDED_EXECUTOR_NAME = 'DIVIDED';--const CONCATENATE_EXECUTOR_NAME = 'CONCATENATE';--const POWER_EXECUTOR_NAME = 'POWER';--const COMPARE_EXECUTOR_NAME = 'COMPARE';-export class OperatorNode extends BaseAstNode {constructor(private _operatorString: string,@@ -38,7 +24,7 @@ export class OperatorNode extends BaseAstNode {override execute() {const children = this.getChildren();- if (this._functionExecutor.name === COMPARE_EXECUTOR_NAME) {+ if (this._functionExecutor.name === FUNCTION_NAMES.COMPARE) {(this._functionExecutor as Compare).setCompareType(this.getToken() as compareToken);}const object1 = children[0].getValue();diff --git a/packages/base-formula-engine/src/basics/function-definition.ts b/packages/base-formula-engine/src/basics/function-definition.tsnew file mode 100644index 0000000000..21e5ca7d5b--- /dev/null+++ b/packages/base-formula-engine/src/basics/function-definition.ts@@ -0,0 +1,16 @@+import { LexerNode } from '../analysis/lexer-node';+import { DEFAULT_TOKEN_TYPE_LAMBDA_OMIT_PARAMETER, DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER } from './token-type';++export function isFirstChildParameter(lexerNode: LexerNode | string) {+ if (!(lexerNode instanceof LexerNode)) {+ return false;+ }+ return lexerNode.getToken() === DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER;+}++export function isChildRunTimeParameter(lexerNode: LexerNode | string) {+ if (!(lexerNode instanceof LexerNode)) {+ return false;+ }+ return lexerNode.getToken() === DEFAULT_TOKEN_TYPE_LAMBDA_OMIT_PARAMETER;+}diff --git a/packages/base-formula-engine/src/basics/token-type.ts b/packages/base-formula-engine/src/basics/token-type.tsindex f3a2de05e4..0bf34c1ba0 100644--- a/packages/base-formula-engine/src/basics/token-type.ts+++ b/packages/base-formula-engine/src/basics/token-type.ts@@ -5,3 +5,9 @@ export const DEFAULT_TOKEN_TYPE_ROOT = 'R_1';export const DEFAULT_TOKEN_TYPE_LAMBDA_PARAMETER = 'L_1';export const DEFAULT_TOKEN_TYPE_LAMBDA_RUNTIME_PARAMETER = 'LR_1';++export const DEFAULT_TOKEN_TYPE_LAMBDA_OMIT_PARAMETER = 'LO_1';++export const DEFAULT_TOKEN_LET_FUNCTION_NAME = 'LET';++export const DEFAULT_TOKEN_LAMBDA_FUNCTION_NAME = 'LAMBDA';diff --git a/packages/base-formula-engine/src/services/runtime.service.ts b/packages/base-formula-engine/src/services/runtime.service.tsindex b83dcd5038..3808a0a3fc 100644--- a/packages/base-formula-engine/src/services/runtime.service.ts+++ b/packages/base-formula-engine/src/services/runtime.service.ts@@ -28,9 +28,9 @@ export interface IFormulaRuntimeService {setCurrent(row: number, column: number, sheetId: string, unitId: string): void;- registerLambdaPrivacyVar(lambdaId: string, lambdaVar: Map<string, Nullable<BaseAstNode>>): void;+ registerFunctionDefinitionPrivacyVar(lambdaId: string, lambdaVar: Map<string, Nullable<BaseAstNode>>): void;- getLambdaPrivacyVar(lambdaId: string): Nullable<Map<string, Nullable<BaseAstNode>>>;+ getFunctionDefinitionPrivacyVar(lambdaId: string): Nullable<Map<string, Nullable<BaseAstNode>>>;setRuntimeData(functionVariant: FunctionVariantType): void;@@ -54,7 +54,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimeprivate _unitArrayFormulaData: UnitArrayFormulaDataType = {};// lambdaId: { key: BaseAstNode }- private _lambdaPrivacyVar: Map<string, Map<string, Nullable<BaseAstNode>>> = new Map();+ private _functionDefinitionPrivacyVar: Map<string, Map<string, Nullable<BaseAstNode>>> = new Map();get currentRow() {return this._currentRow;@@ -79,7 +79,7 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimereset() {this._runtimeData = {};this._unitArrayFormulaData = {};- this._lambdaPrivacyVar.clear();+ this._functionDefinitionPrivacyVar.clear();}setCurrent(row: number, column: number, sheetId: string, unitId: string) {@@ -89,16 +89,16 @@ export class FormulaRuntimeService extends Disposable implements IFormulaRuntimethis._currentUnitId = unitId;}- clearLambdaPrivacyVar() {- this._lambdaPrivacyVar.clear();+ clearFunctionDefinitionPrivacyVar() {+ this._functionDefinitionPrivacyVar.clear();}- registerLambdaPrivacyVar(lambdaId: string, lambdaVar: Map<string, Nullable<BaseAstNode>>) {- this._lambdaPrivacyVar.set(lambdaId, lambdaVar);+ registerFunctionDefinitionPrivacyVar(lambdaId: string, lambdaVar: Map<string, Nullable<BaseAstNode>>) {+ this._functionDefinitionPrivacyVar.set(lambdaId, lambdaVar);}- getLambdaPrivacyVar(lambdaId: string): Nullable<Map<string, Nullable<BaseAstNode>>> {- return this._lambdaPrivacyVar.get(lambdaId);+ getFunctionDefinitionPrivacyVar(lambdaId: string): Nullable<Map<string, Nullable<BaseAstNode>>> {+ return this._functionDefinitionPrivacyVar.get(lambdaId);}setRuntimeData(functionVariant: FunctionVariantType) {diff --git a/packages/base-formula-engine/src/value-object/base-value-object.ts b/packages/base-formula-engine/src/value-object/base-value-object.tsindex 90aef9d037..6017bff54b 100644--- a/packages/base-formula-engine/src/value-object/base-value-object.ts+++ b/packages/base-formula-engine/src/value-object/base-value-object.ts@@ -58,6 +58,10 @@ export class BaseValueObject extends ObjectClassType {return false;}+ isNull() {+ return false;+ }+getNegative(): CalculateValueType {return ErrorValueObject.create(ErrorType.VALUE);}diff --git a/packages/base-formula-engine/src/value-object/primitive-object.ts b/packages/base-formula-engine/src/value-object/primitive-object.tsindex 6161d2a0e8..f1e993eed4 100644--- a/packages/base-formula-engine/src/value-object/primitive-object.ts+++ b/packages/base-formula-engine/src/value-object/primitive-object.ts@@ -5,6 +5,78 @@ import { compareToken } from '../basics/token';import { ErrorValueObject } from '../other-object/error-value-object';import { BaseValueObject, CalculateValueType } from './base-value-object';+export class NullValueObject extends BaseValueObject {+ override isNull(): boolean {+ return true;+ }++ override plus(valueObject: BaseValueObject): CalculateValueType {+ return new NumberValueObject(0, true).plus(valueObject);+ }++ override minus(valueObject: BaseValueObject): CalculateValueType {+ return new NumberValueObject(0, true).minus(valueObject);+ }++ override multiply(valueObject: BaseValueObject): CalculateValueType {+ return new NumberValueObject(0, true).multiply(valueObject);+ }++ override divided(valueObject: BaseValueObject): CalculateValueType {+ return new NumberValueObject(0, true).divided(valueObject);+ }++ override compare(valueObject: BaseValueObject, operator: compareToken): CalculateValueType {+ if (valueObject.isString()) {+ return new StringValueObject('').compare(valueObject, operator);+ }+ if (valueObject.isBoolean()) {+ return new BooleanValueObject(false).compare(valueObject, operator);+ }+ return new NumberValueObject(0, true).compare(valueObject, operator);+ }++ override concatenateFront(valueObject: BaseValueObject): CalculateValueType {+ if (valueObject.isArray()) {+ return valueObject.concatenateBack(new StringValueObject(''));+ }+ return new StringValueObject('').concatenate(valueObject.getValue(), ConcatenateType.FRONT);+ }++ override concatenateBack(valueObject: BaseValueObject): CalculateValueType {+ if (valueObject.isArray()) {+ return valueObject.concatenateFront(new StringValueObject(''));+ }+ return new StringValueObject('').concatenate(valueObject.getValue(), ConcatenateType.BACK);+ }++ override plusBy(value: string | number | boolean): CalculateValueType {+ return new NumberValueObject(0).plusBy(value);+ }++ override minusBy(value: string | number | boolean): CalculateValueType {+ return new NumberValueObject(0).minusBy(value);+ }++ override multiplyBy(value: string | number | boolean): CalculateValueType {+ return new NumberValueObject(0).multiplyBy(value);+ }++ override dividedBy(value: string | number | boolean): CalculateValueType {+ return new NumberValueObject(0).dividedBy(value);+ }++ override compareBy(value: string | number | boolean, operator: compareToken): CalculateValueType {+ if (typeof value === 'string') {+ return new StringValueObject('').compareBy(value, operator);+ }+ if (typeof value === 'boolean') {+ return new BooleanValueObject(false).compareBy(value, operator);+ }+ return new NumberValueObject(0, true).compareBy(value, operator);+ }+}+export class BooleanValueObject extends BaseValueObject {private _value: boolean = false;diff --git a/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.ts b/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.tsindex 12e08a92c8..f5013a9db5 100644--- a/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.ts+++ b/packages/ui-plugin-sheets/src/controllers/editor/editing.controller.ts@@ -45,14 +45,19 @@ export class EditingController extends Disposable {}private _initialNormalInput() {- // const formulaEngine = this.getPluginByName<FormulaPlugin>('formula')?.getFormulaEngine();- // =(sum(max(B1:C10,10)*5-100,((1+1)*2+5)/2,10)+count(B1:C10,10*5-100))*5-100- // =(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- // =((1+2)-A1:B2 + 5)/2 + sum(indirect("A5"):B10 + A1:offset("C5", 1, 1), 100)- // =1+(3*4=4)*5+1- // =(-(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)%- // formulaEngine?.calculate(`=lambda(x,y, x*y*x)(sum(1,(1+2)*3),2)+1-max(100,200)`);-+ /**+ * const formulaEngine = this.getPluginByName<FormulaPlugin>('formula')?.getFormulaEngine();+ * =(sum(max(B1:C10,10)*5-100,((1+1)*2+5)/2,10)+count(B1:C10,10*5-100))*5-100+ * =(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+ * =((1+2)-A1:B2 + 5)/2 + sum(indirect("A5"):B10 + A1:offset("C5", 1, 1), 100)+ * =1+(3*4=4)*5+1+ * =(-(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)%+ * =lambda(x, y, lambda(x,y, x*lambda(x,y, x*y*x)(x,y))(x,y))(sum(1,2,3), 2)+ * =let(x,5,y,4,sum(x,y)+x))+ * =REDUCE(1, A1:C2, LAMBDA(a,b,a+b^2))+ * =sum(, A1:B1)+ * formulaEngine?.calculate(`=lambda(x,y, x*y*x)(sum(1,(1+2)*3),2)+1-max(100,200)`);+ */const sheetData: ISheetData = {};this._currentUniverService.getCurrentUniverSheetInstance()@@ -97,24 +102,21 @@ export class EditingController extends Disposable {},};- this._formulaEngineService- .execute('workbook-01', {- unitData: {- 'workbook-01': sheetData,- },- formulaData,- sheetNameMap: {},- forceCalculate: true,- updateRangeList: [],- })- .then((res) => {- console.log(res.sheetData, res.arrayFormulaData);- });+ // this._formulaEngineService+ // .execute('workbook-01', {+ // unitData: {+ // 'workbook-01': sheetData,+ // },+ // formulaData,+ // sheetNameMap: {},+ // forceCalculate: true,+ // updateRangeList: [],+ // })+ // .then((res) => {+ // console.log(res.sheetData, res.arrayFormulaData);+ // });- // console.log(- // 'calculate',- // this._formulaEngineService.calculate('=1+REDUCE(1, A1:C2, LAMBDA(x,y,LAMBDA(a,b,a*b*a)(x,y)))')- // );+ console.log('calculate', this._formulaEngineService.calculate('=sum(, A1:B1)'));}private _commandExecutedListener() {}