Skip to content
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
39612be
Fix typos in the docs
sequba Dec 29, 2022
1f9d47c
Change CellReference token to make lexer destinguish between CellRefe…
sequba Dec 29, 2022
9419ce4
Add typedoc to NamedExpressions.isNameValid method
sequba Dec 29, 2022
f337190
Add unit tests for named expression names that starts with a valid ce…
sequba Dec 29, 2022
441443a
Fix unit tests
sequba Dec 29, 2022
c47292f
Fix linter errors
sequba Dec 29, 2022
dec33fe
Add more tests for valid named expression names
sequba Jan 3, 2023
efba48b
Describe the actual rules for valid named expression names
sequba Jan 3, 2023
088556a
Add changelog entry
sequba Jan 3, 2023
1a06b3b
Make R1C1-style cell references not allowed as named expression names
sequba Jan 3, 2023
ca7e3cf
Create CellReferenceMatcher and NamedExpressionMatcher classes
sequba Jan 3, 2023
4778ecd
Reuse the parser/lexer regexps inside NamedExpressions.isNameValid me…
sequba Jan 3, 2023
c5f4100
Refactor parser-consts
sequba Jan 3, 2023
0181390
Refactor ProcedureName token
sequba Jan 3, 2023
657dcb0
Refactor token for ColumnRange and RowRange
sequba Jan 3, 2023
8747298
Rename ILexerConfig to LexerConfig
sequba Jan 3, 2023
e751da2
Add typedoc strings for the newly created code entities
sequba Jan 3, 2023
84f71f7
Create ALL_UNICODE_LETTERS_ARRAY const
sequba Jan 3, 2023
c146cea
Refactor ALL_UNICODE_LETTERS_ARRAY
sequba Jan 3, 2023
7b09872
Describe the difference in named expression names validity in the lis…
sequba Jan 4, 2023
3c2e12c
Explain the default value for maxColumns config param
sequba Jan 4, 2023
724b2b0
Make list-of-differences table more logical
sequba Jan 25, 2023
1f28b0f
Minor docs improvements
sequba Jan 25, 2023
5ccab33
Refactor parser consts
sequba Jan 25, 2023
8fe9bb7
Add more unit tests for special cases of a named expression name
sequba Jan 26, 2023
0edd6cc
Merge branch 'develop' into feature/issue-1058
sequba Feb 3, 2023
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Fixed
- Fixed error caused by the named expression names that start with a cell reference. [#1058](https://github.com/handsontable/hyperformula/issues/1058)
- Fixed the validation of the named expression names. Strings `R4C5`, `RC1000`, `R1C`, `RC`, etc. are now considered invalid. (cell references in R1C1 style). [#1058](https://github.com/handsontable/hyperformula/issues/1058)

## [2.3.0] - 2022-12-22

### Added
Expand Down
18 changes: 9 additions & 9 deletions docs/guide/basic-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ handled in a similar manner.

For example, imagine you let users rename their sheets in an
application but by mistake they choose a sheet ID that does not exist.
It would be nice to display the error to the user so they are aware
It would be nice to display the error to the user, so they are aware
of this fact.

```javascript
Expand All @@ -336,11 +336,11 @@ try {
## isItPossibleTo* methods

There are also methods that you may find useful to call in pair with
the above mentioned operations. These methods are prefixed with
the above-mentioned operations. These methods are prefixed with
`isItPossibleTo*` whose sole purpose is to check if the desired
operation is possible. They all return a simple `boolean` value.
You will find it handy when you want to give the user a more generic
message and you don't want to react to specific errors.
message, and you don't want to react to specific errors.
Comment thread
sequba marked this conversation as resolved.
Resolved

This can be particularly useful for interaction with the UI of the
application you work on. For example, you can allow the user to add
Expand Down Expand Up @@ -389,9 +389,9 @@ This demo presents several basic operations integrated with a
sample UI.

<iframe
src="https://codesandbox.io/embed/github/handsontable/hyperformula-demos/tree/2.3.x/basic-operations?autoresize=1&fontsize=11&hidenavigation=1&theme=light&view=preview"
style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;"
title="handsontable/hyperformula-demos: basic-operations"
allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
sandbox="allow-autoplay allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
></iframe>
src="https://codesandbox.io/embed/github/handsontable/hyperformula-demos/tree/2.3.x/basic-operations?autoresize=1&fontsize=11&hidenavigation=1&theme=light&view=preview"
style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;"
title="handsontable/hyperformula-demos: basic-operations"
allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
sandbox="allow-autoplay allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts">
</iframe>
29 changes: 15 additions & 14 deletions docs/guide/list-of-differences.md

Large diffs are not rendered by default.

94 changes: 46 additions & 48 deletions docs/guide/named-expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,42 @@ the names as follows:

## Examples

| Type | Custom name | Example expression |
| :--- | :--- | :--- |
| Named cell | myCell | =A1 |
| Named range of cells | myRange | =A1:D10 |
| Named constant (number) | myNumber | =10 |
| Named constant (string) | myText | ="One Small Step for Man" |
| Named formula | myFormula | =SUM(A1:D10) |
| Type | Custom name | Example expression |
|:------------------------|:------------|:--------------------------|
| Named cell | myCell | =A1 |
| Named range of cells | myRange | =A1:D10 |
| Named constant (number) | myNumber | =10 |
| Named constant (string) | myText | ="One Small Step for Man" |
| Named formula | myFormula | =SUM(A1:D10) |

## Name rules

A name of an expression:
- is case-insensitive,
- must be unique within the scope,
- must contain only UNICODE letters, numbers, an underscore character and a dot character,
- must start with a letter or an underscore,
- must be distinctive from a cell reference in A1-style, e.g. `Q4`, `YEAR2023`,
- must be distinctive from a cell reference in R1C1-style, e.g. `R4C5`, `RC`, `R0C`.

## Naming convention
**Examples of correct and incorrect names:**

| Name | Validity |
|:------------|:----------|
| my Revenue | Incorrect |
| myRevenue | Correct |
| quarter1 | Incorrect |
| quarter_1 | Correct |
| 1stQuarter | Incorrect |
| _1stQuarter | Correct |
| A1 | Incorrect |
| $A$1 | Incorrect |
| RC | Incorrect |
Comment thread
adamu-handsontable marked this conversation as resolved.
Resolved

* The name has to **be unique within the scope**; if you set
'MyPotato' globally (meaning you do not define any scope) it has
to be unique globally. However, you can still define 'MyPotato'
again in the local scope of a sheet.
::: tip
The name must be unique **within the scope**, but it's possible to override a global named expression by a local one.

E.g. if you set 'MyPotato' globally it has to be unique globally. However, you can still define 'MyPotato' again in the local scope of a sheet.

```javascript
// define for a global scope
Expand All @@ -46,27 +68,7 @@ hfInstance.addNamedExpression('MyPotato', '=SUM(100+10)');
// define for the local scope of Sheet2 (sheetId = 1), still a valid name
hfInstance.addNamedExpression('MyPotato', '=Sheet2!$A$1+100', 1);
```

* The name starts with a letter or an underscore. The minimum required
length of a name is based on the `maxColumns`value inside
[configuration object](configuration-options.md).
* The name must not equal a cell reference, e.g. A1, $A$1, R1C1; a separate “1” or “A” is also invalid.
* The name is case-insensitive.
* A space character is not allowed.
* The maximum number of characters is 255.

**Examples of correct and incorrect names:**

| Name | Validity |
| :--- | :--- |
| myRevenue | Correct |
| quarter_1 | Correct |
| _1stQuarter | Correct |
| my Revenue | Incorrect |
| 1stQuarter | Incorrect |
| A1 | Incorrect |
| R1C1 | Incorrect |
| !A$1:D10 | Incorrect |
:::

## Available methods

Expand Down Expand Up @@ -97,7 +99,7 @@ You can change a named expression by using the `changeNamedExpression`
method. Select the name of an expression to change and pass it as
the first parameter, then define the new expression as raw cell
content and optionally add the scope. If you do not define the scope
it will be set to global, meaning the expression will be vaild for the whole workbook. If you want to change many of them, it is advised
it will be set to global, meaning the expression will be valid for the whole workbook. If you want to change many of them, it is advised
to do so in a [batch](batch-operations.md). This method returns
a list of cells whose values were affected by this operation, their absolute addresses, and new values. See the "changes"
section in [basic operations](basic-operations) for more info.
Expand All @@ -113,10 +115,8 @@ You can remove a named expression by using the `removeNamedExpression`
method. Select the name of an expression to remove and pass it as
the first parameter and optionally define the scope. If you do
not define the scope it will be understood as global, meaning,
the whole workbook. This method returns a list of cells whose values
were affected by this operation, their absolute addresses, and new values.
See the changes section in
[basic operations](basic-operations) for more info.
the whole workbook. This method returns a list of [cells whose values
were affected by this operation](basic-operations.md#what-are-the-changes), their absolute addresses, and new values.

```javascript
// remove 'prettyName' expression from 'Sheet1' (sheetId=0)
Expand All @@ -137,17 +137,15 @@ const listOfExpressions = hfInstance.listNamedExpressions();
## Handling errors

Operations on named expressions throw errors when something goes
wrong. These errors can be handled to provide a good user experience
in the application. Be sure to check the
[basic operations](basic-operations) section to read about
error handling. It is also possible to check the availability of operations using `isItPossibleTo*` methods, which are also described in [that section](basic-operations#isitpossibleto-methods).
wrong. These errors can be [handled](basic-operations.md#handling-an-error) to provide a good user experience
in the application. It is also possible to check the availability of operations using `isItPossibleTo*` methods, which are also described in [that section](basic-operations#isitpossibleto-methods).

## Demo

<iframe
src="https://codesandbox.io/embed/github/handsontable/hyperformula-demos/tree/2.3.x/named-expressions?autoresize=1&fontsize=11&hidenavigation=1&theme=light&view=preview"
style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;"
title="handsontable/hyperformula-demos: named-expressions"
allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
sandbox="allow-autoplay allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
></iframe>
src="https://codesandbox.io/embed/github/handsontable/hyperformula-demos/tree/2.3.x/named-expressions?autoresize=1&fontsize=11&hidenavigation=1&theme=light&view=preview"
style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;"
title="handsontable/hyperformula-demos: named-expressions"
allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
sandbox="allow-autoplay allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts">
</iframe>
6 changes: 3 additions & 3 deletions src/Config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -259,15 +259,15 @@ export interface ConfigParams {
* @default 40.000
*
* @category Engine
* */
*/
maxRows: number,
/**
* Sets the maximum number of columns.
*
* @default 18.278
* @default 18.278 (Columns A, B, ..., ZZZ)
*
* @category Engine
* */
*/
maxColumns: number,
/**
* Internally, each date is represented as a number of days that passed since `nullDate`.
Expand Down
2 changes: 1 addition & 1 deletion src/DependencyGraph/FormulaCellVertex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ export class ArrayVertex extends FormulaVertex {

/**
* No-op as array vertices are transformed eagerly.
* */
*/
ensureRecentData(_updatingService: LazilyTransformingAstService) {
}

Expand Down
23 changes: 21 additions & 2 deletions src/NamedExpressions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
import {simpleCellAddress, SimpleCellAddress} from './Cell'
import {Maybe} from './Maybe'
import {Ast, AstNodeType} from './parser'
import {
CELL_REFERENCE_PATTERN,
NAMED_EXPRESSION_PATTERN,
R1C1_CELL_REFERENCE_PATTERN
} from './parser/parser-consts'

export interface NamedExpression {
name: string,
Expand Down Expand Up @@ -158,11 +163,25 @@ export class NamedExpressions {
return this.worksheetStore(sheetId)?.has(expressionName) ?? false
}

/**
* Checks the validity of the named expression name.
* - contains only UNICODE letters, numbers, underscore and dot characters
* - starts with a letter or underscore
* - does not look like a A1-style cell address ([A-Za-z]+[0-9]+)
* - does not look like a R1C1-style cell address ([rR][0-9]*[cC][0-9]*)
*
* ODFF: https://docs.oasis-open.org/office/OpenDocument/v1.3/os/part4-formula/OpenDocument-v1.3-os-part4-formula.html#__RefHeading__1017964_715980110
*/
public isNameValid(expressionName: string): boolean {
if (/^[A-Za-z]+[0-9]+$/.test(expressionName)) {
const a1CellRefRegexp = new RegExp(`^${CELL_REFERENCE_PATTERN}$`)
const r1c1CellRefRegexp = new RegExp(`^${R1C1_CELL_REFERENCE_PATTERN}$`)
const namedExpRegexp = new RegExp(`^${NAMED_EXPRESSION_PATTERN}$`)

if (a1CellRefRegexp.test(expressionName) || r1c1CellRefRegexp.test(expressionName)) {
return false
}
return /^[A-Za-z\u00C0-\u02AF_][A-Za-z0-9\u00C0-\u02AF._]*$/.test(expressionName)

return namedExpRegexp.test(expressionName)
}

public addNamedExpression(expressionName: string, sheetId?: number, options?: NamedExpressionOptions): InternalNamedExpression {
Expand Down
2 changes: 1 addition & 1 deletion src/Operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -664,7 +664,7 @@ export class Operations {
* @param sheet - sheet id from which rows will be removed
* @param rowStart - number of the first row to be deleted
* @param rowEnd - number of the last row to be deleted
* */
*/
private doRemoveRows(rowsToRemove: RowsSpan): RowsRemoval | undefined {
if (this.rowEffectivelyNotInSheet(rowsToRemove.rowStart, rowsToRemove.sheet)) {
return
Expand Down
6 changes: 3 additions & 3 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ export class LanguageAlreadyRegisteredError extends Error {
* @see [[registerFunctionPlugin]]
* @see [[buildFromArray]]
* @see [[buildFromSheets]]
* */
*/
export class FunctionPluginValidationError extends Error {
public static functionNotDeclaredInPlugin(functionId: string, pluginName: string): FunctionPluginValidationError {
return new FunctionPluginValidationError(`Function with id ${functionId} not declared in plugin ${pluginName}`)
Expand All @@ -331,7 +331,7 @@ export class FunctionPluginValidationError extends Error {
* @see [[registerFunctionPlugin]]
* @see [[registerFunction]]
* @see [[unregisterFunction]]
* */
*/
export class ProtectedFunctionError extends Error {
public static cannotRegisterFunctionWithId(functionId: string): ProtectedFunctionError {
return new ProtectedFunctionError(`Cannot register function with id ${functionId}`)
Expand Down Expand Up @@ -376,7 +376,7 @@ export class TargetLocationHasArrayError extends Error {
*
* @see [[addNamedExpression]]
* @see [[changeNamedExpression]]
* */
*/
export class NoRelativeAddressesAllowedError extends Error {
constructor() {
super('Relative addresses not allowed in named expressions.')
Expand Down
4 changes: 2 additions & 2 deletions src/interpreter/plugin/InformationPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ export class InformationPlugin extends FunctionPlugin implements FunctionPluginT
*
* @param ast
* @param state
* */
*/
public sheet(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
return this.runFunctionWithReferenceArgument(ast.args, state, this.metadata('SHEET'),
() => state.formulaAddress.sheet + 1,
Expand All @@ -475,7 +475,7 @@ export class InformationPlugin extends FunctionPlugin implements FunctionPluginT
*
* @param ast
* @param state
* */
*/
public sheets(ast: ProcedureAst, state: InterpreterState): InterpreterValue {
return this.runFunctionWithReferenceArgument(ast.args, state, this.metadata('SHEETS'),
() => this.dependencyGraph.sheetMapping.numberOfSheets(), // return number of sheets if no argument
Expand Down
2 changes: 1 addition & 1 deletion src/interpreter/plugin/NumericAggregationPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -543,7 +543,7 @@ export class NumericAggregationPlugin extends FunctionPlugin implements Function
* @param reducingFunction - reducing function
* @param mapFunction
* @param coercionFunction
* */
*/
private reduce<T>(args: Ast[], state: InterpreterState, initialAccValue: T, functionName: string, reducingFunction: BinaryOperation<T>, mapFunction: MapOperation<T>, coercionFunction: coercionOperation): CellError | T {
if (args.length < 1) {
return new CellError(ErrorType.NA, ErrorMessage.WrongArgNumber)
Expand Down
46 changes: 46 additions & 0 deletions src/parser/CellReferenceMatcher.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* @license
* Copyright (c) 2022 Handsoncode. All rights reserved.
*/

import {
ABSOLUTE_OPERATOR, ALL_UNICODE_LETTERS_ARRAY,
CELL_REFERENCE_PATTERN,
NON_RESERVED_CHARACTER_PATTERN
} from './parser-consts'

const CELL_REFERENCE_WITH_NEXT_CHARACTER_PATTERN = `(${CELL_REFERENCE_PATTERN})[^${NON_RESERVED_CHARACTER_PATTERN}]`

/**
* Helper class for recognizing CellReference token in text
*/
export class CellReferenceMatcher {
readonly POSSIBLE_START_CHARACTERS = [
...ALL_UNICODE_LETTERS_ARRAY,
...Array.from(Array(10)).map((_, i) => i + '0'.charCodeAt(0)).map(code => String.fromCharCode(code)),
Comment thread
sequba marked this conversation as resolved.
Resolved
ABSOLUTE_OPERATOR,
"'",
'_',
]

private cellReferenceRegexp = new RegExp(CELL_REFERENCE_WITH_NEXT_CHARACTER_PATTERN, 'y')

/**
* Method used by the lexer to recognize CellReference token in text
*
* Note: using 'y' sticky flag for a named expression which is not supported on IE11...
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky
*/
match(text: string, startOffset: number): RegExpExecArray | null {
this.cellReferenceRegexp.lastIndex = startOffset

const execResult = this.cellReferenceRegexp.exec(text+'@')

if (execResult == null || execResult[1] == null) {
return null
}

execResult[0] = execResult[1]
return execResult
}
}
8 changes: 4 additions & 4 deletions src/parser/FormulaParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ import {
ErrorLiteral,
GreaterThanOp,
GreaterThanOrEqualOp,
ILexerConfig,
LexerConfig,
LessThanOp,
LessThanOrEqualOp,
LParen,
Expand Down Expand Up @@ -123,7 +123,7 @@ export interface FormulaParserResult {
* P -> SUM(..) <br/>
*/
export class FormulaParser extends EmbeddedActionsParser {
private lexerConfig: ILexerConfig
private lexerConfig: LexerConfig

/**
* Address of the cell in which formula is located
Expand Down Expand Up @@ -443,7 +443,7 @@ export class FormulaParser extends EmbeddedActionsParser {
])
})

constructor(lexerConfig: ILexerConfig, sheetMapping: SheetMappingFn) {
constructor(lexerConfig: LexerConfig, sheetMapping: SheetMappingFn) {
super(lexerConfig.allTokens, {outputCst: false, maxLookahead: 7})
this.lexerConfig = lexerConfig
this.sheetMapping = sheetMapping
Expand Down Expand Up @@ -899,7 +899,7 @@ export interface ExtendedToken extends IToken {
export class FormulaLexer {
private readonly lexer: Lexer

constructor(private lexerConfig: ILexerConfig) {
constructor(private lexerConfig: LexerConfig) {
this.lexer = new Lexer(lexerConfig.allTokens, {ensureOptimizations: true})
}

Expand Down
Loading