Skip to content
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
31 changes: 30 additions & 1 deletion src/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,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
*
Expand Down Expand Up @@ -391,6 +405,8 @@ export class Config implements ConfigParams, ParserConfig {
leapYear1900: false,
localeLang: 'en',
matchWholeCell: true,
matrixColumnSeparator: ',',
matrixRowSeparator: ';',
maxRows: 40_000,
maxColumns: 18_278,
nullYear: 30,
Expand Down Expand Up @@ -428,6 +444,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: '' | ',' | ' ' | '.'
Expand Down Expand Up @@ -527,6 +547,8 @@ export class Config implements ConfigParams, ParserConfig {
language,
licenseKey,
matchWholeCell,
matrixColumnSeparator,
matrixRowSeparator,
maxRows,
maxColumns,
nullYear,
Expand Down Expand Up @@ -560,6 +582,8 @@ export class Config implements ConfigParams, ParserConfig {
this.language = configValueFromParam(language, 'string', 'language')
this.licenseKey = configValueFromParam(licenseKey, 'string', '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
Expand Down Expand Up @@ -610,7 +634,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'},
)
Comment on lines 634 to 643

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't those parameters be in conflict together? ie. I set the functionArgSeparatorand matrixColumnSeparator both as ; ?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

parser will handle this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as in: parser already handles well the conflict those have over ',' symbol

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

}

Expand Down
14 changes: 14 additions & 0 deletions src/MatrixSize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
3 changes: 3 additions & 0 deletions src/NamedExpressions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,5 +320,8 @@ export const doesContainRelativeReferences = (ast: Ast): boolean => {
doesContainRelativeReferences(arg)
)
}
case AstNodeType.MATRIX: {
return ast.args.some(row => row.some(arg => doesContainRelativeReferences(arg)))
}
}
}
10 changes: 6 additions & 4 deletions src/dependencyTransformers/Transformer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,29 +70,31 @@ 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)),
}
}
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
Expand Down
1 change: 1 addition & 0 deletions src/error-message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}.`
Expand Down
2 changes: 1 addition & 1 deletion src/interpreter/ArithmeticHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,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 {
Expand Down
34 changes: 34 additions & 0 deletions src/interpreter/Interpreter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -23,6 +24,7 @@ import {
ArithmeticHelper,
coerceRangeToScalar,
coerceScalarToString,
coerceToRange,
fixNegativeZero,
isNumberOverflow
} from './ArithmeticHelper'
Expand Down Expand Up @@ -226,6 +228,38 @@ export class Interpreter {
case AstNodeType.PARENTHESIS: {
return this.evaluateAst(ast.expression, state)
}
case AstNodeType.MATRIX: {
let totalWidth: Maybe<number> = undefined
const ret: InternalScalarValue[][] = []
for(const astRow of ast.args) {
let rowHeight: Maybe<number> = undefined
const rowRet: InternalScalarValue[][] = []
for(const 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<height;i++) {
rowRet[i].push(...arr.data[i])
}
} else {
return new CellError(ErrorType.REF, ErrorMessage.SizeMismatch)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would say it's ErrorType.VALUE

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Screenshot 2021-05-19 at 10 44 31

}
}
const width = rowRet[0].length
if(totalWidth===undefined) {
totalWidth = width
ret.push(...rowRet)
} else if(totalWidth === width) {
ret.push(...rowRet)
} else {
return new CellError(ErrorType.REF, ErrorMessage.SizeMismatch)
}
}
return SimpleRangeValue.onlyValues(ret)
}
case AstNodeType.ERROR_WITH_RAW_INPUT:
case AstNodeType.ERROR: {
return ast.error
Expand Down
15 changes: 15 additions & 0 deletions src/parser/Ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export type Ast =
| ErrorAst
| ErrorWithRawInputAst
| EmptyArgAst
| MatrixAst

export interface ParsingError {
type: ParsingErrorType,
Expand Down Expand Up @@ -97,6 +98,8 @@ export enum AstNodeType {
ERROR = 'ERROR',

ERROR_WITH_RAW_INPUT = 'ERROR_WITH_RAW_INPUT',

MATRIX = 'MATRIX',
}

export enum RangeSheetReferenceType {
Expand Down Expand Up @@ -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,
Expand Down
3 changes: 3 additions & 0 deletions src/parser/Cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
}
}
}
62 changes: 51 additions & 11 deletions src/parser/FormulaParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import {
buildGreaterThanOpAst,
buildGreaterThanOrEqualOpAst,
buildLessThanOpAst,
buildLessThanOrEqualOpAst,
buildLessThanOrEqualOpAst, buildMatrixAst,
buildMinusOpAst,
buildMinusUnaryOpAst,
buildNamedExpressionAst,
Expand All @@ -55,7 +55,7 @@ import {
buildStringAst,
buildTimesOpAst,
CellReferenceAst,
ErrorAst,
ErrorAst, MatrixAst,
parsingError,
ParsingError,
ParsingErrorType,
Expand All @@ -76,7 +76,7 @@ import {
ILexerConfig,
LessThanOp,
LessThanOrEqualOp,
LParen,
LParen, MatrixLParen, MatrixRParen,
MinusOp,
MultiplicationOp,
NamedExpression,
Expand Down Expand Up @@ -237,6 +237,7 @@ export class FormulaParser extends EmbeddedActionsParser {
])
})


/**
* Rule for concatenation operator expression (e.g. "=" & A1)
*/
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -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(':')
Expand Down Expand Up @@ -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(':')
Expand Down Expand Up @@ -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: () => {
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)
}
},
{
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(this.lexerConfig.MatrixColSeparator)
ret[ret.length-1].push(this.SUBRULE2(this.booleanExpression))
}
},
{
ALT: () => {
this.CONSUME(this.lexerConfig.MatrixRowSeparator)
ret.push([])
ret[ret.length-1].push(this.SUBRULE3(this.booleanExpression))
}
}
])
})
return buildMatrixAst(ret)
})

/**
* Rule for parenthesis expression
*/
Expand Down
Loading