From eb46c4860af65ed353a52ab7c191d9f7de5bb960 Mon Sep 17 00:00:00 2001 From: izulin Date: Sun, 16 May 2021 01:06:26 +0200 Subject: [PATCH 01/13] parsing of matrices --- src/parser/Ast.ts | 15 +++++++ src/parser/FormulaParser.ts | 63 ++++++++++++++++++++++----- src/parser/LexerConfig.ts | 27 ++++++++++-- test/parser/parser.spec.ts | 73 ++++++++++++++++++++++++++++++-- test/parser/white-spaces.spec.ts | 4 +- 5 files changed, 163 insertions(+), 19 deletions(-) diff --git a/src/parser/Ast.ts b/src/parser/Ast.ts index 632e3e7e42..542a127de3 100644 --- a/src/parser/Ast.ts +++ b/src/parser/Ast.ts @@ -39,6 +39,7 @@ export type Ast = | ErrorAst | ErrorWithRawInputAst | EmptyArgAst + | MatrixAst export interface ParsingError { type: ParsingErrorType, @@ -97,6 +98,8 @@ export enum AstNodeType { ERROR = 'ERROR', ERROR_WITH_RAW_INPUT = 'ERROR_WITH_RAW_INPUT', + + MATRIX = 'MATRIX', } export enum RangeSheetReferenceType { @@ -393,6 +396,18 @@ export const buildProcedureAst = (procedureName: string, args: Ast[], leadingWhi internalWhitespace: internalWhitespace?.image, }) +export interface MatrixAst extends AstWithInternalWhitespace { + type: AstNodeType.MATRIX, + args: Ast[][], +} + +export const buildMatrixAst = (args: Ast[][], leadingWhitespace?: IToken, internalWhitespace?: IToken): MatrixAst => ({ + type: AstNodeType.MATRIX, + args, + leadingWhitespace: leadingWhitespace?.image, + internalWhitespace: internalWhitespace?.image, +}) + export interface NamedExpressionAst extends AstWithInternalWhitespace { type: AstNodeType.NAMED_EXPRESSION, expressionName: string, diff --git a/src/parser/FormulaParser.ts b/src/parser/FormulaParser.ts index 6a05509f42..4d4798bd70 100644 --- a/src/parser/FormulaParser.ts +++ b/src/parser/FormulaParser.ts @@ -38,7 +38,7 @@ import { buildGreaterThanOpAst, buildGreaterThanOrEqualOpAst, buildLessThanOpAst, - buildLessThanOrEqualOpAst, + buildLessThanOrEqualOpAst, buildMatrixAst, buildMinusOpAst, buildMinusUnaryOpAst, buildNamedExpressionAst, @@ -76,7 +76,7 @@ import { ILexerConfig, LessThanOp, LessThanOrEqualOp, - LParen, + LParen, MatrixColSep, MatrixLParen, MatrixRowSep, MatrixRParen, MinusOp, MultiplicationOp, NamedExpression, @@ -237,6 +237,7 @@ export class FormulaParser extends EmbeddedActionsParser { ]) }) + /** * Rule for concatenation operator expression (e.g. "=" & A1) */ @@ -365,9 +366,9 @@ export class FormulaParser extends EmbeddedActionsParser { * Rule for positive atomic expressions */ private positiveAtomicExpression: AstRule = this.RULE('positiveAtomicExpression', () => { - return this.OR(this.atomicExpCache || (this.atomicExpCache = [ + return this.OR(this.atomicExpCache ?? (this.atomicExpCache = [ { - ALT: () => this.SUBRULE(this.parenthesisExpression), + ALT: () => this.SUBRULE(this.matrixExpression), }, { ALT: () => this.SUBRULE(this.cellRangeExpression), @@ -505,9 +506,9 @@ export class FormulaParser extends EmbeddedActionsParser { return this.SUBRULE(this.endOfRangeExpression, {ARGS: [start]}) }) - /* - * Rule for column range, e.g. A:B, Sheet1!A:B, Sheet1!A:Sheet1!B - * */ + /** + * Rule for column range, e.g. A:B, Sheet1!A:B, Sheet1!A:Sheet1!B + */ private columnRangeExpression: AstRule = this.RULE('columnRangeExpression', () => { const range = this.CONSUME(ColumnRange) as IExtendedToken const [startImage, endImage] = range.image.split(':') @@ -538,9 +539,9 @@ export class FormulaParser extends EmbeddedActionsParser { return buildColumnRangeAst(start, end, sheetReferenceType, range.leadingWhitespace) }) - /* -* Rule for row range, e.g. 1:2, Sheet1!1:2, Sheet1!1:Sheet1!2 -* */ + /** + * Rule for row range, e.g. 1:2, Sheet1!1:2, Sheet1!1:Sheet1!2 + */ private rowRangeExpression: AstRule = this.RULE('rowRangeExpression', () => { const range = this.CONSUME(RowRange) as IExtendedToken const [startImage, endImage] = range.image.split(':') @@ -716,6 +717,45 @@ export class FormulaParser extends EmbeddedActionsParser { return buildCellRangeAst(startAddress, endAddress, sheetReferenceType, leadingWhitespace) } + private matrixExpression: AstRule = this.RULE('matrixExpression', () => { + return this.OR([ + { + ALT: () => { + this.CONSUME(MatrixLParen) + const ret = this.SUBRULE(this.insideMatrixExpression) + this.CONSUME(MatrixRParen) + return ret + } + }, + { + ALT: () => this.SUBRULE(this.parenthesisExpression) + } + ]) + }) + + private insideMatrixExpression: AstRule = this.RULE('insideMatrixExpression', () => { + const ret: Ast[][] = [[]] + ret[ret.length-1].push(this.SUBRULE(this.booleanExpression)) + this.MANY( () => { + this.OR([ + { + ALT: () => { + this.CONSUME(MatrixColSep) + ret[ret.length-1].push(this.SUBRULE2(this.booleanExpression)) + } + }, + { + ALT: () => { + this.CONSUME(MatrixRowSep) + ret.push([]) + ret[ret.length-1].push(this.SUBRULE3(this.booleanExpression)) + } + } + ]) + }) + return buildMatrixAst(ret) + }) + /** * Rule for parenthesis expression */ @@ -726,6 +766,9 @@ export class FormulaParser extends EmbeddedActionsParser { return buildParenthesisAst(expression, lParenToken.leadingWhitespace, rParenToken.leadingWhitespace) }) + + + /** * Returns {@link CellReferenceAst} or {@link CellRangeAst} based on OFFSET function arguments * diff --git a/src/parser/LexerConfig.ts b/src/parser/LexerConfig.ts index 46972227ff..f9f64e9ea5 100644 --- a/src/parser/LexerConfig.ts +++ b/src/parser/LexerConfig.ts @@ -4,6 +4,7 @@ */ import {createToken, Lexer, TokenType} from 'chevrotain' +import {create} from 'domain' import {ErrorType} from '../Cell' import {ParserConfig} from './ParserConfig' @@ -68,7 +69,13 @@ export const RangeSeparator = createToken({name: 'RangeSeparator', pattern: /:/} export const LParen = createToken({name: 'LParen', pattern: /\(/}) export const RParen = createToken({name: 'RParen', pattern: /\)/}) -/* prcoedures */ +/* matrix parenthesis */ +export const MatrixLParen = createToken({name: 'MatrixLParen', pattern: /{/}) +export const MatrixRParen = createToken({name: 'MatrixRParen', pattern: /}/}) +export const MatrixRowSep = createToken({name: 'MatrixRowSep', pattern: /;/}) +export const MatrixColSep = createToken({name: 'MatrixColSep', pattern: /,/}) + +/* procedures */ export const ProcedureName = createToken({name: 'ProcedureName', pattern: /([A-Za-z\u00C0-\u02AF][A-Za-z0-9\u00C0-\u02AF._]*)\(/}) /* named expressions */ @@ -104,7 +111,17 @@ export const buildLexerConfig = (config: ParserConfig): ILexerConfig => { const functionMapping = config.translationPackage.buildFunctionMapping() /* configurable tokens */ - const ArgSeparator = createToken({name: 'ArgSeparator', pattern: config.functionArgSeparator}) + let ArgSeparator, inject: TokenType[] + if(config.functionArgSeparator === ',') { + ArgSeparator = MatrixColSep + inject = [] + } else if(config.functionArgSeparator === ';') { + ArgSeparator = MatrixRowSep + inject = [] + } else { + ArgSeparator = createToken({name: 'ArgSeparator', pattern: config.functionArgSeparator}) + inject = [ArgSeparator] + } const NumberLiteral = createToken({name: 'NumberLiteral', pattern: new RegExp(`(([${config.decimalSeparator}]\\d+)|(\\d+([${config.decimalSeparator}]\\d*)?))(e[+-]?\\d+)?`)}) const OffsetProcedureName = createToken({name: 'OffsetProcedureName', pattern: new RegExp(offsetProcedureNameLiteral, 'i')}) @@ -125,10 +142,12 @@ export const buildLexerConfig = (config: ParserConfig): ILexerConfig => { LessThanOp, LParen, RParen, + MatrixLParen, + MatrixRParen, OffsetProcedureName, ProcedureName, RangeSeparator, - ArgSeparator, + ...inject, ColumnRange, RowRange, NumberLiteral, @@ -140,6 +159,8 @@ export const buildLexerConfig = (config: ParserConfig): ILexerConfig => { MultiplicationOp, CellReference, NamedExpression, + MatrixRowSep, + MatrixColSep, ] return { diff --git a/test/parser/parser.spec.ts b/test/parser/parser.spec.ts index 196ccd7310..e0673b7c73 100644 --- a/test/parser/parser.spec.ts +++ b/test/parser/parser.spec.ts @@ -23,7 +23,7 @@ import { import {columnIndexToLabel} from '../../src/parser/addressRepresentationConverters' import { ColumnRangeAst, - ErrorWithRawInputAst, + ErrorWithRawInputAst, MatrixAst, ParenthesisAst, RangeSheetReferenceType, RowRangeAst @@ -180,7 +180,7 @@ describe('ParserWithCaching', () => { expect(ast.error).toEqual(new CellError(ErrorType.REF)) }) - it('refernece to address in unexsiting range returns ref error with data input ast', () => { + it('reference to address in nonexisting range returns ref error with data input ast', () => { const sheetMapping = new SheetMapping(buildTranslationPackage(enGB)) sheetMapping.addSheet('Sheet1') const parser = buildEmptyParserWithCaching(new Config(), sheetMapping) @@ -502,7 +502,7 @@ describe('cell references and ranges', () => { expect(ast.reference.sheet).toBe(null) }) - it('cell range with unexisting start sheet should return REF error with data input', () => { + it('cell range with nonexsiting start sheet should return REF error with data input', () => { const sheetMapping = new SheetMapping(buildTranslationPackage(enGB)) sheetMapping.addSheet('Sheet1') sheetMapping.addSheet('Sheet2') @@ -515,7 +515,7 @@ describe('cell references and ranges', () => { expect(ast.error.type).toBe(ErrorType.REF) }) - it('cell range with unexisting end sheet should return REF error with data input', () => { + it('cell range with nonexsiting end sheet should return REF error with data input', () => { const sheetMapping = new SheetMapping(buildTranslationPackage(enGB)) sheetMapping.addSheet('Sheet1') sheetMapping.addSheet('Sheet2') @@ -740,6 +740,71 @@ describe('Named expressions', () => { }) }) +describe('Matrices', () => { + it('simplest matrix', () => { + const parser = buildEmptyParserWithCaching(new Config()) + + const ast = parser.parse('={1}', simpleCellAddress(0, 0, 0)).ast as MatrixAst + expect(ast.type).toBe(AstNodeType.MATRIX) + expect(ast.args.length).toEqual(1) + expect(ast.args[0].length).toEqual(1) + }) + + it('row matrix', () => { + const parser = buildEmptyParserWithCaching(new Config()) + + const ast = parser.parse('={1,2,3}', simpleCellAddress(0, 0, 0)).ast as MatrixAst + expect(ast.type).toBe(AstNodeType.MATRIX) + expect(ast.args.length).toEqual(1) + expect(ast.args[0].length).toEqual(3) + }) + + it('column matrix', () => { + const parser = buildEmptyParserWithCaching(new Config()) + + const ast = parser.parse('={1;2;3}', simpleCellAddress(0, 0, 0)).ast as MatrixAst + expect(ast.type).toBe(AstNodeType.MATRIX) + expect(ast.args.length).toEqual(3) + expect(ast.args[0].length).toEqual(1) + expect(ast.args[1].length).toEqual(1) + expect(ast.args[2].length).toEqual(1) + }) + + it('square matrix', () => { + const parser = buildEmptyParserWithCaching(new Config()) + + const ast = parser.parse('={1,2,3;4,5,6;7,8,9}', simpleCellAddress(0, 0, 0)).ast as MatrixAst + expect(ast.type).toBe(AstNodeType.MATRIX) + expect(ast.args.length).toEqual(3) + expect(ast.args[0].length).toEqual(3) + expect(ast.args[1].length).toEqual(3) + expect(ast.args[2].length).toEqual(3) + }) + + it('longer matrix with extras', () => { + const parser = buildEmptyParserWithCaching(new Config()) + + const ast = parser.parse('={SUM(1,2,3),2,{1,2,3}}', simpleCellAddress(0, 0, 0)).ast as MatrixAst + expect(ast.type).toBe(AstNodeType.MATRIX) + expect(ast.args.length).toEqual(1) + expect(ast.args[0].length).toEqual(3) + const ast2 = ast.args[0][2] as MatrixAst + expect(ast2.type).toBe(AstNodeType.MATRIX) + expect(ast2.args.length).toEqual(1) + expect(ast2.args[0].length).toEqual(3) + }) + + it('matrix in other expressions', () => { + const parser = buildEmptyParserWithCaching(new Config()) + + const ast = parser.parse('=1+{1,2,3}', simpleCellAddress(0, 0, 0)).ast as PlusOpAst + const ast2 = ast.right as MatrixAst + expect(ast2.type).toBe(AstNodeType.MATRIX) + expect(ast2.args.length).toEqual(1) + expect(ast2.args[0].length).toEqual(3) + }) +}) + describe('Parsing errors', () => { it('errors - lexing errors', () => { const parser = buildEmptyParserWithCaching(new Config()) diff --git a/test/parser/white-spaces.spec.ts b/test/parser/white-spaces.spec.ts index 45e1425470..0d884ccd62 100644 --- a/test/parser/white-spaces.spec.ts +++ b/test/parser/white-spaces.spec.ts @@ -53,14 +53,14 @@ describe('tokenizeFormula', () => { const tokens = lexer.tokenizeFormula('=SUM(A1 , A2)').tokens const tokenTypes = tokens.map(token => token.tokenType.name) - expectArrayWithSameContent(tokenTypes, ['EqualsOp', 'ProcedureName', 'CellReference', 'ArgSeparator', 'WhiteSpace', 'CellReference', 'RParen']) + expectArrayWithSameContent(tokenTypes, ['EqualsOp', 'ProcedureName', 'CellReference', 'MatrixColSep', 'WhiteSpace', 'CellReference', 'RParen']) }) it('should not skip whitespace when there is empty argument ', () => { const tokens = lexer.tokenizeFormula('=PV(A1 , ,A2)').tokens const tokenTypes = tokens.map(token => token.tokenType.name) - expectArrayWithSameContent(tokenTypes, ['EqualsOp', 'ProcedureName', 'CellReference', 'ArgSeparator', 'WhiteSpace', 'ArgSeparator', 'CellReference', 'RParen']) + expectArrayWithSameContent(tokenTypes, ['EqualsOp', 'ProcedureName', 'CellReference', 'MatrixColSep', 'WhiteSpace', 'ArgSeparator', 'CellReference', 'RParen']) }) it('should treat space as whitespace', () => { From e0104c98a933f052ac4a1f0d0eb27d9387eff432 Mon Sep 17 00:00:00 2001 From: izulin Date: Sun, 16 May 2021 01:50:34 +0200 Subject: [PATCH 02/13] size prediction --- src/MatrixSize.ts | 14 ++++++++++++++ src/interpreter/Interpreter.ts | 3 +++ test/matrix-size-check.spec.ts | 24 ++++++++++++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/src/MatrixSize.ts b/src/MatrixSize.ts index a7fc56909d..315d9214c7 100644 --- a/src/MatrixSize.ts +++ b/src/MatrixSize.ts @@ -181,6 +181,20 @@ export class MatrixSizePredictor { return new MatrixSize(range.width(), range.height(), true) } } + case AstNodeType.MATRIX: { + const heights = [] + const widths = [] + for(const row of ast.args) { + const sizes = row.map(ast => this._checkMatrixSize(ast, state)) + const h = Math.min(...sizes.map(size => size.height)) + const w = sizes.reduce((total, size) => total+size.width, 0) + heights.push(h) + widths.push(w) + } + const height = heights.reduce((total, h) => total+h, 0) + const width = Math.min(...widths) + return new MatrixSize(width, height) + } case AstNodeType.STRING: case AstNodeType.NUMBER: return MatrixSize.scalar() diff --git a/src/interpreter/Interpreter.ts b/src/interpreter/Interpreter.ts index 77e75016b1..8354ab07ce 100644 --- a/src/interpreter/Interpreter.ts +++ b/src/interpreter/Interpreter.ts @@ -225,6 +225,9 @@ export class Interpreter { } case AstNodeType.PARENTHESIS: { return this.evaluateAst(ast.expression, state) + } + case AstNodeType.MATRIX: { + } case AstNodeType.ERROR_WITH_RAW_INPUT: case AstNodeType.ERROR: { diff --git a/test/matrix-size-check.spec.ts b/test/matrix-size-check.spec.ts index ddd77fbd15..cab8f03e21 100644 --- a/test/matrix-size-check.spec.ts +++ b/test/matrix-size-check.spec.ts @@ -116,6 +116,30 @@ describe('Matrix size check tests', () => { const size = matrixSizePredictor.checkMatrixSize(ast, adr('A1')) expect(size).toEqual(new MatrixSize(2, 3)) }) + + it('check matrix parsing #1', () => { + const parser = buildEmptyParserWithCaching(config) + const ast = parser.parse('={1,2,3;4,5,6}', simpleCellAddress(0, 0, 0)).ast + + const size = matrixSizePredictor.checkMatrixSize(ast, adr('A1')) + expect(size).toEqual(new MatrixSize(3, 2)) + }) + + it('check matrix parsing #2', () => { + const parser = buildEmptyParserWithCaching(config) + const ast = parser.parse('={{1;2},{3;4}}', simpleCellAddress(0, 0, 0)).ast + + const size = matrixSizePredictor.checkMatrixSize(ast, adr('A1')) + expect(size).toEqual(new MatrixSize(2, 2)) + }) + + it('check matrix parsing #3', () => { + const parser = buildEmptyParserWithCaching(config) + const ast = parser.parse('={1,{2,3},4;{5;6},{7,8;9,10},{11;12};13,{14,15},16}', simpleCellAddress(0, 0, 0)).ast + + const size = matrixSizePredictor.checkMatrixSize(ast, adr('A1')) + expect(size).toEqual(new MatrixSize(4, 4)) + }) }) describe('Matrix size check tests, with different config', () => { From 83f61bf378d52b653fb895fcca4ba714a9abe657 Mon Sep 17 00:00:00 2001 From: izulin Date: Sun, 16 May 2021 15:25:25 +0200 Subject: [PATCH 03/13] evaluation, parsing, unparsing --- src/dependencyTransformers/Transformer.ts | 10 ++++--- src/error-message.ts | 1 + src/interpreter/ArithmeticHelper.ts | 2 +- src/interpreter/Interpreter.ts | 33 ++++++++++++++++++++++- src/parser/FormulaParser.ts | 10 +++---- src/parser/Unparser.ts | 4 +++ test/arrays.spec.ts | 22 +++++++++++++++ test/parser/unparse.spec.ts | 11 +++++++- 8 files changed, 81 insertions(+), 12 deletions(-) diff --git a/src/dependencyTransformers/Transformer.ts b/src/dependencyTransformers/Transformer.ts index 4434ab8554..9309690b5e 100644 --- a/src/dependencyTransformers/Transformer.ts +++ b/src/dependencyTransformers/Transformer.ts @@ -70,14 +70,12 @@ export abstract class Transformer implements FormulaTransformer { case AstNodeType.PLUS_UNARY_OP: { return { ...ast, - type: ast.type, value: this.transformAst(ast.value, address), } } case AstNodeType.FUNCTION_CALL: { return { ...ast, - type: ast.type, procedureName: ast.procedureName, args: ast.args.map((arg) => this.transformAst(arg, address)), } @@ -85,14 +83,18 @@ export abstract class Transformer implements FormulaTransformer { case AstNodeType.PARENTHESIS: { return { ...ast, - type: ast.type, expression: this.transformAst(ast.expression, address), } } + case AstNodeType.MATRIX: { + return { + ...ast, + args: ast.args.map((row) => row.map(val => this.transformAst(val, address))) + } + } default: { return { ...ast, - type: ast.type, left: this.transformAst(ast.left, address), right: this.transformAst(ast.right, address), } as Ast diff --git a/src/error-message.ts b/src/error-message.ts index 947b99e842..87226b45b4 100644 --- a/src/error-message.ts +++ b/src/error-message.ts @@ -70,6 +70,7 @@ export class ErrorMessage { public static WrongOrder = 'Wrong order of values.' public static ComplexNumberExpected = 'Complex number expected.' public static ShouldBeIorJ = 'Should be \'i\' or \'j\'.' + public static SizeMismatch = 'Array dimensions mismatched.' public static FunctionName = (arg: string) => `Function name ${arg} not recognized.` public static NamedExpressionName = (arg: string) => `Named expression ${arg} not recognized.` public static LicenseKey = (arg: string) => `License key is ${arg}.` diff --git a/src/interpreter/ArithmeticHelper.ts b/src/interpreter/ArithmeticHelper.ts index 157488410e..146c3f4e5c 100644 --- a/src/interpreter/ArithmeticHelper.ts +++ b/src/interpreter/ArithmeticHelper.ts @@ -535,7 +535,7 @@ export function coerceComplexToString([re, im]: complex, symb?: string): string return `${re}${im < 0 ? '-' : '+'}${imStr}` } -export function coerceToRange(arg: InternalScalarValue): SimpleRangeValue { +export function coerceToRange(arg: InterpreterValue): SimpleRangeValue { if (arg instanceof SimpleRangeValue) { return arg } else { diff --git a/src/interpreter/Interpreter.ts b/src/interpreter/Interpreter.ts index 8354ab07ce..e53fe2613c 100644 --- a/src/interpreter/Interpreter.ts +++ b/src/interpreter/Interpreter.ts @@ -13,6 +13,7 @@ import {ErrorMessage} from '../error-message' import {LicenseKeyValidityState} from '../helpers/licenseKeyValidator' import {ColumnSearchStrategy} from '../Lookup/SearchStrategy' import {Matrix, NotComputedMatrix} from '../Matrix' +import {Maybe} from '../Maybe' import {NamedExpressions} from '../NamedExpressions' import {NumberLiteralHelper} from '../NumberLiteralHelper' // noinspection TypeScriptPreferShortImport @@ -23,6 +24,7 @@ import { ArithmeticHelper, coerceRangeToScalar, coerceScalarToString, + coerceToRange, fixNegativeZero, isNumberOverflow } from './ArithmeticHelper' @@ -227,7 +229,36 @@ export class Interpreter { return this.evaluateAst(ast.expression, state) } case AstNodeType.MATRIX: { - + let totalWidth: Maybe = undefined + const ret: InternalScalarValue[][] = [] + for(let astRow of ast.args) { + let rowHeight: Maybe = undefined + const rowRet: InternalScalarValue[][] = [] + for(let astIt of astRow) { + const arr = coerceToRange(this.evaluateAst(astIt, state)) + const height = arr.height() + if(rowHeight===undefined) { + rowHeight = height + rowRet.push(...arr.data) + } else if(rowHeight === height) { + for(let i=0;i { - this.CONSUME(MatrixLParen) - const ret = this.SUBRULE(this.insideMatrixExpression) - this.CONSUME(MatrixRParen) - return ret + const ltoken = this.CONSUME(MatrixLParen) as IExtendedToken + const ret = this.SUBRULE(this.insideMatrixExpression) as MatrixAst + const rtoken = this.CONSUME(MatrixRParen) as IExtendedToken + return buildMatrixAst(ret.args,ltoken.leadingWhitespace, rtoken.leadingWhitespace) } }, { diff --git a/src/parser/Unparser.ts b/src/parser/Unparser.ts index 31b007a7b2..3652fd0aa3 100644 --- a/src/parser/Unparser.ts +++ b/src/parser/Unparser.ts @@ -97,6 +97,10 @@ export class Unparser { const rightPart = '(' + expression + imageWithWhitespace(')', ast.internalWhitespace) return imageWithWhitespace(rightPart, ast.leadingWhitespace) } + case AstNodeType.MATRIX: { + const ret = '{'+ast.args.map(row => row.map(val => this.unparseAst(val, address)).join(',')).join(';') + imageWithWhitespace('}', ast.internalWhitespace) + return imageWithWhitespace(ret, ast.leadingWhitespace) + } default: { const left = this.unparseAst(ast.left, address) const right = this.unparseAst(ast.right, address) diff --git a/test/arrays.spec.ts b/test/arrays.spec.ts index 1df77bb206..9c1a440107 100644 --- a/test/arrays.spec.ts +++ b/test/arrays.spec.ts @@ -212,3 +212,25 @@ describe('range interpolation', () => { expect(engine.getCellValue(adr('A1', 1))).toEqualError(detailedError(ErrorType.VALUE, ErrorMessage.ScalarExpected)) }) }) + +describe('array parsing', () => { + it('simple array', () => { + const engine = HyperFormula.buildFromArray([['={1,2;3,4}']]) + expect(engine.getSheetValues(0)).toEqual([[1,2],[3,4]]) + }) + + it('nested arrays', () => { + const engine = HyperFormula.buildFromArray([['={1,{2,3},4;{5;6},{7,8;9,10},{11;12};13,{14,15},16}']]) + expect(engine.getSheetValues(0)).toEqual([[1,2,3,4],[5,7,8,11],[6,9,10,12],[13,14,15,16]]) + }) + + it('size mismatch', () => { + const engine = HyperFormula.buildFromArray([['={1,2;3}']]) + expect(engine.getCellValue(adr('A1'))).toEqualError(detailedError(ErrorType.REF,ErrorMessage.SizeMismatch)) + }) + + it('nested with ops', () => { + const engine = HyperFormula.buildFromArray([['=ARRAYFORMULA({1,{2,3}+{0,0},4;{5;6},2*{7,8;9,10},-{11;12};13,{14,15},16})']]) + expect(engine.getSheetValues(0)).toEqual([[1,2,3,4],[5,14,16,-11],[6,18,20,-12],[13,14,15,16]]) + }) +}) diff --git a/test/parser/unparse.spec.ts b/test/parser/unparse.spec.ts index 44899a9461..d1cfa1aa94 100644 --- a/test/parser/unparse.spec.ts +++ b/test/parser/unparse.spec.ts @@ -582,7 +582,7 @@ describe('whitespaces', () => { expect(unparsed).toEqual(formula) }) - it('should unparse empty argument with whiatespaces', () => { + it('should unparse empty argument with whitespaces', () => { const formula = '=PV(1,2,3, ,)' const ast = parser.parse(formula, adr('A1')).ast @@ -590,4 +590,13 @@ describe('whitespaces', () => { expect(unparsed).toEqual(formula) }) + + it('should unparse arrays with whitespaces', () => { + const formula = '= { 1, 2; 3, 4 }' + const ast = parser.parse(formula, adr('A1')).ast + + const unparsed = unparser.unparse(ast, adr('A1')) + + expect(unparsed).toEqual(formula) + }) }) From cb02a3b9b6160b0f5e803803c7faf94c7f714dbd Mon Sep 17 00:00:00 2001 From: izulin Date: Sun, 16 May 2021 15:33:27 +0200 Subject: [PATCH 04/13] tests --- test/arrays.spec.ts | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/test/arrays.spec.ts b/test/arrays.spec.ts index 9c1a440107..979b50318d 100644 --- a/test/arrays.spec.ts +++ b/test/arrays.spec.ts @@ -165,19 +165,34 @@ describe('coercion of array to scalar', () => { expect(engine.getCellValue(adr('D1'))).toEqualError(detailedError(ErrorType.VALUE, ErrorMessage.WrongType)) }) - it('ad-hoc array + function', () => { + it('ad-hoc array + function #1', () => { const engine = HyperFormula.buildFromArray([[0, 2, 3], ['=SIN(ARRAYFORMULA(2*A1:C1))']]) expect(engine.getCellValue(adr('A2'))).toEqual(0) }) - it('ad-hoc array + binary op', () => { + it('ad-hoc array + function #2', () => { + const engine = HyperFormula.buildFromArray([['=SIN({0,2,3})']]) + expect(engine.getCellValue(adr('A1'))).toEqual(0) + }) + + it('ad-hoc array + binary op #1', () => { const engine = HyperFormula.buildFromArray([[1, 2, 3], ['=ARRAYFORMULA(2*A1:C1)+ARRAYFORMULA(2*A1:C1)']]) - expect(engine.getCellValue(adr('A2'))).toEqual(4) + expect(engine.getSheetValues(0)).toEqual([[1,2,3],[4]]) + }) + + it('ad-hoc array + binary op #2', () => { + const engine = HyperFormula.buildFromArray([['={1,2,3}+{1,2,3}']]) + expect(engine.getSheetValues(0)).toEqual([[2]]) }) - it('ad-hoc array + unary op', () => { + it('ad-hoc array + unary op #1', () => { const engine = HyperFormula.buildFromArray([[1, 2, 3], ['=-ARRAYFORMULA(2*A1:C1)']]) - expect(engine.getCellValue(adr('A2'))).toEqual(-2) + expect(engine.getSheetValues(0)).toEqual([[1,2,3],[-2]]) + }) + + it('ad-hoc array + unary op #2', () => { + const engine = HyperFormula.buildFromArray([['=-{1,2,3}']]) + expect(engine.getSheetValues(0)).toEqual([[-1]]) }) }) From 142ece8c68529090896b2cb45ec297c4e8f8e4f9 Mon Sep 17 00:00:00 2001 From: izulin Date: Sun, 16 May 2021 15:35:22 +0200 Subject: [PATCH 05/13] doc --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8ce1499e72..8945ba234b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added casting to scalars from non-range arrays. (#663) - Added support for range interpolation. (#665) - Accepting time in JS Date() objects on the input. (#648) +- Added parsing of arrays in formulas. (#671) ### Fixed - Fixed an issue with arrays and cruds. (#651) From ed562ef74f85dd648791d24dccf13eb02e996d34 Mon Sep 17 00:00:00 2001 From: izulin Date: Sun, 16 May 2021 15:38:08 +0200 Subject: [PATCH 06/13] linter --- src/interpreter/Interpreter.ts | 8 ++++---- src/parser/FormulaParser.ts | 2 +- test/arrays.spec.ts | 12 ++++++------ 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/interpreter/Interpreter.ts b/src/interpreter/Interpreter.ts index e53fe2613c..2907491494 100644 --- a/src/interpreter/Interpreter.ts +++ b/src/interpreter/Interpreter.ts @@ -231,10 +231,10 @@ export class Interpreter { case AstNodeType.MATRIX: { let totalWidth: Maybe = undefined const ret: InternalScalarValue[][] = [] - for(let astRow of ast.args) { + for(const astRow of ast.args) { let rowHeight: Maybe = undefined const rowRet: InternalScalarValue[][] = [] - for(let astIt of astRow) { + for(const astIt of astRow) { const arr = coerceToRange(this.evaluateAst(astIt, state)) const height = arr.height() if(rowHeight===undefined) { @@ -245,7 +245,7 @@ export class Interpreter { rowRet[i].push(...arr.data[i]) } } else { - return new CellError(ErrorType.REF,ErrorMessage.SizeMismatch) + return new CellError(ErrorType.REF, ErrorMessage.SizeMismatch) } } const width = rowRet[0].length @@ -255,7 +255,7 @@ export class Interpreter { } else if(totalWidth === width) { ret.push(...rowRet) } else { - return new CellError(ErrorType.REF,ErrorMessage.SizeMismatch) + return new CellError(ErrorType.REF, ErrorMessage.SizeMismatch) } } return SimpleRangeValue.onlyValues(ret) diff --git a/src/parser/FormulaParser.ts b/src/parser/FormulaParser.ts index 98edeb40c3..bb368d33a7 100644 --- a/src/parser/FormulaParser.ts +++ b/src/parser/FormulaParser.ts @@ -724,7 +724,7 @@ export class FormulaParser extends EmbeddedActionsParser { const ltoken = this.CONSUME(MatrixLParen) as IExtendedToken const ret = this.SUBRULE(this.insideMatrixExpression) as MatrixAst const rtoken = this.CONSUME(MatrixRParen) as IExtendedToken - return buildMatrixAst(ret.args,ltoken.leadingWhitespace, rtoken.leadingWhitespace) + return buildMatrixAst(ret.args, ltoken.leadingWhitespace, rtoken.leadingWhitespace) } }, { diff --git a/test/arrays.spec.ts b/test/arrays.spec.ts index 979b50318d..9687b36b0c 100644 --- a/test/arrays.spec.ts +++ b/test/arrays.spec.ts @@ -177,7 +177,7 @@ describe('coercion of array to scalar', () => { it('ad-hoc array + binary op #1', () => { const engine = HyperFormula.buildFromArray([[1, 2, 3], ['=ARRAYFORMULA(2*A1:C1)+ARRAYFORMULA(2*A1:C1)']]) - expect(engine.getSheetValues(0)).toEqual([[1,2,3],[4]]) + expect(engine.getSheetValues(0)).toEqual([[1, 2, 3], [4]]) }) it('ad-hoc array + binary op #2', () => { @@ -187,7 +187,7 @@ describe('coercion of array to scalar', () => { it('ad-hoc array + unary op #1', () => { const engine = HyperFormula.buildFromArray([[1, 2, 3], ['=-ARRAYFORMULA(2*A1:C1)']]) - expect(engine.getSheetValues(0)).toEqual([[1,2,3],[-2]]) + expect(engine.getSheetValues(0)).toEqual([[1, 2, 3], [-2]]) }) it('ad-hoc array + unary op #2', () => { @@ -231,21 +231,21 @@ describe('range interpolation', () => { describe('array parsing', () => { it('simple array', () => { const engine = HyperFormula.buildFromArray([['={1,2;3,4}']]) - expect(engine.getSheetValues(0)).toEqual([[1,2],[3,4]]) + expect(engine.getSheetValues(0)).toEqual([[1, 2], [3, 4]]) }) it('nested arrays', () => { const engine = HyperFormula.buildFromArray([['={1,{2,3},4;{5;6},{7,8;9,10},{11;12};13,{14,15},16}']]) - expect(engine.getSheetValues(0)).toEqual([[1,2,3,4],[5,7,8,11],[6,9,10,12],[13,14,15,16]]) + expect(engine.getSheetValues(0)).toEqual([[1, 2, 3, 4], [5, 7, 8, 11], [6, 9, 10, 12], [13, 14, 15, 16]]) }) it('size mismatch', () => { const engine = HyperFormula.buildFromArray([['={1,2;3}']]) - expect(engine.getCellValue(adr('A1'))).toEqualError(detailedError(ErrorType.REF,ErrorMessage.SizeMismatch)) + expect(engine.getCellValue(adr('A1'))).toEqualError(detailedError(ErrorType.REF, ErrorMessage.SizeMismatch)) }) it('nested with ops', () => { const engine = HyperFormula.buildFromArray([['=ARRAYFORMULA({1,{2,3}+{0,0},4;{5;6},2*{7,8;9,10},-{11;12};13,{14,15},16})']]) - expect(engine.getSheetValues(0)).toEqual([[1,2,3,4],[5,14,16,-11],[6,18,20,-12],[13,14,15,16]]) + expect(engine.getSheetValues(0)).toEqual([[1, 2, 3, 4], [5, 14, 16, -11], [6, 18, 20, -12], [13, 14, 15, 16]]) }) }) From 213092bc9fbc0d24e807747e840c104d412edcb4 Mon Sep 17 00:00:00 2001 From: izulin Date: Sun, 16 May 2021 20:00:26 +0200 Subject: [PATCH 07/13] compiles --- src/NamedExpressions.ts | 3 +++ src/parser/Cache.ts | 3 +++ src/parser/ParserWithCaching.ts | 4 ++++ 3 files changed, 10 insertions(+) diff --git a/src/NamedExpressions.ts b/src/NamedExpressions.ts index 0f8e0b22e5..65b363fb51 100644 --- a/src/NamedExpressions.ts +++ b/src/NamedExpressions.ts @@ -330,5 +330,8 @@ export const doesContainRelativeReferences = (ast: Ast): boolean => { doesContainRelativeReferences(arg) ) } + case AstNodeType.MATRIX: { + return ast.args.some(row => row.some(arg => doesContainRelativeReferences(arg))) + } } } diff --git a/src/parser/Cache.ts b/src/parser/Cache.ts index 7c17d26bda..16158e8f25 100644 --- a/src/parser/Cache.ts +++ b/src/parser/Cache.ts @@ -90,5 +90,8 @@ export const doesContainFunctions = (ast: Ast, functionCriterion: (functionId: s doesContainFunctions(arg, functionCriterion) ) } + case AstNodeType.MATRIX: { + return ast.args.some(row => row.some(arg => doesContainFunctions(arg, functionCriterion))) + } } } diff --git a/src/parser/ParserWithCaching.ts b/src/parser/ParserWithCaching.ts index 8a4f175cf5..a9c03c6678 100644 --- a/src/parser/ParserWithCaching.ts +++ b/src/parser/ParserWithCaching.ts @@ -214,6 +214,10 @@ export class ParserWithCaching { case AstNodeType.ERROR_WITH_RAW_INPUT: { return imageWithWhitespace(ast.rawInput, ast.leadingWhitespace) } + case AstNodeType.MATRIX: { + const args = ast.args.map(row => row.map(val => this.computeHashOfAstNode(val)).join(',')).join(';') + return imageWithWhitespace('{'+args+imageWithWhitespace('}', ast.internalWhitespace),ast.leadingWhitespace) + } case AstNodeType.PARENTHESIS: { const expression = this.computeHashOfAstNode(ast.expression) const rightPart = '(' + expression + imageWithWhitespace(')', ast.internalWhitespace) From 027597f4e7f5742be1eb89ee9a4f2e8739205256 Mon Sep 17 00:00:00 2001 From: izulin Date: Sun, 16 May 2021 20:02:45 +0200 Subject: [PATCH 08/13] linter --- src/parser/ParserWithCaching.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/parser/ParserWithCaching.ts b/src/parser/ParserWithCaching.ts index a9c03c6678..3c1d2e3167 100644 --- a/src/parser/ParserWithCaching.ts +++ b/src/parser/ParserWithCaching.ts @@ -216,7 +216,7 @@ export class ParserWithCaching { } case AstNodeType.MATRIX: { const args = ast.args.map(row => row.map(val => this.computeHashOfAstNode(val)).join(',')).join(';') - return imageWithWhitespace('{'+args+imageWithWhitespace('}', ast.internalWhitespace),ast.leadingWhitespace) + return imageWithWhitespace('{'+args+imageWithWhitespace('}', ast.internalWhitespace), ast.leadingWhitespace) } case AstNodeType.PARENTHESIS: { const expression = this.computeHashOfAstNode(ast.expression) From a94ee478e53963358258d7f62aa0a2bb8a40ce58 Mon Sep 17 00:00:00 2001 From: izulin Date: Wed, 19 May 2021 12:34:33 +0200 Subject: [PATCH 09/13] extra config options --- src/Config.ts | 31 ++++++++++++++++++++++++++++++- src/parser/FormulaParser.ts | 6 +++--- src/parser/LexerConfig.ts | 21 +++++++++++++-------- src/parser/ParserConfig.ts | 2 ++ src/parser/Unparser.ts | 2 +- 5 files changed, 49 insertions(+), 13 deletions(-) diff --git a/src/Config.ts b/src/Config.ts index 7a79f8b62d..da1eb8ee57 100644 --- a/src/Config.ts +++ b/src/Config.ts @@ -204,6 +204,20 @@ export interface ConfigParams { * @category String */ matchWholeCell: boolean, + /** + * Column separator symbol for array notation. + * + * @default ',' + * @category Formula syntax + */ + matrixColumnSeparator: ',' | ';', + /** + * Row separator symbol for array notation. + * + * @default ';' + * @category Formula syntax + */ + matrixRowSeparator: ';' | '|', /** * Maximum number of rows * @@ -390,6 +404,8 @@ export class Config implements ConfigParams, ParserConfig { leapYear1900: false, localeLang: 'en', matchWholeCell: true, + matrixColumnSeparator: ',', + matrixRowSeparator: ';', maxRows: 40_000, maxColumns: 18_278, nullYear: 30, @@ -427,6 +443,10 @@ export class Config implements ConfigParams, ParserConfig { /** @inheritDoc */ public readonly functionArgSeparator: string /** @inheritDoc */ + public readonly matrixColumnSeparator: ',' | ';' + /** @inheritDoc */ + public readonly matrixRowSeparator: ';' | '|' + /** @inheritDoc */ public readonly decimalSeparator: '.' | ',' /** @inheritDoc */ public readonly thousandSeparator: '' | ',' | ' ' | '.' @@ -531,6 +551,8 @@ export class Config implements ConfigParams, ParserConfig { language, licenseKey, matchWholeCell, + matrixColumnSeparator, + matrixRowSeparator, maxRows, maxColumns, nullYear, @@ -565,6 +587,8 @@ export class Config implements ConfigParams, ParserConfig { this.licenseKey = configValueFromParam(licenseKey, 'string', 'licenseKey') this.#licenseKeyValidityState = checkLicenseKeyValidity(this.licenseKey) this.thousandSeparator = configValueFromParam(thousandSeparator, ['', ',', ' ', '.'], 'thousandSeparator') + this.matrixColumnSeparator = configValueFromParam(matrixColumnSeparator, [',', ';'], 'matrixColumnSeparator') + this.matrixRowSeparator = configValueFromParam(matrixRowSeparator, [';', '|'], 'matrixRowSeparator') this.localeLang = configValueFromParam(localeLang, 'string', 'localeLang') this.functionPlugins = functionPlugins ?? Config.defaultConfig.functionPlugins this.gpujs = gpujs ?? Config.defaultConfig.gpujs @@ -611,7 +635,12 @@ export class Config implements ConfigParams, ParserConfig { configCheckIfParametersNotInConflict( {value: this.decimalSeparator, name: 'decimalSeparator'}, {value: this.functionArgSeparator, name: 'functionArgSeparator'}, - {value: this.thousandSeparator, name: 'thousandSeparator'} + {value: this.thousandSeparator, name: 'thousandSeparator'}, + ) + + configCheckIfParametersNotInConflict( + {value: this.matrixRowSeparator, name: 'matrixRowSeparator'}, + {value: this.matrixColumnSeparator, name: 'matrixColumnSeparator'}, ) } diff --git a/src/parser/FormulaParser.ts b/src/parser/FormulaParser.ts index bb368d33a7..3a873c0a12 100644 --- a/src/parser/FormulaParser.ts +++ b/src/parser/FormulaParser.ts @@ -76,7 +76,7 @@ import { ILexerConfig, LessThanOp, LessThanOrEqualOp, - LParen, MatrixColSep, MatrixLParen, MatrixRowSep, MatrixRParen, + LParen, MatrixLParen, MatrixRParen, MinusOp, MultiplicationOp, NamedExpression, @@ -740,13 +740,13 @@ export class FormulaParser extends EmbeddedActionsParser { this.OR([ { ALT: () => { - this.CONSUME(MatrixColSep) + this.CONSUME(this.lexerConfig.MatrixColSeparator) ret[ret.length-1].push(this.SUBRULE2(this.booleanExpression)) } }, { ALT: () => { - this.CONSUME(MatrixRowSep) + this.CONSUME(this.lexerConfig.MatrixRowSeparator) ret.push([]) ret[ret.length-1].push(this.SUBRULE3(this.booleanExpression)) } diff --git a/src/parser/LexerConfig.ts b/src/parser/LexerConfig.ts index f9f64e9ea5..53b60d41b8 100644 --- a/src/parser/LexerConfig.ts +++ b/src/parser/LexerConfig.ts @@ -72,8 +72,6 @@ export const RParen = createToken({name: 'RParen', pattern: /\)/}) /* matrix parenthesis */ export const MatrixLParen = createToken({name: 'MatrixLParen', pattern: /{/}) export const MatrixRParen = createToken({name: 'MatrixRParen', pattern: /}/}) -export const MatrixRowSep = createToken({name: 'MatrixRowSep', pattern: /;/}) -export const MatrixColSep = createToken({name: 'MatrixColSep', pattern: /,/}) /* procedures */ export const ProcedureName = createToken({name: 'ProcedureName', pattern: /([A-Za-z\u00C0-\u02AF][A-Za-z0-9\u00C0-\u02AF._]*)\(/}) @@ -101,6 +99,8 @@ export interface ILexerConfig { errorMapping: Record, functionMapping: Record, decimalSeparator: '.' | ',', + MatrixColSeparator: TokenType, + MatrixRowSeparator: TokenType, maxColumns: number, maxRows: number, } @@ -110,13 +110,16 @@ export const buildLexerConfig = (config: ParserConfig): ILexerConfig => { const errorMapping = config.errorMapping const functionMapping = config.translationPackage.buildFunctionMapping() + const MatrixRowSeparator = createToken({name: 'MatrixRowSep', pattern: config.matrixRowSeparator}) + const MatrixColSeparator = createToken({name: 'MatrixColSep', pattern: config.matrixColumnSeparator}) + /* configurable tokens */ let ArgSeparator, inject: TokenType[] - if(config.functionArgSeparator === ',') { - ArgSeparator = MatrixColSep + if(config.functionArgSeparator === config.matrixColumnSeparator) { + ArgSeparator = MatrixColSeparator inject = [] - } else if(config.functionArgSeparator === ';') { - ArgSeparator = MatrixRowSep + } else if(config.functionArgSeparator === config.matrixRowSeparator) { + ArgSeparator = MatrixRowSeparator inject = [] } else { ArgSeparator = createToken({name: 'ArgSeparator', pattern: config.functionArgSeparator}) @@ -159,14 +162,16 @@ export const buildLexerConfig = (config: ParserConfig): ILexerConfig => { MultiplicationOp, CellReference, NamedExpression, - MatrixRowSep, - MatrixColSep, + MatrixRowSeparator, + MatrixColSeparator, ] return { ArgSeparator, NumberLiteral, OffsetProcedureName, + MatrixRowSeparator, + MatrixColSeparator, allTokens, errorMapping, functionMapping, diff --git a/src/parser/ParserConfig.ts b/src/parser/ParserConfig.ts index 6df3bff41a..e9894e64cc 100644 --- a/src/parser/ParserConfig.ts +++ b/src/parser/ParserConfig.ts @@ -9,6 +9,8 @@ import {TranslationPackage} from '../i18n' export interface ParserConfig { functionArgSeparator: string, decimalSeparator: '.' | ',', + matrixColumnSeparator: ',' | ';', + matrixRowSeparator: ';' | '|', translationPackage: TranslationPackage, errorMapping: Record, maxColumns: number, diff --git a/src/parser/Unparser.ts b/src/parser/Unparser.ts index 3652fd0aa3..b76dd8ecbe 100644 --- a/src/parser/Unparser.ts +++ b/src/parser/Unparser.ts @@ -98,7 +98,7 @@ export class Unparser { return imageWithWhitespace(rightPart, ast.leadingWhitespace) } case AstNodeType.MATRIX: { - const ret = '{'+ast.args.map(row => row.map(val => this.unparseAst(val, address)).join(',')).join(';') + imageWithWhitespace('}', ast.internalWhitespace) + const ret = '{'+ast.args.map(row => row.map(val => this.unparseAst(val, address)).join(this.config.matrixColumnSeparator)).join(this.config.matrixRowSeparator) + imageWithWhitespace('}', ast.internalWhitespace) return imageWithWhitespace(ret, ast.leadingWhitespace) } default: { From 8054ed27d207f07450802c556c542a7c37118fe4 Mon Sep 17 00:00:00 2001 From: izulin Date: Wed, 19 May 2021 12:47:53 +0200 Subject: [PATCH 10/13] tests --- test/config.spec.ts | 19 +++++++++++++++++++ test/parser/parser.spec.ts | 11 +++++++++++ 2 files changed, 30 insertions(+) diff --git a/test/config.spec.ts b/test/config.spec.ts index d13dbc64e0..ea3c406814 100644 --- a/test/config.spec.ts +++ b/test/config.spec.ts @@ -109,6 +109,9 @@ describe('Config', () => { expect(() => { new Config({ decimalSeparator: ',', functionArgSeparator: ',', thousandSeparator: ',' }) }).toThrowError('Config initialization failed. Parameters in conflict: [decimalSeparator,functionArgSeparator,thousandSeparator]') + expect(() => { + new Config({ matrixColumnSeparator: ';', matrixRowSeparator: ';'}) + }).toThrowError('Config initialization failed. Parameters in conflict: [matrixColumnSeparator,matrixRowSeparator]') }) it('should throw error when currency symbol is empty', () => { @@ -141,6 +144,22 @@ describe('Config', () => { }).toThrowError('Expected one of \'\' \',\' \' \' \'.\' for config parameter: thousandSeparator') }) + it('should throw error when matrix row separator is not correct', () => { + expect(() => { + // eslint-disable-next-line + // @ts-ignore + new Config({ matrixRowSeparator: ',' }) + }).toThrowError('Expected one of \';\' \'|\' for config parameter: matrixRowSeparator') + }) + + it('should throw error when matrix columns separator is not correct', () => { + expect(() => { + // eslint-disable-next-line + // @ts-ignore + new Config({ matrixColumnSeparator: '|' }) + }).toThrowError('Expected one of \',\' \';\' for config parameter: matrixColumnSeparator') + }) + it('#undoLimit validation', () => { expect(() => new Config({ undoLimit: 0 })).not.toThrowError() expect(() => new Config({ undoLimit: 42 })).not.toThrowError() diff --git a/test/parser/parser.spec.ts b/test/parser/parser.spec.ts index e0673b7c73..11db7304dd 100644 --- a/test/parser/parser.spec.ts +++ b/test/parser/parser.spec.ts @@ -803,6 +803,17 @@ describe('Matrices', () => { expect(ast2.args.length).toEqual(1) expect(ast2.args[0].length).toEqual(3) }) + + it('square matrix, other separators', () => { + const parser = buildEmptyParserWithCaching(new Config({matrixRowSeparator: '|', matrixColumnSeparator: ';'})) + + const ast = parser.parse('={1;2;3|4;5;6|7;8;9}', simpleCellAddress(0, 0, 0)).ast as MatrixAst + expect(ast.type).toBe(AstNodeType.MATRIX) + expect(ast.args.length).toEqual(3) + expect(ast.args[0].length).toEqual(3) + expect(ast.args[1].length).toEqual(3) + expect(ast.args[2].length).toEqual(3) + }) }) describe('Parsing errors', () => { From b0dc57f6727309364b6e616e4db58ea6045869d3 Mon Sep 17 00:00:00 2001 From: izulin Date: Wed, 19 May 2021 12:49:09 +0200 Subject: [PATCH 11/13] config --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8945ba234b..3316d5536d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,7 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added casting to scalars from non-range arrays. (#663) - Added support for range interpolation. (#665) - Accepting time in JS Date() objects on the input. (#648) -- Added parsing of arrays in formulas. (#671) +- Added parsing of arrays in formulas (together with respective config options for separators). (#671) ### Fixed - Fixed an issue with arrays and cruds. (#651) From 1f8e21f4e23a1415fc85bae26fa726b2adb8bc60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Przemys=C5=82aw=20Uzna=C5=84ski?= <40573492+izulin@users.noreply.github.com> Date: Thu, 27 May 2021 15:20:04 +0200 Subject: [PATCH 12/13] Update src/parser/FormulaParser.ts Co-authored-by: Wojciech Czerniak --- src/parser/FormulaParser.ts | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/parser/FormulaParser.ts b/src/parser/FormulaParser.ts index 3a873c0a12..0867093b17 100644 --- a/src/parser/FormulaParser.ts +++ b/src/parser/FormulaParser.ts @@ -766,9 +766,6 @@ export class FormulaParser extends EmbeddedActionsParser { return buildParenthesisAst(expression, lParenToken.leadingWhitespace, rParenToken.leadingWhitespace) }) - - - /** * Returns {@link CellReferenceAst} or {@link CellRangeAst} based on OFFSET function arguments * From 03b3bfcedb3ed9be4fc9af11121c64f3c598cc1d Mon Sep 17 00:00:00 2001 From: izulin Date: Thu, 27 May 2021 16:04:15 +0200 Subject: [PATCH 13/13] doc --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 46214ec660..726c538353 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added - Added named expression handling to engine factories. (#680) - Added `getAllNamedExpressionsSerialized` method. (#680) +- Added parsing of arrays in formulas (together with respective config options for separators). (#671) ## [0.6.2] - 2021-05-26 @@ -43,7 +44,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Added casting to scalars from non-range arrays. (#663) - Added support for range interpolation. (#665) - Accepting time in JS Date() objects on the input. (#648) -- Added parsing of arrays in formulas (together with respective config options for separators). (#671) ### Fixed - Fixed issues with scoped named expression. (#646, #641)