Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

8.0 KB
Raw Blame
/**
 * Copyright 2023-present DreamNum Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import type { IUnitRange, Nullable } from '@univerjs/core';
import type { BaseFunction } from '../../functions/base-function';
import type { BaseReferenceObject, FunctionVariantType } from '../reference-object/base-reference-object';
import type { BaseValueObject } from '../value-object/base-value-object';
import { DateSystem } from '@univerjs/core';
import { ErrorType } from '../../basics/error-type';
import { OPERATOR_TOKEN_COMPARE_SET, prefixToken } from '../../basics/token';
import { FUNCTION_NAMES_LOOKUP } from '../../functions/lookup/function-names';
import { FUNCTION_NAMES_META } from '../../functions/meta/function-names';
import { IFunctionService } from '../../services/function.service';
import { IFormulaRuntimeService } from '../../services/runtime.service';
import { LexerNode } from '../analysis/lexer-node';
import { ArrayValueObject } from '../value-object/array-value-object';
import { ErrorValueObject } from '../value-object/base-value-object';
import { NumberValueObject } from '../value-object/primitive-object';
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';

export class PrefixNode extends BaseAstNode {
    private _referenceRanges: IUnitRange[] | null = null;

    getReferenceRanges(): IUnitRange[] | null {
        return this._referenceRanges;
    }

    constructor(
        private _runtimeService: IFormulaRuntimeService,
        private _operatorString: string,
        private _functionExecutor?: Nullable<BaseFunction>
    ) {
        super(_operatorString);
    }

    override get nodeType() {
        return NodeType.PREFIX;
    }

    override execute(dateSystem: DateSystem = DateSystem.Date1900) {
        this._referenceRanges = null;
        const children = this.getChildren();
        let value = children[0].getValue();
        let result: FunctionVariantType;
        if (value == null) {
            console.error('PrefixNode execute value is null');
            this.setValue(ErrorValueObject.create(ErrorType.VALUE));
            return;
        }

        if (this._operatorString === prefixToken.MINUS) {
            if (value.isReferenceObject()) {
                value = (value as BaseReferenceObject).withDateSystem(dateSystem).toArrayValueObject();
            }
            result = this._functionExecutor!.calculate(
                NumberValueObject.create(0),
                (value as BaseValueObject).withDateSystem(dateSystem)
            ) as FunctionVariantType;
        } else if (this._operatorString === prefixToken.AT) {
            result = this._handlerAT(value);
        } else {
            result = ErrorValueObject.create(ErrorType.VALUE);
        }
        this.setValue(result.withDateSystem(dateSystem));
    }

    private _handlerAT(value: FunctionVariantType) {
        if (value instanceof ArrayValueObject) {
            return value.get(0, 0) ?? ErrorValueObject.create(ErrorType.VALUE);
        }
        if (!value.isReferenceObject()) {
            return value;
        }

        const currentValue = value as BaseReferenceObject;
        this._referenceRanges = [];

        if (currentValue.isCell()) {
            return this._getReferencedCell(currentValue);
        }

        if (this._preserveAtRangeForFormula2LookupArray()) {
            return currentValue;
        }

        const runtimeService = this._runtimeService;

        const currentRow = runtimeService.currentRow || 0;
        const currentColumn = runtimeService.currentColumn || 0;

        const rangePos = currentValue.getRangePosition();

        const { startRow, startColumn, endRow, endColumn } = rangePos;

        if (endColumn !== startColumn && endRow !== startRow) {
            return ErrorValueObject.create(ErrorType.VALUE);
        }

        if (startRow === endRow && startColumn === endColumn) {
            return ErrorValueObject.create(ErrorType.VALUE);
        }

        // @ projection to current
        if (endRow === startRow && currentColumn >= startColumn && currentColumn <= endColumn) {
            return this._getReferencedCell(currentValue, undefined, currentColumn);
        } else if (startColumn === endColumn && currentRow >= startRow && currentRow <= endRow) {
            return this._getReferencedCell(currentValue, currentRow);
        }

        if (currentValue.isTable()) {
            return this._getReferencedCell(currentValue, currentRow);
        }

        return ErrorValueObject.create(ErrorType.VALUE);
    }

    private _getReferencedCell(reference: BaseReferenceObject, row?: number, column?: number) {
        const position = reference.getRangePosition();
        const selectedRow = row ?? position.startRow;
        const selectedColumn = column ?? position.startColumn;
        this._referenceRanges = reference.toUnitRanges().map((range) => ({
            unitId: range.unitId,
            sheetId: range.sheetId,
            range: {
                startRow: selectedRow,
                endRow: selectedRow,
                startColumn: selectedColumn,
                endColumn: selectedColumn,
            },
        }));
        return reference.getCellByPosition(selectedRow, selectedColumn);
    }

    private _preserveAtRangeForFormula2LookupArray(): boolean {
        let node: BaseAstNode = this;
        let parent = node.getParent();
        let sawCompareOperator = false;

        while (parent != null) {
            if (parent.nodeType === NodeType.OPERATOR) {
                sawCompareOperator ||= OPERATOR_TOKEN_COMPARE_SET.has(parent.getToken());
            }

            if (parent.nodeType === NodeType.FUNCTION) {
                const functionName = parent.getToken().toUpperCase();
                if (
                    sawCompareOperator &&
                    functionName === FUNCTION_NAMES_LOOKUP.XMATCH
                ) {
                    return parent.getChildren().indexOf(node) === 1;
                }
                return false;
            }

            node = parent;
            parent = parent.getParent();
        }

        return false;
    }
}

export class PrefixNodeFactory extends BaseAstNodeFactory {
    constructor(
        @IFunctionService private readonly _functionService: IFunctionService,
        @IFormulaRuntimeService private readonly _runtimeService: IFormulaRuntimeService
    ) {
        super();
    }

    override get zIndex() {
        return NODE_ORDER_MAP.get(NodeType.PREFIX) || DEFAULT_AST_NODE_FACTORY_Z_INDEX;
    }

    override checkAndCreateNodeType(param: LexerNode | string) {
        if (!(param instanceof LexerNode)) {
            return;
        }

        const token = param.getToken();
        const tokenTrim = token.trim();

        if (tokenTrim.charAt(0) === '"' && tokenTrim.charAt(tokenTrim.length - 1) === '"') {
            return;
        }

        let functionName = '';
        if (tokenTrim === prefixToken.MINUS) {
            functionName = FUNCTION_NAMES_META.MINUS;
        } else if (tokenTrim === prefixToken.AT) {
            return new PrefixNode(this._runtimeService, tokenTrim);
        } else {
            return;
        }

        const functionExecutor = this._functionService.getExecutor(functionName);
        if (!functionExecutor) {
            console.error(`No function ${token}`);
            return ErrorNode.create(ErrorType.NAME);
        }
        return new PrefixNode(this._runtimeService, tokenTrim, functionExecutor);
    }
}