diff --git a/CHANGELOG.md b/CHANGELOG.md index dfe608f4e7..a512297658 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Added support for array arithmetic. (#628) +- Added ARRAYFORMULA function. (#630) - Added performance improvements for array handling. (#629) - Accepting time in JS Date() objects on the input. (#648) diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index f8513d06c9..87486f7007 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -125,12 +125,12 @@ export const myTranslations = { For the simplicity of a basic example, you will not pass any arguments. However, this method imposes a particular structure to be used; there are two optional arguments, `ast` and -`formulaAddress`, and the function must return the results of +`state`, and the function must return the results of the calculations. ```javascript // arguments here are displayed just to show the structure -public hyper(ast, formulaAddress) { +public hyper(ast, state) { return 'Hyperformula'.length; } }; @@ -152,7 +152,7 @@ export class CountHF extends FunctionPlugin { } }; - public hyper(ast, formulaAddress) { + public hyper(ast, state) { return 'Hyperformula'.length } }; diff --git a/src/Evaluator.ts b/src/Evaluator.ts index 907dc259ad..bf6e4e2d7c 100644 --- a/src/Evaluator.ts +++ b/src/Evaluator.ts @@ -6,6 +6,7 @@ import {AbsoluteCellRange} from './AbsoluteCellRange' import {absolutizeDependencies} from './absolutizeDependencies' import {CellError, ErrorType, SimpleCellAddress} from './Cell' +import {InterpreterState} from './interpreter/InterpreterState' import {SimpleRangeValue} from './interpreter/SimpleRangeValue' import {ColumnSearchStrategy} from './Lookup/SearchStrategy' import {Config} from './Config' @@ -60,7 +61,7 @@ export class Evaluator { const address = vertex.getAddress(this.dependencyGraph.lazilyTransformingAstService) const formula = vertex.getFormula(this.dependencyGraph.lazilyTransformingAstService) const currentValue = vertex.isComputed() ? vertex.getCellValue() : null - const newCellValue = this.evaluateAstToCellValue(formula, address) + const newCellValue = this.evaluateAstToCellValue(formula, new InterpreterState(address, this.config.arrays)) vertex.setCellValue(newCellValue) if (newCellValue !== currentValue) { changes.addChange(newCellValue, address) @@ -72,7 +73,7 @@ export class Evaluator { const address = vertex.getAddress() const formula = vertex.getFormula() as Ast const currentValue = vertex.isComputed() ? vertex.getCellValue() : null - const newCellValue = this.evaluateAstToRangeValue(formula, address) + const newCellValue = this.evaluateAstToRangeValue(formula, new InterpreterState(address, this.config.arrays)) if (newCellValue instanceof SimpleRangeValue) { const newCellMatrix = new Matrix(newCellValue.rawNumbers()) vertex.setCellValue(newCellMatrix) @@ -123,7 +124,7 @@ export class Evaluator { } } } - const ret = this.evaluateAstToCellValue(ast, address) + const ret = this.evaluateAstToCellValue(ast, new InterpreterState(address, this.config.arrays)) tmpRanges.forEach((rangeVertex) => { this.dependencyGraph.rangeMapping.removeRange(rangeVertex) @@ -145,13 +146,13 @@ export class Evaluator { if (vertex instanceof FormulaCellVertex) { const address = vertex.getAddress(this.dependencyGraph.lazilyTransformingAstService) const formula = vertex.getFormula(this.dependencyGraph.lazilyTransformingAstService) - const newCellValue = this.evaluateAstToCellValue(formula, address) + const newCellValue = this.evaluateAstToCellValue(formula, new InterpreterState(address, this.config.arrays)) vertex.setCellValue(newCellValue) this.columnSearch.add(getRawValue(newCellValue), address) } else if (vertex instanceof MatrixVertex && vertex.isFormula()) { const address = vertex.getAddress() const formula = vertex.getFormula() as Ast - const newCellValue = this.evaluateAstToRangeValue(formula, address) + const newCellValue = this.evaluateAstToRangeValue(formula, new InterpreterState(address, this.config.arrays)) if (newCellValue instanceof SimpleRangeValue) { const newCellMatrix = new Matrix(newCellValue.rawNumbers()) vertex.setCellValue(newCellMatrix) @@ -166,8 +167,8 @@ export class Evaluator { }) } - private evaluateAstToCellValue(ast: Ast, formulaAddress: SimpleCellAddress): InterpreterValue { - const interpreterValue = this.interpreter.evaluateAst(ast, formulaAddress) + private evaluateAstToCellValue(ast: Ast, state: InterpreterState): InterpreterValue { + const interpreterValue = this.interpreter.evaluateAst(ast, state) if (interpreterValue instanceof SimpleRangeValue) { return interpreterValue } else if (interpreterValue === EmptyValue && this.config.evaluateNullToZero) { @@ -177,8 +178,8 @@ export class Evaluator { } } - private evaluateAstToRangeValue(ast: Ast, formulaAddress: SimpleCellAddress): SimpleRangeValue | CellError { - const interpreterValue = this.interpreter.evaluateAst(ast, formulaAddress) + private evaluateAstToRangeValue(ast: Ast, state: InterpreterState): SimpleRangeValue | CellError { + const interpreterValue = this.interpreter.evaluateAst(ast, state) if (interpreterValue instanceof CellError) { return interpreterValue } else if (interpreterValue instanceof SimpleRangeValue && interpreterValue.hasOnlyNumbers()) { diff --git a/src/i18n/languages/csCZ.ts b/src/i18n/languages/csCZ.ts index 1bb28040bc..76bdab8bc8 100644 --- a/src/i18n/languages/csCZ.ts +++ b/src/i18n/languages/csCZ.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#HODNOTA!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ABS', ACOS: 'ARCCOS', ACOSH: 'ARCCOSH', diff --git a/src/i18n/languages/daDK.ts b/src/i18n/languages/daDK.ts index ea841835ff..93eff0f6d5 100644 --- a/src/i18n/languages/daDK.ts +++ b/src/i18n/languages/daDK.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#VÆRDI!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ABS', ACOS: 'ARCCOS', ACOSH: 'ARCCOSH', diff --git a/src/i18n/languages/deDE.ts b/src/i18n/languages/deDE.ts index 6d4b8b592b..3aa8e3f468 100644 --- a/src/i18n/languages/deDE.ts +++ b/src/i18n/languages/deDE.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#WERT!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ABS', ACOS: 'ARCCOS', ACOSH: 'ARCCOSHYP', diff --git a/src/i18n/languages/enGB.ts b/src/i18n/languages/enGB.ts index 2f81157598..f25f722ccc 100644 --- a/src/i18n/languages/enGB.ts +++ b/src/i18n/languages/enGB.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#VALUE!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ABS', ACOS: 'ACOS', ACOSH: 'ACOSH', diff --git a/src/i18n/languages/esES.ts b/src/i18n/languages/esES.ts index 35dcdbe6eb..b8622a6dd1 100644 --- a/src/i18n/languages/esES.ts +++ b/src/i18n/languages/esES.ts @@ -18,6 +18,7 @@ export const dictionary: RawTranslationPackage = { VALUE: '#¡VALOR!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ABS', ACOS: 'ACOS', ACOSH: 'ACOSH', diff --git a/src/i18n/languages/fiFI.ts b/src/i18n/languages/fiFI.ts index 357e1edefc..9cbb1ea988 100644 --- a/src/i18n/languages/fiFI.ts +++ b/src/i18n/languages/fiFI.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#ARVO!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ITSEISARVO', ACOS: 'ACOS', ACOSH: 'ACOSH', diff --git a/src/i18n/languages/frFR.ts b/src/i18n/languages/frFR.ts index cdc456b193..3ca195050d 100644 --- a/src/i18n/languages/frFR.ts +++ b/src/i18n/languages/frFR.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#VALEUR!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ABS', ACOS: 'ACOS', ACOSH: 'ACOSH', diff --git a/src/i18n/languages/huHU.ts b/src/i18n/languages/huHU.ts index a7b932b64e..968d7d3c34 100644 --- a/src/i18n/languages/huHU.ts +++ b/src/i18n/languages/huHU.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#ÉRTÉK!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ABS', ACOS: 'ARCCOS', ACOSH: 'ARCCOSH', diff --git a/src/i18n/languages/itIT.ts b/src/i18n/languages/itIT.ts index 10cb09d5dc..87dd871177 100644 --- a/src/i18n/languages/itIT.ts +++ b/src/i18n/languages/itIT.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#VALORE!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ASS', ACOS: 'ARCCOS', ACOSH: 'ARCCOSH', diff --git a/src/i18n/languages/nbNO.ts b/src/i18n/languages/nbNO.ts index b78bcba014..db96792487 100644 --- a/src/i18n/languages/nbNO.ts +++ b/src/i18n/languages/nbNO.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#VERDI!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ABS', ACOS: 'ARCCOS', ACOSH: 'ARCCOSH', diff --git a/src/i18n/languages/nlNL.ts b/src/i18n/languages/nlNL.ts index dfc20815fa..e01a972252 100644 --- a/src/i18n/languages/nlNL.ts +++ b/src/i18n/languages/nlNL.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#WAARDE!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ABS', ACOS: 'BOOGCOS', ACOSH: 'BOOGCOSH', diff --git a/src/i18n/languages/plPL.ts b/src/i18n/languages/plPL.ts index 937bc50d4b..54750ce876 100644 --- a/src/i18n/languages/plPL.ts +++ b/src/i18n/languages/plPL.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#ARG!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'WART.BEZWGL', ACOS: 'ACOS', ACOSH: 'ACOSH', diff --git a/src/i18n/languages/ptPT.ts b/src/i18n/languages/ptPT.ts index ad74cd5e01..a44e97a8ef 100644 --- a/src/i18n/languages/ptPT.ts +++ b/src/i18n/languages/ptPT.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#VALOR!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ABS', ACOS: 'ACOS', ACOSH: 'ACOSH', diff --git a/src/i18n/languages/ruRU.ts b/src/i18n/languages/ruRU.ts index 53d64da74c..8d9531d6fa 100644 --- a/src/i18n/languages/ruRU.ts +++ b/src/i18n/languages/ruRU.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#ЗНАЧ!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ABS', ACOS: 'ACOS', ACOSH: 'ACOSH', diff --git a/src/i18n/languages/svSE.ts b/src/i18n/languages/svSE.ts index adeda0e472..f1dd13a2fe 100644 --- a/src/i18n/languages/svSE.ts +++ b/src/i18n/languages/svSE.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#VÄRDEFEL!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'ABS', ACOS: 'ARCCOS', ACOSH: 'ARCCOSH', diff --git a/src/i18n/languages/trTR.ts b/src/i18n/languages/trTR.ts index 898d19df27..9994fa4afe 100644 --- a/src/i18n/languages/trTR.ts +++ b/src/i18n/languages/trTR.ts @@ -18,6 +18,7 @@ const dictionary: RawTranslationPackage = { VALUE: '#DEĞER!', }, functions: { + ARRAYFORMULA: 'ARRAYFORMULA', ABS: 'MUTLAK', ACOS: 'ACOS', ACOSH: 'ACOSH', diff --git a/src/interpreter/FunctionRegistry.ts b/src/interpreter/FunctionRegistry.ts index 40dc3f4f60..ba6f537e01 100644 --- a/src/interpreter/FunctionRegistry.ts +++ b/src/interpreter/FunctionRegistry.ts @@ -155,6 +155,7 @@ export class FunctionRegistry { private readonly functions: Map = new Map() private readonly volatileFunctions: Set = new Set() + private readonly arrayFunctions: Set = new Set() private readonly structuralChangeFunctions: Set = new Set() private readonly functionsWhichDoesNotNeedArgumentsToBeComputed: Set = new Set() @@ -216,22 +217,21 @@ export class FunctionRegistry { return Array.from(this.functions.keys()) } - public doesFunctionNeedArgumentToBeComputed = (functionId: string): boolean => { - return this.functionsWhichDoesNotNeedArgumentsToBeComputed.has(functionId) - } + public doesFunctionNeedArgumentToBeComputed = (functionId: string): boolean => this.functionsWhichDoesNotNeedArgumentsToBeComputed.has(functionId) - public isFunctionVolatile = (functionId: string): boolean => { - return this.volatileFunctions.has(functionId) - } + public isFunctionVolatile = (functionId: string): boolean => this.volatileFunctions.has(functionId) - public isFunctionDependentOnSheetStructureChange = (functionId: string): boolean => { - return this.structuralChangeFunctions.has(functionId) - } + public isArrayFunction = (functionId: string): boolean => this.arrayFunctions.has(functionId) + + public isFunctionDependentOnSheetStructureChange = (functionId: string): boolean => this.structuralChangeFunctions.has(functionId) private categorizeFunction(functionId: string, functionMetadata: FunctionMetadata): void { if (functionMetadata.isVolatile) { this.volatileFunctions.add(functionId) } + if (functionMetadata.arrayFunction) { + this.arrayFunctions.add(functionId) + } if (functionMetadata.doesNotNeedArgumentsToBeComputed) { this.functionsWhichDoesNotNeedArgumentsToBeComputed.add(functionId) } diff --git a/src/interpreter/Interpreter.ts b/src/interpreter/Interpreter.ts index e49ef8d727..00e5a39942 100644 --- a/src/interpreter/Interpreter.ts +++ b/src/interpreter/Interpreter.ts @@ -22,6 +22,7 @@ import {Statistics} from '../statistics/Statistics' import {ArithmeticHelper, coerceScalarToString, fixNegativeZero, isNumberOverflow} from './ArithmeticHelper' import {CriterionBuilder} from './Criterion' import {FunctionRegistry} from './FunctionRegistry' +import {InterpreterState} from './InterpreterState' import { cloneNumber, EmptyValue, @@ -30,6 +31,7 @@ import { InterpreterValue, isExtendedNumber, } from './InterpreterValue' +import {FunctionPlugin, PluginFunctionType} from './plugin/FunctionPlugin' import {ArrayData, SimpleRangeValue} from './SimpleRangeValue' export class Interpreter { @@ -53,8 +55,8 @@ export class Interpreter { this.criterionBuilder = new CriterionBuilder(config) } - public evaluateAst(ast: Ast, formulaAddress: SimpleCellAddress): InterpreterValue { - let val = this.evaluateAstWithoutPostprocessing(ast, formulaAddress) + public evaluateAst(ast: Ast, state: InterpreterState): InterpreterValue { + let val = this.evaluateAstWithoutPostprocessing(ast, state) if (isExtendedNumber(val)) { if (isNumberOverflow(getRawValue(val))) { return new CellError(ErrorType.NUM, ErrorMessage.NaN) @@ -62,7 +64,7 @@ export class Interpreter { val = cloneNumber(val, fixNegativeZero(getRawValue(val))) } } - return wrapperForAddress(val, formulaAddress) + return wrapperForAddress(val, state.formulaAddress) } /** @@ -71,13 +73,13 @@ export class Interpreter { * @param formula - abstract syntax tree of formula * @param formulaAddress - address of the cell in which formula is located */ - private evaluateAstWithoutPostprocessing(ast: Ast, formulaAddress: SimpleCellAddress): InterpreterValue { + private evaluateAstWithoutPostprocessing(ast: Ast, state: InterpreterState): InterpreterValue { switch (ast.type) { case AstNodeType.EMPTY: { return EmptyValue } case AstNodeType.CELL_REFERENCE: { - const address = ast.reference.toSimpleCellAddress(formulaAddress) + const address = ast.reference.toSimpleCellAddress(state.formulaAddress) if (invalidSimpleCellAddress(address)) { return new CellError(ErrorType.REF, ErrorMessage.BadRef) } @@ -88,76 +90,76 @@ export class Interpreter { return ast.value } case AstNodeType.CONCATENATE_OP: { - const leftResult = this.evaluateAst(ast.left, formulaAddress) - const rightResult = this.evaluateAst(ast.right, formulaAddress) - return this.binaryRangeWrapper(this.concatOp, leftResult, rightResult) + const leftResult = this.evaluateAst(ast.left, state) + const rightResult = this.evaluateAst(ast.right, state) + return this.binaryRangeWrapper(this.concatOp, leftResult, rightResult, state) } case AstNodeType.EQUALS_OP: { - const leftResult = this.evaluateAst(ast.left, formulaAddress) - const rightResult = this.evaluateAst(ast.right, formulaAddress) - return this.binaryRangeWrapper(this.equalOp, leftResult, rightResult) + const leftResult = this.evaluateAst(ast.left, state) + const rightResult = this.evaluateAst(ast.right, state) + return this.binaryRangeWrapper(this.equalOp, leftResult, rightResult, state) } case AstNodeType.NOT_EQUAL_OP: { - const leftResult = this.evaluateAst(ast.left, formulaAddress) - const rightResult = this.evaluateAst(ast.right, formulaAddress) - return this.binaryRangeWrapper(this.notEqualOp, leftResult, rightResult) + const leftResult = this.evaluateAst(ast.left, state) + const rightResult = this.evaluateAst(ast.right, state) + return this.binaryRangeWrapper(this.notEqualOp, leftResult, rightResult, state) } case AstNodeType.GREATER_THAN_OP: { - const leftResult = this.evaluateAst(ast.left, formulaAddress) - const rightResult = this.evaluateAst(ast.right, formulaAddress) - return this.binaryRangeWrapper(this.greaterThanOp, leftResult, rightResult) + const leftResult = this.evaluateAst(ast.left, state) + const rightResult = this.evaluateAst(ast.right, state) + return this.binaryRangeWrapper(this.greaterThanOp, leftResult, rightResult, state) } case AstNodeType.LESS_THAN_OP: { - const leftResult = this.evaluateAst(ast.left, formulaAddress) - const rightResult = this.evaluateAst(ast.right, formulaAddress) - return this.binaryRangeWrapper(this.lessThanOp, leftResult, rightResult) + const leftResult = this.evaluateAst(ast.left, state) + const rightResult = this.evaluateAst(ast.right, state) + return this.binaryRangeWrapper(this.lessThanOp, leftResult, rightResult, state) } case AstNodeType.GREATER_THAN_OR_EQUAL_OP: { - const leftResult = this.evaluateAst(ast.left, formulaAddress) - const rightResult = this.evaluateAst(ast.right, formulaAddress) - return this.binaryRangeWrapper(this.greaterThanOrEqualOp, leftResult, rightResult) + const leftResult = this.evaluateAst(ast.left, state) + const rightResult = this.evaluateAst(ast.right, state) + return this.binaryRangeWrapper(this.greaterThanOrEqualOp, leftResult, rightResult, state) } case AstNodeType.LESS_THAN_OR_EQUAL_OP: { - const leftResult = this.evaluateAst(ast.left, formulaAddress) - const rightResult = this.evaluateAst(ast.right, formulaAddress) - return this.binaryRangeWrapper(this.lessThanOrEqualOp, leftResult, rightResult) + const leftResult = this.evaluateAst(ast.left, state) + const rightResult = this.evaluateAst(ast.right, state) + return this.binaryRangeWrapper(this.lessThanOrEqualOp, leftResult, rightResult, state) } case AstNodeType.PLUS_OP: { - const leftResult = this.evaluateAst(ast.left, formulaAddress) - const rightResult = this.evaluateAst(ast.right, formulaAddress) - return this.binaryRangeWrapper(this.plusOp, leftResult, rightResult) + const leftResult = this.evaluateAst(ast.left, state) + const rightResult = this.evaluateAst(ast.right, state) + return this.binaryRangeWrapper(this.plusOp, leftResult, rightResult, state) } case AstNodeType.MINUS_OP: { - const leftResult = this.evaluateAst(ast.left, formulaAddress) - const rightResult = this.evaluateAst(ast.right, formulaAddress) - return this.binaryRangeWrapper(this.minusOp, leftResult, rightResult) + const leftResult = this.evaluateAst(ast.left, state) + const rightResult = this.evaluateAst(ast.right, state) + return this.binaryRangeWrapper(this.minusOp, leftResult, rightResult, state) } case AstNodeType.TIMES_OP: { - const leftResult = this.evaluateAst(ast.left, formulaAddress) - const rightResult = this.evaluateAst(ast.right, formulaAddress) - return this.binaryRangeWrapper(this.timesOp, leftResult, rightResult) + const leftResult = this.evaluateAst(ast.left, state) + const rightResult = this.evaluateAst(ast.right, state) + return this.binaryRangeWrapper(this.timesOp, leftResult, rightResult, state) } case AstNodeType.POWER_OP: { - const leftResult = this.evaluateAst(ast.left, formulaAddress) - const rightResult = this.evaluateAst(ast.right, formulaAddress) - return this.binaryRangeWrapper(this.powerOp, leftResult, rightResult) + const leftResult = this.evaluateAst(ast.left, state) + const rightResult = this.evaluateAst(ast.right, state) + return this.binaryRangeWrapper(this.powerOp, leftResult, rightResult, state) } case AstNodeType.DIV_OP: { - const leftResult = this.evaluateAst(ast.left, formulaAddress) - const rightResult = this.evaluateAst(ast.right, formulaAddress) - return this.binaryRangeWrapper(this.divOp, leftResult, rightResult) + const leftResult = this.evaluateAst(ast.left, state) + const rightResult = this.evaluateAst(ast.right, state) + return this.binaryRangeWrapper(this.divOp, leftResult, rightResult, state) } case AstNodeType.PLUS_UNARY_OP: { - const result = this.evaluateAst(ast.value, formulaAddress) - return this.unaryRangeWrapper(this.unaryPlusOp, result) + const result = this.evaluateAst(ast.value, state) + return this.unaryRangeWrapper(this.unaryPlusOp, result, state) } case AstNodeType.MINUS_UNARY_OP: { - const result = this.evaluateAst(ast.value, formulaAddress) - return this.unaryRangeWrapper(this.unaryMinusOp, result) + const result = this.evaluateAst(ast.value, state) + return this.unaryRangeWrapper(this.unaryMinusOp, result, state) } case AstNodeType.PERCENT_OP: { - const result = this.evaluateAst(ast.value, formulaAddress) - return this.unaryRangeWrapper(this.percentOp, result) + const result = this.evaluateAst(ast.value, state) + return this.unaryRangeWrapper(this.percentOp, result, state) } case AstNodeType.FUNCTION_CALL: { if (this.config.licenseKeyValidityState !== LicenseKeyValidityState.VALID && !FunctionRegistry.functionIsProtected(ast.procedureName)) { @@ -165,14 +167,14 @@ export class Interpreter { } const pluginEntry = this.functionRegistry.getFunction(ast.procedureName) if (pluginEntry && this.config.translationPackage.isFunctionTranslated(ast.procedureName)) { - const [pluginFunction, pluginInstance] = pluginEntry as [string, any] - return pluginInstance[pluginFunction](ast, formulaAddress) + const [pluginFunction, pluginInstance] = pluginEntry + return (pluginInstance as any as Record)[pluginFunction](ast, new InterpreterState(state.formulaAddress, state.arraysFlag || this.functionRegistry.isArrayFunction(ast.procedureName))) } else { return new CellError(ErrorType.NAME, ErrorMessage.FunctionName(ast.procedureName)) } } case AstNodeType.NAMED_EXPRESSION: { - const namedExpression = this.namedExpressions.nearestNamedExpression(ast.expressionName, formulaAddress.sheet) + const namedExpression = this.namedExpressions.nearestNamedExpression(ast.expressionName, state.formulaAddress.sheet) if (namedExpression) { return this.dependencyGraph.getCellValue(namedExpression.address) } else { @@ -183,7 +185,7 @@ export class Interpreter { if (!this.rangeSpansOneSheet(ast)) { return new CellError(ErrorType.REF, ErrorMessage.RangeManySheets) } - const range = AbsoluteCellRange.fromCellRange(ast, formulaAddress) + const range = AbsoluteCellRange.fromCellRange(ast, state.formulaAddress) const matrixVertex = this.dependencyGraph.getMatrix(range) if (matrixVertex) { const matrix = matrixVertex.matrix @@ -204,18 +206,18 @@ export class Interpreter { if (!this.rangeSpansOneSheet(ast)) { return new CellError(ErrorType.REF, ErrorMessage.RangeManySheets) } - const range = AbsoluteColumnRange.fromColumnRange(ast, formulaAddress) + const range = AbsoluteColumnRange.fromColumnRange(ast, state.formulaAddress) return SimpleRangeValue.onlyRange(range, this.dependencyGraph) } case AstNodeType.ROW_RANGE: { if (!this.rangeSpansOneSheet(ast)) { return new CellError(ErrorType.REF, ErrorMessage.RangeManySheets) } - const range = AbsoluteRowRange.fromRowRange(ast, formulaAddress) + const range = AbsoluteRowRange.fromRowRange(ast, state.formulaAddress) return SimpleRangeValue.onlyRange(range, this.dependencyGraph) } case AstNodeType.PARENTHESIS: { - return this.evaluateAst(ast.expression, formulaAddress) + return this.evaluateAst(ast.expression, state) } case AstNodeType.ERROR_WITH_RAW_INPUT: case AstNodeType.ERROR: { @@ -316,11 +318,11 @@ export class Interpreter { private unaryPlusOp = (arg: InternalScalarValue): InternalScalarValue => this.arithmeticHelper.unaryPlus(arg) - private unaryRangeWrapper(op: (arg: InternalScalarValue) => InternalScalarValue, arg: InterpreterValue): InterpreterValue { + private unaryRangeWrapper(op: (arg: InternalScalarValue) => InternalScalarValue, arg: InterpreterValue, state: InterpreterState): InterpreterValue { if (arg instanceof CellError) { return arg } else if(arg instanceof SimpleRangeValue) { - if(!this.config.arrays) { + if(!state.arraysFlag) { return new CellError(ErrorType.VALUE, ErrorMessage.ScalarExpected) } const newRaw = arg.raw().map( @@ -332,14 +334,14 @@ export class Interpreter { } } - private binaryRangeWrapper(op: (arg1: InternalScalarValue, arg2: InternalScalarValue) => InternalScalarValue, arg1: InterpreterValue, arg2: InterpreterValue): InterpreterValue { + private binaryRangeWrapper(op: (arg1: InternalScalarValue, arg2: InternalScalarValue) => InternalScalarValue, arg1: InterpreterValue, arg2: InterpreterValue, state: InterpreterState): InterpreterValue { if (arg1 instanceof CellError) { return arg1 - } else if(arg1 instanceof SimpleRangeValue && !this.config.arrays) { + } else if(arg1 instanceof SimpleRangeValue && !state.arraysFlag) { return new CellError(ErrorType.VALUE, ErrorMessage.ScalarExpected) } else if (arg2 instanceof CellError) { return arg2 - } else if(arg2 instanceof SimpleRangeValue && !this.config.arrays) { + } else if(arg2 instanceof SimpleRangeValue && !state.arraysFlag) { return new CellError(ErrorType.VALUE, ErrorMessage.ScalarExpected) } else if(arg1 instanceof SimpleRangeValue || arg2 instanceof SimpleRangeValue) { if(!(arg1 instanceof SimpleRangeValue)) { diff --git a/src/interpreter/InterpreterState.ts b/src/interpreter/InterpreterState.ts new file mode 100644 index 0000000000..c5042f83e9 --- /dev/null +++ b/src/interpreter/InterpreterState.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright (c) 2021 Handsoncode. All rights reserved. + */ + +import {SimpleCellAddress} from '../Cell' + +/** + * @license + * Copyright (c) 2021 Handsoncode. All rights reserved. + */ + +export class InterpreterState { + constructor(public formulaAddress: SimpleCellAddress, public arraysFlag: boolean) { + } +} + diff --git a/src/interpreter/plugin/AbsPlugin.ts b/src/interpreter/plugin/AbsPlugin.ts index 83a1ecc001..6e14f48257 100644 --- a/src/interpreter/plugin/AbsPlugin.ts +++ b/src/interpreter/plugin/AbsPlugin.ts @@ -3,12 +3,12 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class AbsPlugin extends FunctionPlugin { +export class AbsPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'ABS': { method: 'abs', @@ -18,7 +18,7 @@ export class AbsPlugin extends FunctionPlugin { }, } - public abs(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ABS'), Math.abs) + public abs(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ABS'), Math.abs) } } diff --git a/src/interpreter/plugin/ArrayFormulaPlugin.ts b/src/interpreter/plugin/ArrayFormulaPlugin.ts new file mode 100644 index 0000000000..2738ff51c5 --- /dev/null +++ b/src/interpreter/plugin/ArrayFormulaPlugin.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright (c) 2021 Handsoncode. All rights reserved. + */ + +import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' +import {InternalScalarValue} from '../InterpreterValue' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' + +export class ArrayFormulaPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ + public static implementedFunctions = { + 'ARRAYFORMULA': { + method: 'arrayformula', + arrayFunction: true, + parameters: [ + {argumentType: ArgumentTypes.ANY} + ], + }, + } + + public arrayformula(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ARRAYFORMULA'), (value) => value) + } +} diff --git a/src/interpreter/plugin/BitShiftPlugin.ts b/src/interpreter/plugin/BitShiftPlugin.ts index 00803c3c72..f8655fc928 100644 --- a/src/interpreter/plugin/BitShiftPlugin.ts +++ b/src/interpreter/plugin/BitShiftPlugin.ts @@ -3,17 +3,18 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck, PluginFunctionType} from './FunctionPlugin' const MAX_48BIT_INTEGER = 281474976710655 const SHIFT_MIN_POSITIONS = -53 const SHIFT_MAX_POSITIONS = 53 -export class BitShiftPlugin extends FunctionPlugin { +export class BitShiftPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'BITLSHIFT': { method: 'bitlshift', @@ -31,12 +32,12 @@ export class BitShiftPlugin extends FunctionPlugin { }, } - public bitlshift(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BITLSHIFT'), shiftLeft) + public bitlshift(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BITLSHIFT'), shiftLeft) } - public bitrshift(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BITRSHIFT'), shiftRight) + public bitrshift(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BITRSHIFT'), shiftRight) } } diff --git a/src/interpreter/plugin/BitwiseLogicOperationsPlugin.ts b/src/interpreter/plugin/BitwiseLogicOperationsPlugin.ts index 704ae2a41d..8a2f90c540 100644 --- a/src/interpreter/plugin/BitwiseLogicOperationsPlugin.ts +++ b/src/interpreter/plugin/BitwiseLogicOperationsPlugin.ts @@ -3,12 +3,12 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class BitwiseLogicOperationsPlugin extends FunctionPlugin { +export class BitwiseLogicOperationsPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'BITAND': { method: 'bitand', @@ -33,20 +33,20 @@ export class BitwiseLogicOperationsPlugin extends FunctionPlugin { }, } - public bitand(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BITAND'), + public bitand(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BITAND'), (left: number, right: number) => left & right ) } - public bitor(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BITOR'), + public bitor(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BITOR'), (left: number, right: number) => left | right ) } - public bitxor(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BITXOR'), + public bitxor(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BITXOR'), (left: number, right: number) => left ^ right ) } diff --git a/src/interpreter/plugin/BooleanPlugin.ts b/src/interpreter/plugin/BooleanPlugin.ts index f55ad6d7b8..cf97d92c77 100644 --- a/src/interpreter/plugin/BooleanPlugin.ts +++ b/src/interpreter/plugin/BooleanPlugin.ts @@ -3,16 +3,17 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalNoErrorScalarValue, InternalScalarValue, InterpreterValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' /** * Interpreter plugin containing boolean functions */ -export class BooleanPlugin extends FunctionPlugin { +export class BooleanPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'TRUE': { method: 'literalTrue', @@ -99,10 +100,10 @@ export class BooleanPlugin extends FunctionPlugin { * Returns the logical true * * @param ast - * @param formulaAddress + * @param state */ - public literalTrue(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('TRUE'), () => true) + public literalTrue(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('TRUE'), () => true) } /** @@ -111,10 +112,10 @@ export class BooleanPlugin extends FunctionPlugin { * Returns the logical false * * @param ast - * @param formulaAddress + * @param state */ - public literalFalse(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('FALSE'), () => false) + public literalFalse(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('FALSE'), () => false) } /** @@ -123,10 +124,10 @@ export class BooleanPlugin extends FunctionPlugin { * Returns value specified as second argument if expression is true and third argument if expression is false * * @param ast - * @param formulaAddress + * @param state */ - public conditionalIf(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InterpreterValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IF'), (condition, arg2, arg3) => { + public conditionalIf(ast: ProcedureAst, state: InterpreterState): InterpreterValue { + return this.runFunction(ast.args, state, this.metadata('IF'), (condition, arg2, arg3) => { return condition ? arg2 : arg3 }) } @@ -137,10 +138,10 @@ export class BooleanPlugin extends FunctionPlugin { * Returns true if all of the provided arguments are logically true, and false if any of it is logically false * * @param ast - * @param formulaAddress + * @param state */ - public and(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('AND'), + public and(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('AND'), (...args) => !args.some((arg: boolean) => !arg) ) } @@ -151,20 +152,20 @@ export class BooleanPlugin extends FunctionPlugin { * Returns true if any of the provided arguments are logically true, and false otherwise * * @param ast - * @param formulaAddress + * @param state */ - public or(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('OR'), + public or(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('OR'), (...args) => args.some((arg: boolean) => arg) ) } - public not(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('NOT'), (arg) => !arg) + public not(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('NOT'), (arg) => !arg) } - public xor(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('XOR'), (...args) => { + public xor(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('XOR'), (...args) => { let cnt = 0 args.forEach((arg: boolean) => { if (arg) { @@ -175,8 +176,8 @@ export class BooleanPlugin extends FunctionPlugin { }) } - public switch(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SWITCH'), (selector, ...args) => { + public switch(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SWITCH'), (selector, ...args) => { const n = args.length let i = 0 for (; i + 1 < n; i += 2) { @@ -195,8 +196,8 @@ export class BooleanPlugin extends FunctionPlugin { }) } - public iferror(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IFERROR'), (arg1: InternalScalarValue, arg2: InternalScalarValue) => { + public iferror(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IFERROR'), (arg1: InternalScalarValue, arg2: InternalScalarValue) => { if (arg1 instanceof CellError) { return arg2 } else { @@ -205,8 +206,8 @@ export class BooleanPlugin extends FunctionPlugin { }) } - public ifna(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IFNA'), (arg1: InternalScalarValue, arg2: InternalScalarValue) => { + public ifna(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IFNA'), (arg1: InternalScalarValue, arg2: InternalScalarValue) => { if (arg1 instanceof CellError && arg1.type === ErrorType.NA) { return arg2 } else { @@ -215,8 +216,8 @@ export class BooleanPlugin extends FunctionPlugin { }) } - public choose(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CHOOSE'), (selector, ...args) => { + public choose(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CHOOSE'), (selector, ...args) => { if (selector > args.length) { return new CellError(ErrorType.NUM, ErrorMessage.Selector) } diff --git a/src/interpreter/plugin/CharPlugin.ts b/src/interpreter/plugin/CharPlugin.ts index 698ebb442f..25b63932cf 100644 --- a/src/interpreter/plugin/CharPlugin.ts +++ b/src/interpreter/plugin/CharPlugin.ts @@ -3,13 +3,14 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class CharPlugin extends FunctionPlugin { +export class CharPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'CHAR': { method: 'char', @@ -25,8 +26,8 @@ export class CharPlugin extends FunctionPlugin { }, } - public char(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CHAR'), (value: number) => { + public char(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CHAR'), (value: number) => { if (value < 1 || value >= 256) { return new CellError(ErrorType.VALUE, ErrorMessage.CharacterCodeBounds) } @@ -35,8 +36,8 @@ export class CharPlugin extends FunctionPlugin { }) } - public unichar(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CHAR'), (value: number) => { + public unichar(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CHAR'), (value: number) => { if (value < 1 || value >= 1114112) { return new CellError(ErrorType.VALUE, ErrorMessage.CharacterCodeBounds) } diff --git a/src/interpreter/plugin/CodePlugin.ts b/src/interpreter/plugin/CodePlugin.ts index c1bfcb58a2..68603c47d7 100644 --- a/src/interpreter/plugin/CodePlugin.ts +++ b/src/interpreter/plugin/CodePlugin.ts @@ -3,13 +3,14 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class CodePlugin extends FunctionPlugin { +export class CodePlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'CODE': { method: 'code', @@ -25,8 +26,8 @@ export class CodePlugin extends FunctionPlugin { }, } - public code(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CODE'), (value: string) => { + public code(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CODE'), (value: string) => { if (value.length === 0) { return new CellError(ErrorType.VALUE, ErrorMessage.EmptyString) } @@ -34,8 +35,8 @@ export class CodePlugin extends FunctionPlugin { }) } - public unicode(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('UNICODE'), (value: string) => { + public unicode(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('UNICODE'), (value: string) => { return value.codePointAt(0) ?? new CellError(ErrorType.VALUE, ErrorMessage.EmptyString) }) } diff --git a/src/interpreter/plugin/ComplexPlugin.ts b/src/interpreter/plugin/ComplexPlugin.ts index 5e7327e2ac..460c341187 100644 --- a/src/interpreter/plugin/ComplexPlugin.ts +++ b/src/interpreter/plugin/ComplexPlugin.ts @@ -3,14 +3,15 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' import {coerceComplexToString, complex} from '../ArithmeticHelper' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue, RawInterpreterValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class ComplexPlugin extends FunctionPlugin { +export class ComplexPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'COMPLEX': { method: 'complex', @@ -177,8 +178,8 @@ export class ComplexPlugin extends FunctionPlugin { }, } - public complex(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('COMPLEX'), + public complex(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('COMPLEX'), (re: number, im: number, unit: string) => { if(unit !== 'i' && unit !== 'j') { return new CellError(ErrorType.VALUE, ErrorMessage.ShouldBeIorJ) @@ -188,24 +189,24 @@ export class ComplexPlugin extends FunctionPlugin { ) } - public imabs(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMABS'), abs) + public imabs(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMABS'), abs) } - public imaginary(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMAGINARY'), + public imaginary(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMAGINARY'), ([re, im]: complex) => im ) } - public imreal(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMREAL'), + public imreal(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMREAL'), ([re, im]: complex) => re ) } - public imargument(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMARGUMENT'), + public imargument(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMARGUMENT'), ([re, im]: complex) => { if(re===0 && im===0) { return new CellError(ErrorType.DIV_BY_ZERO) @@ -215,80 +216,80 @@ export class ComplexPlugin extends FunctionPlugin { ) } - public imconjugate(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMCONJUGATE'), + public imconjugate(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMCONJUGATE'), ([re, im]: complex) => coerceComplexToString([re, -im]) ) } - public imcos(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMCOS'), + public imcos(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMCOS'), (arg: complex) => coerceComplexToString(cos(arg)) ) } - public imcosh(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMCOSH'), + public imcosh(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMCOSH'), (arg: complex) => coerceComplexToString(cosh(arg)) ) } - public imcot(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMCOT'), + public imcot(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMCOT'), (arg: complex) => coerceComplexToString(div(cos(arg), sin(arg))) ) } - public imcsc(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMCSC'), + public imcsc(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMCSC'), (arg: complex) => coerceComplexToString(div([1, 0], sin(arg))) ) } - public imcsch(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMCSCH'), + public imcsch(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMCSCH'), (arg: complex) => coerceComplexToString(div([1, 0], sinh(arg))) ) } - public imsec(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMSEC'), + public imsec(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMSEC'), (arg: complex) => coerceComplexToString(div([1, 0], cos(arg))) ) } - public imsech(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMSECH'), + public imsech(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMSECH'), (arg: complex) => coerceComplexToString(div([1, 0], cosh(arg))) ) } - public imsin(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMSIN'), + public imsin(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMSIN'), (arg: complex) => coerceComplexToString(sin(arg)) ) } - public imsinh(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMSINH'), + public imsinh(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMSINH'), (arg: complex) => coerceComplexToString(sinh(arg)) ) } - public imtan(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMTAN'), + public imtan(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMTAN'), (arg: complex) => coerceComplexToString(div(sin(arg), cos(arg))) ) } - public imdiv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMDIV'), + public imdiv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMDIV'), (arg1: complex, arg2: complex) => coerceComplexToString(div(arg1, arg2)) ) } - public improduct(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMPRODUCT'), + public improduct(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMPRODUCT'), (...args: RawInterpreterValue[]) => { const coerced = this.interpreter.arithmeticHelper.coerceComplexExactRanges(args) if (coerced instanceof CellError) { @@ -303,8 +304,8 @@ export class ComplexPlugin extends FunctionPlugin { ) } - public imsum(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMSUM'), + public imsum(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMSUM'), (...args: RawInterpreterValue[]) => { const coerced = this.interpreter.arithmeticHelper.coerceComplexExactRanges(args) if (coerced instanceof CellError) { @@ -319,26 +320,26 @@ export class ComplexPlugin extends FunctionPlugin { ) } - public imsub(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMSUB'), + public imsub(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMSUB'), (arg1: complex, arg2: complex) => coerceComplexToString(sub(arg1, arg2)) ) } - public imexp(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMEXP'), + public imexp(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMEXP'), (arg: complex) => coerceComplexToString(exp(arg)) ) } - public imln(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMLN'), + public imln(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMLN'), (arg: complex) => coerceComplexToString(ln(arg)) ) } - public imlog10(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMLOG10'), + public imlog10(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMLOG10'), (arg: complex) => { const [re, im] = ln(arg) const c = Math.log(10) @@ -347,8 +348,8 @@ export class ComplexPlugin extends FunctionPlugin { ) } - public imlog2(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMLOG2'), + public imlog2(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMLOG2'), (arg: complex) => { const [re, im] = ln(arg) const c = Math.log(2) @@ -357,14 +358,14 @@ export class ComplexPlugin extends FunctionPlugin { ) } - public impower(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMPOWER'), + public impower(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMPOWER'), (arg: complex, n: number) => coerceComplexToString(power(arg, n)) ) } - public imsqrt(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IMSQRT'), + public imsqrt(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IMSQRT'), (arg: complex) => coerceComplexToString(power(arg, 0.5)) ) } diff --git a/src/interpreter/plugin/CountBlankPlugin.ts b/src/interpreter/plugin/CountBlankPlugin.ts index 65164c66db..812dd59256 100644 --- a/src/interpreter/plugin/CountBlankPlugin.ts +++ b/src/interpreter/plugin/CountBlankPlugin.ts @@ -3,15 +3,15 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {EmptyValue, InternalScalarValue, RawScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' /** * Interpreter plugin containing MEDIAN function */ -export class CountBlankPlugin extends FunctionPlugin { +export class CountBlankPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'COUNTBLANK': { @@ -24,8 +24,8 @@ export class CountBlankPlugin extends FunctionPlugin { }, } - public countblank(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('COUNTBLANK'), (...args: RawScalarValue[]) => { + public countblank(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('COUNTBLANK'), (...args: RawScalarValue[]) => { let counter = 0 args.forEach((arg) => { if(arg === EmptyValue) { diff --git a/src/interpreter/plugin/CountUniquePlugin.ts b/src/interpreter/plugin/CountUniquePlugin.ts index 1613871475..929619dc0c 100644 --- a/src/interpreter/plugin/CountUniquePlugin.ts +++ b/src/interpreter/plugin/CountUniquePlugin.ts @@ -3,15 +3,16 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {EmptyValueType, InternalScalarValue, RawScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' /** * Interpreter plugin containing COUNTUNIQUE function */ -export class CountUniquePlugin extends FunctionPlugin { +export class CountUniquePlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'COUNTUNIQUE': { method: 'countunique', @@ -29,10 +30,10 @@ export class CountUniquePlugin extends FunctionPlugin { * Returns number of unique numbers from arguments * * @param ast - * @param formulaAddress + * @param state */ - public countunique(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('COUNTUNIQUE'), (...args: RawScalarValue[]) => { + public countunique(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('COUNTUNIQUE'), (...args: RawScalarValue[]) => { const valuesSet = new Set() const errorsSet = new Set() diff --git a/src/interpreter/plugin/DateTimePlugin.ts b/src/interpreter/plugin/DateTimePlugin.ts index 5c31bf121e..67c643f3cd 100644 --- a/src/interpreter/plugin/DateTimePlugin.ts +++ b/src/interpreter/plugin/DateTimePlugin.ts @@ -3,7 +3,7 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import { instanceOfSimpleDate, instanceOfSimpleTime, @@ -19,6 +19,7 @@ import {ErrorMessage} from '../../error-message' import {format} from '../../format/format' import {Maybe} from '../../Maybe' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import { EmptyValue, getRawValue, @@ -30,12 +31,12 @@ import { RawScalarValue, } from '../InterpreterValue' import {SimpleRangeValue} from '../SimpleRangeValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' /** * Interpreter plugin containing date-specific functions */ -export class DateTimePlugin extends FunctionPlugin { +export class DateTimePlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'DATE': { method: 'date', @@ -239,10 +240,10 @@ export class DateTimePlugin extends FunctionPlugin { * Converts a provided year, month and day into date * * @param ast - * @param formulaAddress + * @param state */ - public date(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DATE'), (year, month, day) => { + public date(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DATE'), (year, month, day) => { const d = Math.trunc(day) let m = Math.trunc(month) let y = Math.trunc(year) @@ -266,8 +267,8 @@ export class DateTimePlugin extends FunctionPlugin { }) } - public time(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('TIME'), + public time(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('TIME'), (h, m, s) => { const ret = timeToNumber({hours: Math.trunc(h), minutes: Math.trunc(m), seconds: Math.trunc(s)}) if(ret<0) { @@ -278,8 +279,8 @@ export class DateTimePlugin extends FunctionPlugin { ) } - public eomonth(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('EOMONTH'), (dateNumber, numberOfMonthsToShift) => { + public eomonth(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('EOMONTH'), (dateNumber, numberOfMonthsToShift) => { const date = this.interpreter.dateHelper.numberToSimpleDate(dateNumber) let ret: Maybe = this.interpreter.dateHelper.dateToNumber(this.interpreter.dateHelper.endOfMonth(offsetMonth(date, numberOfMonthsToShift))) ret = this.interpreter.dateHelper.getWithinBounds(ret) @@ -290,14 +291,14 @@ export class DateTimePlugin extends FunctionPlugin { }) } - public day(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DAY'), + public day(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DAY'), (dateNumber) => this.interpreter.dateHelper.numberToSimpleDate(dateNumber).day ) } - public days(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DAYS'), (endDate, startDate) => Math.trunc(endDate) - Math.trunc(startDate)) + public days(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DAYS'), (endDate, startDate) => Math.trunc(endDate) - Math.trunc(startDate)) } /** @@ -306,10 +307,10 @@ export class DateTimePlugin extends FunctionPlugin { * Returns the month of the year specified by a given date * * @param ast - * @param formulaAddress + * @param state */ - public month(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('MONTH'), + public month(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('MONTH'), (dateNumber) => this.interpreter.dateHelper.numberToSimpleDate(dateNumber).month ) } @@ -320,28 +321,28 @@ export class DateTimePlugin extends FunctionPlugin { * Returns the year specified by a given date * * @param ast - * @param formulaAddress + * @param state */ - public year(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('YEAR'), + public year(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('YEAR'), (dateNumber) => this.interpreter.dateHelper.numberToSimpleDate(dateNumber).year ) } - public hour(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HOUR'), + public hour(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HOUR'), (timeNumber) => numberToSimpleTime(roundToNearestSecond(timeNumber)%1).hours ) } - public minute(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('MINUTE'), + public minute(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('MINUTE'), (timeNumber) => numberToSimpleTime(roundToNearestSecond(timeNumber)%1).minutes ) } - public second(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SECOND'), + public second(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SECOND'), (timeNumber) => numberToSimpleTime(roundToNearestSecond(timeNumber)%1).seconds ) } @@ -352,16 +353,16 @@ export class DateTimePlugin extends FunctionPlugin { * Tries to convert number to specified date format. * * @param ast - * @param formulaAddress + * @param state */ - public text(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('TEXT'), + public text(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('TEXT'), (numberRepresentation, formatArg) => format(numberRepresentation, formatArg, this.config, this.interpreter.dateHelper) ) } - public weekday(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('WEEKDAY'), + public weekday(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('WEEKDAY'), (day: number, type: number) => { const absoluteDay = Math.floor(this.interpreter.dateHelper.relativeNumberToAbsoluteNumber(day)) if(type===3) { @@ -376,8 +377,8 @@ export class DateTimePlugin extends FunctionPlugin { ) } - public weeknum(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('WEEKNUM'), + public weeknum(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('WEEKNUM'), (day: number, type: number) => { const absoluteDay = Math.floor(this.interpreter.dateHelper.relativeNumberToAbsoluteNumber(day)) const date = this.interpreter.dateHelper.numberToSimpleDate(day) @@ -395,8 +396,8 @@ export class DateTimePlugin extends FunctionPlugin { ) } - public isoweeknum(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ISOWEEKNUM'), this.isoweeknumCore) + public isoweeknum(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ISOWEEKNUM'), this.isoweeknumCore) } private isoweeknumCore = (day: number): number => { @@ -412,8 +413,8 @@ export class DateTimePlugin extends FunctionPlugin { return ret } - public datevalue(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DATEVALUE'), + public datevalue(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DATEVALUE'), (date: string) => { const {dateTime} = this.interpreter.dateHelper.parseDateTimeFromConfigFormats(date) if(dateTime === undefined) { @@ -428,8 +429,8 @@ export class DateTimePlugin extends FunctionPlugin { ) } - public timevalue(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('TIMEVALUE'), + public timevalue(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('TIMEVALUE'), (date: string) => { const dateNumber = this.interpreter.dateHelper.dateStringToDateNumber(date) if(dateNumber===undefined){ @@ -440,8 +441,8 @@ export class DateTimePlugin extends FunctionPlugin { ) } - public now(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('NOW'), + public now(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('NOW'), () => { const now = new Date() return timeToNumber({hours: now.getHours(), minutes: now.getMinutes(), seconds: now.getSeconds()})+ @@ -450,8 +451,8 @@ export class DateTimePlugin extends FunctionPlugin { ) } - public today(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('TODAY'), + public today(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('TODAY'), () => { const now = new Date() return this.interpreter.dateHelper.dateToNumber({year: now.getFullYear(), month: now.getMonth()+1, day: now.getDay()}) @@ -459,8 +460,8 @@ export class DateTimePlugin extends FunctionPlugin { ) } - public edate(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('EDATE'), + public edate(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('EDATE'), (dateNumber: number, delta: number) => { const date = this.interpreter.dateHelper.numberToSimpleDate(dateNumber) const newDate = truncateDayInMonth(offsetMonth(date, delta)) @@ -474,8 +475,8 @@ export class DateTimePlugin extends FunctionPlugin { ) } - public datedif(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DATEDIF'), + public datedif(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DATEDIF'), (startDate: number, endDate: number, unit: string) => { if(startDate > endDate) { return new CellError(ErrorType.NUM, ErrorMessage.StartEndDate) @@ -521,8 +522,8 @@ export class DateTimePlugin extends FunctionPlugin { ) } - public days360(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DAYS360'), this.days360Core) + public days360(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DAYS360'), this.days360Core) } private days360Core = (startDate: number, endDate: number, mode: boolean): number => { @@ -538,8 +539,8 @@ export class DateTimePlugin extends FunctionPlugin { return 360 * (nEnd.year - nStart.year) + 30*(nEnd.month-nStart.month) + nEnd.day-nStart.day } - public yearfrac(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('YEARFRAC'), + public yearfrac(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('YEARFRAC'), (startDate: number, endDate: number, mode: number) => { startDate = Math.trunc(startDate) endDate = Math.trunc(endDate) @@ -566,8 +567,8 @@ export class DateTimePlugin extends FunctionPlugin { ) } - public interval(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('INTERVAL'), + public interval(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('INTERVAL'), (arg: number) => { arg = Math.trunc(arg) const second = arg%60 @@ -592,26 +593,26 @@ export class DateTimePlugin extends FunctionPlugin { ) } - public networkdays(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('NETWORKDAYS'), + public networkdays(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('NETWORKDAYS'), (start, end, holidays) => this.networkdayscore(start, end, 1, holidays) ) } - public networkdaysintl(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('NETWORKDAYS.INTL'), + public networkdaysintl(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('NETWORKDAYS.INTL'), (start, end, weekend, holidays) => this.networkdayscore(start, end, weekend, holidays) ) } - public workday(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('WORKDAY'), + public workday(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('WORKDAY'), (start, end, holidays) => this.workdaycore(start, end, 1, holidays) ) } - public workdayintl(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('WORKDAY.INTL'), + public workdayintl(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('WORKDAY.INTL'), (start, end, weekend, holidays) => this.workdaycore(start, end, weekend, holidays) ) } diff --git a/src/interpreter/plugin/DegreesPlugin.ts b/src/interpreter/plugin/DegreesPlugin.ts index deabb6d89b..d7167e4b6a 100644 --- a/src/interpreter/plugin/DegreesPlugin.ts +++ b/src/interpreter/plugin/DegreesPlugin.ts @@ -3,12 +3,12 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class DegreesPlugin extends FunctionPlugin { +export class DegreesPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'DEGREES': { method: 'degrees', @@ -18,8 +18,8 @@ export class DegreesPlugin extends FunctionPlugin { }, } - public degrees(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DEGREES'), + public degrees(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DEGREES'), (arg) => arg * (180 / Math.PI) ) } diff --git a/src/interpreter/plugin/DeltaPlugin.ts b/src/interpreter/plugin/DeltaPlugin.ts index d2b7cfcf93..8a96c567bc 100644 --- a/src/interpreter/plugin/DeltaPlugin.ts +++ b/src/interpreter/plugin/DeltaPlugin.ts @@ -3,12 +3,12 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class DeltaPlugin extends FunctionPlugin { +export class DeltaPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'DELTA': { method: 'delta', @@ -19,8 +19,8 @@ export class DeltaPlugin extends FunctionPlugin { }, } - public delta(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DELTA'), + public delta(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DELTA'), (left: number, right: number) => (left === right ? 1 : 0) ) } diff --git a/src/interpreter/plugin/ExpPlugin.ts b/src/interpreter/plugin/ExpPlugin.ts index c18d95b18c..9ce4d19ccc 100644 --- a/src/interpreter/plugin/ExpPlugin.ts +++ b/src/interpreter/plugin/ExpPlugin.ts @@ -3,12 +3,12 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class ExpPlugin extends FunctionPlugin { +export class ExpPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'EXP': { method: 'exp', @@ -24,9 +24,9 @@ export class ExpPlugin extends FunctionPlugin { * Calculates the exponent for basis e * * @param ast - * @param formulaAddress + * @param state */ - public exp(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('EXP'), Math.exp) + public exp(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('EXP'), Math.exp) } } diff --git a/src/interpreter/plugin/FinancialPlugin.ts b/src/interpreter/plugin/FinancialPlugin.ts index d75b9926ca..5389231d9c 100644 --- a/src/interpreter/plugin/FinancialPlugin.ts +++ b/src/interpreter/plugin/FinancialPlugin.ts @@ -3,9 +3,10 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import { EmptyValue, getRawValue, @@ -15,9 +16,9 @@ import { RawInterpreterValue } from '../InterpreterValue' import {SimpleRangeValue} from '../SimpleRangeValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class FinancialPlugin extends FunctionPlugin { +export class FinancialPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'PMT': { method: 'pmt', @@ -282,24 +283,24 @@ export class FinancialPlugin extends FunctionPlugin { }, } - public pmt(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('PMT'), pmtCore) + public pmt(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('PMT'), pmtCore) } - public ipmt(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('IPMT'), ipmtCore) + public ipmt(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('IPMT'), ipmtCore) } - public ppmt(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('PPMT'), ppmtCore) + public ppmt(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('PPMT'), ppmtCore) } - public fv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('FV'), fvCore) + public fv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('FV'), fvCore) } - public cumipmt(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CUMIPMT'), + public cumipmt(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CUMIPMT'), (rate: number, periods: number, value: number, start: number, end: number, type: number) => { if (start > end) { return new CellError(ErrorType.NUM, ErrorMessage.EndStartPeriod) @@ -313,8 +314,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public cumprinc(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CUMPRINC'), + public cumprinc(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CUMPRINC'), (rate: number, periods: number, value: number, start: number, end: number, type: number) => { if (start > end) { return new CellError(ErrorType.NUM, ErrorMessage.EndStartPeriod) @@ -328,8 +329,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public db(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DB'), + public db(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DB'), (cost: number, salvage: number, life: number, period: number, month: number) => { if ((month===12 && period > life) || (period > life+1)) { return new CellError(ErrorType.NUM, ErrorMessage.PeriodLong) @@ -360,8 +361,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public ddb(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DDB'), + public ddb(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DDB'), (cost: number, salvage: number, life: number, period: number, factor: number) => { if (period > life) { return new CellError(ErrorType.NUM) @@ -384,8 +385,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public dollarde(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DOLLARDE'), + public dollarde(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DOLLARDE'), (dollar, fraction) => { if (fraction < 1) { return new CellError(ErrorType.DIV_BY_ZERO) @@ -400,8 +401,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public dollarfr(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DOLLARFR'), + public dollarfr(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DOLLARFR'), (dollar, fraction) => { if (fraction < 1) { return new CellError(ErrorType.DIV_BY_ZERO) @@ -416,8 +417,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public effect(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('EFFECT'), + public effect(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('EFFECT'), (rate: number, periods: number) => { periods = Math.trunc(periods) return Math.pow(1 + rate / periods, periods) - 1 @@ -425,8 +426,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public ispmt(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ISPMT'), + public ispmt(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ISPMT'), (rate, period, periods, value) => { if(periods===0) { return new CellError(ErrorType.DIV_BY_ZERO) @@ -436,8 +437,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public nominal(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('NOMINAL'), + public nominal(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('NOMINAL'), (rate: number, periods: number) => { periods = Math.trunc(periods) return (Math.pow(rate + 1, 1 / periods) - 1) * periods @@ -445,8 +446,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public nper(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('NPER'), + public nper(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('NPER'), (rate, payment, present, future, type) => { if(rate === 0) { if(payment === 0) { @@ -462,8 +463,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public rate(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('RATE'), + public rate(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('RATE'), (periods, payment, present, future, type, guess) => { if(guess<=-1) { return new CellError(ErrorType.VALUE) @@ -504,8 +505,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public pv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('PV'), + public pv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('PV'), (rate, periods, payment, future, type) => { type = type ? 1 : 0 if(rate === -1) { @@ -524,8 +525,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public rri(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('RRI'), + public rri(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('RRI'), (periods, present, future) => { if (present === 0 || (future < 0 && present > 0) || (future > 0 && present < 0)) { return new CellError(ErrorType.NUM) @@ -536,8 +537,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public sln(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SLN'), + public sln(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SLN'), (cost, salvage, life) => { if (life === 0) { return new CellError(ErrorType.DIV_BY_ZERO) @@ -547,8 +548,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public syd(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SYD'), + public syd(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SYD'), (cost, salvage, life, period) => { if (period > life) { return new CellError(ErrorType.NUM) @@ -558,8 +559,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public tbilleq(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('TBILLEQ'), + public tbilleq(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('TBILLEQ'), (settlement, maturity, discount) => { settlement = Math.round(settlement) maturity = Math.round(maturity) @@ -584,8 +585,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public tbillprice(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('TBILLPRICE'), + public tbillprice(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('TBILLPRICE'), (settlement, maturity, discount) => { settlement = Math.round(settlement) maturity = Math.round(maturity) @@ -610,8 +611,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public tbillyield(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('TBILLYIELD'), + public tbillyield(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('TBILLYIELD'), (settlement, maturity, price) => { settlement = Math.round(settlement) maturity = Math.round(maturity) @@ -629,8 +630,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public fvschedule(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('FVSCHEDULE'), + public fvschedule(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('FVSCHEDULE'), (value: number, ratios: SimpleRangeValue) => { const vals = ratios.valuesFromTopLeftCorner() for(const val of vals) { @@ -649,8 +650,8 @@ export class FinancialPlugin extends FunctionPlugin { }) } - public npv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('NPV'), + public npv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('NPV'), (rate: number, ...args: RawInterpreterValue[]) => { const coerced = this.interpreter.arithmeticHelper.coerceNumbersExactRanges(args) if(coerced instanceof CellError) { @@ -661,8 +662,8 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public mirr(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('MIRR'), + public mirr(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('MIRR'), (range: SimpleRangeValue, frate: number, rrate: number) => { const vals = this.interpreter.arithmeticHelper.manyToExactNumbers(range.valuesFromTopLeftCorner()) if(vals instanceof CellError) { @@ -706,14 +707,14 @@ export class FinancialPlugin extends FunctionPlugin { ) } - public pduration(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('PDURATION'), + public pduration(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('PDURATION'), (rate: number, pv: number, fv: number) => (Math.log(fv) - Math.log(pv))/Math.log(1+rate) ) } - public xnpv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('XNPV'), + public xnpv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('XNPV'), (rate: number, values: SimpleRangeValue, dates: SimpleRangeValue) => { const valArr = values.valuesFromTopLeftCorner() for(const val of valArr) { diff --git a/src/interpreter/plugin/FormulaTextPlugin.ts b/src/interpreter/plugin/FormulaTextPlugin.ts index e8318e4db2..d90f4f25bf 100644 --- a/src/interpreter/plugin/FormulaTextPlugin.ts +++ b/src/interpreter/plugin/FormulaTextPlugin.ts @@ -7,10 +7,11 @@ import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' import {FunctionPlugin} from '../index' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes} from './FunctionPlugin' +import {ArgumentTypes, FunctionPluginTypecheck} from './FunctionPlugin' -export class FormulaTextPlugin extends FunctionPlugin { +export class FormulaTextPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'FORMULATEXT': { method: 'formulatext', @@ -28,10 +29,10 @@ export class FormulaTextPlugin extends FunctionPlugin { * Returns a formula in a given cell as a string. * * @param ast - * @param formulaAddress + * @param state */ - public formulatext(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunctionWithReferenceArgument(ast.args, formulaAddress, this.metadata('FORMULATEXT'), + public formulatext(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunctionWithReferenceArgument(ast.args, state, this.metadata('FORMULATEXT'), () => new CellError(ErrorType.NA, ErrorMessage.WrongArgNumber), (cellReference: SimpleCellAddress) => this.serialization.getCellFormula(cellReference) ?? new CellError(ErrorType.NA, ErrorMessage.Formula) ) diff --git a/src/interpreter/plugin/FunctionPlugin.ts b/src/interpreter/plugin/FunctionPlugin.ts index ffd2e340aa..5649f7ca74 100644 --- a/src/interpreter/plugin/FunctionPlugin.ts +++ b/src/interpreter/plugin/FunctionPlugin.ts @@ -14,8 +14,10 @@ import {Ast, AstNodeType, ProcedureAst} from '../../parser' import {Serialization} from '../../Serialization' import {coerceScalarToBoolean, coerceScalarToString, coerceToRange, complex} from '../ArithmeticHelper' import {Interpreter} from '../Interpreter' +import {InterpreterState} from '../InterpreterState' import { - ExtendedNumber, FormatInfo, + ExtendedNumber, + FormatInfo, getRawValue, InternalScalarValue, InterpreterValue, @@ -53,6 +55,7 @@ export interface FunctionMetadata extends FunctionArguments { isVolatile?: boolean, isDependentOnSheetStructureChange?: boolean, doesNotNeedArgumentsToBeComputed?: boolean, + arrayFunction?: boolean, } export interface FunctionPluginDefinition { @@ -151,14 +154,18 @@ export interface FunctionArgument { greaterThan?: number, } -export type PluginFunctionType = (ast: ProcedureAst, formulaAddress: SimpleCellAddress) => InternalScalarValue +export type PluginFunctionType = (ast: ProcedureAst, state: InterpreterState) => InterpreterValue + +export type FunctionPluginTypecheck = { + [K in keyof T]: T[K] extends PluginFunctionType ? T[K] : never +} /** * Abstract class representing interpreter function plugin. * Plugin may contain multiple functions. Each function should be of type {@link PluginFunctionType} and needs to be * included in {@link implementedFunctions} */ -export abstract class FunctionPlugin { +export abstract class FunctionPlugin implements FunctionPluginTypecheck { /** * Dictionary containing functions implemented by specific plugin, along with function name translations. */ @@ -178,14 +185,14 @@ export abstract class FunctionPlugin { this.serialization = interpreter.serialization } - protected evaluateAst(ast: Ast, formulaAddress: SimpleCellAddress): InterpreterValue { - return this.interpreter.evaluateAst(ast, formulaAddress) + protected evaluateAst(ast: Ast, state: InterpreterState): InterpreterValue { + return this.interpreter.evaluateAst(ast, state) } - protected listOfScalarValues(asts: Ast[], formulaAddress: SimpleCellAddress): [InternalScalarValue, boolean][] { + protected listOfScalarValues(asts: Ast[], state: InterpreterState): [InternalScalarValue, boolean][] { const ret: [InternalScalarValue, boolean][] = [] for (const argAst of asts) { - const value = this.evaluateAst(argAst, formulaAddress) + const value = this.evaluateAst(argAst, state) if (value instanceof SimpleRangeValue) { for (const scalarValue of value.valuesFromTopLeftCorner()) { ret.push([scalarValue, true]) @@ -197,9 +204,9 @@ export abstract class FunctionPlugin { return ret } - public coerceScalarToNumberOrError = (arg: InternalScalarValue): ExtendedNumber | CellError => this.interpreter.arithmeticHelper.coerceScalarToNumberOrError(arg) + protected coerceScalarToNumberOrError = (arg: InternalScalarValue): ExtendedNumber | CellError => this.interpreter.arithmeticHelper.coerceScalarToNumberOrError(arg) - public coerceToType(arg: InterpreterValue, coercedType: FunctionArgument): Maybe { + protected coerceToType(arg: InterpreterValue, coercedType: FunctionArgument): Maybe { let ret if (arg instanceof SimpleRangeValue) { switch(coercedType.argumentType) { @@ -269,25 +276,25 @@ export abstract class FunctionPlugin { protected runFunction = ( args: Ast[], - formulaAddress: SimpleCellAddress, + state: InterpreterState, functionDefinition: FunctionArguments, fn: (...arg: any) => InternalScalarValue ) => { - return this.runFunctionTemplate(args, formulaAddress, functionDefinition, fn) + return this.runFunctionTemplate(args, state, functionDefinition, fn) } protected runMatrixFunction = ( args: Ast[], - formulaAddress: SimpleCellAddress, + state: InterpreterState, functionDefinition: FunctionArguments, fn: (...arg: any) => InterpreterValue ) => { - return this.runFunctionTemplate(args, formulaAddress, functionDefinition, fn) + return this.runFunctionTemplate(args, state, functionDefinition, fn) } private runFunctionTemplate = ( args: Ast[], - formulaAddress: SimpleCellAddress, + state: InterpreterState, functionDefinition: FunctionArguments, fn: (...arg: any) => any ) => { @@ -295,9 +302,9 @@ export abstract class FunctionPlugin { let scalarValues: [InterpreterValue, boolean][] if (functionDefinition.expandRanges) { - scalarValues = this.listOfScalarValues(args, formulaAddress) + scalarValues = this.listOfScalarValues(args, state) } else { - scalarValues = args.map((ast) => [this.evaluateAst(ast, formulaAddress), false]) + scalarValues = args.map((ast) => [this.evaluateAst(ast, state), false]) } const coercedArguments: Maybe[] = [] @@ -346,7 +353,7 @@ export abstract class FunctionPlugin { protected runFunctionWithReferenceArgument = ( args: Ast[], - formulaAddress: SimpleCellAddress, + state: InterpreterState, argumentDefinitions: FunctionArguments, noArgCallback: () => InternalScalarValue | RawScalarValue, referenceCallback: (reference: SimpleCellAddress) => InternalScalarValue, @@ -366,10 +373,10 @@ export abstract class FunctionPlugin { let cellReference: Maybe if (arg.type === AstNodeType.CELL_REFERENCE) { - cellReference = arg.reference.toSimpleCellAddress(formulaAddress) + cellReference = arg.reference.toSimpleCellAddress(state.formulaAddress) } else if (arg.type === AstNodeType.CELL_RANGE || arg.type === AstNodeType.COLUMN_RANGE || arg.type === AstNodeType.ROW_RANGE) { try { - cellReference = AbsoluteCellRange.fromAst(arg, formulaAddress).start + cellReference = AbsoluteCellRange.fromAst(arg, state.formulaAddress).start } catch (e) { return new CellError(ErrorType.REF, ErrorMessage.CellRefExpected) } @@ -379,7 +386,7 @@ export abstract class FunctionPlugin { return this.returnNumberWrapper(referenceCallback(cellReference), argumentDefinitions.returnNumberType) } - return this.runFunction(args, formulaAddress, argumentDefinitions, nonReferenceCallback) + return this.runFunction(args, state, argumentDefinitions, nonReferenceCallback) } protected metadata(name: string): FunctionMetadata { diff --git a/src/interpreter/plugin/InformationPlugin.ts b/src/interpreter/plugin/InformationPlugin.ts index f95a360807..abdaa43ed1 100644 --- a/src/interpreter/plugin/InformationPlugin.ts +++ b/src/interpreter/plugin/InformationPlugin.ts @@ -7,14 +7,15 @@ import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' import {FormulaCellVertex, MatrixVertex} from '../../DependencyGraph' import {ErrorMessage} from '../../error-message' import {AstNodeType, ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {EmptyValue, InternalScalarValue, isExtendedNumber} from '../InterpreterValue' import {SimpleRangeValue} from '../SimpleRangeValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' /** * Interpreter plugin containing information functions */ -export class InformationPlugin extends FunctionPlugin { +export class InformationPlugin extends FunctionPlugin implements FunctionPluginTypecheck { public static implementedFunctions = { 'COLUMN': { method: 'column', @@ -142,10 +143,10 @@ export class InformationPlugin extends FunctionPlugin { * Returns true if provided value is a valid binary number * * @param ast - * @param formulaAddress + * @param state */ - public isbinary(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ISBINARY'), (arg: string) => + public isbinary(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ISBINARY'), (arg: string) => /^[01]{1,10}$/.test(arg) ) } @@ -156,10 +157,10 @@ export class InformationPlugin extends FunctionPlugin { * Returns true if provided value is an error except #N/A! * * @param ast - * @param formulaAddress + * @param state */ - public iserr(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ISERR'), (arg: InternalScalarValue) => + public iserr(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ISERR'), (arg: InternalScalarValue) => (arg instanceof CellError && arg.type !== ErrorType.NA) ) } @@ -170,10 +171,10 @@ export class InformationPlugin extends FunctionPlugin { * Checks whether provided value is an error * * @param ast - * @param formulaAddress + * @param state */ - public iserror(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ISERROR'), (arg: InternalScalarValue) => + public iserror(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ISERROR'), (arg: InternalScalarValue) => (arg instanceof CellError) ) } @@ -184,10 +185,10 @@ export class InformationPlugin extends FunctionPlugin { * Checks whether referenced cell is a formula * * @param ast - * @param formulaAddress + * @param state */ - public isformula(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunctionWithReferenceArgument(ast.args, formulaAddress, this.metadata('ISFORMULA'), + public isformula(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunctionWithReferenceArgument(ast.args, state, this.metadata('ISFORMULA'), () => new CellError(ErrorType.NA, ErrorMessage.WrongArgNumber), (reference: SimpleCellAddress) => { const vertex = this.dependencyGraph.addressMapping.getCell(reference) @@ -202,10 +203,10 @@ export class InformationPlugin extends FunctionPlugin { * Checks whether provided cell reference is empty * * @param ast - * @param formulaAddress + * @param state */ - public isblank(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ISBLANK'), (arg: InternalScalarValue) => + public isblank(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ISBLANK'), (arg: InternalScalarValue) => (arg === EmptyValue) ) } @@ -216,10 +217,10 @@ export class InformationPlugin extends FunctionPlugin { * Returns true if provided value is #N/A! error * * @param ast - * @param formulaAddress + * @param state */ - public isna(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ISNA'), (arg: InternalScalarValue) => + public isna(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ISNA'), (arg: InternalScalarValue) => (arg instanceof CellError && arg.type == ErrorType.NA) ) } @@ -230,10 +231,10 @@ export class InformationPlugin extends FunctionPlugin { * Checks whether provided cell reference is a number * * @param ast - * @param formulaAddress + * @param state */ - public isnumber(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ISNUMBER'), isExtendedNumber) + public isnumber(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ISNUMBER'), isExtendedNumber) } /** @@ -242,10 +243,10 @@ export class InformationPlugin extends FunctionPlugin { * Checks whether provided cell reference is of logical type * * @param ast - * @param formulaAddress + * @param state */ - public islogical(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ISLOGICAL'), (arg: InternalScalarValue) => + public islogical(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ISLOGICAL'), (arg: InternalScalarValue) => (typeof arg === 'boolean') ) } @@ -256,10 +257,10 @@ export class InformationPlugin extends FunctionPlugin { * Returns true if provided value is #REF! error * * @param ast - * @param formulaAddress + * @param state */ - public isref(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ISREF'), (arg: InternalScalarValue) => + public isref(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ISREF'), (arg: InternalScalarValue) => (arg instanceof CellError && (arg.type == ErrorType.REF || arg.type == ErrorType.CYCLE)) ) } @@ -270,10 +271,10 @@ export class InformationPlugin extends FunctionPlugin { * Checks whether provided cell reference is of logical type * * @param ast - * @param formulaAddress + * @param state */ - public istext(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ISTEXT'), (arg: InternalScalarValue) => + public istext(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ISTEXT'), (arg: InternalScalarValue) => (typeof arg === 'string') ) } @@ -284,10 +285,10 @@ export class InformationPlugin extends FunctionPlugin { * Checks whether provided cell reference is of logical type * * @param ast - * @param formulaAddress + * @param state */ - public isnontext(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ISNONTEXT'), (arg: InternalScalarValue) => + public isnontext(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ISNONTEXT'), (arg: InternalScalarValue) => !(typeof arg === 'string') ) } @@ -298,11 +299,11 @@ export class InformationPlugin extends FunctionPlugin { * Returns column number of a reference or a formula cell if reference not provided * * @param ast - * @param formulaAddress + * @param state */ - public column(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunctionWithReferenceArgument(ast.args, formulaAddress, this.metadata('COLUMN'), - () => formulaAddress.col + 1, + public column(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunctionWithReferenceArgument(ast.args, state, this.metadata('COLUMN'), + () => state.formulaAddress.col + 1, (reference: SimpleCellAddress) => reference.col + 1 ) } @@ -313,9 +314,9 @@ export class InformationPlugin extends FunctionPlugin { * Returns number of columns in provided range of cells * * @param ast - * @param formulaAddress + * @param _state */ - public columns(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { + public columns(ast: ProcedureAst, _state: InterpreterState): InternalScalarValue { if (ast.args.length !== 1) { return new CellError(ErrorType.NA, ErrorMessage.WrongArgNumber) } @@ -336,11 +337,11 @@ export class InformationPlugin extends FunctionPlugin { * Returns row number of a reference or a formula cell if reference not provided * * @param ast - * @param formulaAddress + * @param state */ - public row(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunctionWithReferenceArgument(ast.args, formulaAddress, this.metadata('ROW'), - () => formulaAddress.row + 1, + public row(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunctionWithReferenceArgument(ast.args, state, this.metadata('ROW'), + () => state.formulaAddress.row + 1, (reference: SimpleCellAddress) => reference.row + 1 ) } @@ -351,9 +352,9 @@ export class InformationPlugin extends FunctionPlugin { * Returns number of rows in provided range of cells * * @param ast - * @param formulaAddress + * @param _state */ - public rows(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { + public rows(ast: ProcedureAst, _state: InterpreterState): InternalScalarValue { if (ast.args.length !== 1) { return new CellError(ErrorType.NA, ErrorMessage.WrongArgNumber) } @@ -374,10 +375,10 @@ export class InformationPlugin extends FunctionPlugin { * Returns number of rows in provided range of cells * * @param ast - * @param formulaAddress + * @param state */ - public index(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('INDEX'), (rangeValue: SimpleRangeValue, row: number, col: number) => { + public index(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('INDEX'), (rangeValue: SimpleRangeValue, row: number, col: number) => { if (col < 1 || row < 1) { return new CellError(ErrorType.VALUE, ErrorMessage.LessThanOne) } @@ -399,9 +400,9 @@ export class InformationPlugin extends FunctionPlugin { * Returns #N/A! * * @param _ast - * @param _formulaAddress + * @param _state */ - public na(_ast: ProcedureAst, _formulaAddress: SimpleCellAddress): CellError { + public na(_ast: ProcedureAst, _state: InterpreterState): CellError { return new CellError(ErrorType.NA) } @@ -411,11 +412,11 @@ export class InformationPlugin extends FunctionPlugin { * Returns sheet number of a given value or a formula sheet number if no argument is provided * * @param ast - * @param formulaAddress + * @param state * */ - public sheet(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunctionWithReferenceArgument(ast.args, formulaAddress, {parameters: [{argumentType: ArgumentTypes.STRING}]}, - () => formulaAddress.sheet + 1, + public sheet(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunctionWithReferenceArgument(ast.args, state, {parameters: [{argumentType: ArgumentTypes.STRING}]}, + () => state.formulaAddress.sheet + 1, (reference: SimpleCellAddress) => reference.sheet + 1, (value: string) => { const sheetNumber = this.dependencyGraph.sheetMapping.get(value) @@ -435,10 +436,10 @@ export class InformationPlugin extends FunctionPlugin { * It returns always 1 for a valid reference as 3D references are not supported. * * @param ast - * @param formulaAddress + * @param state * */ - public sheets(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunctionWithReferenceArgument(ast.args, formulaAddress, {parameters: [{argumentType: ArgumentTypes.STRING}]}, + public sheets(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunctionWithReferenceArgument(ast.args, state, {parameters: [{argumentType: ArgumentTypes.STRING}]}, () => this.dependencyGraph.sheetMapping.numberOfSheets(), // return number of sheets if no argument () => 1, // return 1 for valid reference () => new CellError(ErrorType.VALUE, ErrorMessage.CellRefExpected) // error otherwise diff --git a/src/interpreter/plugin/IsEvenPlugin.ts b/src/interpreter/plugin/IsEvenPlugin.ts index e9834382da..b62a2c2105 100644 --- a/src/interpreter/plugin/IsEvenPlugin.ts +++ b/src/interpreter/plugin/IsEvenPlugin.ts @@ -3,12 +3,12 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class IsEvenPlugin extends FunctionPlugin { +export class IsEvenPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'ISEVEN': { method: 'iseven', @@ -18,8 +18,8 @@ export class IsEvenPlugin extends FunctionPlugin { }, } - public iseven(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ISEVEN'), + public iseven(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ISEVEN'), (val) => (val % 2 === 0) ) } diff --git a/src/interpreter/plugin/IsOddPlugin.ts b/src/interpreter/plugin/IsOddPlugin.ts index 6082ac6acd..c5b7d6a927 100644 --- a/src/interpreter/plugin/IsOddPlugin.ts +++ b/src/interpreter/plugin/IsOddPlugin.ts @@ -3,12 +3,12 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class IsOddPlugin extends FunctionPlugin { +export class IsOddPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'ISODD': { method: 'isodd', @@ -18,8 +18,8 @@ export class IsOddPlugin extends FunctionPlugin { }, } - public isodd(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ISODD'), + public isodd(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ISODD'), (val) => (val % 2 === 1) ) } diff --git a/src/interpreter/plugin/LogarithmPlugin.ts b/src/interpreter/plugin/LogarithmPlugin.ts index 58afea1618..72882f1561 100644 --- a/src/interpreter/plugin/LogarithmPlugin.ts +++ b/src/interpreter/plugin/LogarithmPlugin.ts @@ -3,12 +3,12 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class LogarithmPlugin extends FunctionPlugin { +export class LogarithmPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'LOG10': { @@ -32,17 +32,17 @@ export class LogarithmPlugin extends FunctionPlugin { }, } - public log10(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('LOG10'), Math.log10) + public log10(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('LOG10'), Math.log10) } - public log(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('LOG'), + public log(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('LOG'), (arg: number, base: number) => Math.log(arg) / Math.log(base) ) } - public ln(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('LN'), Math.log) + public ln(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('LN'), Math.log) } } diff --git a/src/interpreter/plugin/LookupPlugin.ts b/src/interpreter/plugin/LookupPlugin.ts index 99a9198d82..db53e55d79 100644 --- a/src/interpreter/plugin/LookupPlugin.ts +++ b/src/interpreter/plugin/LookupPlugin.ts @@ -4,18 +4,19 @@ */ import {AbsoluteCellRange} from '../../AbsoluteCellRange' -import {CellError, ErrorType, simpleCellAddress, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType, simpleCellAddress} from '../../Cell' import {ErrorMessage} from '../../error-message' import {RowSearchStrategy} from '../../Lookup/RowSearchStrategy' import {SearchStrategy} from '../../Lookup/SearchStrategy' import {ProcedureAst} from '../../parser' import {StatType} from '../../statistics' import {zeroIfEmpty} from '../ArithmeticHelper' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue, RawNoErrorScalarValue, } from '../InterpreterValue' import {SimpleRangeValue} from '../SimpleRangeValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class LookupPlugin extends FunctionPlugin { +export class LookupPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ private rowSearch: RowSearchStrategy = new RowSearchStrategy(this.config, this.dependencyGraph) public static implementedFunctions = { @@ -51,10 +52,10 @@ export class LookupPlugin extends FunctionPlugin { * Corresponds to VLOOKUP(key, range, index, [sorted]) * * @param ast - * @param formulaAddress + * @param state */ - public vlookup(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('VLOOKUP'), (key: RawNoErrorScalarValue, rangeValue: SimpleRangeValue, index: number, sorted: boolean) => { + public vlookup(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('VLOOKUP'), (key: RawNoErrorScalarValue, rangeValue: SimpleRangeValue, index: number, sorted: boolean) => { const range = rangeValue.range() if (range === undefined) { @@ -77,8 +78,8 @@ export class LookupPlugin extends FunctionPlugin { * @param ast * @param formulaAddress */ - public hlookup(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HLOOKUP'), (key: RawNoErrorScalarValue, rangeValue: SimpleRangeValue, index: number, sorted: boolean) => { + public hlookup(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HLOOKUP'), (key: RawNoErrorScalarValue, rangeValue: SimpleRangeValue, index: number, sorted: boolean) => { const range = rangeValue.range() if (range === undefined) { return new CellError(ErrorType.VALUE, ErrorMessage.WrongType) @@ -94,8 +95,8 @@ export class LookupPlugin extends FunctionPlugin { }) } - public match(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('MATCH'), (key: RawNoErrorScalarValue, rangeValue: SimpleRangeValue, sorted: number) => { + public match(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('MATCH'), (key: RawNoErrorScalarValue, rangeValue: SimpleRangeValue, sorted: number) => { return this.doMatch(zeroIfEmpty(key), rangeValue, sorted) }) } diff --git a/src/interpreter/plugin/MathConstantsPlugin.ts b/src/interpreter/plugin/MathConstantsPlugin.ts index 18d3a09d43..45b03e25d0 100644 --- a/src/interpreter/plugin/MathConstantsPlugin.ts +++ b/src/interpreter/plugin/MathConstantsPlugin.ts @@ -3,14 +3,14 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' export const PI = parseFloat(Math.PI.toFixed(14)) -export class MathConstantsPlugin extends FunctionPlugin { +export class MathConstantsPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'PI': { method: 'pi', @@ -24,14 +24,14 @@ export class MathConstantsPlugin extends FunctionPlugin { }, } - public pi(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('PI'), + public pi(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('PI'), () => PI ) } - public sqrtpi(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SQRTPI'), + public sqrtpi(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SQRTPI'), (arg: number) => Math.sqrt(PI*arg) ) } diff --git a/src/interpreter/plugin/MathPlugin.ts b/src/interpreter/plugin/MathPlugin.ts index 9fec8543e1..1d6339f4a9 100644 --- a/src/interpreter/plugin/MathPlugin.ts +++ b/src/interpreter/plugin/MathPlugin.ts @@ -3,14 +3,15 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue, RawInterpreterValue} from '../InterpreterValue' import {SimpleRangeValue} from '../SimpleRangeValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class MathPlugin extends FunctionPlugin { +export class MathPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'FACT': { method: 'fact', @@ -112,8 +113,8 @@ export class MathPlugin extends FunctionPlugin { }, } - public fact(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('FACT'), + public fact(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('FACT'), (arg: number) => { arg = Math.trunc(arg) let ret = 1 @@ -124,8 +125,8 @@ export class MathPlugin extends FunctionPlugin { }) } - public factdouble(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('FACTDOUBLE'), + public factdouble(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('FACTDOUBLE'), (arg: number) => { arg = Math.trunc(arg) let ret = 1 @@ -137,8 +138,8 @@ export class MathPlugin extends FunctionPlugin { ) } - public combin(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('COMBIN'), + public combin(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('COMBIN'), (n: number, m: number) => { if(m>n) { return new CellError(ErrorType.NUM, ErrorMessage.WrongOrder) @@ -149,8 +150,8 @@ export class MathPlugin extends FunctionPlugin { }) } - public combina(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('COMBINA'), + public combina(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('COMBINA'), (n: number, m: number) => { n = Math.trunc(n) m = Math.trunc(m) @@ -166,8 +167,8 @@ export class MathPlugin extends FunctionPlugin { ) } - public gcd(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('GCD'), + public gcd(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('GCD'), (...args: RawInterpreterValue[]) => { const processedArgs = this.interpreter.arithmeticHelper.coerceNumbersCoerceRangesDropNulls(args) if(processedArgs instanceof CellError) { @@ -189,8 +190,8 @@ export class MathPlugin extends FunctionPlugin { ) } - public lcm(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('LCM'), + public lcm(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('LCM'), (...args: RawInterpreterValue[]) => { const processedArgs = this.interpreter.arithmeticHelper.coerceNumbersCoerceRangesDropNulls(args) if(processedArgs instanceof CellError) { @@ -212,8 +213,8 @@ export class MathPlugin extends FunctionPlugin { ) } - public mround(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('MROUND'), + public mround(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('MROUND'), (nom: number, denom: number) => { if(denom===0) { return 0 @@ -226,8 +227,8 @@ export class MathPlugin extends FunctionPlugin { ) } - public multinomial(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('MULTINOMIAL'), + public multinomial(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('MULTINOMIAL'), (...args: number[]) => { let n = 0 let ans = 1 @@ -246,8 +247,8 @@ export class MathPlugin extends FunctionPlugin { ) } - public quotient(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('QUOTIENT'), + public quotient(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('QUOTIENT'), (nom: number, denom: number) => { if(denom===0) { return new CellError(ErrorType.DIV_BY_ZERO) @@ -257,8 +258,8 @@ export class MathPlugin extends FunctionPlugin { ) } - public seriessum(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SERIESSUM'), + public seriessum(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SERIESSUM'), (x: number, n: number, m: number, range: SimpleRangeValue) => { const coefs = this.interpreter.arithmeticHelper.manyToOnlyNumbersDropNulls(range.valuesFromTopLeftCorner()) if(coefs instanceof CellError) { @@ -275,8 +276,8 @@ export class MathPlugin extends FunctionPlugin { ) } - public sign(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SIGN'), + public sign(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SIGN'), (arg: number) => { if(arg>0) { return 1 @@ -289,8 +290,8 @@ export class MathPlugin extends FunctionPlugin { ) } - public sumx2my2(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SUMX2MY2'), + public sumx2my2(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SUMX2MY2'), (rangeX: SimpleRangeValue, rangeY: SimpleRangeValue) => { const valsX = rangeX.valuesFromTopLeftCorner() const valsY = rangeY.valuesFromTopLeftCorner() @@ -317,8 +318,8 @@ export class MathPlugin extends FunctionPlugin { ) } - public sumx2py2(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SUMX2PY2'), + public sumx2py2(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SUMX2PY2'), (rangeX: SimpleRangeValue, rangeY: SimpleRangeValue) => { const valsX = rangeX.valuesFromTopLeftCorner() const valsY = rangeY.valuesFromTopLeftCorner() @@ -345,8 +346,8 @@ export class MathPlugin extends FunctionPlugin { ) } - public sumxmy2(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SUMXMY2'), + public sumxmy2(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SUMXMY2'), (rangeX: SimpleRangeValue, rangeY: SimpleRangeValue) => { const valsX = rangeX.valuesFromTopLeftCorner() const valsY = rangeY.valuesFromTopLeftCorner() diff --git a/src/interpreter/plugin/MatrixPlugin.ts b/src/interpreter/plugin/MatrixPlugin.ts index ef66eed7fe..069057aaff 100644 --- a/src/interpreter/plugin/MatrixPlugin.ts +++ b/src/interpreter/plugin/MatrixPlugin.ts @@ -3,14 +3,15 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {MatrixSize, matrixSizeForMultiplication, matrixSizeForPoolFunction, matrixSizeForTranspose} from '../../Matrix' import {ProcedureAst} from '../../parser' +import {Interpreter} from '../Interpreter' +import {InterpreterState} from '../InterpreterState' import {InterpreterValue} from '../InterpreterValue' import {SimpleRangeValue} from '../SimpleRangeValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' -import {Interpreter} from '../Interpreter' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' export type KernelRunShortcut = (...args: any[]) => number[][] @@ -27,7 +28,7 @@ export interface KernelFunctionThis { } -export class MatrixPlugin extends FunctionPlugin { +export class MatrixPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'MMULT': { method: 'mmult', @@ -71,8 +72,8 @@ export class MatrixPlugin extends FunctionPlugin { } } - public mmult(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InterpreterValue { - return this.runMatrixFunction(ast.args, formulaAddress, this.metadata('MMULT'), (leftMatrix: SimpleRangeValue, rightMatrix: SimpleRangeValue) => { + public mmult(ast: ProcedureAst, state: InterpreterState): InterpreterValue { + return this.runMatrixFunction(ast.args, state, this.metadata('MMULT'), (leftMatrix: SimpleRangeValue, rightMatrix: SimpleRangeValue) => { if (!leftMatrix.hasOnlyNumbers() || !rightMatrix.hasOnlyNumbers()) { return new CellError(ErrorType.VALUE, ErrorMessage.NumberRange) } @@ -90,8 +91,8 @@ export class MatrixPlugin extends FunctionPlugin { }) } - public maxpool(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InterpreterValue { - return this.runMatrixFunction(ast.args, formulaAddress, this.metadata('MAXPOOL'), (matrix: SimpleRangeValue, windowSize: number, stride: number = windowSize) => { + public maxpool(ast: ProcedureAst, state: InterpreterState): InterpreterValue { + return this.runMatrixFunction(ast.args, state, this.metadata('MAXPOOL'), (matrix: SimpleRangeValue, windowSize: number, stride: number = windowSize) => { if (!matrix.hasOnlyNumbers()) { return new CellError(ErrorType.VALUE, ErrorMessage.NumberRange) } @@ -113,8 +114,8 @@ export class MatrixPlugin extends FunctionPlugin { }) } - public medianpool(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InterpreterValue { - return this.runMatrixFunction(ast.args, formulaAddress, this.metadata('MEDIANPOOL'), (matrix: SimpleRangeValue, windowSize: number, stride: number = windowSize) => { + public medianpool(ast: ProcedureAst, state: InterpreterState): InterpreterValue { + return this.runMatrixFunction(ast.args, state, this.metadata('MEDIANPOOL'), (matrix: SimpleRangeValue, windowSize: number, stride: number = windowSize) => { if (!matrix.hasOnlyNumbers()) { return new CellError(ErrorType.VALUE, ErrorMessage.NumberRange) } @@ -178,8 +179,8 @@ export class MatrixPlugin extends FunctionPlugin { }) } - public transpose(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InterpreterValue { - return this.runMatrixFunction(ast.args, formulaAddress, this.metadata('TRANSPOSE'), (matrix: SimpleRangeValue) => { + public transpose(ast: ProcedureAst, state: InterpreterState): InterpreterValue { + return this.runMatrixFunction(ast.args, state, this.metadata('TRANSPOSE'), (matrix: SimpleRangeValue) => { if (!matrix.hasOnlyNumbers()) { return new CellError(ErrorType.VALUE, ErrorMessage.NumberRange) } diff --git a/src/interpreter/plugin/MedianPlugin.ts b/src/interpreter/plugin/MedianPlugin.ts index 8b43c91201..49e4817d63 100644 --- a/src/interpreter/plugin/MedianPlugin.ts +++ b/src/interpreter/plugin/MedianPlugin.ts @@ -3,17 +3,18 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' -import {AstNodeType, ProcedureAst} from '../../parser' +import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue, RawScalarValue} from '../InterpreterValue' import {SimpleRangeValue} from '../SimpleRangeValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' /** * Interpreter plugin containing MEDIAN function */ -export class MedianPlugin extends FunctionPlugin { +export class MedianPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'MEDIAN': { @@ -45,10 +46,10 @@ export class MedianPlugin extends FunctionPlugin { * Returns a median of given numbers. * * @param ast - * @param formulaAddress + * @param state */ - public median(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('MEDIAN'), + public median(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('MEDIAN'), (...args: RawScalarValue[]) => { const values = this.interpreter.arithmeticHelper.coerceNumbersExactRanges(args) if(values instanceof CellError) { @@ -66,8 +67,8 @@ export class MedianPlugin extends FunctionPlugin { }) } - public large(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('LARGE'), + public large(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('LARGE'), (range: SimpleRangeValue, n: number) => { const vals = this.interpreter.arithmeticHelper.manyToExactNumbers(range.valuesFromTopLeftCorner()) if(vals instanceof CellError) { @@ -83,8 +84,8 @@ export class MedianPlugin extends FunctionPlugin { ) } - public small(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SMALL'), + public small(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SMALL'), (range: SimpleRangeValue, n: number) => { const vals = this.interpreter.arithmeticHelper.manyToExactNumbers(range.valuesFromTopLeftCorner()) if(vals instanceof CellError) { diff --git a/src/interpreter/plugin/ModuloPlugin.ts b/src/interpreter/plugin/ModuloPlugin.ts index 5b8d76fbe9..c1a7b0ebf0 100644 --- a/src/interpreter/plugin/ModuloPlugin.ts +++ b/src/interpreter/plugin/ModuloPlugin.ts @@ -3,12 +3,13 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class ModuloPlugin extends FunctionPlugin { +export class ModuloPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'MOD': { method: 'mod', @@ -19,8 +20,8 @@ export class ModuloPlugin extends FunctionPlugin { }, } - public mod(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('MOD'), (dividend: number, divisor: number) => { + public mod(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('MOD'), (dividend: number, divisor: number) => { if (divisor === 0) { return new CellError(ErrorType.DIV_BY_ZERO) } else { diff --git a/src/interpreter/plugin/NumericAggregationPlugin.ts b/src/interpreter/plugin/NumericAggregationPlugin.ts index 6a07261aaa..620076c7c1 100644 --- a/src/interpreter/plugin/NumericAggregationPlugin.ts +++ b/src/interpreter/plugin/NumericAggregationPlugin.ts @@ -5,15 +5,16 @@ import assert from 'assert' import {AbsoluteCellRange, DIFFERENT_SHEETS_ERROR} from '../../AbsoluteCellRange' -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {Maybe} from '../../Maybe' import {Ast, AstNodeType, CellRangeAst, ProcedureAst} from '../../parser' import {ColumnRangeAst, RowRangeAst} from '../../parser/Ast' import {coerceBooleanToNumber} from '../ArithmeticHelper' +import {InterpreterState} from '../InterpreterState' import {EmptyValue, ExtendedNumber, getRawValue, InternalScalarValue, isExtendedNumber, } from '../InterpreterValue' import {SimpleRangeValue} from '../SimpleRangeValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' export type BinaryOperation = (left: T, right: T) => T @@ -21,10 +22,6 @@ export type MapOperation = (arg: ExtendedNumber) => T type coercionOperation = (arg: InternalScalarValue) => Maybe -function identityMap(arg: T): T { - return arg -} - function zeroForInfinite(value: InternalScalarValue) { if (isExtendedNumber(value) && !Number.isFinite(getRawValue(value))) { return 0 @@ -77,7 +74,7 @@ class MomentsAggregate { } } -export class NumericAggregationPlugin extends FunctionPlugin { +export class NumericAggregationPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'SUM': { method: 'sum', @@ -156,14 +153,14 @@ export class NumericAggregationPlugin extends FunctionPlugin { * Returns a sum of given numbers. * * @param ast - * @param formulaAddress + * @param state */ - public sum(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.doSum(ast.args, formulaAddress) + public sum(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.doSum(ast.args, state) } - public sumsq(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.reduce(ast.args, formulaAddress, 0, 'SUMSQ', this.addWithEpsilonRaw, (arg: ExtendedNumber) => Math.pow(getRawValue(arg), 2), strictlyNumbers) + public sumsq(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.reduce(ast.args, state, 0, 'SUMSQ', this.addWithEpsilonRaw, (arg: ExtendedNumber) => Math.pow(getRawValue(arg), 2), strictlyNumbers) } /** @@ -172,14 +169,14 @@ export class NumericAggregationPlugin extends FunctionPlugin { * Returns a max of given numbers. * * @param ast - * @param formulaAddress + * @param state */ - public max(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.doMax(ast.args, formulaAddress) + public max(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.doMax(ast.args, state) } - public maxa(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - const value = this.reduce(ast.args, formulaAddress, Number.NEGATIVE_INFINITY, 'MAXA', + public maxa(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + const value = this.reduce(ast.args, state, Number.NEGATIVE_INFINITY, 'MAXA', (left: number, right: number) => Math.max(left, right), getRawValue, numbersBooleans) @@ -192,34 +189,34 @@ export class NumericAggregationPlugin extends FunctionPlugin { * Returns a min of given numbers. * * @param ast - * @param formulaAddress + * @param state */ - public min(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.doMin(ast.args, formulaAddress) + public min(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.doMin(ast.args, state) } - public mina(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - const value = this.reduce(ast.args, formulaAddress, Number.POSITIVE_INFINITY, 'MINA', + public mina(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + const value = this.reduce(ast.args, state, Number.POSITIVE_INFINITY, 'MINA', (left: number, right: number) => Math.min(left, right), getRawValue, numbersBooleans) return zeroForInfinite(value) } - public count(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.doCount(ast.args, formulaAddress) + public count(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.doCount(ast.args, state) } - public counta(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.doCounta(ast.args, formulaAddress) + public counta(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.doCounta(ast.args, state) } - public average(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.doAverage(ast.args, formulaAddress) + public average(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.doAverage(ast.args, state) } - public averagea(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - const result = this.reduce(ast.args, formulaAddress, MomentsAggregate.empty, '_AGGREGATE_A', + public averagea(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + const result = this.reduce(ast.args, state, MomentsAggregate.empty, '_AGGREGATE_A', (left, right) => left.compose(right), (arg): MomentsAggregate => MomentsAggregate.single(getRawValue(arg)), numbersBooleans @@ -232,16 +229,16 @@ export class NumericAggregationPlugin extends FunctionPlugin { } } - public vars(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.doVarS(ast.args, formulaAddress) + public vars(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.doVarS(ast.args, state) } - public varp(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.doVarP(ast.args, formulaAddress) + public varp(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.doVarP(ast.args, state) } - public vara(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - const result = this.reduceAggregateA(ast.args, formulaAddress) + public vara(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + const result = this.reduceAggregateA(ast.args, state) if (result instanceof CellError) { return result @@ -250,8 +247,8 @@ export class NumericAggregationPlugin extends FunctionPlugin { } } - public varpa(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - const result = this.reduceAggregateA(ast.args, formulaAddress) + public varpa(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + const result = this.reduceAggregateA(ast.args, state) if (result instanceof CellError) { return result @@ -260,16 +257,16 @@ export class NumericAggregationPlugin extends FunctionPlugin { } } - public stdevs(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.doStdevS(ast.args, formulaAddress) + public stdevs(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.doStdevS(ast.args, state) } - public stdevp(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.doStdevP(ast.args, formulaAddress) + public stdevp(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.doStdevP(ast.args, state) } - public stdeva(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - const result = this.reduceAggregateA(ast.args, formulaAddress) + public stdeva(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + const result = this.reduceAggregateA(ast.args, state) if (result instanceof CellError) { return result @@ -279,8 +276,8 @@ export class NumericAggregationPlugin extends FunctionPlugin { } } - public stdevpa(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - const result = this.reduceAggregateA(ast.args, formulaAddress) + public stdevpa(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + const result = this.reduceAggregateA(ast.args, state) if (result instanceof CellError) { return result @@ -290,57 +287,57 @@ export class NumericAggregationPlugin extends FunctionPlugin { } } - public product(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.doProduct(ast.args, formulaAddress) + public product(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.doProduct(ast.args, state) } - public subtotal(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { + public subtotal(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { if (ast.args.length < 1) { return new CellError(ErrorType.NA, ErrorMessage.WrongArgNumber) } - const functionType = this.coerceToType(this.evaluateAst(ast.args[0], formulaAddress), {argumentType: ArgumentTypes.NUMBER}) + const functionType = this.coerceToType(this.evaluateAst(ast.args[0], state), {argumentType: ArgumentTypes.NUMBER}) const args = ast.args.slice(1) switch (functionType) { case 1: case 101: - return this.doAverage(args, formulaAddress) + return this.doAverage(args, state) case 2: case 102: - return this.doCount(args, formulaAddress) + return this.doCount(args, state) case 3: case 103: - return this.doCounta(args, formulaAddress) + return this.doCounta(args, state) case 4: case 104: - return this.doMax(args, formulaAddress) + return this.doMax(args, state) case 5: case 105: - return this.doMin(args, formulaAddress) + return this.doMin(args, state) case 6: case 106: - return this.doProduct(args, formulaAddress) + return this.doProduct(args, state) case 7: case 107: - return this.doStdevS(args, formulaAddress) + return this.doStdevS(args, state) case 8: case 108: - return this.doStdevP(args, formulaAddress) + return this.doStdevP(args, state) case 9: case 109: - return this.doSum(args, formulaAddress) + return this.doSum(args, state) case 10: case 110: - return this.doVarS(args, formulaAddress) + return this.doVarS(args, state) case 11: case 111: - return this.doVarP(args, formulaAddress) + return this.doVarP(args, state) default: return new CellError(ErrorType.VALUE, ErrorMessage.BadMode) } } - private reduceAggregate(args: Ast[], formulaAddress: SimpleCellAddress): MomentsAggregate | CellError{ - return this.reduce(args, formulaAddress, MomentsAggregate.empty, '_AGGREGATE', (left, right) => { + private reduceAggregate(args: Ast[], state: InterpreterState): MomentsAggregate | CellError{ + return this.reduce(args, state, MomentsAggregate.empty, '_AGGREGATE', (left, right) => { return left.compose(right) }, (arg): MomentsAggregate => { return MomentsAggregate.single(getRawValue(arg)) @@ -349,8 +346,8 @@ export class NumericAggregationPlugin extends FunctionPlugin { ) } - private reduceAggregateA(args: Ast[], formulaAddress: SimpleCellAddress): MomentsAggregate | CellError{ - return this.reduce(args, formulaAddress, MomentsAggregate.empty, '_AGGREGATE_A', (left, right) => { + private reduceAggregateA(args: Ast[], state: InterpreterState): MomentsAggregate | CellError{ + return this.reduce(args, state, MomentsAggregate.empty, '_AGGREGATE_A', (left, right) => { return left.compose(right) }, (arg): MomentsAggregate => { return MomentsAggregate.single(getRawValue(arg)) @@ -359,8 +356,8 @@ export class NumericAggregationPlugin extends FunctionPlugin { ) } - private doAverage(args: Ast[], formulaAddress: SimpleCellAddress): InternalScalarValue { - const result = this.reduceAggregate(args, formulaAddress) + private doAverage(args: Ast[], state: InterpreterState): InternalScalarValue { + const result = this.reduceAggregate(args, state) if (result instanceof CellError) { return result @@ -369,8 +366,8 @@ export class NumericAggregationPlugin extends FunctionPlugin { } } - private doVarS(args: Ast[], formulaAddress: SimpleCellAddress): InternalScalarValue { - const result = this.reduceAggregate(args, formulaAddress) + private doVarS(args: Ast[], state: InterpreterState): InternalScalarValue { + const result = this.reduceAggregate(args, state) if (result instanceof CellError) { return result @@ -379,8 +376,8 @@ export class NumericAggregationPlugin extends FunctionPlugin { } } - private doVarP(args: Ast[], formulaAddress: SimpleCellAddress): InternalScalarValue { - const result = this.reduceAggregate(args, formulaAddress) + private doVarP(args: Ast[], state: InterpreterState): InternalScalarValue { + const result = this.reduceAggregate(args, state) if (result instanceof CellError) { return result @@ -389,8 +386,8 @@ export class NumericAggregationPlugin extends FunctionPlugin { } } - private doStdevS(args: Ast[], formulaAddress: SimpleCellAddress): InternalScalarValue { - const result = this.reduceAggregate(args, formulaAddress) + private doStdevS(args: Ast[], state: InterpreterState): InternalScalarValue { + const result = this.reduceAggregate(args, state) if (result instanceof CellError) { return result @@ -400,8 +397,8 @@ export class NumericAggregationPlugin extends FunctionPlugin { } } - private doStdevP(args: Ast[], formulaAddress: SimpleCellAddress): InternalScalarValue { - const result = this.reduceAggregate(args, formulaAddress) + private doStdevP(args: Ast[], state: InterpreterState): InternalScalarValue { + const result = this.reduceAggregate(args, state) if (result instanceof CellError) { return result @@ -411,23 +408,23 @@ export class NumericAggregationPlugin extends FunctionPlugin { } } - private doCount(args: Ast[], formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.reduce(args, formulaAddress, 0, 'COUNT', + private doCount(args: Ast[], state: InterpreterState): InternalScalarValue { + return this.reduce(args, state, 0, 'COUNT', (left: number, right: number) => left + right, getRawValue, (arg) => (isExtendedNumber(arg)) ? 1 : 0 ) } - private doCounta(args: Ast[], formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.reduce(args, formulaAddress, 0, 'COUNTA', (left: number, right: number) => left + right, + private doCounta(args: Ast[], state: InterpreterState): InternalScalarValue { + return this.reduce(args, state, 0, 'COUNTA', (left: number, right: number) => left + right, getRawValue, (arg) => (arg === EmptyValue) ? 0 : 1 ) } - private doMax(args: Ast[], formulaAddress: SimpleCellAddress): InternalScalarValue { - const value = this.reduce(args, formulaAddress, Number.NEGATIVE_INFINITY, 'MAX', + private doMax(args: Ast[], state: InterpreterState): InternalScalarValue { + const value = this.reduce(args, state, Number.NEGATIVE_INFINITY, 'MAX', (left: number, right: number) => Math.max(left, right), getRawValue, strictlyNumbers ) @@ -435,8 +432,8 @@ export class NumericAggregationPlugin extends FunctionPlugin { return zeroForInfinite(value) } - private doMin(args: Ast[], formulaAddress: SimpleCellAddress): InternalScalarValue { - const value = this.reduce(args, formulaAddress, Number.POSITIVE_INFINITY, 'MAX', + private doMin(args: Ast[], state: InterpreterState): InternalScalarValue { + const value = this.reduce(args, state, Number.POSITIVE_INFINITY, 'MAX', (left: number, right: number) => Math.min(left, right), getRawValue, strictlyNumbers ) @@ -444,12 +441,12 @@ export class NumericAggregationPlugin extends FunctionPlugin { return zeroForInfinite(value) } - private doSum(args: Ast[], formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.reduce(args, formulaAddress, 0, 'SUM', this.addWithEpsilonRaw, getRawValue, strictlyNumbers) + private doSum(args: Ast[], state: InterpreterState): InternalScalarValue { + return this.reduce(args, state, 0, 'SUM', this.addWithEpsilonRaw, getRawValue, strictlyNumbers) } - private doProduct(args: Ast[], formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.reduce(args, formulaAddress, 1, 'PRODUCT', (left, right) => left * right, getRawValue, strictlyNumbers) + private doProduct(args: Ast[], state: InterpreterState): InternalScalarValue { + return this.reduce(args, state, 1, 'PRODUCT', (left, right) => left * right, getRawValue, strictlyNumbers) } private addWithEpsilonRaw = (left: number, right: number) => this.interpreter.arithmeticHelper.addWithEpsilonRaw(left, right) @@ -457,15 +454,15 @@ export class NumericAggregationPlugin extends FunctionPlugin { /** * Reduces procedure arguments with given reducing function * - * @param ast - cell range ast - * @param formulaAddress - address of the cell in which formula is located + * @param args + * @param state * @param initialAccValue - initial accumulator value for reducing function * @param functionName - function name to use as cache key * @param reducingFunction - reducing function * @param mapFunction - * @param coerceFunction + * @param coercionFunction * */ - private reduce(args: Ast[], formulaAddress: SimpleCellAddress, initialAccValue: T, functionName: string, reducingFunction: BinaryOperation, mapFunction: MapOperation, coercionFunction: coercionOperation): CellError | T { + private reduce(args: Ast[], state: InterpreterState, initialAccValue: T, functionName: string, reducingFunction: BinaryOperation, mapFunction: MapOperation, coercionFunction: coercionOperation): CellError | T { if (args.length < 1) { return new CellError(ErrorType.NA, ErrorMessage.WrongArgNumber) } @@ -474,10 +471,10 @@ export class NumericAggregationPlugin extends FunctionPlugin { return acc } if (arg.type === AstNodeType.CELL_RANGE || arg.type === AstNodeType.COLUMN_RANGE || arg.type === AstNodeType.ROW_RANGE) { - return this.evaluateRange(arg, formulaAddress, acc, functionName, reducingFunction, mapFunction, coercionFunction) + return this.evaluateRange(arg, state, acc, functionName, reducingFunction, mapFunction, coercionFunction) } let value - value = this.evaluateAst(arg, formulaAddress) + value = this.evaluateAst(arg, state) if (value instanceof SimpleRangeValue) { const coercedRangeValues = Array.from(value.valuesFromTopLeftCorner()) .map(coercionFunction) @@ -525,15 +522,17 @@ export class NumericAggregationPlugin extends FunctionPlugin { * Performs range operation on given range * * @param ast - cell range ast - * @param formulaAddress - address of the cell in which formula is located + * @param state * @param initialAccValue - initial accumulator value for reducing function * @param functionName - function name to use as cache key * @param reducingFunction - reducing function + * @param mapFunction + * @param coercionFunction */ - private evaluateRange(ast: CellRangeAst | ColumnRangeAst | RowRangeAst, formulaAddress: SimpleCellAddress, initialAccValue: T, functionName: string, reducingFunction: BinaryOperation, mapFunction: MapOperation, coercionFunction: coercionOperation): T | CellError { + private evaluateRange(ast: CellRangeAst | ColumnRangeAst | RowRangeAst, state: InterpreterState, initialAccValue: T, functionName: string, reducingFunction: BinaryOperation, mapFunction: MapOperation, coercionFunction: coercionOperation): T | CellError { let range try { - range = AbsoluteCellRange.fromAst(ast, formulaAddress) + range = AbsoluteCellRange.fromAst(ast, state.formulaAddress) } catch (err) { if (err.message === DIFFERENT_SHEETS_ERROR) { return new CellError(ErrorType.REF, ErrorMessage.RangeManySheets) @@ -573,6 +572,8 @@ export class NumericAggregationPlugin extends FunctionPlugin { * * @param functionName - function name (e.g. SUM) * @param range - cell range + * @param mapFunction + * @param coercionFunction */ private getRangeValues(functionName: string, range: AbsoluteCellRange, mapFunction: MapOperation, coercionFunction: coercionOperation): (T | CellError)[] { const rangeResult: (T | CellError)[] = [] diff --git a/src/interpreter/plugin/PowerPlugin.ts b/src/interpreter/plugin/PowerPlugin.ts index 8c56c81601..fb55232e10 100644 --- a/src/interpreter/plugin/PowerPlugin.ts +++ b/src/interpreter/plugin/PowerPlugin.ts @@ -3,12 +3,12 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class PowerPlugin extends FunctionPlugin { +export class PowerPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'POWER': { method: 'power', @@ -19,7 +19,7 @@ export class PowerPlugin extends FunctionPlugin { }, } - public power(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('POWER'), Math.pow) + public power(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('POWER'), Math.pow) } } diff --git a/src/interpreter/plugin/RadiansPlugin.ts b/src/interpreter/plugin/RadiansPlugin.ts index c301d2b951..4512be8cdc 100644 --- a/src/interpreter/plugin/RadiansPlugin.ts +++ b/src/interpreter/plugin/RadiansPlugin.ts @@ -3,12 +3,12 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class RadiansPlugin extends FunctionPlugin { +export class RadiansPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'RADIANS': { method: 'radians', @@ -18,8 +18,8 @@ export class RadiansPlugin extends FunctionPlugin { }, } - public radians(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('RADIANS'), + public radians(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('RADIANS'), (arg) => arg * (Math.PI / 180) ) } diff --git a/src/interpreter/plugin/RadixConversionPlugin.ts b/src/interpreter/plugin/RadixConversionPlugin.ts index a12265c834..1d87d4d08b 100644 --- a/src/interpreter/plugin/RadixConversionPlugin.ts +++ b/src/interpreter/plugin/RadixConversionPlugin.ts @@ -3,13 +3,14 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {padLeft} from '../../format/format' import {Maybe} from '../../Maybe' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' const MAX_LENGTH = 10 const DECIMAL_NUMBER_OF_BITS = 255 @@ -17,7 +18,7 @@ const MIN_BASE = 2 const MAX_BASE = 36 const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ' -export class RadixConversionPlugin extends FunctionPlugin { +export class RadixConversionPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'DEC2BIN': { method: 'dec2bin', @@ -117,26 +118,26 @@ export class RadixConversionPlugin extends FunctionPlugin { }, } - public dec2bin(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DEC2BIN'), + public dec2bin(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DEC2BIN'), (value, places) => decimalToBaseWithExactPadding(value, 2, places) ) } - public dec2oct(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DEC2OCT'), + public dec2oct(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DEC2OCT'), (value, places) => decimalToBaseWithExactPadding(value, 8, places) ) } - public dec2hex(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DEC2HEX'), + public dec2hex(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DEC2HEX'), (value, places) => decimalToBaseWithExactPadding(value, 16, places) ) } - public bin2dec(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BIN2DEC'), (binary) => { + public bin2dec(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BIN2DEC'), (binary) => { const binaryWithSign = coerceStringToBase(binary, 2, MAX_LENGTH) if(binaryWithSign === undefined) { return new CellError(ErrorType.NUM, ErrorMessage.NotBinary) @@ -145,8 +146,8 @@ export class RadixConversionPlugin extends FunctionPlugin { }) } - public bin2oct(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BIN2OCT'), (binary, places) => { + public bin2oct(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BIN2OCT'), (binary, places) => { const binaryWithSign = coerceStringToBase(binary, 2, MAX_LENGTH) if(binaryWithSign === undefined) { return new CellError(ErrorType.NUM, ErrorMessage.NotBinary) @@ -155,8 +156,8 @@ export class RadixConversionPlugin extends FunctionPlugin { }) } - public bin2hex(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BIN2HEX'), (binary, places) => { + public bin2hex(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BIN2HEX'), (binary, places) => { const binaryWithSign = coerceStringToBase(binary, 2, MAX_LENGTH) if(binaryWithSign === undefined) { return new CellError(ErrorType.NUM, ErrorMessage.NotBinary) @@ -165,8 +166,8 @@ export class RadixConversionPlugin extends FunctionPlugin { }) } - public oct2dec(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('OCT2DEC'), (octal) => { + public oct2dec(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('OCT2DEC'), (octal) => { const octalWithSign = coerceStringToBase(octal, 8, MAX_LENGTH) if(octalWithSign === undefined) { return new CellError(ErrorType.NUM, ErrorMessage.NotOctal) @@ -175,8 +176,8 @@ export class RadixConversionPlugin extends FunctionPlugin { }) } - public oct2bin(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('OCT2BIN'), (octal, places) => { + public oct2bin(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('OCT2BIN'), (octal, places) => { const octalWithSign = coerceStringToBase(octal, 8, MAX_LENGTH) if(octalWithSign === undefined) { return new CellError(ErrorType.NUM, ErrorMessage.NotOctal) @@ -185,8 +186,8 @@ export class RadixConversionPlugin extends FunctionPlugin { }) } - public oct2hex(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('OCT2HEX'), (octal, places) => { + public oct2hex(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('OCT2HEX'), (octal, places) => { const octalWithSign = coerceStringToBase(octal, 8, MAX_LENGTH) if(octalWithSign === undefined) { return new CellError(ErrorType.NUM, ErrorMessage.NotOctal) @@ -195,8 +196,8 @@ export class RadixConversionPlugin extends FunctionPlugin { }) } - public hex2dec(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HEX2DEC'), (hexadecimal) => { + public hex2dec(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HEX2DEC'), (hexadecimal) => { const hexadecimalWithSign = coerceStringToBase(hexadecimal, 16, MAX_LENGTH) if(hexadecimalWithSign === undefined) { return new CellError(ErrorType.NUM, ErrorMessage.NotHex) @@ -205,8 +206,8 @@ export class RadixConversionPlugin extends FunctionPlugin { }) } - public hex2bin(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HEX2BIN'), (hexadecimal, places) => { + public hex2bin(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HEX2BIN'), (hexadecimal, places) => { const hexadecimalWithSign = coerceStringToBase(hexadecimal, 16, MAX_LENGTH) if(hexadecimalWithSign === undefined) { return new CellError(ErrorType.NUM, ErrorMessage.NotHex) @@ -215,8 +216,8 @@ export class RadixConversionPlugin extends FunctionPlugin { }) } - public hex2oct(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HEX2OCT'), (hexadecimal, places) => { + public hex2oct(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HEX2OCT'), (hexadecimal, places) => { const hexadecimalWithSign = coerceStringToBase(hexadecimal, 16, MAX_LENGTH) if(hexadecimalWithSign === undefined) { return new CellError(ErrorType.NUM, ErrorMessage.NotHex) @@ -225,12 +226,12 @@ export class RadixConversionPlugin extends FunctionPlugin { }) } - public base(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BASE'), decimalToBaseWithMinimumPadding) + public base(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BASE'), decimalToBaseWithMinimumPadding) } - public decimal(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DECIMAL'), (arg, base) => { + public decimal(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DECIMAL'), (arg, base) => { const input = coerceStringToBase(arg, base, DECIMAL_NUMBER_OF_BITS) if(input === undefined) { return new CellError(ErrorType.NUM, ErrorMessage.NotHex) diff --git a/src/interpreter/plugin/RandomPlugin.ts b/src/interpreter/plugin/RandomPlugin.ts index 0742287139..a49185d264 100644 --- a/src/interpreter/plugin/RandomPlugin.ts +++ b/src/interpreter/plugin/RandomPlugin.ts @@ -3,13 +3,14 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class RandomPlugin extends FunctionPlugin { +export class RandomPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'RAND': { method: 'rand', @@ -33,14 +34,14 @@ export class RandomPlugin extends FunctionPlugin { * in the range [0,1). * * @param ast - * @param formulaAddress + * @param state */ - public rand(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('RAND'), Math.random) + public rand(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('RAND'), Math.random) } - public randbetween(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('RANDBETWEEN'), + public randbetween(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('RANDBETWEEN'), (lower: number, upper: number) => { if(upper{ public static implementedFunctions = { 'ROMAN': { method: 'roman', @@ -26,8 +27,8 @@ export class RomanPlugin extends FunctionPlugin { }, } - public roman(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ROMAN'), + public roman(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ROMAN'), (val: number, mode: RawScalarValue) => { val = Math.trunc(val) if(mode === false) { @@ -51,8 +52,8 @@ export class RomanPlugin extends FunctionPlugin { ) } - public arabic(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ARABIC'), + public arabic(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ARABIC'), (inputString: string) => { inputString = inputString.trim().toUpperCase() let minusSign = false diff --git a/src/interpreter/plugin/RoundingPlugin.ts b/src/interpreter/plugin/RoundingPlugin.ts index aa70f4be07..9db385b6c7 100644 --- a/src/interpreter/plugin/RoundingPlugin.ts +++ b/src/interpreter/plugin/RoundingPlugin.ts @@ -3,11 +3,12 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' export function findNextOddNumber(arg: number): number { const ceiled = Math.ceil(arg) @@ -19,7 +20,7 @@ export function findNextEvenNumber(arg: number): number { return (ceiled % 2 === 0) ? ceiled : ceiled + 1 } -export class RoundingPlugin extends FunctionPlugin { +export class RoundingPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'ROUNDUP': { method: 'roundup', @@ -117,8 +118,8 @@ export class RoundingPlugin extends FunctionPlugin { 'ISO.CEILING': 'CEILING.PRECISE', } - public roundup(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ROUNDDOWN'), (numberToRound: number, places: number): number => { + public roundup(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ROUNDDOWN'), (numberToRound: number, places: number): number => { const placesMultiplier = Math.pow(10, places) if (numberToRound < 0) { return -Math.ceil(-numberToRound * placesMultiplier) / placesMultiplier @@ -128,8 +129,8 @@ export class RoundingPlugin extends FunctionPlugin { }) } - public rounddown(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ROUNDDOWN'), (numberToRound: number, places: number): number => { + public rounddown(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ROUNDDOWN'), (numberToRound: number, places: number): number => { const placesMultiplier = Math.pow(10, places) if (numberToRound < 0) { return -Math.floor(-numberToRound * placesMultiplier) / placesMultiplier @@ -139,8 +140,8 @@ export class RoundingPlugin extends FunctionPlugin { }) } - public round(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ROUND'), (numberToRound: number, places: number): number => { + public round(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ROUND'), (numberToRound: number, places: number): number => { const placesMultiplier = Math.pow(10, places) if (numberToRound < 0) { return -Math.round(-numberToRound * placesMultiplier) / placesMultiplier @@ -150,12 +151,12 @@ export class RoundingPlugin extends FunctionPlugin { }) } - public trunc(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.rounddown(ast, formulaAddress) + public trunc(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.rounddown(ast, state) } - public intFunc(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('INT'), (coercedNumberToRound) => { + public intFunc(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('INT'), (coercedNumberToRound) => { if (coercedNumberToRound < 0) { return -Math.floor(-coercedNumberToRound) } else { @@ -164,8 +165,8 @@ export class RoundingPlugin extends FunctionPlugin { }) } - public even(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('EVEN'), (coercedNumberToRound) => { + public even(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('EVEN'), (coercedNumberToRound) => { if (coercedNumberToRound < 0) { return -findNextEvenNumber(-coercedNumberToRound) } else { @@ -174,8 +175,8 @@ export class RoundingPlugin extends FunctionPlugin { }) } - public odd(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ODD'), (coercedNumberToRound) => { + public odd(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ODD'), (coercedNumberToRound) => { if (coercedNumberToRound < 0) { return -findNextOddNumber(-coercedNumberToRound) } else { @@ -184,8 +185,8 @@ export class RoundingPlugin extends FunctionPlugin { }) } - public ceilingmath(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CEILING.MATH'), + public ceilingmath(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CEILING.MATH'), (value: number, significance: number, mode: number) => { if (significance === 0 || value === 0) { return 0 @@ -200,8 +201,8 @@ export class RoundingPlugin extends FunctionPlugin { }) } - public ceiling(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CEILING'), + public ceiling(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CEILING'), (value: number, significance: number) => { if(value === 0) { return 0 @@ -218,8 +219,8 @@ export class RoundingPlugin extends FunctionPlugin { }) } - public ceilingprecise(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CEILING.PRECISE'), + public ceilingprecise(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CEILING.PRECISE'), (value: number, significance: number) => { if (significance === 0 || value === 0) { return 0 @@ -229,8 +230,8 @@ export class RoundingPlugin extends FunctionPlugin { }) } - public floormath(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('FLOOR.MATH'), + public floormath(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('FLOOR.MATH'), (value: number, significance: number, mode: number) => { if (significance === 0 || value === 0) { return 0 @@ -245,8 +246,8 @@ export class RoundingPlugin extends FunctionPlugin { }) } - public floor(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('FLOOR'), + public floor(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('FLOOR'), (value: number, significance: number) => { if(value === 0) { return 0 @@ -263,8 +264,8 @@ export class RoundingPlugin extends FunctionPlugin { }) } - public floorprecise(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('FLOOR.PRECISE'), + public floorprecise(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('FLOOR.PRECISE'), (value: number, significance: number) => { if (significance === 0 || value === 0) { return 0 diff --git a/src/interpreter/plugin/SimpleArithmertic.ts b/src/interpreter/plugin/SimpleArithmertic.ts index 1ba92e7aac..3b0fb8690e 100644 --- a/src/interpreter/plugin/SimpleArithmertic.ts +++ b/src/interpreter/plugin/SimpleArithmertic.ts @@ -3,12 +3,12 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class SimpleArithmerticPlugin extends FunctionPlugin { +export class SimpleArithmerticPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'HF.ADD': { method: 'add', @@ -114,92 +114,92 @@ export class SimpleArithmerticPlugin extends FunctionPlugin { }, } - public add(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.ADD'), + public add(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.ADD'), this.interpreter.arithmeticHelper.addWithEpsilon ) } - public concat(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.CONCAT'), + public concat(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.CONCAT'), this.interpreter.arithmeticHelper.concat ) } - public divide(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.DIVIDE'), + public divide(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.DIVIDE'), this.interpreter.arithmeticHelper.divide ) } - public eq(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.EQ'), + public eq(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.EQ'), this.interpreter.arithmeticHelper.eq ) } - public gt(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.GT'), + public gt(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.GT'), this.interpreter.arithmeticHelper.gt ) } - public gte(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.GTE'), + public gte(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.GTE'), this.interpreter.arithmeticHelper.geq ) } - public lt(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.LT'), + public lt(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.LT'), this.interpreter.arithmeticHelper.lt ) } - public lte(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.LTE'), + public lte(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.LTE'), this.interpreter.arithmeticHelper.leq ) } - public minus(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.MINUS'), + public minus(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.MINUS'), this.interpreter.arithmeticHelper.subtract ) } - public multiply(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.MULTIPLY'), + public multiply(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.MULTIPLY'), this.interpreter.arithmeticHelper.multiply ) } - public ne(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.NE'), + public ne(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.NE'), this.interpreter.arithmeticHelper.neq ) } - public pow(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.POW'), + public pow(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.POW'), this.interpreter.arithmeticHelper.pow ) } - public uminus(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.UMINUS'), + public uminus(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.UMINUS'), this.interpreter.arithmeticHelper.unaryMinus ) } - public upercent(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.UNARY_PERCENT'), + public upercent(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.UNARY_PERCENT'), this.interpreter.arithmeticHelper.unaryPercent ) } - public uplus(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HF.UPLUS'), + public uplus(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HF.UPLUS'), this.interpreter.arithmeticHelper.unaryPlus ) } diff --git a/src/interpreter/plugin/SqrtPlugin.ts b/src/interpreter/plugin/SqrtPlugin.ts index fe6088a18a..cbb4ef3679 100644 --- a/src/interpreter/plugin/SqrtPlugin.ts +++ b/src/interpreter/plugin/SqrtPlugin.ts @@ -3,12 +3,12 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class SqrtPlugin extends FunctionPlugin { +export class SqrtPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'SQRT': { method: 'sqrt', @@ -18,7 +18,7 @@ export class SqrtPlugin extends FunctionPlugin { }, } - public sqrt(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SQRT'), Math.sqrt) + public sqrt(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SQRT'), Math.sqrt) } } diff --git a/src/interpreter/plugin/StatisticalAggregationPlugin.ts b/src/interpreter/plugin/StatisticalAggregationPlugin.ts index 377a2cf3f5..89a30d48e7 100644 --- a/src/interpreter/plugin/StatisticalAggregationPlugin.ts +++ b/src/interpreter/plugin/StatisticalAggregationPlugin.ts @@ -3,9 +3,10 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {getRawValue, InternalScalarValue, isExtendedNumber, RawInterpreterValue} from '../InterpreterValue' import {SimpleRangeValue} from '../SimpleRangeValue' import { @@ -21,9 +22,9 @@ import { sumsqerr, variance } from './3rdparty/jstat/jstat' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class StatisticalAggregationPlugin extends FunctionPlugin { +export class StatisticalAggregationPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'AVEDEV': { method: 'avedev', @@ -153,8 +154,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { SKEWP: 'SKEW.P', } - public avedev(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('AVEDEV'), + public avedev(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('AVEDEV'), (...args: RawInterpreterValue[]) => { const coerced = this.interpreter.arithmeticHelper.coerceNumbersExactRanges(args) if(coerced instanceof CellError) { @@ -168,8 +169,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { }) } - public devsq(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('DEVSQ'), + public devsq(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('DEVSQ'), (...args: RawInterpreterValue[]) => { const coerced = this.interpreter.arithmeticHelper.coerceNumbersExactRanges(args) if(coerced instanceof CellError) { @@ -182,8 +183,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { }) } - public geomean(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('GEOMEAN'), + public geomean(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('GEOMEAN'), (...args: RawInterpreterValue[]) => { const coerced = this.interpreter.arithmeticHelper.coerceNumbersExactRanges(args) if(coerced instanceof CellError) { @@ -201,8 +202,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { }) } - public harmean(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HARMEAN'), + public harmean(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HARMEAN'), (...args: RawInterpreterValue[]) => { const coerced = this.interpreter.arithmeticHelper.coerceNumbersExactRanges(args) if(coerced instanceof CellError) { @@ -220,8 +221,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { }) } - public correl(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CORREL'), + public correl(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CORREL'), (dataX: SimpleRangeValue, dataY: SimpleRangeValue) => { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new CellError(ErrorType.NA, ErrorMessage.EqualLength) @@ -238,8 +239,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { }) } - public rsq(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('RSQ'), + public rsq(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('RSQ'), (dataX: SimpleRangeValue, dataY: SimpleRangeValue) => { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new CellError(ErrorType.NA, ErrorMessage.EqualLength) @@ -257,8 +258,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { }) } - public covariancep(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('COVARIANCE.P'), + public covariancep(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('COVARIANCE.P'), (dataX: SimpleRangeValue, dataY: SimpleRangeValue) => { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new CellError(ErrorType.NA, ErrorMessage.EqualLength) @@ -279,8 +280,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { }) } - public covariances(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('COVARIANCE.S'), + public covariances(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('COVARIANCE.S'), (dataX: SimpleRangeValue, dataY: SimpleRangeValue) => { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new CellError(ErrorType.NA, ErrorMessage.EqualLength) @@ -298,8 +299,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { }) } - public ztest(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('Z.TEST'), + public ztest(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('Z.TEST'), (range: SimpleRangeValue, x: number, sigma?: number) => { const vals = this.interpreter.arithmeticHelper.manyToExactNumbers(range.valuesFromTopLeftCorner()) if(vals instanceof CellError) { @@ -323,8 +324,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { ) } - public ftest(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('F.TEST'), + public ftest(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('F.TEST'), (dataX: SimpleRangeValue, dataY: SimpleRangeValue) => { const arrX = this.interpreter.arithmeticHelper.manyToExactNumbers(dataX.valuesFromTopLeftCorner()) const arrY = this.interpreter.arithmeticHelper.manyToExactNumbers(dataY.valuesFromTopLeftCorner()) @@ -348,8 +349,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { }) } - public steyx(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('STEYX'), + public steyx(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('STEYX'), (dataX: SimpleRangeValue, dataY: SimpleRangeValue) => { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new CellError(ErrorType.NA, ErrorMessage.EqualLength) @@ -367,8 +368,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { }) } - public slope(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SLOPE'), + public slope(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SLOPE'), (dataX: SimpleRangeValue, dataY: SimpleRangeValue) => { if (dataX.numberOfElements() !== dataY.numberOfElements()) { return new CellError(ErrorType.NA, ErrorMessage.EqualLength) @@ -386,8 +387,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { }) } - public chisqtest(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CHISQ.TEST'), + public chisqtest(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CHISQ.TEST'), (dataX: SimpleRangeValue, dataY: SimpleRangeValue) => { const r = dataX.height() const c = dataX.width() @@ -416,8 +417,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { }) } - public ttest(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('T.TEST'), + public ttest(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('T.TEST'), (dataX: SimpleRangeValue, dataY: SimpleRangeValue, tails: number, type: number) => { const arrX = this.interpreter.arithmeticHelper.manyToExactNumbers(dataX.valuesFromTopLeftCorner()) const arrY = this.interpreter.arithmeticHelper.manyToExactNumbers(dataY.valuesFromTopLeftCorner()) @@ -472,8 +473,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { }) } - public skew(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SKEW'), + public skew(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SKEW'), (...args: RawInterpreterValue[]) => { const coerced = this.interpreter.arithmeticHelper.coerceNumbersExactRanges(args) if(coerced instanceof CellError) { @@ -492,8 +493,8 @@ export class StatisticalAggregationPlugin extends FunctionPlugin { }) } - public skewp(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SKEW.P'), + public skewp(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SKEW.P'), (...args: RawInterpreterValue[]) => { const coerced = this.interpreter.arithmeticHelper.coerceNumbersExactRanges(args) if(coerced instanceof CellError) { diff --git a/src/interpreter/plugin/StatisticalPlugin.ts b/src/interpreter/plugin/StatisticalPlugin.ts index 6d72a28db4..66fd3e00c5 100644 --- a/src/interpreter/plugin/StatisticalPlugin.ts +++ b/src/interpreter/plugin/StatisticalPlugin.ts @@ -3,9 +3,10 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' import {besseli, besselj, besselk, bessely} from './3rdparty/bessel/bessel' import { @@ -29,9 +30,9 @@ import { tci, weibull } from './3rdparty/jstat/jstat' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class StatisticalPlugin extends FunctionPlugin { +export class StatisticalPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'ERF': { method: 'erf', @@ -425,8 +426,8 @@ export class StatisticalPlugin extends FunctionPlugin { POISSONDIST: 'POISSON.DIST', } - public erf(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ERF'), (lowerBound, upperBound) => { + public erf(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ERF'), (lowerBound, upperBound) => { if (upperBound === undefined) { return erf(lowerBound) } else { @@ -435,13 +436,13 @@ export class StatisticalPlugin extends FunctionPlugin { }) } - public erfc(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ERFC'), erfc) + public erfc(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ERFC'), erfc) } - public expondist(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('EXPON.DIST'), + public expondist(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('EXPON.DIST'), (x: number, lambda: number, cumulative: boolean) => { if(cumulative) { return exponential.cdf(x, lambda) @@ -452,24 +453,24 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public fisher(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('FISHER'), + public fisher(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('FISHER'), (x: number) => Math.log((1 + x) / (1 - x)) / 2 ) } - public fisherinv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('FISHERINV'), + public fisherinv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('FISHERINV'), (y: number) => 1 - 2 / (Math.exp(2 * y) + 1) ) } - public gamma(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('GAMMA'), gammafn) + public gamma(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('GAMMA'), gammafn) } - public gammadist(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('GAMMA.DIST'), + public gammadist(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('GAMMA.DIST'), (value: number, alphaVal: number, betaVal: number, cumulative: boolean) => { if(cumulative) { return gamma.cdf(value, alphaVal, betaVal) @@ -480,22 +481,22 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public gammaln(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('GAMMALN'), gammaln) + public gammaln(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('GAMMALN'), gammaln) } - public gammainv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('GAMMA.INV'), gamma.inv) + public gammainv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('GAMMA.INV'), gamma.inv) } - public gauss(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('GAUSS'), + public gauss(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('GAUSS'), (z: number) => normal.cdf(z, 0, 1) - 0.5 ) } - public betadist(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BETA.DIST'), + public betadist(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BETA.DIST'), (x: number, alphaVal: number, betaVal: number, cumulative: boolean, A: number, B: number) => { if(x<=A) { return new CellError(ErrorType.NUM, ErrorMessage.ValueSmall) @@ -512,8 +513,8 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public betainv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BETA.INV'), + public betainv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BETA.INV'), (x: number, alphaVal: number, betaVal: number, A: number, B: number) => { if (A >= B) { return new CellError(ErrorType.NUM, ErrorMessage.WrongOrder) @@ -524,8 +525,8 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public binomialdist(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BINOM.DIST'), + public binomialdist(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BINOM.DIST'), (succ: number, trials: number, prob: number, cumulative: boolean) => { if(succ>trials) { return new CellError(ErrorType.NUM, ErrorMessage.WrongOrder) @@ -541,8 +542,8 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public binomialinv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BINOM.INV'), + public binomialinv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BINOM.INV'), (trials: number, prob: number, alpha: number) => { trials = Math.trunc(trials) let lower = -1 @@ -560,32 +561,32 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public besselifn(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BESSELI'), + public besselifn(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BESSELI'), (x: number, n: number) => besseli(x, Math.trunc(n)) ) } - public besseljfn(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BESSELJ'), + public besseljfn(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BESSELJ'), (x: number, n: number) => besselj(x, Math.trunc(n)) ) } - public besselkfn(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BESSELK'), + public besselkfn(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BESSELK'), (x: number, n: number) => besselk(x, Math.trunc(n)) ) } - public besselyfn(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('BESSELY'), + public besselyfn(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('BESSELY'), (x: number, n: number) => bessely(x, Math.trunc(n)) ) } - public chisqdist(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CHISQ.DIST'), + public chisqdist(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CHISQ.DIST'), (x: number, deg: number, cumulative: boolean) => { deg = Math.trunc(deg) if(cumulative) { @@ -597,26 +598,26 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public chisqdistrt(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CHISQ.DIST.RT'), + public chisqdistrt(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CHISQ.DIST.RT'), (x: number, deg: number) => 1 - chisquare.cdf(x, Math.trunc(deg)) ) } - public chisqinv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CHISQ.INV'), + public chisqinv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CHISQ.INV'), (p: number, deg: number) => chisquare.inv(p, Math.trunc(deg)) ) } - public chisqinvrt(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CHISQ.INV.RT'), + public chisqinvrt(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CHISQ.INV.RT'), (p: number, deg: number) => chisquare.inv(1.0 - p, Math.trunc(deg)) ) } - public fdist(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('F.DIST'), + public fdist(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('F.DIST'), (x: number, deg1: number, deg2: number, cumulative: boolean) => { deg1 = Math.trunc(deg1) deg2 = Math.trunc(deg2) @@ -629,27 +630,27 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public fdistrt(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('F.DIST.RT'), + public fdistrt(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('F.DIST.RT'), (x: number, deg1: number, deg2: number) => 1 - centralF.cdf(x, Math.trunc(deg1), Math.trunc(deg2)) ) } - public finv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('F.INV'), + public finv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('F.INV'), (p: number, deg1: number, deg2: number) => centralF.inv(p, Math.trunc(deg1), Math.trunc(deg2)) ) } - public finvrt(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('F.INV.RT'), + public finvrt(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('F.INV.RT'), (p: number, deg1: number, deg2: number) => centralF.inv(1.0 - p, Math.trunc(deg1), Math.trunc(deg2)) ) } - public weibulldist(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('WEIBULL.DIST'), + public weibulldist(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('WEIBULL.DIST'), (x: number, shape: number, scale: number, cumulative: boolean) => { if(cumulative) { return weibull.cdf(x, scale, shape) @@ -660,8 +661,8 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public poissondist(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('POISSON.DIST'), + public poissondist(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('POISSON.DIST'), (x: number, mean: number, cumulative: boolean) => { x = Math.trunc(x) if(cumulative) { @@ -673,8 +674,8 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public hypgeomdist(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('HYPGEOM.DIST'), + public hypgeomdist(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('HYPGEOM.DIST'), (s: number, numberS: number, populationS: number, numberPop: number, cumulative: boolean) => { if(s > numberS || s > populationS || numberS > numberPop || populationS > numberPop) { return new CellError(ErrorType.NUM, ErrorMessage.ValueLarge) @@ -696,8 +697,8 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public tdist(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('T.DIST'), + public tdist(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('T.DIST'), (x: number, deg: number, cumulative: boolean) => { deg = Math.trunc(deg) if(cumulative) { @@ -709,38 +710,38 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public tdist2t(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('T.DIST.2T'), + public tdist2t(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('T.DIST.2T'), (x: number, deg: number) => (1 - studentt.cdf(x, Math.trunc(deg))) * 2 ) } - public tdistrt(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('T.DIST.RT'), + public tdistrt(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('T.DIST.RT'), (x: number, deg: number) => 1 - studentt.cdf(x, Math.trunc(deg)) ) } - public tdistold(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('TDIST'), + public tdistold(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('TDIST'), (x: number, deg: number, mode: number) => mode*(1 - studentt.cdf(x, Math.trunc(deg))) ) } - public tinv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('T.INV'), + public tinv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('T.INV'), (p: number, deg: number) => studentt.inv(p, Math.trunc(deg)) ) } - public tinv2t(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('T.INV.2T'), + public tinv2t(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('T.INV.2T'), (p: number, deg: number) => studentt.inv(1-p/2, Math.trunc(deg)) ) } - public lognormdist(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('LOGNORM.DIST'), + public lognormdist(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('LOGNORM.DIST'), (x: number, mean: number, stddev: number, cumulative: boolean) => { if(cumulative) { return lognormal.cdf(x, mean, stddev) @@ -751,14 +752,14 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public lognorminv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('LOGNORM.INV'), + public lognorminv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('LOGNORM.INV'), (p: number, mean: number, stddev: number) => lognormal.inv(p, mean, stddev) ) } - public normdist(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('NORM.DIST'), + public normdist(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('NORM.DIST'), (x: number, mean: number, stddev: number, cumulative: boolean) => { if(cumulative) { return normal.cdf(x, mean, stddev) @@ -769,14 +770,14 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public norminv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('NORM.INV'), + public norminv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('NORM.INV'), (p: number, mean: number, stddev: number) => normal.inv(p, mean, stddev) ) } - public normsdist(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('NORM.S.DIST'), + public normsdist(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('NORM.S.DIST'), (x: number, cumulative: boolean) => { if(cumulative) { return normal.cdf(x, 0, 1) @@ -787,20 +788,20 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public normsinv(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('NORM.S.INV'), + public normsinv(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('NORM.S.INV'), (p: number) => normal.inv(p, 0, 1) ) } - public phi(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('PHI'), + public phi(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('PHI'), (x: number) => normal.pdf(x, 0, 1) ) } - public negbinomdist(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('NEGBINOM.DIST'), + public negbinomdist(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('NEGBINOM.DIST'), (nf: number, ns: number, p: number, cumulative: boolean) => { nf = Math.trunc(nf) ns = Math.trunc(ns) @@ -813,16 +814,16 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public confidencenorm(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CONFIDENCE.NORM'), + public confidencenorm(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CONFIDENCE.NORM'), // eslint-disable-next-line // @ts-ignore (alpha: number, stddev: number, size: number) => normalci(1, alpha, stddev, Math.trunc(size))[1] - 1 ) } - public confidencet(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CONFIDENCE.T'), + public confidencet(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CONFIDENCE.T'), (alpha: number, stddev: number, size: number) => { size = Math.trunc(size) if(size===1) { @@ -835,8 +836,8 @@ export class StatisticalPlugin extends FunctionPlugin { ) } - public standardize(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('STANDARDIZE'), + public standardize(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('STANDARDIZE'), (x: number, mean: number, stddev: number) => (x-mean)/stddev ) } diff --git a/src/interpreter/plugin/SumifPlugin.ts b/src/interpreter/plugin/SumifPlugin.ts index 51f4279df7..ec92236d4d 100644 --- a/src/interpreter/plugin/SumifPlugin.ts +++ b/src/interpreter/plugin/SumifPlugin.ts @@ -3,14 +3,15 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {Maybe} from '../../Maybe' import {ProcedureAst} from '../../parser' import {Condition, CriterionFunctionCompute} from '../CriterionFunctionCompute' +import {InterpreterState} from '../InterpreterState' import {getRawValue, InternalScalarValue, isExtendedNumber, RawScalarValue} from '../InterpreterValue' import {SimpleRangeValue} from '../SimpleRangeValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' class AverageResult { @@ -58,7 +59,7 @@ function countifsCacheKey(conditions: Condition[]): string { return ['COUNTIFS', ...conditionsStrings].join(',') } -export class SumifPlugin extends FunctionPlugin { +export class SumifPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'SUMIF': { method: 'sumif', @@ -110,10 +111,10 @@ export class SumifPlugin extends FunctionPlugin { * SumRange is the range on which adding will be performed. * * @param ast - * @param formulaAddress + * @param state */ - public sumif(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SUMIF'), + public sumif(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SUMIF'), (conditionArg: SimpleRangeValue, criterionValue: RawScalarValue, valuesArg: Maybe) => { const criterion = this.interpreter.criterionBuilder.fromCellValue(criterionValue, this.interpreter.arithmeticHelper) if (criterion === undefined) { @@ -133,8 +134,8 @@ export class SumifPlugin extends FunctionPlugin { ) } - public sumifs(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SUMIFS'), (values: SimpleRangeValue, ...args) => { + public sumifs(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SUMIFS'), (values: SimpleRangeValue, ...args) => { const conditions: Condition[] = [] for (let i = 0; i < args.length; i += 2) { const conditionArg = args[i] as SimpleRangeValue @@ -155,8 +156,8 @@ export class SumifPlugin extends FunctionPlugin { }) } - public averageif(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('AVERAGEIF'), + public averageif(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('AVERAGEIF'), (conditionArg: SimpleRangeValue, criterionValue: RawScalarValue, valuesArg: Maybe) => { const criterion = this.interpreter.criterionBuilder.fromCellValue(criterionValue, this.interpreter.arithmeticHelper) if (criterion === undefined) { @@ -196,10 +197,10 @@ export class SumifPlugin extends FunctionPlugin { * Returns number of cells on which criteria evaluates to true. * * @param ast - * @param formulaAddress + * @param state */ - public countif(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('COUNTIF'), + public countif(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('COUNTIF'), (conditionArg: SimpleRangeValue, criterionValue: RawScalarValue) => { const criterion = this.interpreter.criterionBuilder.fromCellValue(criterionValue, this.interpreter.arithmeticHelper) if (criterion === undefined) { @@ -217,8 +218,8 @@ export class SumifPlugin extends FunctionPlugin { ) } - public countifs(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('COUNTIFS'), (...args) => { + public countifs(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('COUNTIFS'), (...args) => { const conditions: Condition[] = [] for (let i = 0; i < args.length; i += 2) { const conditionArg = args[i] as SimpleRangeValue diff --git a/src/interpreter/plugin/SumprodPlugin.ts b/src/interpreter/plugin/SumprodPlugin.ts index 1f1a25ec7e..2ce06cfd93 100644 --- a/src/interpreter/plugin/SumprodPlugin.ts +++ b/src/interpreter/plugin/SumprodPlugin.ts @@ -3,14 +3,15 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {getRawValue, InternalScalarValue, isExtendedNumber} from '../InterpreterValue' import {SimpleRangeValue} from '../SimpleRangeValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' -export class SumprodPlugin extends FunctionPlugin { +export class SumprodPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'SUMPRODUCT': { method: 'sumproduct', @@ -21,8 +22,8 @@ export class SumprodPlugin extends FunctionPlugin { }, } - public sumproduct(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SUMPRODUCT'), (left: SimpleRangeValue, right: SimpleRangeValue) => { + public sumproduct(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SUMPRODUCT'), (left: SimpleRangeValue, right: SimpleRangeValue) => { if (left.numberOfElements() !== right.numberOfElements()) { return new CellError(ErrorType.VALUE, ErrorMessage.EqualLength) } diff --git a/src/interpreter/plugin/TextPlugin.ts b/src/interpreter/plugin/TextPlugin.ts index a7bacbb67a..8323007ccf 100644 --- a/src/interpreter/plugin/TextPlugin.ts +++ b/src/interpreter/plugin/TextPlugin.ts @@ -3,16 +3,17 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue, RawScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' /** * Interpreter plugin containing text-specific functions */ -export class TextPlugin extends FunctionPlugin { +export class TextPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'CONCATENATE': { method: 'concatenate', @@ -148,11 +149,11 @@ export class TextPlugin extends FunctionPlugin { * * Concatenates provided arguments to one string. * - * @param args - * @param formulaAddress + * @param ast + * @param state */ - public concatenate(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CONCATENATE'), (...args) => { + public concatenate(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CONCATENATE'), (...args) => { return ''.concat(...args) }) } @@ -163,10 +164,10 @@ export class TextPlugin extends FunctionPlugin { * Splits provided string using space separator and returns chunk at zero-based position specified by second argument * * @param ast - * @param formulaAddress + * @param state */ - public split(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SPLIT'), (stringToSplit: string, indexToUse: number) => { + public split(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SPLIT'), (stringToSplit: string, indexToUse: number) => { const splittedString = stringToSplit.split(' ') if (indexToUse >= splittedString.length || indexToUse < 0) { @@ -177,45 +178,45 @@ export class TextPlugin extends FunctionPlugin { }) } - public len(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('LEN'), (arg: string) => { + public len(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('LEN'), (arg: string) => { return arg.length }) } - public lower(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('LOWER'), (arg: string) => { + public lower(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('LOWER'), (arg: string) => { return arg.toLowerCase() }) } - public trim(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('TRIM'), (arg: string) => { + public trim(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('TRIM'), (arg: string) => { return arg.replace(/^ +| +$/g, '').replace(/ +/g, ' ') }) } - public proper(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('PROPER'), (arg: string) => { + public proper(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('PROPER'), (arg: string) => { return arg.replace(/\w\S*/g, word => word.charAt(0).toUpperCase() + word.substring(1).toLowerCase()) }) } - public clean(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CLEAN'), (arg: string) => { + public clean(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CLEAN'), (arg: string) => { // eslint-disable-next-line no-control-regex return arg.replace(/[\u0000-\u001F]/g, '') }) } - public exact(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('EXACT'), (left: string, right: string) => { + public exact(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('EXACT'), (left: string, right: string) => { return left === right }) } - public rept(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('REPT'), (text: string, count: number) => { + public rept(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('REPT'), (text: string, count: number) => { if (count < 0) { return new CellError(ErrorType.VALUE, ErrorMessage.NegativeCount) } @@ -223,8 +224,8 @@ export class TextPlugin extends FunctionPlugin { }) } - public right(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('RIGHT'), (text: string, length: number) => { + public right(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('RIGHT'), (text: string, length: number) => { if (length < 0) { return new CellError(ErrorType.VALUE, ErrorMessage.NegativeLength) } else if (length === 0) { @@ -234,8 +235,8 @@ export class TextPlugin extends FunctionPlugin { }) } - public left(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('LEFT'), (text: string, length: number) => { + public left(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('LEFT'), (text: string, length: number) => { if (length < 0) { return new CellError(ErrorType.VALUE, ErrorMessage.NegativeLength) } @@ -243,8 +244,8 @@ export class TextPlugin extends FunctionPlugin { }) } - public mid(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('MID'), (text: string, startPosition: number, numberOfChars: number) => { + public mid(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('MID'), (text: string, startPosition: number, numberOfChars: number) => { if (startPosition < 1) { return new CellError(ErrorType.VALUE, ErrorMessage.LessThanOne) } @@ -255,8 +256,8 @@ export class TextPlugin extends FunctionPlugin { }) } - public replace(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('REPLACE'), (text: string, startPosition: number, numberOfChars: number, newText: string) => { + public replace(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('REPLACE'), (text: string, startPosition: number, numberOfChars: number, newText: string) => { if (startPosition < 1) { return new CellError(ErrorType.VALUE, ErrorMessage.LessThanOne) } @@ -267,8 +268,8 @@ export class TextPlugin extends FunctionPlugin { }) } - public search(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SEARCH'), (pattern, text: string, startIndex: number) => { + public search(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SEARCH'), (pattern, text: string, startIndex: number) => { if (startIndex < 1 || startIndex > text.length) { return new CellError(ErrorType.VALUE, ErrorMessage.LengthBounds) } @@ -287,8 +288,8 @@ export class TextPlugin extends FunctionPlugin { }) } - public substitute(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SUBSTITUTE'), (text: string, oldText: string, newText: string, occurrence: number | undefined) => { + public substitute(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SUBSTITUTE'), (text: string, oldText: string, newText: string, occurrence: number | undefined) => { const oldTextRegexp = new RegExp(oldText, 'g') if (occurrence === undefined) { @@ -311,8 +312,8 @@ export class TextPlugin extends FunctionPlugin { }) } - public find(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('FIND'), (pattern, text: string, startIndex: number) => { + public find(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('FIND'), (pattern, text: string, startIndex: number) => { if (startIndex < 1 || startIndex > text.length) { return new CellError(ErrorType.VALUE, ErrorMessage.IndexBounds) } @@ -324,8 +325,8 @@ export class TextPlugin extends FunctionPlugin { }) } - public t(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('T'), (arg: RawScalarValue) => { + public t(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('T'), (arg: RawScalarValue) => { if (arg instanceof CellError) { return arg } @@ -333,8 +334,8 @@ export class TextPlugin extends FunctionPlugin { }) } - public upper(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('UPPER'), (arg: string) => { + public upper(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('UPPER'), (arg: string) => { return arg.toUpperCase() }) } diff --git a/src/interpreter/plugin/TrigonometryPlugin.ts b/src/interpreter/plugin/TrigonometryPlugin.ts index c0eea39561..2d0e55fd0a 100644 --- a/src/interpreter/plugin/TrigonometryPlugin.ts +++ b/src/interpreter/plugin/TrigonometryPlugin.ts @@ -3,17 +3,18 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {CellError, ErrorType, SimpleCellAddress} from '../../Cell' +import {CellError, ErrorType} from '../../Cell' import {ErrorMessage} from '../../error-message' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InternalScalarValue} from '../InterpreterValue' -import {ArgumentTypes, FunctionPlugin} from './FunctionPlugin' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' import {PI} from './MathConstantsPlugin' /** * Interpreter plugin containing trigonometric functions */ -export class TrigonometryPlugin extends FunctionPlugin { +export class TrigonometryPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'ACOS': { @@ -151,34 +152,34 @@ export class TrigonometryPlugin extends FunctionPlugin { * Returns the arc cosine (or inverse cosine) of a number. * * @param ast - * @param formulaAddress + * @param state */ - public acos(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ACOS'), Math.acos) + public acos(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ACOS'), Math.acos) } - public asin(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ASIN'), Math.asin) + public asin(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ASIN'), Math.asin) } - public cos(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('COS'), Math.cos) + public cos(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('COS'), Math.cos) } - public sin(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SIN'), Math.sin) + public sin(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SIN'), Math.sin) } - public tan(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('TAN'), Math.tan) + public tan(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('TAN'), Math.tan) } - public atan(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ATAN'), Math.atan) + public atan(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ATAN'), Math.atan) } - public atan2(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ATAN2'), + public atan2(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ATAN2'), (x: number, y: number) => { if(x===0 && y===0) { return new CellError(ErrorType.DIV_BY_ZERO) @@ -188,74 +189,74 @@ export class TrigonometryPlugin extends FunctionPlugin { ) } - public cot(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('COT'), + public cot(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('COT'), (arg) => (arg === 0) ? new CellError(ErrorType.DIV_BY_ZERO) : (1 / Math.tan(arg)) ) } - public acot(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ACOT'), + public acot(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ACOT'), (arg) => (arg === 0) ? PI/2 : Math.atan(1/arg) ) } - public sec(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SEC'), + public sec(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SEC'), (arg: number) => 1 / Math.cos(arg) ) } - public csc(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CSC'), + public csc(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CSC'), (arg) => (arg === 0) ? new CellError(ErrorType.DIV_BY_ZERO) : (1 / Math.sin(arg)) ) } - public sinh(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SINH'), Math.sinh) + public sinh(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SINH'), Math.sinh) } - public asinh(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ASINH'), Math.asinh) + public asinh(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ASINH'), Math.asinh) } - public cosh(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('COSH'), Math.cosh) + public cosh(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('COSH'), Math.cosh) } - public acosh(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ACOSH'), Math.acosh) + public acosh(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ACOSH'), Math.acosh) } - public tanh(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('TANH'), Math.tanh) + public tanh(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('TANH'), Math.tanh) } - public atanh(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ATANH'), Math.atanh) + public atanh(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ATANH'), Math.atanh) } - public coth(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('COTH'), + public coth(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('COTH'), (arg) => (arg === 0) ? new CellError(ErrorType.DIV_BY_ZERO) : (1 / Math.tanh(arg)) ) } - public acoth(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('ACOTH'), + public acoth(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('ACOTH'), (arg) => (arg === 0) ? new CellError(ErrorType.NUM, ErrorMessage.NonZero) : Math.atanh(1/arg) ) } - public sech(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('SECH'), + public sech(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('SECH'), (arg: number) => 1 / Math.cosh(arg) ) } - public csch(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('CSCH'), + public csch(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + return this.runFunction(ast.args, state, this.metadata('CSCH'), (arg) => (arg === 0) ? new CellError(ErrorType.DIV_BY_ZERO) : (1 / Math.sinh(arg)) ) } diff --git a/src/interpreter/plugin/VersionPlugin.ts b/src/interpreter/plugin/VersionPlugin.ts index e9dc9556a4..69efc02ed8 100644 --- a/src/interpreter/plugin/VersionPlugin.ts +++ b/src/interpreter/plugin/VersionPlugin.ts @@ -3,12 +3,12 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ -import {SimpleCellAddress} from '../../Cell' import {LicenseKeyValidityState} from '../../helpers/licenseKeyValidator' import {HyperFormula} from '../../HyperFormula' import {ProcedureAst} from '../../parser' +import {InterpreterState} from '../InterpreterState' import {InterpreterValue} from '../InterpreterValue' -import {FunctionPlugin} from './FunctionPlugin' +import {FunctionPlugin, FunctionPluginTypecheck} from './FunctionPlugin' const LICENSE_STATUS_MAP = new Map([ ['agpl-v3', 1], @@ -18,7 +18,7 @@ const LICENSE_STATUS_MAP = new Map([ [LicenseKeyValidityState.EXPIRED, 5], ]) -export class VersionPlugin extends FunctionPlugin { +export class VersionPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'VERSION': { method: 'version', @@ -26,8 +26,8 @@ export class VersionPlugin extends FunctionPlugin { }, } - public version(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InterpreterValue { - return this.runFunction(ast.args, formulaAddress, this.metadata('VERSION'), () => { + public version(ast: ProcedureAst, state: InterpreterState): InterpreterValue { + return this.runFunction(ast.args, state, this.metadata('VERSION'), () => { const { licenseKeyValidityState: validityState, licenseKey, diff --git a/src/interpreter/plugin/index.ts b/src/interpreter/plugin/index.ts index 38c3ba8d86..e6416f7ce0 100644 --- a/src/interpreter/plugin/index.ts +++ b/src/interpreter/plugin/index.ts @@ -3,6 +3,7 @@ * Copyright (c) 2021 Handsoncode. All rights reserved. */ +export {ArrayFormulaPlugin} from './ArrayFormulaPlugin' export {AbsPlugin} from './AbsPlugin' export {BitShiftPlugin} from './BitShiftPlugin' export {BitwiseLogicOperationsPlugin} from './BitwiseLogicOperationsPlugin' diff --git a/test/arrays.spec.ts b/test/arrays.spec.ts index 3a378adbc7..438bc38001 100644 --- a/test/arrays.spec.ts +++ b/test/arrays.spec.ts @@ -1,7 +1,8 @@ import {ErrorType, HyperFormula} from '../src' -import {adr, detailedErrorWithOrigin} from './testUtils' +import {ErrorMessage} from '../src/error-message' +import {adr, detailedError, detailedErrorWithOrigin} from './testUtils' -describe('OPs', () => { +describe('without arrayformula, with arrays flag', () => { it('unary op', () => { const engine = HyperFormula.buildFromArray([[1, 2, 3], ['=SUM(-A1:C1)']], {arrays: true}) expect(engine.getCellValue(adr('A2'))).toEqual(-6) @@ -44,3 +45,102 @@ describe('OPs', () => { expect(engine.getCellValue(adr('A1'))).toEqual(5) }) }) + +describe('without arrayformula, without arrays flag', () => { + it('unary op', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], ['=SUM(-A1:C1)']], {arrays: false}) + expect(engine.getCellValue(adr('A2'))).toEqualError(detailedError(ErrorType.VALUE, ErrorMessage.ScalarExpected)) + }) + + it('binary op', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], ['=SUM(2*A1:C1+A2:C2)']], {arrays: false}) + expect(engine.getCellValue(adr('A3'))).toEqualError(detailedError(ErrorType.VALUE, ErrorMessage.ScalarExpected)) + }) + + it('index', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], ['=INDEX(2*A1:C1+3,1,1)']], {arrays: false}) + expect(engine.getCellValue(adr('A2'))).toEqualError(detailedError(ErrorType.VALUE, ErrorMessage.ScalarExpected)) + }) + + it('binary op + index', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9], + ['=INDEX(A1:C2+A1:B3,1,1)', '=INDEX(A1:C2+A1:B3,1,2)', '=INDEX(A1:C2+A1:B3,1,3)'], + ['=INDEX(A1:C2+A1:B3,2,1)', '=INDEX(A1:C2+A1:B3,2,2)', '=INDEX(A1:C2+A1:B3,2,3)'], + ['=INDEX(A1:C2+A1:B3,3,1)', '=INDEX(A1:C2+A1:B3,3,2)', '=INDEX(A1:C2+A1:B3,3,3)'], + ], {arrays: false}) + expect(engine.getSheetValues(0)).toEqual( + [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9], + [detailedErrorWithOrigin(ErrorType.VALUE, 'Sheet1!A4', ErrorMessage.ScalarExpected), detailedErrorWithOrigin(ErrorType.VALUE, 'Sheet1!B4', ErrorMessage.ScalarExpected), detailedErrorWithOrigin(ErrorType.VALUE, 'Sheet1!C4', ErrorMessage.ScalarExpected)], + [detailedErrorWithOrigin(ErrorType.VALUE, 'Sheet1!A5', ErrorMessage.ScalarExpected), detailedErrorWithOrigin(ErrorType.VALUE, 'Sheet1!B5', ErrorMessage.ScalarExpected), detailedErrorWithOrigin(ErrorType.VALUE, 'Sheet1!C5', ErrorMessage.ScalarExpected)], + [detailedErrorWithOrigin(ErrorType.VALUE, 'Sheet1!A6', ErrorMessage.ScalarExpected), detailedErrorWithOrigin(ErrorType.VALUE, 'Sheet1!B6', ErrorMessage.ScalarExpected), detailedErrorWithOrigin(ErrorType.VALUE, 'Sheet1!C6', ErrorMessage.ScalarExpected)] + ]) + }) + + it('match', () => { + const engine = HyperFormula.buildFromArray([ + ['=MATCH(10,2*A2:E2)'], + [1, 2, 3, 4, 5], + ], {arrays: false}) + expect(engine.getCellValue(adr('A1'))).toEqualError(detailedError(ErrorType.VALUE, ErrorMessage.ScalarExpected)) + }) +}) + +describe('with arrayformula, without arrays flag', () => { + it('unary op', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], ['=ARRAYFORMULA(SUM(-A1:C1))']], {arrays: false}) + expect(engine.getCellValue(adr('A2'))).toEqual(-6) + }) + + it('unary op #2', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], ['=SUM(ARRAYFORMULA(-A1:C1))']], {arrays: false}) + expect(engine.getCellValue(adr('A2'))).toEqual(-6) + }) + + it('binary op', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], ['=ARRAYFORMULA(SUM(2*A1:C1+A2:C2))']], {arrays: false}) + expect(engine.getCellValue(adr('A3'))).toEqual(27) + }) + + it('binary op #2', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], [4, 5, 6], ['=SUM(ARRAYFORMULA(2*A1:C1+A2:C2))']], {arrays: false}) + expect(engine.getCellValue(adr('A3'))).toEqual(27) + }) + + it('index', () => { + const engine = HyperFormula.buildFromArray([[1, 2, 3], ['=ARRAYFORMULA(INDEX(2*A1:C1+3,1,1))']], {arrays: false}) + expect(engine.getCellValue(adr('A2'))).toEqual(5) + }) + + it('binary op + index', () => { + const engine = HyperFormula.buildFromArray([ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9], + ['=ARRAYFORMULA(INDEX(A1:C2+A1:B3,1,1))', '=ARRAYFORMULA(INDEX(A1:C2+A1:B3,1,2))', '=ARRAYFORMULA(INDEX(A1:C2+A1:B3,1,3))'], + ['=ARRAYFORMULA(INDEX(A1:C2+A1:B3,2,1))', '=ARRAYFORMULA(INDEX(A1:C2+A1:B3,2,2))', '=ARRAYFORMULA(INDEX(A1:C2+A1:B3,2,3))'], + ['=ARRAYFORMULA(INDEX(A1:C2+A1:B3,3,1))', '=ARRAYFORMULA(INDEX(A1:C2+A1:B3,3,2))', '=ARRAYFORMULA(INDEX(A1:C2+A1:B3,3,3))'], + ], {arrays: false}) + expect(engine.getSheetValues(0)).toEqual( + [ + [1, 2, 3], + [4, 5, 6], + [7, 8, 9], + [2, 4, detailedErrorWithOrigin(ErrorType.NA, 'Sheet1!C4')], + [8, 10, detailedErrorWithOrigin(ErrorType.NA, 'Sheet1!C5')], + [detailedErrorWithOrigin(ErrorType.NA, 'Sheet1!A6'), detailedErrorWithOrigin(ErrorType.NA, 'Sheet1!B6'), detailedErrorWithOrigin(ErrorType.NA, 'Sheet1!C6')]]) + }) + + it('match', () => { + const engine = HyperFormula.buildFromArray([ + ['=ARRAYFORMULA(MATCH(10,2*A2:E2))'], + [1, 2, 3, 4, 5], + ], {arrays: false}) + expect(engine.getCellValue(adr('A1'))).toEqual(5) + }) +}) diff --git a/test/custom-functions.spec.ts b/test/custom-functions.spec.ts index ca6ee65693..6dfa441ea8 100644 --- a/test/custom-functions.spec.ts +++ b/test/custom-functions.spec.ts @@ -3,15 +3,16 @@ import {ErrorType, SimpleCellAddress} from '../src/Cell' import {ErrorMessage} from '../src/error-message' import {AliasAlreadyExisting, ProtectedFunctionError, ProtectedFunctionTranslationError} from '../src/errors' import {plPL} from '../src/i18n/languages' +import {InterpreterState} from '../src/interpreter/InterpreterState' import {InternalScalarValue} from '../src/interpreter/InterpreterValue' -import {FunctionPlugin} from '../src/interpreter/plugin/FunctionPlugin' +import {FunctionPlugin, FunctionPluginTypecheck} from '../src/interpreter/plugin/FunctionPlugin' import {NumericAggregationPlugin} from '../src/interpreter/plugin/NumericAggregationPlugin' import {SumifPlugin} from '../src/interpreter/plugin/SumifPlugin' import {VersionPlugin} from '../src/interpreter/plugin/VersionPlugin' import {ProcedureAst} from '../src/parser' import {adr, detailedError, expectArrayWithSameContent} from './testUtils' -class FooPlugin extends FunctionPlugin { +class FooPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'FOO': { method: 'foo', @@ -32,16 +33,16 @@ class FooPlugin extends FunctionPlugin { } } - public foo(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { + public foo(_ast: ProcedureAst, _state: InterpreterState): InternalScalarValue { return 'foo' } - public bar(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { + public bar(_ast: ProcedureAst, _state: InterpreterState): InternalScalarValue { return 'bar' } } -class SumWithExtra extends FunctionPlugin { +class SumWithExtra extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'SUM': { method: 'sum', @@ -52,27 +53,27 @@ class SumWithExtra extends FunctionPlugin { 'SUMALIAS': 'SUM', } - public sum(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { - const left = this.evaluateAst(ast.args[0], formulaAddress) as number - const right = this.evaluateAst(ast.args[1], formulaAddress) as number + public sum(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { + const left = this.evaluateAst(ast.args[0], state) as number + const right = this.evaluateAst(ast.args[1], state) as number return 42 + left + right } } -class InvalidPlugin extends FunctionPlugin { +class InvalidPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'FOO': { method: 'foo', } } - public bar(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { + public bar(_ast: ProcedureAst, _state: InterpreterState): InternalScalarValue { return 'bar' } } -class EmptyAliasPlugin extends FunctionPlugin { +class EmptyAliasPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'FOO': { method: 'foo', @@ -84,7 +85,7 @@ class EmptyAliasPlugin extends FunctionPlugin { } } -class OverloadedAliasPlugin extends FunctionPlugin { +class OverloadedAliasPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'FOO': { method: 'foo', @@ -99,14 +100,14 @@ class OverloadedAliasPlugin extends FunctionPlugin { } } -class ReservedNamePlugin extends FunctionPlugin { +class ReservedNamePlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'VERSION': { method: 'version', } } - public version(ast: ProcedureAst, formulaAddress: SimpleCellAddress): InternalScalarValue { + public version(_ast: ProcedureAst, _state: InterpreterState): InternalScalarValue { return 'foo' } } diff --git a/test/extending-plugins.spec.ts b/test/extending-plugins.spec.ts index bc5a39f0c8..ded9af8fac 100644 --- a/test/extending-plugins.spec.ts +++ b/test/extending-plugins.spec.ts @@ -1,18 +1,19 @@ import {ErrorType, HyperFormula} from '../src' import {SimpleCellAddress} from '../src/Cell' import {ErrorMessage} from '../src/error-message' -import {FunctionPlugin} from '../src/interpreter/plugin/FunctionPlugin' +import {InterpreterState} from '../src/interpreter/InterpreterState' +import {FunctionPlugin, FunctionPluginTypecheck} from '../src/interpreter/plugin/FunctionPlugin' import {ProcedureAst} from '../src/parser' import {adr, detailedError} from './testUtils' -class FooPlugin extends FunctionPlugin { +class FooPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'FOO': { method: 'foo', }, } - public foo(_ast: ProcedureAst, _formulaAddress: SimpleCellAddress) { + public foo(_ast: ProcedureAst, _state: InterpreterState) { return 42 } } diff --git a/test/interpreter/function-version.spec.ts b/test/interpreter/function-version.spec.ts index c213fd2160..cbb169c387 100644 --- a/test/interpreter/function-version.spec.ts +++ b/test/interpreter/function-version.spec.ts @@ -1,7 +1,7 @@ import {HyperFormula} from '../../src' import {ProtectedFunctionError} from '../../src/errors' import {InterpreterValue} from '../../src/interpreter/InterpreterValue' -import {FunctionPlugin} from '../../src/interpreter/plugin/FunctionPlugin' +import {FunctionPlugin, FunctionPluginTypecheck} from '../../src/interpreter/plugin/FunctionPlugin' import {adr} from '../testUtils' describe('Function VERSION', () => { @@ -68,7 +68,7 @@ describe('Function VERSION', () => { }) describe('registering', () => { - class VersionExtra extends FunctionPlugin { + class VersionExtra extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'VERSION': { method: 'version', diff --git a/test/optional-parameters.spec.ts b/test/optional-parameters.spec.ts index 25f1246aca..072c5e384b 100644 --- a/test/optional-parameters.spec.ts +++ b/test/optional-parameters.spec.ts @@ -1,11 +1,12 @@ import {ErrorType, HyperFormula} from '../src' import {SimpleCellAddress} from '../src/Cell' import {ErrorMessage} from '../src/error-message' -import {ArgumentTypes, FunctionPlugin} from '../src/interpreter/plugin/FunctionPlugin' +import {InterpreterState} from '../src/interpreter/InterpreterState' +import {ArgumentTypes, FunctionPlugin, FunctionPluginTypecheck} from '../src/interpreter/plugin/FunctionPlugin' import {ProcedureAst} from '../src/parser' import {adr, detailedError} from './testUtils' -class FooPlugin extends FunctionPlugin { +class FooPlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { 'FOO': { method: 'foo', @@ -16,8 +17,8 @@ class FooPlugin extends FunctionPlugin { }, } - public foo(ast: ProcedureAst, formulaAddress: SimpleCellAddress) { - return this.runFunction(ast.args, formulaAddress, this.metadata('FOO'), + public foo(ast: ProcedureAst, state: InterpreterState) { + return this.runFunction(ast.args, state, this.metadata('FOO'), (arg1, arg2) => arg1+'+'+arg2 ) } diff --git a/test/square-plugin-example.spec.ts b/test/square-plugin-example.spec.ts index 5338bf2119..944cb304f8 100644 --- a/test/square-plugin-example.spec.ts +++ b/test/square-plugin-example.spec.ts @@ -1,10 +1,12 @@ import {HyperFormula} from '../src' import {CellError, ErrorType, SimpleCellAddress} from '../src/Cell' -import {FunctionPlugin} from '../src/interpreter/plugin/FunctionPlugin' +import {InterpreterState} from '../src/interpreter/InterpreterState' +import {InternalScalarValue} from '../src/interpreter/InterpreterValue' +import {FunctionPlugin, FunctionPluginTypecheck} from '../src/interpreter/plugin/FunctionPlugin' import {ProcedureAst} from '../src/parser' import {adr, detailedError} from './testUtils' -class SquarePlugin extends FunctionPlugin { +class SquarePlugin extends FunctionPlugin implements FunctionPluginTypecheck{ public static implementedFunctions = { // Key of the mapping describes which function will be used to compute it 'SQUARE': { @@ -12,17 +14,17 @@ class SquarePlugin extends FunctionPlugin { }, } - public square(ast: ProcedureAst, formulaAddress: SimpleCellAddress) { + public square(ast: ProcedureAst, state: InterpreterState): InternalScalarValue { // Take ast of first argument from list of arguments const arg = ast.args[0] // If there was no argument, return NA error if (!arg) { - return detailedError(ErrorType.NA) + return new CellError(ErrorType.NA) } // Compute value of argument - const argValue = this.evaluateAst(arg, formulaAddress) + const argValue = this.evaluateAst(arg, state) if (argValue instanceof CellError) { // If the value is some error, return that error @@ -32,7 +34,7 @@ class SquarePlugin extends FunctionPlugin { return (argValue * argValue) } else { // If it's some other type which doesn't make sense in terms of square (string, boolean), return VALUE error - return detailedError(ErrorType.VALUE) + return new CellError(ErrorType.VALUE) } } }