Skip to content

Instantly share code, notes, and snippets.

@budnix
Created August 23, 2023 11:29
Show Gist options
  • Save budnix/f5d49f9bac271c75281466fe4d806031 to your computer and use it in GitHub Desktop.
Save budnix/f5d49f9bac271c75281466fe4d806031 to your computer and use it in GitHub Desktop.
This file has been truncated, but you can view the full file.
/*!
* Copyright (c) HANDSONCODE sp. z o. o.
*
* HANDSONTABLE is a software distributed by HANDSONCODE sp. z o. o., a Polish corporation based in
* Gdynia, Poland, at Aleja Zwyciestwa 96-98, registered by the District Court in Gdansk under number
* 538651, EU tax ID number: PL5862294002, share capital: PLN 62,800.00.
*
* This software is protected by applicable copyright laws, including international treaties, and dual-
* licensed - depending on whether your use for commercial purposes, meaning intended for or
* resulting in commercial advantage or monetary compensation, or not.
*
* If your use is strictly personal or solely for evaluation purposes, meaning for the purposes of testing
* the suitability, performance, and usefulness of this software outside the production environment,
* you agree to be bound by the terms included in the "handsontable-non-commercial-license.pdf" file.
*
* Your use of this software for commercial purposes is subject to the terms included in an applicable
* license agreement.
*
* In any case, you must not make any such use of this software as to develop software which may be
* considered competitive with this software.
*
* UNLESS EXPRESSLY AGREED OTHERWISE, HANDSONCODE PROVIDES THIS SOFTWARE ON AN "AS IS"
* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, AND IN NO EVENT AND UNDER NO
* LEGAL THEORY, SHALL HANDSONCODE BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY DIRECT,
* INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER ARISING FROM
* USE OR INABILITY TO USE THIS SOFTWARE.
*
* Version: 13.0.0
* Release date: 22/06/2023 (built at 23/08/2023 13:28:23)
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("Handsontable", [], factory);
else if(typeof exports === 'object')
exports["Handsontable"] = factory();
else
root["Handsontable"] = factory();
})(typeof self !== 'undefined' ? self : this, () => {
return /******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ([
/* 0 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AlwaysDense: () => (/* reexport safe */ _DependencyGraph_AddressMapping_ChooseAddressMappingPolicy__WEBPACK_IMPORTED_MODULE_4__.AlwaysDense),
/* harmony export */ AlwaysSparse: () => (/* reexport safe */ _DependencyGraph_AddressMapping_ChooseAddressMappingPolicy__WEBPACK_IMPORTED_MODULE_4__.AlwaysSparse),
/* harmony export */ ArraySize: () => (/* reexport safe */ _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize),
/* harmony export */ CellError: () => (/* reexport safe */ _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError),
/* harmony export */ CellType: () => (/* reexport safe */ _Cell__WEBPACK_IMPORTED_MODULE_1__.CellType),
/* harmony export */ CellValueDetailedType: () => (/* reexport safe */ _Cell__WEBPACK_IMPORTED_MODULE_1__.CellValueDetailedType),
/* harmony export */ CellValueType: () => (/* reexport safe */ _Cell__WEBPACK_IMPORTED_MODULE_1__.CellValueType),
/* harmony export */ ConfigValueTooBigError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.ConfigValueTooBigError),
/* harmony export */ ConfigValueTooSmallError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.ConfigValueTooSmallError),
/* harmony export */ DenseSparseChooseBasedOnThreshold: () => (/* reexport safe */ _DependencyGraph_AddressMapping_ChooseAddressMappingPolicy__WEBPACK_IMPORTED_MODULE_4__.DenseSparseChooseBasedOnThreshold),
/* harmony export */ DetailedCellError: () => (/* reexport safe */ _CellValue__WEBPACK_IMPORTED_MODULE_2__.DetailedCellError),
/* harmony export */ ErrorType: () => (/* reexport safe */ _Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType),
/* harmony export */ EvaluationSuspendedError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.EvaluationSuspendedError),
/* harmony export */ ExpectedOneOfValuesError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.ExpectedOneOfValuesError),
/* harmony export */ ExpectedValueOfTypeError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.ExpectedValueOfTypeError),
/* harmony export */ ExportedCellChange: () => (/* reexport safe */ _Exporter__WEBPACK_IMPORTED_MODULE_6__.ExportedCellChange),
/* harmony export */ ExportedNamedExpressionChange: () => (/* reexport safe */ _Exporter__WEBPACK_IMPORTED_MODULE_6__.ExportedNamedExpressionChange),
/* harmony export */ FunctionArgumentType: () => (/* reexport safe */ _interpreter__WEBPACK_IMPORTED_MODULE_9__.FunctionArgumentType),
/* harmony export */ FunctionPlugin: () => (/* reexport safe */ _interpreter__WEBPACK_IMPORTED_MODULE_9__.FunctionPlugin),
/* harmony export */ FunctionPluginValidationError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.FunctionPluginValidationError),
/* harmony export */ HyperFormula: () => (/* reexport safe */ _HyperFormula__WEBPACK_IMPORTED_MODULE_7__.HyperFormula),
/* harmony export */ InvalidAddressError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.InvalidAddressError),
/* harmony export */ InvalidArgumentsError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.InvalidArgumentsError),
/* harmony export */ LanguageAlreadyRegisteredError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.LanguageAlreadyRegisteredError),
/* harmony export */ LanguageNotRegisteredError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.LanguageNotRegisteredError),
/* harmony export */ MissingTranslationError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.MissingTranslationError),
/* harmony export */ NamedExpressionDoesNotExistError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NamedExpressionDoesNotExistError),
/* harmony export */ NamedExpressionNameIsAlreadyTakenError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NamedExpressionNameIsAlreadyTakenError),
/* harmony export */ NamedExpressionNameIsInvalidError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NamedExpressionNameIsInvalidError),
/* harmony export */ NoOperationToRedoError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NoOperationToRedoError),
/* harmony export */ NoOperationToUndoError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NoOperationToUndoError),
/* harmony export */ NoRelativeAddressesAllowedError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NoRelativeAddressesAllowedError),
/* harmony export */ NoSheetWithIdError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NoSheetWithIdError),
/* harmony export */ NoSheetWithNameError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NoSheetWithNameError),
/* harmony export */ NotAFormulaError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NotAFormulaError),
/* harmony export */ NothingToPasteError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.NothingToPasteError),
/* harmony export */ ProtectedFunctionTranslationError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.ProtectedFunctionTranslationError),
/* harmony export */ SheetNameAlreadyTakenError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.SheetNameAlreadyTakenError),
/* harmony export */ SheetSizeLimitExceededError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.SheetSizeLimitExceededError),
/* harmony export */ SimpleRangeValue: () => (/* reexport safe */ _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_11__.SimpleRangeValue),
/* harmony export */ SourceLocationHasArrayError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.SourceLocationHasArrayError),
/* harmony export */ TargetLocationHasArrayError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.TargetLocationHasArrayError),
/* harmony export */ UnableToParseError: () => (/* reexport safe */ _errors__WEBPACK_IMPORTED_MODULE_5__.UnableToParseError),
/* harmony export */ "default": () => (__WEBPACK_DEFAULT_EXPORT__)
/* harmony export */ });
/* harmony import */ var _ArraySize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _CellValue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(98);
/* harmony import */ var _Config__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(99);
/* harmony import */ var _DependencyGraph_AddressMapping_ChooseAddressMappingPolicy__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(103);
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(77);
/* harmony import */ var _Exporter__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(126);
/* harmony import */ var _HyperFormula__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(108);
/* harmony import */ var _i18n_languages_enGB__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(144);
/* harmony import */ var _interpreter__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(145);
/* harmony import */ var _interpreter_plugin__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(146);
/* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(69);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* Aggregate class for default export
*/
class HyperFormulaNS extends _HyperFormula__WEBPACK_IMPORTED_MODULE_7__.HyperFormula {}
HyperFormulaNS.HyperFormula = _HyperFormula__WEBPACK_IMPORTED_MODULE_7__.HyperFormula;
HyperFormulaNS.ErrorType = _Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType;
HyperFormulaNS.CellError = _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError;
HyperFormulaNS.CellType = _Cell__WEBPACK_IMPORTED_MODULE_1__.CellType;
HyperFormulaNS.CellValueType = _Cell__WEBPACK_IMPORTED_MODULE_1__.CellValueType;
HyperFormulaNS.CellValueDetailedType = _Cell__WEBPACK_IMPORTED_MODULE_1__.CellValueDetailedType;
HyperFormulaNS.DetailedCellError = _CellValue__WEBPACK_IMPORTED_MODULE_2__.DetailedCellError;
HyperFormulaNS.ExportedCellChange = _Exporter__WEBPACK_IMPORTED_MODULE_6__.ExportedCellChange;
HyperFormulaNS.ExportedNamedExpressionChange = _Exporter__WEBPACK_IMPORTED_MODULE_6__.ExportedNamedExpressionChange;
HyperFormulaNS.ConfigValueTooBigError = _errors__WEBPACK_IMPORTED_MODULE_5__.ConfigValueTooBigError;
HyperFormulaNS.ConfigValueTooSmallError = _errors__WEBPACK_IMPORTED_MODULE_5__.ConfigValueTooSmallError;
HyperFormulaNS.EvaluationSuspendedError = _errors__WEBPACK_IMPORTED_MODULE_5__.EvaluationSuspendedError;
HyperFormulaNS.ExpectedOneOfValuesError = _errors__WEBPACK_IMPORTED_MODULE_5__.ExpectedOneOfValuesError;
HyperFormulaNS.ExpectedValueOfTypeError = _errors__WEBPACK_IMPORTED_MODULE_5__.ExpectedValueOfTypeError;
HyperFormulaNS.ArraySize = _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize;
HyperFormulaNS.SimpleRangeValue = _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_11__.SimpleRangeValue;
HyperFormulaNS.FunctionPlugin = _interpreter__WEBPACK_IMPORTED_MODULE_9__.FunctionPlugin;
HyperFormulaNS.FunctionArgumentType = _interpreter__WEBPACK_IMPORTED_MODULE_9__.FunctionArgumentType;
HyperFormulaNS.FunctionPluginValidationError = _errors__WEBPACK_IMPORTED_MODULE_5__.FunctionPluginValidationError;
HyperFormulaNS.InvalidAddressError = _errors__WEBPACK_IMPORTED_MODULE_5__.InvalidAddressError;
HyperFormulaNS.InvalidArgumentsError = _errors__WEBPACK_IMPORTED_MODULE_5__.InvalidArgumentsError;
HyperFormulaNS.LanguageNotRegisteredError = _errors__WEBPACK_IMPORTED_MODULE_5__.LanguageNotRegisteredError;
HyperFormulaNS.LanguageAlreadyRegisteredError = _errors__WEBPACK_IMPORTED_MODULE_5__.LanguageAlreadyRegisteredError;
HyperFormulaNS.MissingTranslationError = _errors__WEBPACK_IMPORTED_MODULE_5__.MissingTranslationError;
HyperFormulaNS.NamedExpressionDoesNotExistError = _errors__WEBPACK_IMPORTED_MODULE_5__.NamedExpressionDoesNotExistError;
HyperFormulaNS.NamedExpressionNameIsAlreadyTakenError = _errors__WEBPACK_IMPORTED_MODULE_5__.NamedExpressionNameIsAlreadyTakenError;
HyperFormulaNS.NamedExpressionNameIsInvalidError = _errors__WEBPACK_IMPORTED_MODULE_5__.NamedExpressionNameIsInvalidError;
HyperFormulaNS.NoOperationToRedoError = _errors__WEBPACK_IMPORTED_MODULE_5__.NoOperationToRedoError;
HyperFormulaNS.NoOperationToUndoError = _errors__WEBPACK_IMPORTED_MODULE_5__.NoOperationToUndoError;
HyperFormulaNS.NoRelativeAddressesAllowedError = _errors__WEBPACK_IMPORTED_MODULE_5__.NoRelativeAddressesAllowedError;
HyperFormulaNS.NoSheetWithIdError = _errors__WEBPACK_IMPORTED_MODULE_5__.NoSheetWithIdError;
HyperFormulaNS.NoSheetWithNameError = _errors__WEBPACK_IMPORTED_MODULE_5__.NoSheetWithNameError;
HyperFormulaNS.NotAFormulaError = _errors__WEBPACK_IMPORTED_MODULE_5__.NotAFormulaError;
HyperFormulaNS.NothingToPasteError = _errors__WEBPACK_IMPORTED_MODULE_5__.NothingToPasteError;
HyperFormulaNS.ProtectedFunctionTranslationError = _errors__WEBPACK_IMPORTED_MODULE_5__.ProtectedFunctionTranslationError;
HyperFormulaNS.SheetNameAlreadyTakenError = _errors__WEBPACK_IMPORTED_MODULE_5__.SheetNameAlreadyTakenError;
HyperFormulaNS.SheetSizeLimitExceededError = _errors__WEBPACK_IMPORTED_MODULE_5__.SheetSizeLimitExceededError;
HyperFormulaNS.SourceLocationHasArrayError = _errors__WEBPACK_IMPORTED_MODULE_5__.SourceLocationHasArrayError;
HyperFormulaNS.TargetLocationHasArrayError = _errors__WEBPACK_IMPORTED_MODULE_5__.TargetLocationHasArrayError;
HyperFormulaNS.UnableToParseError = _errors__WEBPACK_IMPORTED_MODULE_5__.UnableToParseError;
const defaultLanguage = _Config__WEBPACK_IMPORTED_MODULE_3__.Config.defaultConfig.language;
_HyperFormula__WEBPACK_IMPORTED_MODULE_7__.HyperFormula.registerLanguage(defaultLanguage, _i18n_languages_enGB__WEBPACK_IMPORTED_MODULE_8__["default"]);
_HyperFormula__WEBPACK_IMPORTED_MODULE_7__.HyperFormula.languages[_i18n_languages_enGB__WEBPACK_IMPORTED_MODULE_8__["default"].langCode] = _i18n_languages_enGB__WEBPACK_IMPORTED_MODULE_8__["default"];
for (const pluginName of Object.getOwnPropertyNames(_interpreter_plugin__WEBPACK_IMPORTED_MODULE_10__)) {
if (!pluginName.startsWith('_')) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
_HyperFormula__WEBPACK_IMPORTED_MODULE_7__.HyperFormula.registerFunctionPlugin(_interpreter_plugin__WEBPACK_IMPORTED_MODULE_10__[pluginName]);
}
}
/* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = (HyperFormulaNS);
/*** EXPORTS FROM exports-to-window-loader ***/
window['HyperFormula'] = (__webpack_require__(0)["default"]);
/***/ }),
/* 1 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ArraySize: () => (/* binding */ ArraySize),
/* harmony export */ ArraySizePredictor: () => (/* binding */ ArraySizePredictor)
/* harmony export */ });
/* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _interpreter_InterpreterState__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(93);
/* harmony import */ var _interpreter_plugin_FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(94);
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
class ArraySize {
constructor(width, height, isRef = false) {
this.width = width;
this.height = height;
this.isRef = isRef;
if (width <= 0 || height <= 0) {
throw Error('Incorrect array size');
}
}
static fromArray(array) {
return new ArraySize(array.length > 0 ? array[0].length : 0, array.length);
}
static error() {
return new ArraySize(1, 1, true);
}
static scalar() {
return new ArraySize(1, 1, false);
}
isScalar() {
return this.width <= 1 && this.height <= 1 || this.isRef;
}
}
function arraySizeForBinaryOp(leftArraySize, rightArraySize) {
return new ArraySize(Math.max(leftArraySize.width, rightArraySize.width), Math.max(leftArraySize.height, rightArraySize.height));
}
function arraySizeForUnaryOp(arraySize) {
return new ArraySize(arraySize.width, arraySize.height);
}
class ArraySizePredictor {
constructor(config, functionRegistry) {
this.config = config;
this.functionRegistry = functionRegistry;
}
checkArraySize(ast, formulaAddress) {
return this.checkArraySizeForAst(ast, {
formulaAddress,
arraysFlag: this.config.useArrayArithmetic
});
}
checkArraySizeForAst(ast, state) {
switch (ast.type) {
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.FUNCTION_CALL:
{
return this.checkArraySizeForFunction(ast, state);
}
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.COLUMN_RANGE:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ROW_RANGE:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_RANGE:
{
const range = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.fromAstOrUndef(ast, state.formulaAddress);
if (range === undefined) {
return ArraySize.error();
} else {
return new ArraySize(range.width(), range.height(), true);
}
}
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ARRAY:
{
const heights = [];
const widths = [];
for (const row of ast.args) {
const sizes = row.map(ast => this.checkArraySizeForAst(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 ArraySize(width, height);
}
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.STRING:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.NUMBER:
return ArraySize.scalar();
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_REFERENCE:
return new ArraySize(1, 1, true);
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.DIV_OP:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CONCATENATE_OP:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.EQUALS_OP:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.GREATER_THAN_OP:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.GREATER_THAN_OR_EQUAL_OP:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.LESS_THAN_OP:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.LESS_THAN_OR_EQUAL_OP:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.MINUS_OP:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.NOT_EQUAL_OP:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PLUS_OP:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.POWER_OP:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.TIMES_OP:
{
const left = this.checkArraySizeForAst(ast.left, state);
const right = this.checkArraySizeForAst(ast.right, state);
if (!state.arraysFlag && (left.height > 1 || left.width > 1 || right.height > 1 || right.width > 1)) {
return ArraySize.error();
}
return arraySizeForBinaryOp(left, right);
}
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.MINUS_UNARY_OP:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PLUS_UNARY_OP:
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PERCENT_OP:
{
const val = this.checkArraySizeForAst(ast.value, state);
if (!state.arraysFlag && (val.height > 1 || val.width > 1)) {
return ArraySize.error();
}
return arraySizeForUnaryOp(val);
}
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PARENTHESIS:
{
return this.checkArraySizeForAst(ast.expression, state);
}
case _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.EMPTY:
return ArraySize.error();
default:
return ArraySize.error();
}
}
checkArraySizeForFunction(ast, state) {
const metadata = this.functionRegistry.getMetadata(ast.procedureName);
const pluginArraySizeFunction = this.functionRegistry.getArraySizeFunction(ast.procedureName);
if (pluginArraySizeFunction !== undefined) {
return pluginArraySizeFunction(ast, state);
}
const subChecks = ast.args.map(arg => {
var _a;
return this.checkArraySizeForAst(arg, new _interpreter_InterpreterState__WEBPACK_IMPORTED_MODULE_1__.InterpreterState(state.formulaAddress, state.arraysFlag || ((_a = metadata === null || metadata === void 0 ? void 0 : metadata.arrayFunction) !== null && _a !== void 0 ? _a : false)));
});
if (metadata === undefined || metadata.expandRanges || !state.arraysFlag || metadata.vectorizationForbidden || metadata.parameters === undefined) {
return new ArraySize(1, 1);
}
const argumentDefinitions = [...metadata.parameters];
if (metadata.repeatLastArgs === undefined && argumentDefinitions.length < subChecks.length) {
return ArraySize.error();
}
if (metadata.repeatLastArgs !== undefined && argumentDefinitions.length < subChecks.length && (subChecks.length - argumentDefinitions.length) % metadata.repeatLastArgs !== 0) {
return ArraySize.error();
}
while (argumentDefinitions.length < subChecks.length) {
argumentDefinitions.push(...argumentDefinitions.slice(argumentDefinitions.length - metadata.repeatLastArgs));
}
let maxWidth = 1;
let maxHeight = 1;
for (let i = 0; i < subChecks.length; i++) {
if (argumentDefinitions[i].argumentType !== _interpreter_plugin_FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.RANGE && argumentDefinitions[i].argumentType !== _interpreter_plugin_FunctionPlugin__WEBPACK_IMPORTED_MODULE_2__.FunctionArgumentType.ANY) {
maxHeight = Math.max(maxHeight, subChecks[i].height);
maxWidth = Math.max(maxWidth, subChecks[i].width);
}
}
return new ArraySize(maxWidth, maxHeight);
}
}
/***/ }),
/* 2 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AbsoluteCellRange: () => (/* binding */ AbsoluteCellRange),
/* harmony export */ AbsoluteColumnRange: () => (/* binding */ AbsoluteColumnRange),
/* harmony export */ AbsoluteRowRange: () => (/* binding */ AbsoluteRowRange),
/* harmony export */ WRONG_RANGE_SIZE: () => (/* binding */ WRONG_RANGE_SIZE),
/* harmony export */ isSimpleCellRange: () => (/* binding */ isSimpleCellRange),
/* harmony export */ simpleCellRange: () => (/* binding */ simpleCellRange)
/* harmony export */ });
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(77);
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7);
/* harmony import */ var _Span__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(71);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
const WRONG_RANGE_SIZE = 'AbsoluteCellRange: Wrong range size';
function isSimpleCellRange(obj) {
if (obj && (typeof obj === 'object' || typeof obj === 'function')) {
return 'start' in obj && (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellAddress)(obj.start) && 'end' in obj && (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.isSimpleCellAddress)(obj.end);
} else {
return false;
}
}
const simpleCellRange = (start, end) => ({
start,
end
});
class AbsoluteCellRange {
constructor(start, end) {
if (start.sheet !== end.sheet) {
throw new _errors__WEBPACK_IMPORTED_MODULE_1__.SheetsNotEqual(start.sheet, end.sheet);
}
this.start = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(start.sheet, start.col, start.row);
this.end = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(end.sheet, end.col, end.row);
}
get sheet() {
return this.start.sheet;
}
static fromSimpleCellAddresses(start, end) {
if (start.sheet !== end.sheet) {
throw new _errors__WEBPACK_IMPORTED_MODULE_1__.SheetsNotEqual(start.sheet, end.sheet);
}
const width = end.col - start.col;
const height = end.row - start.row;
if (Number.isFinite(height) && Number.isFinite(width)) {
return new AbsoluteCellRange(start, end);
}
if (Number.isFinite(height)) {
return new AbsoluteRowRange(start.sheet, start.row, end.row);
}
return new AbsoluteColumnRange(start.sheet, start.col, end.col);
}
static fromAst(ast, baseAddress) {
if (ast.type === _parser__WEBPACK_IMPORTED_MODULE_2__.AstNodeType.CELL_RANGE) {
return AbsoluteCellRange.fromCellRange(ast, baseAddress);
} else if (ast.type === _parser__WEBPACK_IMPORTED_MODULE_2__.AstNodeType.COLUMN_RANGE) {
return AbsoluteColumnRange.fromColumnRange(ast, baseAddress);
} else {
return AbsoluteRowRange.fromRowRangeAst(ast, baseAddress);
}
}
static fromAstOrUndef(ast, baseAddress) {
try {
return AbsoluteCellRange.fromAst(ast, baseAddress);
} catch (_e) {
return undefined;
}
}
static fromCellRange(x, baseAddress) {
return new AbsoluteCellRange(x.start.toSimpleCellAddress(baseAddress), x.end.toSimpleCellAddress(baseAddress));
}
static spanFrom(topLeftCorner, width, height) {
const ret = AbsoluteCellRange.spanFromOrUndef(topLeftCorner, width, height);
if (ret === undefined) {
throw new Error(WRONG_RANGE_SIZE);
}
return ret;
}
static spanFromOrUndef(topLeftCorner, width, height) {
if (!Number.isFinite(width) && Number.isFinite(height)) {
if (topLeftCorner.col !== 0) {
return undefined;
}
return new AbsoluteRowRange(topLeftCorner.sheet, topLeftCorner.row, topLeftCorner.row + height - 1);
} else if (!Number.isFinite(height) && Number.isFinite(width)) {
if (topLeftCorner.row !== 0) {
return undefined;
}
return new AbsoluteColumnRange(topLeftCorner.sheet, topLeftCorner.col, topLeftCorner.col + width - 1);
} else if (Number.isFinite(height) && Number.isFinite(width)) {
return new AbsoluteCellRange(topLeftCorner, (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(topLeftCorner.sheet, topLeftCorner.col + width - 1, topLeftCorner.row + height - 1));
}
return undefined;
}
static fromCoordinates(sheet, x1, y1, x2, y2) {
return new AbsoluteCellRange((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, x1, y1), (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, x2, y2));
}
isFinite() {
return Number.isFinite(this.size());
}
doesOverlap(other) {
if (this.start.sheet != other.start.sheet) {
return false;
}
if (this.end.row < other.start.row || this.start.row > other.end.row) {
return false;
}
if (this.end.col < other.start.col || this.start.col > other.end.col) {
return false;
}
return true;
}
addressInRange(address) {
if (this.sheet !== address.sheet) {
return false;
}
return this.start.row <= address.row && this.end.row >= address.row && this.start.col <= address.col && this.end.col >= address.col;
}
columnInRange(address) {
if (this.sheet !== address.sheet) {
return false;
}
return this.start.col <= address.col && this.end.col >= address.col;
}
rowInRange(address) {
if (this.sheet !== address.sheet) {
return false;
}
return this.start.row <= address.row && this.end.row >= address.row;
}
containsRange(range) {
return this.addressInRange(range.start) && this.addressInRange(range.end);
}
intersectionWith(other) {
if (this.sheet !== other.start.sheet) {
return undefined;
}
const startRow = Math.max(this.start.row, other.start.row);
const endRow = Math.min(this.end.row, other.end.row);
const startCol = Math.max(this.start.col, other.start.col);
const endCol = Math.min(this.end.col, other.end.col);
if (startRow > endRow || startCol > endCol) {
return undefined;
}
return new AbsoluteCellRange((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.sheet, startCol, startRow), (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.sheet, endCol, endRow));
}
includesRow(row) {
return this.start.row < row && this.end.row >= row;
}
includesColumn(column) {
return this.start.col < column && this.end.col >= column;
}
shiftByRows(numberOfRows) {
this.start.row += numberOfRows;
this.end.row += numberOfRows;
}
expandByRows(numberOfRows) {
this.end.row += numberOfRows;
}
shiftByColumns(numberOfColumns) {
this.start.col += numberOfColumns;
this.end.col += numberOfColumns;
}
shifted(byCols, byRows) {
return AbsoluteCellRange.spanFrom((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.sheet, this.start.col + byCols, this.start.row + byRows), this.width(), this.height());
}
expandByColumns(numberOfColumns) {
this.end.col += numberOfColumns;
}
moveToSheet(toSheet) {
this.start.sheet = toSheet;
this.end.sheet = toSheet;
}
removeSpan(span) {
if (span instanceof _Span__WEBPACK_IMPORTED_MODULE_3__.RowsSpan) {
this.removeRows(span.start, span.end);
} else {
this.removeColumns(span.start, span.end);
}
}
shouldBeRemoved() {
return this.width() <= 0 || this.height() <= 0;
}
rangeWithSameWidth(startRow, numberOfRows) {
return AbsoluteCellRange.spanFrom((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.sheet, this.start.col, startRow), this.width(), numberOfRows);
}
rangeWithSameHeight(startColumn, numberOfColumns) {
return AbsoluteCellRange.spanFrom((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.sheet, startColumn, this.start.row), numberOfColumns, this.height());
}
toString() {
return `${this.start.sheet},${this.start.col},${this.start.row},${this.end.col},${this.end.row}`;
}
width() {
return this.end.col - this.start.col + 1;
}
height() {
return this.end.row - this.start.row + 1;
}
size() {
return this.height() * this.width();
}
arrayOfAddressesInRange() {
const result = [];
for (let y = 0; y < this.height(); ++y) {
result[y] = [];
for (let x = 0; x < this.width(); ++x) {
const value = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.sheet, this.start.col + x, this.start.row + y);
result[y].push(value);
}
}
return result;
}
withStart(newStart) {
return new AbsoluteCellRange(newStart, this.end);
}
sameDimensionsAs(other) {
return this.width() === other.width() && this.height() === other.height();
}
sameAs(other) {
return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.equalSimpleCellAddress)(this.start, other.start) && (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.equalSimpleCellAddress)(this.end, other.end);
}
addressesArrayMap(dependencyGraph, op) {
const ret = [];
let currentRow = this.start.row;
while (currentRow <= this.effectiveEndRow(dependencyGraph)) {
let currentColumn = this.start.col;
const tmp = [];
while (currentColumn <= this.effectiveEndColumn(dependencyGraph)) {
tmp.push(op((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.start.sheet, currentColumn, currentRow)));
currentColumn++;
}
ret.push(tmp);
currentRow++;
}
return ret;
}
addresses(dependencyGraph) {
const ret = [];
let currentRow = this.start.row;
const limitRow = this.effectiveEndRow(dependencyGraph);
const limitColumn = this.effectiveEndColumn(dependencyGraph);
while (currentRow <= limitRow) {
let currentColumn = this.start.col;
while (currentColumn <= limitColumn) {
ret.push((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.start.sheet, currentColumn, currentRow));
currentColumn++;
}
currentRow++;
}
return ret;
}
*addressesWithDirection(right, bottom, dependencyGraph) {
if (right > 0) {
if (bottom > 0) {
let currentRow = this.effectiveEndRow(dependencyGraph);
while (currentRow >= this.start.row) {
let currentColumn = this.effectiveEndColumn(dependencyGraph);
while (currentColumn >= this.start.col) {
yield (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.start.sheet, currentColumn, currentRow);
currentColumn -= 1;
}
currentRow -= 1;
}
} else {
let currentRow = this.start.row;
while (currentRow <= this.effectiveEndRow(dependencyGraph)) {
let currentColumn = this.effectiveEndColumn(dependencyGraph);
while (currentColumn >= this.start.col) {
yield (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.start.sheet, currentColumn, currentRow);
currentColumn -= 1;
}
currentRow += 1;
}
}
} else {
if (bottom > 0) {
let currentRow = this.effectiveEndRow(dependencyGraph);
while (currentRow >= this.start.row) {
let currentColumn = this.start.col;
while (currentColumn <= this.effectiveEndColumn(dependencyGraph)) {
yield (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.start.sheet, currentColumn, currentRow);
currentColumn += 1;
}
currentRow -= 1;
}
} else {
let currentRow = this.start.row;
while (currentRow <= this.effectiveEndRow(dependencyGraph)) {
let currentColumn = this.start.col;
while (currentColumn <= this.effectiveEndColumn(dependencyGraph)) {
yield (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.start.sheet, currentColumn, currentRow);
currentColumn += 1;
}
currentRow += 1;
}
}
}
}
getAddress(col, row) {
if (col < 0 || row < 0 || row > this.height() - 1 || col > this.width() - 1) {
throw Error('Index out of bound');
}
return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(this.start.sheet, this.start.col + col, this.start.row + row);
}
exceedsSheetSizeLimits(maxColumns, maxRows) {
return this.end.col >= maxColumns || this.end.row >= maxRows;
}
effectiveEndColumn(_dependencyGraph) {
return this.end.col;
}
effectiveEndRow(_dependencyGraph) {
return this.end.row;
}
effectiveWidth(_dependencyGraph) {
return this.width();
}
effectiveHeight(_dependencyGraph) {
return this.height();
}
removeRows(rowStart, rowEnd) {
if (rowStart > this.end.row) {
return;
}
if (rowEnd < this.start.row) {
const numberOfRows = rowEnd - rowStart + 1;
return this.shiftByRows(-numberOfRows);
}
if (rowStart <= this.start.row) {
this.start.row = rowStart;
}
this.end.row -= Math.min(rowEnd, this.end.row) - rowStart + 1;
}
removeColumns(columnStart, columnEnd) {
if (columnStart > this.end.col) {
return;
}
if (columnEnd < this.start.col) {
const numberOfColumns = columnEnd - columnStart + 1;
return this.shiftByColumns(-numberOfColumns);
}
if (columnStart <= this.start.col) {
this.start.col = columnStart;
}
this.end.col -= Math.min(columnEnd, this.end.col) - columnStart + 1;
}
}
class AbsoluteColumnRange extends AbsoluteCellRange {
constructor(sheet, columnStart, columnEnd) {
super((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, columnStart, 0), (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, columnEnd, Number.POSITIVE_INFINITY));
}
static fromColumnRange(x, baseAddress) {
const start = x.start.toSimpleColumnAddress(baseAddress);
const end = x.end.toSimpleColumnAddress(baseAddress);
if (start.sheet !== end.sheet) {
throw new _errors__WEBPACK_IMPORTED_MODULE_1__.SheetsNotEqual(start.sheet, end.sheet);
}
return new AbsoluteColumnRange(start.sheet, start.col, end.col);
}
shouldBeRemoved() {
return this.width() <= 0;
}
shiftByRows(_numberOfRows) {
return;
}
expandByRows(_numberOfRows) {
return;
}
shifted(byCols, _byRows) {
return new AbsoluteColumnRange(this.sheet, this.start.col + byCols, this.end.col + byCols);
}
rangeWithSameHeight(startColumn, numberOfColumns) {
return new AbsoluteColumnRange(this.sheet, startColumn, startColumn + numberOfColumns - 1);
}
exceedsSheetSizeLimits(maxColumns, _maxRows) {
return this.end.col >= maxColumns;
}
effectiveEndRow(dependencyGraph) {
return this.effectiveHeight(dependencyGraph) - 1;
}
effectiveHeight(dependencyGraph) {
return dependencyGraph.getSheetHeight(this.sheet);
}
removeRows(_rowStart, _rowEnd) {
return;
}
}
class AbsoluteRowRange extends AbsoluteCellRange {
constructor(sheet, rowStart, rowEnd) {
super((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, 0, rowStart), (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, Number.POSITIVE_INFINITY, rowEnd));
}
static fromRowRangeAst(x, baseAddress) {
const start = x.start.toSimpleRowAddress(baseAddress);
const end = x.end.toSimpleRowAddress(baseAddress);
if (start.sheet !== end.sheet) {
throw new _errors__WEBPACK_IMPORTED_MODULE_1__.SheetsNotEqual(start.sheet, end.sheet);
}
return new AbsoluteRowRange(start.sheet, start.row, end.row);
}
shouldBeRemoved() {
return this.height() <= 0;
}
shiftByColumns(_numberOfColumns) {
return;
}
expandByColumns(_numberOfColumns) {
return;
}
shifted(byCols, byRows) {
return new AbsoluteRowRange(this.sheet, this.start.row + byRows, this.end.row + byRows);
}
rangeWithSameWidth(startRow, numberOfRows) {
return new AbsoluteRowRange(this.sheet, startRow, startRow + numberOfRows - 1);
}
exceedsSheetSizeLimits(_maxColumns, maxRows) {
return this.end.row >= maxRows;
}
effectiveEndColumn(dependencyGraph) {
return this.effectiveWidth(dependencyGraph) - 1;
}
effectiveWidth(dependencyGraph) {
return dependencyGraph.getSheetWidth(this.sheet);
}
removeColumns(_columnStart, _columnEnd) {
return;
}
}
/***/ }),
/* 3 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CellError: () => (/* binding */ CellError),
/* harmony export */ CellType: () => (/* binding */ CellType),
/* harmony export */ CellValueDetailedType: () => (/* binding */ CellValueDetailedType),
/* harmony export */ CellValueJustNumber: () => (/* binding */ CellValueJustNumber),
/* harmony export */ CellValueNoNumber: () => (/* binding */ CellValueNoNumber),
/* harmony export */ CellValueType: () => (/* binding */ CellValueType),
/* harmony export */ CellValueTypeOrd: () => (/* binding */ CellValueTypeOrd),
/* harmony export */ ErrorType: () => (/* binding */ ErrorType),
/* harmony export */ absoluteSheetReference: () => (/* binding */ absoluteSheetReference),
/* harmony export */ addressKey: () => (/* binding */ addressKey),
/* harmony export */ equalSimpleCellAddress: () => (/* binding */ equalSimpleCellAddress),
/* harmony export */ getCellType: () => (/* binding */ getCellType),
/* harmony export */ getCellValueDetailedType: () => (/* binding */ getCellValueDetailedType),
/* harmony export */ getCellValueFormat: () => (/* binding */ getCellValueFormat),
/* harmony export */ getCellValueType: () => (/* binding */ getCellValueType),
/* harmony export */ invalidSimpleCellAddress: () => (/* binding */ invalidSimpleCellAddress),
/* harmony export */ invalidSimpleColumnAddress: () => (/* binding */ invalidSimpleColumnAddress),
/* harmony export */ invalidSimpleRowAddress: () => (/* binding */ invalidSimpleRowAddress),
/* harmony export */ isSimpleCellAddress: () => (/* binding */ isSimpleCellAddress),
/* harmony export */ movedSimpleCellAddress: () => (/* binding */ movedSimpleCellAddress),
/* harmony export */ simpleCellAddress: () => (/* binding */ simpleCellAddress),
/* harmony export */ simpleColumnAddress: () => (/* binding */ simpleColumnAddress),
/* harmony export */ simpleRowAddress: () => (/* binding */ simpleRowAddress)
/* harmony export */ });
/* harmony import */ var _DependencyGraph__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4);
/* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(61);
/* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(70);
/* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(69);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* Possible errors returned by our interpreter.
*/
var ErrorType;
(function (ErrorType) {
/** Division by zero. */
ErrorType["DIV_BY_ZERO"] = "DIV_BY_ZERO";
/** Unknown function name. */
ErrorType["NAME"] = "NAME";
ErrorType["VALUE"] = "VALUE";
ErrorType["NUM"] = "NUM";
ErrorType["NA"] = "NA";
/** Cyclic dependency. */
ErrorType["CYCLE"] = "CYCLE";
/** Wrong address reference. */
ErrorType["REF"] = "REF";
/** Array spill error. */
ErrorType["SPILL"] = "SPILL";
/** Invalid/missing licence error. */
ErrorType["LIC"] = "LIC";
/** Generic error */
ErrorType["ERROR"] = "ERROR";
})(ErrorType || (ErrorType = {}));
var CellType;
(function (CellType) {
CellType["FORMULA"] = "FORMULA";
CellType["VALUE"] = "VALUE";
CellType["ARRAY"] = "ARRAY";
CellType["EMPTY"] = "EMPTY";
CellType["ARRAYFORMULA"] = "ARRAYFORMULA";
})(CellType || (CellType = {}));
const getCellType = (vertex, address) => {
if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_0__.ArrayVertex) {
if (vertex.isLeftCorner(address)) {
return CellType.ARRAYFORMULA;
} else {
return CellType.ARRAY;
}
}
if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_0__.FormulaCellVertex || vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_0__.ParsingErrorVertex) {
return CellType.FORMULA;
}
if (vertex instanceof _DependencyGraph__WEBPACK_IMPORTED_MODULE_0__.ValueCellVertex) {
return CellType.VALUE;
}
return CellType.EMPTY;
};
var CellValueNoNumber;
(function (CellValueNoNumber) {
CellValueNoNumber["EMPTY"] = "EMPTY";
CellValueNoNumber["NUMBER"] = "NUMBER";
CellValueNoNumber["STRING"] = "STRING";
CellValueNoNumber["BOOLEAN"] = "BOOLEAN";
CellValueNoNumber["ERROR"] = "ERROR";
})(CellValueNoNumber || (CellValueNoNumber = {}));
var CellValueJustNumber;
(function (CellValueJustNumber) {
CellValueJustNumber["NUMBER"] = "NUMBER";
})(CellValueJustNumber || (CellValueJustNumber = {}));
const CellValueType = Object.assign(Object.assign({}, CellValueNoNumber), CellValueJustNumber);
const CellValueDetailedType = Object.assign(Object.assign({}, CellValueNoNumber), _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.NumberType);
const CellValueTypeOrd = arg => {
switch (arg) {
case CellValueType.EMPTY:
return 0;
case CellValueType.NUMBER:
return 1;
case CellValueType.STRING:
return 2;
case CellValueType.BOOLEAN:
return 3;
case CellValueType.ERROR:
return 4;
}
throw new Error('Cell value not computed');
};
const getCellValueType = cellValue => {
if (cellValue === _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.EmptyValue) {
return CellValueType.EMPTY;
}
if (cellValue instanceof CellError || cellValue instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_3__.SimpleRangeValue) {
return CellValueType.ERROR;
}
if (typeof cellValue === 'string') {
return CellValueType.STRING;
} else if ((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.isExtendedNumber)(cellValue)) {
return CellValueType.NUMBER;
} else if (typeof cellValue === 'boolean') {
return CellValueType.BOOLEAN;
}
throw new Error('Cell value not computed');
};
const getCellValueDetailedType = cellValue => {
if ((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.isExtendedNumber)(cellValue)) {
return (0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.getTypeOfExtendedNumber)(cellValue);
} else {
return getCellValueType(cellValue);
}
};
const getCellValueFormat = cellValue => {
if ((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.isExtendedNumber)(cellValue)) {
return (0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_2__.getFormatOfExtendedNumber)(cellValue);
} else {
return undefined;
}
};
class CellError {
constructor(type, message, root) {
this.type = type;
this.message = message;
this.root = root;
}
static parsingError() {
return new CellError(ErrorType.ERROR, _error_message__WEBPACK_IMPORTED_MODULE_1__.ErrorMessage.ParseError);
}
attachRootVertex(vertex) {
if (this.root === undefined) {
return new CellError(this.type, this.message, vertex);
} else {
return this;
}
}
}
const simpleRowAddress = (sheet, row) => ({
sheet,
row
});
const invalidSimpleRowAddress = address => address.row < 0;
const simpleColumnAddress = (sheet, col) => ({
sheet,
col
});
const invalidSimpleColumnAddress = address => address.col < 0;
const simpleCellAddress = (sheet, col, row) => ({
sheet,
col,
row
});
const invalidSimpleCellAddress = address => address.col < 0 || address.row < 0;
const movedSimpleCellAddress = (address, toSheet, toRight, toBottom) => {
return simpleCellAddress(toSheet, address.col + toRight, address.row + toBottom);
};
const addressKey = address => `${address.sheet},${address.row},${address.col}`;
function isSimpleCellAddress(obj) {
if (obj && (typeof obj === 'object' || typeof obj === 'function')) {
return 'col' in obj && typeof obj.col === 'number' && 'row' in obj && typeof obj.row === 'number' && 'sheet' in obj && typeof obj.sheet === 'number';
} else {
return false;
}
}
const absoluteSheetReference = (address, baseAddress) => {
var _a;
return (_a = address.sheet) !== null && _a !== void 0 ? _a : baseAddress.sheet;
};
const equalSimpleCellAddress = (left, right) => {
return left.sheet === right.sheet && left.col === right.col && left.row === right.row;
};
/***/ }),
/* 4 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AddressMapping: () => (/* reexport safe */ _AddressMapping_AddressMapping__WEBPACK_IMPORTED_MODULE_1__.AddressMapping),
/* harmony export */ ArrayMapping: () => (/* reexport safe */ _ArrayMapping__WEBPACK_IMPORTED_MODULE_5__.ArrayMapping),
/* harmony export */ ArrayVertex: () => (/* reexport safe */ _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_6__.ArrayVertex),
/* harmony export */ DenseStrategy: () => (/* reexport safe */ _AddressMapping_DenseStrategy__WEBPACK_IMPORTED_MODULE_12__.DenseStrategy),
/* harmony export */ DependencyGraph: () => (/* reexport safe */ _DependencyGraph__WEBPACK_IMPORTED_MODULE_0__.DependencyGraph),
/* harmony export */ EmptyCellVertex: () => (/* reexport safe */ _EmptyCellVertex__WEBPACK_IMPORTED_MODULE_7__.EmptyCellVertex),
/* harmony export */ FormulaCellVertex: () => (/* reexport safe */ _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_6__.FormulaCellVertex),
/* harmony export */ Graph: () => (/* reexport safe */ _Graph__WEBPACK_IMPORTED_MODULE_2__.Graph),
/* harmony export */ ParsingErrorVertex: () => (/* reexport safe */ _ParsingErrorVertex__WEBPACK_IMPORTED_MODULE_9__.ParsingErrorVertex),
/* harmony export */ RangeMapping: () => (/* reexport safe */ _RangeMapping__WEBPACK_IMPORTED_MODULE_3__.RangeMapping),
/* harmony export */ RangeVertex: () => (/* reexport safe */ _RangeVertex__WEBPACK_IMPORTED_MODULE_10__.RangeVertex),
/* harmony export */ SheetMapping: () => (/* reexport safe */ _SheetMapping__WEBPACK_IMPORTED_MODULE_4__.SheetMapping),
/* harmony export */ SparseStrategy: () => (/* reexport safe */ _AddressMapping_SparseStrategy__WEBPACK_IMPORTED_MODULE_11__.SparseStrategy),
/* harmony export */ ValueCellVertex: () => (/* reexport safe */ _ValueCellVertex__WEBPACK_IMPORTED_MODULE_8__.ValueCellVertex)
/* harmony export */ });
/* harmony import */ var _DependencyGraph__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _AddressMapping_AddressMapping__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(76);
/* harmony import */ var _Graph__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(83);
/* harmony import */ var _RangeMapping__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(84);
/* harmony import */ var _SheetMapping__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(85);
/* harmony import */ var _ArrayMapping__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(78);
/* harmony import */ var _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(80);
/* harmony import */ var _EmptyCellVertex__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(88);
/* harmony import */ var _ValueCellVertex__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(89);
/* harmony import */ var _ParsingErrorVertex__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(90);
/* harmony import */ var _RangeVertex__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(82);
/* harmony import */ var _AddressMapping_SparseStrategy__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(91);
/* harmony import */ var _AddressMapping_DenseStrategy__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(92);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/***/ }),
/* 5 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ DependencyGraph: () => (/* binding */ DependencyGraph)
/* harmony export */ });
/* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _absolutizeDependencies__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3);
/* harmony import */ var _ContentChanges__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(68);
/* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(61);
/* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(70);
/* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(69);
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(7);
/* harmony import */ var _Span__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(71);
/* harmony import */ var _statistics__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(72);
/* harmony import */ var ___WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(4);
/* harmony import */ var _AddressMapping_AddressMapping__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(76);
/* harmony import */ var _ArrayMapping__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(78);
/* harmony import */ var _collectAddressesDependentToRange__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(79);
/* harmony import */ var _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(80);
/* harmony import */ var _Graph__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(83);
/* harmony import */ var _RangeMapping__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(84);
/* harmony import */ var _SheetMapping__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(85);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
class DependencyGraph {
constructor(addressMapping, rangeMapping, sheetMapping, arrayMapping, stats, lazilyTransformingAstService, functionRegistry, namedExpressions) {
this.addressMapping = addressMapping;
this.rangeMapping = rangeMapping;
this.sheetMapping = sheetMapping;
this.arrayMapping = arrayMapping;
this.stats = stats;
this.lazilyTransformingAstService = lazilyTransformingAstService;
this.functionRegistry = functionRegistry;
this.namedExpressions = namedExpressions;
this.changes = _ContentChanges__WEBPACK_IMPORTED_MODULE_3__.ContentChanges.empty();
this.dependencyQueryAddresses = vertex => {
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex) {
return this.rangeDependencyQuery(vertex).map(([address, _]) => address);
} else {
const dependenciesResult = this.formulaDependencyQuery(vertex);
if (dependenciesResult !== undefined) {
const [address, dependencies] = dependenciesResult;
return dependencies.map(dependency => {
if (dependency instanceof _parser__WEBPACK_IMPORTED_MODULE_7__.NamedExpressionDependency) {
return this.namedExpressions.namedExpressionOrPlaceholder(dependency.name, address.sheet).address;
} else if ((0,_Cell__WEBPACK_IMPORTED_MODULE_2__.isSimpleCellAddress)(dependency)) {
return dependency;
} else {
return (0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.simpleCellRange)(dependency.start, dependency.end);
}
});
} else {
return [];
}
}
};
this.dependencyQueryVertices = vertex => {
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex) {
return this.rangeDependencyQuery(vertex);
} else {
const dependenciesResult = this.formulaDependencyQuery(vertex);
if (dependenciesResult !== undefined) {
const [address, dependencies] = dependenciesResult;
return dependencies.map(dependency => {
if (dependency instanceof _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange) {
return [dependency.start, this.rangeMapping.fetchRange(dependency.start, dependency.end)];
} else if (dependency instanceof _parser__WEBPACK_IMPORTED_MODULE_7__.NamedExpressionDependency) {
const namedExpression = this.namedExpressions.namedExpressionOrPlaceholder(dependency.name, address.sheet);
return [namedExpression.address, this.addressMapping.fetchCell(namedExpression.address)];
} else {
return [dependency, this.addressMapping.fetchCell(dependency)];
}
});
} else {
return [];
}
}
};
this.rangeDependencyQuery = vertex => {
const allDeps = [];
const {
smallerRangeVertex,
restRange
} = this.rangeMapping.findSmallerRange(vertex.range); //checking whether this range was splitted by bruteForce or not
let range;
if (smallerRangeVertex !== undefined && this.graph.adjacentNodes(smallerRangeVertex).has(vertex)) {
range = restRange;
allDeps.push([new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(smallerRangeVertex.start, smallerRangeVertex.end), smallerRangeVertex]);
} else {
//did we ever need to use full range
range = vertex.range;
}
for (const address of range.addresses(this)) {
const cell = this.addressMapping.getCell(address);
if (cell !== undefined) {
allDeps.push([address, cell]);
}
}
return allDeps;
};
this.formulaDependencyQuery = vertex => {
let formula;
let address;
if (vertex instanceof _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_14__.FormulaVertex) {
address = vertex.getAddress(this.lazilyTransformingAstService);
formula = vertex.getFormula(this.lazilyTransformingAstService);
} else {
return undefined;
}
const deps = (0,_parser__WEBPACK_IMPORTED_MODULE_7__.collectDependencies)(formula, this.functionRegistry);
return [address, (0,_absolutizeDependencies__WEBPACK_IMPORTED_MODULE_1__.absolutizeDependencies)(deps, address)];
};
this.graph = new _Graph__WEBPACK_IMPORTED_MODULE_15__.Graph(this.dependencyQueryVertices);
}
/**
* Invariants:
* - empty cell has associated EmptyCellVertex if and only if it is a dependency (possibly indirect, through range) to some formula
*/
static buildEmpty(lazilyTransformingAstService, config, functionRegistry, namedExpressions, stats) {
return new DependencyGraph(new _AddressMapping_AddressMapping__WEBPACK_IMPORTED_MODULE_11__.AddressMapping(config.chooseAddressMappingPolicy), new _RangeMapping__WEBPACK_IMPORTED_MODULE_16__.RangeMapping(), new _SheetMapping__WEBPACK_IMPORTED_MODULE_17__.SheetMapping(config.translationPackage), new _ArrayMapping__WEBPACK_IMPORTED_MODULE_12__.ArrayMapping(), stats, lazilyTransformingAstService, functionRegistry, namedExpressions);
}
setFormulaToCell(address, ast, dependencies, size, hasVolatileFunction, hasStructuralChangeFunction) {
const newVertex = _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_14__.FormulaVertex.fromAst(ast, address, size, this.lazilyTransformingAstService.version());
this.exchangeOrAddFormulaVertex(newVertex);
this.processCellDependencies(dependencies, newVertex);
this.graph.markNodeAsSpecialRecentlyChanged(newVertex);
if (hasVolatileFunction) {
this.markAsVolatile(newVertex);
}
if (hasStructuralChangeFunction) {
this.markAsDependentOnStructureChange(newVertex);
}
this.correctInfiniteRangesDependency(address);
return this.getAndClearContentChanges();
}
setParsingErrorToCell(address, errorVertex) {
const vertex = this.shrinkPossibleArrayAndGetCell(address);
this.exchangeOrAddGraphNode(vertex, errorVertex);
this.addressMapping.setCell(address, errorVertex);
this.graph.markNodeAsSpecialRecentlyChanged(errorVertex);
this.correctInfiniteRangesDependency(address);
return this.getAndClearContentChanges();
}
setValueToCell(address, value) {
const vertex = this.shrinkPossibleArrayAndGetCell(address);
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) {
this.arrayMapping.removeArray(vertex.getRange());
}
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ValueCellVertex) {
const oldValues = vertex.getValues();
if (oldValues.rawValue !== value.rawValue) {
vertex.setValues(value);
this.graph.markNodeAsSpecialRecentlyChanged(vertex);
}
} else {
const newVertex = new ___WEBPACK_IMPORTED_MODULE_10__.ValueCellVertex(value.parsedValue, value.rawValue);
this.exchangeOrAddGraphNode(vertex, newVertex);
this.addressMapping.setCell(address, newVertex);
this.graph.markNodeAsSpecialRecentlyChanged(newVertex);
}
this.correctInfiniteRangesDependency(address);
return this.getAndClearContentChanges();
}
setCellEmpty(address) {
const vertex = this.shrinkPossibleArrayAndGetCell(address);
if (vertex === undefined) {
return _ContentChanges__WEBPACK_IMPORTED_MODULE_3__.ContentChanges.empty();
}
if (this.graph.adjacentNodes(vertex).size > 0) {
const emptyVertex = new ___WEBPACK_IMPORTED_MODULE_10__.EmptyCellVertex();
this.exchangeGraphNode(vertex, emptyVertex);
if (this.graph.adjacentNodesCount(emptyVertex) === 0) {
this.removeVertex(emptyVertex);
this.addressMapping.removeCell(address);
} else {
this.graph.markNodeAsSpecialRecentlyChanged(emptyVertex);
this.addressMapping.setCell(address, emptyVertex);
}
} else {
this.removeVertex(vertex);
this.addressMapping.removeCell(address);
}
return this.getAndClearContentChanges();
}
ensureThatVertexIsNonArrayCellVertex(vertex) {
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) {
throw new Error('Illegal operation');
}
}
clearRecentlyChangedVertices() {
this.graph.clearSpecialNodesRecentlyChanged();
}
verticesToRecompute() {
return new Set([...this.graph.specialNodesRecentlyChanged, ...this.volatileVertices()]);
}
processCellDependencies(cellDependencies, endVertex) {
cellDependencies.forEach(dep => {
if (dep instanceof _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange) {
const range = dep;
let rangeVertex = this.getRange(range.start, range.end);
if (rangeVertex === undefined) {
rangeVertex = new ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex(range);
this.rangeMapping.setRange(rangeVertex);
}
this.graph.addNode(rangeVertex);
if (!range.isFinite()) {
this.graph.markNodeAsInfiniteRange(rangeVertex);
}
const {
smallerRangeVertex,
restRange
} = this.rangeMapping.findSmallerRange(range);
if (smallerRangeVertex !== undefined) {
this.graph.addEdge(smallerRangeVertex, rangeVertex);
if (rangeVertex.bruteForce) {
rangeVertex.bruteForce = false;
for (const cellFromRange of range.addresses(this)) {
//if we ever switch heuristic to processing by sorted sizes, this would be unnecessary
this.graph.removeEdge(this.fetchCell(cellFromRange), rangeVertex);
}
}
} else {
rangeVertex.bruteForce = true;
}
const array = this.arrayMapping.getArray(restRange);
if (array !== undefined) {
this.graph.addEdge(array, rangeVertex);
} else {
for (const cellFromRange of restRange.addresses(this)) {
this.graph.addEdge(this.fetchCellOrCreateEmpty(cellFromRange), rangeVertex);
}
}
this.graph.addEdge(rangeVertex, endVertex);
if (range.isFinite()) {
this.correctInfiniteRangesDependenciesByRangeVertex(rangeVertex);
}
} else if (dep instanceof _parser__WEBPACK_IMPORTED_MODULE_7__.NamedExpressionDependency) {
const sheetOfVertex = endVertex.getAddress(this.lazilyTransformingAstService).sheet;
const namedExpressionVertex = this.fetchNamedExpressionVertex(dep.name, sheetOfVertex);
this.graph.addEdge(namedExpressionVertex, endVertex);
} else {
this.graph.addEdge(this.fetchCellOrCreateEmpty(dep), endVertex);
}
});
}
fetchNamedExpressionVertex(expressionName, sheetId) {
const namedExpression = this.namedExpressions.namedExpressionOrPlaceholder(expressionName, sheetId);
return this.fetchCellOrCreateEmpty(namedExpression.address);
}
exchangeNode(addressFrom, addressTo) {
const vertexFrom = this.fetchCellOrCreateEmpty(addressFrom);
const vertexTo = this.fetchCellOrCreateEmpty(addressTo);
this.addressMapping.removeCell(addressFrom);
this.exchangeGraphNode(vertexFrom, vertexTo);
}
correctInfiniteRangesDependency(address) {
let vertex = undefined;
for (const range of this.graph.infiniteRanges) {
const infiniteRangeVertex = range;
if (infiniteRangeVertex.range.addressInRange(address)) {
vertex = vertex !== null && vertex !== void 0 ? vertex : this.fetchCellOrCreateEmpty(address);
this.graph.addEdge(vertex, infiniteRangeVertex);
}
}
}
fetchCellOrCreateEmpty(address) {
let vertex = this.addressMapping.getCell(address);
if (vertex === undefined) {
vertex = new ___WEBPACK_IMPORTED_MODULE_10__.EmptyCellVertex();
this.graph.addNode(vertex);
this.addressMapping.setCell(address, vertex);
}
return vertex;
}
removeRows(removedRows) {
this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_GRAPH, () => {
for (const [address, vertex] of this.addressMapping.entriesFromRowsSpan(removedRows)) {
for (const adjacentNode of this.graph.adjacentNodes(vertex)) {
this.graph.markNodeAsSpecialRecentlyChanged(adjacentNode);
}
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) {
if (vertex.isLeftCorner(address)) {
this.shrinkArrayToCorner(vertex);
this.arrayMapping.removeArray(vertex.getRange());
} else {
continue;
}
}
this.removeVertex(vertex);
}
});
this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ADDRESS_MAPPING, () => {
this.addressMapping.removeRows(removedRows);
});
const affectedArrays = this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_RANGES, () => {
const affectedRanges = this.truncateRanges(removedRows, address => address.row);
return this.getArrayVerticesRelatedToRanges(affectedRanges);
});
this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ARRAY_MAPPING, () => {
this.fixArraysAfterRemovingRows(removedRows.sheet, removedRows.rowStart, removedRows.numberOfRows);
});
this.addStructuralNodesToChangeSet();
return {
affectedArrays,
contentChanges: this.getAndClearContentChanges()
};
}
removeSheet(removedSheetId) {
this.clearSheet(removedSheetId);
for (const [adr, vertex] of this.addressMapping.sheetEntries(removedSheetId)) {
for (const adjacentNode of this.graph.adjacentNodes(vertex)) {
this.graph.markNodeAsSpecialRecentlyChanged(adjacentNode);
}
this.removeVertex(vertex);
this.addressMapping.removeCell(adr);
}
this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_RANGES, () => {
const rangesToRemove = this.rangeMapping.removeRangesInSheet(removedSheetId);
for (const range of rangesToRemove) {
this.removeVertex(range);
}
this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ADDRESS_MAPPING, () => {
this.addressMapping.removeSheet(removedSheetId);
});
});
}
clearSheet(sheetId) {
const arrays = new Set();
for (const [address, vertex] of this.addressMapping.sheetEntries(sheetId)) {
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) {
arrays.add(vertex);
} else {
this.setCellEmpty(address);
}
}
for (const array of arrays.values()) {
this.setArrayEmpty(array);
}
this.addStructuralNodesToChangeSet();
}
removeColumns(removedColumns) {
this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_GRAPH, () => {
for (const [address, vertex] of this.addressMapping.entriesFromColumnsSpan(removedColumns)) {
for (const adjacentNode of this.graph.adjacentNodes(vertex)) {
this.graph.markNodeAsSpecialRecentlyChanged(adjacentNode);
}
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) {
if (vertex.isLeftCorner(address)) {
this.shrinkArrayToCorner(vertex);
this.arrayMapping.removeArray(vertex.getRange());
} else {
continue;
}
}
this.removeVertex(vertex);
}
});
this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ADDRESS_MAPPING, () => {
this.addressMapping.removeColumns(removedColumns);
});
const affectedArrays = this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_RANGES, () => {
const affectedRanges = this.truncateRanges(removedColumns, address => address.col);
return this.getArrayVerticesRelatedToRanges(affectedRanges);
});
this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ARRAY_MAPPING, () => {
return this.fixArraysAfterRemovingColumns(removedColumns.sheet, removedColumns.columnStart, removedColumns.numberOfColumns);
});
this.addStructuralNodesToChangeSet();
return {
affectedArrays,
contentChanges: this.getAndClearContentChanges()
};
}
addRows(addedRows) {
this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ADDRESS_MAPPING, () => {
this.addressMapping.addRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows);
});
const affectedArrays = this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_RANGES, () => {
const result = this.rangeMapping.moveAllRangesInSheetAfterRowByRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows);
this.fixRangesWhenAddingRows(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows);
return this.getArrayVerticesRelatedToRanges(result.verticesWithChangedSize);
});
this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ARRAY_MAPPING, () => {
this.fixArraysAfterAddingRow(addedRows.sheet, addedRows.rowStart, addedRows.numberOfRows);
});
for (const vertex of this.addressMapping.verticesFromRowsSpan(addedRows)) {
this.graph.markNodeAsSpecialRecentlyChanged(vertex);
}
this.addStructuralNodesToChangeSet();
return {
affectedArrays
};
}
addColumns(addedColumns) {
this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ADDRESS_MAPPING, () => {
this.addressMapping.addColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns);
});
const affectedArrays = this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_RANGES, () => {
const result = this.rangeMapping.moveAllRangesInSheetAfterColumnByColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns);
this.fixRangesWhenAddingColumns(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns);
return this.getArrayVerticesRelatedToRanges(result.verticesWithChangedSize);
});
this.stats.measure(_statistics__WEBPACK_IMPORTED_MODULE_9__.StatType.ADJUSTING_ARRAY_MAPPING, () => {
return this.fixArraysAfterAddingColumn(addedColumns.sheet, addedColumns.columnStart, addedColumns.numberOfColumns);
});
for (const vertex of this.addressMapping.verticesFromColumnsSpan(addedColumns)) {
this.graph.markNodeAsSpecialRecentlyChanged(vertex);
}
this.addStructuralNodesToChangeSet();
return {
affectedArrays,
contentChanges: this.getAndClearContentChanges()
};
}
ensureNoArrayInRange(range) {
if (this.arrayMapping.isFormulaArrayInRange(range)) {
throw Error('It is not possible to move / replace cells with array');
}
}
isThereSpaceForArray(arrayVertex) {
const range = arrayVertex.getRangeOrUndef();
if (range === undefined) {
return false;
}
for (const address of range.addresses(this)) {
const vertexUnderAddress = this.addressMapping.getCell(address);
if (vertexUnderAddress !== undefined && !(vertexUnderAddress instanceof ___WEBPACK_IMPORTED_MODULE_10__.EmptyCellVertex) && vertexUnderAddress !== arrayVertex) {
return false;
}
}
return true;
}
moveCells(sourceRange, toRight, toBottom, toSheet) {
for (const sourceAddress of sourceRange.addressesWithDirection(toRight, toBottom, this)) {
const targetAddress = (0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(toSheet, sourceAddress.col + toRight, sourceAddress.row + toBottom);
let sourceVertex = this.addressMapping.getCell(sourceAddress);
const targetVertex = this.addressMapping.getCell(targetAddress);
this.addressMapping.removeCell(sourceAddress);
if (sourceVertex !== undefined) {
this.graph.markNodeAsSpecialRecentlyChanged(sourceVertex);
this.addressMapping.setCell(targetAddress, sourceVertex);
let emptyVertex = undefined;
for (const adjacentNode of this.graph.adjacentNodes(sourceVertex)) {
if (adjacentNode instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex && !sourceRange.containsRange(adjacentNode.range)) {
emptyVertex = emptyVertex !== null && emptyVertex !== void 0 ? emptyVertex : this.fetchCellOrCreateEmpty(sourceAddress);
this.graph.addEdge(emptyVertex, adjacentNode);
this.graph.removeEdge(sourceVertex, adjacentNode);
}
}
if (emptyVertex) {
this.graph.markNodeAsSpecialRecentlyChanged(emptyVertex);
this.addressMapping.setCell(sourceAddress, emptyVertex);
}
}
if (targetVertex !== undefined) {
if (sourceVertex === undefined) {
this.addressMapping.removeCell(targetAddress);
}
for (const adjacentNode of this.graph.adjacentNodes(targetVertex)) {
sourceVertex = sourceVertex !== null && sourceVertex !== void 0 ? sourceVertex : this.fetchCellOrCreateEmpty(targetAddress);
this.graph.addEdge(sourceVertex, adjacentNode);
this.graph.markNodeAsSpecialRecentlyChanged(sourceVertex);
}
this.removeVertex(targetVertex);
}
}
for (const rangeVertex of this.rangeMapping.rangeVerticesContainedInRange(sourceRange)) {
for (const adjacentNode of this.graph.adjacentNodes(rangeVertex)) {
if (adjacentNode instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex && !sourceRange.containsRange(adjacentNode.range)) {
this.graph.removeEdge(rangeVertex, adjacentNode);
for (const address of rangeVertex.range.addresses(this)) {
const newEmptyVertex = this.fetchCellOrCreateEmpty(address);
this.graph.addEdge(newEmptyVertex, adjacentNode);
this.addressMapping.setCell(address, newEmptyVertex);
this.graph.markNodeAsSpecialRecentlyChanged(newEmptyVertex);
}
}
}
}
this.rangeMapping.moveRangesInsideSourceRange(sourceRange, toRight, toBottom, toSheet);
}
setArrayEmpty(arrayVertex) {
const arrayRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(arrayVertex.getAddress(this.lazilyTransformingAstService), arrayVertex.width, arrayVertex.height);
const adjacentNodes = this.graph.adjacentNodes(arrayVertex);
for (const address of arrayRange.addresses(this)) {
this.addressMapping.removeCell(address);
}
for (const adjacentNode of adjacentNodes.values()) {
const nodeDependencies = (0,_collectAddressesDependentToRange__WEBPACK_IMPORTED_MODULE_13__.collectAddressesDependentToRange)(this.functionRegistry, adjacentNode, arrayVertex.getRange(), this.lazilyTransformingAstService, this);
for (const address of nodeDependencies) {
const vertex = this.fetchCellOrCreateEmpty(address);
this.graph.addEdge(vertex, adjacentNode);
}
if (nodeDependencies.length > 0) {
this.graph.markNodeAsSpecialRecentlyChanged(adjacentNode);
}
}
this.removeVertex(arrayVertex);
this.arrayMapping.removeArray(arrayVertex.getRange());
}
addVertex(address, vertex) {
this.graph.addNode(vertex);
this.addressMapping.setCell(address, vertex);
}
addArrayVertex(address, vertex) {
this.graph.addNode(vertex);
this.setAddressMappingForArrayVertex(vertex, address);
}
*arrayFormulaNodes() {
for (const vertex of this.graph.nodes) {
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) {
yield vertex;
}
}
}
*entriesFromRowsSpan(rowsSpan) {
yield* this.addressMapping.entriesFromRowsSpan(rowsSpan);
}
*entriesFromColumnsSpan(columnsSpan) {
yield* this.addressMapping.entriesFromColumnsSpan(columnsSpan);
}
existsVertex(address) {
return this.addressMapping.has(address);
}
fetchCell(address) {
return this.addressMapping.fetchCell(address);
}
getCell(address) {
return this.addressMapping.getCell(address);
}
getCellValue(address) {
return this.addressMapping.getCellValue(address);
}
getRawValue(address) {
return this.addressMapping.getRawValue(address);
}
getScalarValue(address) {
const value = this.addressMapping.getCellValue(address);
if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue) {
return new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_4__.ErrorMessage.ScalarExpected);
}
return value;
}
existsEdge(fromNode, toNode) {
return this.graph.existsEdge(fromNode, toNode);
}
getSheetId(sheetName) {
return this.sheetMapping.fetch(sheetName);
}
getSheetHeight(sheet) {
return this.addressMapping.getHeight(sheet);
}
getSheetWidth(sheet) {
return this.addressMapping.getWidth(sheet);
}
getArray(range) {
return this.arrayMapping.getArray(range);
}
setArray(range, vertex) {
this.arrayMapping.setArray(range, vertex);
}
getRange(start, end) {
return this.rangeMapping.getRange(start, end);
}
topSortWithScc() {
return this.graph.topSortWithScc();
}
markAsVolatile(vertex) {
this.graph.markNodeAsSpecial(vertex);
}
markAsDependentOnStructureChange(vertex) {
this.graph.markNodeAsChangingWithStructure(vertex);
}
forceApplyPostponedTransformations() {
for (const vertex of this.graph.nodes.values()) {
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.FormulaCellVertex) {
vertex.ensureRecentData(this.lazilyTransformingAstService);
}
}
}
volatileVertices() {
return this.graph.specialNodes;
}
getArrayVerticesRelatedToRanges(ranges) {
const arrayVertices = ranges.map(range => {
if (this.graph.hasNode(range)) {
return Array.from(this.graph.adjacentNodes(range)).filter(node => node instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex);
} else {
return [];
}
});
return new Set(...arrayVertices);
}
*rawValuesFromRange(range) {
for (const address of range.addresses(this)) {
const value = this.getScalarValue(address);
if (value !== _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.EmptyValue) {
yield [(0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.getRawValue)(value), address];
}
}
}
*entriesFromRange(range) {
for (const address of range.addresses(this)) {
yield [address, this.getCell(address)];
}
}
exchangeGraphNode(oldNode, newNode) {
this.graph.addNode(newNode);
const adjNodesStored = this.graph.adjacentNodes(oldNode);
this.removeVertex(oldNode);
adjNodesStored.forEach(adjacentNode => {
if (this.graph.hasNode(adjacentNode)) {
this.graph.addEdge(newNode, adjacentNode);
}
});
}
exchangeOrAddGraphNode(oldNode, newNode) {
if (oldNode) {
this.exchangeGraphNode(oldNode, newNode);
} else {
this.graph.addNode(newNode);
}
}
computeListOfValuesInRange(range) {
const values = [];
for (const cellFromRange of range.addresses(this)) {
const value = this.getScalarValue(cellFromRange);
values.push(value);
}
return values;
}
shrinkArrayToCorner(array) {
this.cleanAddressMappingUnderArray(array);
for (const adjacentVertex of this.adjacentArrayVertices(array)) {
let relevantDependencies;
if (adjacentVertex instanceof _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_14__.FormulaVertex) {
relevantDependencies = this.formulaDirectDependenciesToArray(adjacentVertex, array);
} else {
relevantDependencies = this.rangeDirectDependenciesToArray(adjacentVertex, array);
}
let dependentToCorner = false;
for (const [address, vertex] of relevantDependencies) {
if (array.isLeftCorner(address)) {
dependentToCorner = true;
}
this.graph.addEdge(vertex, adjacentVertex);
this.graph.markNodeAsSpecialRecentlyChanged(vertex);
}
if (!dependentToCorner) {
this.graph.removeEdge(array, adjacentVertex);
}
}
this.graph.markNodeAsSpecialRecentlyChanged(array);
}
isArrayInternalCell(address) {
const vertex = this.getCell(address);
return vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex && !vertex.isLeftCorner(address);
}
getAndClearContentChanges() {
const changes = this.changes;
this.changes = _ContentChanges__WEBPACK_IMPORTED_MODULE_3__.ContentChanges.empty();
return changes;
}
getAdjacentNodesAddresses(inputVertex) {
const deps = this.graph.adjacentNodes(inputVertex);
const ret = [];
deps.forEach(vertex => {
const castVertex = vertex;
if (castVertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex) {
ret.push((0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.simpleCellRange)(castVertex.start, castVertex.end));
} else {
ret.push(castVertex.getAddress(this.lazilyTransformingAstService));
}
});
return ret;
}
correctInfiniteRangesDependenciesByRangeVertex(vertex) {
for (const range of this.graph.infiniteRanges) {
const infiniteRangeVertex = range;
const intersection = vertex.range.intersectionWith(infiniteRangeVertex.range);
if (intersection === undefined) {
continue;
}
for (const address of intersection.addresses(this)) {
this.graph.addEdge(this.fetchCellOrCreateEmpty(address), range);
}
}
}
cleanAddressMappingUnderArray(vertex) {
const arrayRange = vertex.getRange();
for (const address of arrayRange.addresses(this)) {
const oldValue = vertex.getArrayCellValue(address);
if (this.getCell(address) === vertex) {
if (vertex.isLeftCorner(address)) {
this.changes.addChange(new _Cell__WEBPACK_IMPORTED_MODULE_2__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_2__.ErrorType.REF), address, oldValue);
} else {
this.addressMapping.removeCell(address);
this.changes.addChange(_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.EmptyValue, address, oldValue);
}
} else {
this.changes.addChange(_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.EmptyValue, address, oldValue);
}
}
}
*formulaDirectDependenciesToArray(vertex, array) {
var _a;
const [, formulaDependencies] = (_a = this.formulaDependencyQuery(vertex)) !== null && _a !== void 0 ? _a : [];
if (formulaDependencies === undefined) {
return;
}
for (const dependency of formulaDependencies) {
if (dependency instanceof _parser__WEBPACK_IMPORTED_MODULE_7__.NamedExpressionDependency || dependency instanceof _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange) {
continue;
}
if (array.getRange().addressInRange(dependency)) {
const vertex = this.fetchCellOrCreateEmpty(dependency);
yield [dependency, vertex];
}
}
}
*rangeDirectDependenciesToArray(vertex, array) {
const {
restRange: range
} = this.rangeMapping.findSmallerRange(vertex.range);
for (const address of range.addresses(this)) {
if (array.getRange().addressInRange(address)) {
const cell = this.fetchCellOrCreateEmpty(address);
yield [address, cell];
}
}
}
*adjacentArrayVertices(vertex) {
const adjacentNodes = this.graph.adjacentNodes(vertex);
for (const item of adjacentNodes) {
if (item instanceof _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_14__.FormulaVertex || item instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex) {
yield item;
}
}
}
addStructuralNodesToChangeSet() {
for (const vertex of this.graph.specialNodesStructuralChanges) {
this.graph.markNodeAsSpecialRecentlyChanged(vertex);
}
}
fixRangesWhenAddingRows(sheet, row, numberOfRows) {
const originalValues = Array.from(this.rangeMapping.rangesInSheet(sheet));
for (const rangeVertex of originalValues) {
if (rangeVertex.range.includesRow(row + numberOfRows)) {
if (rangeVertex.bruteForce) {
const addedSubrangeInThatRange = rangeVertex.range.rangeWithSameWidth(row, numberOfRows);
for (const address of addedSubrangeInThatRange.addresses(this)) {
this.graph.addEdge(this.fetchCellOrCreateEmpty(address), rangeVertex);
}
} else {
let currentRangeVertex = rangeVertex;
let find = this.rangeMapping.findSmallerRange(currentRangeVertex.range);
if (find.smallerRangeVertex !== undefined) {
continue;
}
while (find.smallerRangeVertex === undefined) {
const newRangeVertex = new ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex(_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(currentRangeVertex.range.start, currentRangeVertex.range.width(), currentRangeVertex.range.height() - 1));
this.rangeMapping.setRange(newRangeVertex);
this.graph.addNode(newRangeVertex);
const restRange = new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange((0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(currentRangeVertex.range.start.sheet, currentRangeVertex.range.start.col, currentRangeVertex.range.end.row), currentRangeVertex.range.end);
this.addAllFromRange(restRange, currentRangeVertex);
this.graph.addEdge(newRangeVertex, currentRangeVertex);
currentRangeVertex = newRangeVertex;
find = this.rangeMapping.findSmallerRange(currentRangeVertex.range);
}
this.graph.addEdge(find.smallerRangeVertex, currentRangeVertex);
this.addAllFromRange(find.restRange, currentRangeVertex);
this.graph.removeEdge(find.smallerRangeVertex, rangeVertex);
}
}
}
}
addAllFromRange(range, vertex) {
for (const address of range.addresses(this)) {
this.graph.addEdge(this.fetchCellOrCreateEmpty(address), vertex);
}
}
fixRangesWhenAddingColumns(sheet, column, numberOfColumns) {
for (const rangeVertex of this.rangeMapping.rangesInSheet(sheet)) {
if (rangeVertex.range.includesColumn(column + numberOfColumns)) {
let subrange;
if (rangeVertex.bruteForce) {
subrange = rangeVertex.range.rangeWithSameHeight(column, numberOfColumns);
} else {
subrange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom((0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(sheet, column, rangeVertex.range.end.row), numberOfColumns, 1);
}
for (const address of subrange.addresses(this)) {
this.graph.addEdge(this.fetchCellOrCreateEmpty(address), rangeVertex);
}
}
}
}
exchangeOrAddFormulaVertex(vertex) {
const address = vertex.getAddress(this.lazilyTransformingAstService);
const range = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(address, vertex.width, vertex.height);
const oldNode = this.shrinkPossibleArrayAndGetCell(address);
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) {
this.setArray(range, vertex);
}
this.exchangeOrAddGraphNode(oldNode, vertex);
this.addressMapping.setCell(address, vertex);
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) {
if (!this.isThereSpaceForArray(vertex)) {
return;
}
for (const cellAddress of range.addresses(this)) {
if (vertex.isLeftCorner(cellAddress)) {
continue;
}
const old = this.getCell(cellAddress);
this.exchangeOrAddGraphNode(old, vertex);
}
}
for (const cellAddress of range.addresses(this)) {
this.addressMapping.setCell(cellAddress, vertex);
}
}
setAddressMappingForArrayVertex(vertex, formulaAddress) {
this.addressMapping.setCell(formulaAddress, vertex);
if (!(vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex)) {
return;
}
const range = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFromOrUndef(formulaAddress, vertex.width, vertex.height);
if (range === undefined) {
return;
}
this.setArray(range, vertex);
if (!this.isThereSpaceForArray(vertex)) {
return;
}
for (const address of range.addresses(this)) {
this.addressMapping.setCell(address, vertex);
}
}
truncateRanges(span, coordinate) {
const {
verticesToRemove,
verticesToMerge,
verticesWithChangedSize
} = this.rangeMapping.truncateRanges(span, coordinate);
for (const [existingVertex, mergedVertex] of verticesToMerge) {
this.mergeRangeVertices(existingVertex, mergedVertex);
}
for (const rangeVertex of verticesToRemove) {
this.removeVertexAndCleanupDependencies(rangeVertex);
}
return verticesWithChangedSize;
}
fixArraysAfterAddingRow(sheet, rowStart, numberOfRows) {
this.arrayMapping.moveArrayVerticesAfterRowByRows(sheet, rowStart, numberOfRows);
if (rowStart <= 0) {
return;
}
for (const [, array] of this.arrayMapping.arraysInRows(_Span__WEBPACK_IMPORTED_MODULE_8__.RowsSpan.fromRowStartAndEnd(sheet, rowStart - 1, rowStart - 1))) {
const arrayRange = array.getRange();
for (let col = arrayRange.start.col; col <= arrayRange.end.col; ++col) {
for (let row = rowStart; row <= arrayRange.end.row; ++row) {
const destination = (0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(sheet, col, row);
const source = (0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(sheet, col, row + numberOfRows);
const value = array.getArrayCellValue(destination);
this.addressMapping.moveCell(source, destination);
this.changes.addChange(_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.EmptyValue, source, value);
}
}
}
}
fixArraysAfterRemovingRows(sheet, rowStart, numberOfRows) {
this.arrayMapping.moveArrayVerticesAfterRowByRows(sheet, rowStart, -numberOfRows);
if (rowStart <= 0) {
return;
}
for (const [, array] of this.arrayMapping.arraysInRows(_Span__WEBPACK_IMPORTED_MODULE_8__.RowsSpan.fromRowStartAndEnd(sheet, rowStart - 1, rowStart - 1))) {
if (this.isThereSpaceForArray(array)) {
for (const address of array.getRange().addresses(this)) {
this.addressMapping.setCell(address, array);
}
} else {
this.setNoSpaceIfArray(array);
}
}
}
fixArraysAfterAddingColumn(sheet, columnStart, numberOfColumns) {
this.arrayMapping.moveArrayVerticesAfterColumnByColumns(sheet, columnStart, numberOfColumns);
if (columnStart <= 0) {
return;
}
for (const [, array] of this.arrayMapping.arraysInCols(_Span__WEBPACK_IMPORTED_MODULE_8__.ColumnsSpan.fromColumnStartAndEnd(sheet, columnStart - 1, columnStart - 1))) {
const arrayRange = array.getRange();
for (let row = arrayRange.start.row; row <= arrayRange.end.row; ++row) {
for (let col = columnStart; col <= arrayRange.end.col; ++col) {
const destination = (0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(sheet, col, row);
const source = (0,_Cell__WEBPACK_IMPORTED_MODULE_2__.simpleCellAddress)(sheet, col + numberOfColumns, row);
const value = array.getArrayCellValue(destination);
this.addressMapping.moveCell(source, destination);
this.changes.addChange(_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.EmptyValue, source, value);
}
}
}
}
fixArraysAfterRemovingColumns(sheet, columnStart, numberOfColumns) {
this.arrayMapping.moveArrayVerticesAfterColumnByColumns(sheet, columnStart, -numberOfColumns);
if (columnStart <= 0) {
return;
}
for (const [, array] of this.arrayMapping.arraysInCols(_Span__WEBPACK_IMPORTED_MODULE_8__.ColumnsSpan.fromColumnStartAndEnd(sheet, columnStart - 1, columnStart - 1))) {
if (this.isThereSpaceForArray(array)) {
for (const address of array.getRange().addresses(this)) {
this.addressMapping.setCell(address, array);
}
} else {
this.setNoSpaceIfArray(array);
}
}
}
shrinkPossibleArrayAndGetCell(address) {
const vertex = this.getCell(address);
if (!(vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex)) {
return vertex;
}
this.setNoSpaceIfArray(vertex);
return this.getCell(address);
}
setNoSpaceIfArray(vertex) {
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.ArrayVertex) {
this.shrinkArrayToCorner(vertex);
vertex.setNoSpace();
}
}
removeVertex(vertex) {
this.removeVertexAndCleanupDependencies(vertex);
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex) {
this.rangeMapping.removeRange(vertex);
}
}
mergeRangeVertices(existingVertex, newVertex) {
const adjNodesStored = this.graph.adjacentNodes(newVertex);
this.removeVertexAndCleanupDependencies(newVertex);
this.graph.softRemoveEdge(existingVertex, newVertex);
adjNodesStored.forEach(adjacentNode => {
if (this.graph.hasNode(adjacentNode)) {
this.graph.addEdge(existingVertex, adjacentNode);
}
});
}
removeVertexAndCleanupDependencies(inputVertex) {
const dependencies = new Set(this.graph.removeNode(inputVertex));
while (dependencies.size > 0) {
const dependency = dependencies.values().next().value;
dependencies.delete(dependency);
const [address, vertex] = dependency;
if (this.graph.hasNode(vertex) && this.graph.adjacentNodesCount(vertex) === 0) {
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex || vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.EmptyCellVertex) {
this.graph.removeNode(vertex).forEach(candidate => dependencies.add(candidate));
}
if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.RangeVertex) {
this.rangeMapping.removeRange(vertex);
} else if (vertex instanceof ___WEBPACK_IMPORTED_MODULE_10__.EmptyCellVertex) {
this.addressMapping.removeCell(address);
}
}
}
}
}
/***/ }),
/* 6 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ absolutizeDependencies: () => (/* binding */ absolutizeDependencies),
/* harmony export */ filterDependenciesOutOfScope: () => (/* binding */ filterDependenciesOutOfScope)
/* harmony export */ });
/* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* Converts dependencies from maybe relative addressing to absolute addressing.
*
* @param deps - list of addresses in R0C0 format
* @param baseAddress - base address with regard to which make a convertion
*/
const absolutizeDependencies = (deps, baseAddress) => {
return deps.map(dep => dep.absolutize(baseAddress));
};
const filterDependenciesOutOfScope = deps => {
return deps.filter(dep => {
if (dep instanceof _parser__WEBPACK_IMPORTED_MODULE_2__.NamedExpressionDependency) {
return true;
}
if (dep instanceof _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange) {
return !((0,_Cell__WEBPACK_IMPORTED_MODULE_1__.invalidSimpleCellAddress)(dep.start) || (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.invalidSimpleCellAddress)(dep.end));
} else {
return !(0,_Cell__WEBPACK_IMPORTED_MODULE_1__.invalidSimpleCellAddress)(dep);
}
});
};
/***/ }),
/* 7 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AddressDependency: () => (/* reexport safe */ _RelativeDependency__WEBPACK_IMPORTED_MODULE_8__.AddressDependency),
/* harmony export */ AstNodeType: () => (/* reexport safe */ _Ast__WEBPACK_IMPORTED_MODULE_6__.AstNodeType),
/* harmony export */ CellAddress: () => (/* reexport safe */ _CellAddress__WEBPACK_IMPORTED_MODULE_1__.CellAddress),
/* harmony export */ CellRangeDependency: () => (/* reexport safe */ _RelativeDependency__WEBPACK_IMPORTED_MODULE_8__.CellRangeDependency),
/* harmony export */ ColumnRangeDependency: () => (/* reexport safe */ _RelativeDependency__WEBPACK_IMPORTED_MODULE_8__.ColumnRangeDependency),
/* harmony export */ FormulaLexer: () => (/* reexport safe */ _FormulaParser__WEBPACK_IMPORTED_MODULE_5__.FormulaLexer),
/* harmony export */ NamedExpressionDependency: () => (/* reexport safe */ _RelativeDependency__WEBPACK_IMPORTED_MODULE_8__.NamedExpressionDependency),
/* harmony export */ ParserWithCaching: () => (/* reexport safe */ _ParserWithCaching__WEBPACK_IMPORTED_MODULE_2__.ParserWithCaching),
/* harmony export */ ParsingErrorType: () => (/* reexport safe */ _Ast__WEBPACK_IMPORTED_MODULE_6__.ParsingErrorType),
/* harmony export */ RowRangeDependency: () => (/* reexport safe */ _RelativeDependency__WEBPACK_IMPORTED_MODULE_8__.RowRangeDependency),
/* harmony export */ Unparser: () => (/* reexport safe */ _Unparser__WEBPACK_IMPORTED_MODULE_7__.Unparser),
/* harmony export */ buildCellErrorAst: () => (/* reexport safe */ _Ast__WEBPACK_IMPORTED_MODULE_6__.buildCellErrorAst),
/* harmony export */ buildCellRangeAst: () => (/* reexport safe */ _Ast__WEBPACK_IMPORTED_MODULE_6__.buildCellRangeAst),
/* harmony export */ buildLexerConfig: () => (/* reexport safe */ _LexerConfig__WEBPACK_IMPORTED_MODULE_4__.buildLexerConfig),
/* harmony export */ buildParsingErrorAst: () => (/* reexport safe */ _Ast__WEBPACK_IMPORTED_MODULE_6__.buildParsingErrorAst),
/* harmony export */ buildProcedureAst: () => (/* reexport safe */ _Ast__WEBPACK_IMPORTED_MODULE_6__.buildProcedureAst),
/* harmony export */ cellAddressFromString: () => (/* reexport safe */ _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_0__.cellAddressFromString),
/* harmony export */ collectDependencies: () => (/* reexport safe */ _collectDependencies__WEBPACK_IMPORTED_MODULE_3__.collectDependencies),
/* harmony export */ simpleCellAddressFromString: () => (/* reexport safe */ _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddressFromString),
/* harmony export */ simpleCellAddressToString: () => (/* reexport safe */ _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddressToString),
/* harmony export */ simpleCellRangeFromString: () => (/* reexport safe */ _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_0__.simpleCellRangeFromString),
/* harmony export */ simpleCellRangeToString: () => (/* reexport safe */ _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_0__.simpleCellRangeToString)
/* harmony export */ });
/* harmony import */ var _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(8);
/* harmony import */ var _CellAddress__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9);
/* harmony import */ var _ParserWithCaching__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(13);
/* harmony import */ var _collectDependencies__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(66);
/* harmony import */ var _LexerConfig__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(62);
/* harmony import */ var _FormulaParser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(60);
/* harmony import */ var _Ast__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(57);
/* harmony import */ var _Unparser__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(65);
/* harmony import */ var _RelativeDependency__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(67);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/***/ }),
/* 8 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ cellAddressFromString: () => (/* binding */ cellAddressFromString),
/* harmony export */ columnAddressFromString: () => (/* binding */ columnAddressFromString),
/* harmony export */ columnIndexToLabel: () => (/* binding */ columnIndexToLabel),
/* harmony export */ rowAddressFromString: () => (/* binding */ rowAddressFromString),
/* harmony export */ sheetIndexToString: () => (/* binding */ sheetIndexToString),
/* harmony export */ simpleCellAddressFromString: () => (/* binding */ simpleCellAddressFromString),
/* harmony export */ simpleCellAddressToString: () => (/* binding */ simpleCellAddressToString),
/* harmony export */ simpleCellRangeFromString: () => (/* binding */ simpleCellRangeFromString),
/* harmony export */ simpleCellRangeToString: () => (/* binding */ simpleCellRangeToString)
/* harmony export */ });
/* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _CellAddress__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9);
/* harmony import */ var _ColumnAddress__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(10);
/* harmony import */ var _parser_consts__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(12);
/* harmony import */ var _RowAddress__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(11);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
const addressRegex = new RegExp(`^(${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.SHEET_NAME_PATTERN})?(\\${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR}?)([A-Za-z]+)(\\${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR}?)([0-9]+)$`);
const columnRegex = new RegExp(`^(${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.SHEET_NAME_PATTERN})?(\\${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR}?)([A-Za-z]+)$`);
const rowRegex = new RegExp(`^(${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.SHEET_NAME_PATTERN})?(\\${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR}?)([0-9]+)$`);
const simpleSheetNameRegex = new RegExp(`^${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.UNQUOTED_SHEET_NAME_PATTERN}$`);
/**
* Computes R0C0 representation of cell address based on it's string representation and base address.
*
* @param sheetMapping - mapping function needed to change name of a sheet to index
* @param stringAddress - string representation of cell address, e.g. 'C64'
* @param baseAddress - base address for R0C0 conversion
* @returns object representation of address
*/
const cellAddressFromString = (sheetMapping, stringAddress, baseAddress) => {
const result = addressRegex.exec(stringAddress);
const col = columnLabelToIndex(result[6]);
let sheet = extractSheetNumber(result, sheetMapping);
if (sheet === undefined) {
return undefined;
}
if (sheet === null) {
sheet = undefined;
}
const row = Number(result[8]) - 1;
if (result[5] === _parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR && result[7] === _parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR) {
return _CellAddress__WEBPACK_IMPORTED_MODULE_2__.CellAddress.absolute(col, row, sheet);
} else if (result[5] === _parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR) {
return _CellAddress__WEBPACK_IMPORTED_MODULE_2__.CellAddress.absoluteCol(col, row - baseAddress.row, sheet);
} else if (result[7] === _parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR) {
return _CellAddress__WEBPACK_IMPORTED_MODULE_2__.CellAddress.absoluteRow(col - baseAddress.col, row, sheet);
} else {
return _CellAddress__WEBPACK_IMPORTED_MODULE_2__.CellAddress.relative(col - baseAddress.col, row - baseAddress.row, sheet);
}
};
const columnAddressFromString = (sheetMapping, stringAddress, baseAddress) => {
const result = columnRegex.exec(stringAddress);
let sheet = extractSheetNumber(result, sheetMapping);
if (sheet === undefined) {
return undefined;
}
if (sheet === null) {
sheet = undefined;
}
const col = columnLabelToIndex(result[6]);
if (result[5] === _parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR) {
return _ColumnAddress__WEBPACK_IMPORTED_MODULE_3__.ColumnAddress.absolute(col, sheet);
} else {
return _ColumnAddress__WEBPACK_IMPORTED_MODULE_3__.ColumnAddress.relative(col - baseAddress.col, sheet);
}
};
const rowAddressFromString = (sheetMapping, stringAddress, baseAddress) => {
const result = rowRegex.exec(stringAddress);
let sheet = extractSheetNumber(result, sheetMapping);
if (sheet === undefined) {
return undefined;
}
if (sheet === null) {
sheet = undefined;
}
const row = Number(result[6]) - 1;
if (result[5] === _parser_consts__WEBPACK_IMPORTED_MODULE_4__.ABSOLUTE_OPERATOR) {
return _RowAddress__WEBPACK_IMPORTED_MODULE_5__.RowAddress.absolute(row, sheet);
} else {
return _RowAddress__WEBPACK_IMPORTED_MODULE_5__.RowAddress.relative(row - baseAddress.row, sheet);
}
};
/**
* Computes simple (absolute) address of a cell address based on its string representation.
* If sheet name present in string representation but is not present in sheet mapping, returns undefined.
* If sheet name is not present in string representation, returns {@param sheetContext} as sheet number
*
* @param sheetMapping - mapping function needed to change name of a sheet to index
* @param stringAddress - string representation of cell address, e.g. 'C64'
* @param sheetContext - sheet in context of which we should parse the address
* @returns absolute representation of address, e.g. { sheet: 0, col: 1, row: 1 }
*/
const simpleCellAddressFromString = (sheetMapping, stringAddress, sheetContext) => {
const result = addressRegex.exec(stringAddress);
const col = columnLabelToIndex(result[6]);
let sheet = extractSheetNumber(result, sheetMapping);
if (sheet === undefined) {
return undefined;
}
if (sheet === null) {
sheet = sheetContext;
}
const row = Number(result[8]) - 1;
return (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(sheet, col, row);
};
const simpleCellRangeFromString = (sheetMapping, stringAddress, sheetContext) => {
const split = stringAddress.split(_parser_consts__WEBPACK_IMPORTED_MODULE_4__.RANGE_OPERATOR);
if (split.length !== 2) {
return undefined;
}
const [startString, endString] = split;
const start = simpleCellAddressFromString(sheetMapping, startString, sheetContext);
if (start === undefined) {
return undefined;
}
const end = simpleCellAddressFromString(sheetMapping, endString, start.sheet);
if (end === undefined) {
return undefined;
}
if (start.sheet !== end.sheet) {
return undefined;
}
return (0,_AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.simpleCellRange)(start, end);
};
/**
* Returns string representation of absolute address
* If sheet index is not present in sheet mapping, returns undefined
*
* @param sheetIndexMapping - mapping function needed to change sheet index to sheet name
* @param address - object representation of absolute address
* @param sheetIndex - if is not equal with address sheet index, string representation will contain sheet name
*/
const simpleCellAddressToString = (sheetIndexMapping, address, sheetIndex) => {
const column = columnIndexToLabel(address.col);
const sheetName = sheetIndexToString(address.sheet, sheetIndexMapping);
if (sheetName === undefined) {
return undefined;
}
if (sheetIndex !== address.sheet) {
return `${sheetName}!${column}${address.row + 1}`;
} else {
return `${column}${address.row + 1}`;
}
};
const simpleCellRangeToString = (sheetIndexMapping, address, sheetIndex) => {
const startString = simpleCellAddressToString(sheetIndexMapping, address.start, sheetIndex);
const endString = simpleCellAddressToString(sheetIndexMapping, address.end, address.start.sheet);
if (startString === undefined || endString === undefined) {
return undefined;
} else {
return `${startString}${_parser_consts__WEBPACK_IMPORTED_MODULE_4__.RANGE_OPERATOR}${endString}`;
}
};
/**
* Convert column label to index
*
* @param columnStringRepresentation - column label (e.g. 'AAB')
* @returns column index
*/
function columnLabelToIndex(columnStringRepresentation) {
if (columnStringRepresentation.length === 1) {
return columnStringRepresentation.toUpperCase().charCodeAt(0) - 65;
} else {
return columnStringRepresentation.split('').reduce((currentColumn, nextLetter) => {
return currentColumn * 26 + (nextLetter.toUpperCase().charCodeAt(0) - 64);
}, 0) - 1;
}
}
/**
* Converts column index to label
*
* @param column - address to convert
* @returns string representation, e.g. 'AAB'
*/
function columnIndexToLabel(column) {
let result = '';
while (column >= 0) {
result = String.fromCharCode(column % 26 + 97) + result;
column = Math.floor(column / 26) - 1;
}
return result.toUpperCase();
}
function sheetIndexToString(sheetId, sheetMappingFn) {
let sheetName = sheetMappingFn(sheetId);
if (sheetName === undefined) {
return undefined;
}
if (simpleSheetNameRegex.test(sheetName)) {
return sheetName;
} else {
sheetName = sheetName.replace(/'/g, "''");
return `'${sheetName}'`;
}
}
function extractSheetNumber(regexResult, sheetMapping) {
var _a;
let maybeSheetName = (_a = regexResult[3]) !== null && _a !== void 0 ? _a : regexResult[2];
if (maybeSheetName) {
maybeSheetName = maybeSheetName.replace(/''/g, "'");
return sheetMapping(maybeSheetName);
} else {
return null;
}
}
/***/ }),
/* 9 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CellAddress: () => (/* binding */ CellAddress),
/* harmony export */ CellReferenceType: () => (/* binding */ CellReferenceType)
/* harmony export */ });
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/* harmony import */ var _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _ColumnAddress__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(10);
/* harmony import */ var _RowAddress__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(11);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/** Possible kinds of cell references */
var CellReferenceType;
(function (CellReferenceType) {
/** Cell reference with both row and column relative. */
CellReferenceType["CELL_REFERENCE_RELATIVE"] = "CELL_REFERENCE";
/** Cell reference with both row and column absolute. */
CellReferenceType["CELL_REFERENCE_ABSOLUTE"] = "CELL_REFERENCE_ABSOLUTE";
/** Cell reference with absolute column and relative row. */
CellReferenceType["CELL_REFERENCE_ABSOLUTE_COL"] = "CELL_REFERENCE_ABSOLUTE_COL";
/** Cell reference with relative column and absolute row. */
CellReferenceType["CELL_REFERENCE_ABSOLUTE_ROW"] = "CELL_REFERENCE_ABSOLUTE_ROW";
})(CellReferenceType || (CellReferenceType = {}));
class CellAddress {
constructor(col, row, type, sheet) {
this.col = col;
this.row = row;
this.type = type;
this.sheet = sheet;
}
static fromColAndRow(col, row, sheet) {
const factoryMethod = col.isColumnAbsolute() && row.isRowAbsolute() ? CellAddress.absolute.bind(this) : col.isColumnAbsolute() ? CellAddress.absoluteCol.bind(this) : row.isRowAbsolute() ? CellAddress.absoluteRow.bind(this) : CellAddress.relative.bind(this);
return factoryMethod(col.col, row.row, sheet);
}
static relative(col, row, sheet) {
return new CellAddress(col, row, CellReferenceType.CELL_REFERENCE_RELATIVE, sheet);
}
static absolute(col, row, sheet) {
return new CellAddress(col, row, CellReferenceType.CELL_REFERENCE_ABSOLUTE, sheet);
}
static absoluteCol(col, row, sheet) {
return new CellAddress(col, row, CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL, sheet);
}
static absoluteRow(col, row, sheet) {
return new CellAddress(col, row, CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW, sheet);
}
/**
* Converts R0C0 representation of cell address to simple object representation.
*
* @param baseAddress - base address for R0C0 shifts
*/
toSimpleCellAddress(baseAddress) {
const sheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(this, baseAddress);
if (this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE) {
return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, this.col, this.row);
} else if (this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW) {
return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, baseAddress.col + this.col, this.row);
} else if (this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL) {
return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, this.col, baseAddress.row + this.row);
} else {
return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, baseAddress.col + this.col, baseAddress.row + this.row);
}
}
toColumnAddress() {
const refType = this.isColumnRelative() ? _ColumnAddress__WEBPACK_IMPORTED_MODULE_2__.ReferenceType.RELATIVE : _ColumnAddress__WEBPACK_IMPORTED_MODULE_2__.ReferenceType.ABSOLUTE;
return new _ColumnAddress__WEBPACK_IMPORTED_MODULE_2__.ColumnAddress(refType, this.col, this.sheet);
}
toRowAddress() {
const refType = this.isRowRelative() ? _ColumnAddress__WEBPACK_IMPORTED_MODULE_2__.ReferenceType.RELATIVE : _ColumnAddress__WEBPACK_IMPORTED_MODULE_2__.ReferenceType.ABSOLUTE;
return new _RowAddress__WEBPACK_IMPORTED_MODULE_3__.RowAddress(refType, this.row, this.sheet);
}
toSimpleColumnAddress(baseAddress) {
const sheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(this, baseAddress);
let column = this.col;
if (this.isColumnRelative()) {
column += baseAddress.col;
}
return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleColumnAddress)(sheet, column);
}
toSimpleRowAddress(baseAddress) {
const sheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(this, baseAddress);
let row = this.row;
if (this.isRowRelative()) {
row += baseAddress.row;
}
return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleRowAddress)(sheet, row);
}
isRowAbsolute() {
return this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE || this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW;
}
isColumnAbsolute() {
return this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE || this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL;
}
isColumnRelative() {
return this.type === CellReferenceType.CELL_REFERENCE_RELATIVE || this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW;
}
isRowRelative() {
return this.type === CellReferenceType.CELL_REFERENCE_RELATIVE || this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL;
}
isAbsolute() {
return this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE && this.sheet !== undefined;
}
shiftedByRows(numberOfRows) {
return new CellAddress(this.col, this.row + numberOfRows, this.type, this.sheet);
}
shiftedByColumns(numberOfColumns) {
return new CellAddress(this.col + numberOfColumns, this.row, this.type, this.sheet);
}
moved(toSheet, toRight, toBottom) {
const newSheet = this.sheet === undefined ? undefined : toSheet;
return new CellAddress(this.col + toRight, this.row + toBottom, this.type, newSheet);
}
withSheet(sheet) {
return new CellAddress(this.col, this.row, this.type, sheet);
}
isInvalid(baseAddress) {
return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.invalidSimpleCellAddress)(this.toSimpleCellAddress(baseAddress));
}
shiftRelativeDimensions(toRight, toBottom) {
const col = this.isColumnAbsolute() ? this.col : this.col + toRight;
const row = this.isRowAbsolute() ? this.row : this.row + toBottom;
return new CellAddress(col, row, this.type, this.sheet);
}
shiftAbsoluteDimensions(toRight, toBottom) {
const col = this.isColumnRelative() ? this.col : this.col + toRight;
const row = this.isRowRelative() ? this.row : this.row + toBottom;
return new CellAddress(col, row, this.type, this.sheet);
}
hash(withSheet) {
const sheetPart = withSheet && this.sheet !== undefined ? `#${this.sheet}` : '';
switch (this.type) {
case CellReferenceType.CELL_REFERENCE_RELATIVE:
{
return `${sheetPart}#${this.row}R${this.col}`;
}
case CellReferenceType.CELL_REFERENCE_ABSOLUTE:
{
return `${sheetPart}#${this.row}A${this.col}`;
}
case CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL:
{
return `${sheetPart}#${this.row}AC${this.col}`;
}
case CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW:
{
return `${sheetPart}#${this.row}AR${this.col}`;
}
}
}
unparse(baseAddress) {
const simpleAddress = this.toSimpleCellAddress(baseAddress);
if ((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.invalidSimpleCellAddress)(simpleAddress)) {
return undefined;
}
const column = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_1__.columnIndexToLabel)(simpleAddress.col);
const rowDollar = this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE || this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW ? '$' : '';
const colDollar = this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE || this.type === CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL ? '$' : '';
return `${colDollar}${column}${rowDollar}${simpleAddress.row + 1}`;
}
exceedsSheetSizeLimits(maxColumns, maxRows) {
return this.row >= maxRows || this.col >= maxColumns;
}
}
/***/ }),
/* 10 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ColumnAddress: () => (/* binding */ ColumnAddress),
/* harmony export */ ReferenceType: () => (/* binding */ ReferenceType)
/* harmony export */ });
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/* harmony import */ var _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
var ReferenceType;
(function (ReferenceType) {
ReferenceType["RELATIVE"] = "RELATIVE";
ReferenceType["ABSOLUTE"] = "ABSOLUTE";
})(ReferenceType || (ReferenceType = {}));
class ColumnAddress {
constructor(type, col, sheet) {
this.type = type;
this.col = col;
this.sheet = sheet;
}
static absolute(column, sheet) {
return new ColumnAddress(ReferenceType.ABSOLUTE, column, sheet);
}
static relative(column, sheet) {
return new ColumnAddress(ReferenceType.RELATIVE, column, sheet);
}
static compareByAbsoluteAddress(baseAddress) {
return (colA, colB) => colA.toSimpleColumnAddress(baseAddress).col - colB.toSimpleColumnAddress(baseAddress).col;
}
isColumnAbsolute() {
return this.type === ReferenceType.ABSOLUTE;
}
isColumnRelative() {
return this.type === ReferenceType.RELATIVE;
}
isAbsolute() {
return this.type === ReferenceType.ABSOLUTE && this.sheet !== undefined;
}
moved(toSheet, toRight, _toBottom) {
const newSheet = this.sheet === undefined ? undefined : toSheet;
return new ColumnAddress(this.type, this.col + toRight, newSheet);
}
shiftedByColumns(numberOfColumns) {
return new ColumnAddress(this.type, this.col + numberOfColumns, this.sheet);
}
toSimpleColumnAddress(baseAddress) {
const sheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(this, baseAddress);
let column = this.col;
if (this.isColumnRelative()) {
column = baseAddress.col + this.col;
}
return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleColumnAddress)(sheet, column);
}
shiftRelativeDimensions(toRight, _toBottom) {
const col = this.isColumnRelative() ? this.col + toRight : this.col;
return new ColumnAddress(this.type, col, this.sheet);
}
shiftAbsoluteDimensions(toRight, _toBottom) {
const col = this.isColumnAbsolute() ? this.col + toRight : this.col;
return new ColumnAddress(this.type, col, this.sheet);
}
withSheet(sheet) {
return new ColumnAddress(this.type, this.col, sheet);
}
isInvalid(baseAddress) {
return this.toSimpleColumnAddress(baseAddress).col < 0;
}
hash(withSheet) {
const sheetPart = withSheet && this.sheet !== undefined ? `#${this.sheet}` : '';
switch (this.type) {
case ReferenceType.RELATIVE:
{
return `${sheetPart}#COLR${this.col}`;
}
case ReferenceType.ABSOLUTE:
{
return `${sheetPart}#COLA${this.col}`;
}
}
}
unparse(baseAddress) {
const simpleAddress = this.toSimpleColumnAddress(baseAddress);
if ((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.invalidSimpleColumnAddress)(simpleAddress)) {
return undefined;
}
const column = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_1__.columnIndexToLabel)(simpleAddress.col);
const dollar = this.type === ReferenceType.ABSOLUTE ? '$' : '';
return `${dollar}${column}`;
}
exceedsSheetSizeLimits(maxColumns) {
return this.col >= maxColumns;
}
}
/***/ }),
/* 11 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ RowAddress: () => (/* binding */ RowAddress)
/* harmony export */ });
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/* harmony import */ var _ColumnAddress__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(10);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
class RowAddress {
constructor(type, row, sheet) {
this.type = type;
this.row = row;
this.sheet = sheet;
}
static absolute(row, sheet) {
return new RowAddress(_ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.ABSOLUTE, row, sheet);
}
static relative(row, sheet) {
return new RowAddress(_ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.RELATIVE, row, sheet);
}
static compareByAbsoluteAddress(baseAddress) {
return (rowA, rowB) => rowA.toSimpleRowAddress(baseAddress).row - rowB.toSimpleRowAddress(baseAddress).row;
}
isRowAbsolute() {
return this.type === _ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.ABSOLUTE;
}
isRowRelative() {
return this.type === _ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.RELATIVE;
}
isAbsolute() {
return this.type === _ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.ABSOLUTE && this.sheet !== undefined;
}
moved(toSheet, toRight, toBottom) {
const newSheet = this.sheet === undefined ? undefined : toSheet;
return new RowAddress(this.type, this.row + toBottom, newSheet);
}
shiftedByRows(numberOfColumns) {
return new RowAddress(this.type, this.row + numberOfColumns, this.sheet);
}
toSimpleRowAddress(baseAddress) {
const sheet = (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.absoluteSheetReference)(this, baseAddress);
let row = this.row;
if (this.isRowRelative()) {
row = baseAddress.row + this.row;
}
return (0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleRowAddress)(sheet, row);
}
shiftRelativeDimensions(toRight, toBottom) {
const row = this.isRowRelative() ? this.row + toBottom : this.row;
return new RowAddress(this.type, row, this.sheet);
}
shiftAbsoluteDimensions(toRight, toBottom) {
const row = this.isRowAbsolute() ? this.row + toBottom : this.row;
return new RowAddress(this.type, row, this.sheet);
}
withSheet(sheet) {
return new RowAddress(this.type, this.row, sheet);
}
isInvalid(baseAddress) {
return this.toSimpleRowAddress(baseAddress).row < 0;
}
hash(withSheet) {
const sheetPart = withSheet && this.sheet !== undefined ? `#${this.sheet}` : '';
switch (this.type) {
case _ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.RELATIVE:
{
return `${sheetPart}#ROWR${this.row}`;
}
case _ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.ABSOLUTE:
{
return `${sheetPart}#ROWA${this.row}`;
}
}
}
unparse(baseAddress) {
const simpleAddress = this.toSimpleRowAddress(baseAddress);
if ((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.invalidSimpleRowAddress)(simpleAddress)) {
return undefined;
}
const dollar = this.type === _ColumnAddress__WEBPACK_IMPORTED_MODULE_1__.ReferenceType.ABSOLUTE ? '$' : '';
return `${dollar}${simpleAddress.row + 1}`;
}
exceedsSheetSizeLimits(maxRows) {
return this.row >= maxRows;
}
}
/***/ }),
/* 12 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ABSOLUTE_OPERATOR: () => (/* binding */ ABSOLUTE_OPERATOR),
/* harmony export */ ALL_DIGITS_ARRAY: () => (/* binding */ ALL_DIGITS_ARRAY),
/* harmony export */ ALL_UNICODE_LETTERS_ARRAY: () => (/* binding */ ALL_UNICODE_LETTERS_ARRAY),
/* harmony export */ ALL_WHITESPACE_PATTERN: () => (/* binding */ ALL_WHITESPACE_PATTERN),
/* harmony export */ CELL_REFERENCE_PATTERN: () => (/* binding */ CELL_REFERENCE_PATTERN),
/* harmony export */ CELL_REFERENCE_WITH_NEXT_CHARACTER_PATTERN: () => (/* binding */ CELL_REFERENCE_WITH_NEXT_CHARACTER_PATTERN),
/* harmony export */ COLUMN_REFERENCE_PATTERN: () => (/* binding */ COLUMN_REFERENCE_PATTERN),
/* harmony export */ NAMED_EXPRESSION_PATTERN: () => (/* binding */ NAMED_EXPRESSION_PATTERN),
/* harmony export */ NON_RESERVED_CHARACTER_PATTERN: () => (/* binding */ NON_RESERVED_CHARACTER_PATTERN),
/* harmony export */ ODFF_WHITESPACE_PATTERN: () => (/* binding */ ODFF_WHITESPACE_PATTERN),
/* harmony export */ QUOTED_SHEET_NAME_PATTERN: () => (/* binding */ QUOTED_SHEET_NAME_PATTERN),
/* harmony export */ R1C1_CELL_REFERENCE_PATTERN: () => (/* binding */ R1C1_CELL_REFERENCE_PATTERN),
/* harmony export */ RANGE_OPERATOR: () => (/* binding */ RANGE_OPERATOR),
/* harmony export */ ROW_REFERENCE_PATTERN: () => (/* binding */ ROW_REFERENCE_PATTERN),
/* harmony export */ SHEET_NAME_PATTERN: () => (/* binding */ SHEET_NAME_PATTERN),
/* harmony export */ UNICODE_LETTER_PATTERN: () => (/* binding */ UNICODE_LETTER_PATTERN),
/* harmony export */ UNQUOTED_SHEET_NAME_PATTERN: () => (/* binding */ UNQUOTED_SHEET_NAME_PATTERN)
/* harmony export */ });
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
const RANGE_OPERATOR = ':';
const ABSOLUTE_OPERATOR = '$';
const ALL_WHITESPACE_PATTERN = '\\s+';
const ODFF_WHITESPACE_PATTERN = '[ \\t\\n\\r]+';
const UNICODE_LETTER_PATTERN = 'A-Za-z\u00C0-\u02AF';
const NON_RESERVED_CHARACTER_PATTERN = `${UNICODE_LETTER_PATTERN}0-9_.`;
const UNQUOTED_SHEET_NAME_PATTERN = `[${UNICODE_LETTER_PATTERN}0-9_]+`;
const QUOTED_SHEET_NAME_PATTERN = "'(((?!').|'')*)'";
const SHEET_NAME_PATTERN = `(${UNQUOTED_SHEET_NAME_PATTERN}|${QUOTED_SHEET_NAME_PATTERN})!`;
const CELL_REFERENCE_PATTERN = `(${SHEET_NAME_PATTERN})?\\${ABSOLUTE_OPERATOR}?[A-Za-z]+\\${ABSOLUTE_OPERATOR}?[0-9]+`;
const COLUMN_REFERENCE_PATTERN = `(${SHEET_NAME_PATTERN})?\\${ABSOLUTE_OPERATOR}?[A-Za-z]+`;
const ROW_REFERENCE_PATTERN = `(${SHEET_NAME_PATTERN})?\\${ABSOLUTE_OPERATOR}?[0-9]+`;
const R1C1_CELL_REFERENCE_PATTERN = '[rR][0-9]*[cC][0-9]*';
const CELL_REFERENCE_WITH_NEXT_CHARACTER_PATTERN = `(${CELL_REFERENCE_PATTERN})[^${NON_RESERVED_CHARACTER_PATTERN}]`;
const NAMED_EXPRESSION_PATTERN = `[${UNICODE_LETTER_PATTERN}_][${NON_RESERVED_CHARACTER_PATTERN}]*`;
const ALL_DIGITS_ARRAY = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
const ALL_UNICODE_LETTERS_ARRAY = [...Array.from(Array(26)).map((_, i) => i + 'A'.charCodeAt(0)), ...Array.from(Array(26)).map((_, i) => i + 'a'.charCodeAt(0)), ...Array.from(Array(0x02AF - 0x00C0 + 1)).map((_, i) => i + 0x00C0)].map(code => String.fromCharCode(code));
/***/ }),
/* 13 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ParserWithCaching: () => (/* binding */ ParserWithCaching)
/* harmony export */ });
/* harmony import */ var chevrotain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14);
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var ___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7);
/* harmony import */ var _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _Ast__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(57);
/* harmony import */ var _binaryOpTokenMap__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(58);
/* harmony import */ var _Cache__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(59);
/* harmony import */ var _FormulaParser__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(60);
/* harmony import */ var _LexerConfig__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(62);
/* harmony import */ var _Unparser__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(65);
/* harmony import */ var _ColumnAddress__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(10);
/* harmony import */ var _RowAddress__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(11);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* Parses formula using caching if feasible.
*/
class ParserWithCaching {
constructor(config, functionRegistry, sheetMapping) {
this.config = config;
this.functionRegistry = functionRegistry;
this.sheetMapping = sheetMapping;
this.statsCacheUsed = 0;
this.lexerConfig = (0,_LexerConfig__WEBPACK_IMPORTED_MODULE_8__.buildLexerConfig)(config);
this.lexer = new _FormulaParser__WEBPACK_IMPORTED_MODULE_7__.FormulaLexer(this.lexerConfig);
this.formulaParser = new _FormulaParser__WEBPACK_IMPORTED_MODULE_7__.FormulaParser(this.lexerConfig, this.sheetMapping);
this.cache = new _Cache__WEBPACK_IMPORTED_MODULE_6__.Cache(this.functionRegistry);
}
/**
* Parses a formula.
*
* @param text - formula to parse
* @param formulaAddress - address with regard to which formula should be parsed. Impacts computed addresses in R0C0 format.
*/
parse(text, formulaAddress) {
this.formulaAddress = formulaAddress;
const lexerResult = this.tokenizeFormula(text);
if (lexerResult.errors.length > 0) {
const errors = lexerResult.errors.map(e => ({
type: _Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.LexingError,
message: e.message
}));
return {
ast: (0,___WEBPACK_IMPORTED_MODULE_2__.buildParsingErrorAst)(),
errors,
hasVolatileFunction: false,
hasStructuralChangeFunction: false,
dependencies: []
};
}
const hash = this.computeHashFromTokens(lexerResult.tokens, formulaAddress);
let cacheResult = this.cache.get(hash);
if (cacheResult !== undefined) {
++this.statsCacheUsed;
} else {
const processedTokens = this.bindWhitespacesToTokens(lexerResult.tokens);
const parsingResult = this.formulaParser.parseFromTokens(processedTokens, formulaAddress);
if (parsingResult.errors.length > 0) {
return Object.assign(Object.assign({}, parsingResult), {
hasVolatileFunction: false,
hasStructuralChangeFunction: false,
dependencies: []
});
} else {
cacheResult = this.cache.set(hash, parsingResult.ast);
}
}
const {
ast,
hasVolatileFunction,
hasStructuralChangeFunction
} = cacheResult;
const astWithNoReversedRanges = this.convertReversedRangesToRegularRanges(ast);
const dependencies = (0,___WEBPACK_IMPORTED_MODULE_2__.collectDependencies)(astWithNoReversedRanges, this.functionRegistry);
return {
ast: astWithNoReversedRanges,
errors: [],
hasVolatileFunction,
hasStructuralChangeFunction,
dependencies
};
}
convertReversedRangesToRegularRanges(ast) {
switch (ast.type) {
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.EMPTY:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.NUMBER:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.STRING:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ERROR:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ERROR_WITH_RAW_INPUT:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.CELL_REFERENCE:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.NAMED_EXPRESSION:
return ast;
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.CELL_RANGE:
{
const {
start,
end
} = ast;
const orderedEnds = this.orderCellRangeEnds(start, end);
return Object.assign(Object.assign({}, ast), {
start: orderedEnds.start,
end: orderedEnds.end
});
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.COLUMN_RANGE:
{
const {
start,
end
} = ast;
const orderedEnds = this.orderColumnRangeEnds(start, end);
return Object.assign(Object.assign({}, ast), {
start: orderedEnds.start,
end: orderedEnds.end
});
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ROW_RANGE:
{
const {
start,
end
} = ast;
const orderedEnds = this.orderRowRangeEnds(start, end);
return Object.assign(Object.assign({}, ast), {
start: orderedEnds.start,
end: orderedEnds.end
});
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.PERCENT_OP:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.PLUS_UNARY_OP:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.MINUS_UNARY_OP:
{
const valueFixed = this.convertReversedRangesToRegularRanges(ast.value);
return Object.assign(Object.assign({}, ast), {
value: valueFixed
});
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.CONCATENATE_OP:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.EQUALS_OP:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.NOT_EQUAL_OP:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.LESS_THAN_OP:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.GREATER_THAN_OP:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.LESS_THAN_OR_EQUAL_OP:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.GREATER_THAN_OR_EQUAL_OP:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.MINUS_OP:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.PLUS_OP:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.TIMES_OP:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.DIV_OP:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.POWER_OP:
{
const leftFixed = this.convertReversedRangesToRegularRanges(ast.left);
const rightFixed = this.convertReversedRangesToRegularRanges(ast.right);
return Object.assign(Object.assign({}, ast), {
left: leftFixed,
right: rightFixed
});
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.PARENTHESIS:
{
const exprFixed = this.convertReversedRangesToRegularRanges(ast.expression);
return Object.assign(Object.assign({}, ast), {
expression: exprFixed
});
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.FUNCTION_CALL:
{
const argsFixed = ast.args.map(arg => this.convertReversedRangesToRegularRanges(arg));
return Object.assign(Object.assign({}, ast), {
args: argsFixed
});
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ARRAY:
{
const argsFixed = ast.args.map(argsRow => argsRow.map(arg => this.convertReversedRangesToRegularRanges(arg)));
return Object.assign(Object.assign({}, ast), {
args: argsFixed
});
}
}
}
orderCellRangeEnds(endA, endB) {
const ends = [endA, endB];
const [startCol, endCol] = ends.map(e => e.toColumnAddress()).sort(_ColumnAddress__WEBPACK_IMPORTED_MODULE_10__.ColumnAddress.compareByAbsoluteAddress(this.formulaAddress));
const [startRow, endRow] = ends.map(e => e.toRowAddress()).sort(_RowAddress__WEBPACK_IMPORTED_MODULE_11__.RowAddress.compareByAbsoluteAddress(this.formulaAddress));
const [startSheet, endSheet] = ends.map(e => e.sheet).sort(ParserWithCaching.compareSheetIds.bind(this));
return {
start: ___WEBPACK_IMPORTED_MODULE_2__.CellAddress.fromColAndRow(startCol, startRow, startSheet),
end: ___WEBPACK_IMPORTED_MODULE_2__.CellAddress.fromColAndRow(endCol, endRow, endSheet)
};
}
orderColumnRangeEnds(endA, endB) {
const ends = [endA, endB];
const [startCol, endCol] = ends.sort(_ColumnAddress__WEBPACK_IMPORTED_MODULE_10__.ColumnAddress.compareByAbsoluteAddress(this.formulaAddress));
const [startSheet, endSheet] = ends.map(e => e.sheet).sort(ParserWithCaching.compareSheetIds.bind(this));
return {
start: new _ColumnAddress__WEBPACK_IMPORTED_MODULE_10__.ColumnAddress(startCol.type, startCol.col, startSheet),
end: new _ColumnAddress__WEBPACK_IMPORTED_MODULE_10__.ColumnAddress(endCol.type, endCol.col, endSheet)
};
}
orderRowRangeEnds(endA, endB) {
const ends = [endA, endB];
const [startRow, endRow] = ends.sort(_RowAddress__WEBPACK_IMPORTED_MODULE_11__.RowAddress.compareByAbsoluteAddress(this.formulaAddress));
const [startSheet, endSheet] = ends.map(e => e.sheet).sort(ParserWithCaching.compareSheetIds.bind(this));
return {
start: new _RowAddress__WEBPACK_IMPORTED_MODULE_11__.RowAddress(startRow.type, startRow.row, startSheet),
end: new _RowAddress__WEBPACK_IMPORTED_MODULE_11__.RowAddress(endRow.type, endRow.row, endSheet)
};
}
static compareSheetIds(sheetA, sheetB) {
sheetA = sheetA != null ? sheetA : Infinity;
sheetB = sheetB != null ? sheetB : Infinity;
return sheetA - sheetB;
}
fetchCachedResultForAst(ast) {
const hash = this.computeHashFromAst(ast);
return this.fetchCachedResult(hash);
}
fetchCachedResult(hash) {
const cacheResult = this.cache.get(hash);
if (cacheResult === undefined) {
throw new Error('There is no AST with such key in the cache');
} else {
const {
ast,
hasVolatileFunction,
hasStructuralChangeFunction,
relativeDependencies
} = cacheResult;
return {
ast,
errors: [],
hasVolatileFunction,
hasStructuralChangeFunction,
dependencies: relativeDependencies
};
}
}
computeHashFromTokens(tokens, baseAddress) {
var _a;
let hash = '';
let idx = 0;
while (idx < tokens.length) {
const token = tokens[idx];
if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(token, _LexerConfig__WEBPACK_IMPORTED_MODULE_8__.CellReference)) {
const cellAddress = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.cellAddressFromString)(this.sheetMapping, token.image, baseAddress);
if (cellAddress === undefined) {
hash = hash.concat(token.image);
} else {
hash = hash.concat(cellAddress.hash(true));
}
} else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(token, _LexerConfig__WEBPACK_IMPORTED_MODULE_8__.ProcedureName)) {
const procedureName = token.image.toUpperCase().slice(0, -1);
const canonicalProcedureName = (_a = this.lexerConfig.functionMapping[procedureName]) !== null && _a !== void 0 ? _a : procedureName;
hash = hash.concat(canonicalProcedureName, '(');
} else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(token, _LexerConfig__WEBPACK_IMPORTED_MODULE_8__.ColumnRange)) {
const [start, end] = token.image.split(':');
const startAddress = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.columnAddressFromString)(this.sheetMapping, start, baseAddress);
const endAddress = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.columnAddressFromString)(this.sheetMapping, end, baseAddress);
if (startAddress === undefined || endAddress === undefined) {
hash = hash.concat('!REF');
} else {
hash = hash.concat(startAddress.hash(true), ':', endAddress.hash(true));
}
} else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(token, _LexerConfig__WEBPACK_IMPORTED_MODULE_8__.RowRange)) {
const [start, end] = token.image.split(':');
const startAddress = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.rowAddressFromString)(this.sheetMapping, start, baseAddress);
const endAddress = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.rowAddressFromString)(this.sheetMapping, end, baseAddress);
if (startAddress === undefined || endAddress === undefined) {
hash = hash.concat('!REF');
} else {
hash = hash.concat(startAddress.hash(true), ':', endAddress.hash(true));
}
} else {
hash = hash.concat(token.image);
}
idx++;
}
return hash;
}
rememberNewAst(ast) {
const hash = this.computeHashFromAst(ast);
return this.cache.maybeSetAndThenGet(hash, ast);
}
computeHashFromAst(ast) {
return '=' + this.computeHashOfAstNode(ast);
}
computeHashOfAstNode(ast) {
switch (ast.type) {
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.EMPTY:
{
return ast.leadingWhitespace || '';
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.NUMBER:
{
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)((0,_Unparser__WEBPACK_IMPORTED_MODULE_9__.formatNumber)(ast.value, this.config.decimalSeparator), ast.leadingWhitespace);
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.STRING:
{
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)('"' + ast.value + '"', ast.leadingWhitespace);
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.NAMED_EXPRESSION:
{
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(ast.expressionName, ast.leadingWhitespace);
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.FUNCTION_CALL:
{
const args = ast.args.map(arg => this.computeHashOfAstNode(arg)).join(this.config.functionArgSeparator);
const rightPart = ast.procedureName + '(' + args + (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(')', ast.internalWhitespace);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(rightPart, ast.leadingWhitespace);
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.CELL_REFERENCE:
{
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(ast.reference.hash(true), ast.leadingWhitespace);
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.COLUMN_RANGE:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ROW_RANGE:
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.CELL_RANGE:
{
const start = ast.start.hash(ast.sheetReferenceType !== _Ast__WEBPACK_IMPORTED_MODULE_4__.RangeSheetReferenceType.RELATIVE);
const end = ast.end.hash(ast.sheetReferenceType === _Ast__WEBPACK_IMPORTED_MODULE_4__.RangeSheetReferenceType.BOTH_ABSOLUTE);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(start + ':' + end, ast.leadingWhitespace);
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.MINUS_UNARY_OP:
{
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)('-' + this.computeHashOfAstNode(ast.value), ast.leadingWhitespace);
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.PLUS_UNARY_OP:
{
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)('+' + this.computeHashOfAstNode(ast.value), ast.leadingWhitespace);
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.PERCENT_OP:
{
return this.computeHashOfAstNode(ast.value) + (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)('%', ast.leadingWhitespace);
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ERROR:
{
const image = this.config.translationPackage.getErrorTranslation(ast.error ? ast.error.type : _Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.ERROR);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(image, ast.leadingWhitespace);
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ERROR_WITH_RAW_INPUT:
{
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(ast.rawInput, ast.leadingWhitespace);
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.ARRAY:
{
const args = ast.args.map(row => row.map(val => this.computeHashOfAstNode(val)).join(',')).join(';');
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)('{' + args + (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)('}', ast.internalWhitespace), ast.leadingWhitespace);
}
case ___WEBPACK_IMPORTED_MODULE_2__.AstNodeType.PARENTHESIS:
{
const expression = this.computeHashOfAstNode(ast.expression);
const rightPart = '(' + expression + (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(')', ast.internalWhitespace);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(rightPart, ast.leadingWhitespace);
}
default:
{
return this.computeHashOfAstNode(ast.left) + (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.imageWithWhitespace)(_binaryOpTokenMap__WEBPACK_IMPORTED_MODULE_5__.binaryOpTokenMap[ast.type], ast.leadingWhitespace) + this.computeHashOfAstNode(ast.right);
}
}
}
bindWhitespacesToTokens(tokens) {
const processedTokens = [];
const first = tokens[0];
if (!(0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(first, this.lexerConfig.WhiteSpace)) {
processedTokens.push(first);
}
for (let i = 1; i < tokens.length; ++i) {
const current = tokens[i];
if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(current, this.lexerConfig.WhiteSpace)) {
continue;
}
const previous = tokens[i - 1];
if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(previous, this.lexerConfig.WhiteSpace)) {
current.leadingWhitespace = previous;
}
processedTokens.push(current);
}
return processedTokens;
}
tokenizeFormula(text) {
return this.lexer.tokenizeFormula(text);
}
}
/***/ }),
/* 14 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Alternation: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.Alternation),
/* harmony export */ CstParser: () => (/* reexport safe */ _parse_parser_parser__WEBPACK_IMPORTED_MODULE_1__.CstParser),
/* harmony export */ EMPTY_ALT: () => (/* reexport safe */ _parse_parser_parser__WEBPACK_IMPORTED_MODULE_1__.EMPTY_ALT),
/* harmony export */ EOF: () => (/* reexport safe */ _scan_tokens_public__WEBPACK_IMPORTED_MODULE_3__.EOF),
/* harmony export */ EarlyExitException: () => (/* reexport safe */ _parse_exceptions_public__WEBPACK_IMPORTED_MODULE_5__.EarlyExitException),
/* harmony export */ EmbeddedActionsParser: () => (/* reexport safe */ _parse_parser_parser__WEBPACK_IMPORTED_MODULE_1__.EmbeddedActionsParser),
/* harmony export */ Flat: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.Flat),
/* harmony export */ GAstVisitor: () => (/* reexport safe */ _parse_grammar_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_8__.GAstVisitor),
/* harmony export */ Lexer: () => (/* reexport safe */ _scan_lexer_public__WEBPACK_IMPORTED_MODULE_2__.Lexer),
/* harmony export */ LexerDefinitionErrorType: () => (/* reexport safe */ _scan_lexer_public__WEBPACK_IMPORTED_MODULE_2__.LexerDefinitionErrorType),
/* harmony export */ MismatchedTokenException: () => (/* reexport safe */ _parse_exceptions_public__WEBPACK_IMPORTED_MODULE_5__.MismatchedTokenException),
/* harmony export */ NoViableAltException: () => (/* reexport safe */ _parse_exceptions_public__WEBPACK_IMPORTED_MODULE_5__.NoViableAltException),
/* harmony export */ NonTerminal: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.NonTerminal),
/* harmony export */ NotAllInputParsedException: () => (/* reexport safe */ _parse_exceptions_public__WEBPACK_IMPORTED_MODULE_5__.NotAllInputParsedException),
/* harmony export */ Option: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.Option),
/* harmony export */ Parser: () => (/* reexport safe */ _parse_parser_parser__WEBPACK_IMPORTED_MODULE_1__.Parser),
/* harmony export */ ParserDefinitionErrorType: () => (/* reexport safe */ _parse_parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType),
/* harmony export */ Repetition: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.Repetition),
/* harmony export */ RepetitionMandatory: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.RepetitionMandatory),
/* harmony export */ RepetitionMandatoryWithSeparator: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.RepetitionMandatoryWithSeparator),
/* harmony export */ RepetitionWithSeparator: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.RepetitionWithSeparator),
/* harmony export */ Rule: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.Rule),
/* harmony export */ Terminal: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.Terminal),
/* harmony export */ VERSION: () => (/* reexport safe */ _version__WEBPACK_IMPORTED_MODULE_0__.VERSION),
/* harmony export */ assignOccurrenceIndices: () => (/* reexport safe */ _parse_grammar_gast_gast_resolver_public__WEBPACK_IMPORTED_MODULE_9__.assignOccurrenceIndices),
/* harmony export */ clearCache: () => (/* binding */ clearCache),
/* harmony export */ createSyntaxDiagramsCode: () => (/* reexport safe */ _diagrams_render_public__WEBPACK_IMPORTED_MODULE_10__.createSyntaxDiagramsCode),
/* harmony export */ createToken: () => (/* reexport safe */ _scan_tokens_public__WEBPACK_IMPORTED_MODULE_3__.createToken),
/* harmony export */ createTokenInstance: () => (/* reexport safe */ _scan_tokens_public__WEBPACK_IMPORTED_MODULE_3__.createTokenInstance),
/* harmony export */ defaultGrammarResolverErrorProvider: () => (/* reexport safe */ _parse_errors_public__WEBPACK_IMPORTED_MODULE_4__.defaultGrammarResolverErrorProvider),
/* harmony export */ defaultGrammarValidatorErrorProvider: () => (/* reexport safe */ _parse_errors_public__WEBPACK_IMPORTED_MODULE_4__.defaultGrammarValidatorErrorProvider),
/* harmony export */ defaultLexerErrorProvider: () => (/* reexport safe */ _scan_lexer_errors_public__WEBPACK_IMPORTED_MODULE_6__.defaultLexerErrorProvider),
/* harmony export */ defaultParserErrorProvider: () => (/* reexport safe */ _parse_errors_public__WEBPACK_IMPORTED_MODULE_4__.defaultParserErrorProvider),
/* harmony export */ generateParserFactory: () => (/* reexport safe */ _generate_generate_public__WEBPACK_IMPORTED_MODULE_11__.generateParserFactory),
/* harmony export */ generateParserModule: () => (/* reexport safe */ _generate_generate_public__WEBPACK_IMPORTED_MODULE_11__.generateParserModule),
/* harmony export */ isRecognitionException: () => (/* reexport safe */ _parse_exceptions_public__WEBPACK_IMPORTED_MODULE_5__.isRecognitionException),
/* harmony export */ resolveGrammar: () => (/* reexport safe */ _parse_grammar_gast_gast_resolver_public__WEBPACK_IMPORTED_MODULE_9__.resolveGrammar),
/* harmony export */ serializeGrammar: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.serializeGrammar),
/* harmony export */ serializeProduction: () => (/* reexport safe */ _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__.serializeProduction),
/* harmony export */ tokenLabel: () => (/* reexport safe */ _scan_tokens_public__WEBPACK_IMPORTED_MODULE_3__.tokenLabel),
/* harmony export */ tokenMatcher: () => (/* reexport safe */ _scan_tokens_public__WEBPACK_IMPORTED_MODULE_3__.tokenMatcher),
/* harmony export */ tokenName: () => (/* reexport safe */ _scan_tokens_public__WEBPACK_IMPORTED_MODULE_3__.tokenName),
/* harmony export */ validateGrammar: () => (/* reexport safe */ _parse_grammar_gast_gast_resolver_public__WEBPACK_IMPORTED_MODULE_9__.validateGrammar)
/* harmony export */ });
/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15);
/* harmony import */ var _parse_parser_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16);
/* harmony import */ var _scan_lexer_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(22);
/* harmony import */ var _scan_tokens_public__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(21);
/* harmony import */ var _parse_errors_public__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(35);
/* harmony import */ var _parse_exceptions_public__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(42);
/* harmony import */ var _scan_lexer_errors_public__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(28);
/* harmony import */ var _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(20);
/* harmony import */ var _parse_grammar_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(31);
/* harmony import */ var _parse_grammar_gast_gast_resolver_public__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(39);
/* harmony import */ var _diagrams_render_public__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(54);
/* harmony import */ var _generate_generate_public__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(55);
// semantic version
// Tokens utilities
// Other Utilities
// grammar reflection API
// GAST Utilities
/* istanbul ignore next */
function clearCache() {
console.warn("The clearCache function was 'soft' removed from the Chevrotain API." +
"\n\t It performs no action other than printing this message." +
"\n\t Please avoid using it as it will be completely removed in the future");
}
//# sourceMappingURL=api.js.map
/***/ }),
/* 15 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ VERSION: () => (/* binding */ VERSION)
/* harmony export */ });
// needs a separate module as this is required inside chevrotain productive code
// and also in the entry point for webpack(api.ts).
// A separate file avoids cyclic dependencies and webpack errors.
var VERSION = "6.5.0";
//# sourceMappingURL=version.js.map
/***/ }),
/* 16 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CstParser: () => (/* binding */ CstParser),
/* harmony export */ DEFAULT_PARSER_CONFIG: () => (/* binding */ DEFAULT_PARSER_CONFIG),
/* harmony export */ DEFAULT_RULE_CONFIG: () => (/* binding */ DEFAULT_RULE_CONFIG),
/* harmony export */ EMPTY_ALT: () => (/* binding */ EMPTY_ALT),
/* harmony export */ END_OF_FILE: () => (/* binding */ END_OF_FILE),
/* harmony export */ EmbeddedActionsParser: () => (/* binding */ EmbeddedActionsParser),
/* harmony export */ Parser: () => (/* binding */ Parser),
/* harmony export */ ParserDefinitionErrorType: () => (/* binding */ ParserDefinitionErrorType)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _grammar_follow__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(18);
/* harmony import */ var _scan_tokens_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(21);
/* harmony import */ var _cst_cst__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(33);
/* harmony import */ var _errors_public__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(35);
/* harmony import */ var _grammar_gast_gast_resolver_public__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(39);
/* harmony import */ var _traits_recoverable__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(41);
/* harmony import */ var _traits_looksahead__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(43);
/* harmony import */ var _traits_tree_builder__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(44);
/* harmony import */ var _traits_lexer_adapter__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(47);
/* harmony import */ var _traits_recognizer_api__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(48);
/* harmony import */ var _traits_recognizer_engine__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(49);
/* harmony import */ var _traits_error_handler__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(50);
/* harmony import */ var _traits_context_assist__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(51);
/* harmony import */ var _traits_gast_recorder__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(52);
/* harmony import */ var _traits_perf_tracer__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(53);
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var END_OF_FILE = (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_2__.createTokenInstance)(_scan_tokens_public__WEBPACK_IMPORTED_MODULE_2__.EOF, "", NaN, NaN, NaN, NaN, NaN, NaN);
Object.freeze(END_OF_FILE);
var DEFAULT_PARSER_CONFIG = Object.freeze({
recoveryEnabled: false,
maxLookahead: 4,
ignoredIssues: {},
dynamicTokensEnabled: false,
outputCst: true,
errorMessageProvider: _errors_public__WEBPACK_IMPORTED_MODULE_4__.defaultParserErrorProvider,
nodeLocationTracking: "none",
traceInitPerf: false,
skipValidations: false
});
var DEFAULT_RULE_CONFIG = Object.freeze({
recoveryValueFunc: function () { return undefined; },
resyncEnabled: true
});
var ParserDefinitionErrorType;
(function (ParserDefinitionErrorType) {
ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_NAME"] = 0] = "INVALID_RULE_NAME";
ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_RULE_NAME"] = 1] = "DUPLICATE_RULE_NAME";
ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_OVERRIDE"] = 2] = "INVALID_RULE_OVERRIDE";
ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_PRODUCTIONS"] = 3] = "DUPLICATE_PRODUCTIONS";
ParserDefinitionErrorType[ParserDefinitionErrorType["UNRESOLVED_SUBRULE_REF"] = 4] = "UNRESOLVED_SUBRULE_REF";
ParserDefinitionErrorType[ParserDefinitionErrorType["LEFT_RECURSION"] = 5] = "LEFT_RECURSION";
ParserDefinitionErrorType[ParserDefinitionErrorType["NONE_LAST_EMPTY_ALT"] = 6] = "NONE_LAST_EMPTY_ALT";
ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_ALTS"] = 7] = "AMBIGUOUS_ALTS";
ParserDefinitionErrorType[ParserDefinitionErrorType["CONFLICT_TOKENS_RULES_NAMESPACE"] = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE";
ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_TOKEN_NAME"] = 9] = "INVALID_TOKEN_NAME";
ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_NESTED_RULE_NAME"] = 10] = "INVALID_NESTED_RULE_NAME";
ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_NESTED_NAME"] = 11] = "DUPLICATE_NESTED_NAME";
ParserDefinitionErrorType[ParserDefinitionErrorType["NO_NON_EMPTY_LOOKAHEAD"] = 12] = "NO_NON_EMPTY_LOOKAHEAD";
ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_PREFIX_ALTS"] = 13] = "AMBIGUOUS_PREFIX_ALTS";
ParserDefinitionErrorType[ParserDefinitionErrorType["TOO_MANY_ALTS"] = 14] = "TOO_MANY_ALTS";
})(ParserDefinitionErrorType || (ParserDefinitionErrorType = {}));
function EMPTY_ALT(value) {
if (value === void 0) { value = undefined; }
return function () {
return value;
};
}
var Parser = /** @class */ (function () {
function Parser(tokenVocabulary, config) {
if (config === void 0) { config = DEFAULT_PARSER_CONFIG; }
this.ignoredIssues = DEFAULT_PARSER_CONFIG.ignoredIssues;
this.definitionErrors = [];
this.selfAnalysisDone = false;
var that = this;
that.initErrorHandler(config);
that.initLexerAdapter();
that.initLooksAhead(config);
that.initRecognizerEngine(tokenVocabulary, config);
that.initRecoverable(config);
that.initTreeBuilder(config);
that.initContentAssist();
that.initGastRecorder(config);
that.initPerformanceTracer(config);
/* istanbul ignore if - complete over-kill to test this, we should only add a test when we actually hard deprecate it and throw an error... */
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, "ignoredIssues") &&
config.ignoredIssues !== DEFAULT_PARSER_CONFIG.ignoredIssues) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.PRINT_WARNING)("The <ignoredIssues> IParserConfig property is soft-deprecated and will be removed in future versions.\n\t" +
"Please use the <IGNORE_AMBIGUITIES> flag on the relevant DSL method instead.");
}
this.ignoredIssues = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, "ignoredIssues")
? config.ignoredIssues
: DEFAULT_PARSER_CONFIG.ignoredIssues;
this.skipValidations = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, "skipValidations")
? config.skipValidations
: DEFAULT_PARSER_CONFIG.skipValidations;
}
/**
* @deprecated use the **instance** method with the same name instead
*/
Parser.performSelfAnalysis = function (parserInstance) {
;
parserInstance.performSelfAnalysis();
};
Parser.prototype.performSelfAnalysis = function () {
var _this = this;
this.TRACE_INIT("performSelfAnalysis", function () {
var defErrorsMsgs;
_this.selfAnalysisDone = true;
var className = _this.className;
_this.TRACE_INIT("toFastProps", function () {
// Without this voodoo magic the parser would be x3-x4 slower
// It seems it is better to invoke `toFastProperties` **before**
// Any manipulations of the `this` object done during the recording phase.
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.toFastProperties)(_this);
});
_this.TRACE_INIT("Grammar Recording", function () {
try {
_this.enableRecording();
// Building the GAST
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(_this.definedRulesNames, function (currRuleName) {
var wrappedRule = _this[currRuleName];
var originalGrammarAction = wrappedRule["originalGrammarAction"];
var recordedRuleGast = undefined;
_this.TRACE_INIT(currRuleName + " Rule", function () {
recordedRuleGast = _this.topLevelRuleRecord(currRuleName, originalGrammarAction);
});
_this.gastProductionsCache[currRuleName] = recordedRuleGast;
});
}
finally {
_this.disableRecording();
}
});
var resolverErrors = [];
_this.TRACE_INIT("Grammar Resolving", function () {
resolverErrors = (0,_grammar_gast_gast_resolver_public__WEBPACK_IMPORTED_MODULE_5__.resolveGrammar)({
rules: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(_this.gastProductionsCache)
});
_this.definitionErrors.push.apply(_this.definitionErrors, resolverErrors); // mutability for the win?
});
_this.TRACE_INIT("Grammar Validations", function () {
// only perform additional grammar validations IFF no resolving errors have occurred.
// as unresolved grammar may lead to unhandled runtime exceptions in the follow up validations.
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(resolverErrors) && _this.skipValidations === false) {
var validationErrors = (0,_grammar_gast_gast_resolver_public__WEBPACK_IMPORTED_MODULE_5__.validateGrammar)({
rules: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(_this.gastProductionsCache),
maxLookahead: _this.maxLookahead,
tokenTypes: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(_this.tokensMap),
ignoredIssues: _this.ignoredIssues,
errMsgProvider: _errors_public__WEBPACK_IMPORTED_MODULE_4__.defaultGrammarValidatorErrorProvider,
grammarName: className
});
_this.definitionErrors.push.apply(_this.definitionErrors, validationErrors); // mutability for the win?
}
});
// this analysis may fail if the grammar is not perfectly valid
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(_this.definitionErrors)) {
// The results of these computations are not needed unless error recovery is enabled.
if (_this.recoveryEnabled) {
_this.TRACE_INIT("computeAllProdsFollows", function () {
var allFollows = (0,_grammar_follow__WEBPACK_IMPORTED_MODULE_1__.computeAllProdsFollows)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(_this.gastProductionsCache));
_this.resyncFollows = allFollows;
});
}
_this.TRACE_INIT("ComputeLookaheadFunctions", function () {
_this.preComputeLookaheadFunctions((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(_this.gastProductionsCache));
});
}
_this.TRACE_INIT("expandAllNestedRuleNames", function () {
// TODO: is this needed for EmbeddedActionsParser?
var cstAnalysisResult = (0,_cst_cst__WEBPACK_IMPORTED_MODULE_3__.expandAllNestedRuleNames)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(_this.gastProductionsCache), _this.fullRuleNameToShort);
_this.allRuleNames = cstAnalysisResult.allRuleNames;
});
if (!Parser.DEFER_DEFINITION_ERRORS_HANDLING &&
!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(_this.definitionErrors)) {
defErrorsMsgs = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(_this.definitionErrors, function (defError) { return defError.message; });
throw new Error("Parser Definition Errors detected:\n " + defErrorsMsgs.join("\n-------------------------------\n"));
}
});
};
// Set this flag to true if you don't want the Parser to throw error when problems in it's definition are detected.
// (normally during the parser's constructor).
// This is a design time flag, it will not affect the runtime error handling of the parser, just design time errors,
// for example: duplicate rule names, referencing an unresolved subrule, ect...
// This flag should not be enabled during normal usage, it is used in special situations, for example when
// needing to display the parser definition errors in some GUI(online playground).
Parser.DEFER_DEFINITION_ERRORS_HANDLING = false;
return Parser;
}());
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.applyMixins)(Parser, [
_traits_recoverable__WEBPACK_IMPORTED_MODULE_6__.Recoverable,
_traits_looksahead__WEBPACK_IMPORTED_MODULE_7__.LooksAhead,
_traits_tree_builder__WEBPACK_IMPORTED_MODULE_8__.TreeBuilder,
_traits_lexer_adapter__WEBPACK_IMPORTED_MODULE_9__.LexerAdapter,
_traits_recognizer_engine__WEBPACK_IMPORTED_MODULE_11__.RecognizerEngine,
_traits_recognizer_api__WEBPACK_IMPORTED_MODULE_10__.RecognizerApi,
_traits_error_handler__WEBPACK_IMPORTED_MODULE_12__.ErrorHandler,
_traits_context_assist__WEBPACK_IMPORTED_MODULE_13__.ContentAssist,
_traits_gast_recorder__WEBPACK_IMPORTED_MODULE_14__.GastRecorder,
_traits_perf_tracer__WEBPACK_IMPORTED_MODULE_15__.PerformanceTracer
]);
var CstParser = /** @class */ (function (_super) {
__extends(CstParser, _super);
function CstParser(tokenVocabulary, config) {
if (config === void 0) { config = DEFAULT_PARSER_CONFIG; }
var _this = this;
var configClone = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.cloneObj)(config);
configClone.outputCst = true;
_this = _super.call(this, tokenVocabulary, configClone) || this;
return _this;
}
return CstParser;
}(Parser));
var EmbeddedActionsParser = /** @class */ (function (_super) {
__extends(EmbeddedActionsParser, _super);
function EmbeddedActionsParser(tokenVocabulary, config) {
if (config === void 0) { config = DEFAULT_PARSER_CONFIG; }
var _this = this;
var configClone = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.cloneObj)(config);
configClone.outputCst = false;
_this = _super.call(this, tokenVocabulary, configClone) || this;
return _this;
}
return EmbeddedActionsParser;
}(Parser));
//# sourceMappingURL=parser.js.map
/***/ }),
/* 17 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ IDENTITY: () => (/* binding */ IDENTITY),
/* harmony export */ NOOP: () => (/* binding */ NOOP),
/* harmony export */ PRINT_ERROR: () => (/* binding */ PRINT_ERROR),
/* harmony export */ PRINT_WARNING: () => (/* binding */ PRINT_WARNING),
/* harmony export */ applyMixins: () => (/* binding */ applyMixins),
/* harmony export */ assign: () => (/* binding */ assign),
/* harmony export */ assignNoOverwrite: () => (/* binding */ assignNoOverwrite),
/* harmony export */ cloneArr: () => (/* binding */ cloneArr),
/* harmony export */ cloneObj: () => (/* binding */ cloneObj),
/* harmony export */ compact: () => (/* binding */ compact),
/* harmony export */ contains: () => (/* binding */ contains),
/* harmony export */ defaults: () => (/* binding */ defaults),
/* harmony export */ difference: () => (/* binding */ difference),
/* harmony export */ drop: () => (/* binding */ drop),
/* harmony export */ dropRight: () => (/* binding */ dropRight),
/* harmony export */ every: () => (/* binding */ every),
/* harmony export */ filter: () => (/* binding */ filter),
/* harmony export */ find: () => (/* binding */ find),
/* harmony export */ findAll: () => (/* binding */ findAll),
/* harmony export */ first: () => (/* binding */ first),
/* harmony export */ flatten: () => (/* binding */ flatten),
/* harmony export */ forEach: () => (/* binding */ forEach),
/* harmony export */ groupBy: () => (/* binding */ groupBy),
/* harmony export */ has: () => (/* binding */ has),
/* harmony export */ indexOf: () => (/* binding */ indexOf),
/* harmony export */ isArray: () => (/* binding */ isArray),
/* harmony export */ isES2015MapSupported: () => (/* binding */ isES2015MapSupported),
/* harmony export */ isEmpty: () => (/* binding */ isEmpty),
/* harmony export */ isFunction: () => (/* binding */ isFunction),
/* harmony export */ isObject: () => (/* binding */ isObject),
/* harmony export */ isRegExp: () => (/* binding */ isRegExp),
/* harmony export */ isString: () => (/* binding */ isString),
/* harmony export */ isUndefined: () => (/* binding */ isUndefined),
/* harmony export */ keys: () => (/* binding */ keys),
/* harmony export */ last: () => (/* binding */ last),
/* harmony export */ map: () => (/* binding */ map),
/* harmony export */ mapValues: () => (/* binding */ mapValues),
/* harmony export */ merge: () => (/* binding */ merge),
/* harmony export */ packArray: () => (/* binding */ packArray),
/* harmony export */ partial: () => (/* binding */ partial),
/* harmony export */ peek: () => (/* binding */ peek),
/* harmony export */ pick: () => (/* binding */ pick),
/* harmony export */ reduce: () => (/* binding */ reduce),
/* harmony export */ reject: () => (/* binding */ reject),
/* harmony export */ some: () => (/* binding */ some),
/* harmony export */ sortBy: () => (/* binding */ sortBy),
/* harmony export */ timer: () => (/* binding */ timer),
/* harmony export */ toFastProperties: () => (/* binding */ toFastProperties),
/* harmony export */ uniq: () => (/* binding */ uniq),
/* harmony export */ values: () => (/* binding */ values),
/* harmony export */ zipObject: () => (/* binding */ zipObject)
/* harmony export */ });
/*
Utils using lodash style API. (not necessarily 100% compliant) for functional and other utils.
These utils should replace usage of lodash in the production code base. not because they are any better...
but for the purpose of being a dependency free library.
The hotspots in the code are already written in imperative style for performance reasons.
so writing several dozen utils which may be slower than the original lodash, does not matter as much
considering they will not be invoked in hotspots...
*/
function isEmpty(arr) {
return arr && arr.length === 0;
}
function keys(obj) {
if (obj === undefined || obj === null) {
return [];
}
return Object.keys(obj);
}
function values(obj) {
var vals = [];
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; i++) {
vals.push(obj[keys[i]]);
}
return vals;
}
function mapValues(obj, callback) {
var result = [];
var objKeys = keys(obj);
for (var idx = 0; idx < objKeys.length; idx++) {
var currKey = objKeys[idx];
result.push(callback.call(null, obj[currKey], currKey));
}
return result;
}
function map(arr, callback) {
var result = [];
for (var idx = 0; idx < arr.length; idx++) {
result.push(callback.call(null, arr[idx], idx));
}
return result;
}
function flatten(arr) {
var result = [];
for (var idx = 0; idx < arr.length; idx++) {
var currItem = arr[idx];
if (Array.isArray(currItem)) {
result = result.concat(flatten(currItem));
}
else {
result.push(currItem);
}
}
return result;
}
function first(arr) {
return isEmpty(arr) ? undefined : arr[0];
}
function last(arr) {
var len = arr && arr.length;
return len ? arr[len - 1] : undefined;
}
function forEach(collection, iteratorCallback) {
/* istanbul ignore else */
if (Array.isArray(collection)) {
for (var i = 0; i < collection.length; i++) {
iteratorCallback.call(null, collection[i], i);
}
}
else if (isObject(collection)) {
var colKeys = keys(collection);
for (var i = 0; i < colKeys.length; i++) {
var key = colKeys[i];
var value = collection[key];
iteratorCallback.call(null, value, key);
}
}
else {
throw Error("non exhaustive match");
}
}
function isString(item) {
return typeof item === "string";
}
function isUndefined(item) {
return item === undefined;
}
function isFunction(item) {
return item instanceof Function;
}
function drop(arr, howMuch) {
if (howMuch === void 0) { howMuch = 1; }
return arr.slice(howMuch, arr.length);
}
function dropRight(arr, howMuch) {
if (howMuch === void 0) { howMuch = 1; }
return arr.slice(0, arr.length - howMuch);
}
function filter(arr, predicate) {
var result = [];
if (Array.isArray(arr)) {
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (predicate.call(null, item)) {
result.push(item);
}
}
}
return result;
}
function reject(arr, predicate) {
return filter(arr, function (item) { return !predicate(item); });
}
function pick(obj, predicate) {
var keys = Object.keys(obj);
var result = {};
for (var i = 0; i < keys.length; i++) {
var currKey = keys[i];
var currItem = obj[currKey];
if (predicate(currItem)) {
result[currKey] = currItem;
}
}
return result;
}
function has(obj, prop) {
if (isObject(obj)) {
return obj.hasOwnProperty(prop);
}
return false;
}
function contains(arr, item) {
return find(arr, function (currItem) { return currItem === item; }) !== undefined ? true : false;
}
/**
* shallow clone
*/
function cloneArr(arr) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr.push(arr[i]);
}
return newArr;
}
/**
* shallow clone
*/
function cloneObj(obj) {
var clonedObj = {};
for (var key in obj) {
/* istanbul ignore else */
if (Object.prototype.hasOwnProperty.call(obj, key)) {
clonedObj[key] = obj[key];
}
}
return clonedObj;
}
function find(arr, predicate) {
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (predicate.call(null, item)) {
return item;
}
}
return undefined;
}
function findAll(arr, predicate) {
var found = [];
for (var i = 0; i < arr.length; i++) {
var item = arr[i];
if (predicate.call(null, item)) {
found.push(item);
}
}
return found;
}
function reduce(arrOrObj, iterator, initial) {
var isArr = Array.isArray(arrOrObj);
var vals = isArr ? arrOrObj : values(arrOrObj);
var objKeys = isArr ? [] : keys(arrOrObj);
var accumulator = initial;
for (var i = 0; i < vals.length; i++) {
accumulator = iterator.call(null, accumulator, vals[i], isArr ? i : objKeys[i]);
}
return accumulator;
}
function compact(arr) {
return reject(arr, function (item) { return item === null || item === undefined; });
}
function uniq(arr, identity) {
if (identity === void 0) { identity = function (item) { return item; }; }
var identities = [];
return reduce(arr, function (result, currItem) {
var currIdentity = identity(currItem);
if (contains(identities, currIdentity)) {
return result;
}
else {
identities.push(currIdentity);
return result.concat(currItem);
}
}, []);
}
function partial(func) {
var restArgs = [];
for (var _i = 1; _i < arguments.length; _i++) {
restArgs[_i - 1] = arguments[_i];
}
var firstArg = [null];
var allArgs = firstArg.concat(restArgs);
return Function.bind.apply(func, allArgs);
}
function isArray(obj) {
return Array.isArray(obj);
}
function isRegExp(obj) {
return obj instanceof RegExp;
}
function isObject(obj) {
return obj instanceof Object;
}
function every(arr, predicate) {
for (var i = 0; i < arr.length; i++) {
if (!predicate(arr[i], i)) {
return false;
}
}
return true;
}
function difference(arr, values) {
return reject(arr, function (item) { return contains(values, item); });
}
function some(arr, predicate) {
for (var i = 0; i < arr.length; i++) {
if (predicate(arr[i])) {
return true;
}
}
return false;
}
function indexOf(arr, value) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === value) {
return i;
}
}
return -1;
}
function sortBy(arr, orderFunc) {
var result = cloneArr(arr);
result.sort(function (a, b) { return orderFunc(a) - orderFunc(b); });
return result;
}
function zipObject(keys, values) {
if (keys.length !== values.length) {
throw Error("can't zipObject with different number of keys and values!");
}
var result = {};
for (var i = 0; i < keys.length; i++) {
result[keys[i]] = values[i];
}
return result;
}
/**
* mutates! (and returns) target
*/
function assign(target) {
var sources = [];
for (var _i = 1; _i < arguments.length; _i++) {
sources[_i - 1] = arguments[_i];
}
for (var i = 0; i < sources.length; i++) {
var curSource = sources[i];
var currSourceKeys = keys(curSource);
for (var j = 0; j < currSourceKeys.length; j++) {
var currKey = currSourceKeys[j];
target[currKey] = curSource[currKey];
}
}
return target;
}
/**
* mutates! (and returns) target
*/
function assignNoOverwrite(target) {
var sources = [];
for (var _i = 1; _i < arguments.length; _i++) {
sources[_i - 1] = arguments[_i];
}
for (var i = 0; i < sources.length; i++) {
var curSource = sources[i];
if (isUndefined(curSource)) {
continue;
}
var currSourceKeys = keys(curSource);
for (var j = 0; j < currSourceKeys.length; j++) {
var currKey = currSourceKeys[j];
if (!has(target, currKey)) {
target[currKey] = curSource[currKey];
}
}
}
return target;
}
function defaults() {
var sources = [];
for (var _i = 0; _i < arguments.length; _i++) {
sources[_i] = arguments[_i];
}
return assignNoOverwrite.apply(null, [{}].concat(sources));
}
function groupBy(arr, groupKeyFunc) {
var result = {};
forEach(arr, function (item) {
var currGroupKey = groupKeyFunc(item);
var currGroupArr = result[currGroupKey];
if (currGroupArr) {
currGroupArr.push(item);
}
else {
result[currGroupKey] = [item];
}
});
return result;
}
/**
* Merge obj2 into obj1.
* Will overwrite existing properties with the same name
*/
function merge(obj1, obj2) {
var result = cloneObj(obj1);
var keys2 = keys(obj2);
for (var i = 0; i < keys2.length; i++) {
var key = keys2[i];
var value = obj2[key];
result[key] = value;
}
return result;
}
function NOOP() { }
function IDENTITY(item) {
return item;
}
/**
* Will return a new packed array with same values.
*/
function packArray(holeyArr) {
var result = [];
for (var i = 0; i < holeyArr.length; i++) {
var orgValue = holeyArr[i];
result.push(orgValue !== undefined ? orgValue : undefined);
}
return result;
}
function PRINT_ERROR(msg) {
/* istanbul ignore else - can't override global.console in node.js */
if (console && console.error) {
console.error("Error: " + msg);
}
}
function PRINT_WARNING(msg) {
/* istanbul ignore else - can't override global.console in node.js*/
if (console && console.warn) {
// TODO: modify docs accordingly
console.warn("Warning: " + msg);
}
}
function isES2015MapSupported() {
return typeof Map === "function";
}
function applyMixins(derivedCtor, baseCtors) {
baseCtors.forEach(function (baseCtor) {
var baseProto = baseCtor.prototype;
Object.getOwnPropertyNames(baseProto).forEach(function (propName) {
if (propName === "constructor") {
return;
}
var basePropDescriptor = Object.getOwnPropertyDescriptor(baseProto, propName);
// Handle Accessors
if (basePropDescriptor &&
(basePropDescriptor.get || basePropDescriptor.set)) {
Object.defineProperty(derivedCtor.prototype, propName, basePropDescriptor);
}
else {
derivedCtor.prototype[propName] = baseCtor.prototype[propName];
}
});
});
}
// base on: https://github.com/petkaantonov/bluebird/blob/b97c0d2d487e8c5076e8bd897e0dcd4622d31846/src/util.js#L201-L216
function toFastProperties(toBecomeFast) {
function FakeConstructor() { }
// If our object is used as a constructor it would receive
FakeConstructor.prototype = toBecomeFast;
var fakeInstance = new FakeConstructor();
function fakeAccess() {
return typeof fakeInstance.bar;
}
// help V8 understand this is a "real" prototype by actually using
// the fake instance.
fakeAccess();
fakeAccess();
return toBecomeFast;
// Eval prevents optimization of this method (even though this is dead code)
/* istanbul ignore next */
// tslint:disable-next-line
eval(toBecomeFast);
}
function peek(arr) {
return arr[arr.length - 1];
}
/* istanbul ignore next - for performance tracing*/
function timer(func) {
var start = new Date().getTime();
var val = func();
var end = new Date().getTime();
var total = end - start;
return { time: total, value: val };
}
//# sourceMappingURL=utils.js.map
/***/ }),
/* 18 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ResyncFollowsWalker: () => (/* binding */ ResyncFollowsWalker),
/* harmony export */ buildBetweenProdsFollowPrefix: () => (/* binding */ buildBetweenProdsFollowPrefix),
/* harmony export */ buildInProdFollowPrefix: () => (/* binding */ buildInProdFollowPrefix),
/* harmony export */ computeAllProdsFollows: () => (/* binding */ computeAllProdsFollows)
/* harmony export */ });
/* harmony import */ var _rest__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(19);
/* harmony import */ var _first__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(29);
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(17);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(32);
/* harmony import */ var _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20);
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
// This ResyncFollowsWalker computes all of the follows required for RESYNC
// (skipping reference production).
var ResyncFollowsWalker = /** @class */ (function (_super) {
__extends(ResyncFollowsWalker, _super);
function ResyncFollowsWalker(topProd) {
var _this = _super.call(this) || this;
_this.topProd = topProd;
_this.follows = {};
return _this;
}
ResyncFollowsWalker.prototype.startWalking = function () {
this.walk(this.topProd);
return this.follows;
};
ResyncFollowsWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) {
// do nothing! just like in the public sector after 13:00
};
ResyncFollowsWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) {
var followName = buildBetweenProdsFollowPrefix(refProd.referencedRule, refProd.idx) +
this.topProd.name;
var fullRest = currRest.concat(prevRest);
var restProd = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.Flat({ definition: fullRest });
var t_in_topProd_follows = (0,_first__WEBPACK_IMPORTED_MODULE_1__.first)(restProd);
this.follows[followName] = t_in_topProd_follows;
};
return ResyncFollowsWalker;
}(_rest__WEBPACK_IMPORTED_MODULE_0__.RestWalker));
function computeAllProdsFollows(topProductions) {
var reSyncFollows = {};
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(topProductions, function (topProd) {
var currRefsFollow = new ResyncFollowsWalker(topProd).startWalking();
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.assign)(reSyncFollows, currRefsFollow);
});
return reSyncFollows;
}
function buildBetweenProdsFollowPrefix(inner, occurenceInParent) {
return inner.name + occurenceInParent + _constants__WEBPACK_IMPORTED_MODULE_3__.IN;
}
function buildInProdFollowPrefix(terminal) {
var terminalName = terminal.terminalType.name;
return terminalName + terminal.idx + _constants__WEBPACK_IMPORTED_MODULE_3__.IN;
}
//# sourceMappingURL=follow.js.map
/***/ }),
/* 19 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ RestWalker: () => (/* binding */ RestWalker)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20);
/**
* A Grammar Walker that computes the "remaining" grammar "after" a productions in the grammar.
*/
var RestWalker = /** @class */ (function () {
function RestWalker() {
}
RestWalker.prototype.walk = function (prod, prevRest) {
var _this = this;
if (prevRest === void 0) { prevRest = []; }
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(prod.definition, function (subProd, index) {
var currRest = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.drop)(prod.definition, index + 1);
/* istanbul ignore else */
if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.NonTerminal) {
_this.walkProdRef(subProd, currRest, prevRest);
}
else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Terminal) {
_this.walkTerminal(subProd, currRest, prevRest);
}
else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Flat) {
_this.walkFlat(subProd, currRest, prevRest);
}
else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Option) {
_this.walkOption(subProd, currRest, prevRest);
}
else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatory) {
_this.walkAtLeastOne(subProd, currRest, prevRest);
}
else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatoryWithSeparator) {
_this.walkAtLeastOneSep(subProd, currRest, prevRest);
}
else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionWithSeparator) {
_this.walkManySep(subProd, currRest, prevRest);
}
else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Repetition) {
_this.walkMany(subProd, currRest, prevRest);
}
else if (subProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Alternation) {
_this.walkOr(subProd, currRest, prevRest);
}
else {
throw Error("non exhaustive match");
}
});
};
RestWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { };
RestWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { };
RestWalker.prototype.walkFlat = function (flatProd, currRest, prevRest) {
// ABCDEF => after the D the rest is EF
var fullOrRest = currRest.concat(prevRest);
this.walk(flatProd, fullOrRest);
};
RestWalker.prototype.walkOption = function (optionProd, currRest, prevRest) {
// ABC(DE)?F => after the (DE)? the rest is F
var fullOrRest = currRest.concat(prevRest);
this.walk(optionProd, fullOrRest);
};
RestWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) {
// ABC(DE)+F => after the (DE)+ the rest is (DE)?F
var fullAtLeastOneRest = [
new _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Option({ definition: atLeastOneProd.definition })
].concat(currRest, prevRest);
this.walk(atLeastOneProd, fullAtLeastOneRest);
};
RestWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) {
// ABC DE(,DE)* F => after the (,DE)+ the rest is (,DE)?F
var fullAtLeastOneSepRest = restForRepetitionWithSeparator(atLeastOneSepProd, currRest, prevRest);
this.walk(atLeastOneSepProd, fullAtLeastOneSepRest);
};
RestWalker.prototype.walkMany = function (manyProd, currRest, prevRest) {
// ABC(DE)*F => after the (DE)* the rest is (DE)?F
var fullManyRest = [
new _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Option({ definition: manyProd.definition })
].concat(currRest, prevRest);
this.walk(manyProd, fullManyRest);
};
RestWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) {
// ABC (DE(,DE)*)? F => after the (,DE)* the rest is (,DE)?F
var fullManySepRest = restForRepetitionWithSeparator(manySepProd, currRest, prevRest);
this.walk(manySepProd, fullManySepRest);
};
RestWalker.prototype.walkOr = function (orProd, currRest, prevRest) {
var _this = this;
// ABC(D|E|F)G => when finding the (D|E|F) the rest is G
var fullOrRest = currRest.concat(prevRest);
// walk all different alternatives
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(orProd.definition, function (alt) {
// wrapping each alternative in a single definition wrapper
// to avoid errors in computing the rest of that alternative in the invocation to computeInProdFollows
// (otherwise for OR([alt1,alt2]) alt2 will be considered in 'rest' of alt1
var prodWrapper = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Flat({ definition: [alt] });
_this.walk(prodWrapper, fullOrRest);
});
};
return RestWalker;
}());
function restForRepetitionWithSeparator(repSepProd, currRest, prevRest) {
var repSepRest = [
new _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Option({
definition: [
new _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Terminal({ terminalType: repSepProd.separator })
].concat(repSepProd.definition)
})
];
var fullRepSepRest = repSepRest.concat(currRest, prevRest);
return fullRepSepRest;
}
//# sourceMappingURL=rest.js.map
/***/ }),
/* 20 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AbstractProduction: () => (/* binding */ AbstractProduction),
/* harmony export */ Alternation: () => (/* binding */ Alternation),
/* harmony export */ Flat: () => (/* binding */ Flat),
/* harmony export */ NonTerminal: () => (/* binding */ NonTerminal),
/* harmony export */ Option: () => (/* binding */ Option),
/* harmony export */ Repetition: () => (/* binding */ Repetition),
/* harmony export */ RepetitionMandatory: () => (/* binding */ RepetitionMandatory),
/* harmony export */ RepetitionMandatoryWithSeparator: () => (/* binding */ RepetitionMandatoryWithSeparator),
/* harmony export */ RepetitionWithSeparator: () => (/* binding */ RepetitionWithSeparator),
/* harmony export */ Rule: () => (/* binding */ Rule),
/* harmony export */ Terminal: () => (/* binding */ Terminal),
/* harmony export */ serializeGrammar: () => (/* binding */ serializeGrammar),
/* harmony export */ serializeProduction: () => (/* binding */ serializeProduction)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _scan_tokens_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(21);
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var AbstractProduction = /** @class */ (function () {
function AbstractProduction(definition) {
this.definition = definition;
}
AbstractProduction.prototype.accept = function (visitor) {
visitor.visit(this);
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(this.definition, function (prod) {
prod.accept(visitor);
});
};
return AbstractProduction;
}());
var NonTerminal = /** @class */ (function (_super) {
__extends(NonTerminal, _super);
function NonTerminal(options) {
var _this = _super.call(this, []) || this;
_this.idx = 1;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; }));
return _this;
}
Object.defineProperty(NonTerminal.prototype, "definition", {
get: function () {
if (this.referencedRule !== undefined) {
return this.referencedRule.definition;
}
return [];
},
set: function (definition) {
// immutable
},
enumerable: true,
configurable: true
});
NonTerminal.prototype.accept = function (visitor) {
visitor.visit(this);
// don't visit children of a reference, we will get cyclic infinite loops if we do so
};
return NonTerminal;
}(AbstractProduction));
var Rule = /** @class */ (function (_super) {
__extends(Rule, _super);
function Rule(options) {
var _this = _super.call(this, options.definition) || this;
_this.orgText = "";
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; }));
return _this;
}
return Rule;
}(AbstractProduction));
// TODO: is this only used in an Alternation?
// Perhaps `Flat` should be renamed to `Alternative`?
var Flat = /** @class */ (function (_super) {
__extends(Flat, _super);
// A named Flat production is used to indicate a Nested Rule in an alternation
function Flat(options) {
var _this = _super.call(this, options.definition) || this;
_this.ignoreAmbiguities = false;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; }));
return _this;
}
return Flat;
}(AbstractProduction));
var Option = /** @class */ (function (_super) {
__extends(Option, _super);
function Option(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; }));
return _this;
}
return Option;
}(AbstractProduction));
var RepetitionMandatory = /** @class */ (function (_super) {
__extends(RepetitionMandatory, _super);
function RepetitionMandatory(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; }));
return _this;
}
return RepetitionMandatory;
}(AbstractProduction));
var RepetitionMandatoryWithSeparator = /** @class */ (function (_super) {
__extends(RepetitionMandatoryWithSeparator, _super);
function RepetitionMandatoryWithSeparator(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; }));
return _this;
}
return RepetitionMandatoryWithSeparator;
}(AbstractProduction));
var Repetition = /** @class */ (function (_super) {
__extends(Repetition, _super);
function Repetition(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; }));
return _this;
}
return Repetition;
}(AbstractProduction));
var RepetitionWithSeparator = /** @class */ (function (_super) {
__extends(RepetitionWithSeparator, _super);
function RepetitionWithSeparator(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; }));
return _this;
}
return RepetitionWithSeparator;
}(AbstractProduction));
var Alternation = /** @class */ (function (_super) {
__extends(Alternation, _super);
function Alternation(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
_this.ignoreAmbiguities = false;
_this.hasPredicates = false;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(_this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; }));
return _this;
}
return Alternation;
}(AbstractProduction));
var Terminal = /** @class */ (function () {
function Terminal(options) {
this.idx = 1;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.assign)(this, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(options, function (v) { return v !== undefined; }));
}
Terminal.prototype.accept = function (visitor) {
visitor.visit(this);
};
return Terminal;
}());
function serializeGrammar(topRules) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(topRules, serializeProduction);
}
function serializeProduction(node) {
function convertDefinition(definition) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(definition, serializeProduction);
}
/* istanbul ignore else */
if (node instanceof NonTerminal) {
return {
type: "NonTerminal",
name: node.nonTerminalName,
idx: node.idx
};
}
else if (node instanceof Flat) {
return {
type: "Flat",
definition: convertDefinition(node.definition)
};
}
else if (node instanceof Option) {
return {
type: "Option",
idx: node.idx,
definition: convertDefinition(node.definition)
};
}
else if (node instanceof RepetitionMandatory) {
return {
type: "RepetitionMandatory",
name: node.name,
idx: node.idx,
definition: convertDefinition(node.definition)
};
}
else if (node instanceof RepetitionMandatoryWithSeparator) {
return {
type: "RepetitionMandatoryWithSeparator",
name: node.name,
idx: node.idx,
separator: (serializeProduction(new Terminal({ terminalType: node.separator }))),
definition: convertDefinition(node.definition)
};
}
else if (node instanceof RepetitionWithSeparator) {
return {
type: "RepetitionWithSeparator",
name: node.name,
idx: node.idx,
separator: (serializeProduction(new Terminal({ terminalType: node.separator }))),
definition: convertDefinition(node.definition)
};
}
else if (node instanceof Repetition) {
return {
type: "Repetition",
name: node.name,
idx: node.idx,
definition: convertDefinition(node.definition)
};
}
else if (node instanceof Alternation) {
return {
type: "Alternation",
name: node.name,
idx: node.idx,
definition: convertDefinition(node.definition)
};
}
else if (node instanceof Terminal) {
var serializedTerminal = {
type: "Terminal",
name: node.terminalType.name,
label: (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_1__.tokenLabel)(node.terminalType),
idx: node.idx
};
var pattern = node.terminalType.PATTERN;
if (node.terminalType.PATTERN) {
serializedTerminal.pattern = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isRegExp)(pattern)
? pattern.source
: pattern;
}
return serializedTerminal;
}
else if (node instanceof Rule) {
return {
type: "Rule",
name: node.name,
orgText: node.orgText,
definition: convertDefinition(node.definition)
};
}
else {
throw Error("non exhaustive match");
}
}
//# sourceMappingURL=gast_public.js.map
/***/ }),
/* 21 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ EOF: () => (/* binding */ EOF),
/* harmony export */ createToken: () => (/* binding */ createToken),
/* harmony export */ createTokenInstance: () => (/* binding */ createTokenInstance),
/* harmony export */ hasTokenLabel: () => (/* binding */ hasTokenLabel),
/* harmony export */ tokenLabel: () => (/* binding */ tokenLabel),
/* harmony export */ tokenMatcher: () => (/* binding */ tokenMatcher),
/* harmony export */ tokenName: () => (/* binding */ tokenName)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _lexer_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(22);
/* harmony import */ var _tokens__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(27);
function tokenLabel(tokType) {
if (hasTokenLabel(tokType)) {
return tokType.LABEL;
}
else {
return tokType.name;
}
}
function tokenName(tokType) {
return tokType.name;
}
function hasTokenLabel(obj) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isString)(obj.LABEL) && obj.LABEL !== "";
}
var PARENT = "parent";
var CATEGORIES = "categories";
var LABEL = "label";
var GROUP = "group";
var PUSH_MODE = "push_mode";
var POP_MODE = "pop_mode";
var LONGER_ALT = "longer_alt";
var LINE_BREAKS = "line_breaks";
var START_CHARS_HINT = "start_chars_hint";
function createToken(config) {
return createTokenInternal(config);
}
function createTokenInternal(config) {
var pattern = config.pattern;
var tokenType = {};
tokenType.name = config.name;
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(pattern)) {
tokenType.PATTERN = pattern;
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, PARENT)) {
throw "The parent property is no longer supported.\n" +
"See: https://github.com/SAP/chevrotain/issues/564#issuecomment-349062346 for details.";
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, CATEGORIES)) {
// casting to ANY as this will be fixed inside `augmentTokenTypes``
tokenType.CATEGORIES = config[CATEGORIES];
}
(0,_tokens__WEBPACK_IMPORTED_MODULE_2__.augmentTokenTypes)([tokenType]);
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, LABEL)) {
tokenType.LABEL = config[LABEL];
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, GROUP)) {
tokenType.GROUP = config[GROUP];
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, POP_MODE)) {
tokenType.POP_MODE = config[POP_MODE];
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, PUSH_MODE)) {
tokenType.PUSH_MODE = config[PUSH_MODE];
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, LONGER_ALT)) {
tokenType.LONGER_ALT = config[LONGER_ALT];
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, LINE_BREAKS)) {
tokenType.LINE_BREAKS = config[LINE_BREAKS];
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, START_CHARS_HINT)) {
tokenType.START_CHARS_HINT = config[START_CHARS_HINT];
}
return tokenType;
}
var EOF = createToken({ name: "EOF", pattern: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.NA });
(0,_tokens__WEBPACK_IMPORTED_MODULE_2__.augmentTokenTypes)([EOF]);
function createTokenInstance(tokType, image, startOffset, endOffset, startLine, endLine, startColumn, endColumn) {
return {
image: image,
startOffset: startOffset,
endOffset: endOffset,
startLine: startLine,
endLine: endLine,
startColumn: startColumn,
endColumn: endColumn,
tokenTypeIdx: tokType.tokenTypeIdx,
tokenType: tokType
};
}
function tokenMatcher(token, tokType) {
return (0,_tokens__WEBPACK_IMPORTED_MODULE_2__.tokenStructuredMatcher)(token, tokType);
}
//# sourceMappingURL=tokens_public.js.map
/***/ }),
/* 22 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Lexer: () => (/* binding */ Lexer),
/* harmony export */ LexerDefinitionErrorType: () => (/* binding */ LexerDefinitionErrorType)
/* harmony export */ });
/* harmony import */ var _lexer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(23);
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17);
/* harmony import */ var _tokens__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(27);
/* harmony import */ var _scan_lexer_errors_public__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(28);
/* harmony import */ var _reg_exp_parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(26);
var LexerDefinitionErrorType;
(function (LexerDefinitionErrorType) {
LexerDefinitionErrorType[LexerDefinitionErrorType["MISSING_PATTERN"] = 0] = "MISSING_PATTERN";
LexerDefinitionErrorType[LexerDefinitionErrorType["INVALID_PATTERN"] = 1] = "INVALID_PATTERN";
LexerDefinitionErrorType[LexerDefinitionErrorType["EOI_ANCHOR_FOUND"] = 2] = "EOI_ANCHOR_FOUND";
LexerDefinitionErrorType[LexerDefinitionErrorType["UNSUPPORTED_FLAGS_FOUND"] = 3] = "UNSUPPORTED_FLAGS_FOUND";
LexerDefinitionErrorType[LexerDefinitionErrorType["DUPLICATE_PATTERNS_FOUND"] = 4] = "DUPLICATE_PATTERNS_FOUND";
LexerDefinitionErrorType[LexerDefinitionErrorType["INVALID_GROUP_TYPE_FOUND"] = 5] = "INVALID_GROUP_TYPE_FOUND";
LexerDefinitionErrorType[LexerDefinitionErrorType["PUSH_MODE_DOES_NOT_EXIST"] = 6] = "PUSH_MODE_DOES_NOT_EXIST";
LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE"] = 7] = "MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE";
LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY"] = 8] = "MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY";
LexerDefinitionErrorType[LexerDefinitionErrorType["MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST"] = 9] = "MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST";
LexerDefinitionErrorType[LexerDefinitionErrorType["LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED"] = 10] = "LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED";
LexerDefinitionErrorType[LexerDefinitionErrorType["SOI_ANCHOR_FOUND"] = 11] = "SOI_ANCHOR_FOUND";
LexerDefinitionErrorType[LexerDefinitionErrorType["EMPTY_MATCH_PATTERN"] = 12] = "EMPTY_MATCH_PATTERN";
LexerDefinitionErrorType[LexerDefinitionErrorType["NO_LINE_BREAKS_FLAGS"] = 13] = "NO_LINE_BREAKS_FLAGS";
LexerDefinitionErrorType[LexerDefinitionErrorType["UNREACHABLE_PATTERN"] = 14] = "UNREACHABLE_PATTERN";
LexerDefinitionErrorType[LexerDefinitionErrorType["IDENTIFY_TERMINATOR"] = 15] = "IDENTIFY_TERMINATOR";
LexerDefinitionErrorType[LexerDefinitionErrorType["CUSTOM_LINE_BREAK"] = 16] = "CUSTOM_LINE_BREAK";
})(LexerDefinitionErrorType || (LexerDefinitionErrorType = {}));
var DEFAULT_LEXER_CONFIG = {
deferDefinitionErrorsHandling: false,
positionTracking: "full",
lineTerminatorsPattern: /\n|\r\n?/g,
lineTerminatorCharacters: ["\n", "\r"],
ensureOptimizations: false,
safeMode: false,
errorMessageProvider: _scan_lexer_errors_public__WEBPACK_IMPORTED_MODULE_3__.defaultLexerErrorProvider,
traceInitPerf: false,
skipValidations: false
};
Object.freeze(DEFAULT_LEXER_CONFIG);
var Lexer = /** @class */ (function () {
function Lexer(lexerDefinition, config) {
var _this = this;
if (config === void 0) { config = DEFAULT_LEXER_CONFIG; }
this.lexerDefinition = lexerDefinition;
this.lexerDefinitionErrors = [];
this.lexerDefinitionWarning = [];
this.patternIdxToConfig = {};
this.charCodeToPatternIdxToConfig = {};
this.modes = [];
this.emptyGroups = {};
this.config = undefined;
this.trackStartLines = true;
this.trackEndLines = true;
this.hasCustom = false;
this.canModeBeOptimized = {};
if (typeof config === "boolean") {
throw Error("The second argument to the Lexer constructor is now an ILexerConfig Object.\n" +
"a boolean 2nd argument is no longer supported");
}
// todo: defaults func?
this.config = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.merge)(DEFAULT_LEXER_CONFIG, config);
var traceInitVal = this.config.traceInitPerf;
if (traceInitVal === true) {
this.traceInitMaxIdent = Infinity;
this.traceInitPerf = true;
}
else if (typeof traceInitVal === "number") {
this.traceInitMaxIdent = traceInitVal;
this.traceInitPerf = true;
}
this.traceInitIndent = -1;
this.TRACE_INIT("Lexer Constructor", function () {
var actualDefinition;
var hasOnlySingleMode = true;
_this.TRACE_INIT("Lexer Config handling", function () {
if (_this.config.lineTerminatorsPattern ===
DEFAULT_LEXER_CONFIG.lineTerminatorsPattern) {
// optimized built-in implementation for the defaults definition of lineTerminators
_this.config.lineTerminatorsPattern = _lexer__WEBPACK_IMPORTED_MODULE_0__.LineTerminatorOptimizedTester;
}
else {
if (_this.config.lineTerminatorCharacters ===
DEFAULT_LEXER_CONFIG.lineTerminatorCharacters) {
throw Error("Error: Missing <lineTerminatorCharacters> property on the Lexer config.\n" +
"\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS");
}
}
if (config.safeMode && config.ensureOptimizations) {
throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');
}
_this.trackStartLines = /full|onlyStart/i.test(_this.config.positionTracking);
_this.trackEndLines = /full/i.test(_this.config.positionTracking);
// Convert SingleModeLexerDefinition into a IMultiModeLexerDefinition.
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isArray)(lexerDefinition)) {
actualDefinition = { modes: {} };
actualDefinition.modes[_lexer__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_MODE] = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(lexerDefinition);
actualDefinition[_lexer__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_MODE] = _lexer__WEBPACK_IMPORTED_MODULE_0__.DEFAULT_MODE;
}
else {
// no conversion needed, input should already be a IMultiModeLexerDefinition
hasOnlySingleMode = false;
actualDefinition = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneObj)((lexerDefinition));
}
});
if (_this.config.skipValidations === false) {
_this.TRACE_INIT("performRuntimeChecks", function () {
_this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat((0,_lexer__WEBPACK_IMPORTED_MODULE_0__.performRuntimeChecks)(actualDefinition, _this.trackStartLines, _this.config.lineTerminatorCharacters));
});
_this.TRACE_INIT("performWarningRuntimeChecks", function () {
_this.lexerDefinitionWarning = _this.lexerDefinitionWarning.concat((0,_lexer__WEBPACK_IMPORTED_MODULE_0__.performWarningRuntimeChecks)(actualDefinition, _this.trackStartLines, _this.config.lineTerminatorCharacters));
});
}
// for extra robustness to avoid throwing an none informative error message
actualDefinition.modes = actualDefinition.modes
? actualDefinition.modes
: {};
// an error of undefined TokenTypes will be detected in "performRuntimeChecks" above.
// this transformation is to increase robustness in the case of partially invalid lexer definition.
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(actualDefinition.modes, function (currModeValue, currModeName) {
actualDefinition.modes[currModeName] = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.reject)(currModeValue, function (currTokType) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isUndefined)(currTokType); });
});
var allModeNames = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.keys)(actualDefinition.modes);
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(actualDefinition.modes, function (currModDef, currModName) {
_this.TRACE_INIT("Mode: <" + currModName + "> processing", function () {
_this.modes.push(currModName);
if (_this.config.skipValidations === false) {
_this.TRACE_INIT("validatePatterns", function () {
_this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat((0,_lexer__WEBPACK_IMPORTED_MODULE_0__.validatePatterns)(currModDef, allModeNames));
});
}
// If definition errors were encountered, the analysis phase may fail unexpectedly/
// Considering a lexer with definition errors may never be used, there is no point
// to performing the analysis anyhow...
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(_this.lexerDefinitionErrors)) {
(0,_tokens__WEBPACK_IMPORTED_MODULE_2__.augmentTokenTypes)(currModDef);
var currAnalyzeResult_1;
_this.TRACE_INIT("analyzeTokenTypes", function () {
currAnalyzeResult_1 = (0,_lexer__WEBPACK_IMPORTED_MODULE_0__.analyzeTokenTypes)(currModDef, {
lineTerminatorCharacters: _this.config
.lineTerminatorCharacters,
positionTracking: config.positionTracking,
ensureOptimizations: config.ensureOptimizations,
safeMode: config.safeMode,
tracer: _this.TRACE_INIT.bind(_this)
});
});
_this.patternIdxToConfig[currModName] =
currAnalyzeResult_1.patternIdxToConfig;
_this.charCodeToPatternIdxToConfig[currModName] =
currAnalyzeResult_1.charCodeToPatternIdxToConfig;
_this.emptyGroups = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.merge)(_this.emptyGroups, currAnalyzeResult_1.emptyGroups);
_this.hasCustom =
currAnalyzeResult_1.hasCustom || _this.hasCustom;
_this.canModeBeOptimized[currModName] =
currAnalyzeResult_1.canBeOptimized;
}
});
});
_this.defaultMode = actualDefinition.defaultMode;
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(_this.lexerDefinitionErrors) &&
!_this.config.deferDefinitionErrorsHandling) {
var allErrMessages = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(_this.lexerDefinitionErrors, function (error) {
return error.message;
});
var allErrMessagesString = allErrMessages.join("-----------------------\n");
throw new Error("Errors detected in definition of Lexer:\n" +
allErrMessagesString);
}
// Only print warning if there are no errors, This will avoid pl
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(_this.lexerDefinitionWarning, function (warningDescriptor) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.PRINT_WARNING)(warningDescriptor.message);
});
_this.TRACE_INIT("Choosing sub-methods implementations", function () {
// Choose the relevant internal implementations for this specific parser.
// These implementations should be in-lined by the JavaScript engine
// to provide optimal performance in each scenario.
if (_lexer__WEBPACK_IMPORTED_MODULE_0__.SUPPORT_STICKY) {
_this.chopInput = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.IDENTITY;
_this.match = _this.matchWithTest;
}
else {
_this.updateLastIndex = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
_this.match = _this.matchWithExec;
}
if (hasOnlySingleMode) {
_this.handleModes = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
}
if (_this.trackStartLines === false) {
_this.computeNewColumn = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.IDENTITY;
}
if (_this.trackEndLines === false) {
_this.updateTokenEndLineColumnLocation = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
}
if (/full/i.test(_this.config.positionTracking)) {
_this.createTokenInstance = _this.createFullToken;
}
else if (/onlyStart/i.test(_this.config.positionTracking)) {
_this.createTokenInstance = _this.createStartOnlyToken;
}
else if (/onlyOffset/i.test(_this.config.positionTracking)) {
_this.createTokenInstance = _this.createOffsetOnlyToken;
}
else {
throw Error("Invalid <positionTracking> config option: \"" + _this.config.positionTracking + "\"");
}
if (_this.hasCustom) {
_this.addToken = _this.addTokenUsingPush;
_this.handlePayload = _this.handlePayloadWithCustom;
}
else {
_this.addToken = _this.addTokenUsingMemberAccess;
_this.handlePayload = _this.handlePayloadNoCustom;
}
});
_this.TRACE_INIT("Failed Optimization Warnings", function () {
var unOptimizedModes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.reduce)(_this.canModeBeOptimized, function (cannotBeOptimized, canBeOptimized, modeName) {
if (canBeOptimized === false) {
cannotBeOptimized.push(modeName);
}
return cannotBeOptimized;
}, []);
if (config.ensureOptimizations && !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(unOptimizedModes)) {
throw Error("Lexer Modes: < " + unOptimizedModes.join(", ") + " > cannot be optimized.\n" +
'\t Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.\n' +
"\t Or inspect the console log for details on how to resolve these issues.");
}
});
_this.TRACE_INIT("clearRegExpParserCache", function () {
(0,_reg_exp_parser__WEBPACK_IMPORTED_MODULE_4__.clearRegExpParserCache)();
});
_this.TRACE_INIT("toFastProperties", function () {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.toFastProperties)(_this);
});
});
}
Lexer.prototype.tokenize = function (text, initialMode) {
if (initialMode === void 0) { initialMode = this.defaultMode; }
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(this.lexerDefinitionErrors)) {
var allErrMessages = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(this.lexerDefinitionErrors, function (error) {
return error.message;
});
var allErrMessagesString = allErrMessages.join("-----------------------\n");
throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n" +
allErrMessagesString);
}
var lexResult = this.tokenizeInternal(text, initialMode);
return lexResult;
};
// There is quite a bit of duplication between this and "tokenizeInternalLazy"
// This is intentional due to performance considerations.
Lexer.prototype.tokenizeInternal = function (text, initialMode) {
var _this = this;
var i, j, matchAltImage, longerAltIdx, matchedImage, payload, altPayload, imageLength, group, tokType, newToken, errLength, droppedChar, msg, match;
var orgText = text;
var orgLength = orgText.length;
var offset = 0;
var matchedTokensIndex = 0;
// initializing the tokensArray to the "guessed" size.
// guessing too little will still reduce the number of array re-sizes on pushes.
// guessing too large (Tested by guessing x4 too large) may cost a bit more of memory
// but would still have a faster runtime by avoiding (All but one) array resizing.
var guessedNumberOfTokens = this.hasCustom
? 0 // will break custom token pattern APIs the matchedTokens array will contain undefined elements.
: Math.floor(text.length / 10);
var matchedTokens = new Array(guessedNumberOfTokens);
var errors = [];
var line = this.trackStartLines ? 1 : undefined;
var column = this.trackStartLines ? 1 : undefined;
var groups = (0,_lexer__WEBPACK_IMPORTED_MODULE_0__.cloneEmptyGroups)(this.emptyGroups);
var trackLines = this.trackStartLines;
var lineTerminatorPattern = this.config.lineTerminatorsPattern;
var currModePatternsLength = 0;
var patternIdxToConfig = [];
var currCharCodeToPatternIdxToConfig = [];
var modeStack = [];
var emptyArray = [];
Object.freeze(emptyArray);
var getPossiblePatterns = undefined;
function getPossiblePatternsSlow() {
return patternIdxToConfig;
}
function getPossiblePatternsOptimized(charCode) {
var optimizedCharIdx = (0,_lexer__WEBPACK_IMPORTED_MODULE_0__.charCodeToOptimizedIndex)(charCode);
var possiblePatterns = currCharCodeToPatternIdxToConfig[optimizedCharIdx];
if (possiblePatterns === undefined) {
return emptyArray;
}
else {
return possiblePatterns;
}
}
var pop_mode = function (popToken) {
// TODO: perhaps avoid this error in the edge case there is no more input?
if (modeStack.length === 1 &&
// if we have both a POP_MODE and a PUSH_MODE this is in-fact a "transition"
// So no error should occur.
popToken.tokenType.PUSH_MODE === undefined) {
// if we try to pop the last mode there lexer will no longer have ANY mode.
// thus the pop is ignored, an error will be created and the lexer will continue parsing in the previous mode.
var msg_1 = _this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(popToken);
errors.push({
offset: popToken.startOffset,
line: popToken.startLine !== undefined
? popToken.startLine
: undefined,
column: popToken.startColumn !== undefined
? popToken.startColumn
: undefined,
length: popToken.image.length,
message: msg_1
});
}
else {
modeStack.pop();
var newMode = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.last)(modeStack);
patternIdxToConfig = _this.patternIdxToConfig[newMode];
currCharCodeToPatternIdxToConfig = _this
.charCodeToPatternIdxToConfig[newMode];
currModePatternsLength = patternIdxToConfig.length;
var modeCanBeOptimized = _this.canModeBeOptimized[newMode] &&
_this.config.safeMode === false;
if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {
getPossiblePatterns = getPossiblePatternsOptimized;
}
else {
getPossiblePatterns = getPossiblePatternsSlow;
}
}
};
function push_mode(newMode) {
modeStack.push(newMode);
currCharCodeToPatternIdxToConfig = this
.charCodeToPatternIdxToConfig[newMode];
patternIdxToConfig = this.patternIdxToConfig[newMode];
currModePatternsLength = patternIdxToConfig.length;
currModePatternsLength = patternIdxToConfig.length;
var modeCanBeOptimized = this.canModeBeOptimized[newMode] &&
this.config.safeMode === false;
if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {
getPossiblePatterns = getPossiblePatternsOptimized;
}
else {
getPossiblePatterns = getPossiblePatternsSlow;
}
}
// this pattern seems to avoid a V8 de-optimization, although that de-optimization does not
// seem to matter performance wise.
push_mode.call(this, initialMode);
var currConfig;
while (offset < orgLength) {
matchedImage = null;
var nextCharCode = orgText.charCodeAt(offset);
var chosenPatternIdxToConfig = getPossiblePatterns(nextCharCode);
var chosenPatternsLength = chosenPatternIdxToConfig.length;
for (i = 0; i < chosenPatternsLength; i++) {
currConfig = chosenPatternIdxToConfig[i];
var currPattern = currConfig.pattern;
payload = null;
// manually in-lined because > 600 chars won't be in-lined in V8
var singleCharCode = currConfig.short;
if (singleCharCode !== false) {
if (nextCharCode === singleCharCode) {
// single character string
matchedImage = currPattern;
}
}
else if (currConfig.isCustom === true) {
match = currPattern.exec(orgText, offset, matchedTokens, groups);
if (match !== null) {
matchedImage = match[0];
if (match.payload !== undefined) {
payload = match.payload;
}
}
else {
matchedImage = null;
}
}
else {
this.updateLastIndex(currPattern, offset);
matchedImage = this.match(currPattern, text, offset);
}
if (matchedImage !== null) {
// even though this pattern matched we must try a another longer alternative.
// this can be used to prioritize keywords over identifiers
longerAltIdx = currConfig.longerAlt;
if (longerAltIdx !== undefined) {
// TODO: micro optimize, avoid extra prop access
// by saving/linking longerAlt on the original config?
var longerAltConfig = patternIdxToConfig[longerAltIdx];
var longerAltPattern = longerAltConfig.pattern;
altPayload = null;
// single Char can never be a longer alt so no need to test it.
// manually in-lined because > 600 chars won't be in-lined in V8
if (longerAltConfig.isCustom === true) {
match = longerAltPattern.exec(orgText, offset, matchedTokens, groups);
if (match !== null) {
matchAltImage = match[0];
if (match.payload !== undefined) {
altPayload = match.payload;
}
}
else {
matchAltImage = null;
}
}
else {
this.updateLastIndex(longerAltPattern, offset);
matchAltImage = this.match(longerAltPattern, text, offset);
}
if (matchAltImage &&
matchAltImage.length > matchedImage.length) {
matchedImage = matchAltImage;
payload = altPayload;
currConfig = longerAltConfig;
}
}
break;
}
}
// successful match
if (matchedImage !== null) {
imageLength = matchedImage.length;
group = currConfig.group;
if (group !== undefined) {
tokType = currConfig.tokenTypeIdx;
// TODO: "offset + imageLength" and the new column may be computed twice in case of "full" location information inside
// createFullToken method
newToken = this.createTokenInstance(matchedImage, offset, tokType, currConfig.tokenType, line, column, imageLength);
this.handlePayload(newToken, payload);
// TODO: optimize NOOP in case there are no special groups?
if (group === false) {
matchedTokensIndex = this.addToken(matchedTokens, matchedTokensIndex, newToken);
}
else {
groups[group].push(newToken);
}
}
text = this.chopInput(text, imageLength);
offset = offset + imageLength;
// TODO: with newlines the column may be assigned twice
column = this.computeNewColumn(column, imageLength);
if (trackLines === true &&
currConfig.canLineTerminator === true) {
var numOfLTsInMatch = 0;
var foundTerminator = void 0;
var lastLTEndOffset = void 0;
lineTerminatorPattern.lastIndex = 0;
do {
foundTerminator = lineTerminatorPattern.test(matchedImage);
if (foundTerminator === true) {
lastLTEndOffset =
lineTerminatorPattern.lastIndex - 1;
numOfLTsInMatch++;
}
} while (foundTerminator === true);
if (numOfLTsInMatch !== 0) {
line = line + numOfLTsInMatch;
column = imageLength - lastLTEndOffset;
this.updateTokenEndLineColumnLocation(newToken, group, lastLTEndOffset, numOfLTsInMatch, line, column, imageLength);
}
}
// will be NOOP if no modes present
this.handleModes(currConfig, pop_mode, push_mode, newToken);
}
else {
// error recovery, drop characters until we identify a valid token's start point
var errorStartOffset = offset;
var errorLine = line;
var errorColumn = column;
var foundResyncPoint = false;
while (!foundResyncPoint && offset < orgLength) {
// drop chars until we succeed in matching something
droppedChar = orgText.charCodeAt(offset);
// Identity Func (when sticky flag is enabled)
text = this.chopInput(text, 1);
offset++;
for (j = 0; j < currModePatternsLength; j++) {
var currConfig_1 = patternIdxToConfig[j];
var currPattern = currConfig_1.pattern;
// manually in-lined because > 600 chars won't be in-lined in V8
var singleCharCode = currConfig_1.short;
if (singleCharCode !== false) {
if (orgText.charCodeAt(offset) === singleCharCode) {
// single character string
foundResyncPoint = true;
}
}
else if (currConfig_1.isCustom === true) {
foundResyncPoint =
currPattern.exec(orgText, offset, matchedTokens, groups) !== null;
}
else {
this.updateLastIndex(currPattern, offset);
foundResyncPoint = currPattern.exec(text) !== null;
}
if (foundResyncPoint === true) {
break;
}
}
}
errLength = offset - errorStartOffset;
// at this point we either re-synced or reached the end of the input text
msg = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(orgText, errorStartOffset, errLength, errorLine, errorColumn);
errors.push({
offset: errorStartOffset,
line: errorLine,
column: errorColumn,
length: errLength,
message: msg
});
}
}
// if we do have custom patterns which push directly into the
// TODO: custom tokens should not push directly??
if (!this.hasCustom) {
// if we guessed a too large size for the tokens array this will shrink it to the right size.
matchedTokens.length = matchedTokensIndex;
}
return {
tokens: matchedTokens,
groups: groups,
errors: errors
};
};
Lexer.prototype.handleModes = function (config, pop_mode, push_mode, newToken) {
if (config.pop === true) {
// need to save the PUSH_MODE property as if the mode is popped
// patternIdxToPopMode is updated to reflect the new mode after popping the stack
var pushMode = config.push;
pop_mode(newToken);
if (pushMode !== undefined) {
push_mode.call(this, pushMode);
}
}
else if (config.push !== undefined) {
push_mode.call(this, config.push);
}
};
Lexer.prototype.chopInput = function (text, length) {
return text.substring(length);
};
Lexer.prototype.updateLastIndex = function (regExp, newLastIndex) {
regExp.lastIndex = newLastIndex;
};
// TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler
Lexer.prototype.updateTokenEndLineColumnLocation = function (newToken, group, lastLTIdx, numOfLTsInMatch, line, column, imageLength) {
var lastCharIsLT, fixForEndingInLT;
if (group !== undefined) {
// a none skipped multi line Token, need to update endLine/endColumn
lastCharIsLT = lastLTIdx === imageLength - 1;
fixForEndingInLT = lastCharIsLT ? -1 : 0;
if (!(numOfLTsInMatch === 1 && lastCharIsLT === true)) {
// if a token ends in a LT that last LT only affects the line numbering of following Tokens
newToken.endLine = line + fixForEndingInLT;
// the last LT in a token does not affect the endColumn either as the [columnStart ... columnEnd)
// inclusive to exclusive range.
newToken.endColumn = column - 1 + -fixForEndingInLT;
}
// else single LT in the last character of a token, no need to modify the endLine/EndColumn
}
};
Lexer.prototype.computeNewColumn = function (oldColumn, imageLength) {
return oldColumn + imageLength;
};
// Place holder, will be replaced by the correct variant according to the locationTracking option at runtime.
/* istanbul ignore next - place holder */
Lexer.prototype.createTokenInstance = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return null;
};
Lexer.prototype.createOffsetOnlyToken = function (image, startOffset, tokenTypeIdx, tokenType) {
return {
image: image,
startOffset: startOffset,
tokenTypeIdx: tokenTypeIdx,
tokenType: tokenType
};
};
Lexer.prototype.createStartOnlyToken = function (image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn) {
return {
image: image,
startOffset: startOffset,
startLine: startLine,
startColumn: startColumn,
tokenTypeIdx: tokenTypeIdx,
tokenType: tokenType
};
};
Lexer.prototype.createFullToken = function (image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn, imageLength) {
return {
image: image,
startOffset: startOffset,
endOffset: startOffset + imageLength - 1,
startLine: startLine,
endLine: startLine,
startColumn: startColumn,
endColumn: startColumn + imageLength - 1,
tokenTypeIdx: tokenTypeIdx,
tokenType: tokenType
};
};
// Place holder, will be replaced by the correct variant according to the locationTracking option at runtime.
/* istanbul ignore next - place holder */
Lexer.prototype.addToken = function (tokenVector, index, tokenToAdd) {
return 666;
};
Lexer.prototype.addTokenUsingPush = function (tokenVector, index, tokenToAdd) {
tokenVector.push(tokenToAdd);
return index;
};
Lexer.prototype.addTokenUsingMemberAccess = function (tokenVector, index, tokenToAdd) {
tokenVector[index] = tokenToAdd;
index++;
return index;
};
// Place holder, will be replaced by the correct variant according to the hasCustom flag option at runtime.
/* istanbul ignore next - place holder */
Lexer.prototype.handlePayload = function (token, payload) { };
Lexer.prototype.handlePayloadNoCustom = function (token, payload) { };
Lexer.prototype.handlePayloadWithCustom = function (token, payload) {
if (payload !== null) {
token.payload = payload;
}
};
/* istanbul ignore next - place holder to be replaced with chosen alternative at runtime */
Lexer.prototype.match = function (pattern, text, offset) {
return null;
};
Lexer.prototype.matchWithTest = function (pattern, text, offset) {
var found = pattern.test(text);
if (found === true) {
return text.substring(offset, pattern.lastIndex);
}
return null;
};
Lexer.prototype.matchWithExec = function (pattern, text) {
var regExpArray = pattern.exec(text);
return regExpArray !== null ? regExpArray[0] : regExpArray;
};
// Duplicated from the parser's perf trace trait to allow future extraction
// of the lexer to a separate package.
Lexer.prototype.TRACE_INIT = function (phaseDesc, phaseImpl) {
// No need to optimize this using NOOP pattern because
// It is not called in a hot spot...
if (this.traceInitPerf === true) {
this.traceInitIndent++;
var indent = new Array(this.traceInitIndent + 1).join("\t");
if (this.traceInitIndent < this.traceInitMaxIdent) {
console.log(indent + "--> <" + phaseDesc + ">");
}
var _a = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.timer)(phaseImpl), time = _a.time, value = _a.value;
/* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */
var traceMethod = time > 10 ? console.warn : console.log;
if (this.traceInitIndent < this.traceInitMaxIdent) {
traceMethod(indent + "<-- <" + phaseDesc + "> time: " + time + "ms");
}
this.traceInitIndent--;
return value;
}
else {
return phaseImpl();
}
};
Lexer.SKIPPED = "This marks a skipped Token pattern, this means each token identified by it will" +
"be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.";
Lexer.NA = /NOT_APPLICABLE/;
return Lexer;
}());
//# sourceMappingURL=lexer_public.js.map
/***/ }),
/* 23 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ DEFAULT_MODE: () => (/* binding */ DEFAULT_MODE),
/* harmony export */ LineTerminatorOptimizedTester: () => (/* binding */ LineTerminatorOptimizedTester),
/* harmony export */ MODES: () => (/* binding */ MODES),
/* harmony export */ SUPPORT_STICKY: () => (/* binding */ SUPPORT_STICKY),
/* harmony export */ addStartOfInput: () => (/* binding */ addStartOfInput),
/* harmony export */ addStickyFlag: () => (/* binding */ addStickyFlag),
/* harmony export */ analyzeTokenTypes: () => (/* binding */ analyzeTokenTypes),
/* harmony export */ buildLineBreakIssueMessage: () => (/* binding */ buildLineBreakIssueMessage),
/* harmony export */ charCodeToOptimizedIndex: () => (/* binding */ charCodeToOptimizedIndex),
/* harmony export */ cloneEmptyGroups: () => (/* binding */ cloneEmptyGroups),
/* harmony export */ disableSticky: () => (/* binding */ disableSticky),
/* harmony export */ enableSticky: () => (/* binding */ enableSticky),
/* harmony export */ findDuplicatePatterns: () => (/* binding */ findDuplicatePatterns),
/* harmony export */ findEmptyMatchRegExps: () => (/* binding */ findEmptyMatchRegExps),
/* harmony export */ findEndOfInputAnchor: () => (/* binding */ findEndOfInputAnchor),
/* harmony export */ findInvalidGroupType: () => (/* binding */ findInvalidGroupType),
/* harmony export */ findInvalidPatterns: () => (/* binding */ findInvalidPatterns),
/* harmony export */ findMissingPatterns: () => (/* binding */ findMissingPatterns),
/* harmony export */ findModesThatDoNotExist: () => (/* binding */ findModesThatDoNotExist),
/* harmony export */ findStartOfInputAnchor: () => (/* binding */ findStartOfInputAnchor),
/* harmony export */ findUnreachablePatterns: () => (/* binding */ findUnreachablePatterns),
/* harmony export */ findUnsupportedFlags: () => (/* binding */ findUnsupportedFlags),
/* harmony export */ isCustomPattern: () => (/* binding */ isCustomPattern),
/* harmony export */ isShortPattern: () => (/* binding */ isShortPattern),
/* harmony export */ minOptimizationVal: () => (/* binding */ minOptimizationVal),
/* harmony export */ performRuntimeChecks: () => (/* binding */ performRuntimeChecks),
/* harmony export */ performWarningRuntimeChecks: () => (/* binding */ performWarningRuntimeChecks),
/* harmony export */ validatePatterns: () => (/* binding */ validatePatterns)
/* harmony export */ });
/* harmony import */ var regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(24);
/* harmony import */ var regexp_to_ast__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _lexer_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(22);
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(17);
/* harmony import */ var _reg_exp__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(25);
/* harmony import */ var _reg_exp_parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(26);
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var PATTERN = "PATTERN";
var DEFAULT_MODE = "defaultMode";
var MODES = "modes";
var SUPPORT_STICKY = typeof new RegExp("(?:)").sticky === "boolean";
function disableSticky() {
SUPPORT_STICKY = false;
}
function enableSticky() {
SUPPORT_STICKY = true;
}
function analyzeTokenTypes(tokenTypes, options) {
options = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.defaults)(options, {
useSticky: SUPPORT_STICKY,
debug: false,
safeMode: false,
positionTracking: "full",
lineTerminatorCharacters: ["\r", "\n"],
tracer: function (msg, action) { return action(); }
});
var tracer = options.tracer;
tracer("initCharCodeToOptimizedIndexMap", function () {
initCharCodeToOptimizedIndexMap();
});
var onlyRelevantTypes;
tracer("Reject Lexer.NA", function () {
onlyRelevantTypes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.reject)(tokenTypes, function (currType) {
return currType[PATTERN] === _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.NA;
});
});
var hasCustom = false;
var allTransformedPatterns;
tracer("Transform Patterns", function () {
hasCustom = false;
allTransformedPatterns = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (currType) {
var currPattern = currType[PATTERN];
/* istanbul ignore else */
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(currPattern)) {
var regExpSource = currPattern.source;
if (regExpSource.length === 1 &&
// only these regExp meta characters which can appear in a length one regExp
regExpSource !== "^" &&
regExpSource !== "$" &&
regExpSource !== ".") {
return regExpSource;
}
else if (regExpSource.length === 2 &&
regExpSource[0] === "\\" &&
// not a meta character
!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.contains)([
"d",
"D",
"s",
"S",
"t",
"r",
"n",
"t",
"0",
"c",
"b",
"B",
"f",
"v",
"w",
"W"
], regExpSource[1])) {
// escaped meta Characters: /\+/ /\[/
// or redundant escaping: /\a/
// without the escaping "\"
return regExpSource[1];
}
else {
return options.useSticky
? addStickyFlag(currPattern)
: addStartOfInput(currPattern);
}
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isFunction)(currPattern)) {
hasCustom = true;
// CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object
return { exec: currPattern };
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(currPattern, "exec")) {
hasCustom = true;
// ICustomPattern
return currPattern;
}
else if (typeof currPattern === "string") {
if (currPattern.length === 1) {
return currPattern;
}
else {
var escapedRegExpString = currPattern.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
var wrappedRegExp = new RegExp(escapedRegExpString);
return options.useSticky
? addStickyFlag(wrappedRegExp)
: addStartOfInput(wrappedRegExp);
}
}
else {
throw Error("non exhaustive match");
}
});
});
var patternIdxToType;
var patternIdxToGroup;
var patternIdxToLongerAltIdx;
var patternIdxToPushMode;
var patternIdxToPopMode;
tracer("misc mapping", function () {
patternIdxToType = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (currType) { return currType.tokenTypeIdx; });
patternIdxToGroup = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (clazz) {
var groupName = clazz.GROUP;
/* istanbul ignore next */
if (groupName === _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.SKIPPED) {
return undefined;
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(groupName)) {
return groupName;
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isUndefined)(groupName)) {
return false;
}
else {
throw Error("non exhaustive match");
}
});
patternIdxToLongerAltIdx = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (clazz) {
var longerAltType = clazz.LONGER_ALT;
if (longerAltType) {
var longerAltIdx = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.indexOf)(onlyRelevantTypes, longerAltType);
return longerAltIdx;
}
});
patternIdxToPushMode = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (clazz) { return clazz.PUSH_MODE; });
patternIdxToPopMode = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (clazz) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(clazz, "POP_MODE");
});
});
var patternIdxToCanLineTerminator;
tracer("Line Terminator Handling", function () {
var lineTerminatorCharCodes = getCharCodes(options.lineTerminatorCharacters);
patternIdxToCanLineTerminator = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (tokType) { return false; });
if (options.positionTracking !== "onlyOffset") {
patternIdxToCanLineTerminator = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, function (tokType) {
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(tokType, "LINE_BREAKS")) {
return tokType.LINE_BREAKS;
}
else {
if (checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false) {
return (0,_reg_exp__WEBPACK_IMPORTED_MODULE_3__.canMatchCharCode)(lineTerminatorCharCodes, tokType.PATTERN);
}
}
});
}
});
var patternIdxToIsCustom;
var patternIdxToShort;
var emptyGroups;
var patternIdxToConfig;
tracer("Misc Mapping #2", function () {
patternIdxToIsCustom = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(onlyRelevantTypes, isCustomPattern);
patternIdxToShort = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(allTransformedPatterns, isShortPattern);
emptyGroups = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.reduce)(onlyRelevantTypes, function (acc, clazz) {
var groupName = clazz.GROUP;
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(groupName) && !(groupName === _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.SKIPPED)) {
acc[groupName] = [];
}
return acc;
}, {});
patternIdxToConfig = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(allTransformedPatterns, function (x, idx) {
return {
pattern: allTransformedPatterns[idx],
longerAlt: patternIdxToLongerAltIdx[idx],
canLineTerminator: patternIdxToCanLineTerminator[idx],
isCustom: patternIdxToIsCustom[idx],
short: patternIdxToShort[idx],
group: patternIdxToGroup[idx],
push: patternIdxToPushMode[idx],
pop: patternIdxToPopMode[idx],
tokenTypeIdx: patternIdxToType[idx],
tokenType: onlyRelevantTypes[idx]
};
});
});
var canBeOptimized = true;
var charCodeToPatternIdxToConfig = [];
if (!options.safeMode) {
tracer("First Char Optimization", function () {
charCodeToPatternIdxToConfig = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.reduce)(onlyRelevantTypes, function (result, currTokType, idx) {
if (typeof currTokType.PATTERN === "string") {
var charCode = currTokType.PATTERN.charCodeAt(0);
var optimizedIdx = charCodeToOptimizedIndex(charCode);
addToMapOfArrays(result, optimizedIdx, patternIdxToConfig[idx]);
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isArray)(currTokType.START_CHARS_HINT)) {
var lastOptimizedIdx_1;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(currTokType.START_CHARS_HINT, function (charOrInt) {
var charCode = typeof charOrInt === "string"
? charOrInt.charCodeAt(0)
: charOrInt;
var currOptimizedIdx = charCodeToOptimizedIndex(charCode);
// Avoid adding the config multiple times
if (lastOptimizedIdx_1 !== currOptimizedIdx) {
lastOptimizedIdx_1 = currOptimizedIdx;
addToMapOfArrays(result, currOptimizedIdx, patternIdxToConfig[idx]);
}
});
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(currTokType.PATTERN)) {
if (currTokType.PATTERN.unicode) {
canBeOptimized = false;
if (options.ensureOptimizations) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.PRINT_ERROR)("" + _reg_exp__WEBPACK_IMPORTED_MODULE_3__.failedOptimizationPrefixMsg +
("\tUnable to analyze < " + currTokType.PATTERN.toString() + " > pattern.\n") +
"\tThe regexp unicode flag is not currently supported by the regexp-to-ast library.\n" +
"\tThis will disable the lexer's first char optimizations.\n" +
"\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE");
}
}
else {
var optimizedCodes = (0,_reg_exp__WEBPACK_IMPORTED_MODULE_3__.getOptimizedStartCodesIndices)(currTokType.PATTERN, options.ensureOptimizations);
/* istanbul ignore if */
// start code will only be empty given an empty regExp or failure of regexp-to-ast library
// the first should be a different validation and the second cannot be tested.
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isEmpty)(optimizedCodes)) {
// we cannot understand what codes may start possible matches
// The optimization correctness requires knowing start codes for ALL patterns.
// Not actually sure this is an error, no debug message
canBeOptimized = false;
}
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(optimizedCodes, function (code) {
addToMapOfArrays(result, code, patternIdxToConfig[idx]);
});
}
}
else {
if (options.ensureOptimizations) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.PRINT_ERROR)("" + _reg_exp__WEBPACK_IMPORTED_MODULE_3__.failedOptimizationPrefixMsg +
("\tTokenType: <" + currTokType.name + "> is using a custom token pattern without providing <start_chars_hint> parameter.\n") +
"\tThis will disable the lexer's first char optimizations.\n" +
"\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE");
}
canBeOptimized = false;
}
return result;
}, []);
});
}
tracer("ArrayPacking", function () {
charCodeToPatternIdxToConfig = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.packArray)(charCodeToPatternIdxToConfig);
});
return {
emptyGroups: emptyGroups,
patternIdxToConfig: patternIdxToConfig,
charCodeToPatternIdxToConfig: charCodeToPatternIdxToConfig,
hasCustom: hasCustom,
canBeOptimized: canBeOptimized
};
}
function validatePatterns(tokenTypes, validModesNames) {
var errors = [];
var missingResult = findMissingPatterns(tokenTypes);
errors = errors.concat(missingResult.errors);
var invalidResult = findInvalidPatterns(missingResult.valid);
var validTokenTypes = invalidResult.valid;
errors = errors.concat(invalidResult.errors);
errors = errors.concat(validateRegExpPattern(validTokenTypes));
errors = errors.concat(findInvalidGroupType(validTokenTypes));
errors = errors.concat(findModesThatDoNotExist(validTokenTypes, validModesNames));
errors = errors.concat(findUnreachablePatterns(validTokenTypes));
return errors;
}
function validateRegExpPattern(tokenTypes) {
var errors = [];
var withRegExpPatterns = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (currTokType) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(currTokType[PATTERN]);
});
errors = errors.concat(findEndOfInputAnchor(withRegExpPatterns));
errors = errors.concat(findStartOfInputAnchor(withRegExpPatterns));
errors = errors.concat(findUnsupportedFlags(withRegExpPatterns));
errors = errors.concat(findDuplicatePatterns(withRegExpPatterns));
errors = errors.concat(findEmptyMatchRegExps(withRegExpPatterns));
return errors;
}
function findMissingPatterns(tokenTypes) {
var tokenTypesWithMissingPattern = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (currType) {
return !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(currType, PATTERN);
});
var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(tokenTypesWithMissingPattern, function (currType) {
return {
message: "Token Type: ->" +
currType.name +
"<- missing static 'PATTERN' property",
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.MISSING_PATTERN,
tokenTypes: [currType]
};
});
var valid = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.difference)(tokenTypes, tokenTypesWithMissingPattern);
return { errors: errors, valid: valid };
}
function findInvalidPatterns(tokenTypes) {
var tokenTypesWithInvalidPattern = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (currType) {
var pattern = currType[PATTERN];
return (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(pattern) &&
!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isFunction)(pattern) &&
!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(pattern, "exec") &&
!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(pattern));
});
var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(tokenTypesWithInvalidPattern, function (currType) {
return {
message: "Token Type: ->" +
currType.name +
"<- static 'PATTERN' can only be a RegExp, a" +
" Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.INVALID_PATTERN,
tokenTypes: [currType]
};
});
var valid = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.difference)(tokenTypes, tokenTypesWithInvalidPattern);
return { errors: errors, valid: valid };
}
var end_of_input = /[^\\][\$]/;
function findEndOfInputAnchor(tokenTypes) {
var EndAnchorFinder = /** @class */ (function (_super) {
__extends(EndAnchorFinder, _super);
function EndAnchorFinder() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.found = false;
return _this;
}
EndAnchorFinder.prototype.visitEndAnchor = function (node) {
this.found = true;
};
return EndAnchorFinder;
}(regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__.BaseRegExpVisitor));
var invalidRegex = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (currType) {
var pattern = currType[PATTERN];
try {
var regexpAst = (0,_reg_exp_parser__WEBPACK_IMPORTED_MODULE_4__.getRegExpAst)(pattern);
var endAnchorVisitor = new EndAnchorFinder();
endAnchorVisitor.visit(regexpAst);
return endAnchorVisitor.found;
}
catch (e) {
// old behavior in case of runtime exceptions with regexp-to-ast.
/* istanbul ignore next - cannot ensure an error in regexp-to-ast*/
return end_of_input.test(pattern.source);
}
});
var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(invalidRegex, function (currType) {
return {
message: "Unexpected RegExp Anchor Error:\n" +
"\tToken Type: ->" +
currType.name +
"<- static 'PATTERN' cannot contain end of input anchor '$'\n" +
"\tSee sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#ANCHORS" +
"\tfor details.",
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.EOI_ANCHOR_FOUND,
tokenTypes: [currType]
};
});
return errors;
}
function findEmptyMatchRegExps(tokenTypes) {
var matchesEmptyString = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (currType) {
var pattern = currType[PATTERN];
return pattern.test("");
});
var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(matchesEmptyString, function (currType) {
return {
message: "Token Type: ->" +
currType.name +
"<- static 'PATTERN' must not match an empty string",
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,
tokenTypes: [currType]
};
});
return errors;
}
var start_of_input = /[^\\[][\^]|^\^/;
function findStartOfInputAnchor(tokenTypes) {
var StartAnchorFinder = /** @class */ (function (_super) {
__extends(StartAnchorFinder, _super);
function StartAnchorFinder() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.found = false;
return _this;
}
StartAnchorFinder.prototype.visitStartAnchor = function (node) {
this.found = true;
};
return StartAnchorFinder;
}(regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__.BaseRegExpVisitor));
var invalidRegex = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (currType) {
var pattern = currType[PATTERN];
try {
var regexpAst = (0,_reg_exp_parser__WEBPACK_IMPORTED_MODULE_4__.getRegExpAst)(pattern);
var startAnchorVisitor = new StartAnchorFinder();
startAnchorVisitor.visit(regexpAst);
return startAnchorVisitor.found;
}
catch (e) {
// old behavior in case of runtime exceptions with regexp-to-ast.
/* istanbul ignore next - cannot ensure an error in regexp-to-ast*/
return start_of_input.test(pattern.source);
}
});
var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(invalidRegex, function (currType) {
return {
message: "Unexpected RegExp Anchor Error:\n" +
"\tToken Type: ->" +
currType.name +
"<- static 'PATTERN' cannot contain start of input anchor '^'\n" +
"\tSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#ANCHORS" +
"\tfor details.",
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.SOI_ANCHOR_FOUND,
tokenTypes: [currType]
};
});
return errors;
}
function findUnsupportedFlags(tokenTypes) {
var invalidFlags = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (currType) {
var pattern = currType[PATTERN];
return (pattern instanceof RegExp && (pattern.multiline || pattern.global));
});
var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(invalidFlags, function (currType) {
return {
message: "Token Type: ->" +
currType.name +
"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,
tokenTypes: [currType]
};
});
return errors;
}
// This can only test for identical duplicate RegExps, not semantically equivalent ones.
function findDuplicatePatterns(tokenTypes) {
var found = [];
var identicalPatterns = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(tokenTypes, function (outerType) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.reduce)(tokenTypes, function (result, innerType) {
if (outerType.PATTERN.source === innerType.PATTERN.source &&
!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.contains)(found, innerType) &&
innerType.PATTERN !== _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.NA) {
// this avoids duplicates in the result, each Token Type may only appear in one "set"
// in essence we are creating Equivalence classes on equality relation.
found.push(innerType);
result.push(innerType);
return result;
}
return result;
}, []);
});
identicalPatterns = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.compact)(identicalPatterns);
var duplicatePatterns = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(identicalPatterns, function (currIdenticalSet) {
return currIdenticalSet.length > 1;
});
var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(duplicatePatterns, function (setOfIdentical) {
var tokenTypeNames = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(setOfIdentical, function (currType) {
return currType.name;
});
var dupPatternSrc = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.first)(setOfIdentical).PATTERN;
return {
message: "The same RegExp pattern ->" + dupPatternSrc + "<-" +
("has been used in all of the following Token Types: " + tokenTypeNames.join(", ") + " <-"),
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,
tokenTypes: setOfIdentical
};
});
return errors;
}
function findInvalidGroupType(tokenTypes) {
var invalidTypes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (clazz) {
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(clazz, "GROUP")) {
return false;
}
var group = clazz.GROUP;
return group !== _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.SKIPPED && group !== _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.NA && !(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(group);
});
var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(invalidTypes, function (currType) {
return {
message: "Token Type: ->" +
currType.name +
"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,
tokenTypes: [currType]
};
});
return errors;
}
function findModesThatDoNotExist(tokenTypes, validModes) {
var invalidModes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.filter)(tokenTypes, function (clazz) {
return (clazz.PUSH_MODE !== undefined &&
!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.contains)(validModes, clazz.PUSH_MODE));
});
var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(invalidModes, function (tokType) {
var msg = "Token Type: ->" + tokType.name + "<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->" + tokType.PUSH_MODE + "<-" +
"which does not exist";
return {
message: msg,
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,
tokenTypes: [tokType]
};
});
return errors;
}
function findUnreachablePatterns(tokenTypes) {
var errors = [];
var canBeTested = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.reduce)(tokenTypes, function (result, tokType, idx) {
var pattern = tokType.PATTERN;
if (pattern === _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.NA) {
return result;
}
// a more comprehensive validation for all forms of regExps would require
// deeper regExp analysis capabilities
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(pattern)) {
result.push({ str: pattern, idx: idx, tokenType: tokType });
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(pattern) && noMetaChar(pattern)) {
result.push({ str: pattern.source, idx: idx, tokenType: tokType });
}
return result;
}, []);
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(tokenTypes, function (tokType, testIdx) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(canBeTested, function (_a) {
var str = _a.str, idx = _a.idx, tokenType = _a.tokenType;
if (testIdx < idx && testTokenType(str, tokType.PATTERN)) {
var msg = "Token: ->" + tokenType.name + "<- can never be matched.\n" +
("Because it appears AFTER the Token Type ->" + tokType.name + "<-") +
"in the lexer's definition.\n" +
"See https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#UNREACHABLE";
errors.push({
message: msg,
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.UNREACHABLE_PATTERN,
tokenTypes: [tokType, tokenType]
});
}
});
});
return errors;
}
function testTokenType(str, pattern) {
/* istanbul ignore else */
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(pattern)) {
var regExpArray = pattern.exec(str);
return regExpArray !== null && regExpArray.index === 0;
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isFunction)(pattern)) {
// maintain the API of custom patterns
return pattern(str, 0, [], {});
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(pattern, "exec")) {
// maintain the API of custom patterns
return pattern.exec(str, 0, [], {});
}
else if (typeof pattern === "string") {
return pattern === str;
}
else {
throw Error("non exhaustive match");
}
}
function noMetaChar(regExp) {
//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
var metaChars = [
".",
"\\",
"[",
"]",
"|",
"^",
"$",
"(",
")",
"?",
"*",
"+",
"{"
];
return ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.find)(metaChars, function (char) { return regExp.source.indexOf(char) !== -1; }) ===
undefined);
}
function addStartOfInput(pattern) {
var flags = pattern.ignoreCase ? "i" : "";
// always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input.
// duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/)
return new RegExp("^(?:" + pattern.source + ")", flags);
}
function addStickyFlag(pattern) {
var flags = pattern.ignoreCase ? "iy" : "y";
// always wrapping in a none capturing group preceded by '^' to make sure matching can only work on start of input.
// duplicate/redundant start of input markers have no meaning (/^^^^A/ === /^A/)
return new RegExp("" + pattern.source, flags);
}
function performRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) {
var errors = [];
// some run time checks to help the end users.
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(lexerDefinition, DEFAULT_MODE)) {
errors.push({
message: "A MultiMode Lexer cannot be initialized without a <" +
DEFAULT_MODE +
"> property in its definition\n",
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE
});
}
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(lexerDefinition, MODES)) {
errors.push({
message: "A MultiMode Lexer cannot be initialized without a <" +
MODES +
"> property in its definition\n",
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY
});
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(lexerDefinition, MODES) &&
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(lexerDefinition, DEFAULT_MODE) &&
!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(lexerDefinition.modes, lexerDefinition.defaultMode)) {
errors.push({
message: "A MultiMode Lexer cannot be initialized with a " + DEFAULT_MODE + ": <" + lexerDefinition.defaultMode + ">" +
"which does not exist\n",
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST
});
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(lexerDefinition, MODES)) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(lexerDefinition.modes, function (currModeValue, currModeName) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(currModeValue, function (currTokType, currIdx) {
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isUndefined)(currTokType)) {
errors.push({
message: "A Lexer cannot be initialized using an undefined Token Type. Mode:" +
("<" + currModeName + "> at index: <" + currIdx + ">\n"),
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED
});
}
});
});
}
return errors;
}
function performWarningRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) {
var warnings = [];
var hasAnyLineBreak = false;
var allTokenTypes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.compact)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.flatten)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.mapValues)(lexerDefinition.modes, function (tokTypes) { return tokTypes; })));
var concreteTokenTypes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.reject)(allTokenTypes, function (currType) { return currType[PATTERN] === _lexer_public__WEBPACK_IMPORTED_MODULE_1__.Lexer.NA; });
var terminatorCharCodes = getCharCodes(lineTerminatorCharacters);
if (trackLines) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(concreteTokenTypes, function (tokType) {
var currIssue = checkLineBreaksIssues(tokType, terminatorCharCodes);
if (currIssue !== false) {
var message = buildLineBreakIssueMessage(tokType, currIssue);
var warningDescriptor = {
message: message,
type: currIssue.issue,
tokenType: tokType
};
warnings.push(warningDescriptor);
}
else {
// we don't want to attempt to scan if the user explicitly specified the line_breaks option.
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(tokType, "LINE_BREAKS")) {
if (tokType.LINE_BREAKS === true) {
hasAnyLineBreak = true;
}
}
else {
if ((0,_reg_exp__WEBPACK_IMPORTED_MODULE_3__.canMatchCharCode)(terminatorCharCodes, tokType.PATTERN)) {
hasAnyLineBreak = true;
}
}
}
});
}
if (trackLines && !hasAnyLineBreak) {
warnings.push({
message: "Warning: No LINE_BREAKS Found.\n" +
"\tThis Lexer has been defined to track line and column information,\n" +
"\tBut none of the Token Types can be identified as matching a line terminator.\n" +
"\tSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n" +
"\tfor details.",
type: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS
});
}
return warnings;
}
function cloneEmptyGroups(emptyGroups) {
var clonedResult = {};
var groupKeys = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.keys)(emptyGroups);
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.forEach)(groupKeys, function (currKey) {
var currGroupValue = emptyGroups[currKey];
/* istanbul ignore else */
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isArray)(currGroupValue)) {
clonedResult[currKey] = [];
}
else {
throw Error("non exhaustive match");
}
});
return clonedResult;
}
// TODO: refactor to avoid duplication
function isCustomPattern(tokenType) {
var pattern = tokenType.PATTERN;
/* istanbul ignore else */
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(pattern)) {
return false;
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isFunction)(pattern)) {
// CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object
return true;
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(pattern, "exec")) {
// ICustomPattern
return true;
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(pattern)) {
return false;
}
else {
throw Error("non exhaustive match");
}
}
function isShortPattern(pattern) {
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(pattern) && pattern.length === 1) {
return pattern.charCodeAt(0);
}
else {
return false;
}
}
/**
* Faster than using a RegExp for default newline detection during lexing.
*/
var LineTerminatorOptimizedTester = {
// implements /\n|\r\n?/g.test
test: function (text) {
var len = text.length;
for (var i = this.lastIndex; i < len; i++) {
var c = text.charCodeAt(i);
if (c === 10) {
this.lastIndex = i + 1;
return true;
}
else if (c === 13) {
if (text.charCodeAt(i + 1) === 10) {
this.lastIndex = i + 2;
}
else {
this.lastIndex = i + 1;
}
return true;
}
}
return false;
},
lastIndex: 0
};
function checkLineBreaksIssues(tokType, lineTerminatorCharCodes) {
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.has)(tokType, "LINE_BREAKS")) {
// if the user explicitly declared the line_breaks option we will respect their choice
// and assume it is correct.
return false;
}
else {
/* istanbul ignore else */
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isRegExp)(tokType.PATTERN)) {
try {
(0,_reg_exp__WEBPACK_IMPORTED_MODULE_3__.canMatchCharCode)(lineTerminatorCharCodes, tokType.PATTERN);
}
catch (e) {
/* istanbul ignore next - to test this we would have to mock <canMatchCharCode> to throw an error */
return {
issue: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.IDENTIFY_TERMINATOR,
errMsg: e.message
};
}
return false;
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(tokType.PATTERN)) {
// string literal patterns can always be analyzed to detect line terminator usage
return false;
}
else if (isCustomPattern(tokType)) {
// custom token types
return { issue: _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.CUSTOM_LINE_BREAK };
}
else {
throw Error("non exhaustive match");
}
}
}
function buildLineBreakIssueMessage(tokType, details) {
/* istanbul ignore else */
if (details.issue === _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.IDENTIFY_TERMINATOR) {
return ("Warning: unable to identify line terminator usage in pattern.\n" +
("\tThe problem is in the <" + tokType.name + "> Token Type\n") +
("\t Root cause: " + details.errMsg + ".\n") +
"\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR");
}
else if (details.issue === _lexer_public__WEBPACK_IMPORTED_MODULE_1__.LexerDefinitionErrorType.CUSTOM_LINE_BREAK) {
return ("Warning: A Custom Token Pattern should specify the <line_breaks> option.\n" +
("\tThe problem is in the <" + tokType.name + "> Token Type\n") +
"\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK");
}
else {
throw Error("non exhaustive match");
}
}
function getCharCodes(charsOrCodes) {
var charCodes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.map)(charsOrCodes, function (numOrString) {
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isString)(numOrString) && numOrString.length > 0) {
return numOrString.charCodeAt(0);
}
else {
return numOrString;
}
});
return charCodes;
}
function addToMapOfArrays(map, key, value) {
if (map[key] === undefined) {
map[key] = [value];
}
else {
map[key].push(value);
}
}
var minOptimizationVal = 256;
/**
* We ae mapping charCode above ASCI (256) into buckets each in the size of 256.
* This is because ASCI are the most common start chars so each one of those will get its own
* possible token configs vector.
*
* Tokens starting with charCodes "above" ASCI are uncommon, so we can "afford"
* to place these into buckets of possible token configs, What we gain from
* this is avoiding the case of creating an optimization 'charCodeToPatternIdxToConfig'
* which would contain 10,000+ arrays of small size (e.g unicode Identifiers scenario).
* Our 'charCodeToPatternIdxToConfig' max size will now be:
* 256 + (2^16 / 2^8) - 1 === 511
*
* note the hack for fast division integer part extraction
* See: https://stackoverflow.com/a/4228528
*/
function charCodeToOptimizedIndex(charCode) {
return charCode < minOptimizationVal
? charCode
: charCodeToOptimizedIdxMap[charCode];
}
/**
* This is a compromise between cold start / hot running performance
* Creating this array takes ~3ms on a modern machine,
* But if we perform the computation at runtime as needed the CSS Lexer benchmark
* performance degrades by ~10%
*
* TODO: Perhaps it should be lazy initialized only if a charCode > 255 is used.
*/
var charCodeToOptimizedIdxMap = [];
function initCharCodeToOptimizedIndexMap() {
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_2__.isEmpty)(charCodeToOptimizedIdxMap)) {
charCodeToOptimizedIdxMap = new Array(65536);
for (var i = 0; i < 65536; i++) {
/* tslint:disable */
charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i;
/* tslint:enable */
}
}
}
//# sourceMappingURL=lexer.js.map
/***/ }),
/* 24 */
/***/ (function(module, exports) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;;(function(root, factory) {
// istanbul ignore next
if (true) {
// istanbul ignore next
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))
} else {}
})(
typeof self !== "undefined"
? // istanbul ignore next
self
: this,
function() {
// references
// https://hackernoon.com/the-madness-of-parsing-real-world-javascript-regexps-d9ee336df983
// https://www.ecma-international.org/ecma-262/8.0/index.html#prod-Pattern
function RegExpParser() {}
RegExpParser.prototype.saveState = function() {
return {
idx: this.idx,
input: this.input,
groupIdx: this.groupIdx
}
}
RegExpParser.prototype.restoreState = function(newState) {
this.idx = newState.idx
this.input = newState.input
this.groupIdx = newState.groupIdx
}
RegExpParser.prototype.pattern = function(input) {
// parser state
this.idx = 0
this.input = input
this.groupIdx = 0
this.consumeChar("/")
var value = this.disjunction()
this.consumeChar("/")
var flags = {
type: "Flags",
global: false,
ignoreCase: false,
multiLine: false,
unicode: false,
sticky: false
}
while (this.isRegExpFlag()) {
switch (this.popChar()) {
case "g":
addFlag(flags, "global")
break
case "i":
addFlag(flags, "ignoreCase")
break
case "m":
addFlag(flags, "multiLine")
break
case "u":
addFlag(flags, "unicode")
break
case "y":
addFlag(flags, "sticky")
break
}
}
if (this.idx !== this.input.length) {
throw Error(
"Redundant input: " + this.input.substring(this.idx)
)
}
return { type: "Pattern", flags: flags, value: value }
}
RegExpParser.prototype.disjunction = function() {
var alts = []
alts.push(this.alternative())
while (this.peekChar() === "|") {
this.consumeChar("|")
alts.push(this.alternative())
}
return { type: "Disjunction", value: alts }
}
RegExpParser.prototype.alternative = function() {
var terms = []
while (this.isTerm()) {
terms.push(this.term())
}
return { type: "Alternative", value: terms }
}
RegExpParser.prototype.term = function() {
if (this.isAssertion()) {
return this.assertion()
} else {
return this.atom()
}
}
RegExpParser.prototype.assertion = function() {
switch (this.popChar()) {
case "^":
return { type: "StartAnchor" }
case "$":
return { type: "EndAnchor" }
// '\b' or '\B'
case "\\":
switch (this.popChar()) {
case "b":
return { type: "WordBoundary" }
case "B":
return { type: "NonWordBoundary" }
}
// istanbul ignore next
throw Error("Invalid Assertion Escape")
// '(?=' or '(?!'
case "(":
this.consumeChar("?")
var type
switch (this.popChar()) {
case "=":
type = "Lookahead"
break
case "!":
type = "NegativeLookahead"
break
}
ASSERT_EXISTS(type)
var disjunction = this.disjunction()
this.consumeChar(")")
return { type: type, value: disjunction }
}
// istanbul ignore next
ASSERT_NEVER_REACH_HERE()
}
RegExpParser.prototype.quantifier = function(isBacktracking) {
var range
switch (this.popChar()) {
case "*":
range = {
atLeast: 0,
atMost: Infinity
}
break
case "+":
range = {
atLeast: 1,
atMost: Infinity
}
break
case "?":
range = {
atLeast: 0,
atMost: 1
}
break
case "{":
var atLeast = this.integerIncludingZero()
switch (this.popChar()) {
case "}":
range = {
atLeast: atLeast,
atMost: atLeast
}
break
case ",":
var atMost
if (this.isDigit()) {
atMost = this.integerIncludingZero()
range = {
atLeast: atLeast,
atMost: atMost
}
} else {
range = {
atLeast: atLeast,
atMost: Infinity
}
}
this.consumeChar("}")
break
}
// throwing exceptions from "ASSERT_EXISTS" during backtracking
// causes severe performance degradations
if (isBacktracking === true && range === undefined) {
return undefined
}
ASSERT_EXISTS(range)
break
}
// throwing exceptions from "ASSERT_EXISTS" during backtracking
// causes severe performance degradations
if (isBacktracking === true && range === undefined) {
return undefined
}
ASSERT_EXISTS(range)
if (this.peekChar(0) === "?") {
this.consumeChar("?")
range.greedy = false
} else {
range.greedy = true
}
range.type = "Quantifier"
return range
}
RegExpParser.prototype.atom = function() {
var atom
switch (this.peekChar()) {
case ".":
atom = this.dotAll()
break
case "\\":
atom = this.atomEscape()
break
case "[":
atom = this.characterClass()
break
case "(":
atom = this.group()
break
}
if (atom === undefined && this.isPatternCharacter()) {
atom = this.patternCharacter()
}
ASSERT_EXISTS(atom)
if (this.isQuantifier()) {
atom.quantifier = this.quantifier()
}
return atom
}
RegExpParser.prototype.dotAll = function() {
this.consumeChar(".")
return {
type: "Set",
complement: true,
value: [cc("\n"), cc("\r"), cc("\u2028"), cc("\u2029")]
}
}
RegExpParser.prototype.atomEscape = function() {
this.consumeChar("\\")
switch (this.peekChar()) {
case "1":
case "2":
case "3":
case "4":
case "5":
case "6":
case "7":
case "8":
case "9":
return this.decimalEscapeAtom()
case "d":
case "D":
case "s":
case "S":
case "w":
case "W":
return this.characterClassEscape()
case "f":
case "n":
case "r":
case "t":
case "v":
return this.controlEscapeAtom()
case "c":
return this.controlLetterEscapeAtom()
case "0":
return this.nulCharacterAtom()
case "x":
return this.hexEscapeSequenceAtom()
case "u":
return this.regExpUnicodeEscapeSequenceAtom()
default:
return this.identityEscapeAtom()
}
}
RegExpParser.prototype.decimalEscapeAtom = function() {
var value = this.positiveInteger()
return { type: "GroupBackReference", value: value }
}
RegExpParser.prototype.characterClassEscape = function() {
var set
var complement = false
switch (this.popChar()) {
case "d":
set = digitsCharCodes
break
case "D":
set = digitsCharCodes
complement = true
break
case "s":
set = whitespaceCodes
break
case "S":
set = whitespaceCodes
complement = true
break
case "w":
set = wordCharCodes
break
case "W":
set = wordCharCodes
complement = true
break
}
ASSERT_EXISTS(set)
return { type: "Set", value: set, complement: complement }
}
RegExpParser.prototype.controlEscapeAtom = function() {
var escapeCode
switch (this.popChar()) {
case "f":
escapeCode = cc("\f")
break
case "n":
escapeCode = cc("\n")
break
case "r":
escapeCode = cc("\r")
break
case "t":
escapeCode = cc("\t")
break
case "v":
escapeCode = cc("\v")
break
}
ASSERT_EXISTS(escapeCode)
return { type: "Character", value: escapeCode }
}
RegExpParser.prototype.controlLetterEscapeAtom = function() {
this.consumeChar("c")
var letter = this.popChar()
if (/[a-zA-Z]/.test(letter) === false) {
throw Error("Invalid ")
}
var letterCode = letter.toUpperCase().charCodeAt(0) - 64
return { type: "Character", value: letterCode }
}
RegExpParser.prototype.nulCharacterAtom = function() {
// TODO implement '[lookahead ∉ DecimalDigit]'
// TODO: for the deprecated octal escape sequence
this.consumeChar("0")
return { type: "Character", value: cc("\0") }
}
RegExpParser.prototype.hexEscapeSequenceAtom = function() {
this.consumeChar("x")
return this.parseHexDigits(2)
}
RegExpParser.prototype.regExpUnicodeEscapeSequenceAtom = function() {
this.consumeChar("u")
return this.parseHexDigits(4)
}
RegExpParser.prototype.identityEscapeAtom = function() {
// TODO: implement "SourceCharacter but not UnicodeIDContinue"
// // http://unicode.org/reports/tr31/#Specific_Character_Adjustments
var escapedChar = this.popChar()
return { type: "Character", value: cc(escapedChar) }
}
RegExpParser.prototype.classPatternCharacterAtom = function() {
switch (this.peekChar()) {
// istanbul ignore next
case "\n":
// istanbul ignore next
case "\r":
// istanbul ignore next
case "\u2028":
// istanbul ignore next
case "\u2029":
// istanbul ignore next
case "\\":
// istanbul ignore next
case "]":
throw Error("TBD")
default:
var nextChar = this.popChar()
return { type: "Character", value: cc(nextChar) }
}
}
RegExpParser.prototype.characterClass = function() {
var set = []
var complement = false
this.consumeChar("[")
if (this.peekChar(0) === "^") {
this.consumeChar("^")
complement = true
}
while (this.isClassAtom()) {
var from = this.classAtom()
var isFromSingleChar = from.type === "Character"
if (isFromSingleChar && this.isRangeDash()) {
this.consumeChar("-")
var to = this.classAtom()
var isToSingleChar = to.type === "Character"
// a range can only be used when both sides are single characters
if (isToSingleChar) {
if (to.value < from.value) {
throw Error("Range out of order in character class")
}
set.push({ from: from.value, to: to.value })
} else {
// literal dash
insertToSet(from.value, set)
set.push(cc("-"))
insertToSet(to.value, set)
}
} else {
insertToSet(from.value, set)
}
}
this.consumeChar("]")
return { type: "Set", complement: complement, value: set }
}
RegExpParser.prototype.classAtom = function() {
switch (this.peekChar()) {
// istanbul ignore next
case "]":
// istanbul ignore next
case "\n":
// istanbul ignore next
case "\r":
// istanbul ignore next
case "\u2028":
// istanbul ignore next
case "\u2029":
throw Error("TBD")
case "\\":
return this.classEscape()
default:
return this.classPatternCharacterAtom()
}
}
RegExpParser.prototype.classEscape = function() {
this.consumeChar("\\")
switch (this.peekChar()) {
// Matches a backspace.
// (Not to be confused with \b word boundary outside characterClass)
case "b":
this.consumeChar("b")
return { type: "Character", value: cc("\u0008") }
case "d":
case "D":
case "s":
case "S":
case "w":
case "W":
return this.characterClassEscape()
case "f":
case "n":
case "r":
case "t":
case "v":
return this.controlEscapeAtom()
case "c":
return this.controlLetterEscapeAtom()
case "0":
return this.nulCharacterAtom()
case "x":
return this.hexEscapeSequenceAtom()
case "u":
return this.regExpUnicodeEscapeSequenceAtom()
default:
return this.identityEscapeAtom()
}
}
RegExpParser.prototype.group = function() {
var capturing = true
this.consumeChar("(")
switch (this.peekChar(0)) {
case "?":
this.consumeChar("?")
this.consumeChar(":")
capturing = false
break
default:
this.groupIdx++
break
}
var value = this.disjunction()
this.consumeChar(")")
var groupAst = {
type: "Group",
capturing: capturing,
value: value
}
if (capturing) {
groupAst.idx = this.groupIdx
}
return groupAst
}
RegExpParser.prototype.positiveInteger = function() {
var number = this.popChar()
// istanbul ignore next - can't ever get here due to previous lookahead checks
// still implementing this error checking in case this ever changes.
if (decimalPatternNoZero.test(number) === false) {
throw Error("Expecting a positive integer")
}
while (decimalPattern.test(this.peekChar(0))) {
number += this.popChar()
}
return parseInt(number, 10)
}
RegExpParser.prototype.integerIncludingZero = function() {
var number = this.popChar()
if (decimalPattern.test(number) === false) {
throw Error("Expecting an integer")
}
while (decimalPattern.test(this.peekChar(0))) {
number += this.popChar()
}
return parseInt(number, 10)
}
RegExpParser.prototype.patternCharacter = function() {
var nextChar = this.popChar()
switch (nextChar) {
// istanbul ignore next
case "\n":
// istanbul ignore next
case "\r":
// istanbul ignore next
case "\u2028":
// istanbul ignore next
case "\u2029":
// istanbul ignore next
case "^":
// istanbul ignore next
case "$":
// istanbul ignore next
case "\\":
// istanbul ignore next
case ".":
// istanbul ignore next
case "*":
// istanbul ignore next
case "+":
// istanbul ignore next
case "?":
// istanbul ignore next
case "(":
// istanbul ignore next
case ")":
// istanbul ignore next
case "[":
// istanbul ignore next
case "|":
// istanbul ignore next
throw Error("TBD")
default:
return { type: "Character", value: cc(nextChar) }
}
}
RegExpParser.prototype.isRegExpFlag = function() {
switch (this.peekChar(0)) {
case "g":
case "i":
case "m":
case "u":
case "y":
return true
default:
return false
}
}
RegExpParser.prototype.isRangeDash = function() {
return this.peekChar() === "-" && this.isClassAtom(1)
}
RegExpParser.prototype.isDigit = function() {
return decimalPattern.test(this.peekChar(0))
}
RegExpParser.prototype.isClassAtom = function(howMuch) {
if (howMuch === undefined) {
howMuch = 0
}
switch (this.peekChar(howMuch)) {
case "]":
case "\n":
case "\r":
case "\u2028":
case "\u2029":
return false
default:
return true
}
}
RegExpParser.prototype.isTerm = function() {
return this.isAtom() || this.isAssertion()
}
RegExpParser.prototype.isAtom = function() {
if (this.isPatternCharacter()) {
return true
}
switch (this.peekChar(0)) {
case ".":
case "\\": // atomEscape
case "[": // characterClass
// TODO: isAtom must be called before isAssertion - disambiguate
case "(": // group
return true
default:
return false
}
}
RegExpParser.prototype.isAssertion = function() {
switch (this.peekChar(0)) {
case "^":
case "$":
return true
// '\b' or '\B'
case "\\":
switch (this.peekChar(1)) {
case "b":
case "B":
return true
default:
return false
}
// '(?=' or '(?!'
case "(":
return (
this.peekChar(1) === "?" &&
(this.peekChar(2) === "=" || this.peekChar(2) === "!")
)
default:
return false
}
}
RegExpParser.prototype.isQuantifier = function() {
var prevState = this.saveState()
try {
return this.quantifier(true) !== undefined
} catch (e) {
return false
} finally {
this.restoreState(prevState)
}
}
RegExpParser.prototype.isPatternCharacter = function() {
switch (this.peekChar()) {
case "^":
case "$":
case "\\":
case ".":
case "*":
case "+":
case "?":
case "(":
case ")":
case "[":
case "|":
case "/":
case "\n":
case "\r":
case "\u2028":
case "\u2029":
return false
default:
return true
}
}
RegExpParser.prototype.parseHexDigits = function(howMany) {
var hexString = ""
for (var i = 0; i < howMany; i++) {
var hexChar = this.popChar()
if (hexDigitPattern.test(hexChar) === false) {
throw Error("Expecting a HexDecimal digits")
}
hexString += hexChar
}
var charCode = parseInt(hexString, 16)
return { type: "Character", value: charCode }
}
RegExpParser.prototype.peekChar = function(howMuch) {
if (howMuch === undefined) {
howMuch = 0
}
return this.input[this.idx + howMuch]
}
RegExpParser.prototype.popChar = function() {
var nextChar = this.peekChar(0)
this.consumeChar()
return nextChar
}
RegExpParser.prototype.consumeChar = function(char) {
if (char !== undefined && this.input[this.idx] !== char) {
throw Error(
"Expected: '" +
char +
"' but found: '" +
this.input[this.idx] +
"' at offset: " +
this.idx
)
}
if (this.idx >= this.input.length) {
throw Error("Unexpected end of input")
}
this.idx++
}
// consts and utilities
var hexDigitPattern = /[0-9a-fA-F]/
var decimalPattern = /[0-9]/
var decimalPatternNoZero = /[1-9]/
function cc(char) {
return char.charCodeAt(0)
}
function insertToSet(item, set) {
if (item.length !== undefined) {
item.forEach(function(subItem) {
set.push(subItem)
})
} else {
set.push(item)
}
}
function addFlag(flagObj, flagKey) {
if (flagObj[flagKey] === true) {
throw "duplicate flag " + flagKey
}
flagObj[flagKey] = true
}
function ASSERT_EXISTS(obj) {
// istanbul ignore next
if (obj === undefined) {
throw Error("Internal Error - Should never get here!")
}
}
// istanbul ignore next
function ASSERT_NEVER_REACH_HERE() {
throw Error("Internal Error - Should never get here!")
}
var i
var digitsCharCodes = []
for (i = cc("0"); i <= cc("9"); i++) {
digitsCharCodes.push(i)
}
var wordCharCodes = [cc("_")].concat(digitsCharCodes)
for (i = cc("a"); i <= cc("z"); i++) {
wordCharCodes.push(i)
}
for (i = cc("A"); i <= cc("Z"); i++) {
wordCharCodes.push(i)
}
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-classes
var whitespaceCodes = [
cc(" "),
cc("\f"),
cc("\n"),
cc("\r"),
cc("\t"),
cc("\v"),
cc("\t"),
cc("\u00a0"),
cc("\u1680"),
cc("\u2000"),
cc("\u2001"),
cc("\u2002"),
cc("\u2003"),
cc("\u2004"),
cc("\u2005"),
cc("\u2006"),
cc("\u2007"),
cc("\u2008"),
cc("\u2009"),
cc("\u200a"),
cc("\u2028"),
cc("\u2029"),
cc("\u202f"),
cc("\u205f"),
cc("\u3000"),
cc("\ufeff")
]
function BaseRegExpVisitor() {}
BaseRegExpVisitor.prototype.visitChildren = function(node) {
for (var key in node) {
var child = node[key]
/* istanbul ignore else */
if (node.hasOwnProperty(key)) {
if (child.type !== undefined) {
this.visit(child)
} else if (Array.isArray(child)) {
child.forEach(function(subChild) {
this.visit(subChild)
}, this)
}
}
}
}
BaseRegExpVisitor.prototype.visit = function(node) {
switch (node.type) {
case "Pattern":
this.visitPattern(node)
break
case "Flags":
this.visitFlags(node)
break
case "Disjunction":
this.visitDisjunction(node)
break
case "Alternative":
this.visitAlternative(node)
break
case "StartAnchor":
this.visitStartAnchor(node)
break
case "EndAnchor":
this.visitEndAnchor(node)
break
case "WordBoundary":
this.visitWordBoundary(node)
break
case "NonWordBoundary":
this.visitNonWordBoundary(node)
break
case "Lookahead":
this.visitLookahead(node)
break
case "NegativeLookahead":
this.visitNegativeLookahead(node)
break
case "Character":
this.visitCharacter(node)
break
case "Set":
this.visitSet(node)
break
case "Group":
this.visitGroup(node)
break
case "GroupBackReference":
this.visitGroupBackReference(node)
break
case "Quantifier":
this.visitQuantifier(node)
break
}
this.visitChildren(node)
}
BaseRegExpVisitor.prototype.visitPattern = function(node) {}
BaseRegExpVisitor.prototype.visitFlags = function(node) {}
BaseRegExpVisitor.prototype.visitDisjunction = function(node) {}
BaseRegExpVisitor.prototype.visitAlternative = function(node) {}
// Assertion
BaseRegExpVisitor.prototype.visitStartAnchor = function(node) {}
BaseRegExpVisitor.prototype.visitEndAnchor = function(node) {}
BaseRegExpVisitor.prototype.visitWordBoundary = function(node) {}
BaseRegExpVisitor.prototype.visitNonWordBoundary = function(node) {}
BaseRegExpVisitor.prototype.visitLookahead = function(node) {}
BaseRegExpVisitor.prototype.visitNegativeLookahead = function(node) {}
// atoms
BaseRegExpVisitor.prototype.visitCharacter = function(node) {}
BaseRegExpVisitor.prototype.visitSet = function(node) {}
BaseRegExpVisitor.prototype.visitGroup = function(node) {}
BaseRegExpVisitor.prototype.visitGroupBackReference = function(node) {}
BaseRegExpVisitor.prototype.visitQuantifier = function(node) {}
return {
RegExpParser: RegExpParser,
BaseRegExpVisitor: BaseRegExpVisitor,
VERSION: "0.4.0"
}
}
)
/***/ }),
/* 25 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ canMatchCharCode: () => (/* binding */ canMatchCharCode),
/* harmony export */ failedOptimizationPrefixMsg: () => (/* binding */ failedOptimizationPrefixMsg),
/* harmony export */ firstCharOptimizedIndices: () => (/* binding */ firstCharOptimizedIndices),
/* harmony export */ getOptimizedStartCodesIndices: () => (/* binding */ getOptimizedStartCodesIndices)
/* harmony export */ });
/* harmony import */ var regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(24);
/* harmony import */ var regexp_to_ast__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17);
/* harmony import */ var _reg_exp_parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(26);
/* harmony import */ var _lexer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(23);
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var complementErrorMessage = "Complement Sets are not supported for first char optimization";
var failedOptimizationPrefixMsg = 'Unable to use "first char" lexer optimizations:\n';
function getOptimizedStartCodesIndices(regExp, ensureOptimizations) {
if (ensureOptimizations === void 0) { ensureOptimizations = false; }
try {
var ast = (0,_reg_exp_parser__WEBPACK_IMPORTED_MODULE_2__.getRegExpAst)(regExp);
var firstChars = firstCharOptimizedIndices(ast.value, {}, ast.flags.ignoreCase);
return firstChars;
}
catch (e) {
/* istanbul ignore next */
// Testing this relies on the regexp-to-ast library having a bug... */
// TODO: only the else branch needs to be ignored, try to fix with newer prettier / tsc
if (e.message === complementErrorMessage) {
if (ensureOptimizations) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.PRINT_WARNING)("" + failedOptimizationPrefixMsg +
("\tUnable to optimize: < " + regExp.toString() + " >\n") +
"\tComplement Sets cannot be automatically optimized.\n" +
"\tThis will disable the lexer's first char optimizations.\n" +
"\tSee: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.");
}
}
else {
var msgSuffix = "";
if (ensureOptimizations) {
msgSuffix =
"\n\tThis will disable the lexer's first char optimizations.\n" +
"\tSee: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.";
}
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.PRINT_ERROR)(failedOptimizationPrefixMsg + "\n" +
("\tFailed parsing: < " + regExp.toString() + " >\n") +
("\tUsing the regexp-to-ast library version: " + regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__.VERSION + "\n") +
"\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues" +
msgSuffix);
}
}
return [];
}
function firstCharOptimizedIndices(ast, result, ignoreCase) {
switch (ast.type) {
case "Disjunction":
for (var i = 0; i < ast.value.length; i++) {
firstCharOptimizedIndices(ast.value[i], result, ignoreCase);
}
break;
case "Alternative":
var terms = ast.value;
for (var i = 0; i < terms.length; i++) {
var term = terms[i];
// skip terms that cannot effect the first char results
switch (term.type) {
case "EndAnchor":
// A group back reference cannot affect potential starting char.
// because if a back reference is the first production than automatically
// the group being referenced has had to come BEFORE so its codes have already been added
case "GroupBackReference":
// assertions do not affect potential starting codes
case "Lookahead":
case "NegativeLookahead":
case "StartAnchor":
case "WordBoundary":
case "NonWordBoundary":
continue;
}
var atom = term;
switch (atom.type) {
case "Character":
addOptimizedIdxToResult(atom.value, result, ignoreCase);
break;
case "Set":
if (atom.complement === true) {
throw Error(complementErrorMessage);
}
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(atom.value, function (code) {
if (typeof code === "number") {
addOptimizedIdxToResult(code, result, ignoreCase);
}
else {
// range
var range = code;
// cannot optimize when ignoreCase is
if (ignoreCase === true) {
for (var rangeCode = range.from; rangeCode <= range.to; rangeCode++) {
addOptimizedIdxToResult(rangeCode, result, ignoreCase);
}
}
// Optimization (2 orders of magnitude less work for very large ranges)
else {
// handle unoptimized values
for (var rangeCode = range.from; rangeCode <= range.to &&
rangeCode < _lexer__WEBPACK_IMPORTED_MODULE_3__.minOptimizationVal; rangeCode++) {
addOptimizedIdxToResult(rangeCode, result, ignoreCase);
}
// Less common charCode where we optimize for faster init time, by using larger "buckets"
if (range.to >= _lexer__WEBPACK_IMPORTED_MODULE_3__.minOptimizationVal) {
var minUnOptVal = range.from >= _lexer__WEBPACK_IMPORTED_MODULE_3__.minOptimizationVal
? range.from
: _lexer__WEBPACK_IMPORTED_MODULE_3__.minOptimizationVal;
var maxUnOptVal = range.to;
var minOptIdx = (0,_lexer__WEBPACK_IMPORTED_MODULE_3__.charCodeToOptimizedIndex)(minUnOptVal);
var maxOptIdx = (0,_lexer__WEBPACK_IMPORTED_MODULE_3__.charCodeToOptimizedIndex)(maxUnOptVal);
for (var currOptIdx = minOptIdx; currOptIdx <= maxOptIdx; currOptIdx++) {
result[currOptIdx] = currOptIdx;
}
}
}
}
});
break;
case "Group":
firstCharOptimizedIndices(atom.value, result, ignoreCase);
break;
/* istanbul ignore next */
default:
throw Error("Non Exhaustive Match");
}
// reached a mandatory production, no more **start** codes can be found on this alternative
var isOptionalQuantifier = atom.quantifier !== undefined &&
atom.quantifier.atLeast === 0;
if (
// A group may be optional due to empty contents /(?:)/
// or if everything inside it is optional /((a)?)/
(atom.type === "Group" &&
isWholeOptional(atom) === false) ||
// If this term is not a group it may only be optional if it has an optional quantifier
(atom.type !== "Group" && isOptionalQuantifier === false)) {
break;
}
}
break;
/* istanbul ignore next */
default:
throw Error("non exhaustive match!");
}
// console.log(Object.keys(result).length)
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.values)(result);
}
function addOptimizedIdxToResult(code, result, ignoreCase) {
var optimizedCharIdx = (0,_lexer__WEBPACK_IMPORTED_MODULE_3__.charCodeToOptimizedIndex)(code);
result[optimizedCharIdx] = optimizedCharIdx;
if (ignoreCase === true) {
handleIgnoreCase(code, result);
}
}
function handleIgnoreCase(code, result) {
var char = String.fromCharCode(code);
var upperChar = char.toUpperCase();
/* istanbul ignore else */
if (upperChar !== char) {
var optimizedCharIdx = (0,_lexer__WEBPACK_IMPORTED_MODULE_3__.charCodeToOptimizedIndex)(upperChar.charCodeAt(0));
result[optimizedCharIdx] = optimizedCharIdx;
}
else {
var lowerChar = char.toLowerCase();
if (lowerChar !== char) {
var optimizedCharIdx = (0,_lexer__WEBPACK_IMPORTED_MODULE_3__.charCodeToOptimizedIndex)(lowerChar.charCodeAt(0));
result[optimizedCharIdx] = optimizedCharIdx;
}
}
}
function findCode(setNode, targetCharCodes) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.find)(setNode.value, function (codeOrRange) {
if (typeof codeOrRange === "number") {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.contains)(targetCharCodes, codeOrRange);
}
else {
// range
var range_1 = codeOrRange;
return ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.find)(targetCharCodes, function (targetCode) {
return range_1.from <= targetCode && targetCode <= range_1.to;
}) !== undefined);
}
});
}
function isWholeOptional(ast) {
if (ast.quantifier && ast.quantifier.atLeast === 0) {
return true;
}
if (!ast.value) {
return false;
}
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isArray)(ast.value)
? (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.every)(ast.value, isWholeOptional)
: isWholeOptional(ast.value);
}
var CharCodeFinder = /** @class */ (function (_super) {
__extends(CharCodeFinder, _super);
function CharCodeFinder(targetCharCodes) {
var _this = _super.call(this) || this;
_this.targetCharCodes = targetCharCodes;
_this.found = false;
return _this;
}
CharCodeFinder.prototype.visitChildren = function (node) {
// No need to keep looking...
if (this.found === true) {
return;
}
// switch lookaheads as they do not actually consume any characters thus
// finding a charCode at lookahead context does not mean that regexp can actually contain it in a match.
switch (node.type) {
case "Lookahead":
this.visitLookahead(node);
return;
case "NegativeLookahead":
this.visitNegativeLookahead(node);
return;
}
_super.prototype.visitChildren.call(this, node);
};
CharCodeFinder.prototype.visitCharacter = function (node) {
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.contains)(this.targetCharCodes, node.value)) {
this.found = true;
}
};
CharCodeFinder.prototype.visitSet = function (node) {
if (node.complement) {
if (findCode(node, this.targetCharCodes) === undefined) {
this.found = true;
}
}
else {
if (findCode(node, this.targetCharCodes) !== undefined) {
this.found = true;
}
}
};
return CharCodeFinder;
}(regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__.BaseRegExpVisitor));
function canMatchCharCode(charCodes, pattern) {
if (pattern instanceof RegExp) {
var ast = (0,_reg_exp_parser__WEBPACK_IMPORTED_MODULE_2__.getRegExpAst)(pattern);
var charCodeFinder = new CharCodeFinder(charCodes);
charCodeFinder.visit(ast);
return charCodeFinder.found;
}
else {
return ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.find)(pattern, function (char) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.contains)(charCodes, char.charCodeAt(0));
}) !== undefined);
}
}
//# sourceMappingURL=reg_exp.js.map
/***/ }),
/* 26 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ clearRegExpParserCache: () => (/* binding */ clearRegExpParserCache),
/* harmony export */ getRegExpAst: () => (/* binding */ getRegExpAst)
/* harmony export */ });
/* harmony import */ var regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(24);
/* harmony import */ var regexp_to_ast__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__);
var regExpAstCache = {};
var regExpParser = new regexp_to_ast__WEBPACK_IMPORTED_MODULE_0__.RegExpParser();
function getRegExpAst(regExp) {
var regExpStr = regExp.toString();
if (regExpAstCache.hasOwnProperty(regExpStr)) {
return regExpAstCache[regExpStr];
}
else {
var regExpAst = regExpParser.pattern(regExpStr);
regExpAstCache[regExpStr] = regExpAst;
return regExpAst;
}
}
function clearRegExpParserCache() {
regExpAstCache = {};
}
//# sourceMappingURL=reg_exp_parser.js.map
/***/ }),
/* 27 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ assignCategoriesMapProp: () => (/* binding */ assignCategoriesMapProp),
/* harmony export */ assignCategoriesTokensProp: () => (/* binding */ assignCategoriesTokensProp),
/* harmony export */ assignTokenDefaultProps: () => (/* binding */ assignTokenDefaultProps),
/* harmony export */ augmentTokenTypes: () => (/* binding */ augmentTokenTypes),
/* harmony export */ expandCategories: () => (/* binding */ expandCategories),
/* harmony export */ hasCategoriesProperty: () => (/* binding */ hasCategoriesProperty),
/* harmony export */ hasExtendingTokensTypesMapProperty: () => (/* binding */ hasExtendingTokensTypesMapProperty),
/* harmony export */ hasExtendingTokensTypesProperty: () => (/* binding */ hasExtendingTokensTypesProperty),
/* harmony export */ hasShortKeyProperty: () => (/* binding */ hasShortKeyProperty),
/* harmony export */ isTokenType: () => (/* binding */ isTokenType),
/* harmony export */ singleAssignCategoriesToksMap: () => (/* binding */ singleAssignCategoriesToksMap),
/* harmony export */ tokenIdxToClass: () => (/* binding */ tokenIdxToClass),
/* harmony export */ tokenShortNameIdx: () => (/* binding */ tokenShortNameIdx),
/* harmony export */ tokenStructuredMatcher: () => (/* binding */ tokenStructuredMatcher),
/* harmony export */ tokenStructuredMatcherNoCategories: () => (/* binding */ tokenStructuredMatcherNoCategories)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
function tokenStructuredMatcher(tokInstance, tokConstructor) {
var instanceType = tokInstance.tokenTypeIdx;
if (instanceType === tokConstructor.tokenTypeIdx) {
return true;
}
else {
return (tokConstructor.isParent === true &&
tokConstructor.categoryMatchesMap[instanceType] === true);
}
}
// Optimized tokenMatcher in case our grammar does not use token categories
// Being so tiny it is much more likely to be in-lined and this avoid the function call overhead
function tokenStructuredMatcherNoCategories(token, tokType) {
return token.tokenTypeIdx === tokType.tokenTypeIdx;
}
var tokenShortNameIdx = 1;
var tokenIdxToClass = {};
function augmentTokenTypes(tokenTypes) {
// collect the parent Token Types as well.
var tokenTypesAndParents = expandCategories(tokenTypes);
// add required tokenType and categoryMatches properties
assignTokenDefaultProps(tokenTypesAndParents);
// fill up the categoryMatches
assignCategoriesMapProp(tokenTypesAndParents);
assignCategoriesTokensProp(tokenTypesAndParents);
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(tokenTypesAndParents, function (tokType) {
tokType.isParent = tokType.categoryMatches.length > 0;
});
}
function expandCategories(tokenTypes) {
var result = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.cloneArr)(tokenTypes);
var categories = tokenTypes;
var searching = true;
while (searching) {
categories = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.compact)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(categories, function (currTokType) { return currTokType.CATEGORIES; })));
var newCategories = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.difference)(categories, result);
result = result.concat(newCategories);
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(newCategories)) {
searching = false;
}
else {
categories = newCategories;
}
}
return result;
}
function assignTokenDefaultProps(tokenTypes) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(tokenTypes, function (currTokType) {
if (!hasShortKeyProperty(currTokType)) {
tokenIdxToClass[tokenShortNameIdx] = currTokType;
currTokType.tokenTypeIdx = tokenShortNameIdx++;
}
// CATEGORIES? : TokenType | TokenType[]
if (hasCategoriesProperty(currTokType) &&
!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isArray)(currTokType.CATEGORIES)
// &&
// !isUndefined(currTokType.CATEGORIES.PATTERN)
) {
currTokType.CATEGORIES = [currTokType.CATEGORIES];
}
if (!hasCategoriesProperty(currTokType)) {
currTokType.CATEGORIES = [];
}
if (!hasExtendingTokensTypesProperty(currTokType)) {
currTokType.categoryMatches = [];
}
if (!hasExtendingTokensTypesMapProperty(currTokType)) {
currTokType.categoryMatchesMap = {};
}
});
}
function assignCategoriesTokensProp(tokenTypes) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(tokenTypes, function (currTokType) {
// avoid duplications
currTokType.categoryMatches = [];
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(currTokType.categoryMatchesMap, function (val, key) {
currTokType.categoryMatches.push(tokenIdxToClass[key].tokenTypeIdx);
});
});
}
function assignCategoriesMapProp(tokenTypes) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(tokenTypes, function (currTokType) {
singleAssignCategoriesToksMap([], currTokType);
});
}
function singleAssignCategoriesToksMap(path, nextNode) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(path, function (pathNode) {
nextNode.categoryMatchesMap[pathNode.tokenTypeIdx] = true;
});
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(nextNode.CATEGORIES, function (nextCategory) {
var newPath = path.concat(nextNode);
// avoids infinite loops due to cyclic categories.
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains)(newPath, nextCategory)) {
singleAssignCategoriesToksMap(newPath, nextCategory);
}
});
}
function hasShortKeyProperty(tokType) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(tokType, "tokenTypeIdx");
}
function hasCategoriesProperty(tokType) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(tokType, "CATEGORIES");
}
function hasExtendingTokensTypesProperty(tokType) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(tokType, "categoryMatches");
}
function hasExtendingTokensTypesMapProperty(tokType) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(tokType, "categoryMatchesMap");
}
function isTokenType(tokType) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(tokType, "tokenTypeIdx");
}
//# sourceMappingURL=tokens.js.map
/***/ }),
/* 28 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ defaultLexerErrorProvider: () => (/* binding */ defaultLexerErrorProvider)
/* harmony export */ });
var defaultLexerErrorProvider = {
buildUnableToPopLexerModeMessage: function (token) {
return "Unable to pop Lexer Mode after encountering Token ->" + token.image + "<- The Mode Stack is empty";
},
buildUnexpectedCharactersMessage: function (fullText, startOffset, length, line, column) {
return ("unexpected character: ->" + fullText.charAt(startOffset) + "<- at offset: " + startOffset + "," + (" skipped " + length + " characters."));
}
};
//# sourceMappingURL=lexer_errors_public.js.map
/***/ }),
/* 29 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ first: () => (/* binding */ first),
/* harmony export */ firstForBranching: () => (/* binding */ firstForBranching),
/* harmony export */ firstForSequence: () => (/* binding */ firstForSequence),
/* harmony export */ firstForTerminal: () => (/* binding */ firstForTerminal)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20);
/* harmony import */ var _gast_gast__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(30);
function first(prod) {
/* istanbul ignore else */
if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.NonTerminal) {
// this could in theory cause infinite loops if
// (1) prod A refs prod B.
// (2) prod B refs prod A
// (3) AB can match the empty set
// in other words a cycle where everything is optional so the first will keep
// looking ahead for the next optional part and will never exit
// currently there is no safeguard for this unique edge case because
// (1) not sure a grammar in which this can happen is useful for anything (productive)
return first(prod.referencedRule);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Terminal) {
return firstForTerminal(prod);
}
else if ((0,_gast_gast__WEBPACK_IMPORTED_MODULE_2__.isSequenceProd)(prod)) {
return firstForSequence(prod);
}
else if ((0,_gast_gast__WEBPACK_IMPORTED_MODULE_2__.isBranchingProd)(prod)) {
return firstForBranching(prod);
}
else {
throw Error("non exhaustive match");
}
}
function firstForSequence(prod) {
var firstSet = [];
var seq = prod.definition;
var nextSubProdIdx = 0;
var hasInnerProdsRemaining = seq.length > nextSubProdIdx;
var currSubProd;
// so we enter the loop at least once (if the definition is not empty
var isLastInnerProdOptional = true;
// scan a sequence until it's end or until we have found a NONE optional production in it
while (hasInnerProdsRemaining && isLastInnerProdOptional) {
currSubProd = seq[nextSubProdIdx];
isLastInnerProdOptional = (0,_gast_gast__WEBPACK_IMPORTED_MODULE_2__.isOptionalProd)(currSubProd);
firstSet = firstSet.concat(first(currSubProd));
nextSubProdIdx = nextSubProdIdx + 1;
hasInnerProdsRemaining = seq.length > nextSubProdIdx;
}
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.uniq)(firstSet);
}
function firstForBranching(prod) {
var allAlternativesFirsts = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(prod.definition, function (innerProd) {
return first(innerProd);
});
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.uniq)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)(allAlternativesFirsts));
}
function firstForTerminal(terminal) {
return [terminal.terminalType];
}
//# sourceMappingURL=first.js.map
/***/ }),
/* 30 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ DslMethodsCollectorVisitor: () => (/* binding */ DslMethodsCollectorVisitor),
/* harmony export */ collectMethods: () => (/* binding */ collectMethods),
/* harmony export */ getProductionDslName: () => (/* binding */ getProductionDslName),
/* harmony export */ isBranchingProd: () => (/* binding */ isBranchingProd),
/* harmony export */ isOptionalProd: () => (/* binding */ isOptionalProd),
/* harmony export */ isSequenceProd: () => (/* binding */ isSequenceProd)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _gast_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20);
/* harmony import */ var _gast_visitor_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(31);
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
function isSequenceProd(prod) {
return (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Flat ||
prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Option ||
prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Repetition ||
prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatory ||
prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatoryWithSeparator ||
prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionWithSeparator ||
prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Terminal ||
prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Rule);
}
function isOptionalProd(prod, alreadyVisited) {
if (alreadyVisited === void 0) { alreadyVisited = []; }
var isDirectlyOptional = prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Option ||
prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Repetition ||
prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionWithSeparator;
if (isDirectlyOptional) {
return true;
}
// note that this can cause infinite loop if one optional empty TOP production has a cyclic dependency with another
// empty optional top rule
// may be indirectly optional ((A?B?C?) | (D?E?F?))
if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Alternation) {
// for OR its enough for just one of the alternatives to be optional
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.some)(prod.definition, function (subProd) {
return isOptionalProd(subProd, alreadyVisited);
});
}
else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.NonTerminal && (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains)(alreadyVisited, prod)) {
// avoiding stack overflow due to infinite recursion
return false;
}
else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.AbstractProduction) {
if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.NonTerminal) {
alreadyVisited.push(prod);
}
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(prod.definition, function (subProd) {
return isOptionalProd(subProd, alreadyVisited);
});
}
else {
return false;
}
}
function isBranchingProd(prod) {
return prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Alternation;
}
function getProductionDslName(prod) {
/* istanbul ignore else */
if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.NonTerminal) {
return "SUBRULE";
}
else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Option) {
return "OPTION";
}
else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Alternation) {
return "OR";
}
else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatory) {
return "AT_LEAST_ONE";
}
else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatoryWithSeparator) {
return "AT_LEAST_ONE_SEP";
}
else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionWithSeparator) {
return "MANY_SEP";
}
else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Repetition) {
return "MANY";
}
else if (prod instanceof _gast_public__WEBPACK_IMPORTED_MODULE_1__.Terminal) {
return "CONSUME";
}
else {
throw Error("non exhaustive match");
}
}
var DslMethodsCollectorVisitor = /** @class */ (function (_super) {
__extends(DslMethodsCollectorVisitor, _super);
function DslMethodsCollectorVisitor() {
var _this = _super !== null && _super.apply(this, arguments) || this;
// A minus is never valid in an identifier name
_this.separator = "-";
_this.dslMethods = {
option: [],
alternation: [],
repetition: [],
repetitionWithSeparator: [],
repetitionMandatory: [],
repetitionMandatoryWithSeparator: []
};
return _this;
}
DslMethodsCollectorVisitor.prototype.reset = function () {
this.dslMethods = {
option: [],
alternation: [],
repetition: [],
repetitionWithSeparator: [],
repetitionMandatory: [],
repetitionMandatoryWithSeparator: []
};
};
DslMethodsCollectorVisitor.prototype.visitTerminal = function (terminal) {
var key = terminal.terminalType.name + this.separator + "Terminal";
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(this.dslMethods, key)) {
this.dslMethods[key] = [];
}
this.dslMethods[key].push(terminal);
};
DslMethodsCollectorVisitor.prototype.visitNonTerminal = function (subrule) {
var key = subrule.nonTerminalName + this.separator + "Terminal";
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(this.dslMethods, key)) {
this.dslMethods[key] = [];
}
this.dslMethods[key].push(subrule);
};
DslMethodsCollectorVisitor.prototype.visitOption = function (option) {
this.dslMethods.option.push(option);
};
DslMethodsCollectorVisitor.prototype.visitRepetitionWithSeparator = function (manySep) {
this.dslMethods.repetitionWithSeparator.push(manySep);
};
DslMethodsCollectorVisitor.prototype.visitRepetitionMandatory = function (atLeastOne) {
this.dslMethods.repetitionMandatory.push(atLeastOne);
};
DslMethodsCollectorVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) {
this.dslMethods.repetitionMandatoryWithSeparator.push(atLeastOneSep);
};
DslMethodsCollectorVisitor.prototype.visitRepetition = function (many) {
this.dslMethods.repetition.push(many);
};
DslMethodsCollectorVisitor.prototype.visitAlternation = function (or) {
this.dslMethods.alternation.push(or);
};
return DslMethodsCollectorVisitor;
}(_gast_visitor_public__WEBPACK_IMPORTED_MODULE_2__.GAstVisitor));
var collectorVisitor = new DslMethodsCollectorVisitor();
function collectMethods(rule) {
collectorVisitor.reset();
rule.accept(collectorVisitor);
var dslMethods = collectorVisitor.dslMethods;
// avoid uncleaned references
collectorVisitor.reset();
return dslMethods;
}
//# sourceMappingURL=gast.js.map
/***/ }),
/* 31 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ GAstVisitor: () => (/* binding */ GAstVisitor)
/* harmony export */ });
/* harmony import */ var _gast_public__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(20);
var GAstVisitor = /** @class */ (function () {
function GAstVisitor() {
}
GAstVisitor.prototype.visit = function (node) {
var nodeAny = node;
switch (nodeAny.constructor) {
case _gast_public__WEBPACK_IMPORTED_MODULE_0__.NonTerminal:
return this.visitNonTerminal(nodeAny);
case _gast_public__WEBPACK_IMPORTED_MODULE_0__.Flat:
return this.visitFlat(nodeAny);
case _gast_public__WEBPACK_IMPORTED_MODULE_0__.Option:
return this.visitOption(nodeAny);
case _gast_public__WEBPACK_IMPORTED_MODULE_0__.RepetitionMandatory:
return this.visitRepetitionMandatory(nodeAny);
case _gast_public__WEBPACK_IMPORTED_MODULE_0__.RepetitionMandatoryWithSeparator:
return this.visitRepetitionMandatoryWithSeparator(nodeAny);
case _gast_public__WEBPACK_IMPORTED_MODULE_0__.RepetitionWithSeparator:
return this.visitRepetitionWithSeparator(nodeAny);
case _gast_public__WEBPACK_IMPORTED_MODULE_0__.Repetition:
return this.visitRepetition(nodeAny);
case _gast_public__WEBPACK_IMPORTED_MODULE_0__.Alternation:
return this.visitAlternation(nodeAny);
case _gast_public__WEBPACK_IMPORTED_MODULE_0__.Terminal:
return this.visitTerminal(nodeAny);
case _gast_public__WEBPACK_IMPORTED_MODULE_0__.Rule:
return this.visitRule(nodeAny);
/* istanbul ignore next */
default:
throw Error("non exhaustive match");
}
};
GAstVisitor.prototype.visitNonTerminal = function (node) { };
GAstVisitor.prototype.visitFlat = function (node) { };
GAstVisitor.prototype.visitOption = function (node) { };
GAstVisitor.prototype.visitRepetition = function (node) { };
GAstVisitor.prototype.visitRepetitionMandatory = function (node) { };
GAstVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { };
GAstVisitor.prototype.visitRepetitionWithSeparator = function (node) { };
GAstVisitor.prototype.visitAlternation = function (node) { };
GAstVisitor.prototype.visitTerminal = function (node) { };
GAstVisitor.prototype.visitRule = function (node) { };
return GAstVisitor;
}());
//# sourceMappingURL=gast_visitor_public.js.map
/***/ }),
/* 32 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ IN: () => (/* binding */ IN)
/* harmony export */ });
// TODO: can this be removed? where is it used?
var IN = "_~IN~_";
//# sourceMappingURL=constants.js.map
/***/ }),
/* 33 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ NamedDSLMethodsCollectorVisitor: () => (/* binding */ NamedDSLMethodsCollectorVisitor),
/* harmony export */ addNoneTerminalToCst: () => (/* binding */ addNoneTerminalToCst),
/* harmony export */ addTerminalToCst: () => (/* binding */ addTerminalToCst),
/* harmony export */ expandAllNestedRuleNames: () => (/* binding */ expandAllNestedRuleNames),
/* harmony export */ setNodeLocationFull: () => (/* binding */ setNodeLocationFull),
/* harmony export */ setNodeLocationOnlyOffset: () => (/* binding */ setNodeLocationOnlyOffset)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _grammar_keys__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(34);
/* harmony import */ var _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(20);
/* harmony import */ var _grammar_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(31);
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/**
* This nodeLocation tracking is not efficient and should only be used
* when error recovery is enabled or the Token Vector contains virtual Tokens
* (e.g, Python Indent/Outdent)
* As it executes the calculation for every single terminal/nonTerminal
* and does not rely on the fact the token vector is **sorted**
*/
function setNodeLocationOnlyOffset(currNodeLocation, newLocationInfo) {
// First (valid) update for this cst node
if (isNaN(currNodeLocation.startOffset) === true) {
// assumption1: Token location information is either NaN or a valid number
// assumption2: Token location information is fully valid if it exist
// (both start/end offsets exist and are numbers).
currNodeLocation.startOffset = newLocationInfo.startOffset;
currNodeLocation.endOffset = newLocationInfo.endOffset;
}
// Once the startOffset has been updated with a valid number it should never receive
// any farther updates as the Token vector is sorted.
// We still have to check this this condition for every new possible location info
// because with error recovery enabled we may encounter invalid tokens (NaN location props)
else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) {
currNodeLocation.endOffset = newLocationInfo.endOffset;
}
}
/**
* This nodeLocation tracking is not efficient and should only be used
* when error recovery is enabled or the Token Vector contains virtual Tokens
* (e.g, Python Indent/Outdent)
* As it executes the calculation for every single terminal/nonTerminal
* and does not rely on the fact the token vector is **sorted**
*/
function setNodeLocationFull(currNodeLocation, newLocationInfo) {
// First (valid) update for this cst node
if (isNaN(currNodeLocation.startOffset) === true) {
// assumption1: Token location information is either NaN or a valid number
// assumption2: Token location information is fully valid if it exist
// (all start/end props exist and are numbers).
currNodeLocation.startOffset = newLocationInfo.startOffset;
currNodeLocation.startColumn = newLocationInfo.startColumn;
currNodeLocation.startLine = newLocationInfo.startLine;
currNodeLocation.endOffset = newLocationInfo.endOffset;
currNodeLocation.endColumn = newLocationInfo.endColumn;
currNodeLocation.endLine = newLocationInfo.endLine;
}
// Once the start props has been updated with a valid number it should never receive
// any farther updates as the Token vector is sorted.
// We still have to check this this condition for every new possible location info
// because with error recovery enabled we may encounter invalid tokens (NaN location props)
else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) {
currNodeLocation.endOffset = newLocationInfo.endOffset;
currNodeLocation.endColumn = newLocationInfo.endColumn;
currNodeLocation.endLine = newLocationInfo.endLine;
}
}
function addTerminalToCst(node, token, tokenTypeName) {
if (node.children[tokenTypeName] === undefined) {
node.children[tokenTypeName] = [token];
}
else {
node.children[tokenTypeName].push(token);
}
}
function addNoneTerminalToCst(node, ruleName, ruleResult) {
if (node.children[ruleName] === undefined) {
node.children[ruleName] = [ruleResult];
}
else {
node.children[ruleName].push(ruleResult);
}
}
var NamedDSLMethodsCollectorVisitor = /** @class */ (function (_super) {
__extends(NamedDSLMethodsCollectorVisitor, _super);
function NamedDSLMethodsCollectorVisitor(ruleIdx) {
var _this = _super.call(this) || this;
_this.result = [];
_this.ruleIdx = ruleIdx;
return _this;
}
NamedDSLMethodsCollectorVisitor.prototype.collectNamedDSLMethod = function (node, newNodeConstructor, methodIdx) {
// TODO: better hack to copy what we need here...
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(node.name)) {
// copy without name so this will indeed be processed later.
var nameLessNode
/* istanbul ignore else */
= void 0;
/* istanbul ignore else */
if (node instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Option ||
node instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Repetition ||
node instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.RepetitionMandatory ||
node instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Alternation) {
nameLessNode = new newNodeConstructor({
definition: node.definition,
idx: node.idx
});
}
else if (node instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.RepetitionMandatoryWithSeparator ||
node instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.RepetitionWithSeparator) {
nameLessNode = new newNodeConstructor({
definition: node.definition,
idx: node.idx,
separator: node.separator
});
}
else {
throw Error("non exhaustive match");
}
var def = [nameLessNode];
var key = (0,_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.getKeyForAutomaticLookahead)(this.ruleIdx, methodIdx, node.idx);
this.result.push({ def: def, key: key, name: node.name, orgProd: node });
}
};
NamedDSLMethodsCollectorVisitor.prototype.visitOption = function (node) {
this.collectNamedDSLMethod(node, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Option, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OPTION_IDX);
};
NamedDSLMethodsCollectorVisitor.prototype.visitRepetition = function (node) {
this.collectNamedDSLMethod(node, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Repetition, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_IDX);
};
NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionMandatory = function (node) {
this.collectNamedDSLMethod(node, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.RepetitionMandatory, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_IDX);
};
NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) {
this.collectNamedDSLMethod(node, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.RepetitionMandatoryWithSeparator, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_SEP_IDX);
};
NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionWithSeparator = function (node) {
this.collectNamedDSLMethod(node, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.RepetitionWithSeparator, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_SEP_IDX);
};
NamedDSLMethodsCollectorVisitor.prototype.visitAlternation = function (node) {
var _this = this;
this.collectNamedDSLMethod(node, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Alternation, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OR_IDX);
var hasMoreThanOneAlternative = node.definition.length > 1;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(node.definition, function (currFlatAlt, altIdx) {
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(currFlatAlt.name)) {
var def = currFlatAlt.definition;
if (hasMoreThanOneAlternative) {
def = [new _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Option({ definition: currFlatAlt.definition })];
}
else {
// mandatory
def = currFlatAlt.definition;
}
var key = (0,_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.getKeyForAltIndex)(_this.ruleIdx, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OR_IDX, node.idx, altIdx);
_this.result.push({
def: def,
key: key,
name: currFlatAlt.name,
orgProd: currFlatAlt
});
}
});
};
return NamedDSLMethodsCollectorVisitor;
}(_grammar_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_3__.GAstVisitor));
function expandAllNestedRuleNames(topRules, fullToShortName) {
var result = {
allRuleNames: []
};
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(topRules, function (currTopRule) {
var currTopRuleShortName = fullToShortName[currTopRule.name];
result.allRuleNames.push(currTopRule.name);
var namedCollectorVisitor = new NamedDSLMethodsCollectorVisitor(currTopRuleShortName);
currTopRule.accept(namedCollectorVisitor);
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(namedCollectorVisitor.result, function (_a) {
var def = _a.def, key = _a.key, name = _a.name;
result.allRuleNames.push(currTopRule.name + name);
});
});
return result;
}
//# sourceMappingURL=cst.js.map
/***/ }),
/* 34 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AT_LEAST_ONE_IDX: () => (/* binding */ AT_LEAST_ONE_IDX),
/* harmony export */ AT_LEAST_ONE_SEP_IDX: () => (/* binding */ AT_LEAST_ONE_SEP_IDX),
/* harmony export */ BITS_FOR_ALT_IDX: () => (/* binding */ BITS_FOR_ALT_IDX),
/* harmony export */ BITS_FOR_METHOD_TYPE: () => (/* binding */ BITS_FOR_METHOD_TYPE),
/* harmony export */ BITS_FOR_OCCURRENCE_IDX: () => (/* binding */ BITS_FOR_OCCURRENCE_IDX),
/* harmony export */ BITS_FOR_RULE_IDX: () => (/* binding */ BITS_FOR_RULE_IDX),
/* harmony export */ MANY_IDX: () => (/* binding */ MANY_IDX),
/* harmony export */ MANY_SEP_IDX: () => (/* binding */ MANY_SEP_IDX),
/* harmony export */ OPTION_IDX: () => (/* binding */ OPTION_IDX),
/* harmony export */ OR_IDX: () => (/* binding */ OR_IDX),
/* harmony export */ getKeyForAltIndex: () => (/* binding */ getKeyForAltIndex),
/* harmony export */ getKeyForAutomaticLookahead: () => (/* binding */ getKeyForAutomaticLookahead)
/* harmony export */ });
// Lookahead keys are 32Bit integers in the form
// TTTTTTTT-ZZZZZZZZZZZZ-YYYY-XXXXXXXX
// XXXX -> Occurrence Index bitmap.
// YYYY -> DSL Method Type bitmap.
// ZZZZZZZZZZZZZZZ -> Rule short Index bitmap.
// TTTTTTTTT -> alternation alternative index bitmap
var BITS_FOR_METHOD_TYPE = 4;
var BITS_FOR_OCCURRENCE_IDX = 8;
var BITS_FOR_RULE_IDX = 12;
// TODO: validation, this means that there may at most 2^8 --> 256 alternatives for an alternation.
var BITS_FOR_ALT_IDX = 8;
// short string used as part of mapping keys.
// being short improves the performance when composing KEYS for maps out of these
// The 5 - 8 bits (16 possible values, are reserved for the DSL method indices)
/* tslint:disable */
var OR_IDX = 1 << BITS_FOR_OCCURRENCE_IDX;
var OPTION_IDX = 2 << BITS_FOR_OCCURRENCE_IDX;
var MANY_IDX = 3 << BITS_FOR_OCCURRENCE_IDX;
var AT_LEAST_ONE_IDX = 4 << BITS_FOR_OCCURRENCE_IDX;
var MANY_SEP_IDX = 5 << BITS_FOR_OCCURRENCE_IDX;
var AT_LEAST_ONE_SEP_IDX = 6 << BITS_FOR_OCCURRENCE_IDX;
/* tslint:enable */
// this actually returns a number, but it is always used as a string (object prop key)
function getKeyForAutomaticLookahead(ruleIdx, dslMethodIdx, occurrence) {
/* tslint:disable */
return occurrence | dslMethodIdx | ruleIdx;
/* tslint:enable */
}
var BITS_START_FOR_ALT_IDX = 32 - BITS_FOR_ALT_IDX;
function getKeyForAltIndex(ruleIdx, dslMethodIdx, occurrence, altIdx) {
/* tslint:disable */
// alternative indices are zero based, thus must always add one (turn on one bit) to guarantee uniqueness.
var altIdxBitMap = (altIdx + 1) << BITS_START_FOR_ALT_IDX;
return (getKeyForAutomaticLookahead(ruleIdx, dslMethodIdx, occurrence) |
altIdxBitMap);
/* tslint:enable */
}
//# sourceMappingURL=keys.js.map
/***/ }),
/* 35 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ defaultGrammarResolverErrorProvider: () => (/* binding */ defaultGrammarResolverErrorProvider),
/* harmony export */ defaultGrammarValidatorErrorProvider: () => (/* binding */ defaultGrammarValidatorErrorProvider),
/* harmony export */ defaultParserErrorProvider: () => (/* binding */ defaultParserErrorProvider)
/* harmony export */ });
/* harmony import */ var _scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17);
/* harmony import */ var _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(20);
/* harmony import */ var _grammar_gast_gast__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(30);
/* harmony import */ var _grammar_checks__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(36);
var defaultParserErrorProvider = {
buildMismatchTokenMessage: function (_a) {
var expected = _a.expected, actual = _a.actual, previous = _a.previous, ruleName = _a.ruleName;
var hasLabel = (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.hasTokenLabel)(expected);
var expectedMsg = hasLabel
? "--> " + (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.tokenLabel)(expected) + " <--"
: "token of type --> " + expected.name + " <--";
var msg = "Expecting " + expectedMsg + " but found --> '" + actual.image + "' <--";
return msg;
},
buildNotAllInputParsedMessage: function (_a) {
var firstRedundant = _a.firstRedundant, ruleName = _a.ruleName;
return ("Redundant input, expecting EOF but found: " + firstRedundant.image);
},
buildNoViableAltMessage: function (_a) {
var expectedPathsPerAlt = _a.expectedPathsPerAlt, actual = _a.actual, previous = _a.previous, customUserDescription = _a.customUserDescription, ruleName = _a.ruleName;
var errPrefix = "Expecting: ";
// TODO: issue: No Viable Alternative Error may have incomplete details. #502
var actualText = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(actual).image;
var errSuffix = "\nbut found: '" + actualText + "'";
if (customUserDescription) {
return errPrefix + customUserDescription + errSuffix;
}
else {
var allLookAheadPaths = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.reduce)(expectedPathsPerAlt, function (result, currAltPaths) { return result.concat(currAltPaths); }, []);
var nextValidTokenSequences = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(allLookAheadPaths, function (currPath) {
return "[" + (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(currPath, function (currTokenType) {
return (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.tokenLabel)(currTokenType);
}).join(", ") + "]";
});
var nextValidSequenceItems = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(nextValidTokenSequences, function (itemMsg, idx) { return " " + (idx + 1) + ". " + itemMsg; });
var calculatedDescription = "one of these possible Token sequences:\n" + nextValidSequenceItems.join("\n");
return errPrefix + calculatedDescription + errSuffix;
}
},
buildEarlyExitMessage: function (_a) {
var expectedIterationPaths = _a.expectedIterationPaths, actual = _a.actual, customUserDescription = _a.customUserDescription, ruleName = _a.ruleName;
var errPrefix = "Expecting: ";
// TODO: issue: No Viable Alternative Error may have incomplete details. #502
var actualText = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(actual).image;
var errSuffix = "\nbut found: '" + actualText + "'";
if (customUserDescription) {
return errPrefix + customUserDescription + errSuffix;
}
else {
var nextValidTokenSequences = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(expectedIterationPaths, function (currPath) {
return "[" + (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(currPath, function (currTokenType) {
return (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.tokenLabel)(currTokenType);
}).join(",") + "]";
});
var calculatedDescription = "expecting at least one iteration which starts with one of these possible Token sequences::\n " +
("<" + nextValidTokenSequences.join(" ,") + ">");
return errPrefix + calculatedDescription + errSuffix;
}
}
};
Object.freeze(defaultParserErrorProvider);
var defaultGrammarResolverErrorProvider = {
buildRuleNotFoundError: function (topLevelRule, undefinedRule) {
var msg = "Invalid grammar, reference to a rule which is not defined: ->" +
undefinedRule.nonTerminalName +
"<-\n" +
"inside top level rule: ->" +
topLevelRule.name +
"<-";
return msg;
}
};
var defaultGrammarValidatorErrorProvider = {
buildDuplicateFoundError: function (topLevelRule, duplicateProds) {
function getExtraProductionArgument(prod) {
if (prod instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Terminal) {
return prod.terminalType.name;
}
else if (prod instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.NonTerminal) {
return prod.nonTerminalName;
}
else {
return "";
}
}
var topLevelName = topLevelRule.name;
var duplicateProd = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(duplicateProds);
var index = duplicateProd.idx;
var dslName = (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_3__.getProductionDslName)(duplicateProd);
var extraArgument = getExtraProductionArgument(duplicateProd);
var hasExplicitIndex = index > 0;
var msg = "->" + dslName + (hasExplicitIndex ? index : "") + "<- " + (extraArgument ? "with argument: ->" + extraArgument + "<-" : "") + "\n appears more than once (" + duplicateProds.length + " times) in the top level rule: ->" + topLevelName + "<-. \n For further details see: https://sap.github.io/chevrotain/docs/FAQ.html#NUMERICAL_SUFFIXES \n ";
// white space trimming time! better to trim afterwards as it allows to use WELL formatted multi line template strings...
msg = msg.replace(/[ \t]+/g, " ");
msg = msg.replace(/\s\s+/g, "\n");
return msg;
},
buildInvalidNestedRuleNameError: function (topLevelRule, nestedProd) {
var msg = "Invalid nested rule name: ->" + nestedProd.name + "<- inside rule: ->" + topLevelRule.name + "<-\n" +
("it must match the pattern: ->" + _grammar_checks__WEBPACK_IMPORTED_MODULE_4__.validNestedRuleName.toString() + "<-.\n") +
"Note that this means a nested rule name must start with the '$'(dollar) sign.";
return msg;
},
buildDuplicateNestedRuleNameError: function (topLevelRule, nestedProd) {
var duplicateName = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(nestedProd).name;
var errMsg = "Duplicate nested rule name: ->" + duplicateName + "<- inside rule: ->" + topLevelRule.name + "<-\n" +
"A nested name must be unique in the scope of a top level grammar rule.";
return errMsg;
},
buildNamespaceConflictError: function (rule) {
var errMsg = "Namespace conflict found in grammar.\n" +
("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <" + rule.name + ">.\n") +
"To resolve this make sure each Terminal and Non-Terminal names are unique\n" +
"This is easy to accomplish by using the convention that Terminal names start with an uppercase letter\n" +
"and Non-Terminal names start with a lower case letter.";
return errMsg;
},
buildAlternationPrefixAmbiguityError: function (options) {
var pathMsg = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(options.prefixPath, function (currTok) {
return (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.tokenLabel)(currTok);
}).join(", ");
var occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx;
var errMsg = "Ambiguous alternatives: <" + options.ambiguityIndices.join(" ,") + "> due to common lookahead prefix\n" +
("in <OR" + occurrence + "> inside <" + options.topLevelRule.name + "> Rule,\n") +
("<" + pathMsg + "> may appears as a prefix path in all these alternatives.\n") +
"See: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX\n" +
"For Further details.";
return errMsg;
},
buildAlternationAmbiguityError: function (options) {
var pathMsg = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(options.prefixPath, function (currtok) {
return (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.tokenLabel)(currtok);
}).join(", ");
var occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx;
var currMessage = "Ambiguous Alternatives Detected: <" + options.ambiguityIndices.join(" ,") + "> in <OR" + occurrence + ">" +
(" inside <" + options.topLevelRule.name + "> Rule,\n") +
("<" + pathMsg + "> may appears as a prefix path in all these alternatives.\n");
currMessage =
currMessage +
"See: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\n" +
"For Further details.";
return currMessage;
},
buildEmptyRepetitionError: function (options) {
var dslName = (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_3__.getProductionDslName)(options.repetition);
if (options.repetition.idx !== 0) {
dslName += options.repetition.idx;
}
var errMsg = "The repetition <" + dslName + "> within Rule <" + options.topLevelRule.name + "> can never consume any tokens.\n" +
"This could lead to an infinite loop.";
return errMsg;
},
buildTokenNameError: function (options) {
var tokTypeName = options.tokenType.name;
var errMsg = "Invalid Grammar Token name: ->" + tokTypeName + "<- it must match the pattern: ->" + options.expectedPattern.toString() + "<-";
return errMsg;
},
buildEmptyAlternationError: function (options) {
var errMsg = "Ambiguous empty alternative: <" + (options.emptyChoiceIdx + 1) + ">" +
(" in <OR" + options.alternation.idx + "> inside <" + options.topLevelRule.name + "> Rule.\n") +
"Only the last alternative may be an empty alternative.";
return errMsg;
},
buildTooManyAlternativesError: function (options) {
var errMsg = "An Alternation cannot have more than 256 alternatives:\n" +
("<OR" + options.alternation.idx + "> inside <" + options.topLevelRule.name + "> Rule.\n has " + (options.alternation.definition.length +
1) + " alternatives.");
return errMsg;
},
buildLeftRecursionError: function (options) {
var ruleName = options.topLevelRule.name;
var pathNames = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.map(options.leftRecursionPath, function (currRule) { return currRule.name; });
var leftRecursivePath = ruleName + " --> " + pathNames
.concat([ruleName])
.join(" --> ");
var errMsg = "Left Recursion found in grammar.\n" +
("rule: <" + ruleName + "> can be invoked from itself (directly or indirectly)\n") +
("without consuming any Tokens. The grammar path that causes this is: \n " + leftRecursivePath + "\n") +
" To fix this refactor your grammar to remove the left recursion.\n" +
"see: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring.";
return errMsg;
},
buildInvalidRuleNameError: function (options) {
var ruleName = options.topLevelRule.name;
var expectedPatternString = options.expectedPattern.toString();
var errMsg = "Invalid grammar rule name: ->" + ruleName + "<- it must match the pattern: ->" + expectedPatternString + "<-";
return errMsg;
},
buildDuplicateRuleNameError: function (options) {
var ruleName;
if (options.topLevelRule instanceof _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_2__.Rule) {
ruleName = options.topLevelRule.name;
}
else {
ruleName = options.topLevelRule;
}
var errMsg = "Duplicate definition, rule: ->" + ruleName + "<- is already defined in the grammar: ->" + options.grammarName + "<-";
return errMsg;
}
};
//# sourceMappingURL=errors_public.js.map
/***/ }),
/* 36 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ OccurrenceValidationCollector: () => (/* binding */ OccurrenceValidationCollector),
/* harmony export */ RepetionCollector: () => (/* binding */ RepetionCollector),
/* harmony export */ checkPrefixAlternativesAmbiguities: () => (/* binding */ checkPrefixAlternativesAmbiguities),
/* harmony export */ getFirstNoneTerminal: () => (/* binding */ getFirstNoneTerminal),
/* harmony export */ identifyProductionForDuplicates: () => (/* binding */ identifyProductionForDuplicates),
/* harmony export */ validNestedRuleName: () => (/* binding */ validNestedRuleName),
/* harmony export */ validTermsPattern: () => (/* binding */ validTermsPattern),
/* harmony export */ validateAmbiguousAlternationAlternatives: () => (/* binding */ validateAmbiguousAlternationAlternatives),
/* harmony export */ validateEmptyOrAlternative: () => (/* binding */ validateEmptyOrAlternative),
/* harmony export */ validateGrammar: () => (/* binding */ validateGrammar),
/* harmony export */ validateNestedRuleName: () => (/* binding */ validateNestedRuleName),
/* harmony export */ validateNoLeftRecursion: () => (/* binding */ validateNoLeftRecursion),
/* harmony export */ validateRuleDoesNotAlreadyExist: () => (/* binding */ validateRuleDoesNotAlreadyExist),
/* harmony export */ validateRuleIsOverridden: () => (/* binding */ validateRuleIsOverridden),
/* harmony export */ validateRuleName: () => (/* binding */ validateRuleName),
/* harmony export */ validateSomeNonEmptyLookaheadPath: () => (/* binding */ validateSomeNonEmptyLookaheadPath),
/* harmony export */ validateTokenName: () => (/* binding */ validateTokenName),
/* harmony export */ validateTooManyAlts: () => (/* binding */ validateTooManyAlts)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _parser_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16);
/* harmony import */ var _gast_gast__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(30);
/* harmony import */ var _lookahead__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(37);
/* harmony import */ var _cst_cst__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(33);
/* harmony import */ var _interpreter__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(38);
/* harmony import */ var _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(20);
/* harmony import */ var _gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(31);
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
function validateGrammar(topLevels, globalMaxLookahead, tokenTypes, ignoredIssues, errMsgProvider, grammarName) {
var duplicateErrors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(topLevels, function (currTopLevel) {
return validateDuplicateProductions(currTopLevel, errMsgProvider);
});
var leftRecursionErrors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(topLevels, function (currTopRule) {
return validateNoLeftRecursion(currTopRule, currTopRule, errMsgProvider);
});
var emptyAltErrors = [];
var ambiguousAltsErrors = [];
var emptyRepetitionErrors = [];
// left recursion could cause infinite loops in the following validations.
// It is safest to first have the user fix the left recursion errors first and only then examine Further issues.
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(leftRecursionErrors, _utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)) {
emptyAltErrors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(topLevels, function (currTopRule) {
return validateEmptyOrAlternative(currTopRule, errMsgProvider);
});
ambiguousAltsErrors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(topLevels, function (currTopRule) {
return validateAmbiguousAlternationAlternatives(currTopRule, globalMaxLookahead, ignoredIssues, errMsgProvider);
});
emptyRepetitionErrors = validateSomeNonEmptyLookaheadPath(topLevels, globalMaxLookahead, errMsgProvider);
}
var termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider);
var tokenNameErrors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(tokenTypes, function (currTokType) {
return validateTokenName(currTokType, errMsgProvider);
});
var nestedRulesNameErrors = validateNestedRulesNames(topLevels, errMsgProvider);
var nestedRulesDuplicateErrors = validateDuplicateNestedRules(topLevels, errMsgProvider);
var tooManyAltsErrors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(topLevels, function (curRule) {
return validateTooManyAlts(curRule, errMsgProvider);
});
var ruleNameErrors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(topLevels, function (curRule) {
return validateRuleName(curRule, errMsgProvider);
});
var duplicateRulesError = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(topLevels, function (curRule) {
return validateRuleDoesNotAlreadyExist(curRule, topLevels, grammarName, errMsgProvider);
});
return (_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten(duplicateErrors.concat(tokenNameErrors, nestedRulesNameErrors, nestedRulesDuplicateErrors, emptyRepetitionErrors, leftRecursionErrors, emptyAltErrors, ambiguousAltsErrors, termsNamespaceConflictErrors, tooManyAltsErrors, ruleNameErrors, duplicateRulesError)));
}
function validateNestedRulesNames(topLevels, errMsgProvider) {
var result = [];
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(topLevels, function (curTopLevel) {
var namedCollectorVisitor = new _cst_cst__WEBPACK_IMPORTED_MODULE_4__.NamedDSLMethodsCollectorVisitor("");
curTopLevel.accept(namedCollectorVisitor);
var nestedProds = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(namedCollectorVisitor.result, function (currItem) { return currItem.orgProd; });
result.push((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(nestedProds, function (currNestedProd) {
return validateNestedRuleName(curTopLevel, currNestedProd, errMsgProvider);
}));
});
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)(result);
}
function validateDuplicateProductions(topLevelRule, errMsgProvider) {
var collectorVisitor = new OccurrenceValidationCollector();
topLevelRule.accept(collectorVisitor);
var allRuleProductions = collectorVisitor.allProductions;
var productionGroups = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.groupBy(allRuleProductions, identifyProductionForDuplicates);
var duplicates = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick(productionGroups, function (currGroup) {
return currGroup.length > 1;
});
var errors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values(duplicates), function (currDuplicates) {
var firstProd = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.first(currDuplicates);
var msg = errMsgProvider.buildDuplicateFoundError(topLevelRule, currDuplicates);
var dslName = (0,_gast_gast__WEBPACK_IMPORTED_MODULE_2__.getProductionDslName)(firstProd);
var defError = {
message: msg,
type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,
ruleName: topLevelRule.name,
dslName: dslName,
occurrence: firstProd.idx
};
var param = getExtraProductionArgument(firstProd);
if (param) {
defError.parameter = param;
}
return defError;
});
return errors;
}
function identifyProductionForDuplicates(prod) {
return (0,_gast_gast__WEBPACK_IMPORTED_MODULE_2__.getProductionDslName)(prod) + "_#_" + prod.idx + "_#_" + getExtraProductionArgument(prod);
}
function getExtraProductionArgument(prod) {
if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.Terminal) {
return prod.terminalType.name;
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.NonTerminal) {
return prod.nonTerminalName;
}
else {
return "";
}
}
var OccurrenceValidationCollector = /** @class */ (function (_super) {
__extends(OccurrenceValidationCollector, _super);
function OccurrenceValidationCollector() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.allProductions = [];
return _this;
}
OccurrenceValidationCollector.prototype.visitNonTerminal = function (subrule) {
this.allProductions.push(subrule);
};
OccurrenceValidationCollector.prototype.visitOption = function (option) {
this.allProductions.push(option);
};
OccurrenceValidationCollector.prototype.visitRepetitionWithSeparator = function (manySep) {
this.allProductions.push(manySep);
};
OccurrenceValidationCollector.prototype.visitRepetitionMandatory = function (atLeastOne) {
this.allProductions.push(atLeastOne);
};
OccurrenceValidationCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) {
this.allProductions.push(atLeastOneSep);
};
OccurrenceValidationCollector.prototype.visitRepetition = function (many) {
this.allProductions.push(many);
};
OccurrenceValidationCollector.prototype.visitAlternation = function (or) {
this.allProductions.push(or);
};
OccurrenceValidationCollector.prototype.visitTerminal = function (terminal) {
this.allProductions.push(terminal);
};
return OccurrenceValidationCollector;
}(_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_7__.GAstVisitor));
var validTermsPattern = /^[a-zA-Z_]\w*$/;
var validNestedRuleName = new RegExp(validTermsPattern.source.replace("^", "^\\$"));
// TODO: remove this limitation now that we use recorders
function validateRuleName(rule, errMsgProvider) {
var errors = [];
var ruleName = rule.name;
if (!ruleName.match(validTermsPattern)) {
errors.push({
message: errMsgProvider.buildInvalidRuleNameError({
topLevelRule: rule,
expectedPattern: validTermsPattern
}),
type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.INVALID_RULE_NAME,
ruleName: ruleName
});
}
return errors;
}
// TODO: did the nested rule name regExp now change?
function validateNestedRuleName(topLevel, nestedProd, errMsgProvider) {
var errors = [];
var errMsg;
if (!nestedProd.name.match(validNestedRuleName)) {
errMsg = errMsgProvider.buildInvalidNestedRuleNameError(topLevel, nestedProd);
errors.push({
message: errMsg,
type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.INVALID_NESTED_RULE_NAME,
ruleName: topLevel.name
});
}
return errors;
}
// TODO: remove this limitation now that we use recorders
function validateTokenName(tokenType, errMsgProvider) {
var errors = [];
var tokTypeName = tokenType.name;
if (!tokTypeName.match(validTermsPattern)) {
errors.push({
message: errMsgProvider.buildTokenNameError({
tokenType: tokenType,
expectedPattern: validTermsPattern
}),
type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.INVALID_TOKEN_NAME
});
}
return errors;
}
function validateRuleDoesNotAlreadyExist(rule, allRules, className, errMsgProvider) {
var errors = [];
var occurrences = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce)(allRules, function (result, curRule) {
if (curRule.name === rule.name) {
return result + 1;
}
return result;
}, 0);
if (occurrences > 1) {
var errMsg = errMsgProvider.buildDuplicateRuleNameError({
topLevelRule: rule,
grammarName: className
});
errors.push({
message: errMsg,
type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,
ruleName: rule.name
});
}
return errors;
}
// TODO: is there anyway to get only the rule names of rules inherited from the super grammars?
// This is not part of the IGrammarErrorProvider because the validation cannot be performed on
// The grammar structure, only at runtime.
function validateRuleIsOverridden(ruleName, definedRulesNames, className) {
var errors = [];
var errMsg;
if (!_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains(definedRulesNames, ruleName)) {
errMsg =
"Invalid rule override, rule: ->" + ruleName + "<- cannot be overridden in the grammar: ->" + className + "<-" +
"as it is not defined in any of the super grammars ";
errors.push({
message: errMsg,
type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,
ruleName: ruleName
});
}
return errors;
}
function validateNoLeftRecursion(topRule, currRule, errMsgProvider, path) {
if (path === void 0) { path = []; }
var errors = [];
var nextNonTerminals = getFirstNoneTerminal(currRule.definition);
if (_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty(nextNonTerminals)) {
return [];
}
else {
var ruleName = topRule.name;
var foundLeftRecursion = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains(nextNonTerminals, topRule);
if (foundLeftRecursion) {
errors.push({
message: errMsgProvider.buildLeftRecursionError({
topLevelRule: topRule,
leftRecursionPath: path
}),
type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.LEFT_RECURSION,
ruleName: ruleName
});
}
// we are only looking for cyclic paths leading back to the specific topRule
// other cyclic paths are ignored, we still need this difference to avoid infinite loops...
var validNextSteps = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.difference(nextNonTerminals, path.concat([topRule]));
var errorsFromNextSteps = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(validNextSteps, function (currRefRule) {
var newPath = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.cloneArr(path);
newPath.push(currRefRule);
return validateNoLeftRecursion(topRule, currRefRule, errMsgProvider, newPath);
});
return errors.concat(_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten(errorsFromNextSteps));
}
}
function getFirstNoneTerminal(definition) {
var result = [];
if (_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty(definition)) {
return result;
}
var firstProd = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.first(definition);
/* istanbul ignore else */
if (firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.NonTerminal) {
result.push(firstProd.referencedRule);
}
else if (firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.Flat ||
firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.Option ||
firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.RepetitionMandatory ||
firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.RepetitionMandatoryWithSeparator ||
firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.RepetitionWithSeparator ||
firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.Repetition) {
result = result.concat(getFirstNoneTerminal(firstProd.definition));
}
else if (firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.Alternation) {
// each sub definition in alternation is a FLAT
result = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten(_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(firstProd.definition, function (currSubDef) {
return getFirstNoneTerminal(currSubDef.definition);
}));
}
else if (firstProd instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_6__.Terminal) {
// nothing to see, move along
}
else {
throw Error("non exhaustive match");
}
var isFirstOptional = (0,_gast_gast__WEBPACK_IMPORTED_MODULE_2__.isOptionalProd)(firstProd);
var hasMore = definition.length > 1;
if (isFirstOptional && hasMore) {
var rest = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.drop(definition);
return result.concat(getFirstNoneTerminal(rest));
}
else {
return result;
}
}
var OrCollector = /** @class */ (function (_super) {
__extends(OrCollector, _super);
function OrCollector() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.alternations = [];
return _this;
}
OrCollector.prototype.visitAlternation = function (node) {
this.alternations.push(node);
};
return OrCollector;
}(_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_7__.GAstVisitor));
function validateEmptyOrAlternative(topLevelRule, errMsgProvider) {
var orCollector = new OrCollector();
topLevelRule.accept(orCollector);
var ors = orCollector.alternations;
var errors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce(ors, function (errors, currOr) {
var exceptLast = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.dropRight(currOr.definition);
var currErrors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(exceptLast, function (currAlternative, currAltIdx) {
var possibleFirstInAlt = (0,_interpreter__WEBPACK_IMPORTED_MODULE_5__.nextPossibleTokensAfter)([currAlternative], [], null, 1);
if (_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty(possibleFirstInAlt)) {
return {
message: errMsgProvider.buildEmptyAlternationError({
topLevelRule: topLevelRule,
alternation: currOr,
emptyChoiceIdx: currAltIdx
}),
type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,
ruleName: topLevelRule.name,
occurrence: currOr.idx,
alternative: currAltIdx + 1
};
}
else {
return null;
}
});
return errors.concat(_utils_utils__WEBPACK_IMPORTED_MODULE_0__.compact(currErrors));
}, []);
return errors;
}
function validateAmbiguousAlternationAlternatives(topLevelRule, globalMaxLookahead, ignoredIssues, errMsgProvider) {
var orCollector = new OrCollector();
topLevelRule.accept(orCollector);
var ors = orCollector.alternations;
// TODO: this filtering should be deprecated once we remove the ignoredIssues
// IParserConfig property
var ignoredIssuesForCurrentRule = ignoredIssues[topLevelRule.name];
if (ignoredIssuesForCurrentRule) {
ors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reject)(ors, function (currOr) {
return ignoredIssuesForCurrentRule[(0,_gast_gast__WEBPACK_IMPORTED_MODULE_2__.getProductionDslName)(currOr) +
(currOr.idx === 0 ? "" : currOr.idx)];
});
}
// New Handling of ignoring ambiguities
// - https://github.com/SAP/chevrotain/issues/869
ors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reject)(ors, function (currOr) { return currOr.ignoreAmbiguities === true; });
var errors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce(ors, function (result, currOr) {
var currOccurrence = currOr.idx;
var actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead;
var alternatives = (0,_lookahead__WEBPACK_IMPORTED_MODULE_3__.getLookaheadPathsForOr)(currOccurrence, topLevelRule, actualMaxLookahead, currOr);
var altsAmbiguityErrors = checkAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider);
var altsPrefixAmbiguityErrors = checkPrefixAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider);
return result.concat(altsAmbiguityErrors, altsPrefixAmbiguityErrors);
}, []);
return errors;
}
var RepetionCollector = /** @class */ (function (_super) {
__extends(RepetionCollector, _super);
function RepetionCollector() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.allProductions = [];
return _this;
}
RepetionCollector.prototype.visitRepetitionWithSeparator = function (manySep) {
this.allProductions.push(manySep);
};
RepetionCollector.prototype.visitRepetitionMandatory = function (atLeastOne) {
this.allProductions.push(atLeastOne);
};
RepetionCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) {
this.allProductions.push(atLeastOneSep);
};
RepetionCollector.prototype.visitRepetition = function (many) {
this.allProductions.push(many);
};
return RepetionCollector;
}(_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_7__.GAstVisitor));
function validateTooManyAlts(topLevelRule, errMsgProvider) {
var orCollector = new OrCollector();
topLevelRule.accept(orCollector);
var ors = orCollector.alternations;
var errors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce(ors, function (errors, currOr) {
if (currOr.definition.length > 255) {
errors.push({
message: errMsgProvider.buildTooManyAlternativesError({
topLevelRule: topLevelRule,
alternation: currOr
}),
type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.TOO_MANY_ALTS,
ruleName: topLevelRule.name,
occurrence: currOr.idx
});
}
return errors;
}, []);
return errors;
}
function validateSomeNonEmptyLookaheadPath(topLevelRules, maxLookahead, errMsgProvider) {
var errors = [];
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(topLevelRules, function (currTopRule) {
var collectorVisitor = new RepetionCollector();
currTopRule.accept(collectorVisitor);
var allRuleProductions = collectorVisitor.allProductions;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(allRuleProductions, function (currProd) {
var prodType = (0,_lookahead__WEBPACK_IMPORTED_MODULE_3__.getProdType)(currProd);
var actualMaxLookahead = currProd.maxLookahead || maxLookahead;
var currOccurrence = currProd.idx;
var paths = (0,_lookahead__WEBPACK_IMPORTED_MODULE_3__.getLookaheadPathsForOptionalProd)(currOccurrence, currTopRule, prodType, actualMaxLookahead);
var pathsInsideProduction = paths[0];
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)(pathsInsideProduction))) {
var errMsg = errMsgProvider.buildEmptyRepetitionError({
topLevelRule: currTopRule,
repetition: currProd
});
errors.push({
message: errMsg,
type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,
ruleName: currTopRule.name
});
}
});
});
return errors;
}
function checkAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) {
var foundAmbiguousPaths = [];
var identicalAmbiguities = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce)(alternatives, function (result, currAlt, currAltIdx) {
// ignore (skip) ambiguities with this alternative
if (alternation.definition[currAltIdx].ignoreAmbiguities === true) {
return result;
}
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(currAlt, function (currPath) {
var altsCurrPathAppearsIn = [currAltIdx];
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(alternatives, function (currOtherAlt, currOtherAltIdx) {
if (currAltIdx !== currOtherAltIdx &&
(0,_lookahead__WEBPACK_IMPORTED_MODULE_3__.containsPath)(currOtherAlt, currPath) &&
// ignore (skip) ambiguities with this "other" alternative
alternation.definition[currOtherAltIdx]
.ignoreAmbiguities !== true) {
altsCurrPathAppearsIn.push(currOtherAltIdx);
}
});
if (altsCurrPathAppearsIn.length > 1 &&
!(0,_lookahead__WEBPACK_IMPORTED_MODULE_3__.containsPath)(foundAmbiguousPaths, currPath)) {
foundAmbiguousPaths.push(currPath);
result.push({
alts: altsCurrPathAppearsIn,
path: currPath
});
}
});
return result;
}, []);
var currErrors = _utils_utils__WEBPACK_IMPORTED_MODULE_0__.map(identicalAmbiguities, function (currAmbDescriptor) {
var ambgIndices = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(currAmbDescriptor.alts, function (currAltIdx) { return currAltIdx + 1; });
var currMessage = errMsgProvider.buildAlternationAmbiguityError({
topLevelRule: rule,
alternation: alternation,
ambiguityIndices: ambgIndices,
prefixPath: currAmbDescriptor.path
});
return {
message: currMessage,
type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.AMBIGUOUS_ALTS,
ruleName: rule.name,
occurrence: alternation.idx,
alternatives: [currAmbDescriptor.alts]
};
});
return currErrors;
}
function checkPrefixAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) {
var errors = [];
// flatten
var pathsAndIndices = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce)(alternatives, function (result, currAlt, idx) {
var currPathsAndIdx = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(currAlt, function (currPath) {
return { idx: idx, path: currPath };
});
return result.concat(currPathsAndIdx);
}, []);
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(pathsAndIndices, function (currPathAndIdx) {
var alternativeGast = alternation.definition[currPathAndIdx.idx];
// ignore (skip) ambiguities with this alternative
if (alternativeGast.ignoreAmbiguities === true) {
return;
}
var targetIdx = currPathAndIdx.idx;
var targetPath = currPathAndIdx.path;
var prefixAmbiguitiesPathsAndIndices = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.findAll)(pathsAndIndices, function (searchPathAndIdx) {
// prefix ambiguity can only be created from lower idx (higher priority) path
return (
// ignore (skip) ambiguities with this "other" alternative
alternation.definition[searchPathAndIdx.idx]
.ignoreAmbiguities !== true &&
searchPathAndIdx.idx < targetIdx &&
// checking for strict prefix because identical lookaheads
// will be be detected using a different validation.
(0,_lookahead__WEBPACK_IMPORTED_MODULE_3__.isStrictPrefixOfPath)(searchPathAndIdx.path, targetPath));
});
var currPathPrefixErrors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(prefixAmbiguitiesPathsAndIndices, function (currAmbPathAndIdx) {
var ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1];
var occurrence = alternation.idx === 0 ? "" : alternation.idx;
var message = errMsgProvider.buildAlternationPrefixAmbiguityError({
topLevelRule: rule,
alternation: alternation,
ambiguityIndices: ambgIndices,
prefixPath: currAmbPathAndIdx.path
});
return {
message: message,
type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS,
ruleName: rule.name,
occurrence: occurrence,
alternatives: ambgIndices
};
});
errors = errors.concat(currPathPrefixErrors);
});
return errors;
}
function checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider) {
var errors = [];
var tokenNames = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(tokenTypes, function (currToken) { return currToken.name; });
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(topLevels, function (currRule) {
var currRuleName = currRule.name;
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains)(tokenNames, currRuleName)) {
var errMsg = errMsgProvider.buildNamespaceConflictError(currRule);
errors.push({
message: errMsg,
type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,
ruleName: currRuleName
});
}
});
return errors;
}
function validateDuplicateNestedRules(topLevelRules, errMsgProvider) {
var errors = [];
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(topLevelRules, function (currTopRule) {
var namedCollectorVisitor = new _cst_cst__WEBPACK_IMPORTED_MODULE_4__.NamedDSLMethodsCollectorVisitor("");
currTopRule.accept(namedCollectorVisitor);
var prodsByGroup = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.groupBy)(namedCollectorVisitor.result, function (item) { return item.name; });
var duplicates = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.pick)(prodsByGroup, function (currGroup) {
return currGroup.length > 1;
});
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(duplicates), function (currDupGroup) {
var currDupProds = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(currDupGroup, function (dupGroup) { return dupGroup.orgProd; });
var errMsg = errMsgProvider.buildDuplicateNestedRuleNameError(currTopRule, currDupProds);
errors.push({
message: errMsg,
type: _parser_parser__WEBPACK_IMPORTED_MODULE_1__.ParserDefinitionErrorType.DUPLICATE_NESTED_NAME,
ruleName: currTopRule.name
});
});
});
return errors;
}
//# sourceMappingURL=checks.js.map
/***/ }),
/* 37 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ PROD_TYPE: () => (/* binding */ PROD_TYPE),
/* harmony export */ areTokenCategoriesNotUsed: () => (/* binding */ areTokenCategoriesNotUsed),
/* harmony export */ buildAlternativesLookAheadFunc: () => (/* binding */ buildAlternativesLookAheadFunc),
/* harmony export */ buildLookaheadFuncForOptionalProd: () => (/* binding */ buildLookaheadFuncForOptionalProd),
/* harmony export */ buildLookaheadFuncForOr: () => (/* binding */ buildLookaheadFuncForOr),
/* harmony export */ buildSingleAlternativeLookaheadFunction: () => (/* binding */ buildSingleAlternativeLookaheadFunction),
/* harmony export */ containsPath: () => (/* binding */ containsPath),
/* harmony export */ getLookaheadPathsForOptionalProd: () => (/* binding */ getLookaheadPathsForOptionalProd),
/* harmony export */ getLookaheadPathsForOr: () => (/* binding */ getLookaheadPathsForOr),
/* harmony export */ getProdType: () => (/* binding */ getProdType),
/* harmony export */ isStrictPrefixOfPath: () => (/* binding */ isStrictPrefixOfPath),
/* harmony export */ lookAheadSequenceFromAlternatives: () => (/* binding */ lookAheadSequenceFromAlternatives)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _interpreter__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(38);
/* harmony import */ var _rest__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(19);
/* harmony import */ var _scan_tokens__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(27);
/* harmony import */ var _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(20);
/* harmony import */ var _gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(31);
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var PROD_TYPE;
(function (PROD_TYPE) {
PROD_TYPE[PROD_TYPE["OPTION"] = 0] = "OPTION";
PROD_TYPE[PROD_TYPE["REPETITION"] = 1] = "REPETITION";
PROD_TYPE[PROD_TYPE["REPETITION_MANDATORY"] = 2] = "REPETITION_MANDATORY";
PROD_TYPE[PROD_TYPE["REPETITION_MANDATORY_WITH_SEPARATOR"] = 3] = "REPETITION_MANDATORY_WITH_SEPARATOR";
PROD_TYPE[PROD_TYPE["REPETITION_WITH_SEPARATOR"] = 4] = "REPETITION_WITH_SEPARATOR";
PROD_TYPE[PROD_TYPE["ALTERNATION"] = 5] = "ALTERNATION";
})(PROD_TYPE || (PROD_TYPE = {}));
function getProdType(prod) {
/* istanbul ignore else */
if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.Option) {
return PROD_TYPE.OPTION;
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.Repetition) {
return PROD_TYPE.REPETITION;
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.RepetitionMandatory) {
return PROD_TYPE.REPETITION_MANDATORY;
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.RepetitionMandatoryWithSeparator) {
return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR;
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.RepetitionWithSeparator) {
return PROD_TYPE.REPETITION_WITH_SEPARATOR;
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.Alternation) {
return PROD_TYPE.ALTERNATION;
}
else {
throw Error("non exhaustive match");
}
}
function buildLookaheadFuncForOr(occurrence, ruleGrammar, maxLookahead, hasPredicates, dynamicTokensEnabled, laFuncBuilder) {
var lookAheadPaths = getLookaheadPathsForOr(occurrence, ruleGrammar, maxLookahead);
var tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths)
? _scan_tokens__WEBPACK_IMPORTED_MODULE_3__.tokenStructuredMatcherNoCategories
: _scan_tokens__WEBPACK_IMPORTED_MODULE_3__.tokenStructuredMatcher;
return laFuncBuilder(lookAheadPaths, hasPredicates, tokenMatcher, dynamicTokensEnabled);
}
/**
* When dealing with an Optional production (OPTION/MANY/2nd iteration of AT_LEAST_ONE/...) we need to compare
* the lookahead "inside" the production and the lookahead immediately "after" it in the same top level rule (context free).
*
* Example: given a production:
* ABC(DE)?DF
*
* The optional '(DE)?' should only be entered if we see 'DE'. a single Token 'D' is not sufficient to distinguish between the two
* alternatives.
*
* @returns A Lookahead function which will return true IFF the parser should parse the Optional production.
*/
function buildLookaheadFuncForOptionalProd(occurrence, ruleGrammar, k, dynamicTokensEnabled, prodType, lookaheadBuilder) {
var lookAheadPaths = getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k);
var tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths)
? _scan_tokens__WEBPACK_IMPORTED_MODULE_3__.tokenStructuredMatcherNoCategories
: _scan_tokens__WEBPACK_IMPORTED_MODULE_3__.tokenStructuredMatcher;
return lookaheadBuilder(lookAheadPaths[0], tokenMatcher, dynamicTokensEnabled);
}
function buildAlternativesLookAheadFunc(alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) {
var numOfAlts = alts.length;
var areAllOneTokenLookahead = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(alts, function (currAlt) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(currAlt, function (currPath) {
return currPath.length === 1;
});
});
// This version takes into account the predicates as well.
if (hasPredicates) {
/**
* @returns {number} - The chosen alternative index
*/
return function (orAlts) {
// unfortunately the predicates must be extracted every single time
// as they cannot be cached due to references to parameters(vars) which are no longer valid.
// note that in the common case of no predicates, no cpu time will be wasted on this (see else block)
var predicates = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(orAlts, function (currAlt) { return currAlt.GATE; });
for (var t = 0; t < numOfAlts; t++) {
var currAlt = alts[t];
var currNumOfPaths = currAlt.length;
var currPredicate = predicates[t];
if (currPredicate !== undefined &&
currPredicate.call(this) === false) {
// if the predicate does not match there is no point in checking the paths
continue;
}
nextPath: for (var j = 0; j < currNumOfPaths; j++) {
var currPath = currAlt[j];
var currPathLength = currPath.length;
for (var i = 0; i < currPathLength; i++) {
var nextToken = this.LA(i + 1);
if (tokenMatcher(nextToken, currPath[i]) === false) {
// mismatch in current path
// try the next pth
continue nextPath;
}
}
// found a full path that matches.
// this will also work for an empty ALT as the loop will be skipped
return t;
}
// none of the paths for the current alternative matched
// try the next alternative
}
// none of the alternatives could be matched
return undefined;
};
}
else if (areAllOneTokenLookahead && !dynamicTokensEnabled) {
// optimized (common) case of all the lookaheads paths requiring only
// a single token lookahead. These Optimizations cannot work if dynamically defined Tokens are used.
var singleTokenAlts = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(alts, function (currAlt) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)(currAlt);
});
var choiceToAlt_1 = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce)(singleTokenAlts, function (result, currAlt, idx) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(currAlt, function (currTokType) {
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(result, currTokType.tokenTypeIdx)) {
result[currTokType.tokenTypeIdx] = idx;
}
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(currTokType.categoryMatches, function (currExtendingType) {
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(result, currExtendingType)) {
result[currExtendingType] = idx;
}
});
});
return result;
}, []);
/**
* @returns {number} - The chosen alternative index
*/
return function () {
var nextToken = this.LA(1);
return choiceToAlt_1[nextToken.tokenTypeIdx];
};
}
else {
// optimized lookahead without needing to check the predicates at all.
// this causes code duplication which is intentional to improve performance.
/**
* @returns {number} - The chosen alternative index
*/
return function () {
for (var t = 0; t < numOfAlts; t++) {
var currAlt = alts[t];
var currNumOfPaths = currAlt.length;
nextPath: for (var j = 0; j < currNumOfPaths; j++) {
var currPath = currAlt[j];
var currPathLength = currPath.length;
for (var i = 0; i < currPathLength; i++) {
var nextToken = this.LA(i + 1);
if (tokenMatcher(nextToken, currPath[i]) === false) {
// mismatch in current path
// try the next pth
continue nextPath;
}
}
// found a full path that matches.
// this will also work for an empty ALT as the loop will be skipped
return t;
}
// none of the paths for the current alternative matched
// try the next alternative
}
// none of the alternatives could be matched
return undefined;
};
}
}
function buildSingleAlternativeLookaheadFunction(alt, tokenMatcher, dynamicTokensEnabled) {
var areAllOneTokenLookahead = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(alt, function (currPath) {
return currPath.length === 1;
});
var numOfPaths = alt.length;
// optimized (common) case of all the lookaheads paths requiring only
// a single token lookahead.
if (areAllOneTokenLookahead && !dynamicTokensEnabled) {
var singleTokensTypes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)(alt);
if (singleTokensTypes.length === 1 &&
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(singleTokensTypes[0].categoryMatches)) {
var expectedTokenType = singleTokensTypes[0];
var expectedTokenUniqueKey_1 = expectedTokenType.tokenTypeIdx;
return function () {
return this.LA(1).tokenTypeIdx === expectedTokenUniqueKey_1;
};
}
else {
var choiceToAlt_2 = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce)(singleTokensTypes, function (result, currTokType, idx) {
result[currTokType.tokenTypeIdx] = true;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(currTokType.categoryMatches, function (currExtendingType) {
result[currExtendingType] = true;
});
return result;
}, []);
return function () {
var nextToken = this.LA(1);
return choiceToAlt_2[nextToken.tokenTypeIdx] === true;
};
}
}
else {
return function () {
nextPath: for (var j = 0; j < numOfPaths; j++) {
var currPath = alt[j];
var currPathLength = currPath.length;
for (var i = 0; i < currPathLength; i++) {
var nextToken = this.LA(i + 1);
if (tokenMatcher(nextToken, currPath[i]) === false) {
// mismatch in current path
// try the next pth
continue nextPath;
}
}
// found a full path that matches.
return true;
}
// none of the paths matched
return false;
};
}
}
var RestDefinitionFinderWalker = /** @class */ (function (_super) {
__extends(RestDefinitionFinderWalker, _super);
function RestDefinitionFinderWalker(topProd, targetOccurrence, targetProdType) {
var _this = _super.call(this) || this;
_this.topProd = topProd;
_this.targetOccurrence = targetOccurrence;
_this.targetProdType = targetProdType;
return _this;
}
RestDefinitionFinderWalker.prototype.startWalking = function () {
this.walk(this.topProd);
return this.restDef;
};
RestDefinitionFinderWalker.prototype.checkIsTarget = function (node, expectedProdType, currRest, prevRest) {
if (node.idx === this.targetOccurrence &&
this.targetProdType === expectedProdType) {
this.restDef = currRest.concat(prevRest);
return true;
}
// performance optimization, do not iterate over the entire Grammar ast after we have found the target
return false;
};
RestDefinitionFinderWalker.prototype.walkOption = function (optionProd, currRest, prevRest) {
if (!this.checkIsTarget(optionProd, PROD_TYPE.OPTION, currRest, prevRest)) {
_super.prototype.walkOption.call(this, optionProd, currRest, prevRest);
}
};
RestDefinitionFinderWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) {
if (!this.checkIsTarget(atLeastOneProd, PROD_TYPE.REPETITION_MANDATORY, currRest, prevRest)) {
_super.prototype.walkOption.call(this, atLeastOneProd, currRest, prevRest);
}
};
RestDefinitionFinderWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) {
if (!this.checkIsTarget(atLeastOneSepProd, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currRest, prevRest)) {
_super.prototype.walkOption.call(this, atLeastOneSepProd, currRest, prevRest);
}
};
RestDefinitionFinderWalker.prototype.walkMany = function (manyProd, currRest, prevRest) {
if (!this.checkIsTarget(manyProd, PROD_TYPE.REPETITION, currRest, prevRest)) {
_super.prototype.walkOption.call(this, manyProd, currRest, prevRest);
}
};
RestDefinitionFinderWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) {
if (!this.checkIsTarget(manySepProd, PROD_TYPE.REPETITION_WITH_SEPARATOR, currRest, prevRest)) {
_super.prototype.walkOption.call(this, manySepProd, currRest, prevRest);
}
};
return RestDefinitionFinderWalker;
}(_rest__WEBPACK_IMPORTED_MODULE_2__.RestWalker));
/**
* Returns the definition of a target production in a top level level rule.
*/
var InsideDefinitionFinderVisitor = /** @class */ (function (_super) {
__extends(InsideDefinitionFinderVisitor, _super);
function InsideDefinitionFinderVisitor(targetOccurrence, targetProdType, targetRef) {
var _this = _super.call(this) || this;
_this.targetOccurrence = targetOccurrence;
_this.targetProdType = targetProdType;
_this.targetRef = targetRef;
_this.result = [];
return _this;
}
InsideDefinitionFinderVisitor.prototype.checkIsTarget = function (node, expectedProdName) {
if (node.idx === this.targetOccurrence &&
this.targetProdType === expectedProdName &&
(this.targetRef === undefined || node === this.targetRef)) {
this.result = node.definition;
}
};
InsideDefinitionFinderVisitor.prototype.visitOption = function (node) {
this.checkIsTarget(node, PROD_TYPE.OPTION);
};
InsideDefinitionFinderVisitor.prototype.visitRepetition = function (node) {
this.checkIsTarget(node, PROD_TYPE.REPETITION);
};
InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatory = function (node) {
this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY);
};
InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) {
this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR);
};
InsideDefinitionFinderVisitor.prototype.visitRepetitionWithSeparator = function (node) {
this.checkIsTarget(node, PROD_TYPE.REPETITION_WITH_SEPARATOR);
};
InsideDefinitionFinderVisitor.prototype.visitAlternation = function (node) {
this.checkIsTarget(node, PROD_TYPE.ALTERNATION);
};
return InsideDefinitionFinderVisitor;
}(_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_5__.GAstVisitor));
function initializeArrayOfArrays(size) {
var result = new Array(size);
for (var i = 0; i < size; i++) {
result[i] = [];
}
return result;
}
/**
* A sort of hash function between a Path in the grammar and a string.
* Note that this returns multiple "hashes" to support the scenario of token categories.
* - A single path with categories may match multiple **actual** paths.
*/
function pathToHashKeys(path) {
var keys = [""];
for (var i = 0; i < path.length; i++) {
var tokType = path[i];
var longerKeys = [];
for (var j = 0; j < keys.length; j++) {
var currShorterKey = keys[j];
longerKeys.push(currShorterKey + "_" + tokType.tokenTypeIdx);
for (var t = 0; t < tokType.categoryMatches.length; t++) {
var categoriesKeySuffix = "_" + tokType.categoryMatches[t];
longerKeys.push(currShorterKey + categoriesKeySuffix);
}
}
keys = longerKeys;
}
return keys;
}
/**
* Imperative style due to being called from a hot spot
*/
function isUniquePrefixHash(altKnownPathsKeys, searchPathKeys, idx) {
for (var currAltIdx = 0; currAltIdx < altKnownPathsKeys.length; currAltIdx++) {
// We only want to test vs the other alternatives
if (currAltIdx === idx) {
continue;
}
var otherAltKnownPathsKeys = altKnownPathsKeys[currAltIdx];
for (var searchIdx = 0; searchIdx < searchPathKeys.length; searchIdx++) {
var searchKey = searchPathKeys[searchIdx];
if (otherAltKnownPathsKeys[searchKey] === true) {
return false;
}
}
}
// None of the SearchPathKeys were found in any of the other alternatives
return true;
}
function lookAheadSequenceFromAlternatives(altsDefs, k) {
var partialAlts = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(altsDefs, function (currAlt) { return (0,_interpreter__WEBPACK_IMPORTED_MODULE_1__.possiblePathsFrom)([currAlt], 1); });
var finalResult = initializeArrayOfArrays(partialAlts.length);
var altsHashes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(partialAlts, function (currAltPaths) {
var dict = {};
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(currAltPaths, function (item) {
var keys = pathToHashKeys(item.partialPath);
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(keys, function (currKey) {
dict[currKey] = true;
});
});
return dict;
});
var newData = partialAlts;
// maxLookahead loop
for (var pathLength = 1; pathLength <= k; pathLength++) {
var currDataset = newData;
newData = initializeArrayOfArrays(currDataset.length);
var _loop_1 = function (altIdx) {
var currAltPathsAndSuffixes = currDataset[altIdx];
// paths in current alternative loop
for (var currPathIdx = 0; currPathIdx < currAltPathsAndSuffixes.length; currPathIdx++) {
var currPathPrefix = currAltPathsAndSuffixes[currPathIdx].partialPath;
var suffixDef = currAltPathsAndSuffixes[currPathIdx].suffixDef;
var prefixKeys = pathToHashKeys(currPathPrefix);
var isUnique = isUniquePrefixHash(altsHashes, prefixKeys, altIdx);
// End of the line for this path.
if (isUnique ||
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(suffixDef) ||
currPathPrefix.length === k) {
var currAltResult = finalResult[altIdx];
// TODO: Can we implement a containsPath using Maps/Dictionaries?
if (containsPath(currAltResult, currPathPrefix) === false) {
currAltResult.push(currPathPrefix);
// Update all new keys for the current path.
for (var j = 0; j < prefixKeys.length; j++) {
var currKey = prefixKeys[j];
altsHashes[altIdx][currKey] = true;
}
}
}
// Expand longer paths
else {
var newPartialPathsAndSuffixes = (0,_interpreter__WEBPACK_IMPORTED_MODULE_1__.possiblePathsFrom)(suffixDef, pathLength + 1, currPathPrefix);
newData[altIdx] = newData[altIdx].concat(newPartialPathsAndSuffixes);
// Update keys for new known paths
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(newPartialPathsAndSuffixes, function (item) {
var prefixKeys = pathToHashKeys(item.partialPath);
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(prefixKeys, function (key) {
altsHashes[altIdx][key] = true;
});
});
}
}
};
// alternatives loop
for (var altIdx = 0; altIdx < currDataset.length; altIdx++) {
_loop_1(altIdx);
}
}
return finalResult;
}
function getLookaheadPathsForOr(occurrence, ruleGrammar, k, orProd) {
var visitor = new InsideDefinitionFinderVisitor(occurrence, PROD_TYPE.ALTERNATION, orProd);
ruleGrammar.accept(visitor);
return lookAheadSequenceFromAlternatives(visitor.result, k);
}
function getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k) {
var insideDefVisitor = new InsideDefinitionFinderVisitor(occurrence, prodType);
ruleGrammar.accept(insideDefVisitor);
var insideDef = insideDefVisitor.result;
var afterDefWalker = new RestDefinitionFinderWalker(ruleGrammar, occurrence, prodType);
var afterDef = afterDefWalker.startWalking();
var insideFlat = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.Flat({ definition: insideDef });
var afterFlat = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_4__.Flat({ definition: afterDef });
return lookAheadSequenceFromAlternatives([insideFlat, afterFlat], k);
}
function containsPath(alternative, searchPath) {
compareOtherPath: for (var i = 0; i < alternative.length; i++) {
var otherPath = alternative[i];
if (otherPath.length !== searchPath.length) {
continue;
}
for (var j = 0; j < otherPath.length; j++) {
var searchTok = searchPath[j];
var otherTok = otherPath[j];
var matchingTokens = searchTok === otherTok ||
otherTok.categoryMatchesMap[searchTok.tokenTypeIdx] !==
undefined;
if (matchingTokens === false) {
continue compareOtherPath;
}
}
return true;
}
return false;
}
function isStrictPrefixOfPath(prefix, other) {
return (prefix.length < other.length &&
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(prefix, function (tokType, idx) {
var otherTokType = other[idx];
return (tokType === otherTokType ||
otherTokType.categoryMatchesMap[tokType.tokenTypeIdx]);
}));
}
function areTokenCategoriesNotUsed(lookAheadPaths) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(lookAheadPaths, function (singleAltPaths) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(singleAltPaths, function (singlePath) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)(singlePath, function (token) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(token.categoryMatches); });
});
});
}
//# sourceMappingURL=lookahead.js.map
/***/ }),
/* 38 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AbstractNextPossibleTokensWalker: () => (/* binding */ AbstractNextPossibleTokensWalker),
/* harmony export */ AbstractNextTerminalAfterProductionWalker: () => (/* binding */ AbstractNextTerminalAfterProductionWalker),
/* harmony export */ NextAfterTokenWalker: () => (/* binding */ NextAfterTokenWalker),
/* harmony export */ NextTerminalAfterAtLeastOneSepWalker: () => (/* binding */ NextTerminalAfterAtLeastOneSepWalker),
/* harmony export */ NextTerminalAfterAtLeastOneWalker: () => (/* binding */ NextTerminalAfterAtLeastOneWalker),
/* harmony export */ NextTerminalAfterManySepWalker: () => (/* binding */ NextTerminalAfterManySepWalker),
/* harmony export */ NextTerminalAfterManyWalker: () => (/* binding */ NextTerminalAfterManyWalker),
/* harmony export */ nextPossibleTokensAfter: () => (/* binding */ nextPossibleTokensAfter),
/* harmony export */ possiblePathsFrom: () => (/* binding */ possiblePathsFrom)
/* harmony export */ });
/* harmony import */ var _rest__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(19);
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17);
/* harmony import */ var _first__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29);
/* harmony import */ var _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(20);
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var AbstractNextPossibleTokensWalker = /** @class */ (function (_super) {
__extends(AbstractNextPossibleTokensWalker, _super);
function AbstractNextPossibleTokensWalker(topProd, path) {
var _this = _super.call(this) || this;
_this.topProd = topProd;
_this.path = path;
_this.possibleTokTypes = [];
_this.nextProductionName = "";
_this.nextProductionOccurrence = 0;
_this.found = false;
_this.isAtEndOfPath = false;
return _this;
}
AbstractNextPossibleTokensWalker.prototype.startWalking = function () {
this.found = false;
if (this.path.ruleStack[0] !== this.topProd.name) {
throw Error("The path does not start with the walker's top Rule!");
}
// immutable for the win
this.ruleStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(this.path.ruleStack).reverse(); // intelij bug requires assertion
this.occurrenceStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(this.path.occurrenceStack).reverse(); // intelij bug requires assertion
// already verified that the first production is valid, we now seek the 2nd production
this.ruleStack.pop();
this.occurrenceStack.pop();
this.updateExpectedNext();
this.walk(this.topProd);
return this.possibleTokTypes;
};
AbstractNextPossibleTokensWalker.prototype.walk = function (prod, prevRest) {
if (prevRest === void 0) { prevRest = []; }
// stop scanning once we found the path
if (!this.found) {
_super.prototype.walk.call(this, prod, prevRest);
}
};
AbstractNextPossibleTokensWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) {
// found the next production, need to keep walking in it
if (refProd.referencedRule.name === this.nextProductionName &&
refProd.idx === this.nextProductionOccurrence) {
var fullRest = currRest.concat(prevRest);
this.updateExpectedNext();
this.walk(refProd.referencedRule, fullRest);
}
};
AbstractNextPossibleTokensWalker.prototype.updateExpectedNext = function () {
// need to consume the Terminal
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(this.ruleStack)) {
// must reset nextProductionXXX to avoid walking down another Top Level production while what we are
// really seeking is the last Terminal...
this.nextProductionName = "";
this.nextProductionOccurrence = 0;
this.isAtEndOfPath = true;
}
else {
this.nextProductionName = this.ruleStack.pop();
this.nextProductionOccurrence = this.occurrenceStack.pop();
}
};
return AbstractNextPossibleTokensWalker;
}(_rest__WEBPACK_IMPORTED_MODULE_0__.RestWalker));
var NextAfterTokenWalker = /** @class */ (function (_super) {
__extends(NextAfterTokenWalker, _super);
function NextAfterTokenWalker(topProd, path) {
var _this = _super.call(this, topProd, path) || this;
_this.path = path;
_this.nextTerminalName = "";
_this.nextTerminalOccurrence = 0;
_this.nextTerminalName = _this.path.lastTok.name;
_this.nextTerminalOccurrence = _this.path.lastTokOccurrence;
return _this;
}
NextAfterTokenWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) {
if (this.isAtEndOfPath &&
terminal.terminalType.name === this.nextTerminalName &&
terminal.idx === this.nextTerminalOccurrence &&
!this.found) {
var fullRest = currRest.concat(prevRest);
var restProd = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Flat({ definition: fullRest });
this.possibleTokTypes = (0,_first__WEBPACK_IMPORTED_MODULE_2__.first)(restProd);
this.found = true;
}
};
return NextAfterTokenWalker;
}(AbstractNextPossibleTokensWalker));
/**
* This walker only "walks" a single "TOP" level in the Grammar Ast, this means
* it never "follows" production refs
*/
var AbstractNextTerminalAfterProductionWalker = /** @class */ (function (_super) {
__extends(AbstractNextTerminalAfterProductionWalker, _super);
function AbstractNextTerminalAfterProductionWalker(topRule, occurrence) {
var _this = _super.call(this) || this;
_this.topRule = topRule;
_this.occurrence = occurrence;
_this.result = {
token: undefined,
occurrence: undefined,
isEndOfRule: undefined
};
return _this;
}
AbstractNextTerminalAfterProductionWalker.prototype.startWalking = function () {
this.walk(this.topRule);
return this.result;
};
return AbstractNextTerminalAfterProductionWalker;
}(_rest__WEBPACK_IMPORTED_MODULE_0__.RestWalker));
var NextTerminalAfterManyWalker = /** @class */ (function (_super) {
__extends(NextTerminalAfterManyWalker, _super);
function NextTerminalAfterManyWalker() {
return _super !== null && _super.apply(this, arguments) || this;
}
NextTerminalAfterManyWalker.prototype.walkMany = function (manyProd, currRest, prevRest) {
if (manyProd.idx === this.occurrence) {
var firstAfterMany = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(currRest.concat(prevRest));
this.result.isEndOfRule = firstAfterMany === undefined;
if (firstAfterMany instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal) {
this.result.token = firstAfterMany.terminalType;
this.result.occurrence = firstAfterMany.idx;
}
}
else {
_super.prototype.walkMany.call(this, manyProd, currRest, prevRest);
}
};
return NextTerminalAfterManyWalker;
}(AbstractNextTerminalAfterProductionWalker));
var NextTerminalAfterManySepWalker = /** @class */ (function (_super) {
__extends(NextTerminalAfterManySepWalker, _super);
function NextTerminalAfterManySepWalker() {
return _super !== null && _super.apply(this, arguments) || this;
}
NextTerminalAfterManySepWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) {
if (manySepProd.idx === this.occurrence) {
var firstAfterManySep = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(currRest.concat(prevRest));
this.result.isEndOfRule = firstAfterManySep === undefined;
if (firstAfterManySep instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal) {
this.result.token = firstAfterManySep.terminalType;
this.result.occurrence = firstAfterManySep.idx;
}
}
else {
_super.prototype.walkManySep.call(this, manySepProd, currRest, prevRest);
}
};
return NextTerminalAfterManySepWalker;
}(AbstractNextTerminalAfterProductionWalker));
var NextTerminalAfterAtLeastOneWalker = /** @class */ (function (_super) {
__extends(NextTerminalAfterAtLeastOneWalker, _super);
function NextTerminalAfterAtLeastOneWalker() {
return _super !== null && _super.apply(this, arguments) || this;
}
NextTerminalAfterAtLeastOneWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) {
if (atLeastOneProd.idx === this.occurrence) {
var firstAfterAtLeastOne = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(currRest.concat(prevRest));
this.result.isEndOfRule = firstAfterAtLeastOne === undefined;
if (firstAfterAtLeastOne instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal) {
this.result.token = firstAfterAtLeastOne.terminalType;
this.result.occurrence = firstAfterAtLeastOne.idx;
}
}
else {
_super.prototype.walkAtLeastOne.call(this, atLeastOneProd, currRest, prevRest);
}
};
return NextTerminalAfterAtLeastOneWalker;
}(AbstractNextTerminalAfterProductionWalker));
// TODO: reduce code duplication in the AfterWalkers
var NextTerminalAfterAtLeastOneSepWalker = /** @class */ (function (_super) {
__extends(NextTerminalAfterAtLeastOneSepWalker, _super);
function NextTerminalAfterAtLeastOneSepWalker() {
return _super !== null && _super.apply(this, arguments) || this;
}
NextTerminalAfterAtLeastOneSepWalker.prototype.walkAtLeastOneSep = function (atleastOneSepProd, currRest, prevRest) {
if (atleastOneSepProd.idx === this.occurrence) {
var firstAfterfirstAfterAtLeastOneSep = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(currRest.concat(prevRest));
this.result.isEndOfRule =
firstAfterfirstAfterAtLeastOneSep === undefined;
if (firstAfterfirstAfterAtLeastOneSep instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal) {
this.result.token =
firstAfterfirstAfterAtLeastOneSep.terminalType;
this.result.occurrence = firstAfterfirstAfterAtLeastOneSep.idx;
}
}
else {
_super.prototype.walkAtLeastOneSep.call(this, atleastOneSepProd, currRest, prevRest);
}
};
return NextTerminalAfterAtLeastOneSepWalker;
}(AbstractNextTerminalAfterProductionWalker));
function possiblePathsFrom(targetDef, maxLength, currPath) {
if (currPath === void 0) { currPath = []; }
// avoid side effects
currPath = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(currPath);
var result = [];
var i = 0;
// TODO: avoid inner funcs
function remainingPathWith(nextDef) {
return nextDef.concat((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(targetDef, i + 1));
}
// TODO: avoid inner funcs
function getAlternativesForProd(definition) {
var alternatives = possiblePathsFrom(remainingPathWith(definition), maxLength, currPath);
return result.concat(alternatives);
}
/**
* Mandatory productions will halt the loop as the paths computed from their recursive calls will already contain the
* following (rest) of the targetDef.
*
* For optional productions (Option/Repetition/...) the loop will continue to represent the paths that do not include the
* the optional production.
*/
while (currPath.length < maxLength && i < targetDef.length) {
var prod = targetDef[i];
/* istanbul ignore else */
if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Flat) {
return getAlternativesForProd(prod.definition);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.NonTerminal) {
return getAlternativesForProd(prod.definition);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Option) {
result = getAlternativesForProd(prod.definition);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.RepetitionMandatory) {
var newDef = prod.definition.concat([
new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({
definition: prod.definition
})
]);
return getAlternativesForProd(newDef);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.RepetitionMandatoryWithSeparator) {
var newDef = [
new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Flat({ definition: prod.definition }),
new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({
definition: [
new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal({ terminalType: prod.separator })
].concat(prod.definition)
})
];
return getAlternativesForProd(newDef);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.RepetitionWithSeparator) {
var newDef = prod.definition.concat([
new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({
definition: [
new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal({ terminalType: prod.separator })
].concat(prod.definition)
})
]);
result = getAlternativesForProd(newDef);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition) {
var newDef = prod.definition.concat([
new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({
definition: prod.definition
})
]);
result = getAlternativesForProd(newDef);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Alternation) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(prod.definition, function (currAlt) {
result = getAlternativesForProd(currAlt.definition);
});
return result;
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal) {
currPath.push(prod.terminalType);
}
else {
throw Error("non exhaustive match");
}
i++;
}
result.push({
partialPath: currPath,
suffixDef: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(targetDef, i)
});
return result;
}
function nextPossibleTokensAfter(initialDef, tokenVector, tokMatcher, maxLookAhead) {
var EXIT_NON_TERMINAL = "EXIT_NONE_TERMINAL";
// to avoid creating a new Array each time.
var EXIT_NON_TERMINAL_ARR = [EXIT_NON_TERMINAL];
var EXIT_ALTERNATIVE = "EXIT_ALTERNATIVE";
var foundCompletePath = false;
var tokenVectorLength = tokenVector.length;
var minimalAlternativesIndex = tokenVectorLength - maxLookAhead - 1;
var result = [];
var possiblePaths = [];
possiblePaths.push({
idx: -1,
def: initialDef,
ruleStack: [],
occurrenceStack: []
});
while (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(possiblePaths)) {
var currPath = possiblePaths.pop();
// skip alternatives if no more results can be found (assuming deterministic grammar with fixed lookahead)
if (currPath === EXIT_ALTERNATIVE) {
if (foundCompletePath &&
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.last)(possiblePaths).idx <= minimalAlternativesIndex) {
// remove irrelevant alternative
possiblePaths.pop();
}
continue;
}
var currDef = currPath.def;
var currIdx = currPath.idx;
var currRuleStack = currPath.ruleStack;
var currOccurrenceStack = currPath.occurrenceStack;
// For Example: an empty path could exist in a valid grammar in the case of an EMPTY_ALT
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(currDef)) {
continue;
}
var prod = currDef[0];
/* istanbul ignore else */
if (prod === EXIT_NON_TERMINAL) {
var nextPath = {
idx: currIdx,
def: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef),
ruleStack: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.dropRight)(currRuleStack),
occurrenceStack: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.dropRight)(currOccurrenceStack)
};
possiblePaths.push(nextPath);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal) {
/* istanbul ignore else */
if (currIdx < tokenVectorLength - 1) {
var nextIdx = currIdx + 1;
var actualToken = tokenVector[nextIdx];
if (tokMatcher(actualToken, prod.terminalType)) {
var nextPath = {
idx: nextIdx,
def: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef),
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPath);
}
// end of the line
}
else if (currIdx === tokenVectorLength - 1) {
// IGNORE ABOVE ELSE
result.push({
nextTokenType: prod.terminalType,
nextTokenOccurrence: prod.idx,
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
});
foundCompletePath = true;
}
else {
throw Error("non exhaustive match");
}
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.NonTerminal) {
var newRuleStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(currRuleStack);
newRuleStack.push(prod.nonTerminalName);
var newOccurrenceStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(currOccurrenceStack);
newOccurrenceStack.push(prod.idx);
var nextPath = {
idx: currIdx,
def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef)),
ruleStack: newRuleStack,
occurrenceStack: newOccurrenceStack
};
possiblePaths.push(nextPath);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Option) {
// the order of alternatives is meaningful, FILO (Last path will be traversed first).
var nextPathWithout = {
idx: currIdx,
def: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef),
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPathWithout);
// required marker to avoid backtracking paths whose higher priority alternatives already matched
possiblePaths.push(EXIT_ALTERNATIVE);
var nextPathWith = {
idx: currIdx,
def: prod.definition.concat((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef)),
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPathWith);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.RepetitionMandatory) {
// TODO:(THE NEW operators here take a while...) (convert once?)
var secondIteration = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({
definition: prod.definition,
idx: prod.idx
});
var nextDef = prod.definition.concat([secondIteration], (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef));
var nextPath = {
idx: currIdx,
def: nextDef,
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPath);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.RepetitionMandatoryWithSeparator) {
// TODO:(THE NEW operators here take a while...) (convert once?)
var separatorGast = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal({
terminalType: prod.separator
});
var secondIteration = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({
definition: [separatorGast].concat(prod.definition),
idx: prod.idx
});
var nextDef = prod.definition.concat([secondIteration], (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef));
var nextPath = {
idx: currIdx,
def: nextDef,
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPath);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.RepetitionWithSeparator) {
// the order of alternatives is meaningful, FILO (Last path will be traversed first).
var nextPathWithout = {
idx: currIdx,
def: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef),
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPathWithout);
// required marker to avoid backtracking paths whose higher priority alternatives already matched
possiblePaths.push(EXIT_ALTERNATIVE);
var separatorGast = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Terminal({
terminalType: prod.separator
});
var nthRepetition = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({
definition: [separatorGast].concat(prod.definition),
idx: prod.idx
});
var nextDef = prod.definition.concat([nthRepetition], (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef));
var nextPathWith = {
idx: currIdx,
def: nextDef,
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPathWith);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition) {
// the order of alternatives is meaningful, FILO (Last path will be traversed first).
var nextPathWithout = {
idx: currIdx,
def: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef),
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPathWithout);
// required marker to avoid backtracking paths whose higher priority alternatives already matched
possiblePaths.push(EXIT_ALTERNATIVE);
// TODO: an empty repetition will cause infinite loops here, will the parser detect this in selfAnalysis?
var nthRepetition = new _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Repetition({
definition: prod.definition,
idx: prod.idx
});
var nextDef = prod.definition.concat([nthRepetition], (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef));
var nextPathWith = {
idx: currIdx,
def: nextDef,
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(nextPathWith);
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Alternation) {
// the order of alternatives is meaningful, FILO (Last path will be traversed first).
for (var i = prod.definition.length - 1; i >= 0; i--) {
var currAlt = prod.definition[i];
var currAltPath = {
idx: currIdx,
def: currAlt.definition.concat((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef)),
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
};
possiblePaths.push(currAltPath);
possiblePaths.push(EXIT_ALTERNATIVE);
}
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Flat) {
possiblePaths.push({
idx: currIdx,
def: prod.definition.concat((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.drop)(currDef)),
ruleStack: currRuleStack,
occurrenceStack: currOccurrenceStack
});
}
else if (prod instanceof _gast_gast_public__WEBPACK_IMPORTED_MODULE_3__.Rule) {
// last because we should only encounter at most a single one of these per invocation.
possiblePaths.push(expandTopLevelRule(prod, currIdx, currRuleStack, currOccurrenceStack));
}
else {
throw Error("non exhaustive match");
}
}
return result;
}
function expandTopLevelRule(topRule, currIdx, currRuleStack, currOccurrenceStack) {
var newRuleStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(currRuleStack);
newRuleStack.push(topRule.name);
var newCurrOccurrenceStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(currOccurrenceStack);
// top rule is always assumed to have been called with occurrence index 1
newCurrOccurrenceStack.push(1);
return {
idx: currIdx,
def: topRule.definition,
ruleStack: newRuleStack,
occurrenceStack: newCurrOccurrenceStack
};
}
//# sourceMappingURL=interpreter.js.map
/***/ }),
/* 39 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ assignOccurrenceIndices: () => (/* binding */ assignOccurrenceIndices),
/* harmony export */ resolveGrammar: () => (/* binding */ resolveGrammar),
/* harmony export */ validateGrammar: () => (/* binding */ validateGrammar)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _resolver__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40);
/* harmony import */ var _checks__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(36);
/* harmony import */ var _errors_public__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(35);
/* harmony import */ var _gast__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(30);
function resolveGrammar(options) {
options = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.defaults)(options, {
errMsgProvider: _errors_public__WEBPACK_IMPORTED_MODULE_3__.defaultGrammarResolverErrorProvider
});
var topRulesTable = {};
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(options.rules, function (rule) {
topRulesTable[rule.name] = rule;
});
return (0,_resolver__WEBPACK_IMPORTED_MODULE_1__.resolveGrammar)(topRulesTable, options.errMsgProvider);
}
function validateGrammar(options) {
options = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.defaults)(options, {
errMsgProvider: _errors_public__WEBPACK_IMPORTED_MODULE_3__.defaultGrammarValidatorErrorProvider,
ignoredIssues: {}
});
return (0,_checks__WEBPACK_IMPORTED_MODULE_2__.validateGrammar)(options.rules, options.maxLookahead, options.tokenTypes, options.ignoredIssues, options.errMsgProvider, options.grammarName);
}
function assignOccurrenceIndices(options) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(options.rules, function (currRule) {
var methodsCollector = new _gast__WEBPACK_IMPORTED_MODULE_4__.DslMethodsCollectorVisitor();
currRule.accept(methodsCollector);
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(methodsCollector.dslMethods, function (methods) {
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(methods, function (currMethod, arrIdx) {
currMethod.idx = arrIdx + 1;
});
});
});
}
//# sourceMappingURL=gast_resolver_public.js.map
/***/ }),
/* 40 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ GastRefResolverVisitor: () => (/* binding */ GastRefResolverVisitor),
/* harmony export */ resolveGrammar: () => (/* binding */ resolveGrammar)
/* harmony export */ });
/* harmony import */ var _parser_parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16);
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17);
/* harmony import */ var _gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(31);
var __extends = (undefined && undefined.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
function resolveGrammar(topLevels, errMsgProvider) {
var refResolver = new GastRefResolverVisitor(topLevels, errMsgProvider);
refResolver.resolveRefs();
return refResolver.errors;
}
var GastRefResolverVisitor = /** @class */ (function (_super) {
__extends(GastRefResolverVisitor, _super);
function GastRefResolverVisitor(nameToTopRule, errMsgProvider) {
var _this = _super.call(this) || this;
_this.nameToTopRule = nameToTopRule;
_this.errMsgProvider = errMsgProvider;
_this.errors = [];
return _this;
}
GastRefResolverVisitor.prototype.resolveRefs = function () {
var _this = this;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.values)(this.nameToTopRule), function (prod) {
_this.currTopLevel = prod;
prod.accept(_this);
});
};
GastRefResolverVisitor.prototype.visitNonTerminal = function (node) {
var ref = this.nameToTopRule[node.nonTerminalName];
if (!ref) {
var msg = this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel, node);
this.errors.push({
message: msg,
type: _parser_parser__WEBPACK_IMPORTED_MODULE_0__.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,
ruleName: this.currTopLevel.name,
unresolvedRefName: node.nonTerminalName
});
}
else {
node.referencedRule = ref;
}
};
return GastRefResolverVisitor;
}(_gast_gast_visitor_public__WEBPACK_IMPORTED_MODULE_2__.GAstVisitor));
//# sourceMappingURL=resolver.js.map
/***/ }),
/* 41 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ EOF_FOLLOW_KEY: () => (/* binding */ EOF_FOLLOW_KEY),
/* harmony export */ IN_RULE_RECOVERY_EXCEPTION: () => (/* binding */ IN_RULE_RECOVERY_EXCEPTION),
/* harmony export */ InRuleRecoveryException: () => (/* binding */ InRuleRecoveryException),
/* harmony export */ Recoverable: () => (/* binding */ Recoverable),
/* harmony export */ attemptInRepetitionRecovery: () => (/* binding */ attemptInRepetitionRecovery)
/* harmony export */ });
/* harmony import */ var _scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17);
/* harmony import */ var _exceptions_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(42);
/* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(32);
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(16);
var EOF_FOLLOW_KEY = {};
var IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException";
function InRuleRecoveryException(message) {
this.name = IN_RULE_RECOVERY_EXCEPTION;
this.message = message;
}
InRuleRecoveryException.prototype = Error.prototype;
/**
* This trait is responsible for the error recovery and fault tolerant logic
*/
var Recoverable = /** @class */ (function () {
function Recoverable() {
}
Recoverable.prototype.initRecoverable = function (config) {
this.firstAfterRepMap = {};
this.resyncFollows = {};
this.recoveryEnabled = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.has)(config, "recoveryEnabled")
? config.recoveryEnabled
: _parser__WEBPACK_IMPORTED_MODULE_4__.DEFAULT_PARSER_CONFIG.recoveryEnabled;
// performance optimization, NOOP will be inlined which
// effectively means that this optional feature does not exist
// when not used.
if (this.recoveryEnabled) {
this.attemptInRepetitionRecovery = attemptInRepetitionRecovery;
}
};
Recoverable.prototype.getTokenToInsert = function (tokType) {
var tokToInsert = (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.createTokenInstance)(tokType, "", NaN, NaN, NaN, NaN, NaN, NaN);
tokToInsert.isInsertedInRecovery = true;
return tokToInsert;
};
Recoverable.prototype.canTokenTypeBeInsertedInRecovery = function (tokType) {
return true;
};
Recoverable.prototype.tryInRepetitionRecovery = function (grammarRule, grammarRuleArgs, lookAheadFunc, expectedTokType) {
var _this = this;
// TODO: can the resyncTokenType be cached?
var reSyncTokType = this.findReSyncTokenType();
var savedLexerState = this.exportLexerState();
var resyncedTokens = [];
var passedResyncPoint = false;
var nextTokenWithoutResync = this.LA(1);
var currToken = this.LA(1);
var generateErrorMessage = function () {
var previousToken = _this.LA(0);
// we are preemptively re-syncing before an error has been detected, therefor we must reproduce
// the error that would have been thrown
var msg = _this.errorMessageProvider.buildMismatchTokenMessage({
expected: expectedTokType,
actual: nextTokenWithoutResync,
previous: previousToken,
ruleName: _this.getCurrRuleFullName()
});
var error = new _exceptions_public__WEBPACK_IMPORTED_MODULE_2__.MismatchedTokenException(msg, nextTokenWithoutResync, _this.LA(0));
// the first token here will be the original cause of the error, this is not part of the resyncedTokens property.
error.resyncedTokens = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.dropRight)(resyncedTokens);
_this.SAVE_ERROR(error);
};
while (!passedResyncPoint) {
// re-synced to a point where we can safely exit the repetition/
if (this.tokenMatcher(currToken, expectedTokType)) {
generateErrorMessage();
return; // must return here to avoid reverting the inputIdx
}
else if (lookAheadFunc.call(this)) {
// we skipped enough tokens so we can resync right back into another iteration of the repetition grammar rule
generateErrorMessage();
// recursive invocation in other to support multiple re-syncs in the same top level repetition grammar rule
grammarRule.apply(this, grammarRuleArgs);
return; // must return here to avoid reverting the inputIdx
}
else if (this.tokenMatcher(currToken, reSyncTokType)) {
passedResyncPoint = true;
}
else {
currToken = this.SKIP_TOKEN();
this.addToResyncTokens(currToken, resyncedTokens);
}
}
// we were unable to find a CLOSER point to resync inside the Repetition, reset the state.
// The parsing exception we were trying to prevent will happen in the NEXT parsing step. it may be handled by
// "between rules" resync recovery later in the flow.
this.importLexerState(savedLexerState);
};
Recoverable.prototype.shouldInRepetitionRecoveryBeTried = function (expectTokAfterLastMatch, nextTokIdx, notStuck) {
// Edge case of arriving from a MANY repetition which is stuck
// Attempting recovery in this case could cause an infinite loop
if (notStuck === false) {
return false;
}
// arguments to try and perform resync into the next iteration of the many are missing
if (expectTokAfterLastMatch === undefined || nextTokIdx === undefined) {
return false;
}
// no need to recover, next token is what we expect...
if (this.tokenMatcher(this.LA(1), expectTokAfterLastMatch)) {
return false;
}
// error recovery is disabled during backtracking as it can make the parser ignore a valid grammar path
// and prefer some backtracking path that includes recovered errors.
if (this.isBackTracking()) {
return false;
}
// if we can perform inRule recovery (single token insertion or deletion) we always prefer that recovery algorithm
// because if it works, it makes the least amount of changes to the input stream (greedy algorithm)
//noinspection RedundantIfStatementJS
if (this.canPerformInRuleRecovery(expectTokAfterLastMatch, this.getFollowsForInRuleRecovery(expectTokAfterLastMatch, nextTokIdx))) {
return false;
}
return true;
};
// Error Recovery functionality
Recoverable.prototype.getFollowsForInRuleRecovery = function (tokType, tokIdxInRule) {
var grammarPath = this.getCurrentGrammarPath(tokType, tokIdxInRule);
var follows = this.getNextPossibleTokenTypes(grammarPath);
return follows;
};
Recoverable.prototype.tryInRuleRecovery = function (expectedTokType, follows) {
if (this.canRecoverWithSingleTokenInsertion(expectedTokType, follows)) {
var tokToInsert = this.getTokenToInsert(expectedTokType);
return tokToInsert;
}
if (this.canRecoverWithSingleTokenDeletion(expectedTokType)) {
var nextTok = this.SKIP_TOKEN();
this.consumeToken();
return nextTok;
}
throw new InRuleRecoveryException("sad sad panda");
};
Recoverable.prototype.canPerformInRuleRecovery = function (expectedToken, follows) {
return (this.canRecoverWithSingleTokenInsertion(expectedToken, follows) ||
this.canRecoverWithSingleTokenDeletion(expectedToken));
};
Recoverable.prototype.canRecoverWithSingleTokenInsertion = function (expectedTokType, follows) {
var _this = this;
if (!this.canTokenTypeBeInsertedInRecovery(expectedTokType)) {
return false;
}
// must know the possible following tokens to perform single token insertion
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(follows)) {
return false;
}
var mismatchedTok = this.LA(1);
var isMisMatchedTokInFollows = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.find)(follows, function (possibleFollowsTokType) {
return _this.tokenMatcher(mismatchedTok, possibleFollowsTokType);
}) !== undefined;
return isMisMatchedTokInFollows;
};
Recoverable.prototype.canRecoverWithSingleTokenDeletion = function (expectedTokType) {
var isNextTokenWhatIsExpected = this.tokenMatcher(this.LA(2), expectedTokType);
return isNextTokenWhatIsExpected;
};
Recoverable.prototype.isInCurrentRuleReSyncSet = function (tokenTypeIdx) {
var followKey = this.getCurrFollowKey();
var currentRuleReSyncSet = this.getFollowSetFromFollowKey(followKey);
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.contains)(currentRuleReSyncSet, tokenTypeIdx);
};
Recoverable.prototype.findReSyncTokenType = function () {
var allPossibleReSyncTokTypes = this.flattenFollowSet();
// this loop will always terminate as EOF is always in the follow stack and also always (virtually) in the input
var nextToken = this.LA(1);
var k = 2;
while (true) {
var nextTokenType = nextToken.tokenType;
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.contains)(allPossibleReSyncTokTypes, nextTokenType)) {
return nextTokenType;
}
nextToken = this.LA(k);
k++;
}
};
Recoverable.prototype.getCurrFollowKey = function () {
// the length is at least one as we always add the ruleName to the stack before invoking the rule.
if (this.RULE_STACK.length === 1) {
return EOF_FOLLOW_KEY;
}
var currRuleShortName = this.getLastExplicitRuleShortName();
var currRuleIdx = this.getLastExplicitRuleOccurrenceIndex();
var prevRuleShortName = this.getPreviousExplicitRuleShortName();
return {
ruleName: this.shortRuleNameToFullName(currRuleShortName),
idxInCallingRule: currRuleIdx,
inRule: this.shortRuleNameToFullName(prevRuleShortName)
};
};
Recoverable.prototype.buildFullFollowKeyStack = function () {
var _this = this;
var explicitRuleStack = this.RULE_STACK;
var explicitOccurrenceStack = this.RULE_OCCURRENCE_STACK;
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(this.LAST_EXPLICIT_RULE_STACK)) {
explicitRuleStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(this.LAST_EXPLICIT_RULE_STACK, function (idx) { return _this.RULE_STACK[idx]; });
explicitOccurrenceStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(this.LAST_EXPLICIT_RULE_STACK, function (idx) { return _this.RULE_OCCURRENCE_STACK[idx]; });
}
// TODO: only iterate over explicit rules here
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(explicitRuleStack, function (ruleName, idx) {
if (idx === 0) {
return EOF_FOLLOW_KEY;
}
return {
ruleName: _this.shortRuleNameToFullName(ruleName),
idxInCallingRule: explicitOccurrenceStack[idx],
inRule: _this.shortRuleNameToFullName(explicitRuleStack[idx - 1])
};
});
};
Recoverable.prototype.flattenFollowSet = function () {
var _this = this;
var followStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(this.buildFullFollowKeyStack(), function (currKey) {
return _this.getFollowSetFromFollowKey(currKey);
});
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.flatten)(followStack);
};
Recoverable.prototype.getFollowSetFromFollowKey = function (followKey) {
if (followKey === EOF_FOLLOW_KEY) {
return [_scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.EOF];
}
var followName = followKey.ruleName +
followKey.idxInCallingRule +
_constants__WEBPACK_IMPORTED_MODULE_3__.IN +
followKey.inRule;
return this.resyncFollows[followName];
};
// It does not make any sense to include a virtual EOF token in the list of resynced tokens
// as EOF does not really exist and thus does not contain any useful information (line/column numbers)
Recoverable.prototype.addToResyncTokens = function (token, resyncTokens) {
if (!this.tokenMatcher(token, _scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.EOF)) {
resyncTokens.push(token);
}
return resyncTokens;
};
Recoverable.prototype.reSyncTo = function (tokType) {
var resyncedTokens = [];
var nextTok = this.LA(1);
while (this.tokenMatcher(nextTok, tokType) === false) {
nextTok = this.SKIP_TOKEN();
this.addToResyncTokens(nextTok, resyncedTokens);
}
// the last token is not part of the error.
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.dropRight)(resyncedTokens);
};
Recoverable.prototype.attemptInRepetitionRecovery = function (prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) {
// by default this is a NO-OP
// The actual implementation is with the function(not method) below
};
Recoverable.prototype.getCurrentGrammarPath = function (tokType, tokIdxInRule) {
var pathRuleStack = this.getHumanReadableRuleStack();
var pathOccurrenceStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(this.RULE_OCCURRENCE_STACK);
var grammarPath = {
ruleStack: pathRuleStack,
occurrenceStack: pathOccurrenceStack,
lastTok: tokType,
lastTokOccurrence: tokIdxInRule
};
return grammarPath;
};
Recoverable.prototype.getHumanReadableRuleStack = function () {
var _this = this;
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isEmpty)(this.LAST_EXPLICIT_RULE_STACK)) {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(this.LAST_EXPLICIT_RULE_STACK, function (currIdx) {
return _this.shortRuleNameToFullName(_this.RULE_STACK[currIdx]);
});
}
else {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.map)(this.RULE_STACK, function (currShortName) {
return _this.shortRuleNameToFullName(currShortName);
});
}
};
return Recoverable;
}());
function attemptInRepetitionRecovery(prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) {
var key = this.getKeyForAutomaticLookahead(dslMethodIdx, prodOccurrence);
var firstAfterRepInfo = this.firstAfterRepMap[key];
if (firstAfterRepInfo === undefined) {
var currRuleName = this.getCurrRuleFullName();
var ruleGrammar = this.getGAstProductions()[currRuleName];
var walker = new nextToksWalker(ruleGrammar, prodOccurrence);
firstAfterRepInfo = walker.startWalking();
this.firstAfterRepMap[key] = firstAfterRepInfo;
}
var expectTokAfterLastMatch = firstAfterRepInfo.token;
var nextTokIdx = firstAfterRepInfo.occurrence;
var isEndOfRule = firstAfterRepInfo.isEndOfRule;
// special edge case of a TOP most repetition after which the input should END.
// this will force an attempt for inRule recovery in that scenario.
if (this.RULE_STACK.length === 1 &&
isEndOfRule &&
expectTokAfterLastMatch === undefined) {
expectTokAfterLastMatch = _scan_tokens_public__WEBPACK_IMPORTED_MODULE_0__.EOF;
nextTokIdx = 1;
}
if (this.shouldInRepetitionRecoveryBeTried(expectTokAfterLastMatch, nextTokIdx, notStuck)) {
// TODO: performance optimization: instead of passing the original args here, we modify
// the args param (or create a new one) and make sure the lookahead func is explicitly provided
// to avoid searching the cache for it once more.
this.tryInRepetitionRecovery(prodFunc, args, lookaheadFunc, expectTokAfterLastMatch);
}
}
//# sourceMappingURL=recoverable.js.map
/***/ }),
/* 42 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ EarlyExitException: () => (/* binding */ EarlyExitException),
/* harmony export */ MismatchedTokenException: () => (/* binding */ MismatchedTokenException),
/* harmony export */ NoViableAltException: () => (/* binding */ NoViableAltException),
/* harmony export */ NotAllInputParsedException: () => (/* binding */ NotAllInputParsedException),
/* harmony export */ isRecognitionException: () => (/* binding */ isRecognitionException)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
var MISMATCHED_TOKEN_EXCEPTION = "MismatchedTokenException";
var NO_VIABLE_ALT_EXCEPTION = "NoViableAltException";
var EARLY_EXIT_EXCEPTION = "EarlyExitException";
var NOT_ALL_INPUT_PARSED_EXCEPTION = "NotAllInputParsedException";
var RECOGNITION_EXCEPTION_NAMES = [
MISMATCHED_TOKEN_EXCEPTION,
NO_VIABLE_ALT_EXCEPTION,
EARLY_EXIT_EXCEPTION,
NOT_ALL_INPUT_PARSED_EXCEPTION
];
Object.freeze(RECOGNITION_EXCEPTION_NAMES);
// hacks to bypass no support for custom Errors in javascript/typescript
function isRecognitionException(error) {
// can't do instanceof on hacked custom js exceptions
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains)(RECOGNITION_EXCEPTION_NAMES, error.name);
}
function MismatchedTokenException(message, token, previousToken) {
this.name = MISMATCHED_TOKEN_EXCEPTION;
this.message = message;
this.token = token;
this.previousToken = previousToken;
this.resyncedTokens = [];
}
// must use the "Error.prototype" instead of "new Error"
// because the stack trace points to where "new Error" was invoked"
MismatchedTokenException.prototype = Error.prototype;
function NoViableAltException(message, token, previousToken) {
this.name = NO_VIABLE_ALT_EXCEPTION;
this.message = message;
this.token = token;
this.previousToken = previousToken;
this.resyncedTokens = [];
}
NoViableAltException.prototype = Error.prototype;
function NotAllInputParsedException(message, token) {
this.name = NOT_ALL_INPUT_PARSED_EXCEPTION;
this.message = message;
this.token = token;
this.resyncedTokens = [];
}
NotAllInputParsedException.prototype = Error.prototype;
function EarlyExitException(message, token, previousToken) {
this.name = EARLY_EXIT_EXCEPTION;
this.message = message;
this.token = token;
this.previousToken = previousToken;
this.resyncedTokens = [];
}
EarlyExitException.prototype = Error.prototype;
//# sourceMappingURL=exceptions_public.js.map
/***/ }),
/* 43 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ LooksAhead: () => (/* binding */ LooksAhead)
/* harmony export */ });
/* harmony import */ var _grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(37);
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17);
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(16);
/* harmony import */ var _grammar_keys__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(34);
/* harmony import */ var _grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(30);
/**
* Trait responsible for the lookahead related utilities and optimizations.
*/
var LooksAhead = /** @class */ (function () {
function LooksAhead() {
}
LooksAhead.prototype.initLooksAhead = function (config) {
this.dynamicTokensEnabled = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.has)(config, "dynamicTokensEnabled")
? config.dynamicTokensEnabled
: _parser__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled;
this.maxLookahead = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.has)(config, "maxLookahead")
? config.maxLookahead
: _parser__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_PARSER_CONFIG.maxLookahead;
/* istanbul ignore next - Using plain array as dictionary will be tested on older node.js versions and IE11 */
this.lookAheadFuncsCache = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isES2015MapSupported)() ? new Map() : [];
// Performance optimization on newer engines that support ES6 Map
// For larger Maps this is slightly faster than using a plain object (array in our case).
/* istanbul ignore else - The else branch will be tested on older node.js versions and IE11 */
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isES2015MapSupported)()) {
this.getLaFuncFromCache = this.getLaFuncFromMap;
this.setLaFuncCache = this.setLaFuncCacheUsingMap;
}
else {
this.getLaFuncFromCache = this.getLaFuncFromObj;
this.setLaFuncCache = this.setLaFuncUsingObj;
}
};
LooksAhead.prototype.preComputeLookaheadFunctions = function (rules) {
var _this = this;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(rules, function (currRule) {
_this.TRACE_INIT(currRule.name + " Rule Lookahead", function () {
var _a = (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__.collectMethods)(currRule), alternation = _a.alternation, repetition = _a.repetition, option = _a.option, repetitionMandatory = _a.repetitionMandatory, repetitionMandatoryWithSeparator = _a.repetitionMandatoryWithSeparator, repetitionWithSeparator = _a.repetitionWithSeparator;
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(alternation, function (currProd) {
var prodIdx = currProd.idx === 0 ? "" : currProd.idx;
_this.TRACE_INIT("" + (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__.getProductionDslName)(currProd) + prodIdx, function () {
var laFunc = (0,_grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.buildLookaheadFuncForOr)(currProd.idx, currRule, currProd.maxLookahead || _this.maxLookahead, currProd.hasPredicates, _this.dynamicTokensEnabled, _this.lookAheadBuilderForAlternatives);
var key = (0,_grammar_keys__WEBPACK_IMPORTED_MODULE_3__.getKeyForAutomaticLookahead)(_this.fullRuleNameToShort[currRule.name], _grammar_keys__WEBPACK_IMPORTED_MODULE_3__.OR_IDX, currProd.idx);
_this.setLaFuncCache(key, laFunc);
});
});
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(repetition, function (currProd) {
_this.computeLookaheadFunc(currRule, currProd.idx, _grammar_keys__WEBPACK_IMPORTED_MODULE_3__.MANY_IDX, _grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.PROD_TYPE.REPETITION, currProd.maxLookahead, (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__.getProductionDslName)(currProd));
});
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(option, function (currProd) {
_this.computeLookaheadFunc(currRule, currProd.idx, _grammar_keys__WEBPACK_IMPORTED_MODULE_3__.OPTION_IDX, _grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.PROD_TYPE.OPTION, currProd.maxLookahead, (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__.getProductionDslName)(currProd));
});
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(repetitionMandatory, function (currProd) {
_this.computeLookaheadFunc(currRule, currProd.idx, _grammar_keys__WEBPACK_IMPORTED_MODULE_3__.AT_LEAST_ONE_IDX, _grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.PROD_TYPE.REPETITION_MANDATORY, currProd.maxLookahead, (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__.getProductionDslName)(currProd));
});
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(repetitionMandatoryWithSeparator, function (currProd) {
_this.computeLookaheadFunc(currRule, currProd.idx, _grammar_keys__WEBPACK_IMPORTED_MODULE_3__.AT_LEAST_ONE_SEP_IDX, _grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currProd.maxLookahead, (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__.getProductionDslName)(currProd));
});
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.forEach)(repetitionWithSeparator, function (currProd) {
_this.computeLookaheadFunc(currRule, currProd.idx, _grammar_keys__WEBPACK_IMPORTED_MODULE_3__.MANY_SEP_IDX, _grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.PROD_TYPE.REPETITION_WITH_SEPARATOR, currProd.maxLookahead, (0,_grammar_gast_gast__WEBPACK_IMPORTED_MODULE_4__.getProductionDslName)(currProd));
});
});
});
};
LooksAhead.prototype.computeLookaheadFunc = function (rule, prodOccurrence, prodKey, prodType, prodMaxLookahead, dslMethodName) {
var _this = this;
this.TRACE_INIT("" + dslMethodName + (prodOccurrence === 0 ? "" : prodOccurrence), function () {
var laFunc = (0,_grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.buildLookaheadFuncForOptionalProd)(prodOccurrence, rule, prodMaxLookahead || _this.maxLookahead, _this.dynamicTokensEnabled, prodType, _this.lookAheadBuilderForOptional);
var key = (0,_grammar_keys__WEBPACK_IMPORTED_MODULE_3__.getKeyForAutomaticLookahead)(_this.fullRuleNameToShort[rule.name], prodKey, prodOccurrence);
_this.setLaFuncCache(key, laFunc);
});
};
LooksAhead.prototype.lookAheadBuilderForOptional = function (alt, tokenMatcher, dynamicTokensEnabled) {
return (0,_grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.buildSingleAlternativeLookaheadFunction)(alt, tokenMatcher, dynamicTokensEnabled);
};
LooksAhead.prototype.lookAheadBuilderForAlternatives = function (alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) {
return (0,_grammar_lookahead__WEBPACK_IMPORTED_MODULE_0__.buildAlternativesLookAheadFunc)(alts, hasPredicates, tokenMatcher, dynamicTokensEnabled);
};
// this actually returns a number, but it is always used as a string (object prop key)
LooksAhead.prototype.getKeyForAutomaticLookahead = function (dslMethodIdx, occurrence) {
var currRuleShortName = this.getLastExplicitRuleShortName();
return (0,_grammar_keys__WEBPACK_IMPORTED_MODULE_3__.getKeyForAutomaticLookahead)(currRuleShortName, dslMethodIdx, occurrence);
};
/* istanbul ignore next */
LooksAhead.prototype.getLaFuncFromCache = function (key) {
return undefined;
};
LooksAhead.prototype.getLaFuncFromMap = function (key) {
return this.lookAheadFuncsCache.get(key);
};
/* istanbul ignore next - Using plain array as dictionary will be tested on older node.js versions and IE11 */
LooksAhead.prototype.getLaFuncFromObj = function (key) {
return this.lookAheadFuncsCache[key];
};
/* istanbul ignore next */
LooksAhead.prototype.setLaFuncCache = function (key, value) { };
LooksAhead.prototype.setLaFuncCacheUsingMap = function (key, value) {
this.lookAheadFuncsCache.set(key, value);
};
/* istanbul ignore next - Using plain array as dictionary will be tested on older node.js versions and IE11 */
LooksAhead.prototype.setLaFuncUsingObj = function (key, value) {
this.lookAheadFuncsCache[key] = value;
};
return LooksAhead;
}());
//# sourceMappingURL=looksahead.js.map
/***/ }),
/* 44 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ TreeBuilder: () => (/* binding */ TreeBuilder)
/* harmony export */ });
/* harmony import */ var _cst_cst__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(33);
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17);
/* harmony import */ var _cst_cst_visitor__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(45);
/* harmony import */ var _grammar_keys__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(34);
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(16);
/**
* This trait is responsible for the CST building logic.
*/
var TreeBuilder = /** @class */ (function () {
function TreeBuilder() {
}
TreeBuilder.prototype.initTreeBuilder = function (config) {
this.LAST_EXPLICIT_RULE_STACK = [];
this.CST_STACK = [];
this.outputCst = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.has)(config, "outputCst")
? config.outputCst
: _parser__WEBPACK_IMPORTED_MODULE_4__.DEFAULT_PARSER_CONFIG.outputCst;
this.nodeLocationTracking = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.has)(config, "nodeLocationTracking")
? config.nodeLocationTracking
: _parser__WEBPACK_IMPORTED_MODULE_4__.DEFAULT_PARSER_CONFIG.nodeLocationTracking;
if (!this.outputCst) {
this.cstInvocationStateUpdate = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
this.cstFinallyStateUpdate = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
this.cstPostTerminal = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
this.cstPostNonTerminal = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
this.cstPostRule = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
this.getLastExplicitRuleShortName = this.getLastExplicitRuleShortNameNoCst;
this.getPreviousExplicitRuleShortName = this.getPreviousExplicitRuleShortNameNoCst;
this.getLastExplicitRuleOccurrenceIndex = this.getLastExplicitRuleOccurrenceIndexNoCst;
this.manyInternal = this.manyInternalNoCst;
this.orInternal = this.orInternalNoCst;
this.optionInternal = this.optionInternalNoCst;
this.atLeastOneInternal = this.atLeastOneInternalNoCst;
this.manySepFirstInternal = this.manySepFirstInternalNoCst;
this.atLeastOneSepFirstInternal = this.atLeastOneSepFirstInternalNoCst;
}
else {
if (/full/i.test(this.nodeLocationTracking)) {
if (this.recoveryEnabled) {
this.setNodeLocationFromToken = _cst_cst__WEBPACK_IMPORTED_MODULE_0__.setNodeLocationFull;
this.setNodeLocationFromNode = _cst_cst__WEBPACK_IMPORTED_MODULE_0__.setNodeLocationFull;
this.cstPostRule = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery;
}
else {
this.setNodeLocationFromToken = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
this.setNodeLocationFromNode = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
this.cstPostRule = this.cstPostRuleFull;
this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular;
}
}
else if (/onlyOffset/i.test(this.nodeLocationTracking)) {
if (this.recoveryEnabled) {
this.setNodeLocationFromToken = (_cst_cst__WEBPACK_IMPORTED_MODULE_0__.setNodeLocationOnlyOffset);
this.setNodeLocationFromNode = (_cst_cst__WEBPACK_IMPORTED_MODULE_0__.setNodeLocationOnlyOffset);
this.cstPostRule = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery;
}
else {
this.setNodeLocationFromToken = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
this.setNodeLocationFromNode = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
this.cstPostRule = this.cstPostRuleOnlyOffset;
this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular;
}
}
else if (/none/i.test(this.nodeLocationTracking)) {
this.setNodeLocationFromToken = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
this.setNodeLocationFromNode = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
this.cstPostRule = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
this.setInitialNodeLocation = _utils_utils__WEBPACK_IMPORTED_MODULE_1__.NOOP;
}
else {
throw Error("Invalid <nodeLocationTracking> config option: \"" + config.nodeLocationTracking + "\"");
}
}
};
TreeBuilder.prototype.setInitialNodeLocationOnlyOffsetRecovery = function (cstNode) {
cstNode.location = {
startOffset: NaN,
endOffset: NaN
};
};
TreeBuilder.prototype.setInitialNodeLocationOnlyOffsetRegular = function (cstNode) {
cstNode.location = {
// without error recovery the starting Location of a new CstNode is guaranteed
// To be the next Token's startOffset (for valid inputs).
// For invalid inputs there won't be any CSTOutput so this potential
// inaccuracy does not matter
startOffset: this.LA(1).startOffset,
endOffset: NaN
};
};
TreeBuilder.prototype.setInitialNodeLocationFullRecovery = function (cstNode) {
cstNode.location = {
startOffset: NaN,
startLine: NaN,
startColumn: NaN,
endOffset: NaN,
endLine: NaN,
endColumn: NaN
};
};
/**
* @see setInitialNodeLocationOnlyOffsetRegular for explanation why this work
* @param cstNode
*/
TreeBuilder.prototype.setInitialNodeLocationFullRegular = function (cstNode) {
var nextToken = this.LA(1);
cstNode.location = {
startOffset: nextToken.startOffset,
startLine: nextToken.startLine,
startColumn: nextToken.startColumn,
endOffset: NaN,
endLine: NaN,
endColumn: NaN
};
};
// CST
TreeBuilder.prototype.cstNestedInvocationStateUpdate = function (nestedName, shortName) {
var cstNode = {
name: nestedName,
fullName: this.shortRuleNameToFull[this.getLastExplicitRuleShortName()] +
nestedName,
children: {}
};
this.setInitialNodeLocation(cstNode);
this.CST_STACK.push(cstNode);
};
TreeBuilder.prototype.cstInvocationStateUpdate = function (fullRuleName, shortName) {
this.LAST_EXPLICIT_RULE_STACK.push(this.RULE_STACK.length - 1);
var cstNode = {
name: fullRuleName,
children: {}
};
this.setInitialNodeLocation(cstNode);
this.CST_STACK.push(cstNode);
};
TreeBuilder.prototype.cstFinallyStateUpdate = function () {
this.LAST_EXPLICIT_RULE_STACK.pop();
this.CST_STACK.pop();
};
TreeBuilder.prototype.cstNestedFinallyStateUpdate = function () {
var lastCstNode = this.CST_STACK.pop();
// TODO: the naming is bad, this should go directly to the
// (correct) cstLocation update method
// e.g if we put other logic in postRule...
this.cstPostRule(lastCstNode);
};
TreeBuilder.prototype.cstPostRuleFull = function (ruleCstNode) {
var prevToken = this.LA(0);
var loc = ruleCstNode.location;
// If this condition is true it means we consumed at least one Token
// In this CstNode or its nested children.
if (loc.startOffset <= prevToken.startOffset === true) {
loc.endOffset = prevToken.endOffset;
loc.endLine = prevToken.endLine;
loc.endColumn = prevToken.endColumn;
}
// "empty" CstNode edge case
else {
loc.startOffset = NaN;
loc.startLine = NaN;
loc.startColumn = NaN;
}
};
TreeBuilder.prototype.cstPostRuleOnlyOffset = function (ruleCstNode) {
var prevToken = this.LA(0);
var loc = ruleCstNode.location;
// If this condition is true it means we consumed at least one Token
// In this CstNode or its nested children.
if (loc.startOffset <= prevToken.startOffset === true) {
loc.endOffset = prevToken.endOffset;
}
// "empty" CstNode edge case
else {
loc.startOffset = NaN;
}
};
TreeBuilder.prototype.cstPostTerminal = function (key, consumedToken) {
var rootCst = this.CST_STACK[this.CST_STACK.length - 1];
(0,_cst_cst__WEBPACK_IMPORTED_MODULE_0__.addTerminalToCst)(rootCst, consumedToken, key);
// This is only used when **both** error recovery and CST Output are enabled.
this.setNodeLocationFromToken(rootCst.location, consumedToken);
};
TreeBuilder.prototype.cstPostNonTerminal = function (ruleCstResult, ruleName) {
// Avoid side effects due to back tracking
// TODO: This costs a 2-3% in performance, A flag on IParserConfig
// could be used to get rid of this conditional, but not sure its worth the effort
// and API complexity.
if (this.isBackTracking() !== true) {
var preCstNode = this.CST_STACK[this.CST_STACK.length - 1];
(0,_cst_cst__WEBPACK_IMPORTED_MODULE_0__.addNoneTerminalToCst)(preCstNode, ruleName, ruleCstResult);
// This is only used when **both** error recovery and CST Output are enabled.
this.setNodeLocationFromNode(preCstNode.location, ruleCstResult.location);
}
};
TreeBuilder.prototype.getBaseCstVisitorConstructor = function () {
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isUndefined)(this.baseCstVisitorConstructor)) {
var newBaseCstVisitorConstructor = (0,_cst_cst_visitor__WEBPACK_IMPORTED_MODULE_2__.createBaseSemanticVisitorConstructor)(this.className, this.allRuleNames);
this.baseCstVisitorConstructor = newBaseCstVisitorConstructor;
return newBaseCstVisitorConstructor;
}
return this.baseCstVisitorConstructor;
};
TreeBuilder.prototype.getBaseCstVisitorConstructorWithDefaults = function () {
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isUndefined)(this.baseCstVisitorWithDefaultsConstructor)) {
var newConstructor = (0,_cst_cst_visitor__WEBPACK_IMPORTED_MODULE_2__.createBaseVisitorConstructorWithDefaults)(this.className, this.allRuleNames, this.getBaseCstVisitorConstructor());
this.baseCstVisitorWithDefaultsConstructor = newConstructor;
return newConstructor;
}
return this.baseCstVisitorWithDefaultsConstructor;
};
TreeBuilder.prototype.nestedRuleBeforeClause = function (methodOpts, laKey) {
var nestedName;
if (methodOpts.NAME !== undefined) {
nestedName = methodOpts.NAME;
this.nestedRuleInvocationStateUpdate(nestedName, laKey);
return nestedName;
}
else {
return undefined;
}
};
TreeBuilder.prototype.nestedAltBeforeClause = function (methodOpts, occurrence, methodKeyIdx, altIdx) {
var ruleIdx = this.getLastExplicitRuleShortName();
var shortName = (0,_grammar_keys__WEBPACK_IMPORTED_MODULE_3__.getKeyForAltIndex)(ruleIdx, methodKeyIdx, occurrence, altIdx);
var nestedName;
if (methodOpts.NAME !== undefined) {
nestedName = methodOpts.NAME;
this.nestedRuleInvocationStateUpdate(nestedName, shortName);
return {
shortName: shortName,
nestedName: nestedName
};
}
else {
return undefined;
}
};
TreeBuilder.prototype.nestedRuleFinallyClause = function (laKey, nestedName) {
var cstStack = this.CST_STACK;
var nestedRuleCst = cstStack[cstStack.length - 1];
this.nestedRuleFinallyStateUpdate();
// this return a different result than the previous invocation because "nestedRuleFinallyStateUpdate" pops the cst stack
var parentCstNode = cstStack[cstStack.length - 1];
(0,_cst_cst__WEBPACK_IMPORTED_MODULE_0__.addNoneTerminalToCst)(parentCstNode, nestedName, nestedRuleCst);
this.setNodeLocationFromNode(parentCstNode.location, nestedRuleCst.location);
};
TreeBuilder.prototype.getLastExplicitRuleShortName = function () {
var lastExplictIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 1];
return this.RULE_STACK[lastExplictIndex];
};
TreeBuilder.prototype.getLastExplicitRuleShortNameNoCst = function () {
var ruleStack = this.RULE_STACK;
return ruleStack[ruleStack.length - 1];
};
TreeBuilder.prototype.getPreviousExplicitRuleShortName = function () {
var lastExplicitIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 2];
return this.RULE_STACK[lastExplicitIndex];
};
TreeBuilder.prototype.getPreviousExplicitRuleShortNameNoCst = function () {
var ruleStack = this.RULE_STACK;
return ruleStack[ruleStack.length - 2];
};
TreeBuilder.prototype.getLastExplicitRuleOccurrenceIndex = function () {
var lastExplicitIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 1];
return this.RULE_OCCURRENCE_STACK[lastExplicitIndex];
};
TreeBuilder.prototype.getLastExplicitRuleOccurrenceIndexNoCst = function () {
var occurrenceStack = this.RULE_OCCURRENCE_STACK;
return occurrenceStack[occurrenceStack.length - 1];
};
TreeBuilder.prototype.nestedRuleInvocationStateUpdate = function (nestedRuleName, shortNameKey) {
this.RULE_OCCURRENCE_STACK.push(1);
this.RULE_STACK.push(shortNameKey);
this.cstNestedInvocationStateUpdate(nestedRuleName, shortNameKey);
};
TreeBuilder.prototype.nestedRuleFinallyStateUpdate = function () {
this.RULE_STACK.pop();
this.RULE_OCCURRENCE_STACK.pop();
// NOOP when cst is disabled
this.cstNestedFinallyStateUpdate();
};
return TreeBuilder;
}());
//# sourceMappingURL=tree_builder.js.map
/***/ }),
/* 45 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CstVisitorDefinitionError: () => (/* binding */ CstVisitorDefinitionError),
/* harmony export */ createBaseSemanticVisitorConstructor: () => (/* binding */ createBaseSemanticVisitorConstructor),
/* harmony export */ createBaseVisitorConstructorWithDefaults: () => (/* binding */ createBaseVisitorConstructorWithDefaults),
/* harmony export */ defaultVisit: () => (/* binding */ defaultVisit),
/* harmony export */ validateMissingCstMethods: () => (/* binding */ validateMissingCstMethods),
/* harmony export */ validateRedundantMethods: () => (/* binding */ validateRedundantMethods),
/* harmony export */ validateVisitor: () => (/* binding */ validateVisitor)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _lang_lang_extensions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(46);
/* harmony import */ var _grammar_checks__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(36);
function defaultVisit(ctx, param) {
var childrenNames = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.keys)(ctx);
var childrenNamesLength = childrenNames.length;
for (var i = 0; i < childrenNamesLength; i++) {
var currChildName = childrenNames[i];
var currChildArray = ctx[currChildName];
var currChildArrayLength = currChildArray.length;
for (var j = 0; j < currChildArrayLength; j++) {
var currChild = currChildArray[j];
// distinction between Tokens Children and CstNode children
if (currChild.tokenTypeIdx === undefined) {
if (currChild.fullName !== undefined) {
this[currChild.fullName](currChild.children, param);
}
else {
this[currChild.name](currChild.children, param);
}
}
}
}
// defaultVisit does not support generic out param
return undefined;
}
function createBaseSemanticVisitorConstructor(grammarName, ruleNames) {
var derivedConstructor = function () { };
// can be overwritten according to:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/
// name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname
(0,_lang_lang_extensions__WEBPACK_IMPORTED_MODULE_1__.defineNameProp)(derivedConstructor, grammarName + "BaseSemantics");
var semanticProto = {
visit: function (cstNode, param) {
// enables writing more concise visitor methods when CstNode has only a single child
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isArray)(cstNode)) {
// A CST Node's children dictionary can never have empty arrays as values
// If a key is defined there will be at least one element in the corresponding value array.
cstNode = cstNode[0];
}
// enables passing optional CstNodes concisely.
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(cstNode)) {
return undefined;
}
if (cstNode.fullName !== undefined) {
return this[cstNode.fullName](cstNode.children, param);
}
else {
return this[cstNode.name](cstNode.children, param);
}
},
validateVisitor: function () {
var semanticDefinitionErrors = validateVisitor(this, ruleNames);
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(semanticDefinitionErrors)) {
var errorMessages = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(semanticDefinitionErrors, function (currDefError) { return currDefError.msg; });
throw Error("Errors Detected in CST Visitor <" + (0,_lang_lang_extensions__WEBPACK_IMPORTED_MODULE_1__.functionName)(this.constructor) + ">:\n\t" +
("" + errorMessages.join("\n\n").replace(/\n/g, "\n\t")));
}
}
};
derivedConstructor.prototype = semanticProto;
derivedConstructor.prototype.constructor = derivedConstructor;
derivedConstructor._RULE_NAMES = ruleNames;
return derivedConstructor;
}
function createBaseVisitorConstructorWithDefaults(grammarName, ruleNames, baseConstructor) {
var derivedConstructor = function () { };
// can be overwritten according to:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/
// name?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FGlobal_Objects%2FFunction%2Fname
(0,_lang_lang_extensions__WEBPACK_IMPORTED_MODULE_1__.defineNameProp)(derivedConstructor, grammarName + "BaseSemanticsWithDefaults");
var withDefaultsProto = Object.create(baseConstructor.prototype);
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(ruleNames, function (ruleName) {
withDefaultsProto[ruleName] = defaultVisit;
});
derivedConstructor.prototype = withDefaultsProto;
derivedConstructor.prototype.constructor = derivedConstructor;
return derivedConstructor;
}
var CstVisitorDefinitionError;
(function (CstVisitorDefinitionError) {
CstVisitorDefinitionError[CstVisitorDefinitionError["REDUNDANT_METHOD"] = 0] = "REDUNDANT_METHOD";
CstVisitorDefinitionError[CstVisitorDefinitionError["MISSING_METHOD"] = 1] = "MISSING_METHOD";
})(CstVisitorDefinitionError || (CstVisitorDefinitionError = {}));
function validateVisitor(visitorInstance, ruleNames) {
var missingErrors = validateMissingCstMethods(visitorInstance, ruleNames);
var redundantErrors = validateRedundantMethods(visitorInstance, ruleNames);
return missingErrors.concat(redundantErrors);
}
function validateMissingCstMethods(visitorInstance, ruleNames) {
var errors = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(ruleNames, function (currRuleName) {
if (!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isFunction)(visitorInstance[currRuleName])) {
return {
msg: "Missing visitor method: <" + currRuleName + "> on " + (0,_lang_lang_extensions__WEBPACK_IMPORTED_MODULE_1__.functionName)(visitorInstance.constructor) + " CST Visitor.",
type: CstVisitorDefinitionError.MISSING_METHOD,
methodName: currRuleName
};
}
});
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.compact)(errors);
}
var VALID_PROP_NAMES = ["constructor", "visit", "validateVisitor"];
function validateRedundantMethods(visitorInstance, ruleNames) {
var errors = [];
for (var prop in visitorInstance) {
if (_grammar_checks__WEBPACK_IMPORTED_MODULE_2__.validTermsPattern.test(prop) &&
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isFunction)(visitorInstance[prop]) &&
!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains)(VALID_PROP_NAMES, prop) &&
!(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains)(ruleNames, prop)) {
errors.push({
msg: "Redundant visitor method: <" + prop + "> on " + (0,_lang_lang_extensions__WEBPACK_IMPORTED_MODULE_1__.functionName)(visitorInstance.constructor) + " CST Visitor\n" +
"There is no Grammar Rule corresponding to this method's name.\n" +
("For utility methods on visitor classes use methods names that do not match /" + _grammar_checks__WEBPACK_IMPORTED_MODULE_2__.validTermsPattern.source + "/."),
type: CstVisitorDefinitionError.REDUNDANT_METHOD,
methodName: prop
});
}
}
return errors;
}
//# sourceMappingURL=cst_visitor.js.map
/***/ }),
/* 46 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ classNameFromInstance: () => (/* binding */ classNameFromInstance),
/* harmony export */ defineNameProp: () => (/* binding */ defineNameProp),
/* harmony export */ functionName: () => (/* binding */ functionName)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
function classNameFromInstance(instance) {
return functionName(instance.constructor);
}
var FUNC_NAME_REGEXP = /^\s*function\s*(\S*)\s*\(/;
var NAME = "name";
/* istanbul ignore next too many hacks for IE/old versions of node.js here*/
function functionName(func) {
// Engines that support Function.prototype.name OR the nth (n>1) time after
// the name has been computed in the following else block.
var existingNameProp = func.name;
if (existingNameProp) {
return existingNameProp;
}
// hack for IE and engines that do not support Object.defineProperty on function.name (Node.js 0.10 && 0.12)
var computedName = func.toString().match(FUNC_NAME_REGEXP)[1];
return computedName;
}
/**
* @returns {boolean} - has the property been successfully defined
*/
function defineNameProp(obj, nameValue) {
var namePropDescriptor = Object.getOwnPropertyDescriptor(obj, NAME);
/* istanbul ignore else -> will only run in old versions of node.js */
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isUndefined)(namePropDescriptor) || namePropDescriptor.configurable) {
Object.defineProperty(obj, NAME, {
enumerable: false,
configurable: true,
writable: false,
value: nameValue
});
return true;
}
/* istanbul ignore next -> will only run in old versions of node.js */
return false;
}
//# sourceMappingURL=lang_extensions.js.map
/***/ }),
/* 47 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ LexerAdapter: () => (/* binding */ LexerAdapter)
/* harmony export */ });
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16);
/**
* Trait responsible abstracting over the interaction with Lexer output (Token vector).
*
* This could be generalized to support other kinds of lexers, e.g.
* - Just in Time Lexing / Lexer-Less parsing.
* - Streaming Lexer.
*/
var LexerAdapter = /** @class */ (function () {
function LexerAdapter() {
}
LexerAdapter.prototype.initLexerAdapter = function () {
this.tokVector = [];
this.tokVectorLength = 0;
this.currIdx = -1;
};
Object.defineProperty(LexerAdapter.prototype, "input", {
get: function () {
return this.tokVector;
},
set: function (newInput) {
if (this.selfAnalysisDone !== true) {
throw Error("Missing <performSelfAnalysis> invocation at the end of the Parser's constructor.");
}
this.reset();
this.tokVector = newInput;
this.tokVectorLength = newInput.length;
},
enumerable: true,
configurable: true
});
// skips a token and returns the next token
LexerAdapter.prototype.SKIP_TOKEN = function () {
if (this.currIdx <= this.tokVector.length - 2) {
this.consumeToken();
return this.LA(1);
}
else {
return _parser__WEBPACK_IMPORTED_MODULE_0__.END_OF_FILE;
}
};
// Lexer (accessing Token vector) related methods which can be overridden to implement lazy lexers
// or lexers dependent on parser context.
LexerAdapter.prototype.LA = function (howMuch) {
var soughtIdx = this.currIdx + howMuch;
if (soughtIdx < 0 || this.tokVectorLength <= soughtIdx) {
return _parser__WEBPACK_IMPORTED_MODULE_0__.END_OF_FILE;
}
else {
return this.tokVector[soughtIdx];
}
};
LexerAdapter.prototype.consumeToken = function () {
this.currIdx++;
};
LexerAdapter.prototype.exportLexerState = function () {
return this.currIdx;
};
LexerAdapter.prototype.importLexerState = function (newState) {
this.currIdx = newState;
};
LexerAdapter.prototype.resetLexerState = function () {
this.currIdx = -1;
};
LexerAdapter.prototype.moveToTerminatedState = function () {
this.currIdx = this.tokVector.length - 1;
};
LexerAdapter.prototype.getLexerPosition = function () {
return this.exportLexerState();
};
return LexerAdapter;
}());
//# sourceMappingURL=lexer_adapter.js.map
/***/ }),
/* 48 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ RecognizerApi: () => (/* binding */ RecognizerApi)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _exceptions_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(42);
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(16);
/* harmony import */ var _errors_public__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(35);
/* harmony import */ var _grammar_checks__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(36);
/* harmony import */ var _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(20);
/**
* This trait is responsible for implementing the public API
* for defining Chevrotain parsers, i.e:
* - CONSUME
* - RULE
* - OPTION
* - ...
*/
var RecognizerApi = /** @class */ (function () {
function RecognizerApi() {
}
RecognizerApi.prototype.ACTION = function (impl) {
return impl.call(this);
};
RecognizerApi.prototype.consume = function (idx, tokType, options) {
return this.consumeInternal(tokType, idx, options);
};
RecognizerApi.prototype.subrule = function (idx, ruleToCall, options) {
return this.subruleInternal(ruleToCall, idx, options);
};
RecognizerApi.prototype.option = function (idx, actionORMethodDef) {
return this.optionInternal(actionORMethodDef, idx);
};
RecognizerApi.prototype.or = function (idx, altsOrOpts) {
return this.orInternal(altsOrOpts, idx);
};
RecognizerApi.prototype.many = function (idx, actionORMethodDef) {
return this.manyInternal(idx, actionORMethodDef);
};
RecognizerApi.prototype.atLeastOne = function (idx, actionORMethodDef) {
return this.atLeastOneInternal(idx, actionORMethodDef);
};
RecognizerApi.prototype.CONSUME = function (tokType, options) {
return this.consumeInternal(tokType, 0, options);
};
RecognizerApi.prototype.CONSUME1 = function (tokType, options) {
return this.consumeInternal(tokType, 1, options);
};
RecognizerApi.prototype.CONSUME2 = function (tokType, options) {
return this.consumeInternal(tokType, 2, options);
};
RecognizerApi.prototype.CONSUME3 = function (tokType, options) {
return this.consumeInternal(tokType, 3, options);
};
RecognizerApi.prototype.CONSUME4 = function (tokType, options) {
return this.consumeInternal(tokType, 4, options);
};
RecognizerApi.prototype.CONSUME5 = function (tokType, options) {
return this.consumeInternal(tokType, 5, options);
};
RecognizerApi.prototype.CONSUME6 = function (tokType, options) {
return this.consumeInternal(tokType, 6, options);
};
RecognizerApi.prototype.CONSUME7 = function (tokType, options) {
return this.consumeInternal(tokType, 7, options);
};
RecognizerApi.prototype.CONSUME8 = function (tokType, options) {
return this.consumeInternal(tokType, 8, options);
};
RecognizerApi.prototype.CONSUME9 = function (tokType, options) {
return this.consumeInternal(tokType, 9, options);
};
RecognizerApi.prototype.SUBRULE = function (ruleToCall, options) {
return this.subruleInternal(ruleToCall, 0, options);
};
RecognizerApi.prototype.SUBRULE1 = function (ruleToCall, options) {
return this.subruleInternal(ruleToCall, 1, options);
};
RecognizerApi.prototype.SUBRULE2 = function (ruleToCall, options) {
return this.subruleInternal(ruleToCall, 2, options);
};
RecognizerApi.prototype.SUBRULE3 = function (ruleToCall, options) {
return this.subruleInternal(ruleToCall, 3, options);
};
RecognizerApi.prototype.SUBRULE4 = function (ruleToCall, options) {
return this.subruleInternal(ruleToCall, 4, options);
};
RecognizerApi.prototype.SUBRULE5 = function (ruleToCall, options) {
return this.subruleInternal(ruleToCall, 5, options);
};
RecognizerApi.prototype.SUBRULE6 = function (ruleToCall, options) {
return this.subruleInternal(ruleToCall, 6, options);
};
RecognizerApi.prototype.SUBRULE7 = function (ruleToCall, options) {
return this.subruleInternal(ruleToCall, 7, options);
};
RecognizerApi.prototype.SUBRULE8 = function (ruleToCall, options) {
return this.subruleInternal(ruleToCall, 8, options);
};
RecognizerApi.prototype.SUBRULE9 = function (ruleToCall, options) {
return this.subruleInternal(ruleToCall, 9, options);
};
RecognizerApi.prototype.OPTION = function (actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 0);
};
RecognizerApi.prototype.OPTION1 = function (actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 1);
};
RecognizerApi.prototype.OPTION2 = function (actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 2);
};
RecognizerApi.prototype.OPTION3 = function (actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 3);
};
RecognizerApi.prototype.OPTION4 = function (actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 4);
};
RecognizerApi.prototype.OPTION5 = function (actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 5);
};
RecognizerApi.prototype.OPTION6 = function (actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 6);
};
RecognizerApi.prototype.OPTION7 = function (actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 7);
};
RecognizerApi.prototype.OPTION8 = function (actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 8);
};
RecognizerApi.prototype.OPTION9 = function (actionORMethodDef) {
return this.optionInternal(actionORMethodDef, 9);
};
RecognizerApi.prototype.OR = function (altsOrOpts) {
return this.orInternal(altsOrOpts, 0);
};
RecognizerApi.prototype.OR1 = function (altsOrOpts) {
return this.orInternal(altsOrOpts, 1);
};
RecognizerApi.prototype.OR2 = function (altsOrOpts) {
return this.orInternal(altsOrOpts, 2);
};
RecognizerApi.prototype.OR3 = function (altsOrOpts) {
return this.orInternal(altsOrOpts, 3);
};
RecognizerApi.prototype.OR4 = function (altsOrOpts) {
return this.orInternal(altsOrOpts, 4);
};
RecognizerApi.prototype.OR5 = function (altsOrOpts) {
return this.orInternal(altsOrOpts, 5);
};
RecognizerApi.prototype.OR6 = function (altsOrOpts) {
return this.orInternal(altsOrOpts, 6);
};
RecognizerApi.prototype.OR7 = function (altsOrOpts) {
return this.orInternal(altsOrOpts, 7);
};
RecognizerApi.prototype.OR8 = function (altsOrOpts) {
return this.orInternal(altsOrOpts, 8);
};
RecognizerApi.prototype.OR9 = function (altsOrOpts) {
return this.orInternal(altsOrOpts, 9);
};
RecognizerApi.prototype.MANY = function (actionORMethodDef) {
this.manyInternal(0, actionORMethodDef);
};
RecognizerApi.prototype.MANY1 = function (actionORMethodDef) {
this.manyInternal(1, actionORMethodDef);
};
RecognizerApi.prototype.MANY2 = function (actionORMethodDef) {
this.manyInternal(2, actionORMethodDef);
};
RecognizerApi.prototype.MANY3 = function (actionORMethodDef) {
this.manyInternal(3, actionORMethodDef);
};
RecognizerApi.prototype.MANY4 = function (actionORMethodDef) {
this.manyInternal(4, actionORMethodDef);
};
RecognizerApi.prototype.MANY5 = function (actionORMethodDef) {
this.manyInternal(5, actionORMethodDef);
};
RecognizerApi.prototype.MANY6 = function (actionORMethodDef) {
this.manyInternal(6, actionORMethodDef);
};
RecognizerApi.prototype.MANY7 = function (actionORMethodDef) {
this.manyInternal(7, actionORMethodDef);
};
RecognizerApi.prototype.MANY8 = function (actionORMethodDef) {
this.manyInternal(8, actionORMethodDef);
};
RecognizerApi.prototype.MANY9 = function (actionORMethodDef) {
this.manyInternal(9, actionORMethodDef);
};
RecognizerApi.prototype.MANY_SEP = function (options) {
this.manySepFirstInternal(0, options);
};
RecognizerApi.prototype.MANY_SEP1 = function (options) {
this.manySepFirstInternal(1, options);
};
RecognizerApi.prototype.MANY_SEP2 = function (options) {
this.manySepFirstInternal(2, options);
};
RecognizerApi.prototype.MANY_SEP3 = function (options) {
this.manySepFirstInternal(3, options);
};
RecognizerApi.prototype.MANY_SEP4 = function (options) {
this.manySepFirstInternal(4, options);
};
RecognizerApi.prototype.MANY_SEP5 = function (options) {
this.manySepFirstInternal(5, options);
};
RecognizerApi.prototype.MANY_SEP6 = function (options) {
this.manySepFirstInternal(6, options);
};
RecognizerApi.prototype.MANY_SEP7 = function (options) {
this.manySepFirstInternal(7, options);
};
RecognizerApi.prototype.MANY_SEP8 = function (options) {
this.manySepFirstInternal(8, options);
};
RecognizerApi.prototype.MANY_SEP9 = function (options) {
this.manySepFirstInternal(9, options);
};
RecognizerApi.prototype.AT_LEAST_ONE = function (actionORMethodDef) {
this.atLeastOneInternal(0, actionORMethodDef);
};
RecognizerApi.prototype.AT_LEAST_ONE1 = function (actionORMethodDef) {
return this.atLeastOneInternal(1, actionORMethodDef);
};
RecognizerApi.prototype.AT_LEAST_ONE2 = function (actionORMethodDef) {
this.atLeastOneInternal(2, actionORMethodDef);
};
RecognizerApi.prototype.AT_LEAST_ONE3 = function (actionORMethodDef) {
this.atLeastOneInternal(3, actionORMethodDef);
};
RecognizerApi.prototype.AT_LEAST_ONE4 = function (actionORMethodDef) {
this.atLeastOneInternal(4, actionORMethodDef);
};
RecognizerApi.prototype.AT_LEAST_ONE5 = function (actionORMethodDef) {
this.atLeastOneInternal(5, actionORMethodDef);
};
RecognizerApi.prototype.AT_LEAST_ONE6 = function (actionORMethodDef) {
this.atLeastOneInternal(6, actionORMethodDef);
};
RecognizerApi.prototype.AT_LEAST_ONE7 = function (actionORMethodDef) {
this.atLeastOneInternal(7, actionORMethodDef);
};
RecognizerApi.prototype.AT_LEAST_ONE8 = function (actionORMethodDef) {
this.atLeastOneInternal(8, actionORMethodDef);
};
RecognizerApi.prototype.AT_LEAST_ONE9 = function (actionORMethodDef) {
this.atLeastOneInternal(9, actionORMethodDef);
};
RecognizerApi.prototype.AT_LEAST_ONE_SEP = function (options) {
this.atLeastOneSepFirstInternal(0, options);
};
RecognizerApi.prototype.AT_LEAST_ONE_SEP1 = function (options) {
this.atLeastOneSepFirstInternal(1, options);
};
RecognizerApi.prototype.AT_LEAST_ONE_SEP2 = function (options) {
this.atLeastOneSepFirstInternal(2, options);
};
RecognizerApi.prototype.AT_LEAST_ONE_SEP3 = function (options) {
this.atLeastOneSepFirstInternal(3, options);
};
RecognizerApi.prototype.AT_LEAST_ONE_SEP4 = function (options) {
this.atLeastOneSepFirstInternal(4, options);
};
RecognizerApi.prototype.AT_LEAST_ONE_SEP5 = function (options) {
this.atLeastOneSepFirstInternal(5, options);
};
RecognizerApi.prototype.AT_LEAST_ONE_SEP6 = function (options) {
this.atLeastOneSepFirstInternal(6, options);
};
RecognizerApi.prototype.AT_LEAST_ONE_SEP7 = function (options) {
this.atLeastOneSepFirstInternal(7, options);
};
RecognizerApi.prototype.AT_LEAST_ONE_SEP8 = function (options) {
this.atLeastOneSepFirstInternal(8, options);
};
RecognizerApi.prototype.AT_LEAST_ONE_SEP9 = function (options) {
this.atLeastOneSepFirstInternal(9, options);
};
RecognizerApi.prototype.RULE = function (name, implementation, config) {
if (config === void 0) { config = _parser__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_RULE_CONFIG; }
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.contains)(this.definedRulesNames, name)) {
var errMsg = _errors_public__WEBPACK_IMPORTED_MODULE_3__.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({
topLevelRule: name,
grammarName: this.className
});
var error = {
message: errMsg,
type: _parser__WEBPACK_IMPORTED_MODULE_2__.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,
ruleName: name
};
this.definitionErrors.push(error);
}
this.definedRulesNames.push(name);
var ruleImplementation = this.defineRule(name, implementation, config);
this[name] = ruleImplementation;
return ruleImplementation;
};
RecognizerApi.prototype.OVERRIDE_RULE = function (name, impl, config) {
if (config === void 0) { config = _parser__WEBPACK_IMPORTED_MODULE_2__.DEFAULT_RULE_CONFIG; }
var ruleErrors = [];
ruleErrors = ruleErrors.concat((0,_grammar_checks__WEBPACK_IMPORTED_MODULE_4__.validateRuleIsOverridden)(name, this.definedRulesNames, this.className));
this.definitionErrors.push.apply(this.definitionErrors, ruleErrors); // mutability for the win
var ruleImplementation = this.defineRule(name, impl, config);
this[name] = ruleImplementation;
return ruleImplementation;
};
RecognizerApi.prototype.BACKTRACK = function (grammarRule, args) {
return function () {
// save org state
this.isBackTrackingStack.push(1);
var orgState = this.saveRecogState();
try {
grammarRule.apply(this, args);
// if no exception was thrown we have succeed parsing the rule.
return true;
}
catch (e) {
if ((0,_exceptions_public__WEBPACK_IMPORTED_MODULE_1__.isRecognitionException)(e)) {
return false;
}
else {
throw e;
}
}
finally {
this.reloadRecogState(orgState);
this.isBackTrackingStack.pop();
}
};
};
// GAST export APIs
RecognizerApi.prototype.getGAstProductions = function () {
return this.gastProductionsCache;
};
RecognizerApi.prototype.getSerializedGastProductions = function () {
return (0,_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_5__.serializeGrammar)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(this.gastProductionsCache));
};
return RecognizerApi;
}());
//# sourceMappingURL=recognizer_api.js.map
/***/ }),
/* 49 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ RecognizerEngine: () => (/* binding */ RecognizerEngine)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _grammar_keys__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(34);
/* harmony import */ var _exceptions_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(42);
/* harmony import */ var _grammar_lookahead__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(37);
/* harmony import */ var _grammar_interpreter__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(38);
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(16);
/* harmony import */ var _recoverable__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(41);
/* harmony import */ var _scan_tokens_public__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(21);
/* harmony import */ var _scan_tokens__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(27);
/* harmony import */ var _lang_lang_extensions__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(46);
/**
* This trait is responsible for the runtime parsing engine
* Used by the official API (recognizer_api.ts)
*/
var RecognizerEngine = /** @class */ (function () {
function RecognizerEngine() {
}
RecognizerEngine.prototype.initRecognizerEngine = function (tokenVocabulary, config) {
this.className = (0,_lang_lang_extensions__WEBPACK_IMPORTED_MODULE_9__.classNameFromInstance)(this);
// TODO: would using an ES6 Map or plain object be faster (CST building scenario)
this.shortRuleNameToFull = {};
this.fullRuleNameToShort = {};
this.ruleShortNameIdx = 256;
this.tokenMatcher = _scan_tokens__WEBPACK_IMPORTED_MODULE_8__.tokenStructuredMatcherNoCategories;
this.definedRulesNames = [];
this.tokensMap = {};
this.allRuleNames = [];
this.isBackTrackingStack = [];
this.RULE_STACK = [];
this.RULE_OCCURRENCE_STACK = [];
this.gastProductionsCache = {};
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, "serializedGrammar")) {
throw Error("The Parser's configuration can no longer contain a <serializedGrammar> property.\n" +
"\tSee: https://sap.github.io/chevrotain/docs/changes/BREAKING_CHANGES.html#_6-0-0\n" +
"\tFor Further details.");
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isArray)(tokenVocabulary)) {
// This only checks for Token vocabularies provided as arrays.
// That is good enough because the main objective is to detect users of pre-V4.0 APIs
// rather than all edge cases of empty Token vocabularies.
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(tokenVocabulary)) {
throw Error("A Token Vocabulary cannot be empty.\n" +
"\tNote that the first argument for the parser constructor\n" +
"\tis no longer a Token vector (since v4.0).");
}
if (typeof tokenVocabulary[0].startOffset === "number") {
throw Error("The Parser constructor no longer accepts a token vector as the first argument.\n" +
"\tSee: https://sap.github.io/chevrotain/docs/changes/BREAKING_CHANGES.html#_4-0-0\n" +
"\tFor Further details.");
}
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isArray)(tokenVocabulary)) {
this.tokensMap = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce)(tokenVocabulary, function (acc, tokType) {
acc[tokType.name] = tokType;
return acc;
}, {});
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(tokenVocabulary, "modes") &&
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(tokenVocabulary.modes)), _scan_tokens__WEBPACK_IMPORTED_MODULE_8__.isTokenType)) {
var allTokenTypes = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.flatten)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(tokenVocabulary.modes));
var uniqueTokens = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.uniq)(allTokenTypes);
this.tokensMap = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.reduce)(uniqueTokens, function (acc, tokType) {
acc[tokType.name] = tokType;
return acc;
}, {});
}
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isObject)(tokenVocabulary)) {
this.tokensMap = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.cloneObj)(tokenVocabulary);
}
else {
throw new Error("<tokensDictionary> argument must be An Array of Token constructors," +
" A dictionary of Token constructors or an IMultiModeLexerDefinition");
}
// always add EOF to the tokenNames -> constructors map. it is useful to assure all the input has been
// parsed with a clear error message ("expecting EOF but found ...")
/* tslint:disable */
this.tokensMap["EOF"] = _scan_tokens_public__WEBPACK_IMPORTED_MODULE_7__.EOF;
// TODO: This check may not be accurate for multi mode lexers
var noTokenCategoriesUsed = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.every)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(tokenVocabulary), function (tokenConstructor) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isEmpty)(tokenConstructor.categoryMatches); });
this.tokenMatcher = noTokenCategoriesUsed
? _scan_tokens__WEBPACK_IMPORTED_MODULE_8__.tokenStructuredMatcherNoCategories
: _scan_tokens__WEBPACK_IMPORTED_MODULE_8__.tokenStructuredMatcher;
// Because ES2015+ syntax should be supported for creating Token classes
// We cannot assume that the Token classes were created using the "extendToken" utilities
// Therefore we must augment the Token classes both on Lexer initialization and on Parser initialization
(0,_scan_tokens__WEBPACK_IMPORTED_MODULE_8__.augmentTokenTypes)((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.values)(this.tokensMap));
};
RecognizerEngine.prototype.defineRule = function (ruleName, impl, config) {
if (this.selfAnalysisDone) {
throw Error("Grammar rule <" + ruleName + "> may not be defined after the 'performSelfAnalysis' method has been called'\n" +
"Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.");
}
var resyncEnabled = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, "resyncEnabled")
? config.resyncEnabled
: _parser__WEBPACK_IMPORTED_MODULE_5__.DEFAULT_RULE_CONFIG.resyncEnabled;
var recoveryValueFunc = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, "recoveryValueFunc")
? config.recoveryValueFunc
: _parser__WEBPACK_IMPORTED_MODULE_5__.DEFAULT_RULE_CONFIG.recoveryValueFunc;
// performance optimization: Use small integers as keys for the longer human readable "full" rule names.
// this greatly improves Map access time (as much as 8% for some performance benchmarks).
/* tslint:disable */
var shortName = this.ruleShortNameIdx <<
(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.BITS_FOR_METHOD_TYPE + _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.BITS_FOR_OCCURRENCE_IDX);
/* tslint:enable */
this.ruleShortNameIdx++;
this.shortRuleNameToFull[shortName] = ruleName;
this.fullRuleNameToShort[ruleName] = shortName;
function invokeRuleWithTry(args) {
try {
if (this.outputCst === true) {
impl.apply(this, args);
var cst = this.CST_STACK[this.CST_STACK.length - 1];
this.cstPostRule(cst);
return cst;
}
else {
return impl.apply(this, args);
}
}
catch (e) {
return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc);
}
finally {
this.ruleFinallyStateUpdate();
}
}
var wrappedGrammarRule;
wrappedGrammarRule = function (idxInCallingRule, args) {
if (idxInCallingRule === void 0) { idxInCallingRule = 0; }
this.ruleInvocationStateUpdate(shortName, ruleName, idxInCallingRule);
return invokeRuleWithTry.call(this, args);
};
var ruleNamePropName = "ruleName";
wrappedGrammarRule[ruleNamePropName] = ruleName;
wrappedGrammarRule["originalGrammarAction"] = impl;
return wrappedGrammarRule;
};
RecognizerEngine.prototype.invokeRuleCatch = function (e, resyncEnabledConfig, recoveryValueFunc) {
var isFirstInvokedRule = this.RULE_STACK.length === 1;
// note the reSync is always enabled for the first rule invocation, because we must always be able to
// reSync with EOF and just output some INVALID ParseTree
// during backtracking reSync recovery is disabled, otherwise we can't be certain the backtracking
// path is really the most valid one
var reSyncEnabled = resyncEnabledConfig &&
!this.isBackTracking() &&
this.recoveryEnabled;
if ((0,_exceptions_public__WEBPACK_IMPORTED_MODULE_2__.isRecognitionException)(e)) {
var recogError = e;
if (reSyncEnabled) {
var reSyncTokType = this.findReSyncTokenType();
if (this.isInCurrentRuleReSyncSet(reSyncTokType)) {
recogError.resyncedTokens = this.reSyncTo(reSyncTokType);
if (this.outputCst) {
var partialCstResult = this.CST_STACK[this.CST_STACK.length - 1];
partialCstResult.recoveredNode = true;
return partialCstResult;
}
else {
return recoveryValueFunc();
}
}
else {
if (this.outputCst) {
var partialCstResult = this.CST_STACK[this.CST_STACK.length - 1];
partialCstResult.recoveredNode = true;
recogError.partialCstResult = partialCstResult;
}
// to be handled Further up the call stack
throw recogError;
}
}
else if (isFirstInvokedRule) {
// otherwise a Redundant input error will be created as well and we cannot guarantee that this is indeed the case
this.moveToTerminatedState();
// the parser should never throw one of its own errors outside its flow.
// even if error recovery is disabled
return recoveryValueFunc();
}
else {
// to be recovered Further up the call stack
throw recogError;
}
}
else {
// some other Error type which we don't know how to handle (for example a built in JavaScript Error)
throw e;
}
};
// Implementation of parsing DSL
RecognizerEngine.prototype.optionInternal = function (actionORMethodDef, occurrence) {
var key = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OPTION_IDX, occurrence);
var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, key);
try {
return this.optionInternalLogic(actionORMethodDef, occurrence, key);
}
finally {
if (nestedName !== undefined) {
this.nestedRuleFinallyClause(key, nestedName);
}
}
};
RecognizerEngine.prototype.optionInternalNoCst = function (actionORMethodDef, occurrence) {
var key = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OPTION_IDX, occurrence);
return this.optionInternalLogic(actionORMethodDef, occurrence, key);
};
RecognizerEngine.prototype.optionInternalLogic = function (actionORMethodDef, occurrence, key) {
var _this = this;
var lookAheadFunc = this.getLaFuncFromCache(key);
var action;
var predicate;
if (actionORMethodDef.DEF !== undefined) {
action = actionORMethodDef.DEF;
predicate = actionORMethodDef.GATE;
// predicate present
if (predicate !== undefined) {
var orgLookaheadFunction_1 = lookAheadFunc;
lookAheadFunc = function () {
return (predicate.call(_this) && orgLookaheadFunction_1.call(_this));
};
}
}
else {
action = actionORMethodDef;
}
if (lookAheadFunc.call(this) === true) {
return action.call(this);
}
return undefined;
};
RecognizerEngine.prototype.atLeastOneInternal = function (prodOccurrence, actionORMethodDef) {
var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_IDX, prodOccurrence);
var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, laKey);
try {
return this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, laKey);
}
finally {
if (nestedName !== undefined) {
this.nestedRuleFinallyClause(laKey, nestedName);
}
}
};
RecognizerEngine.prototype.atLeastOneInternalNoCst = function (prodOccurrence, actionORMethodDef) {
var key = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_IDX, prodOccurrence);
this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, key);
};
RecognizerEngine.prototype.atLeastOneInternalLogic = function (prodOccurrence, actionORMethodDef, key) {
var _this = this;
var lookAheadFunc = this.getLaFuncFromCache(key);
var action;
var predicate;
if (actionORMethodDef.DEF !== undefined) {
action = actionORMethodDef.DEF;
predicate = actionORMethodDef.GATE;
// predicate present
if (predicate !== undefined) {
var orgLookaheadFunction_2 = lookAheadFunc;
lookAheadFunc = function () {
return (predicate.call(_this) && orgLookaheadFunction_2.call(_this));
};
}
}
else {
action = actionORMethodDef;
}
if (lookAheadFunc.call(this) === true) {
var notStuck = this.doSingleRepetition(action);
while (lookAheadFunc.call(this) === true &&
notStuck === true) {
notStuck = this.doSingleRepetition(action);
}
}
else {
throw this.raiseEarlyExitException(prodOccurrence, _grammar_lookahead__WEBPACK_IMPORTED_MODULE_3__.PROD_TYPE.REPETITION_MANDATORY, actionORMethodDef.ERR_MSG);
}
// note that while it may seem that this can cause an error because by using a recursive call to
// AT_LEAST_ONE we change the grammar to AT_LEAST_TWO, AT_LEAST_THREE ... , the possible recursive call
// from the tryInRepetitionRecovery(...) will only happen IFF there really are TWO/THREE/.... items.
// Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled
this.attemptInRepetitionRecovery(this.atLeastOneInternal, [prodOccurrence, actionORMethodDef], lookAheadFunc, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_IDX, prodOccurrence, _grammar_interpreter__WEBPACK_IMPORTED_MODULE_4__.NextTerminalAfterAtLeastOneWalker);
};
RecognizerEngine.prototype.atLeastOneSepFirstInternal = function (prodOccurrence, options) {
var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_SEP_IDX, prodOccurrence);
var nestedName = this.nestedRuleBeforeClause(options, laKey);
try {
this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey);
}
finally {
if (nestedName !== undefined) {
this.nestedRuleFinallyClause(laKey, nestedName);
}
}
};
RecognizerEngine.prototype.atLeastOneSepFirstInternalNoCst = function (prodOccurrence, options) {
var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_SEP_IDX, prodOccurrence);
this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey);
};
RecognizerEngine.prototype.atLeastOneSepFirstInternalLogic = function (prodOccurrence, options, key) {
var _this = this;
var action = options.DEF;
var separator = options.SEP;
var firstIterationLookaheadFunc = this.getLaFuncFromCache(key);
// 1st iteration
if (firstIterationLookaheadFunc.call(this) === true) {
;
action.call(this);
// TODO: Optimization can move this function construction into "attemptInRepetitionRecovery"
// because it is only needed in error recovery scenarios.
var separatorLookAheadFunc = function () {
return _this.tokenMatcher(_this.LA(1), separator);
};
// 2nd..nth iterations
while (this.tokenMatcher(this.LA(1), separator) === true) {
// note that this CONSUME will never enter recovery because
// the separatorLookAheadFunc checks that the separator really does exist.
this.CONSUME(separator);
action.call(this);
}
// Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled
this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [
prodOccurrence,
separator,
separatorLookAheadFunc,
action,
_grammar_interpreter__WEBPACK_IMPORTED_MODULE_4__.NextTerminalAfterAtLeastOneSepWalker
], separatorLookAheadFunc, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_SEP_IDX, prodOccurrence, _grammar_interpreter__WEBPACK_IMPORTED_MODULE_4__.NextTerminalAfterAtLeastOneSepWalker);
}
else {
throw this.raiseEarlyExitException(prodOccurrence, _grammar_lookahead__WEBPACK_IMPORTED_MODULE_3__.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, options.ERR_MSG);
}
};
RecognizerEngine.prototype.manyInternal = function (prodOccurrence, actionORMethodDef) {
var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_IDX, prodOccurrence);
var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, laKey);
try {
return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey);
}
finally {
if (nestedName !== undefined) {
this.nestedRuleFinallyClause(laKey, nestedName);
}
}
};
RecognizerEngine.prototype.manyInternalNoCst = function (prodOccurrence, actionORMethodDef) {
var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_IDX, prodOccurrence);
return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey);
};
RecognizerEngine.prototype.manyInternalLogic = function (prodOccurrence, actionORMethodDef, key) {
var _this = this;
var lookaheadFunction = this.getLaFuncFromCache(key);
var action;
var predicate;
if (actionORMethodDef.DEF !== undefined) {
action = actionORMethodDef.DEF;
predicate = actionORMethodDef.GATE;
// predicate present
if (predicate !== undefined) {
var orgLookaheadFunction_3 = lookaheadFunction;
lookaheadFunction = function () {
return (predicate.call(_this) && orgLookaheadFunction_3.call(_this));
};
}
}
else {
action = actionORMethodDef;
}
var notStuck = true;
while (lookaheadFunction.call(this) === true && notStuck === true) {
notStuck = this.doSingleRepetition(action);
}
// Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled
this.attemptInRepetitionRecovery(this.manyInternal, [prodOccurrence, actionORMethodDef], lookaheadFunction, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_IDX, prodOccurrence, _grammar_interpreter__WEBPACK_IMPORTED_MODULE_4__.NextTerminalAfterManyWalker,
// The notStuck parameter is only relevant when "attemptInRepetitionRecovery"
// is invoked from manyInternal, in the MANY_SEP case and AT_LEAST_ONE[_SEP]
// An infinite loop cannot occur as:
// - Either the lookahead is guaranteed to consume something (Single Token Separator)
// - AT_LEAST_ONE by definition is guaranteed to consume something (or error out).
notStuck);
};
RecognizerEngine.prototype.manySepFirstInternal = function (prodOccurrence, options) {
var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_SEP_IDX, prodOccurrence);
var nestedName = this.nestedRuleBeforeClause(options, laKey);
try {
this.manySepFirstInternalLogic(prodOccurrence, options, laKey);
}
finally {
if (nestedName !== undefined) {
this.nestedRuleFinallyClause(laKey, nestedName);
}
}
};
RecognizerEngine.prototype.manySepFirstInternalNoCst = function (prodOccurrence, options) {
var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_SEP_IDX, prodOccurrence);
this.manySepFirstInternalLogic(prodOccurrence, options, laKey);
};
RecognizerEngine.prototype.manySepFirstInternalLogic = function (prodOccurrence, options, key) {
var _this = this;
var action = options.DEF;
var separator = options.SEP;
var firstIterationLaFunc = this.getLaFuncFromCache(key);
// 1st iteration
if (firstIterationLaFunc.call(this) === true) {
action.call(this);
var separatorLookAheadFunc = function () {
return _this.tokenMatcher(_this.LA(1), separator);
};
// 2nd..nth iterations
while (this.tokenMatcher(this.LA(1), separator) === true) {
// note that this CONSUME will never enter recovery because
// the separatorLookAheadFunc checks that the separator really does exist.
this.CONSUME(separator);
// No need for checking infinite loop here due to consuming the separator.
action.call(this);
}
// Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled
this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [
prodOccurrence,
separator,
separatorLookAheadFunc,
action,
_grammar_interpreter__WEBPACK_IMPORTED_MODULE_4__.NextTerminalAfterManySepWalker
], separatorLookAheadFunc, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.MANY_SEP_IDX, prodOccurrence, _grammar_interpreter__WEBPACK_IMPORTED_MODULE_4__.NextTerminalAfterManySepWalker);
}
};
RecognizerEngine.prototype.repetitionSepSecondInternal = function (prodOccurrence, separator, separatorLookAheadFunc, action, nextTerminalAfterWalker) {
while (separatorLookAheadFunc()) {
// note that this CONSUME will never enter recovery because
// the separatorLookAheadFunc checks that the separator really does exist.
this.CONSUME(separator);
action.call(this);
}
// we can only arrive to this function after an error
// has occurred (hence the name 'second') so the following
// IF will always be entered, its possible to remove it...
// however it is kept to avoid confusion and be consistent.
// Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled
/* istanbul ignore else */
this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [
prodOccurrence,
separator,
separatorLookAheadFunc,
action,
nextTerminalAfterWalker
], separatorLookAheadFunc, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.AT_LEAST_ONE_SEP_IDX, prodOccurrence, nextTerminalAfterWalker);
};
RecognizerEngine.prototype.doSingleRepetition = function (action) {
var beforeIteration = this.getLexerPosition();
action.call(this);
var afterIteration = this.getLexerPosition();
// This boolean will indicate if this repetition progressed
// or if we are "stuck" (potential infinite loop in the repetition).
return afterIteration > beforeIteration;
};
RecognizerEngine.prototype.orInternalNoCst = function (altsOrOpts, occurrence) {
var alts = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isArray)(altsOrOpts)
? altsOrOpts
: altsOrOpts.DEF;
var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OR_IDX, occurrence);
var laFunc = this.getLaFuncFromCache(laKey);
var altIdxToTake = laFunc.call(this, alts);
if (altIdxToTake !== undefined) {
var chosenAlternative = alts[altIdxToTake];
return chosenAlternative.ALT.call(this);
}
this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG);
};
RecognizerEngine.prototype.orInternal = function (altsOrOpts, occurrence) {
var laKey = this.getKeyForAutomaticLookahead(_grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OR_IDX, occurrence);
var nestedName = this.nestedRuleBeforeClause(altsOrOpts, laKey);
try {
var alts = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isArray)(altsOrOpts)
? altsOrOpts
: altsOrOpts.DEF;
var laFunc = this.getLaFuncFromCache(laKey);
var altIdxToTake = laFunc.call(this, alts);
if (altIdxToTake !== undefined) {
var chosenAlternative = alts[altIdxToTake];
var nestedAltBeforeClauseResult = this.nestedAltBeforeClause(chosenAlternative, occurrence, _grammar_keys__WEBPACK_IMPORTED_MODULE_1__.OR_IDX, altIdxToTake);
try {
return chosenAlternative.ALT.call(this);
}
finally {
if (nestedAltBeforeClauseResult !== undefined) {
this.nestedRuleFinallyClause(nestedAltBeforeClauseResult.shortName, nestedAltBeforeClauseResult.nestedName);
}
}
}
this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG);
}
finally {
if (nestedName !== undefined) {
this.nestedRuleFinallyClause(laKey, nestedName);
}
}
};
RecognizerEngine.prototype.ruleFinallyStateUpdate = function () {
this.RULE_STACK.pop();
this.RULE_OCCURRENCE_STACK.pop();
// NOOP when cst is disabled
this.cstFinallyStateUpdate();
if (this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) {
var firstRedundantTok = this.LA(1);
var errMsg = this.errorMessageProvider.buildNotAllInputParsedMessage({
firstRedundant: firstRedundantTok,
ruleName: this.getCurrRuleFullName()
});
this.SAVE_ERROR(new _exceptions_public__WEBPACK_IMPORTED_MODULE_2__.NotAllInputParsedException(errMsg, firstRedundantTok));
}
};
RecognizerEngine.prototype.subruleInternal = function (ruleToCall, idx, options) {
var ruleResult;
try {
var args = options !== undefined ? options.ARGS : undefined;
ruleResult = ruleToCall.call(this, idx, args);
this.cstPostNonTerminal(ruleResult, options !== undefined && options.LABEL !== undefined
? options.LABEL
: ruleToCall.ruleName);
return ruleResult;
}
catch (e) {
this.subruleInternalError(e, options, ruleToCall.ruleName);
}
};
RecognizerEngine.prototype.subruleInternalError = function (e, options, ruleName) {
if ((0,_exceptions_public__WEBPACK_IMPORTED_MODULE_2__.isRecognitionException)(e) && e.partialCstResult !== undefined) {
this.cstPostNonTerminal(e.partialCstResult, options !== undefined && options.LABEL !== undefined
? options.LABEL
: ruleName);
delete e.partialCstResult;
}
throw e;
};
RecognizerEngine.prototype.consumeInternal = function (tokType, idx, options) {
var consumedToken;
try {
var nextToken = this.LA(1);
if (this.tokenMatcher(nextToken, tokType) === true) {
this.consumeToken();
consumedToken = nextToken;
}
else {
this.consumeInternalError(tokType, nextToken, options);
}
}
catch (eFromConsumption) {
consumedToken = this.consumeInternalRecovery(tokType, idx, eFromConsumption);
}
this.cstPostTerminal(options !== undefined && options.LABEL !== undefined
? options.LABEL
: tokType.name, consumedToken);
return consumedToken;
};
RecognizerEngine.prototype.consumeInternalError = function (tokType, nextToken, options) {
var msg;
var previousToken = this.LA(0);
if (options !== undefined && options.ERR_MSG) {
msg = options.ERR_MSG;
}
else {
msg = this.errorMessageProvider.buildMismatchTokenMessage({
expected: tokType,
actual: nextToken,
previous: previousToken,
ruleName: this.getCurrRuleFullName()
});
}
throw this.SAVE_ERROR(new _exceptions_public__WEBPACK_IMPORTED_MODULE_2__.MismatchedTokenException(msg, nextToken, previousToken));
};
RecognizerEngine.prototype.consumeInternalRecovery = function (tokType, idx, eFromConsumption) {
// no recovery allowed during backtracking, otherwise backtracking may recover invalid syntax and accept it
// but the original syntax could have been parsed successfully without any backtracking + recovery
if (this.recoveryEnabled &&
// TODO: more robust checking of the exception type. Perhaps Typescript extending expressions?
eFromConsumption.name === "MismatchedTokenException" &&
!this.isBackTracking()) {
var follows = this.getFollowsForInRuleRecovery(tokType, idx);
try {
return this.tryInRuleRecovery(tokType, follows);
}
catch (eFromInRuleRecovery) {
if (eFromInRuleRecovery.name === _recoverable__WEBPACK_IMPORTED_MODULE_6__.IN_RULE_RECOVERY_EXCEPTION) {
// failed in RuleRecovery.
// throw the original error in order to trigger reSync error recovery
throw eFromConsumption;
}
else {
throw eFromInRuleRecovery;
}
}
}
else {
throw eFromConsumption;
}
};
RecognizerEngine.prototype.saveRecogState = function () {
// errors is a getter which will clone the errors array
var savedErrors = this.errors;
var savedRuleStack = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.cloneArr)(this.RULE_STACK);
return {
errors: savedErrors,
lexerState: this.exportLexerState(),
RULE_STACK: savedRuleStack,
CST_STACK: this.CST_STACK,
LAST_EXPLICIT_RULE_STACK: this.LAST_EXPLICIT_RULE_STACK
};
};
RecognizerEngine.prototype.reloadRecogState = function (newState) {
this.errors = newState.errors;
this.importLexerState(newState.lexerState);
this.RULE_STACK = newState.RULE_STACK;
};
RecognizerEngine.prototype.ruleInvocationStateUpdate = function (shortName, fullName, idxInCallingRule) {
this.RULE_OCCURRENCE_STACK.push(idxInCallingRule);
this.RULE_STACK.push(shortName);
// NOOP when cst is disabled
this.cstInvocationStateUpdate(fullName, shortName);
};
RecognizerEngine.prototype.isBackTracking = function () {
return this.isBackTrackingStack.length !== 0;
};
RecognizerEngine.prototype.getCurrRuleFullName = function () {
var shortName = this.getLastExplicitRuleShortName();
return this.shortRuleNameToFull[shortName];
};
RecognizerEngine.prototype.shortRuleNameToFullName = function (shortName) {
return this.shortRuleNameToFull[shortName];
};
RecognizerEngine.prototype.isAtEndOfInput = function () {
return this.tokenMatcher(this.LA(1), _scan_tokens_public__WEBPACK_IMPORTED_MODULE_7__.EOF);
};
RecognizerEngine.prototype.reset = function () {
this.resetLexerState();
this.isBackTrackingStack = [];
this.errors = [];
this.RULE_STACK = [];
this.LAST_EXPLICIT_RULE_STACK = [];
// TODO: extract a specific rest for TreeBuilder trait
this.CST_STACK = [];
this.RULE_OCCURRENCE_STACK = [];
};
return RecognizerEngine;
}());
//# sourceMappingURL=recognizer_engine.js.map
/***/ }),
/* 50 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ErrorHandler: () => (/* binding */ ErrorHandler)
/* harmony export */ });
/* harmony import */ var _exceptions_public__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(42);
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17);
/* harmony import */ var _grammar_lookahead__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(37);
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(16);
/**
* Trait responsible for runtime parsing errors.
*/
var ErrorHandler = /** @class */ (function () {
function ErrorHandler() {
}
ErrorHandler.prototype.initErrorHandler = function (config) {
this._errors = [];
this.errorMessageProvider = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.defaults)(config.errorMessageProvider, _parser__WEBPACK_IMPORTED_MODULE_3__.DEFAULT_PARSER_CONFIG.errorMessageProvider);
};
ErrorHandler.prototype.SAVE_ERROR = function (error) {
if ((0,_exceptions_public__WEBPACK_IMPORTED_MODULE_0__.isRecognitionException)(error)) {
error.context = {
ruleStack: this.getHumanReadableRuleStack(),
ruleOccurrenceStack: (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(this.RULE_OCCURRENCE_STACK)
};
this._errors.push(error);
return error;
}
else {
throw Error("Trying to save an Error which is not a RecognitionException");
}
};
Object.defineProperty(ErrorHandler.prototype, "errors", {
// TODO: extract these methods to ErrorHandler Trait?
get: function () {
return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.cloneArr)(this._errors);
},
set: function (newErrors) {
this._errors = newErrors;
},
enumerable: true,
configurable: true
});
// TODO: consider caching the error message computed information
ErrorHandler.prototype.raiseEarlyExitException = function (occurrence, prodType, userDefinedErrMsg) {
var ruleName = this.getCurrRuleFullName();
var ruleGrammar = this.getGAstProductions()[ruleName];
var lookAheadPathsPerAlternative = (0,_grammar_lookahead__WEBPACK_IMPORTED_MODULE_2__.getLookaheadPathsForOptionalProd)(occurrence, ruleGrammar, prodType, this.maxLookahead);
var insideProdPaths = lookAheadPathsPerAlternative[0];
var actualTokens = [];
for (var i = 1; i <= this.maxLookahead; i++) {
actualTokens.push(this.LA(i));
}
var msg = this.errorMessageProvider.buildEarlyExitMessage({
expectedIterationPaths: insideProdPaths,
actual: actualTokens,
previous: this.LA(0),
customUserDescription: userDefinedErrMsg,
ruleName: ruleName
});
throw this.SAVE_ERROR(new _exceptions_public__WEBPACK_IMPORTED_MODULE_0__.EarlyExitException(msg, this.LA(1), this.LA(0)));
};
// TODO: consider caching the error message computed information
ErrorHandler.prototype.raiseNoAltException = function (occurrence, errMsgTypes) {
var ruleName = this.getCurrRuleFullName();
var ruleGrammar = this.getGAstProductions()[ruleName];
// TODO: getLookaheadPathsForOr can be slow for large enough maxLookahead and certain grammars, consider caching ?
var lookAheadPathsPerAlternative = (0,_grammar_lookahead__WEBPACK_IMPORTED_MODULE_2__.getLookaheadPathsForOr)(occurrence, ruleGrammar, this.maxLookahead);
var actualTokens = [];
for (var i = 1; i <= this.maxLookahead; i++) {
actualTokens.push(this.LA(i));
}
var previousToken = this.LA(0);
var errMsg = this.errorMessageProvider.buildNoViableAltMessage({
expectedPathsPerAlt: lookAheadPathsPerAlternative,
actual: actualTokens,
previous: previousToken,
customUserDescription: errMsgTypes,
ruleName: this.getCurrRuleFullName()
});
throw this.SAVE_ERROR(new _exceptions_public__WEBPACK_IMPORTED_MODULE_0__.NoViableAltException(errMsg, this.LA(1), previousToken));
};
return ErrorHandler;
}());
//# sourceMappingURL=error_handler.js.map
/***/ }),
/* 51 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ContentAssist: () => (/* binding */ ContentAssist)
/* harmony export */ });
/* harmony import */ var _grammar_interpreter__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(38);
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(17);
var ContentAssist = /** @class */ (function () {
function ContentAssist() {
}
ContentAssist.prototype.initContentAssist = function () { };
ContentAssist.prototype.computeContentAssist = function (startRuleName, precedingInput) {
var startRuleGast = this.gastProductionsCache[startRuleName];
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.isUndefined)(startRuleGast)) {
throw Error("Rule ->" + startRuleName + "<- does not exist in this grammar.");
}
return (0,_grammar_interpreter__WEBPACK_IMPORTED_MODULE_0__.nextPossibleTokensAfter)([startRuleGast], precedingInput, this.tokenMatcher, this.maxLookahead);
};
// TODO: should this be a member method or a utility? it does not have any state or usage of 'this'...
// TODO: should this be more explicitly part of the public API?
ContentAssist.prototype.getNextPossibleTokenTypes = function (grammarPath) {
var topRuleName = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_1__.first)(grammarPath.ruleStack);
var gastProductions = this.getGAstProductions();
var topProduction = gastProductions[topRuleName];
var nextPossibleTokenTypes = new _grammar_interpreter__WEBPACK_IMPORTED_MODULE_0__.NextAfterTokenWalker(topProduction, grammarPath).startWalking();
return nextPossibleTokenTypes;
};
return ContentAssist;
}());
//# sourceMappingURL=context_assist.js.map
/***/ }),
/* 52 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ GastRecorder: () => (/* binding */ GastRecorder)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20);
/* harmony import */ var _scan_lexer_public__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(22);
/* harmony import */ var _scan_tokens__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(27);
/* harmony import */ var _scan_tokens_public__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(21);
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(16);
/* harmony import */ var _grammar_keys__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(34);
var RECORDING_NULL_OBJECT = {
description: "This Object indicates the Parser is during Recording Phase"
};
Object.freeze(RECORDING_NULL_OBJECT);
var HANDLE_SEPARATOR = true;
var MAX_METHOD_IDX = Math.pow(2, _grammar_keys__WEBPACK_IMPORTED_MODULE_6__.BITS_FOR_OCCURRENCE_IDX) - 1;
var RFT = (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_4__.createToken)({ name: "RECORDING_PHASE_TOKEN", pattern: _scan_lexer_public__WEBPACK_IMPORTED_MODULE_2__.Lexer.NA });
(0,_scan_tokens__WEBPACK_IMPORTED_MODULE_3__.augmentTokenTypes)([RFT]);
var RECORDING_PHASE_TOKEN = (0,_scan_tokens_public__WEBPACK_IMPORTED_MODULE_4__.createTokenInstance)(RFT, "This IToken indicates the Parser is in Recording Phase\n\t" +
"" +
"See: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details",
// Using "-1" instead of NaN (as in EOF) because an actual number is less likely to
// cause errors if the output of LA or CONSUME would be (incorrectly) used during the recording phase.
-1, -1, -1, -1, -1, -1);
Object.freeze(RECORDING_PHASE_TOKEN);
var RECORDING_PHASE_CSTNODE = {
name: "This CSTNode indicates the Parser is in Recording Phase\n\t" +
"See: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details",
children: {}
};
/**
* This trait handles the creation of the GAST structure for Chevrotain Grammars
*/
var GastRecorder = /** @class */ (function () {
function GastRecorder() {
}
GastRecorder.prototype.initGastRecorder = function (config) {
this.recordingProdStack = [];
this.RECORDING_PHASE = false;
};
GastRecorder.prototype.enableRecording = function () {
var _this = this;
this.RECORDING_PHASE = true;
this.TRACE_INIT("Enable Recording", function () {
var _loop_1 = function (i) {
var idx = i > 0 ? i : "";
_this["CONSUME" + idx] = function (arg1, arg2) {
return this.consumeInternalRecord(arg1, i, arg2);
};
_this["SUBRULE" + idx] = function (arg1, arg2) {
return this.subruleInternalRecord(arg1, i, arg2);
};
_this["OPTION" + idx] = function (arg1) {
return this.optionInternalRecord(arg1, i);
};
_this["OR" + idx] = function (arg1) {
return this.orInternalRecord(arg1, i);
};
_this["MANY" + idx] = function (arg1) {
this.manyInternalRecord(i, arg1);
};
_this["MANY_SEP" + idx] = function (arg1) {
this.manySepFirstInternalRecord(i, arg1);
};
_this["AT_LEAST_ONE" + idx] = function (arg1) {
this.atLeastOneInternalRecord(i, arg1);
};
_this["AT_LEAST_ONE_SEP" + idx] = function (arg1) {
this.atLeastOneSepFirstInternalRecord(i, arg1);
};
};
/**
* Warning Dark Voodoo Magic upcoming!
* We are "replacing" the public parsing DSL methods API
* With **new** alternative implementations on the Parser **instance**
*
* So far this is the only way I've found to avoid performance regressions during parsing time.
* - Approx 30% performance regression was measured on Chrome 75 Canary when attempting to replace the "internal"
* implementations directly instead.
*/
for (var i = 0; i < 10; i++) {
_loop_1(i);
}
// DSL methods with the idx(suffix) as an argument
_this["consume"] = function (idx, arg1, arg2) {
return this.consumeInternalRecord(arg1, idx, arg2);
};
_this["subrule"] = function (idx, arg1, arg2) {
return this.subruleInternalRecord(arg1, idx, arg2);
};
_this["option"] = function (idx, arg1) {
return this.optionInternalRecord(arg1, idx);
};
_this["or"] = function (idx, arg1) {
return this.orInternalRecord(arg1, idx);
};
_this["many"] = function (idx, arg1) {
this.manyInternalRecord(idx, arg1);
};
_this["atLeastOne"] = function (idx, arg1) {
this.atLeastOneInternalRecord(idx, arg1);
};
_this.ACTION = _this.ACTION_RECORD;
_this.BACKTRACK = _this.BACKTRACK_RECORD;
_this.LA = _this.LA_RECORD;
});
};
GastRecorder.prototype.disableRecording = function () {
var _this = this;
this.RECORDING_PHASE = false;
// By deleting these **instance** properties, any future invocation
// will be deferred to the original methods on the **prototype** object
// This seems to get rid of any incorrect optimizations that V8 may
// do during the recording phase.
this.TRACE_INIT("Deleting Recording methods", function () {
for (var i = 0; i < 10; i++) {
var idx = i > 0 ? i : "";
delete _this["CONSUME" + idx];
delete _this["SUBRULE" + idx];
delete _this["OPTION" + idx];
delete _this["OR" + idx];
delete _this["MANY" + idx];
delete _this["MANY_SEP" + idx];
delete _this["AT_LEAST_ONE" + idx];
delete _this["AT_LEAST_ONE_SEP" + idx];
}
delete _this["consume"];
delete _this["subrule"];
delete _this["option"];
delete _this["or"];
delete _this["many"];
delete _this["atLeastOne"];
delete _this.ACTION;
delete _this.BACKTRACK;
delete _this.LA;
});
};
// TODO: is there any way to use this method to check no
// Parser methods are called inside an ACTION?
// Maybe try/catch/finally on ACTIONS while disabling the recorders state changes?
GastRecorder.prototype.ACTION_RECORD = function (impl) {
// NO-OP during recording
return;
};
// Executing backtracking logic will break our recording logic assumptions
GastRecorder.prototype.BACKTRACK_RECORD = function (grammarRule, args) {
return function () { return true; };
};
// LA is part of the official API and may be used for custom lookahead logic
// by end users who may forget to wrap it in ACTION or inside a GATE
GastRecorder.prototype.LA_RECORD = function (howMuch) {
// We cannot use the RECORD_PHASE_TOKEN here because someone may depend
// On LA return EOF at the end of the input so an infinite loop may occur.
return _parser__WEBPACK_IMPORTED_MODULE_5__.END_OF_FILE;
};
GastRecorder.prototype.topLevelRuleRecord = function (name, def) {
try {
var newTopLevelRule = new _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Rule({ definition: [], name: name });
newTopLevelRule.name = name;
this.recordingProdStack.push(newTopLevelRule);
def.call(this);
this.recordingProdStack.pop();
return newTopLevelRule;
}
catch (originalError) {
if (originalError.KNOWN_RECORDER_ERROR !== true) {
try {
originalError.message =
originalError.message +
'\n\t This error was thrown during the "grammar recording phase" For more info see:\n\t' +
"https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording";
}
catch (mutabilityError) {
// We may not be able to modify the original error object
throw originalError;
}
}
throw originalError;
}
};
// Implementation of parsing DSL
GastRecorder.prototype.optionInternalRecord = function (actionORMethodDef, occurrence) {
return recordProd.call(this, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Option, actionORMethodDef, occurrence);
};
GastRecorder.prototype.atLeastOneInternalRecord = function (occurrence, actionORMethodDef) {
recordProd.call(this, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatory, actionORMethodDef, occurrence);
};
GastRecorder.prototype.atLeastOneSepFirstInternalRecord = function (occurrence, options) {
recordProd.call(this, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatoryWithSeparator, options, occurrence, HANDLE_SEPARATOR);
};
GastRecorder.prototype.manyInternalRecord = function (occurrence, actionORMethodDef) {
recordProd.call(this, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Repetition, actionORMethodDef, occurrence);
};
GastRecorder.prototype.manySepFirstInternalRecord = function (occurrence, options) {
recordProd.call(this, _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionWithSeparator, options, occurrence, HANDLE_SEPARATOR);
};
GastRecorder.prototype.orInternalRecord = function (altsOrOpts, occurrence) {
return recordOrProd.call(this, altsOrOpts, occurrence);
};
GastRecorder.prototype.subruleInternalRecord = function (ruleToCall, occurrence, options) {
assertMethodIdxIsValid(occurrence);
if (!ruleToCall || (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(ruleToCall, "ruleName") === false) {
var error = new Error("<SUBRULE" + getIdxSuffix(occurrence) + "> argument is invalid" +
(" expecting a Parser method reference but got: <" + JSON.stringify(ruleToCall) + ">") +
("\n inside top level rule: <" + this.recordingProdStack[0].name + ">"));
error.KNOWN_RECORDER_ERROR = true;
throw error;
}
var prevProd = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.peek)(this.recordingProdStack);
var ruleName = ruleToCall["ruleName"];
var newNoneTerminal = new _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.NonTerminal({
idx: occurrence,
nonTerminalName: ruleName,
// The resolving of the `referencedRule` property will be done once all the Rule's GASTs have been created
referencedRule: undefined
});
prevProd.definition.push(newNoneTerminal);
return this.outputCst
? RECORDING_PHASE_CSTNODE
: RECORDING_NULL_OBJECT;
};
GastRecorder.prototype.consumeInternalRecord = function (tokType, occurrence, options) {
assertMethodIdxIsValid(occurrence);
if (!(0,_scan_tokens__WEBPACK_IMPORTED_MODULE_3__.hasShortKeyProperty)(tokType)) {
var error = new Error("<CONSUME" + getIdxSuffix(occurrence) + "> argument is invalid" +
(" expecting a TokenType reference but got: <" + JSON.stringify(tokType) + ">") +
("\n inside top level rule: <" + this.recordingProdStack[0].name + ">"));
error.KNOWN_RECORDER_ERROR = true;
throw error;
}
var prevProd = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.peek)(this.recordingProdStack);
var newNoneTerminal = new _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Terminal({
idx: occurrence,
terminalType: tokType
});
prevProd.definition.push(newNoneTerminal);
return RECORDING_PHASE_TOKEN;
};
return GastRecorder;
}());
function recordProd(prodConstructor, mainProdArg, occurrence, handleSep) {
if (handleSep === void 0) { handleSep = false; }
assertMethodIdxIsValid(occurrence);
var prevProd = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.peek)(this.recordingProdStack);
var grammarAction = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isFunction)(mainProdArg)
? mainProdArg
: mainProdArg.DEF;
var newProd = new prodConstructor({ definition: [], idx: occurrence });
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(mainProdArg, "NAME")) {
newProd.name = mainProdArg.NAME;
}
if (handleSep) {
newProd.separator = mainProdArg.SEP;
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(mainProdArg, "MAX_LOOKAHEAD")) {
newProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;
}
this.recordingProdStack.push(newProd);
grammarAction.call(this);
prevProd.definition.push(newProd);
this.recordingProdStack.pop();
return RECORDING_NULL_OBJECT;
}
function recordOrProd(mainProdArg, occurrence) {
var _this = this;
assertMethodIdxIsValid(occurrence);
var prevProd = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.peek)(this.recordingProdStack);
// Only an array of alternatives
var hasOptions = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isArray)(mainProdArg) === false;
var alts = hasOptions === false ? mainProdArg : mainProdArg.DEF;
var newOrProd = new _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Alternation({
definition: [],
idx: occurrence,
ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true
});
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(mainProdArg, "NAME")) {
newOrProd.name = mainProdArg.NAME;
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(mainProdArg, "MAX_LOOKAHEAD")) {
newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;
}
var hasPredicates = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.some)(alts, function (currAlt) { return (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.isFunction)(currAlt.GATE); });
newOrProd.hasPredicates = hasPredicates;
prevProd.definition.push(newOrProd);
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(alts, function (currAlt) {
var currAltFlat = new _grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Flat({ definition: [] });
newOrProd.definition.push(currAltFlat);
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(currAlt, "NAME")) {
currAltFlat.name = currAlt.NAME;
}
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(currAlt, "IGNORE_AMBIGUITIES")) {
currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES;
}
// **implicit** ignoreAmbiguities due to usage of gate
else if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(currAlt, "GATE")) {
currAltFlat.ignoreAmbiguities = true;
}
_this.recordingProdStack.push(currAltFlat);
currAlt.ALT.call(_this);
_this.recordingProdStack.pop();
});
return RECORDING_NULL_OBJECT;
}
function getIdxSuffix(idx) {
return idx === 0 ? "" : "" + idx;
}
function assertMethodIdxIsValid(idx) {
if (idx < 0 || idx > MAX_METHOD_IDX) {
var error = new Error(
// The stack trace will contain all the needed details
"Invalid DSL Method idx value: <" + idx + ">\n\t" +
("Idx value must be a none negative value smaller than " + (MAX_METHOD_IDX +
1)));
error.KNOWN_RECORDER_ERROR = true;
throw error;
}
}
//# sourceMappingURL=gast_recorder.js.map
/***/ }),
/* 53 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ PerformanceTracer: () => (/* binding */ PerformanceTracer)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16);
/**
* Trait responsible for runtime parsing errors.
*/
var PerformanceTracer = /** @class */ (function () {
function PerformanceTracer() {
}
PerformanceTracer.prototype.initPerformanceTracer = function (config) {
if ((0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.has)(config, "traceInitPerf")) {
var userTraceInitPerf = config.traceInitPerf;
var traceIsNumber = typeof userTraceInitPerf === "number";
this.traceInitMaxIdent = traceIsNumber
? userTraceInitPerf
: Infinity;
this.traceInitPerf = traceIsNumber
? userTraceInitPerf > 0
: userTraceInitPerf;
}
else {
this.traceInitMaxIdent = 0;
this.traceInitPerf = _parser__WEBPACK_IMPORTED_MODULE_1__.DEFAULT_PARSER_CONFIG.traceInitPerf;
}
this.traceInitIndent = -1;
};
PerformanceTracer.prototype.TRACE_INIT = function (phaseDesc, phaseImpl) {
// No need to optimize this using NOOP pattern because
// It is not called in a hot spot...
if (this.traceInitPerf === true) {
this.traceInitIndent++;
var indent = new Array(this.traceInitIndent + 1).join("\t");
if (this.traceInitIndent < this.traceInitMaxIdent) {
console.log(indent + "--> <" + phaseDesc + ">");
}
var _a = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.timer)(phaseImpl), time = _a.time, value = _a.value;
/* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */
var traceMethod = time > 10 ? console.warn : console.log;
if (this.traceInitIndent < this.traceInitMaxIdent) {
traceMethod(indent + "<-- <" + phaseDesc + "> time: " + time + "ms");
}
this.traceInitIndent--;
return value;
}
else {
return phaseImpl();
}
};
return PerformanceTracer;
}());
//# sourceMappingURL=perf_tracer.js.map
/***/ }),
/* 54 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ createSyntaxDiagramsCode: () => (/* binding */ createSyntaxDiagramsCode)
/* harmony export */ });
/* harmony import */ var _version__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15);
function createSyntaxDiagramsCode(grammar, _a) {
var _b = _a === void 0 ? {} : _a, _c = _b.resourceBase, resourceBase = _c === void 0 ? "https://unpkg.com/chevrotain@" + _version__WEBPACK_IMPORTED_MODULE_0__.VERSION + "/diagrams/" : _c, _d = _b.css, css = _d === void 0 ? "https://unpkg.com/chevrotain@" + _version__WEBPACK_IMPORTED_MODULE_0__.VERSION + "/diagrams/diagrams.css" : _d;
var header = "\n<!-- This is a generated file -->\n<!DOCTYPE html>\n<meta charset=\"utf-8\">\n<style>\n body {\n background-color: hsl(30, 20%, 95%)\n }\n</style>\n\n";
var cssHtml = "\n<link rel='stylesheet' href='" + css + "'>\n";
var scripts = "\n<script src='" + resourceBase + "vendor/railroad-diagrams.js'></script>\n<script src='" + resourceBase + "src/diagrams_builder.js'></script>\n<script src='" + resourceBase + "src/diagrams_behavior.js'></script>\n<script src='" + resourceBase + "src/main.js'></script>\n";
var diagramsDiv = "\n<div id=\"diagrams\" align=\"center\"></div> \n";
var serializedGrammar = "\n<script>\n window.serializedGrammar = " + JSON.stringify(grammar, null, " ") + ";\n</script>\n";
var initLogic = "\n<script>\n var diagramsDiv = document.getElementById(\"diagrams\");\n main.drawDiagramsFromSerializedGrammar(serializedGrammar, diagramsDiv);\n</script>\n";
return (header + cssHtml + scripts + diagramsDiv + serializedGrammar + initLogic);
}
//# sourceMappingURL=render_public.js.map
/***/ }),
/* 55 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ generateParserFactory: () => (/* binding */ generateParserFactory),
/* harmony export */ generateParserModule: () => (/* binding */ generateParserModule)
/* harmony export */ });
/* harmony import */ var _generate__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(56);
function generateParserFactory(options) {
var wrapperText = (0,_generate__WEBPACK_IMPORTED_MODULE_0__.genWrapperFunction)({
name: options.name,
rules: options.rules
});
var constructorWrapper = new Function("tokenVocabulary", "config", "chevrotain", wrapperText);
return function (config) {
return constructorWrapper(options.tokenVocabulary, config,
// TODO: check how the require is transpiled/webpacked
__webpack_require__(14));
};
}
function generateParserModule(options) {
return (0,_generate__WEBPACK_IMPORTED_MODULE_0__.genUmdModule)({ name: options.name, rules: options.rules });
}
//# sourceMappingURL=generate_public.js.map
/***/ }),
/* 56 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ genAllRules: () => (/* binding */ genAllRules),
/* harmony export */ genAlternation: () => (/* binding */ genAlternation),
/* harmony export */ genClass: () => (/* binding */ genClass),
/* harmony export */ genNonTerminal: () => (/* binding */ genNonTerminal),
/* harmony export */ genRule: () => (/* binding */ genRule),
/* harmony export */ genSingleAlt: () => (/* binding */ genSingleAlt),
/* harmony export */ genTerminal: () => (/* binding */ genTerminal),
/* harmony export */ genUmdModule: () => (/* binding */ genUmdModule),
/* harmony export */ genWrapperFunction: () => (/* binding */ genWrapperFunction)
/* harmony export */ });
/* harmony import */ var _utils_utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(17);
/* harmony import */ var _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(20);
/**
* Missing features
* 1. Rule arguments
* 2. Gates
* 3. embedded actions
*/
var NL = "\n";
function genUmdModule(options) {
return "\n(function (root, factory) {\n if (typeof define === 'function' && define.amd) {\n // AMD. Register as an anonymous module.\n define(['chevrotain'], factory);\n } else if (typeof module === 'object' && module.exports) {\n // Node. Does not work with strict CommonJS, but\n // only CommonJS-like environments that support module.exports,\n // like Node.\n module.exports = factory(require('chevrotain'));\n } else {\n // Browser globals (root is window)\n root.returnExports = factory(root.b);\n }\n}(typeof self !== 'undefined' ? self : this, function (chevrotain) {\n\n" + genClass(options) + "\n \nreturn {\n " + options.name + ": " + options.name + " \n}\n}));\n";
}
function genWrapperFunction(options) {
return " \n" + genClass(options) + "\nreturn new " + options.name + "(tokenVocabulary, config) \n";
}
function genClass(options) {
// TODO: how to pass the token vocabulary? Constructor? other?
var result = "\nfunction " + options.name + "(tokenVocabulary, config) {\n // invoke super constructor\n // No support for embedded actions currently, so we can 'hardcode'\n // The use of CstParser.\n chevrotain.CstParser.call(this, tokenVocabulary, config)\n\n const $ = this\n\n " + genAllRules(options.rules) + "\n\n // very important to call this after all the rules have been defined.\n // otherwise the parser may not work correctly as it will lack information\n // derived during the self analysis phase.\n this.performSelfAnalysis(this)\n}\n\n// inheritance as implemented in javascript in the previous decade... :(\n" + options.name + ".prototype = Object.create(chevrotain.CstParser.prototype)\n" + options.name + ".prototype.constructor = " + options.name + " \n ";
return result;
}
function genAllRules(rules) {
var rulesText = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(rules, function (currRule) {
return genRule(currRule, 1);
});
return rulesText.join("\n");
}
function genRule(prod, n) {
var result = indent(n, "$.RULE(\"" + prod.name + "\", function() {") + NL;
result += genDefinition(prod.definition, n + 1);
result += indent(n + 1, "})") + NL;
return result;
}
function genTerminal(prod, n) {
var name = prod.terminalType.name;
// TODO: potential performance optimization, avoid tokenMap Dictionary access
return indent(n, "$.CONSUME" + prod.idx + "(this.tokensMap." + name + ")" + NL);
}
function genNonTerminal(prod, n) {
return indent(n, "$.SUBRULE" + prod.idx + "($." + prod.nonTerminalName + ")" + NL);
}
function genAlternation(prod, n) {
var result = indent(n, "$.OR" + prod.idx + "([") + NL;
var alts = (0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.map)(prod.definition, function (altDef) { return genSingleAlt(altDef, n + 1); });
result += alts.join("," + NL);
result += NL + indent(n, "])" + NL);
return result;
}
function genSingleAlt(prod, n) {
var result = indent(n, "{") + NL;
if (prod.name) {
result += indent(n + 1, "NAME: \"" + prod.name + "\",") + NL;
}
result += indent(n + 1, "ALT: function() {") + NL;
result += genDefinition(prod.definition, n + 1);
result += indent(n + 1, "}") + NL;
result += indent(n, "}");
return result;
}
function genProd(prod, n) {
/* istanbul ignore else */
if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.NonTerminal) {
return genNonTerminal(prod, n);
}
else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Option) {
return genDSLRule("OPTION", prod, n);
}
else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatory) {
return genDSLRule("AT_LEAST_ONE", prod, n);
}
else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionMandatoryWithSeparator) {
return genDSLRule("AT_LEAST_ONE_SEP", prod, n);
}
else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.RepetitionWithSeparator) {
return genDSLRule("MANY_SEP", prod, n);
}
else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Repetition) {
return genDSLRule("MANY", prod, n);
}
else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Alternation) {
return genAlternation(prod, n);
}
else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Terminal) {
return genTerminal(prod, n);
}
else if (prod instanceof _parse_grammar_gast_gast_public__WEBPACK_IMPORTED_MODULE_1__.Flat) {
return genDefinition(prod.definition, n);
}
else {
throw Error("non exhaustive match");
}
}
function genDSLRule(dslName, prod, n) {
var result = indent(n, "$." + (dslName + prod.idx) + "(");
if (prod.name || prod.separator) {
result += "{" + NL;
if (prod.name) {
result += indent(n + 1, "NAME: \"" + prod.name + "\"") + "," + NL;
}
if (prod.separator) {
result +=
indent(n + 1, "SEP: this.tokensMap." + prod.separator.name) +
"," +
NL;
}
result += "DEF: " + genDefFunction(prod.definition, n + 2) + NL;
result += indent(n, "}") + NL;
}
else {
result += genDefFunction(prod.definition, n + 1);
}
result += indent(n, ")") + NL;
return result;
}
function genDefFunction(definition, n) {
var def = "function() {" + NL;
def += genDefinition(definition, n);
def += indent(n, "}") + NL;
return def;
}
function genDefinition(def, n) {
var result = "";
(0,_utils_utils__WEBPACK_IMPORTED_MODULE_0__.forEach)(def, function (prod) {
result += genProd(prod, n + 1);
});
return result;
}
function indent(howMuch, text) {
var spaces = Array(howMuch * 4 + 1).join(" ");
return spaces + text;
}
//# sourceMappingURL=generate.js.map
/***/ }),
/* 57 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AstNodeType: () => (/* binding */ AstNodeType),
/* harmony export */ ParsingErrorType: () => (/* binding */ ParsingErrorType),
/* harmony export */ RangeSheetReferenceType: () => (/* binding */ RangeSheetReferenceType),
/* harmony export */ buildArrayAst: () => (/* binding */ buildArrayAst),
/* harmony export */ buildCellErrorAst: () => (/* binding */ buildCellErrorAst),
/* harmony export */ buildCellRangeAst: () => (/* binding */ buildCellRangeAst),
/* harmony export */ buildCellReferenceAst: () => (/* binding */ buildCellReferenceAst),
/* harmony export */ buildColumnRangeAst: () => (/* binding */ buildColumnRangeAst),
/* harmony export */ buildConcatenateOpAst: () => (/* binding */ buildConcatenateOpAst),
/* harmony export */ buildDivOpAst: () => (/* binding */ buildDivOpAst),
/* harmony export */ buildEmptyArgAst: () => (/* binding */ buildEmptyArgAst),
/* harmony export */ buildEqualsOpAst: () => (/* binding */ buildEqualsOpAst),
/* harmony export */ buildErrorWithRawInputAst: () => (/* binding */ buildErrorWithRawInputAst),
/* harmony export */ buildGreaterThanOpAst: () => (/* binding */ buildGreaterThanOpAst),
/* harmony export */ buildGreaterThanOrEqualOpAst: () => (/* binding */ buildGreaterThanOrEqualOpAst),
/* harmony export */ buildLessThanOpAst: () => (/* binding */ buildLessThanOpAst),
/* harmony export */ buildLessThanOrEqualOpAst: () => (/* binding */ buildLessThanOrEqualOpAst),
/* harmony export */ buildMinusOpAst: () => (/* binding */ buildMinusOpAst),
/* harmony export */ buildMinusUnaryOpAst: () => (/* binding */ buildMinusUnaryOpAst),
/* harmony export */ buildNamedExpressionAst: () => (/* binding */ buildNamedExpressionAst),
/* harmony export */ buildNotEqualOpAst: () => (/* binding */ buildNotEqualOpAst),
/* harmony export */ buildNumberAst: () => (/* binding */ buildNumberAst),
/* harmony export */ buildParenthesisAst: () => (/* binding */ buildParenthesisAst),
/* harmony export */ buildParsingErrorAst: () => (/* binding */ buildParsingErrorAst),
/* harmony export */ buildPercentOpAst: () => (/* binding */ buildPercentOpAst),
/* harmony export */ buildPlusOpAst: () => (/* binding */ buildPlusOpAst),
/* harmony export */ buildPlusUnaryOpAst: () => (/* binding */ buildPlusUnaryOpAst),
/* harmony export */ buildPowerOpAst: () => (/* binding */ buildPowerOpAst),
/* harmony export */ buildProcedureAst: () => (/* binding */ buildProcedureAst),
/* harmony export */ buildRowRangeAst: () => (/* binding */ buildRowRangeAst),
/* harmony export */ buildStringAst: () => (/* binding */ buildStringAst),
/* harmony export */ buildTimesOpAst: () => (/* binding */ buildTimesOpAst),
/* harmony export */ imageWithWhitespace: () => (/* binding */ imageWithWhitespace),
/* harmony export */ parsingError: () => (/* binding */ parsingError)
/* harmony export */ });
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
const parsingError = (type, message) => ({
type,
message
});
var ParsingErrorType;
(function (ParsingErrorType) {
ParsingErrorType["LexingError"] = "LexingError";
ParsingErrorType["ParserError"] = "ParsingError";
ParsingErrorType["StaticOffsetError"] = "StaticOffsetError";
ParsingErrorType["StaticOffsetOutOfRangeError"] = "StaticOffsetOutOfRangeError";
ParsingErrorType["RangeOffsetNotAllowed"] = "RangeOffsetNotAllowed";
})(ParsingErrorType || (ParsingErrorType = {}));
var AstNodeType;
(function (AstNodeType) {
AstNodeType["EMPTY"] = "EMPTY";
AstNodeType["NUMBER"] = "NUMBER";
AstNodeType["STRING"] = "STRING";
AstNodeType["MINUS_UNARY_OP"] = "MINUS_UNARY_OP";
AstNodeType["PLUS_UNARY_OP"] = "PLUS_UNARY_OP";
AstNodeType["PERCENT_OP"] = "PERCENT_OP";
AstNodeType["CONCATENATE_OP"] = "CONCATENATE_OP";
AstNodeType["EQUALS_OP"] = "EQUALS_OP";
AstNodeType["NOT_EQUAL_OP"] = "NOT_EQUAL_OP";
AstNodeType["GREATER_THAN_OP"] = "GREATER_THAN_OP";
AstNodeType["LESS_THAN_OP"] = "LESS_THAN_OP";
AstNodeType["GREATER_THAN_OR_EQUAL_OP"] = "GREATER_THAN_OR_EQUAL_OP";
AstNodeType["LESS_THAN_OR_EQUAL_OP"] = "LESS_THAN_OR_EQUAL_OP";
AstNodeType["PLUS_OP"] = "PLUS_OP";
AstNodeType["MINUS_OP"] = "MINUS_OP";
AstNodeType["TIMES_OP"] = "TIMES_OP";
AstNodeType["DIV_OP"] = "DIV_OP";
AstNodeType["POWER_OP"] = "POWER_OP";
AstNodeType["FUNCTION_CALL"] = "FUNCTION_CALL";
AstNodeType["NAMED_EXPRESSION"] = "NAMED_EXPRESSION";
AstNodeType["PARENTHESIS"] = "PARENTHESES";
AstNodeType["CELL_REFERENCE"] = "CELL_REFERENCE";
AstNodeType["CELL_RANGE"] = "CELL_RANGE";
AstNodeType["COLUMN_RANGE"] = "COLUMN_RANGE";
AstNodeType["ROW_RANGE"] = "ROW_RANGE";
AstNodeType["ERROR"] = "ERROR";
AstNodeType["ERROR_WITH_RAW_INPUT"] = "ERROR_WITH_RAW_INPUT";
AstNodeType["ARRAY"] = "ARRAY";
})(AstNodeType || (AstNodeType = {}));
var RangeSheetReferenceType;
(function (RangeSheetReferenceType) {
RangeSheetReferenceType[RangeSheetReferenceType["RELATIVE"] = 0] = "RELATIVE";
RangeSheetReferenceType[RangeSheetReferenceType["START_ABSOLUTE"] = 1] = "START_ABSOLUTE";
RangeSheetReferenceType[RangeSheetReferenceType["BOTH_ABSOLUTE"] = 2] = "BOTH_ABSOLUTE";
})(RangeSheetReferenceType || (RangeSheetReferenceType = {}));
const buildEmptyArgAst = leadingWhitespace => ({
type: AstNodeType.EMPTY,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildNumberAst = (value, leadingWhitespace) => ({
type: AstNodeType.NUMBER,
value: value,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildStringAst = token => {
var _a;
return {
type: AstNodeType.STRING,
value: token.image.slice(1, -1),
leadingWhitespace: (_a = token.leadingWhitespace) === null || _a === void 0 ? void 0 : _a.image
};
};
const buildCellReferenceAst = (reference, leadingWhitespace) => ({
type: AstNodeType.CELL_REFERENCE,
reference,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildCellRangeAst = (start, end, sheetReferenceType, leadingWhitespace) => {
assertRangeConsistency(start, end, sheetReferenceType);
return {
type: AstNodeType.CELL_RANGE,
start,
end,
sheetReferenceType,
leadingWhitespace
};
};
const buildColumnRangeAst = (start, end, sheetReferenceType, leadingWhitespace) => {
assertRangeConsistency(start, end, sheetReferenceType);
return {
type: AstNodeType.COLUMN_RANGE,
start,
end,
sheetReferenceType,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
};
};
const buildRowRangeAst = (start, end, sheetReferenceType, leadingWhitespace) => {
assertRangeConsistency(start, end, sheetReferenceType);
return {
type: AstNodeType.ROW_RANGE,
start,
end,
sheetReferenceType,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
};
};
const buildConcatenateOpAst = (left, right, leadingWhitespace) => ({
type: AstNodeType.CONCATENATE_OP,
left,
right,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildEqualsOpAst = (left, right, leadingWhitespace) => ({
type: AstNodeType.EQUALS_OP,
left,
right,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildNotEqualOpAst = (left, right, leadingWhitespace) => ({
type: AstNodeType.NOT_EQUAL_OP,
left,
right,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildGreaterThanOpAst = (left, right, leadingWhitespace) => ({
type: AstNodeType.GREATER_THAN_OP,
left,
right,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildLessThanOpAst = (left, right, leadingWhitespace) => ({
type: AstNodeType.LESS_THAN_OP,
left,
right,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildGreaterThanOrEqualOpAst = (left, right, leadingWhitespace) => ({
type: AstNodeType.GREATER_THAN_OR_EQUAL_OP,
left,
right,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildLessThanOrEqualOpAst = (left, right, leadingWhitespace) => ({
type: AstNodeType.LESS_THAN_OR_EQUAL_OP,
left,
right,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildPlusOpAst = (left, right, leadingWhitespace) => ({
type: AstNodeType.PLUS_OP,
left,
right,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildMinusOpAst = (left, right, leadingWhitespace) => ({
type: AstNodeType.MINUS_OP,
left,
right,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildTimesOpAst = (left, right, leadingWhitespace) => ({
type: AstNodeType.TIMES_OP,
left,
right,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildDivOpAst = (left, right, leadingWhitespace) => ({
type: AstNodeType.DIV_OP,
left,
right,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildPowerOpAst = (left, right, leadingWhitespace) => ({
type: AstNodeType.POWER_OP,
left,
right,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildMinusUnaryOpAst = (value, leadingWhitespace) => ({
type: AstNodeType.MINUS_UNARY_OP,
value,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildPlusUnaryOpAst = (value, leadingWhitespace) => ({
type: AstNodeType.PLUS_UNARY_OP,
value,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildPercentOpAst = (value, leadingWhitespace) => ({
type: AstNodeType.PERCENT_OP,
value,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildProcedureAst = (procedureName, args, leadingWhitespace, internalWhitespace, hyperlink) => ({
type: AstNodeType.FUNCTION_CALL,
procedureName,
args,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image,
internalWhitespace: internalWhitespace === null || internalWhitespace === void 0 ? void 0 : internalWhitespace.image,
hyperlink
});
const buildArrayAst = (args, leadingWhitespace, internalWhitespace) => ({
type: AstNodeType.ARRAY,
args,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image,
internalWhitespace: internalWhitespace === null || internalWhitespace === void 0 ? void 0 : internalWhitespace.image
});
const buildNamedExpressionAst = (expressionName, leadingWhitespace) => ({
type: AstNodeType.NAMED_EXPRESSION,
expressionName,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildParenthesisAst = (expression, leadingWhitespace, internalWhitespace) => ({
type: AstNodeType.PARENTHESIS,
expression,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image,
internalWhitespace: internalWhitespace === null || internalWhitespace === void 0 ? void 0 : internalWhitespace.image
});
const buildCellErrorAst = (error, leadingWhitespace) => ({
type: AstNodeType.ERROR,
error,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildErrorWithRawInputAst = (rawInput, error, leadingWhitespace) => ({
type: AstNodeType.ERROR_WITH_RAW_INPUT,
error,
rawInput,
leadingWhitespace: leadingWhitespace === null || leadingWhitespace === void 0 ? void 0 : leadingWhitespace.image
});
const buildParsingErrorAst = () => ({
type: AstNodeType.ERROR,
error: _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError.parsingError()
});
function assertRangeConsistency(start, end, sheetReferenceType) {
if (start.sheet !== undefined && end.sheet === undefined || start.sheet === undefined && end.sheet !== undefined) {
throw new Error('Start address inconsistent with end address');
}
if (start.sheet === undefined && sheetReferenceType !== RangeSheetReferenceType.RELATIVE || start.sheet !== undefined && sheetReferenceType === RangeSheetReferenceType.RELATIVE) {
throw new Error('Sheet address inconsistent with sheet reference type');
}
}
function imageWithWhitespace(image, leadingWhitespace) {
return (leadingWhitespace !== null && leadingWhitespace !== void 0 ? leadingWhitespace : '') + image;
}
/***/ }),
/* 58 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ binaryOpTokenMap: () => (/* binding */ binaryOpTokenMap)
/* harmony export */ });
/* harmony import */ var _Ast__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(57);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
const binaryOpTokenMap = {
[_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PLUS_OP]: '+',
[_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.MINUS_OP]: '-',
[_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.TIMES_OP]: '*',
[_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.DIV_OP]: '/',
[_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.CONCATENATE_OP]: '&',
[_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.POWER_OP]: '^',
[_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.EQUALS_OP]: '=',
[_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.NOT_EQUAL_OP]: '<>',
[_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.GREATER_THAN_OP]: '>',
[_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.GREATER_THAN_OR_EQUAL_OP]: '>=',
[_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.LESS_THAN_OP]: '<',
[_Ast__WEBPACK_IMPORTED_MODULE_0__.AstNodeType.LESS_THAN_OR_EQUAL_OP]: '<='
};
/***/ }),
/* 59 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Cache: () => (/* binding */ Cache),
/* harmony export */ doesContainFunctions: () => (/* binding */ doesContainFunctions)
/* harmony export */ });
/* harmony import */ var ___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
const buildCacheEntry = (ast, relativeDependencies, hasVolatileFunction, hasStructuralChangeFunction) => ({
ast,
relativeDependencies,
hasVolatileFunction,
hasStructuralChangeFunction
});
class Cache {
constructor(functionRegistry) {
this.functionRegistry = functionRegistry;
this.cache = new Map();
}
set(hash, ast) {
const astRelativeDependencies = (0,___WEBPACK_IMPORTED_MODULE_0__.collectDependencies)(ast, this.functionRegistry);
const cacheEntry = buildCacheEntry(ast, astRelativeDependencies, doesContainFunctions(ast, this.functionRegistry.isFunctionVolatile), doesContainFunctions(ast, this.functionRegistry.isFunctionDependentOnSheetStructureChange));
this.cache.set(hash, cacheEntry);
return cacheEntry;
}
get(hash) {
return this.cache.get(hash);
}
maybeSetAndThenGet(hash, ast) {
const entryFromCache = this.cache.get(hash);
if (entryFromCache !== undefined) {
return entryFromCache.ast;
} else {
this.set(hash, ast);
return ast;
}
}
}
const doesContainFunctions = (ast, functionCriterion) => {
switch (ast.type) {
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.EMPTY:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.NUMBER:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.STRING:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.ERROR:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.ERROR_WITH_RAW_INPUT:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.CELL_REFERENCE:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.CELL_RANGE:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.COLUMN_RANGE:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.ROW_RANGE:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.NAMED_EXPRESSION:
return false;
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PERCENT_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PLUS_UNARY_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.MINUS_UNARY_OP:
{
return doesContainFunctions(ast.value, functionCriterion);
}
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.CONCATENATE_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.EQUALS_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.NOT_EQUAL_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.LESS_THAN_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.GREATER_THAN_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.LESS_THAN_OR_EQUAL_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.GREATER_THAN_OR_EQUAL_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.MINUS_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PLUS_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.TIMES_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.DIV_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.POWER_OP:
return doesContainFunctions(ast.left, functionCriterion) || doesContainFunctions(ast.right, functionCriterion);
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PARENTHESIS:
return doesContainFunctions(ast.expression, functionCriterion);
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.FUNCTION_CALL:
{
if (functionCriterion(ast.procedureName)) {
return true;
}
return ast.args.some(arg => doesContainFunctions(arg, functionCriterion));
}
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.ARRAY:
{
return ast.args.some(row => row.some(arg => doesContainFunctions(arg, functionCriterion)));
}
}
};
/***/ }),
/* 60 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ FormulaLexer: () => (/* binding */ FormulaLexer),
/* harmony export */ FormulaParser: () => (/* binding */ FormulaParser)
/* harmony export */ });
/* harmony import */ var chevrotain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14);
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61);
/* harmony import */ var _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _Ast__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(57);
/* harmony import */ var _CellAddress__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(9);
/* harmony import */ var _LexerConfig__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(62);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* LL(k) formula parser described using Chevrotain DSL
*
* It is equivalent to the grammar below:
*
* F -> '=' E <br/>
* B -> K < B | K >= B ... | K <br/>
* K -> E & K | E <br/>
* E -> M + E | M - E | M <br/>
* M -> W * M | W / M | W <br/>
* W -> C * W | C <br/>
* C -> N | R | O | A | P | num <br/>
* N -> '(' E ')' <br/>
* R -> A:OFFSET(..) | A:A <br/>
* O -> OFFSET(..) | OFFSET(..):A | OFFSET(..):OFFSET(..) <br/>
* A -> A1 | $A1 | A$1 | $A$1 <br/>
* P -> SUM(..) <br/>
*/
class FormulaParser extends chevrotain__WEBPACK_IMPORTED_MODULE_0__.EmbeddedActionsParser {
constructor(lexerConfig, sheetMapping) {
super(lexerConfig.allTokens, {
outputCst: false,
maxLookahead: 7
});
this.booleanExpressionOrEmpty = this.RULE('booleanExpressionOrEmpty', () => {
return this.OR([{
ALT: () => this.SUBRULE(this.booleanExpression)
}, {
ALT: (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.EMPTY_ALT)((0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildEmptyArgAst)())
}]);
});
/**
* Rule for procedure expressions: SUM(1,A1)
*/
this.procedureExpression = this.RULE('procedureExpression', () => {
var _a;
const procedureNameToken = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.ProcedureName);
const procedureName = procedureNameToken.image.toUpperCase().slice(0, -1);
const canonicalProcedureName = (_a = this.lexerConfig.functionMapping[procedureName]) !== null && _a !== void 0 ? _a : procedureName;
const args = [];
let argument = this.SUBRULE(this.booleanExpressionOrEmpty);
this.MANY(() => {
var _a;
const separator = this.CONSUME(this.lexerConfig.ArgSeparator);
if (argument.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.EMPTY) {
argument.leadingWhitespace = (_a = separator.leadingWhitespace) === null || _a === void 0 ? void 0 : _a.image;
}
args.push(argument);
argument = this.SUBRULE2(this.booleanExpressionOrEmpty);
});
args.push(argument);
if (args.length === 1 && args[0].type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.EMPTY) {
args.length = 0;
}
const rParenToken = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RParen);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildProcedureAst)(canonicalProcedureName, args, procedureNameToken.leadingWhitespace, rParenToken.leadingWhitespace);
});
this.namedExpressionExpression = this.RULE('namedExpressionExpression', () => {
const name = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.NamedExpression);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildNamedExpressionAst)(name.image, name.leadingWhitespace);
});
/**
* Rule for OFFSET() function expression
*/
this.offsetProcedureExpression = this.RULE('offsetProcedureExpression', () => {
const args = [];
this.CONSUME(this.lexerConfig.OffsetProcedureName);
this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.LParen);
this.MANY_SEP({
SEP: this.lexerConfig.ArgSeparator,
DEF: () => {
args.push(this.SUBRULE(this.booleanExpression));
}
});
this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RParen);
return this.handleOffsetHeuristic(args);
});
/**
* Rule for column range, e.g. A:B, Sheet1!A:B, Sheet1!A:Sheet1!B
*/
this.columnRangeExpression = this.RULE('columnRangeExpression', () => {
const range = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.ColumnRange);
const [startImage, endImage] = range.image.split(':');
const firstAddress = this.ACTION(() => (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.columnAddressFromString)(this.sheetMapping, startImage, this.formulaAddress));
const secondAddress = this.ACTION(() => (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.columnAddressFromString)(this.sheetMapping, endImage, this.formulaAddress));
if (firstAddress === undefined || secondAddress === undefined) {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF));
}
if (firstAddress.exceedsSheetSizeLimits(this.lexerConfig.maxColumns) || secondAddress.exceedsSheetSizeLimits(this.lexerConfig.maxColumns)) {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildErrorWithRawInputAst)(range.image, new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NAME), range.leadingWhitespace);
}
if (firstAddress.sheet === undefined && secondAddress.sheet !== undefined) {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.ParserError, 'Malformed range expression');
}
const {
firstEnd,
secondEnd,
sheetRefType
} = FormulaParser.fixSheetIdsForRangeEnds(firstAddress, secondAddress);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildColumnRangeAst)(firstEnd, secondEnd, sheetRefType, range.leadingWhitespace);
});
/**
* Rule for row range, e.g. 1:2, Sheet1!1:2, Sheet1!1:Sheet1!2
*/
this.rowRangeExpression = this.RULE('rowRangeExpression', () => {
const range = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RowRange);
const [startImage, endImage] = range.image.split(':');
const firstAddress = this.ACTION(() => (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.rowAddressFromString)(this.sheetMapping, startImage, this.formulaAddress));
const secondAddress = this.ACTION(() => (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.rowAddressFromString)(this.sheetMapping, endImage, this.formulaAddress));
if (firstAddress === undefined || secondAddress === undefined) {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF));
}
if (firstAddress.exceedsSheetSizeLimits(this.lexerConfig.maxRows) || secondAddress.exceedsSheetSizeLimits(this.lexerConfig.maxRows)) {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildErrorWithRawInputAst)(range.image, new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NAME), range.leadingWhitespace);
}
if (firstAddress.sheet === undefined && secondAddress.sheet !== undefined) {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.ParserError, 'Malformed range expression');
}
const {
firstEnd,
secondEnd,
sheetRefType
} = FormulaParser.fixSheetIdsForRangeEnds(firstAddress, secondAddress);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildRowRangeAst)(firstEnd, secondEnd, sheetRefType, range.leadingWhitespace);
});
/**
* Rule for cell reference expression (e.g. A1, $A1, A$1, $A$1, $Sheet42!A$17)
*/
this.cellReference = this.RULE('cellReference', () => {
const cell = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.CellReference);
const address = this.ACTION(() => {
return (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.cellAddressFromString)(this.sheetMapping, cell.image, this.formulaAddress);
});
if (address === undefined) {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildErrorWithRawInputAst)(cell.image, new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF), cell.leadingWhitespace);
} else if (address.exceedsSheetSizeLimits(this.lexerConfig.maxColumns, this.lexerConfig.maxRows)) {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildErrorWithRawInputAst)(cell.image, new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NAME), cell.leadingWhitespace);
} else {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellReferenceAst)(address, cell.leadingWhitespace);
}
});
/**
* Rule for end range reference expression with additional checks considering range start
*/
this.endRangeReference = this.RULE('endRangeReference', start => {
var _a;
const end = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.CellReference);
const startAddress = this.ACTION(() => {
return (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.cellAddressFromString)(this.sheetMapping, start.image, this.formulaAddress);
});
const endAddress = this.ACTION(() => {
return (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.cellAddressFromString)(this.sheetMapping, end.image, this.formulaAddress);
});
if (startAddress === undefined || endAddress === undefined) {
return this.ACTION(() => {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildErrorWithRawInputAst)(`${start.image}:${end.image}`, new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF), start.leadingWhitespace);
});
} else if (startAddress.exceedsSheetSizeLimits(this.lexerConfig.maxColumns, this.lexerConfig.maxRows) || endAddress.exceedsSheetSizeLimits(this.lexerConfig.maxColumns, this.lexerConfig.maxRows)) {
return this.ACTION(() => {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildErrorWithRawInputAst)(`${start.image}:${end.image}`, new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NAME), start.leadingWhitespace);
});
}
return this.buildCellRange(startAddress, endAddress, (_a = start.leadingWhitespace) === null || _a === void 0 ? void 0 : _a.image);
});
/**
* Rule for end of range expression
*
* End of range may be a cell reference or OFFSET() function call
*/
this.endOfRangeExpression = this.RULE('endOfRangeExpression', start => {
return this.OR([{
ALT: () => {
return this.SUBRULE(this.endRangeReference, {
ARGS: [start]
});
}
}, {
ALT: () => {
var _a;
const offsetProcedure = this.SUBRULE(this.offsetProcedureExpression);
const startAddress = this.ACTION(() => {
return (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.cellAddressFromString)(this.sheetMapping, start.image, this.formulaAddress);
});
if (startAddress === undefined) {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF));
}
if (offsetProcedure.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.CELL_REFERENCE) {
return this.buildCellRange(startAddress, offsetProcedure.reference, (_a = start.leadingWhitespace) === null || _a === void 0 ? void 0 : _a.image);
} else {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.RangeOffsetNotAllowed, 'Range offset not allowed here');
}
}
}]);
});
/**
* Rule for cell ranges (e.g. A1:B$3, A1:OFFSET())
*/
this.cellRangeExpression = this.RULE('cellRangeExpression', () => {
const start = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.CellReference);
this.CONSUME2(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RangeSeparator);
return this.SUBRULE(this.endOfRangeExpression, {
ARGS: [start]
});
});
/**
* Rule for end range reference expression starting with offset procedure with additional checks considering range start
*/
this.endRangeWithOffsetStartReference = this.RULE('endRangeWithOffsetStartReference', start => {
const end = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.CellReference);
const endAddress = this.ACTION(() => {
return (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_3__.cellAddressFromString)(this.sheetMapping, end.image, this.formulaAddress);
});
if (endAddress === undefined) {
return this.ACTION(() => {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF));
});
}
return this.buildCellRange(start.reference, endAddress, start.leadingWhitespace);
});
/**
* Rule for end of range expression
*
* End of range may be a cell reference or OFFSET() function call
*/
this.endOfRangeWithOffsetStartExpression = this.RULE('endOfRangeWithOffsetStartExpression', start => {
return this.OR([{
ALT: () => {
return this.SUBRULE(this.endRangeWithOffsetStartReference, {
ARGS: [start]
});
}
}, {
ALT: () => {
const offsetProcedure = this.SUBRULE(this.offsetProcedureExpression);
if (offsetProcedure.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.CELL_REFERENCE) {
return this.buildCellRange(start.reference, offsetProcedure.reference, start.leadingWhitespace);
} else {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.RangeOffsetNotAllowed, 'Range offset not allowed here');
}
}
}]);
});
/**
* Rule for expressions that start with the OFFSET function.
*
* The OFFSET function can occur as a cell reference, or as a part of a cell range.
* To preserve LL(k) properties, expressions that start with the OFFSET function need a separate rule.
*
* Depending on the presence of the {@link RangeSeparator}, a proper {@link Ast} node type is built.
*/
this.offsetExpression = this.RULE('offsetExpression', () => {
const offsetProcedure = this.SUBRULE(this.offsetProcedureExpression);
let end;
this.OPTION(() => {
this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RangeSeparator);
if (offsetProcedure.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.CELL_RANGE) {
end = this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.RangeOffsetNotAllowed, 'Range offset not allowed here');
} else {
end = this.SUBRULE(this.endOfRangeWithOffsetStartExpression, {
ARGS: [offsetProcedure]
});
}
});
if (end !== undefined) {
return end;
}
return offsetProcedure;
});
this.insideArrayExpression = this.RULE('insideArrayExpression', () => {
const ret = [[]];
ret[ret.length - 1].push(this.SUBRULE(this.booleanExpression));
this.MANY(() => {
this.OR([{
ALT: () => {
this.CONSUME(this.lexerConfig.ArrayColSeparator);
ret[ret.length - 1].push(this.SUBRULE2(this.booleanExpression));
}
}, {
ALT: () => {
this.CONSUME(this.lexerConfig.ArrayRowSeparator);
ret.push([]);
ret[ret.length - 1].push(this.SUBRULE3(this.booleanExpression));
}
}]);
});
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildArrayAst)(ret);
});
/**
* Rule for parenthesis expression
*/
this.parenthesisExpression = this.RULE('parenthesisExpression', () => {
const lParenToken = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.LParen);
const expression = this.SUBRULE(this.booleanExpression);
const rParenToken = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RParen);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildParenthesisAst)(expression, lParenToken.leadingWhitespace, rParenToken.leadingWhitespace);
});
this.arrayExpression = this.RULE('arrayExpression', () => {
return this.OR([{
ALT: () => {
const ltoken = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.ArrayLParen);
const ret = this.SUBRULE(this.insideArrayExpression);
const rtoken = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.ArrayRParen);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildArrayAst)(ret.args, ltoken.leadingWhitespace, rtoken.leadingWhitespace);
}
}, {
ALT: () => this.SUBRULE(this.parenthesisExpression)
}]);
});
this.numericStringToNumber = input => {
const normalized = input.replace(this.lexerConfig.decimalSeparator, '.');
return Number(normalized);
};
/**
* Rule for positive atomic expressions
*/
this.positiveAtomicExpression = this.RULE('positiveAtomicExpression', () => {
var _a;
return this.OR((_a = this.atomicExpCache) !== null && _a !== void 0 ? _a : this.atomicExpCache = [{
ALT: () => this.SUBRULE(this.arrayExpression)
}, {
ALT: () => this.SUBRULE(this.cellRangeExpression)
}, {
ALT: () => this.SUBRULE(this.columnRangeExpression)
}, {
ALT: () => this.SUBRULE(this.rowRangeExpression)
}, {
ALT: () => this.SUBRULE(this.offsetExpression)
}, {
ALT: () => this.SUBRULE(this.cellReference)
}, {
ALT: () => this.SUBRULE(this.procedureExpression)
}, {
ALT: () => this.SUBRULE(this.namedExpressionExpression)
}, {
ALT: () => {
const number = this.CONSUME(this.lexerConfig.NumberLiteral);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildNumberAst)(this.numericStringToNumber(number.image), number.leadingWhitespace);
}
}, {
ALT: () => {
const str = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.StringLiteral);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildStringAst)(str);
}
}, {
ALT: () => {
const token = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.ErrorLiteral);
const errString = token.image.toUpperCase();
const errorType = this.lexerConfig.errorMapping[errString];
if (errorType) {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(errorType), token.leadingWhitespace);
} else {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.ParserError, 'Unknown error literal');
}
}
}]);
});
this.rightUnaryOpAtomicExpression = this.RULE('rightUnaryOpAtomicExpression', () => {
const positiveAtomicExpression = this.SUBRULE(this.positiveAtomicExpression);
const percentage = this.OPTION(() => {
return this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.PercentOp);
});
if (percentage) {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildPercentOpAst)(positiveAtomicExpression, percentage.leadingWhitespace);
}
return positiveAtomicExpression;
});
/**
* Rule for atomic expressions, which is positive atomic expression or negation of it
*/
this.atomicExpression = this.RULE('atomicExpression', () => {
return this.OR([{
ALT: () => {
const op = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.AdditionOp);
const value = this.SUBRULE(this.atomicExpression);
if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.PlusOp)) {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildPlusUnaryOpAst)(value, op.leadingWhitespace);
} else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.MinusOp)) {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildMinusUnaryOpAst)(value, op.leadingWhitespace);
} else {
this.customParsingError = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.parsingError)(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.ParserError, 'Mismatched token type');
return this.customParsingError;
}
}
}, {
ALT: () => this.SUBRULE2(this.rightUnaryOpAtomicExpression)
}]);
});
/**
* Rule for power expression
*/
this.powerExpression = this.RULE('powerExpression', () => {
let lhs = this.SUBRULE(this.atomicExpression);
this.MANY(() => {
const op = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.PowerOp);
const rhs = this.SUBRULE2(this.atomicExpression);
if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.PowerOp)) {
lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildPowerOpAst)(lhs, rhs, op.leadingWhitespace);
} else {
this.ACTION(() => {
throw Error('Operator not supported');
});
}
});
return lhs;
});
/**
* Rule for multiplication category operators (e.g. 1 * A1, 1 / A1)
*/
this.multiplicationExpression = this.RULE('multiplicationExpression', () => {
let lhs = this.SUBRULE(this.powerExpression);
this.MANY(() => {
const op = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.MultiplicationOp);
const rhs = this.SUBRULE2(this.powerExpression);
if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.TimesOp)) {
lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildTimesOpAst)(lhs, rhs, op.leadingWhitespace);
} else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.DivOp)) {
lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildDivOpAst)(lhs, rhs, op.leadingWhitespace);
} else {
this.ACTION(() => {
throw Error('Operator not supported');
});
}
});
return lhs;
});
/**
* Rule for addition category operators (e.g. 1 + A1, 1 - A1)
*/
this.additionExpression = this.RULE('additionExpression', () => {
let lhs = this.SUBRULE(this.multiplicationExpression);
this.MANY(() => {
const op = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.AdditionOp);
const rhs = this.SUBRULE2(this.multiplicationExpression);
if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.PlusOp)) {
lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildPlusOpAst)(lhs, rhs, op.leadingWhitespace);
} else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.MinusOp)) {
lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildMinusOpAst)(lhs, rhs, op.leadingWhitespace);
} else {
this.ACTION(() => {
throw Error('Operator not supported');
});
}
});
return lhs;
});
/**
* Rule for concatenation operator expression (e.g. "=" & A1)
*/
this.concatenateExpression = this.RULE('concatenateExpression', () => {
let lhs = this.SUBRULE(this.additionExpression);
this.MANY(() => {
const op = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.ConcatenateOp);
const rhs = this.SUBRULE2(this.additionExpression);
lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildConcatenateOpAst)(lhs, rhs, op.leadingWhitespace);
});
return lhs;
});
/**
* Rule for boolean expression (e.g. 1 <= A1)
*/
this.booleanExpression = this.RULE('booleanExpression', () => {
let lhs = this.SUBRULE(this.concatenateExpression);
this.MANY(() => {
const op = this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.BooleanOp);
const rhs = this.SUBRULE2(this.concatenateExpression);
if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.EqualsOp)) {
lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildEqualsOpAst)(lhs, rhs, op.leadingWhitespace);
} else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.NotEqualOp)) {
lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildNotEqualOpAst)(lhs, rhs, op.leadingWhitespace);
} else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.GreaterThanOp)) {
lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildGreaterThanOpAst)(lhs, rhs, op.leadingWhitespace);
} else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.LessThanOp)) {
lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildLessThanOpAst)(lhs, rhs, op.leadingWhitespace);
} else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.GreaterThanOrEqualOp)) {
lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildGreaterThanOrEqualOpAst)(lhs, rhs, op.leadingWhitespace);
} else if ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(op, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.LessThanOrEqualOp)) {
lhs = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildLessThanOrEqualOpAst)(lhs, rhs, op.leadingWhitespace);
} else {
this.ACTION(() => {
throw Error('Operator not supported');
});
}
});
return lhs;
});
/**
* Entry rule
*/
this.formula = this.RULE('formula', () => {
this.CONSUME(_LexerConfig__WEBPACK_IMPORTED_MODULE_6__.EqualsOp);
return this.SUBRULE(this.booleanExpression);
});
this.lexerConfig = lexerConfig;
this.sheetMapping = sheetMapping;
this.formulaAddress = (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(0, 0, 0);
this.performSelfAnalysis();
}
/**
* Parses tokenized formula and builds abstract syntax tree
*
* @param {ExtendedToken[]} tokens - tokenized formula
* @param {SimpleCellAddress} formulaAddress - address of the cell in which formula is located
*/
parseFromTokens(tokens, formulaAddress) {
this.input = tokens;
let ast = this.formulaWithContext(formulaAddress);
let errors = [];
if (this.customParsingError) {
errors.push(this.customParsingError);
}
errors = errors.concat(this.errors.map(e => ({
type: _Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.ParserError,
message: e.message
})));
if (errors.length > 0) {
ast = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildParsingErrorAst)();
}
return {
ast,
errors
};
}
reset() {
super.reset();
this.customParsingError = undefined;
}
/**
* Entry rule wrapper that sets formula address
*
* @param {SimpleCellAddress} address - address of the cell in which formula is located
*/
formulaWithContext(address) {
this.formulaAddress = address;
return this.formula();
}
buildCellRange(firstAddress, secondAddress, leadingWhitespace) {
if (firstAddress.sheet === undefined && secondAddress.sheet !== undefined) {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.ParserError, 'Malformed range expression');
}
const {
firstEnd,
secondEnd,
sheetRefType
} = FormulaParser.fixSheetIdsForRangeEnds(firstAddress, secondAddress);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellRangeAst)(firstEnd, secondEnd, sheetRefType, leadingWhitespace);
}
static fixSheetIdsForRangeEnds(firstEnd, secondEnd) {
const sheetRefType = FormulaParser.rangeSheetReferenceType(firstEnd.sheet, secondEnd.sheet);
const secondEndFixed = firstEnd.sheet !== undefined && secondEnd.sheet === undefined ? secondEnd.withSheet(firstEnd.sheet) : secondEnd;
return {
firstEnd,
secondEnd: secondEndFixed,
sheetRefType
};
}
/**
* Returns {@link CellReferenceAst} or {@link CellRangeAst} based on OFFSET function arguments
*
* @param {Ast[]} args - OFFSET function arguments
*/
handleOffsetHeuristic(args) {
const cellArg = args[0];
if (cellArg.type !== _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.CELL_REFERENCE) {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'First argument to OFFSET is not a reference');
}
const rowsArg = args[1];
let rowShift;
if (rowsArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER && Number.isInteger(rowsArg.value)) {
rowShift = rowsArg.value;
} else if (rowsArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.PLUS_UNARY_OP && rowsArg.value.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER && Number.isInteger(rowsArg.value.value)) {
rowShift = rowsArg.value.value;
} else if (rowsArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.MINUS_UNARY_OP && rowsArg.value.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER && Number.isInteger(rowsArg.value.value)) {
rowShift = -rowsArg.value.value;
} else {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Second argument to OFFSET is not a static number');
}
const columnsArg = args[2];
let colShift;
if (columnsArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER && Number.isInteger(columnsArg.value)) {
colShift = columnsArg.value;
} else if (columnsArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.PLUS_UNARY_OP && columnsArg.value.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER && Number.isInteger(columnsArg.value.value)) {
colShift = columnsArg.value.value;
} else if (columnsArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.MINUS_UNARY_OP && columnsArg.value.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER && Number.isInteger(columnsArg.value.value)) {
colShift = -columnsArg.value.value;
} else {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Third argument to OFFSET is not a static number');
}
const heightArg = args[3];
let height;
if (heightArg === undefined) {
height = 1;
} else if (heightArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER) {
height = heightArg.value;
if (height < 1) {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Fourth argument to OFFSET is too small number');
} else if (!Number.isInteger(height)) {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Fourth argument to OFFSET is not integer');
}
} else {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Fourth argument to OFFSET is not a static number');
}
const widthArg = args[4];
let width;
if (widthArg === undefined) {
width = 1;
} else if (widthArg.type === _Ast__WEBPACK_IMPORTED_MODULE_4__.AstNodeType.NUMBER) {
width = widthArg.value;
if (width < 1) {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Fifth argument to OFFSET is too small number');
} else if (!Number.isInteger(width)) {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Fifth argument to OFFSET is not integer');
}
} else {
return this.parsingError(_Ast__WEBPACK_IMPORTED_MODULE_4__.ParsingErrorType.StaticOffsetError, 'Fifth argument to OFFSET is not a static number');
}
const topLeftCorner = new _CellAddress__WEBPACK_IMPORTED_MODULE_5__.CellAddress(cellArg.reference.col + colShift, cellArg.reference.row + rowShift, cellArg.reference.type);
let absoluteCol = topLeftCorner.col;
let absoluteRow = topLeftCorner.row;
if (cellArg.reference.type === _CellAddress__WEBPACK_IMPORTED_MODULE_5__.CellReferenceType.CELL_REFERENCE_RELATIVE || cellArg.reference.type === _CellAddress__WEBPACK_IMPORTED_MODULE_5__.CellReferenceType.CELL_REFERENCE_ABSOLUTE_COL) {
absoluteRow = absoluteRow + this.formulaAddress.row;
}
if (cellArg.reference.type === _CellAddress__WEBPACK_IMPORTED_MODULE_5__.CellReferenceType.CELL_REFERENCE_RELATIVE || cellArg.reference.type === _CellAddress__WEBPACK_IMPORTED_MODULE_5__.CellReferenceType.CELL_REFERENCE_ABSOLUTE_ROW) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
absoluteCol = absoluteCol + this.formulaAddress.col;
}
if (absoluteCol < 0 || absoluteRow < 0) {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellErrorAst)(new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.OutOfSheet));
}
if (width === 1 && height === 1) {
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellReferenceAst)(topLeftCorner);
} else {
const bottomRightCorner = new _CellAddress__WEBPACK_IMPORTED_MODULE_5__.CellAddress(topLeftCorner.col + width - 1, topLeftCorner.row + height - 1, topLeftCorner.type);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildCellRangeAst)(topLeftCorner, bottomRightCorner, _Ast__WEBPACK_IMPORTED_MODULE_4__.RangeSheetReferenceType.RELATIVE);
}
}
parsingError(type, message) {
this.customParsingError = (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.parsingError)(type, message);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_4__.buildParsingErrorAst)();
}
static rangeSheetReferenceType(start, end) {
if (start === undefined) {
return _Ast__WEBPACK_IMPORTED_MODULE_4__.RangeSheetReferenceType.RELATIVE;
} else if (end === undefined) {
return _Ast__WEBPACK_IMPORTED_MODULE_4__.RangeSheetReferenceType.START_ABSOLUTE;
} else {
return _Ast__WEBPACK_IMPORTED_MODULE_4__.RangeSheetReferenceType.BOTH_ABSOLUTE;
}
}
}
class FormulaLexer {
constructor(lexerConfig) {
this.lexerConfig = lexerConfig;
this.lexer = new chevrotain__WEBPACK_IMPORTED_MODULE_0__.Lexer(lexerConfig.allTokens, {
ensureOptimizations: true
});
}
/**
* Returns Lexer tokens from formula string
*
* @param {string} text - string representation of a formula
*/
tokenizeFormula(text) {
const lexingResult = this.lexer.tokenize(text);
let tokens = lexingResult.tokens;
tokens = this.trimTrailingWhitespaces(tokens);
tokens = this.skipWhitespacesInsideRanges(tokens);
tokens = this.skipWhitespacesBeforeArgSeparators(tokens);
lexingResult.tokens = tokens;
return lexingResult;
}
skipWhitespacesInsideRanges(tokens) {
return FormulaLexer.filterTokensByNeighbors(tokens, (previous, current, next) => {
return ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(previous, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.CellReference) || (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(previous, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RangeSeparator)) && (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(current, this.lexerConfig.WhiteSpace) && ((0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(next, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.CellReference) || (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(next, _LexerConfig__WEBPACK_IMPORTED_MODULE_6__.RangeSeparator));
});
}
skipWhitespacesBeforeArgSeparators(tokens) {
return FormulaLexer.filterTokensByNeighbors(tokens, (previous, current, next) => {
return !(0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(previous, this.lexerConfig.ArgSeparator) && (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(current, this.lexerConfig.WhiteSpace) && (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(next, this.lexerConfig.ArgSeparator);
});
}
static filterTokensByNeighbors(tokens, shouldBeSkipped) {
if (tokens.length < 3) {
return tokens;
}
let i = 0;
const filteredTokens = [tokens[i++]];
while (i < tokens.length - 1) {
if (!shouldBeSkipped(tokens[i - 1], tokens[i], tokens[i + 1])) {
filteredTokens.push(tokens[i]);
}
++i;
}
filteredTokens.push(tokens[i]);
return filteredTokens;
}
trimTrailingWhitespaces(tokens) {
if (tokens.length > 0 && (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.tokenMatcher)(tokens[tokens.length - 1], this.lexerConfig.WhiteSpace)) {
tokens.pop();
}
return tokens;
}
}
/***/ }),
/* 61 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ErrorMessage: () => (/* binding */ ErrorMessage)
/* harmony export */ });
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* This is a class for detailed error messages across HyperFormula.
*/
class ErrorMessage {}
ErrorMessage.DistinctSigns = 'Distinct signs.';
ErrorMessage.WrongArgNumber = 'Wrong number of arguments.';
ErrorMessage.EmptyArg = 'Empty function argument.';
ErrorMessage.EmptyArray = 'Empty array not allowed.';
ErrorMessage.ArrayDimensions = 'Array dimensions are not compatible.';
ErrorMessage.NoSpaceForArrayResult = 'No space for array result.';
ErrorMessage.ValueSmall = 'Value too small.';
ErrorMessage.ValueLarge = 'Value too large.';
ErrorMessage.BadCriterion = 'Incorrect criterion.';
ErrorMessage.RangeManySheets = 'Range spans more than one sheet.';
ErrorMessage.CellRangeExpected = 'Cell range expected.';
ErrorMessage.WrongDimension = 'Wrong range dimension.';
ErrorMessage.ScalarExpected = 'Cell range not allowed.';
ErrorMessage.NumberCoercion = 'Value cannot be coerced to number.';
ErrorMessage.NumberExpected = 'Number argument expected.';
ErrorMessage.IntegerExpected = 'Value needs to be an integer.';
ErrorMessage.BadMode = 'Mode not recognized.';
ErrorMessage.DateBounds = 'Date outside of bounds.';
ErrorMessage.OutOfSheet = 'Resulting reference is out of the sheet.';
ErrorMessage.WrongType = 'Wrong type of argument.';
ErrorMessage.NaN = 'NaN or infinite value encountered.';
ErrorMessage.EqualLength = 'Ranges need to be of equal length.';
ErrorMessage.Negative = 'Value cannot be negative.';
ErrorMessage.NotBinary = 'String does not represent a binary number.';
ErrorMessage.NotOctal = 'String does not represent an octal number.';
ErrorMessage.NotHex = 'String does not represent a hexadecimal number.';
ErrorMessage.EndStartPeriod = 'End period needs to be at least start period.';
ErrorMessage.CellRefExpected = 'Cell reference expected.';
ErrorMessage.EmptyRange = 'Empty range not allowed.';
ErrorMessage.BadRef = 'Address is not correct.';
ErrorMessage.NumberRange = 'Number-only range expected.';
ErrorMessage.ValueNotFound = 'Value not found.';
ErrorMessage.ValueBaseLarge = 'Value in base too large.';
ErrorMessage.ValueBaseSmall = 'Value in base too small.';
ErrorMessage.ValueBaseLong = 'Value in base too long.';
ErrorMessage.NegativeLength = 'Length cannot be negative.';
ErrorMessage.PatternNotFound = 'Pattern not found.';
ErrorMessage.OneValue = 'Needs at least one value.';
ErrorMessage.TwoValues = 'Range needs to contain at least two elements.';
ErrorMessage.ThreeValues = 'Range needs to contain at least three elements.';
ErrorMessage.IndexBounds = 'Index out of bounds.';
ErrorMessage.IndexLarge = 'Index too large.';
ErrorMessage.Formula = 'Expected formula.';
ErrorMessage.NegativeCount = 'Count cannot be negative.';
ErrorMessage.ParseError = 'Parsing error.';
ErrorMessage.SheetRef = 'Sheet does not exist.';
ErrorMessage.PeriodLong = 'Period number cannot exceed life length.';
ErrorMessage.InvalidDate = 'Invalid date.';
ErrorMessage.BitshiftLong = 'Result of bitshift is too long.';
ErrorMessage.EmptyString = 'Empty-string argument not allowed.';
ErrorMessage.LengthBounds = 'Length out of bounds.';
ErrorMessage.NegativeTime = 'Time cannot be negative.';
ErrorMessage.NoDefault = 'No default option.';
ErrorMessage.NoConditionMet = 'None of the conditions were met.';
ErrorMessage.Selector = 'Selector cannot exceed the number of arguments.';
ErrorMessage.StartEndDate = 'Start date needs to be earlier than end date.';
ErrorMessage.IncorrectDateTime = 'String does not represent correct DateTime.';
ErrorMessage.CharacterCodeBounds = 'Character code out of bounds.';
ErrorMessage.NonZero = 'Argument cannot be 0.';
ErrorMessage.LessThanOne = 'Argument cannot be less than 1.';
ErrorMessage.WeekendString = 'Incorrect weekend bitmask string.';
ErrorMessage.InvalidRoman = 'Invalid roman numeral.';
ErrorMessage.WrongOrder = 'Wrong order of values.';
ErrorMessage.ComplexNumberExpected = 'Complex number expected.';
ErrorMessage.ShouldBeIorJ = 'Should be \'i\' or \'j\'.';
ErrorMessage.SizeMismatch = 'Array dimensions mismatched.';
ErrorMessage.FunctionName = arg => `Function name ${arg} not recognized.`;
ErrorMessage.NamedExpressionName = arg => `Named expression ${arg} not recognized.`;
ErrorMessage.LicenseKey = arg => `License key is ${arg}.`;
/***/ }),
/* 62 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AdditionOp: () => (/* binding */ AdditionOp),
/* harmony export */ ArrayLParen: () => (/* binding */ ArrayLParen),
/* harmony export */ ArrayRParen: () => (/* binding */ ArrayRParen),
/* harmony export */ BooleanOp: () => (/* binding */ BooleanOp),
/* harmony export */ CellReference: () => (/* binding */ CellReference),
/* harmony export */ ColumnRange: () => (/* binding */ ColumnRange),
/* harmony export */ ConcatenateOp: () => (/* binding */ ConcatenateOp),
/* harmony export */ DivOp: () => (/* binding */ DivOp),
/* harmony export */ EqualsOp: () => (/* binding */ EqualsOp),
/* harmony export */ ErrorLiteral: () => (/* binding */ ErrorLiteral),
/* harmony export */ GreaterThanOp: () => (/* binding */ GreaterThanOp),
/* harmony export */ GreaterThanOrEqualOp: () => (/* binding */ GreaterThanOrEqualOp),
/* harmony export */ LParen: () => (/* binding */ LParen),
/* harmony export */ LessThanOp: () => (/* binding */ LessThanOp),
/* harmony export */ LessThanOrEqualOp: () => (/* binding */ LessThanOrEqualOp),
/* harmony export */ MinusOp: () => (/* binding */ MinusOp),
/* harmony export */ MultiplicationOp: () => (/* binding */ MultiplicationOp),
/* harmony export */ NamedExpression: () => (/* binding */ NamedExpression),
/* harmony export */ NotEqualOp: () => (/* binding */ NotEqualOp),
/* harmony export */ PercentOp: () => (/* binding */ PercentOp),
/* harmony export */ PlusOp: () => (/* binding */ PlusOp),
/* harmony export */ PowerOp: () => (/* binding */ PowerOp),
/* harmony export */ ProcedureName: () => (/* binding */ ProcedureName),
/* harmony export */ RParen: () => (/* binding */ RParen),
/* harmony export */ RangeSeparator: () => (/* binding */ RangeSeparator),
/* harmony export */ RowRange: () => (/* binding */ RowRange),
/* harmony export */ StringLiteral: () => (/* binding */ StringLiteral),
/* harmony export */ TimesOp: () => (/* binding */ TimesOp),
/* harmony export */ buildLexerConfig: () => (/* binding */ buildLexerConfig)
/* harmony export */ });
/* harmony import */ var chevrotain__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(14);
/* harmony import */ var _parser_consts__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(12);
/* harmony import */ var _CellReferenceMatcher__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(63);
/* harmony import */ var _NamedExpressionMatcher__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(64);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
const AdditionOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'AdditionOp',
pattern: chevrotain__WEBPACK_IMPORTED_MODULE_0__.Lexer.NA
});
const PlusOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'PlusOp',
pattern: /\+/,
categories: AdditionOp
});
const MinusOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'MinusOp',
pattern: /-/,
categories: AdditionOp
});
const MultiplicationOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'MultiplicationOp',
pattern: chevrotain__WEBPACK_IMPORTED_MODULE_0__.Lexer.NA
});
const TimesOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'TimesOp',
pattern: /\*/,
categories: MultiplicationOp
});
const DivOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'DivOp',
pattern: /\//,
categories: MultiplicationOp
});
const PowerOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'PowerOp',
pattern: /\^/
});
const PercentOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'PercentOp',
pattern: /%/
});
const BooleanOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'BooleanOp',
pattern: chevrotain__WEBPACK_IMPORTED_MODULE_0__.Lexer.NA
});
const EqualsOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'EqualsOp',
pattern: /=/,
categories: BooleanOp
});
const NotEqualOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'NotEqualOp',
pattern: /<>/,
categories: BooleanOp
});
const GreaterThanOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'GreaterThanOp',
pattern: />/,
categories: BooleanOp
});
const LessThanOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'LessThanOp',
pattern: /</,
categories: BooleanOp
});
const GreaterThanOrEqualOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'GreaterThanOrEqualOp',
pattern: />=/,
categories: BooleanOp
});
const LessThanOrEqualOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'LessThanOrEqualOp',
pattern: /<=/,
categories: BooleanOp
});
const ConcatenateOp = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'ConcatenateOp',
pattern: /&/
});
const LParen = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'LParen',
pattern: /\(/
});
const RParen = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'RParen',
pattern: /\)/
});
const ArrayLParen = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'ArrayLParen',
pattern: /{/
});
const ArrayRParen = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'ArrayRParen',
pattern: /}/
});
const StringLiteral = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'StringLiteral',
pattern: /"([^"\\]*(\\.[^"\\]*)*)"/
});
const ErrorLiteral = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'ErrorLiteral',
pattern: /#[A-Za-z0-9\/]+[?!]?/
});
const RangeSeparator = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'RangeSeparator',
pattern: new RegExp(_parser_consts__WEBPACK_IMPORTED_MODULE_1__.RANGE_OPERATOR)
});
const ColumnRange = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'ColumnRange',
pattern: new RegExp(`${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.COLUMN_REFERENCE_PATTERN}${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.RANGE_OPERATOR}${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.COLUMN_REFERENCE_PATTERN}`)
});
const RowRange = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'RowRange',
pattern: new RegExp(`${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.ROW_REFERENCE_PATTERN}${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.RANGE_OPERATOR}${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.ROW_REFERENCE_PATTERN}`)
});
const ProcedureName = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'ProcedureName',
pattern: new RegExp(`([${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.UNICODE_LETTER_PATTERN}][${_parser_consts__WEBPACK_IMPORTED_MODULE_1__.NON_RESERVED_CHARACTER_PATTERN}]*)\\(`)
});
const cellReferenceMatcher = new _CellReferenceMatcher__WEBPACK_IMPORTED_MODULE_2__.CellReferenceMatcher();
const CellReference = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'CellReference',
pattern: cellReferenceMatcher.match.bind(cellReferenceMatcher),
start_chars_hint: cellReferenceMatcher.POSSIBLE_START_CHARACTERS,
line_breaks: false
});
const namedExpressionMatcher = new _NamedExpressionMatcher__WEBPACK_IMPORTED_MODULE_3__.NamedExpressionMatcher();
const NamedExpression = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'NamedExpression',
pattern: namedExpressionMatcher.match.bind(namedExpressionMatcher),
start_chars_hint: namedExpressionMatcher.POSSIBLE_START_CHARACTERS,
line_breaks: false
});
/**
* Builds the configuration object for the lexer
*/
const buildLexerConfig = config => {
const offsetProcedureNameLiteral = config.translationPackage.getFunctionTranslation('OFFSET');
const errorMapping = config.errorMapping;
const functionMapping = config.translationPackage.buildFunctionMapping();
const whitespaceTokenRegexp = new RegExp(config.ignoreWhiteSpace === 'standard' ? _parser_consts__WEBPACK_IMPORTED_MODULE_1__.ODFF_WHITESPACE_PATTERN : _parser_consts__WEBPACK_IMPORTED_MODULE_1__.ALL_WHITESPACE_PATTERN);
const WhiteSpace = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'WhiteSpace',
pattern: whitespaceTokenRegexp
});
const ArrayRowSeparator = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'ArrayRowSep',
pattern: config.arrayRowSeparator
});
const ArrayColSeparator = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'ArrayColSep',
pattern: config.arrayColumnSeparator
});
const NumberLiteral = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'NumberLiteral',
pattern: new RegExp(`(([${config.decimalSeparator}]\\d+)|(\\d+([${config.decimalSeparator}]\\d*)?))(e[+-]?\\d+)?`)
});
const OffsetProcedureName = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'OffsetProcedureName',
pattern: new RegExp(offsetProcedureNameLiteral, 'i')
});
let ArgSeparator;
let inject;
if (config.functionArgSeparator === config.arrayColumnSeparator) {
ArgSeparator = ArrayColSeparator;
inject = [];
} else if (config.functionArgSeparator === config.arrayRowSeparator) {
ArgSeparator = ArrayRowSeparator;
inject = [];
} else {
ArgSeparator = (0,chevrotain__WEBPACK_IMPORTED_MODULE_0__.createToken)({
name: 'ArgSeparator',
pattern: config.functionArgSeparator
});
inject = [ArgSeparator];
}
/* order is important, first pattern is used */
const allTokens = [WhiteSpace, PlusOp, MinusOp, TimesOp, DivOp, PowerOp, EqualsOp, NotEqualOp, PercentOp, GreaterThanOrEqualOp, LessThanOrEqualOp, GreaterThanOp, LessThanOp, LParen, RParen, ArrayLParen, ArrayRParen, OffsetProcedureName, ProcedureName, RangeSeparator, ...inject, ColumnRange, RowRange, NumberLiteral, StringLiteral, ErrorLiteral, ConcatenateOp, BooleanOp, AdditionOp, MultiplicationOp, CellReference, NamedExpression, ArrayRowSeparator, ArrayColSeparator];
return {
ArgSeparator,
NumberLiteral,
OffsetProcedureName,
ArrayRowSeparator,
ArrayColSeparator,
WhiteSpace,
allTokens,
errorMapping,
functionMapping,
decimalSeparator: config.decimalSeparator,
maxColumns: config.maxColumns,
maxRows: config.maxRows
};
};
/***/ }),
/* 63 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CellReferenceMatcher: () => (/* binding */ CellReferenceMatcher)
/* harmony export */ });
/* harmony import */ var _parser_consts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* Helper class for recognizing CellReference token in text
*/
class CellReferenceMatcher {
constructor() {
this.POSSIBLE_START_CHARACTERS = [..._parser_consts__WEBPACK_IMPORTED_MODULE_0__.ALL_UNICODE_LETTERS_ARRAY, ..._parser_consts__WEBPACK_IMPORTED_MODULE_0__.ALL_DIGITS_ARRAY, _parser_consts__WEBPACK_IMPORTED_MODULE_0__.ABSOLUTE_OPERATOR, "'", '_'];
this.cellReferenceRegexp = new RegExp(_parser_consts__WEBPACK_IMPORTED_MODULE_0__.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, startOffset) {
this.cellReferenceRegexp.lastIndex = startOffset;
const execResult = this.cellReferenceRegexp.exec(text + '@');
if (execResult == null || execResult[1] == null) {
return null;
}
execResult[0] = execResult[1];
return execResult;
}
}
/***/ }),
/* 64 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ NamedExpressionMatcher: () => (/* binding */ NamedExpressionMatcher)
/* harmony export */ });
/* harmony import */ var _parser_consts__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* Helper class for recognizing NamedExpression token in text
*/
class NamedExpressionMatcher {
constructor() {
this.POSSIBLE_START_CHARACTERS = [..._parser_consts__WEBPACK_IMPORTED_MODULE_0__.ALL_UNICODE_LETTERS_ARRAY, '_'];
this.namedExpressionRegexp = new RegExp(_parser_consts__WEBPACK_IMPORTED_MODULE_0__.NAMED_EXPRESSION_PATTERN, 'y');
this.r1c1CellRefRegexp = new RegExp(`^${_parser_consts__WEBPACK_IMPORTED_MODULE_0__.R1C1_CELL_REFERENCE_PATTERN}$`);
}
/**
* Method used by the lexer to recognize NamedExpression 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, startOffset) {
this.namedExpressionRegexp.lastIndex = startOffset;
const execResult = this.namedExpressionRegexp.exec(text);
if (execResult == null || execResult[0] == null) {
return null;
}
if (this.r1c1CellRefRegexp.test(execResult[0])) {
return null;
}
return execResult;
}
}
/***/ }),
/* 65 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Unparser: () => (/* binding */ Unparser),
/* harmony export */ formatNumber: () => (/* binding */ formatNumber)
/* harmony export */ });
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(0);
/* harmony import */ var _addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8);
/* harmony import */ var _Ast__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(57);
/* harmony import */ var _binaryOpTokenMap__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(58);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
class Unparser {
constructor(config, lexerConfig, sheetMappingFn, namedExpressions) {
this.config = config;
this.lexerConfig = lexerConfig;
this.sheetMappingFn = sheetMappingFn;
this.namedExpressions = namedExpressions;
}
unparse(ast, address) {
return '=' + this.unparseAst(ast, address);
}
unparseAst(ast, address) {
var _a, _b;
switch (ast.type) {
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.EMPTY:
{
return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)('', ast.leadingWhitespace);
}
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.NUMBER:
{
return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(formatNumber(ast.value, this.config.decimalSeparator), ast.leadingWhitespace);
}
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.STRING:
{
return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)('"' + ast.value + '"', ast.leadingWhitespace);
}
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.FUNCTION_CALL:
{
const args = ast.args.map(arg => arg !== undefined ? this.unparseAst(arg, address) : '').join(this.config.functionArgSeparator);
const procedureName = this.config.translationPackage.isFunctionTranslated(ast.procedureName) ? this.config.translationPackage.getFunctionTranslation(ast.procedureName) : ast.procedureName;
const rightPart = procedureName + '(' + args + (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(')', ast.internalWhitespace);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(rightPart, ast.leadingWhitespace);
}
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.NAMED_EXPRESSION:
{
const originalNamedExpressionName = (_a = this.namedExpressions.nearestNamedExpression(ast.expressionName, address.sheet)) === null || _a === void 0 ? void 0 : _a.displayName;
return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(originalNamedExpressionName || ast.expressionName, ast.leadingWhitespace);
}
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_REFERENCE:
{
let image;
if (ast.reference.sheet !== undefined) {
image = this.unparseSheetName(ast.reference.sheet) + '!';
} else {
image = '';
}
image += (_b = ast.reference.unparse(address)) !== null && _b !== void 0 ? _b : this.config.translationPackage.getErrorTranslation(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(image, ast.leadingWhitespace);
}
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.COLUMN_RANGE:
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ROW_RANGE:
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_RANGE:
{
return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(this.formatRange(ast, address), ast.leadingWhitespace);
}
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PLUS_UNARY_OP:
{
const unparsedExpr = this.unparseAst(ast.value, address);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)('+', ast.leadingWhitespace) + unparsedExpr;
}
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.MINUS_UNARY_OP:
{
const unparsedExpr = this.unparseAst(ast.value, address);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)('-', ast.leadingWhitespace) + unparsedExpr;
}
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PERCENT_OP:
{
return this.unparseAst(ast.value, address) + (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)('%', ast.leadingWhitespace);
}
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ERROR:
{
const image = this.config.translationPackage.getErrorTranslation(ast.error ? ast.error.type : _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.ERROR);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(image, ast.leadingWhitespace);
}
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ERROR_WITH_RAW_INPUT:
{
return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(ast.rawInput, ast.leadingWhitespace);
}
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PARENTHESIS:
{
const expression = this.unparseAst(ast.expression, address);
const rightPart = '(' + expression + (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(')', ast.internalWhitespace);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(rightPart, ast.leadingWhitespace);
}
case _Ast__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ARRAY:
{
const ret = '{' + ast.args.map(row => row.map(val => this.unparseAst(val, address)).join(this.config.arrayColumnSeparator)).join(this.config.arrayRowSeparator) + (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)('}', ast.internalWhitespace);
return (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(ret, ast.leadingWhitespace);
}
default:
{
const left = this.unparseAst(ast.left, address);
const right = this.unparseAst(ast.right, address);
return left + (0,_Ast__WEBPACK_IMPORTED_MODULE_3__.imageWithWhitespace)(_binaryOpTokenMap__WEBPACK_IMPORTED_MODULE_4__.binaryOpTokenMap[ast.type], ast.leadingWhitespace) + right;
}
}
}
unparseSheetName(sheetId) {
const sheetName = (0,_addressRepresentationConverters__WEBPACK_IMPORTED_MODULE_2__.sheetIndexToString)(sheetId, this.sheetMappingFn);
if (sheetName === undefined) {
throw new _index__WEBPACK_IMPORTED_MODULE_1__.NoSheetWithIdError(sheetId);
}
return sheetName;
}
formatRange(ast, baseAddress) {
let startSheeet = '';
let endSheet = '';
if (ast.start.sheet !== undefined && ast.sheetReferenceType !== _Ast__WEBPACK_IMPORTED_MODULE_3__.RangeSheetReferenceType.RELATIVE) {
startSheeet = this.unparseSheetName(ast.start.sheet) + '!';
}
if (ast.end.sheet !== undefined && ast.sheetReferenceType === _Ast__WEBPACK_IMPORTED_MODULE_3__.RangeSheetReferenceType.BOTH_ABSOLUTE) {
endSheet = this.unparseSheetName(ast.end.sheet) + '!';
}
const unparsedStart = ast.start.unparse(baseAddress);
const unparsedEnd = ast.end.unparse(baseAddress);
if (unparsedStart === undefined || unparsedEnd === undefined) {
return this.config.translationPackage.getErrorTranslation(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.REF);
}
return `${startSheeet}${unparsedStart}:${endSheet}${unparsedEnd}`;
}
}
function formatNumber(number, decimalSeparator) {
const numericString = number.toString();
return numericString.replace('.', decimalSeparator);
}
/***/ }),
/* 66 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ collectDependencies: () => (/* binding */ collectDependencies)
/* harmony export */ });
/* harmony import */ var ___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
const collectDependenciesFn = (ast, functionRegistry, dependenciesSet, needArgument) => {
switch (ast.type) {
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.EMPTY:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.NUMBER:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.STRING:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.ERROR:
return;
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.NAMED_EXPRESSION:
{
if (needArgument) {
dependenciesSet.push(new ___WEBPACK_IMPORTED_MODULE_0__.NamedExpressionDependency(ast.expressionName));
}
return;
}
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.CELL_REFERENCE:
{
if (needArgument) {
dependenciesSet.push(new ___WEBPACK_IMPORTED_MODULE_0__.AddressDependency(ast.reference));
}
return;
}
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.CELL_RANGE:
{
if (needArgument && ast.start.sheet === ast.end.sheet) {
dependenciesSet.push(new ___WEBPACK_IMPORTED_MODULE_0__.CellRangeDependency(ast.start, ast.end));
}
return;
}
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.COLUMN_RANGE:
{
if (needArgument && ast.start.sheet === ast.end.sheet) {
dependenciesSet.push(new ___WEBPACK_IMPORTED_MODULE_0__.ColumnRangeDependency(ast.start, ast.end));
}
return;
}
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.ROW_RANGE:
{
if (needArgument && ast.start.sheet === ast.end.sheet) {
dependenciesSet.push(new ___WEBPACK_IMPORTED_MODULE_0__.RowRangeDependency(ast.start, ast.end));
}
return;
}
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PERCENT_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PLUS_UNARY_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.MINUS_UNARY_OP:
{
collectDependenciesFn(ast.value, functionRegistry, dependenciesSet, true);
return;
}
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.CONCATENATE_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.EQUALS_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.NOT_EQUAL_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.LESS_THAN_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.GREATER_THAN_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.LESS_THAN_OR_EQUAL_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.GREATER_THAN_OR_EQUAL_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.MINUS_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PLUS_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.TIMES_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.DIV_OP:
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.POWER_OP:
collectDependenciesFn(ast.left, functionRegistry, dependenciesSet, true);
collectDependenciesFn(ast.right, functionRegistry, dependenciesSet, true);
return;
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.PARENTHESIS:
collectDependenciesFn(ast.expression, functionRegistry, dependenciesSet, needArgument);
return;
case ___WEBPACK_IMPORTED_MODULE_0__.AstNodeType.FUNCTION_CALL:
{
const functionNeedArgument = !functionRegistry.doesFunctionNeedArgumentToBeComputed(ast.procedureName);
ast.args.forEach(argAst => collectDependenciesFn(argAst, functionRegistry, dependenciesSet, functionNeedArgument));
return;
}
}
};
const collectDependencies = (ast, functionRegistry) => {
const result = new Array();
collectDependenciesFn(ast, functionRegistry, result, true);
return result;
};
/***/ }),
/* 67 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AddressDependency: () => (/* binding */ AddressDependency),
/* harmony export */ CellRangeDependency: () => (/* binding */ CellRangeDependency),
/* harmony export */ ColumnRangeDependency: () => (/* binding */ ColumnRangeDependency),
/* harmony export */ NamedExpressionDependency: () => (/* binding */ NamedExpressionDependency),
/* harmony export */ RowRangeDependency: () => (/* binding */ RowRangeDependency)
/* harmony export */ });
/* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
class AddressDependency {
constructor(dependency) {
this.dependency = dependency;
}
absolutize(baseAddress) {
return this.dependency.toSimpleCellAddress(baseAddress);
}
}
class CellRangeDependency {
constructor(start, end) {
this.start = start;
this.end = end;
}
absolutize(baseAddress) {
return new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange(this.start.toSimpleCellAddress(baseAddress), this.end.toSimpleCellAddress(baseAddress));
}
}
class ColumnRangeDependency {
constructor(start, end) {
this.start = start;
this.end = end;
}
absolutize(baseAddress) {
const start = this.start.toSimpleColumnAddress(baseAddress);
const end = this.end.toSimpleColumnAddress(baseAddress);
return new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteColumnRange(start.sheet, start.col, end.col);
}
}
class RowRangeDependency {
constructor(start, end) {
this.start = start;
this.end = end;
}
absolutize(baseAddress) {
const start = this.start.toSimpleRowAddress(baseAddress);
const end = this.end.toSimpleRowAddress(baseAddress);
return new _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteRowRange(start.sheet, start.row, end.row);
}
}
class NamedExpressionDependency {
constructor(name) {
this.name = name;
}
absolutize(_baseAddress) {
return this;
}
}
/***/ }),
/* 68 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ContentChanges: () => (/* binding */ ContentChanges)
/* harmony export */ });
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(69);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
class ContentChanges {
constructor() {
this.changes = new Map();
}
static empty() {
return new ContentChanges();
}
addAll(other) {
for (const change of other.changes.values()) {
this.add(change.address, change);
}
return this;
}
addChange(newValue, address, oldValue) {
this.addInterpreterValue(newValue, address, oldValue);
}
exportChanges(exporter) {
let ret = [];
this.changes.forEach(e => {
const change = exporter.exportChange(e);
if (Array.isArray(change)) {
ret = ret.concat(change);
} else {
ret.push(change);
}
});
return ret;
}
getChanges() {
return Array.from(this.changes.values());
}
isEmpty() {
return this.changes.size === 0;
}
add(address, change) {
const value = change.value;
if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_1__.SimpleRangeValue) {
for (const cellAddress of value.effectiveAddressesFromData(address)) {
this.changes.delete(`${cellAddress.sheet},${cellAddress.col},${cellAddress.row}`);
}
}
this.changes.set((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.addressKey)(address), change);
}
addInterpreterValue(value, address, oldValue) {
this.add(address, {
address,
value,
oldValue
});
}
}
/***/ }),
/* 69 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ SimpleRangeValue: () => (/* binding */ SimpleRangeValue)
/* harmony export */ });
/* harmony import */ var _ArraySize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61);
/* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(70);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* A class that represents a range of data.
*/
class SimpleRangeValue {
/**
* In most cases, it's more convenient to create a `SimpleRangeValue` object
* by calling one of the [static factory methods](#fromrange).
*/
constructor(_data,
/**
* A property that represents the address of the range.
*/
range, dependencyGraph, _hasOnlyNumbers) {
this._data = _data;
this.range = range;
this.dependencyGraph = dependencyGraph;
this._hasOnlyNumbers = _hasOnlyNumbers;
this.size = _data === undefined ? new _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize(range.effectiveWidth(dependencyGraph), range.effectiveHeight(dependencyGraph)) : new _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize(_data[0].length, _data.length);
}
/**
* Returns the range data as a 2D array.
*/
get data() {
this.ensureThatComputed();
return this._data;
}
/**
* A factory method. Returns a `SimpleRangeValue` object with the provided range address and the provided data.
*/
static fromRange(data, range, dependencyGraph) {
return new SimpleRangeValue(data, range, dependencyGraph, true);
}
/**
* A factory method. Returns a `SimpleRangeValue` object with the provided numeric data.
*/
static onlyNumbers(data) {
return new SimpleRangeValue(data, undefined, undefined, true);
}
/**
* A factory method. Returns a `SimpleRangeValue` object with the provided data.
*/
static onlyValues(data) {
return new SimpleRangeValue(data, undefined, undefined, undefined);
}
/**
* A factory method. Returns a `SimpleRangeValue` object with the provided range address.
*/
static onlyRange(range, dependencyGraph) {
return new SimpleRangeValue(undefined, range, dependencyGraph, undefined);
}
/**
* A factory method. Returns a `SimpleRangeValue` object that contains a single value.
*/
static fromScalar(scalar) {
return new SimpleRangeValue([[scalar]], undefined, undefined, undefined);
}
/**
* Returns `true` if and only if the `SimpleRangeValue` has no address set.
*/
isAdHoc() {
return this.range === undefined;
}
/**
* Returns the number of columns contained in the range.
*/
width() {
return this.size.width;
}
/**
* Returns the number of rows contained in the range.
*/
height() {
return this.size.height;
}
/**
* Returns the range data as a 1D array.
*/
valuesFromTopLeftCorner() {
this.ensureThatComputed();
const ret = [];
for (let i = 0; i < this._data.length; i++) {
for (let j = 0; j < this._data[0].length; j++) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
ret.push(this._data[i][j]);
}
}
return ret;
}
/**
* Generates the addresses of the cells contained in the range assuming the provided address is the left corner of the range.
*/
*effectiveAddressesFromData(leftCorner) {
for (let row = 0; row < this.data.length; ++row) {
const rowData = this.data[row];
for (let col = 0; col < rowData.length; ++col) {
yield (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(leftCorner.sheet, leftCorner.col + col, leftCorner.row + row);
}
}
}
/**
* Generates values and addresses of the cells contained in the range assuming the provided address is the left corner of the range.
*
* This method combines the functionalities of [`iterateValuesFromTopLeftCorner()`](#iteratevaluesfromtopleftcorner) and [`effectiveAddressesFromData()`](#effectiveaddressesfromdata).
*/
*entriesFromTopLeftCorner(leftCorner) {
this.ensureThatComputed();
for (let row = 0; row < this.size.height; ++row) {
for (let col = 0; col < this.size.width; ++col) {
yield [this._data[row][col], (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(leftCorner.sheet, leftCorner.col + col, leftCorner.row + row)];
}
}
}
/**
* Generates the values of the cells contained in the range assuming the provided address is the left corner of the range.
*/
*iterateValuesFromTopLeftCorner() {
yield* this.valuesFromTopLeftCorner();
}
/**
* Returns the number of cells contained in the range.
*/
numberOfElements() {
return this.size.width * this.size.height;
}
/**
* Returns `true` if and only if the range contains only numeric values.
*/
hasOnlyNumbers() {
if (this._hasOnlyNumbers === undefined) {
this._hasOnlyNumbers = true;
for (const row of this.data) {
for (const v of row) {
if (typeof v !== 'number') {
this._hasOnlyNumbers = false;
return false;
}
}
}
}
return this._hasOnlyNumbers;
}
/**
* Returns the range data as a 2D array of numbers.
*
* Internal use only.
*/
rawNumbers() {
return this._data;
}
/**
* Returns the range data as a 2D array.
*
* Internal use only.
*/
rawData() {
var _a;
this.ensureThatComputed();
return (_a = this._data) !== null && _a !== void 0 ? _a : [];
}
/**
* Returns `true` if and only if the range has the same width and height as the `other` range object.
*/
sameDimensionsAs(other) {
return this.width() === other.width() && this.height() === other.height();
}
/**
* Computes the range data if it is not computed yet.
*/
ensureThatComputed() {
if (this._data !== undefined) {
return;
}
this._hasOnlyNumbers = true;
this._data = this.range.addressesArrayMap(this.dependencyGraph, cellFromRange => {
const value = this.dependencyGraph.getCellValue(cellFromRange);
if (value instanceof SimpleRangeValue) {
this._hasOnlyNumbers = false;
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ScalarExpected);
} else if ((0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_3__.isExtendedNumber)(value)) {
return value;
} else {
this._hasOnlyNumbers = false;
return value;
}
});
}
}
/***/ }),
/* 70 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ CurrencyNumber: () => (/* binding */ CurrencyNumber),
/* harmony export */ DateNumber: () => (/* binding */ DateNumber),
/* harmony export */ DateTimeNumber: () => (/* binding */ DateTimeNumber),
/* harmony export */ EmptyValue: () => (/* binding */ EmptyValue),
/* harmony export */ NumberType: () => (/* binding */ NumberType),
/* harmony export */ PercentNumber: () => (/* binding */ PercentNumber),
/* harmony export */ RichNumber: () => (/* binding */ RichNumber),
/* harmony export */ TimeNumber: () => (/* binding */ TimeNumber),
/* harmony export */ cloneNumber: () => (/* binding */ cloneNumber),
/* harmony export */ getFormatOfExtendedNumber: () => (/* binding */ getFormatOfExtendedNumber),
/* harmony export */ getRawValue: () => (/* binding */ getRawValue),
/* harmony export */ getTypeFormatOfExtendedNumber: () => (/* binding */ getTypeFormatOfExtendedNumber),
/* harmony export */ getTypeOfExtendedNumber: () => (/* binding */ getTypeOfExtendedNumber),
/* harmony export */ isExtendedNumber: () => (/* binding */ isExtendedNumber)
/* harmony export */ });
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
const EmptyValue = Symbol('Empty value');
function getRawValue(num) {
if (num instanceof RichNumber) {
return num.val;
} else {
return num;
}
}
class RichNumber {
constructor(val, format) {
this.val = val;
this.format = format;
}
fromNumber(val) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
return new this.constructor(val);
}
}
function cloneNumber(val, newVal) {
if (typeof val === 'number') {
return newVal;
} else {
const ret = val.fromNumber(newVal);
ret.format = val.format;
return ret;
}
}
class DateNumber extends RichNumber {
getDetailedType() {
return NumberType.NUMBER_DATE;
}
}
class CurrencyNumber extends RichNumber {
getDetailedType() {
return NumberType.NUMBER_CURRENCY;
}
}
class TimeNumber extends RichNumber {
getDetailedType() {
return NumberType.NUMBER_TIME;
}
}
class DateTimeNumber extends RichNumber {
getDetailedType() {
return NumberType.NUMBER_DATETIME;
}
}
class PercentNumber extends RichNumber {
getDetailedType() {
return NumberType.NUMBER_PERCENT;
}
}
function isExtendedNumber(val) {
return typeof val === 'number' || val instanceof RichNumber;
}
var NumberType;
(function (NumberType) {
NumberType["NUMBER_RAW"] = "NUMBER_RAW";
NumberType["NUMBER_DATE"] = "NUMBER_DATE";
NumberType["NUMBER_TIME"] = "NUMBER_TIME";
NumberType["NUMBER_DATETIME"] = "NUMBER_DATETIME";
NumberType["NUMBER_CURRENCY"] = "NUMBER_CURRENCY";
NumberType["NUMBER_PERCENT"] = "NUMBER_PERCENT";
})(NumberType || (NumberType = {}));
function getTypeOfExtendedNumber(num) {
if (num instanceof RichNumber) {
return num.getDetailedType();
} else {
return NumberType.NUMBER_RAW;
}
}
function getFormatOfExtendedNumber(num) {
if (num instanceof RichNumber) {
return num.format;
} else {
return undefined;
}
}
function getTypeFormatOfExtendedNumber(num) {
if (num instanceof RichNumber) {
return {
type: num.getDetailedType(),
format: num.format
};
} else {
return {
type: NumberType.NUMBER_RAW
};
}
}
/***/ }),
/* 71 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ColumnsSpan: () => (/* binding */ ColumnsSpan),
/* harmony export */ RowsSpan: () => (/* binding */ RowsSpan)
/* harmony export */ });
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/*
* A class representing a set of rows in specific sheet
*/
class RowsSpan {
constructor(sheet, rowStart, rowEnd) {
this.sheet = sheet;
this.rowStart = rowStart;
this.rowEnd = rowEnd;
if (rowStart < 0) {
throw Error('Starting row cant be less than 0');
}
if (rowEnd < rowStart) {
throw Error('Row span cant end before start');
}
}
get numberOfRows() {
return this.rowEnd - this.rowStart + 1;
}
get start() {
return this.rowStart;
}
get end() {
return this.rowEnd;
}
static fromNumberOfRows(sheet, rowStart, numberOfRows) {
return new RowsSpan(sheet, rowStart, rowStart + numberOfRows - 1);
}
static fromRowStartAndEnd(sheet, rowStart, rowEnd) {
return new RowsSpan(sheet, rowStart, rowEnd);
}
*rows() {
for (let col = this.rowStart; col <= this.rowEnd; ++col) {
yield col;
}
}
intersect(otherSpan) {
if (this.sheet !== otherSpan.sheet) {
throw Error('Can\'t intersect spans from different sheets');
}
const start = Math.max(this.rowStart, otherSpan.rowStart);
const end = Math.min(this.rowEnd, otherSpan.rowEnd);
if (start > end) {
return null;
}
return new RowsSpan(this.sheet, start, end);
}
firstRow() {
return new RowsSpan(this.sheet, this.rowStart, this.rowStart);
}
}
/*
* A class representing a set of columns in specific sheet
*/
class ColumnsSpan {
constructor(sheet, columnStart, columnEnd) {
this.sheet = sheet;
this.columnStart = columnStart;
this.columnEnd = columnEnd;
if (columnStart < 0) {
throw Error('Starting column cant be less than 0');
}
if (columnEnd < columnStart) {
throw Error('Column span cant end before start');
}
}
get numberOfColumns() {
return this.columnEnd - this.columnStart + 1;
}
get start() {
return this.columnStart;
}
get end() {
return this.columnEnd;
}
static fromNumberOfColumns(sheet, columnStart, numberOfColumns) {
return new ColumnsSpan(sheet, columnStart, columnStart + numberOfColumns - 1);
}
static fromColumnStartAndEnd(sheet, columnStart, columnEnd) {
return new ColumnsSpan(sheet, columnStart, columnEnd);
}
*columns() {
for (let col = this.columnStart; col <= this.columnEnd; ++col) {
yield col;
}
}
intersect(otherSpan) {
if (this.sheet !== otherSpan.sheet) {
throw Error('Can\'t intersect spans from different sheets');
}
const start = Math.max(this.columnStart, otherSpan.columnStart);
const end = Math.min(this.columnEnd, otherSpan.columnEnd);
if (start > end) {
return null;
}
return new ColumnsSpan(this.sheet, start, end);
}
firstColumn() {
return new ColumnsSpan(this.sheet, this.columnStart, this.columnStart);
}
}
/***/ }),
/* 72 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ EmptyStatistics: () => (/* reexport safe */ _EmptyStatistics__WEBPACK_IMPORTED_MODULE_0__.EmptyStatistics),
/* harmony export */ StatType: () => (/* reexport safe */ _StatType__WEBPACK_IMPORTED_MODULE_2__.StatType),
/* harmony export */ Statistics: () => (/* reexport safe */ _Statistics__WEBPACK_IMPORTED_MODULE_1__.Statistics)
/* harmony export */ });
/* harmony import */ var _EmptyStatistics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(73);
/* harmony import */ var _Statistics__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(74);
/* harmony import */ var _StatType__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(75);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/***/ }),
/* 73 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ EmptyStatistics: () => (/* binding */ EmptyStatistics)
/* harmony export */ });
/* harmony import */ var _Statistics__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(74);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/** Do not store stats in the memory. Stats are not needed on daily basis */
class EmptyStatistics extends _Statistics__WEBPACK_IMPORTED_MODULE_0__.Statistics {
/** @inheritDoc */
incrementCriterionFunctionFullCacheUsed() {
// do nothing
}
/** @inheritDoc */
incrementCriterionFunctionPartialCacheUsed() {
// do nothing
}
/** @inheritDoc */
start(_name) {
// do nothing
}
/** @inheritDoc */
end(_name) {
// do nothing
}
}
/***/ }),
/* 74 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Statistics: () => (/* binding */ Statistics)
/* harmony export */ });
/* harmony import */ var _StatType__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(75);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* Provides tracking performance statistics to the engine
*/
class Statistics {
constructor() {
this.stats = new Map([[_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_FULL_CACHE_USED, 0], [_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_PARTIAL_CACHE_USED, 0]]);
this.startTimes = new Map();
}
incrementCriterionFunctionFullCacheUsed() {
var _a;
const newValue = ((_a = this.stats.get(_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_FULL_CACHE_USED)) !== null && _a !== void 0 ? _a : 0) + 1;
this.stats.set(_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_FULL_CACHE_USED, newValue);
}
incrementCriterionFunctionPartialCacheUsed() {
var _a;
const newValue = ((_a = this.stats.get(_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_PARTIAL_CACHE_USED)) !== null && _a !== void 0 ? _a : 0) + 1;
this.stats.set(_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_PARTIAL_CACHE_USED, newValue);
}
/**
* Resets statistics
*/
reset() {
this.stats.clear();
this.startTimes.clear();
this.stats.set(_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_FULL_CACHE_USED, 0);
this.stats.set(_StatType__WEBPACK_IMPORTED_MODULE_0__.StatType.CRITERION_FUNCTION_PARTIAL_CACHE_USED, 0);
}
/**
* Starts tracking particular statistic.
*
* @param name - statistic to start tracking
*/
start(name) {
if (this.startTimes.get(name)) {
throw Error(`Statistics ${name} already started`);
} else {
this.startTimes.set(name, Date.now());
}
}
/**
* Stops tracking particular statistic.
* Raise error if tracking statistic wasn't started.
*
* @param name - statistic to stop tracking
*/
end(name) {
var _a;
const now = Date.now();
const startTime = this.startTimes.get(name);
if (startTime) {
let values = (_a = this.stats.get(name)) !== null && _a !== void 0 ? _a : 0;
values += now - startTime;
this.stats.set(name, values);
this.startTimes.delete(name);
} else {
throw Error(`Statistics ${name} not started`);
}
}
/**
* Measure given statistic as execution of given function.
*
* @param name - statistic to track
* @param func - function to call
* @returns result of the function call
*/
measure(name, func) {
this.start(name);
const result = func();
this.end(name);
return result;
}
/**
* Returns the snapshot of current results
*/
snapshot() {
return new Map(this.stats);
}
}
/***/ }),
/* 75 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ StatType: () => (/* binding */ StatType)
/* harmony export */ });
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
var StatType;
(function (StatType) {
/* build engine */
StatType["BUILD_ENGINE_TOTAL"] = "BUILD_ENGINE_TOTAL";
StatType["PARSER"] = "PARSER";
StatType["GRAPH_BUILD"] = "GRAPH_BUILD";
StatType["COLLECT_DEPENDENCIES"] = "COLLECT_DEPENDENCIES";
StatType["PROCESS_DEPENDENCIES"] = "PROCESS_DEPENDENCIES";
StatType["TOP_SORT"] = "TOP_SORT";
StatType["BUILD_COLUMN_INDEX"] = "BUILD_COLUMN_INDEX";
StatType["EVALUATION"] = "EVALUATION";
StatType["VLOOKUP"] = "VLOOKUP";
/* crud adjustments */
StatType["TRANSFORM_ASTS"] = "TRANSFORM_ASTS";
StatType["TRANSFORM_ASTS_POSTPONED"] = "TRANSFORM_ASTS_POSTPONED";
StatType["ADJUSTING_ADDRESS_MAPPING"] = "ADJUSTING_ADDRESS_MAPPING";
StatType["ADJUSTING_ARRAY_MAPPING"] = "ADJUSTING_ARRAY_MAPPING";
StatType["ADJUSTING_RANGES"] = "ADJUSTING_RANGES";
StatType["ADJUSTING_GRAPH"] = "ADJUSTING_GRAPH";
/* criterion cache */
StatType["CRITERION_FUNCTION_FULL_CACHE_USED"] = "CRITERION_FUNCTION_FULL_CACHE_USED";
StatType["CRITERION_FUNCTION_PARTIAL_CACHE_USED"] = "CRITERION_FUNCTION_PARTIAL_CACHE_USED";
})(StatType || (StatType = {}));
/***/ }),
/* 76 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AddressMapping: () => (/* binding */ AddressMapping)
/* harmony export */ });
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(77);
/* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(70);
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
class AddressMapping {
constructor(policy) {
this.policy = policy;
this.mapping = new Map();
}
/** @inheritDoc */
getCell(address) {
const sheetMapping = this.mapping.get(address.sheet);
if (sheetMapping === undefined) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(address.sheet);
}
return sheetMapping.getCell(address);
}
fetchCell(address) {
const sheetMapping = this.mapping.get(address.sheet);
if (sheetMapping === undefined) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(address.sheet);
}
const vertex = sheetMapping.getCell(address);
if (!vertex) {
throw Error('Vertex for address missing in AddressMapping');
}
return vertex;
}
strategyFor(sheetId) {
const strategy = this.mapping.get(sheetId);
if (strategy === undefined) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(sheetId);
}
return strategy;
}
addSheet(sheetId, strategy) {
if (this.mapping.has(sheetId)) {
throw Error('Sheet already added');
}
this.mapping.set(sheetId, strategy);
}
autoAddSheet(sheetId, sheet, sheetBoundaries) {
const {
height,
width,
fill
} = sheetBoundaries;
const strategyConstructor = this.policy.call(fill);
this.addSheet(sheetId, new strategyConstructor(width, height));
}
getCellValue(address) {
const vertex = this.getCell(address);
if (vertex === undefined) {
return _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_1__.EmptyValue;
} else if (vertex instanceof _index__WEBPACK_IMPORTED_MODULE_2__.ArrayVertex) {
return vertex.getArrayCellValue(address);
} else {
return vertex.getCellValue();
}
}
getRawValue(address) {
const vertex = this.getCell(address);
if (vertex instanceof _index__WEBPACK_IMPORTED_MODULE_2__.ValueCellVertex) {
return vertex.getValues().rawValue;
} else if (vertex instanceof _index__WEBPACK_IMPORTED_MODULE_2__.ArrayVertex) {
return vertex.getArrayCellRawValue(address);
} else {
return null;
}
}
/** @inheritDoc */
setCell(address, newVertex) {
const sheetMapping = this.mapping.get(address.sheet);
if (!sheetMapping) {
throw Error('Sheet not initialized');
}
sheetMapping.setCell(address, newVertex);
}
moveCell(source, destination) {
const sheetMapping = this.mapping.get(source.sheet);
if (!sheetMapping) {
throw Error('Sheet not initialized.');
}
if (source.sheet !== destination.sheet) {
throw Error('Cannot move cells between sheets.');
}
if (sheetMapping.has(destination)) {
throw new Error('Cannot move cell. Destination already occupied.');
}
const vertex = sheetMapping.getCell(source);
if (vertex === undefined) {
throw new Error('Cannot move cell. No cell with such address.');
}
this.setCell(destination, vertex);
this.removeCell(source);
}
removeCell(address) {
const sheetMapping = this.mapping.get(address.sheet);
if (!sheetMapping) {
throw Error('Sheet not initialized');
}
sheetMapping.removeCell(address);
}
/** @inheritDoc */
has(address) {
const sheetMapping = this.mapping.get(address.sheet);
if (sheetMapping === undefined) {
return false;
}
return sheetMapping.has(address);
}
/** @inheritDoc */
getHeight(sheetId) {
const sheetMapping = this.mapping.get(sheetId);
if (sheetMapping === undefined) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(sheetId);
}
return sheetMapping.getHeight();
}
/** @inheritDoc */
getWidth(sheetId) {
const sheetMapping = this.mapping.get(sheetId);
if (!sheetMapping) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(sheetId);
}
return sheetMapping.getWidth();
}
addRows(sheet, row, numberOfRows) {
const sheetMapping = this.mapping.get(sheet);
if (sheetMapping === undefined) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(sheet);
}
sheetMapping.addRows(row, numberOfRows);
}
removeRows(removedRows) {
const sheetMapping = this.mapping.get(removedRows.sheet);
if (sheetMapping === undefined) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(removedRows.sheet);
}
sheetMapping.removeRows(removedRows);
}
removeSheet(sheetId) {
this.mapping.delete(sheetId);
}
addColumns(sheet, column, numberOfColumns) {
const sheetMapping = this.mapping.get(sheet);
if (sheetMapping === undefined) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(sheet);
}
sheetMapping.addColumns(column, numberOfColumns);
}
removeColumns(removedColumns) {
const sheetMapping = this.mapping.get(removedColumns.sheet);
if (sheetMapping === undefined) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(removedColumns.sheet);
}
sheetMapping.removeColumns(removedColumns);
}
*verticesFromRowsSpan(rowsSpan) {
yield* this.mapping.get(rowsSpan.sheet).verticesFromRowsSpan(rowsSpan); // eslint-disable-line @typescript-eslint/no-non-null-assertion
}
*verticesFromColumnsSpan(columnsSpan) {
yield* this.mapping.get(columnsSpan.sheet).verticesFromColumnsSpan(columnsSpan); // eslint-disable-line @typescript-eslint/no-non-null-assertion
}
*entriesFromRowsSpan(rowsSpan) {
yield* this.mapping.get(rowsSpan.sheet).entriesFromRowsSpan(rowsSpan);
}
*entriesFromColumnsSpan(columnsSpan) {
yield* this.mapping.get(columnsSpan.sheet).entriesFromColumnsSpan(columnsSpan);
}
*entries() {
for (const [sheet, mapping] of this.mapping.entries()) {
yield* mapping.getEntries(sheet);
}
}
*sheetEntries(sheet) {
const sheetMapping = this.mapping.get(sheet);
if (sheetMapping !== undefined) {
yield* sheetMapping.getEntries(sheet);
} else {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(sheet);
}
}
}
/***/ }),
/* 77 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ AliasAlreadyExisting: () => (/* binding */ AliasAlreadyExisting),
/* harmony export */ ConfigValueEmpty: () => (/* binding */ ConfigValueEmpty),
/* harmony export */ ConfigValueTooBigError: () => (/* binding */ ConfigValueTooBigError),
/* harmony export */ ConfigValueTooSmallError: () => (/* binding */ ConfigValueTooSmallError),
/* harmony export */ EvaluationSuspendedError: () => (/* binding */ EvaluationSuspendedError),
/* harmony export */ ExpectedOneOfValuesError: () => (/* binding */ ExpectedOneOfValuesError),
/* harmony export */ ExpectedValueOfTypeError: () => (/* binding */ ExpectedValueOfTypeError),
/* harmony export */ FunctionPluginValidationError: () => (/* binding */ FunctionPluginValidationError),
/* harmony export */ InvalidAddressError: () => (/* binding */ InvalidAddressError),
/* harmony export */ InvalidArgumentsError: () => (/* binding */ InvalidArgumentsError),
/* harmony export */ LanguageAlreadyRegisteredError: () => (/* binding */ LanguageAlreadyRegisteredError),
/* harmony export */ LanguageNotRegisteredError: () => (/* binding */ LanguageNotRegisteredError),
/* harmony export */ MissingTranslationError: () => (/* binding */ MissingTranslationError),
/* harmony export */ NamedExpressionDoesNotExistError: () => (/* binding */ NamedExpressionDoesNotExistError),
/* harmony export */ NamedExpressionNameIsAlreadyTakenError: () => (/* binding */ NamedExpressionNameIsAlreadyTakenError),
/* harmony export */ NamedExpressionNameIsInvalidError: () => (/* binding */ NamedExpressionNameIsInvalidError),
/* harmony export */ NoOperationToRedoError: () => (/* binding */ NoOperationToRedoError),
/* harmony export */ NoOperationToUndoError: () => (/* binding */ NoOperationToUndoError),
/* harmony export */ NoRelativeAddressesAllowedError: () => (/* binding */ NoRelativeAddressesAllowedError),
/* harmony export */ NoSheetWithIdError: () => (/* binding */ NoSheetWithIdError),
/* harmony export */ NoSheetWithNameError: () => (/* binding */ NoSheetWithNameError),
/* harmony export */ NotAFormulaError: () => (/* binding */ NotAFormulaError),
/* harmony export */ NothingToPasteError: () => (/* binding */ NothingToPasteError),
/* harmony export */ ProtectedFunctionError: () => (/* binding */ ProtectedFunctionError),
/* harmony export */ ProtectedFunctionTranslationError: () => (/* binding */ ProtectedFunctionTranslationError),
/* harmony export */ SheetNameAlreadyTakenError: () => (/* binding */ SheetNameAlreadyTakenError),
/* harmony export */ SheetSizeLimitExceededError: () => (/* binding */ SheetSizeLimitExceededError),
/* harmony export */ SheetsNotEqual: () => (/* binding */ SheetsNotEqual),
/* harmony export */ SourceLocationHasArrayError: () => (/* binding */ SourceLocationHasArrayError),
/* harmony export */ TargetLocationHasArrayError: () => (/* binding */ TargetLocationHasArrayError),
/* harmony export */ UnableToParseError: () => (/* binding */ UnableToParseError)
/* harmony export */ });
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* Error thrown when the sheet of a given ID does not exist.
*/
class NoSheetWithIdError extends Error {
constructor(sheetId) {
super(`There's no sheet with id = ${sheetId}`);
}
}
/**
* Error thrown when the sheet of a given name does not exist.
*/
class NoSheetWithNameError extends Error {
constructor(sheetName) {
super(`There's no sheet with name '${sheetName}'`);
}
}
/**
* Error thrown when the sheet of a given name already exists.
*/
class SheetNameAlreadyTakenError extends Error {
constructor(sheetName) {
super(`Sheet with name ${sheetName} already exists`);
}
}
/**
* Error thrown when loaded sheet size exceeds configured limits.
*/
class SheetSizeLimitExceededError extends Error {
constructor() {
super('Sheet size limit exceeded');
}
}
/**
* Error thrown when the the provided string is not a valid formula, i.e does not start with "="
*/
class NotAFormulaError extends Error {
constructor() {
super('This is not a formula');
}
}
/**
* Error thrown when the given address is invalid.
*/
class InvalidAddressError extends Error {
constructor(address) {
super(`Address (row = ${address.row}, col = ${address.col}) is invalid`);
}
}
/**
* Error thrown when the given arguments are invalid
*/
class InvalidArgumentsError extends Error {
constructor(expectedArguments) {
super(`Invalid arguments, expected ${expectedArguments}`);
}
}
/**
* Error thrown when the given sheets are not equal.
*/
class SheetsNotEqual extends Error {
constructor(sheet1, sheet2) {
super(`Sheets ${sheet1} and ${sheet2} are not equal.`);
}
}
/**
* Error thrown when the given named expression already exists in the workbook and therefore it cannot be added.
*/
class NamedExpressionNameIsAlreadyTakenError extends Error {
constructor(expressionName) {
super(`Name of Named Expression '${expressionName}' is already present`);
}
}
/**
* Error thrown when the name given for the named expression is invalid.
*/
class NamedExpressionNameIsInvalidError extends Error {
constructor(expressionName) {
super(`Name of Named Expression '${expressionName}' is invalid`);
}
}
/**
* Error thrown when the given named expression does not exist.
*/
class NamedExpressionDoesNotExistError extends Error {
constructor(expressionName) {
super(`Named Expression '${expressionName}' does not exist`);
}
}
/**
* Error thrown when there are no operations to be undone by the [[undo]] method.
*/
class NoOperationToUndoError extends Error {
constructor() {
super('There is no operation to undo');
}
}
/**
* Error thrown when there are no operations to redo by the [[redo]] method.
*/
class NoOperationToRedoError extends Error {
constructor() {
super('There is no operation to redo');
}
}
/**
* Error thrown when there is nothing to paste by the [[paste]] method.
*/
class NothingToPasteError extends Error {
constructor() {
super('There is nothing to paste');
}
}
function replacer(key, val) {
switch (typeof val) {
case 'function':
case 'symbol':
return val.toString();
case 'bigint':
return 'BigInt(' + val.toString() + ')';
default:
{
if (val instanceof RegExp) {
return 'RegExp(' + val.toString() + ')';
} else {
return val;
}
}
}
}
/**
* Error thrown when the given value cannot be parsed.
*
* Checks against the validity in:
*
* @see [[buildFromArray]]
* @see [[buildFromSheets]]
* @see [[setCellsContents]]
*/
class UnableToParseError extends Error {
constructor(value) {
super(`Unable to parse value: ${JSON.stringify(value, replacer, 4)}`);
}
}
/**
* Error thrown when the expected value type differs from the given value type.
* It also displays the expected type.
* This error might be thrown while setting or updating the [[ConfigParams]].
* The following methods accept [[ConfigParams]] as a parameter:
*
* @see [[buildEmpty]]
* @see [[buildFromArray]]
* @see [[buildFromSheets]]
* @see [[updateConfig]]
*/
class ExpectedValueOfTypeError extends Error {
constructor(expectedType, paramName) {
super(`Expected value of type: ${expectedType} for config parameter: ${paramName}`);
}
}
/**
* Error thrown when supplied config parameter value is an empty string.
* This error might be thrown while setting or updating the [[ConfigParams]].
* The following methods accept [[ConfigParams]] as a parameter:
*
* @see [[buildEmpty]]
* @see [[buildFromArray]]
* @see [[buildFromSheets]]
* @see [[updateConfig]]
*/
class ConfigValueEmpty extends Error {
constructor(paramName) {
super(`Config parameter ${paramName} cannot be empty.`);
}
}
/**
* Error thrown when supplied config parameter value is too small.
* This error might be thrown while setting or updating the [[ConfigParams]].
* The following methods accept [[ConfigParams]] as a parameter:
*
* @see [[buildEmpty]]
* @see [[buildFromArray]]
* @see [[buildFromSheets]]
* @see [[updateConfig]]
*/
class ConfigValueTooSmallError extends Error {
constructor(paramName, minimum) {
super(`Config parameter ${paramName} should be at least ${minimum}`);
}
}
/**
* Error thrown when supplied config parameter value is too big.
* This error might be thrown while setting or updating the [[ConfigParams]].
* The following methods accept [[ConfigParams]] as a parameter:
*
* @see [[buildEmpty]]
* @see [[buildFromArray]]
* @see [[buildFromSheets]]
* @see [[updateConfig]]
*/
class ConfigValueTooBigError extends Error {
constructor(paramName, maximum) {
super(`Config parameter ${paramName} should be at most ${maximum}`);
}
}
/**
* Error thrown when the value was expected to be set for a config parameter.
* It also displays the expected value.
* This error might be thrown while setting or updating the [[ConfigParams]].
* The following methods accept [[ConfigParams]] as a parameter:
*
* @see [[buildEmpty]]
* @see [[buildFromArray]]
* @see [[buildFromSheets]]
* @see [[updateConfig]]
*/
class ExpectedOneOfValuesError extends Error {
constructor(values, paramName) {
super(`Expected one of ${values} for config parameter: ${paramName}`);
}
}
/**
* Error thrown when computations become suspended.
* To perform any other action wait for the batch to complete or resume the evaluation.
* Relates to:
*
* @see [[batch]]
* @see [[suspendEvaluation]]
* @see [[resumeEvaluation]]
*/
class EvaluationSuspendedError extends Error {
constructor() {
super('Computations are suspended');
}
}
/**
* Error thrown when translation is missing in translation package.
*
* TODO
*/
class MissingTranslationError extends Error {
constructor(key) {
super(`Translation for ${key} is missing in the translation package you're using.`);
}
}
/**
* Error thrown when trying to override protected translation.
*
* @see [[registerLanguage]]
* @see [[registerFunction]]
* @see [[registerFunctionPlugin]]
*/
class ProtectedFunctionTranslationError extends Error {
constructor(key) {
super(`Cannot register translation for function with id: ${key}`);
}
}
/**
* Error thrown when trying to retrieve not registered language
*
* @see [[getLanguage]]
* @see [[unregisterLanguage]]
*/
class LanguageNotRegisteredError extends Error {
constructor() {
super('Language not registered.');
}
}
/**
* Error thrown when trying to register already registered language
*
* @see [[registerLanguage]]
*/
class LanguageAlreadyRegisteredError extends Error {
constructor() {
super('Language already registered.');
}
}
/**
* Error thrown when function plugin is invalid.
*
* @see [[registerFunction]]
* @see [[registerFunctionPlugin]]
* @see [[buildFromArray]]
* @see [[buildFromSheets]]
*/
class FunctionPluginValidationError extends Error {
static functionNotDeclaredInPlugin(functionId, pluginName) {
return new FunctionPluginValidationError(`Function with id ${functionId} not declared in plugin ${pluginName}`);
}
static functionMethodNotFound(functionName, pluginName) {
return new FunctionPluginValidationError(`Function method ${functionName} not found in plugin ${pluginName}`);
}
}
/**
* Error thrown when trying to register, override or remove function with reserved id.
*
* @see [[registerFunctionPlugin]]
* @see [[registerFunction]]
* @see [[unregisterFunction]]
*/
class ProtectedFunctionError extends Error {
static cannotRegisterFunctionWithId(functionId) {
return new ProtectedFunctionError(`Cannot register function with id ${functionId}`);
}
static cannotUnregisterFunctionWithId(functionId) {
return new ProtectedFunctionError(`Cannot unregister function with id ${functionId}`);
}
static cannotUnregisterProtectedPlugin() {
return new ProtectedFunctionError('Cannot unregister protected plugin');
}
}
/**
* Error thrown when selected source location has an array.
*/
class SourceLocationHasArrayError extends Error {
constructor() {
super('Cannot perform this operation, source location has an array inside.');
}
}
/**
* Error thrown when selected target location has an array.
*
* @see [[addRows]]
* @see [[addColumns]]
* @see [[moveCells]]
* @see [[moveRows]]
* @see [[moveColumns]]
* @see [[paste]]
*/
class TargetLocationHasArrayError extends Error {
constructor() {
super('Cannot perform this operation, target location has an array inside.');
}
}
/**
* Error thrown when named expression contains relative addresses.
*
* @see [[addNamedExpression]]
* @see [[changeNamedExpression]]
*/
class NoRelativeAddressesAllowedError extends Error {
constructor() {
super('Relative addresses not allowed in named expressions.');
}
}
/**
* Error thrown when alias to a function is already defined.
*
* @see [[registerFunctionPlugin]]
* @see [[registerFunction]]
*/
class AliasAlreadyExisting extends Error {
constructor(name, pluginName) {
super(`Alias id ${name} in plugin ${pluginName} already defined as a function or alias.`);
}
}
/***/ }),
/* 78 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ArrayMapping: () => (/* binding */ ArrayMapping)
/* harmony export */ });
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
class ArrayMapping {
constructor() {
this.arrayMapping = new Map();
}
getArray(range) {
const array = this.getArrayByCorner(range.start);
if (array === null || array === void 0 ? void 0 : array.getRange().sameAs(range)) {
return array;
}
return;
}
getArrayByCorner(address) {
return this.arrayMapping.get((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.addressKey)(address));
}
setArray(range, vertex) {
this.arrayMapping.set((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.addressKey)(range.start), vertex);
}
removeArray(range) {
if (typeof range === 'string') {
this.arrayMapping.delete(range);
} else {
this.arrayMapping.delete((0,_Cell__WEBPACK_IMPORTED_MODULE_0__.addressKey)(range.start));
}
}
count() {
return this.arrayMapping.size;
}
*arraysInRows(rowsSpan) {
for (const [mtxKey, mtx] of this.arrayMapping.entries()) {
if (mtx.spansThroughSheetRows(rowsSpan.sheet, rowsSpan.rowStart, rowsSpan.rowEnd)) {
yield [mtxKey, mtx];
}
}
}
*arraysInCols(col) {
for (const [mtxKey, mtx] of this.arrayMapping.entries()) {
if (mtx.spansThroughSheetColumn(col.sheet, col.columnStart, col.columnEnd)) {
yield [mtxKey, mtx];
}
}
}
isFormulaArrayInRow(sheet, row) {
for (const mtx of this.arrayMapping.values()) {
if (mtx.spansThroughSheetRows(sheet, row)) {
return true;
}
}
return false;
}
isFormulaArrayInAllRows(span) {
let result = true;
for (const row of span.rows()) {
if (!this.isFormulaArrayInRow(span.sheet, row)) {
result = false;
}
}
return result;
}
isFormulaArrayInColumn(sheet, column) {
for (const mtx of this.arrayMapping.values()) {
if (mtx.spansThroughSheetColumn(sheet, column)) {
return true;
}
}
return false;
}
isFormulaArrayInAllColumns(span) {
let result = true;
for (const col of span.columns()) {
if (!this.isFormulaArrayInColumn(span.sheet, col)) {
result = false;
}
}
return result;
}
isFormulaArrayInRange(range) {
for (const mtx of this.arrayMapping.values()) {
if (mtx.getRange().doesOverlap(range)) {
return true;
}
}
return false;
}
isFormulaArrayAtAddress(address) {
for (const mtx of this.arrayMapping.values()) {
if (mtx.getRange().addressInRange(address)) {
return true;
}
}
return false;
}
moveArrayVerticesAfterRowByRows(sheet, row, numberOfRows) {
this.updateArrayVerticesInSheet(sheet, (key, vertex) => {
const range = vertex.getRange();
return row <= range.start.row ? [range.shifted(0, numberOfRows), vertex] : undefined;
});
}
moveArrayVerticesAfterColumnByColumns(sheet, column, numberOfColumns) {
this.updateArrayVerticesInSheet(sheet, (key, vertex) => {
const range = vertex.getRange();
return column <= range.start.col ? [range.shifted(numberOfColumns, 0), vertex] : undefined;
});
}
updateArrayVerticesInSheet(sheet, fn) {
const updated = Array();
for (const [key, vertex] of this.arrayMapping.entries()) {
if (vertex.sheet !== sheet) {
continue;
}
const result = fn(key, vertex);
if (result !== undefined) {
this.removeArray(key);
updated.push(result);
}
}
updated.forEach(([range, array]) => {
this.setArray(range, array);
});
}
}
/***/ }),
/* 79 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ collectAddressesDependentToRange: () => (/* binding */ collectAddressesDependentToRange)
/* harmony export */ });
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7);
/* harmony import */ var _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(80);
/* harmony import */ var _RangeVertex__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(82);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
const collectAddressesDependentToRange = (functionRegistry, vertex, range, lazilyTransformingAstService, dependencyGraph) => {
if (vertex instanceof _RangeVertex__WEBPACK_IMPORTED_MODULE_2__.RangeVertex) {
const intersection = vertex.range.intersectionWith(range);
if (intersection !== undefined) {
return Array.from(intersection.addresses(dependencyGraph));
} else {
return [];
}
}
let formula;
let address;
if (vertex instanceof _FormulaCellVertex__WEBPACK_IMPORTED_MODULE_1__.FormulaVertex) {
formula = vertex.getFormula(lazilyTransformingAstService);
address = vertex.getAddress(lazilyTransformingAstService);
} else {
return [];
}
return (0,_parser__WEBPACK_IMPORTED_MODULE_0__.collectDependencies)(formula, functionRegistry).filter(d => d instanceof _parser__WEBPACK_IMPORTED_MODULE_0__.AddressDependency).map(d => d.dependency.toSimpleCellAddress(address)).filter(d => range.addressInRange(d));
};
/***/ }),
/* 80 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ArrayVertex: () => (/* binding */ ArrayVertex),
/* harmony export */ FormulaCellVertex: () => (/* binding */ FormulaCellVertex),
/* harmony export */ FormulaVertex: () => (/* binding */ FormulaVertex)
/* harmony export */ });
/* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _ArraySize__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _ArrayValue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(81);
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3);
/* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(61);
/* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(70);
/* harmony import */ var _Span__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(71);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
class FormulaVertex {
constructor(formula, cellAddress, version) {
this.formula = formula;
this.cellAddress = cellAddress;
this.version = version;
}
get width() {
return 1;
}
get height() {
return 1;
}
static fromAst(formula, address, size, version) {
if (size.isScalar()) {
return new FormulaCellVertex(formula, address, version);
} else {
return new ArrayVertex(formula, address, size, version);
}
}
/**
* Returns formula stored in this vertex
*/
getFormula(updatingService) {
this.ensureRecentData(updatingService);
return this.formula;
}
ensureRecentData(updatingService) {
if (this.version != updatingService.version()) {
const [newAst, newAddress, newVersion] = updatingService.applyTransformations(this.formula, this.cellAddress, this.version);
this.formula = newAst;
this.cellAddress = newAddress;
this.version = newVersion;
}
}
/**
* Returns address of the cell associated with vertex
*/
getAddress(updatingService) {
this.ensureRecentData(updatingService);
return this.cellAddress;
}
}
class ArrayVertex extends FormulaVertex {
constructor(formula, cellAddress, size, version = 0) {
super(formula, cellAddress, version);
if (size.isRef) {
this.array = new _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.ErroredArray(new _Cell__WEBPACK_IMPORTED_MODULE_3__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_3__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_4__.ErrorMessage.NoSpaceForArrayResult), _ArraySize__WEBPACK_IMPORTED_MODULE_1__.ArraySize.error());
} else {
this.array = new _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.NotComputedArray(size);
}
}
get width() {
return this.array.width();
}
get height() {
return this.array.height();
}
get sheet() {
return this.cellAddress.sheet;
}
get leftCorner() {
return this.cellAddress;
}
setCellValue(value) {
if (value instanceof _Cell__WEBPACK_IMPORTED_MODULE_3__.CellError) {
this.setErrorValue(value);
return value;
}
const array = _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.ArrayValue.fromInterpreterValue(value);
array.resize(this.array.size);
this.array = array;
return value;
}
getCellValue() {
if (this.array instanceof _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.NotComputedArray) {
throw Error('Array not computed yet.');
}
return this.array.simpleRangeValue();
}
valueOrUndef() {
if (this.array instanceof _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.NotComputedArray) {
return undefined;
}
return this.array.simpleRangeValue();
}
getArrayCellValue(address) {
const col = address.col - this.cellAddress.col;
const row = address.row - this.cellAddress.row;
try {
return this.array.get(col, row);
} catch (e) {
return new _Cell__WEBPACK_IMPORTED_MODULE_3__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_3__.ErrorType.REF);
}
}
getArrayCellRawValue(address) {
const val = this.getArrayCellValue(address);
if (val instanceof _Cell__WEBPACK_IMPORTED_MODULE_3__.CellError || val === _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.EmptyValue) {
return undefined;
} else {
return (0,_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.getRawValue)(val);
}
}
setArrayCellValue(address, value) {
const col = address.col - this.cellAddress.col;
const row = address.row - this.cellAddress.row;
if (this.array instanceof _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.ArrayValue) {
this.array.set(col, row, value);
}
}
setNoSpace() {
this.array = new _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.ErroredArray(new _Cell__WEBPACK_IMPORTED_MODULE_3__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_3__.ErrorType.SPILL, _error_message__WEBPACK_IMPORTED_MODULE_4__.ErrorMessage.NoSpaceForArrayResult), _ArraySize__WEBPACK_IMPORTED_MODULE_1__.ArraySize.error());
return this.getCellValue();
}
getRange() {
return _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFrom(this.cellAddress, this.width, this.height);
}
getRangeOrUndef() {
return _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.spanFromOrUndef(this.cellAddress, this.width, this.height);
}
setAddress(address) {
this.cellAddress = address;
}
setFormula(newFormula) {
this.formula = newFormula;
}
spansThroughSheetRows(sheet, startRow, endRow = startRow) {
return this.cellAddress.sheet === sheet && this.cellAddress.row <= endRow && startRow < this.cellAddress.row + this.height;
}
spansThroughSheetColumn(sheet, col, columnEnd = col) {
return this.cellAddress.sheet === sheet && this.cellAddress.col <= columnEnd && col < this.cellAddress.col + this.width;
}
isComputed() {
return !(this.array instanceof _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.NotComputedArray);
}
columnsFromArray() {
return _Span__WEBPACK_IMPORTED_MODULE_6__.ColumnsSpan.fromNumberOfColumns(this.cellAddress.sheet, this.cellAddress.col, this.width);
}
rowsFromArray() {
return _Span__WEBPACK_IMPORTED_MODULE_6__.RowsSpan.fromNumberOfRows(this.cellAddress.sheet, this.cellAddress.row, this.height);
}
/**
* No-op as array vertices are transformed eagerly.
*/
ensureRecentData(_updatingService) {}
isLeftCorner(address) {
return (0,_Cell__WEBPACK_IMPORTED_MODULE_3__.equalSimpleCellAddress)(this.cellAddress, address);
}
setErrorValue(error) {
this.array = new _ArrayValue__WEBPACK_IMPORTED_MODULE_2__.ErroredArray(error, this.array.size);
}
}
/**
* Represents vertex which keeps formula
*/
class FormulaCellVertex extends FormulaVertex {
constructor( /** Formula in AST format */
formula, /** Address which this vertex represents */
address, version) {
super(formula, address, version);
}
valueOrUndef() {
return this.cachedCellValue;
}
/**
* Sets computed cell value stored in this vertex
*/
setCellValue(cellValue) {
this.cachedCellValue = cellValue;
return this.cachedCellValue;
}
/**
* Returns cell value stored in vertex
*/
getCellValue() {
if (this.cachedCellValue !== undefined) {
return this.cachedCellValue;
} else {
throw Error('Value of the formula cell is not computed.');
}
}
isComputed() {
return this.cachedCellValue !== undefined;
}
}
/***/ }),
/* 81 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ArrayValue: () => (/* binding */ ArrayValue),
/* harmony export */ ErroredArray: () => (/* binding */ ErroredArray),
/* harmony export */ NotComputedArray: () => (/* binding */ NotComputedArray)
/* harmony export */ });
/* harmony import */ var _ArraySize__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(70);
/* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(69);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
class NotComputedArray {
constructor(size) {
this.size = size;
}
width() {
return this.size.width;
}
height() {
return this.size.height;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
get(col, row) {
throw Error('Array not computed yet.');
}
simpleRangeValue() {
throw Error('Array not computed yet.');
}
}
class ArrayValue {
constructor(array) {
this.size = new _ArraySize__WEBPACK_IMPORTED_MODULE_0__.ArraySize(array.length > 0 ? array[0].length : 0, array.length);
this.array = array;
}
static fromInterpreterValue(value) {
if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_2__.SimpleRangeValue) {
return new ArrayValue(value.data);
} else {
return new ArrayValue([[value]]);
}
}
simpleRangeValue() {
return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_2__.SimpleRangeValue.onlyValues(this.array);
}
addRows(aboveRow, numberOfRows) {
this.array.splice(aboveRow, 0, ...this.nullArrays(numberOfRows, this.width()));
this.size.height += numberOfRows;
}
addColumns(aboveColumn, numberOfColumns) {
for (let i = 0; i < this.height(); i++) {
this.array[i].splice(aboveColumn, 0, ...new Array(numberOfColumns).fill(_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_1__.EmptyValue));
}
this.size.width += numberOfColumns;
}
removeRows(startRow, endRow) {
if (this.outOfBound(0, startRow) || this.outOfBound(0, endRow)) {
throw Error('Array index out of bound');
}
const numberOfRows = endRow - startRow + 1;
this.array.splice(startRow, numberOfRows);
this.size.height -= numberOfRows;
}
removeColumns(leftmostColumn, rightmostColumn) {
if (this.outOfBound(leftmostColumn, 0) || this.outOfBound(rightmostColumn, 0)) {
throw Error('Array index out of bound');
}
const numberOfColumns = rightmostColumn - leftmostColumn + 1;
for (const row of this.array) {
row.splice(leftmostColumn, numberOfColumns);
}
this.size.width -= numberOfColumns;
}
nullArrays(count, size) {
const result = [];
for (let i = 0; i < count; ++i) {
result.push(new Array(size).fill(_interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_1__.EmptyValue));
}
return result;
}
get(col, row) {
if (this.outOfBound(col, row)) {
throw Error('Array index out of bound');
}
return this.array[row][col];
}
set(col, row, value) {
if (this.outOfBound(col, row)) {
throw Error('Array index out of bound');
}
this.array[row][col] = value;
}
width() {
return this.size.width;
}
height() {
return this.size.height;
}
raw() {
return this.array;
}
resize(newSize) {
if (this.height() < newSize.height && isFinite(newSize.height)) {
this.addRows(this.height(), newSize.height - this.height());
}
if (this.height() > newSize.height) {
throw Error('Resizing to smaller array');
}
if (this.width() < newSize.width && isFinite(newSize.width)) {
this.addColumns(this.width(), newSize.width - this.width());
}
if (this.width() > newSize.width) {
throw Error('Resizing to smaller array');
}
}
outOfBound(col, row) {
return col < 0 || row < 0 || row > this.size.height - 1 || col > this.size.width - 1;
}
}
class ErroredArray {
constructor(error, size) {
this.error = error;
this.size = size;
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
get(col, row) {
return this.error;
}
width() {
return this.size.width;
}
height() {
return this.size.height;
}
simpleRangeValue() {
return this.error;
}
}
/***/ }),
/* 82 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ RangeVertex: () => (/* binding */ RangeVertex)
/* harmony export */ });
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* Represents vertex bound to range
*/
class RangeVertex {
constructor(range) {
this.range = range;
this.functionCache = new Map();
this.criterionFunctionCache = new Map();
this.dependentCacheRanges = new Set();
this.bruteForce = false;
}
get start() {
return this.range.start;
}
get end() {
return this.range.end;
}
get sheet() {
return this.range.start.sheet;
}
/**
* Returns cached value stored for given function
*
* @param functionName - name of the function
*/
getFunctionValue(functionName) {
return this.functionCache.get(functionName);
}
/**
* Stores cached value for given function
*
* @param functionName - name of the function
* @param value - cached value
*/
setFunctionValue(functionName, value) {
this.functionCache.set(functionName, value);
}
/**
* Returns cached value for given cache key and criterion text representation
*
* @param cacheKey - key to retrieve from the cache
* @param criterionString - criterion text (ex. '<=5')
*/
getCriterionFunctionValue(cacheKey, criterionString) {
var _a;
return (_a = this.getCriterionFunctionValues(cacheKey).get(criterionString)) === null || _a === void 0 ? void 0 : _a[0];
}
/**
* Returns all cached values stored for given criterion function
*
* @param cacheKey - key to retrieve from the cache
*/
getCriterionFunctionValues(cacheKey) {
var _a;
return (_a = this.criterionFunctionCache.get(cacheKey)) !== null && _a !== void 0 ? _a : new Map();
}
/**
* Stores all values for given criterion function
*
* @param cacheKey - key to store in the cache
* @param values - map with values
*/
setCriterionFunctionValues(cacheKey, values) {
this.criterionFunctionCache.set(cacheKey, values);
}
addDependentCacheRange(dependentRange) {
if (dependentRange !== this) {
this.dependentCacheRanges.add(dependentRange);
}
}
/**
* Clears function cache
*/
clearCache() {
this.functionCache.clear();
this.criterionFunctionCache.clear();
this.dependentCacheRanges.forEach(range => range.criterionFunctionCache.clear());
this.dependentCacheRanges.clear();
}
/**
* Returns start of the range (it's top-left corner)
*/
getStart() {
return this.start;
}
/**
* Returns end of the range (it's bottom-right corner)
*/
getEnd() {
return this.end;
}
}
/***/ }),
/* 83 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ Graph: () => (/* binding */ Graph)
/* harmony export */ });
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
var NodeVisitStatus;
(function (NodeVisitStatus) {
NodeVisitStatus[NodeVisitStatus["ON_STACK"] = 0] = "ON_STACK";
NodeVisitStatus[NodeVisitStatus["PROCESSED"] = 1] = "PROCESSED";
NodeVisitStatus[NodeVisitStatus["POPPED"] = 2] = "POPPED";
})(NodeVisitStatus || (NodeVisitStatus = {}));
/**
* Provides graph directed structure
*
* Invariants:
* - this.edges(node) exists if and only if node is in the graph
* - this.specialNodes* are always subset of this.nodes
* - this.edges(node) is subset of this.nodes (i.e. it does not contain nodes not present in graph) -- this invariant DOES NOT HOLD right now
*/
class Graph {
constructor(dependencyQuery) {
this.dependencyQuery = dependencyQuery;
/** Set with nodes in graph. */
this.nodes = new Set();
this.specialNodes = new Set();
this.specialNodesStructuralChanges = new Set();
this.specialNodesRecentlyChanged = new Set();
this.infiniteRanges = new Set();
/** Nodes adjacency mapping. */
this.edges = new Map();
}
/**
* Adds node to a graph
*
* @param node - a node to be added
*/
addNode(node) {
this.nodes.add(node);
if (!this.edges.has(node)) {
this.edges.set(node, new Set());
}
}
/**
* Adds edge between nodes.
*
* The nodes had to be added to the graph before, or the error will be raised
*
* @param fromNode - node from which edge is outcoming
* @param toNode - node to which edge is incoming
*/
addEdge(fromNode, toNode) {
if (!this.nodes.has(fromNode)) {
throw new Error(`Unknown node ${fromNode}`);
}
if (!this.nodes.has(toNode)) {
throw new Error(`Unknown node ${toNode}`);
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.edges.get(fromNode).add(toNode);
}
removeEdge(fromNode, toNode) {
if (this.existsEdge(fromNode, toNode)) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.edges.get(fromNode).delete(toNode);
} else {
throw new Error('Edge does not exist');
}
}
softRemoveEdge(fromNode, toNode) {
var _a;
(_a = this.edges.get(fromNode)) === null || _a === void 0 ? void 0 : _a.delete(toNode);
}
removeIncomingEdges(toNode) {
this.edges.forEach(nodeEdges => {
nodeEdges.delete(toNode);
});
}
/**
* Returns nodes adjacent to given node
*
* @param node - node to which adjacent nodes we want to retrieve
*/
adjacentNodes(node) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this.edges.get(node);
}
adjacentNodesCount(node) {
return this.adjacentNodes(node).size;
}
/**
* Checks whether a node is present in graph
*
* @param node - node to check
*/
hasNode(node) {
return this.nodes.has(node);
}
/**
* Returns number of nodes in graph
*/
nodesCount() {
return this.nodes.size;
}
/**
* Returns number of edges in graph
*/
edgesCount() {
let result = 0;
this.edges.forEach(edgesForNode => result += edgesForNode.size);
return result;
}
removeNode(node) {
for (const adjacentNode of this.adjacentNodes(node).values()) {
this.markNodeAsSpecialRecentlyChanged(adjacentNode);
}
this.edges.delete(node);
this.nodes.delete(node);
this.specialNodes.delete(node);
this.specialNodesRecentlyChanged.delete(node);
this.specialNodesStructuralChanges.delete(node);
this.infiniteRanges.delete(node);
return this.removeDependencies(node);
}
markNodeAsSpecial(node) {
this.specialNodes.add(node);
}
markNodeAsSpecialRecentlyChanged(node) {
if (this.nodes.has(node)) {
this.specialNodesRecentlyChanged.add(node);
}
}
markNodeAsChangingWithStructure(node) {
this.specialNodesStructuralChanges.add(node);
}
clearSpecialNodesRecentlyChanged() {
this.specialNodesRecentlyChanged.clear();
}
markNodeAsInfiniteRange(node) {
this.infiniteRanges.add(node);
}
/**
* Checks whether exists edge between nodes
*
* @param fromNode - node from which edge is outcoming
* @param toNode - node to which edge is incoming
*/
existsEdge(fromNode, toNode) {
var _a, _b;
return (_b = (_a = this.edges.get(fromNode)) === null || _a === void 0 ? void 0 : _a.has(toNode)) !== null && _b !== void 0 ? _b : false;
}
/*
* return a topological sort order, but separates vertices that exist in some cycle
*/
topSortWithScc() {
return this.getTopSortedWithSccSubgraphFrom(Array.from(this.nodes), () => true, () => {});
}
/**
*
* an iterative implementation of Tarjan's algorithm for finding strongly connected compontents
* returns vertices in order of topological sort, but vertices that are on cycles are kept separate
*
* @param modifiedNodes - seed for computation. During engine init run, all of the vertices of grap. In recomputation run, changed vertices.
* @param operatingFunction - recomputes value of a node, and returns whether a change occured
* @param onCycle - action to be performed when node is on cycle
*/
getTopSortedWithSccSubgraphFrom(modifiedNodes, operatingFunction, onCycle) {
const entranceTime = new Map();
const low = new Map();
const parent = new Map();
const inSCC = new Set();
// node status life cycle:
// undefined -> ON_STACK -> PROCESSED -> POPPED
const nodeStatus = new Map();
const order = [];
let time = 0;
const sccNonSingletons = new Set();
modifiedNodes.reverse();
modifiedNodes.forEach(v => {
if (nodeStatus.get(v) !== undefined) {
return;
}
const DFSstack = [v];
const SCCstack = [];
nodeStatus.set(v, NodeVisitStatus.ON_STACK);
while (DFSstack.length > 0) {
const u = DFSstack[DFSstack.length - 1];
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
switch (nodeStatus.get(u)) {
case NodeVisitStatus.ON_STACK:
{
entranceTime.set(u, time);
low.set(u, time);
SCCstack.push(u);
time++;
this.adjacentNodes(u).forEach(t => {
if (entranceTime.get(t) === undefined) {
DFSstack.push(t);
parent.set(t, u);
nodeStatus.set(t, NodeVisitStatus.ON_STACK);
}
});
nodeStatus.set(u, NodeVisitStatus.PROCESSED);
break;
}
case NodeVisitStatus.PROCESSED:
{
// leaving this DFS subtree
let uLow;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
uLow = entranceTime.get(u);
this.adjacentNodes(u).forEach(t => {
if (!inSCC.has(t)) {
if (parent.get(t) === u) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
uLow = Math.min(uLow, low.get(t));
} else {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
uLow = Math.min(uLow, entranceTime.get(t));
}
}
});
low.set(u, uLow);
if (uLow === entranceTime.get(u)) {
const currentSCC = [];
do {
currentSCC.push(SCCstack[SCCstack.length - 1]);
SCCstack.pop();
} while (currentSCC[currentSCC.length - 1] !== u);
currentSCC.forEach(t => {
inSCC.add(t);
});
order.push(...currentSCC);
if (currentSCC.length > 1) {
currentSCC.forEach(t => {
sccNonSingletons.add(t);
});
}
}
DFSstack.pop();
nodeStatus.set(u, NodeVisitStatus.POPPED);
break;
}
case NodeVisitStatus.POPPED:
{
// it's a 'shadow' copy, we already processed this vertex and can ignore it
DFSstack.pop();
break;
}
}
}
});
const shouldBeUpdatedMapping = new Set(modifiedNodes);
const sorted = [];
const cycled = [];
order.reverse();
order.forEach(t => {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
if (sccNonSingletons.has(t) || this.adjacentNodes(t).has(t)) {
cycled.push(t);
onCycle(t);
this.adjacentNodes(t).forEach(s => shouldBeUpdatedMapping.add(s));
} else {
sorted.push(t);
if (shouldBeUpdatedMapping.has(t) && operatingFunction(t)) {
this.adjacentNodes(t).forEach(s => shouldBeUpdatedMapping.add(s));
}
}
});
return {
sorted,
cycled
};
}
getDependencies(vertex) {
const result = [];
this.edges.forEach((adjacentNodes, sourceNode) => {
if (adjacentNodes.has(vertex)) {
result.push(sourceNode);
}
});
return result;
}
removeDependencies(node) {
const dependencies = this.dependencyQuery(node);
for (const [_, dependency] of dependencies) {
this.softRemoveEdge(dependency, node);
}
return dependencies;
}
}
/***/ }),
/* 84 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ RangeMapping: () => (/* binding */ RangeMapping)
/* harmony export */ });
/* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* Mapping from address ranges to range vertices
*/
class RangeMapping {
constructor() {
/** Map in which actual data is stored. */
this.rangeMapping = new Map();
}
getMappingSize(sheet) {
var _a, _b;
return (_b = (_a = this.rangeMapping.get(sheet)) === null || _a === void 0 ? void 0 : _a.size) !== null && _b !== void 0 ? _b : 0;
}
/**
* Saves range vertex
*
* @param vertex - vertex to save
*/
setRange(vertex) {
let sheetMap = this.rangeMapping.get(vertex.getStart().sheet);
if (sheetMap === undefined) {
sheetMap = new Map();
this.rangeMapping.set(vertex.getStart().sheet, sheetMap);
}
const key = keyFromAddresses(vertex.getStart(), vertex.getEnd());
sheetMap.set(key, vertex);
}
removeRange(vertex) {
const sheet = vertex.getStart().sheet;
const sheetMap = this.rangeMapping.get(sheet);
if (sheetMap === undefined) {
return;
}
const key = keyFromAddresses(vertex.getStart(), vertex.getEnd());
sheetMap.delete(key);
if (sheetMap.size === 0) {
this.rangeMapping.delete(sheet);
}
}
/**
* Returns associated vertex for given range
*
* @param start - top-left corner of the range
* @param end - bottom-right corner of the range
*/
getRange(start, end) {
const sheetMap = this.rangeMapping.get(start.sheet);
const key = keyFromAddresses(start, end);
return sheetMap === null || sheetMap === void 0 ? void 0 : sheetMap.get(key);
}
fetchRange(start, end) {
const maybeRange = this.getRange(start, end);
if (!maybeRange) {
throw Error('Range does not exist');
}
return maybeRange;
}
truncateRanges(span, coordinate) {
const verticesToRemove = Array();
const updated = Array();
const verticesWithChangedSize = Array();
const sheet = span.sheet;
for (const [key, vertex] of this.entriesFromSheet(span.sheet)) {
const range = vertex.range;
if (span.start <= coordinate(vertex.range.end)) {
range.removeSpan(span);
if (range.shouldBeRemoved()) {
this.removeByKey(sheet, key);
verticesToRemove.push(vertex);
} else {
updated.push([key, vertex]);
}
verticesWithChangedSize.push(vertex);
}
}
const verticesToMerge = [];
updated.sort((left, right) => compareBy(left[1], right[1], coordinate));
for (const [oldKey, vertex] of updated) {
const newKey = keyFromRange(vertex.range);
if (newKey === oldKey) {
continue;
}
const existingVertex = this.getByKey(sheet, newKey);
this.removeByKey(sheet, oldKey);
if (existingVertex !== undefined && vertex != existingVertex) {
verticesToMerge.push([existingVertex, vertex]);
} else {
this.setRange(vertex);
}
}
return {
verticesToRemove,
verticesToMerge,
verticesWithChangedSize
};
}
moveAllRangesInSheetAfterRowByRows(sheet, row, numberOfRows) {
return this.updateVerticesFromSheet(sheet, (key, vertex) => {
if (row <= vertex.start.row) {
vertex.range.shiftByRows(numberOfRows);
return {
changedSize: false,
vertex: vertex
};
} else if (row > vertex.start.row && row <= vertex.end.row) {
vertex.range.expandByRows(numberOfRows);
return {
changedSize: true,
vertex: vertex
};
} else {
return undefined;
}
});
}
moveAllRangesInSheetAfterColumnByColumns(sheet, column, numberOfColumns) {
return this.updateVerticesFromSheet(sheet, (key, vertex) => {
if (column <= vertex.start.col) {
vertex.range.shiftByColumns(numberOfColumns);
return {
changedSize: false,
vertex: vertex
};
} else if (column > vertex.start.col && column <= vertex.end.col) {
vertex.range.expandByColumns(numberOfColumns);
return {
changedSize: true,
vertex: vertex
};
} else {
return undefined;
}
});
}
moveRangesInsideSourceRange(sourceRange, toRight, toBottom, toSheet) {
this.updateVerticesFromSheet(sourceRange.sheet, (key, vertex) => {
if (sourceRange.containsRange(vertex.range)) {
vertex.range.shiftByColumns(toRight);
vertex.range.shiftByRows(toBottom);
vertex.range.moveToSheet(toSheet);
return {
changedSize: false,
vertex: vertex
};
} else {
return undefined;
}
});
}
removeRangesInSheet(sheet) {
if (this.rangeMapping.has(sheet)) {
const ranges = this.rangeMapping.get(sheet).values();
this.rangeMapping.delete(sheet);
return ranges;
}
return [][Symbol.iterator]();
}
*rangesInSheet(sheet) {
const sheetMap = this.rangeMapping.get(sheet);
if (!sheetMap) {
return;
}
yield* sheetMap.values();
}
*rangeVerticesContainedInRange(sourceRange) {
for (const rangeVertex of this.rangesInSheet(sourceRange.sheet)) {
if (sourceRange.containsRange(rangeVertex.range)) {
yield rangeVertex;
}
}
}
/**
* Finds smaller range does have own vertex.
*
* @param range
*/
findSmallerRange(range) {
if (range.height() > 1 && Number.isFinite(range.height())) {
const valuesRangeEndRowLess = (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(range.end.sheet, range.end.col, range.end.row - 1);
const rowLessVertex = this.getRange(range.start, valuesRangeEndRowLess);
if (rowLessVertex !== undefined) {
const restRange = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.fromSimpleCellAddresses((0,_Cell__WEBPACK_IMPORTED_MODULE_1__.simpleCellAddress)(range.start.sheet, range.start.col, range.end.row), range.end);
return {
smallerRangeVertex: rowLessVertex,
restRange
};
}
}
return {
restRange: range
};
}
*entriesFromSheet(sheet) {
const sheetMap = this.rangeMapping.get(sheet);
if (!sheetMap) {
return;
}
yield* sheetMap.entries();
}
removeByKey(sheet, key) {
this.rangeMapping.get(sheet).delete(key);
}
getByKey(sheet, key) {
var _a;
return (_a = this.rangeMapping.get(sheet)) === null || _a === void 0 ? void 0 : _a.get(key);
}
updateVerticesFromSheet(sheet, fn) {
const updated = Array();
for (const [key, vertex] of this.entriesFromSheet(sheet)) {
const result = fn(key, vertex);
if (result !== undefined) {
this.removeByKey(sheet, key);
updated.push(result);
}
}
updated.forEach(entry => {
this.setRange(entry.vertex);
});
return {
verticesWithChangedSize: updated.filter(entry => entry.changedSize).map(entry => entry.vertex)
};
}
}
function keyFromAddresses(start, end) {
return `${start.col},${start.row},${end.col},${end.row}`;
}
function keyFromRange(range) {
return keyFromAddresses(range.start, range.end);
}
const compareBy = (left, right, coordinate) => {
const leftStart = coordinate(left.range.start);
const rightStart = coordinate(left.range.start);
if (leftStart === rightStart) {
const leftEnd = coordinate(left.range.end);
const rightEnd = coordinate(right.range.end);
return leftEnd - rightEnd;
} else {
return leftStart - rightStart;
}
};
/***/ }),
/* 85 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ SheetMapping: () => (/* binding */ SheetMapping)
/* harmony export */ });
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(77);
/* harmony import */ var _i18n__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(86);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
function canonicalize(sheetDisplayName) {
return sheetDisplayName.toLowerCase();
}
class Sheet {
constructor(id, displayName) {
this.id = id;
this.displayName = displayName;
}
get canonicalName() {
return canonicalize(this.displayName);
}
}
class SheetMapping {
constructor(languages) {
this.languages = languages;
this.mappingFromCanonicalName = new Map();
this.mappingFromId = new Map();
this.lastSheetId = -1;
this.fetch = sheetName => {
const sheet = this.mappingFromCanonicalName.get(canonicalize(sheetName));
if (sheet === undefined) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithNameError(sheetName);
}
return sheet.id;
};
this.get = sheetName => {
var _a;
return (_a = this.mappingFromCanonicalName.get(canonicalize(sheetName))) === null || _a === void 0 ? void 0 : _a.id;
};
this.fetchDisplayName = sheetId => {
return this.fetchSheetById(sheetId).displayName;
};
this.sheetNamePrefix = languages.getUITranslation(_i18n__WEBPACK_IMPORTED_MODULE_1__.UIElement.NEW_SHEET_PREFIX);
}
addSheet(newSheetDisplayName = `${this.sheetNamePrefix}${this.lastSheetId + 2}`) {
const newSheetCanonicalName = canonicalize(newSheetDisplayName);
if (this.mappingFromCanonicalName.has(newSheetCanonicalName)) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__.SheetNameAlreadyTakenError(newSheetDisplayName);
}
this.lastSheetId++;
const sheet = new Sheet(this.lastSheetId, newSheetDisplayName);
this.store(sheet);
return sheet.id;
}
removeSheet(sheetId) {
const sheet = this.fetchSheetById(sheetId);
if (sheetId == this.lastSheetId) {
--this.lastSheetId;
}
this.mappingFromCanonicalName.delete(sheet.canonicalName);
this.mappingFromId.delete(sheet.id);
}
getDisplayName(sheetId) {
var _a;
return (_a = this.mappingFromId.get(sheetId)) === null || _a === void 0 ? void 0 : _a.displayName;
}
*displayNames() {
for (const sheet of this.mappingFromCanonicalName.values()) {
yield sheet.displayName;
}
}
numberOfSheets() {
return this.mappingFromCanonicalName.size;
}
hasSheetWithId(sheetId) {
return this.mappingFromId.has(sheetId);
}
hasSheetWithName(sheetName) {
return this.mappingFromCanonicalName.has(canonicalize(sheetName));
}
renameSheet(sheetId, newDisplayName) {
const sheet = this.fetchSheetById(sheetId);
const currentDisplayName = sheet.displayName;
if (currentDisplayName === newDisplayName) {
return undefined;
}
const sheetWithThisCanonicalName = this.mappingFromCanonicalName.get(canonicalize(newDisplayName));
if (sheetWithThisCanonicalName !== undefined && sheetWithThisCanonicalName.id !== sheet.id) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__.SheetNameAlreadyTakenError(newDisplayName);
}
const currentCanonicalName = sheet.canonicalName;
this.mappingFromCanonicalName.delete(currentCanonicalName);
sheet.displayName = newDisplayName;
this.store(sheet);
return currentDisplayName;
}
sheetNames() {
return Array.from(this.mappingFromId.values()).map(s => s.displayName);
}
store(sheet) {
this.mappingFromId.set(sheet.id, sheet);
this.mappingFromCanonicalName.set(sheet.canonicalName, sheet);
}
fetchSheetById(sheetId) {
const sheet = this.mappingFromId.get(sheetId);
if (sheet === undefined) {
throw new _errors__WEBPACK_IMPORTED_MODULE_0__.NoSheetWithIdError(sheetId);
}
return sheet;
}
}
/***/ }),
/* 86 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ TranslationPackage: () => (/* reexport safe */ _TranslationPackage__WEBPACK_IMPORTED_MODULE_0__.TranslationPackage),
/* harmony export */ UIElement: () => (/* binding */ UIElement),
/* harmony export */ buildTranslationPackage: () => (/* reexport safe */ _TranslationPackage__WEBPACK_IMPORTED_MODULE_0__.buildTranslationPackage)
/* harmony export */ });
/* harmony import */ var _TranslationPackage__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(87);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
var UIElement;
(function (UIElement) {
UIElement["NEW_SHEET_PREFIX"] = "NEW_SHEET_PREFIX";
})(UIElement || (UIElement = {}));
/***/ }),
/* 87 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ TranslationPackage: () => (/* binding */ TranslationPackage),
/* harmony export */ buildTranslationPackage: () => (/* binding */ buildTranslationPackage)
/* harmony export */ });
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/* harmony import */ var _errors__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(77);
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(86);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
class TranslationPackage {
constructor(functions, errors, ui) {
this.functions = functions;
this.errors = errors;
this.ui = ui;
this._protectedTranslations = {
'VERSION': 'VERSION'
};
this.checkUI();
this.checkErrors();
this.checkFunctionTranslations(this.functions);
Object.assign(this.functions, this._protectedTranslations);
}
extendFunctions(additionalFunctionTranslations) {
this.checkFunctionTranslations(additionalFunctionTranslations);
Object.assign(this.functions, additionalFunctionTranslations);
}
buildFunctionMapping() {
return Object.keys(this.functions).reduce((ret, key) => {
ret[this.functions[key]] = key;
return ret;
}, {});
}
buildErrorMapping() {
return Object.keys(this.errors).reduce((ret, key) => {
ret[this.errors[key]] = key;
return ret;
}, {});
}
isFunctionTranslated(key) {
return this.functions[key] !== undefined;
}
getFunctionTranslations(functionIds) {
const translations = [];
for (const functionId of functionIds) {
if (this.isFunctionTranslated(functionId)) {
translations.push(this.functions[functionId]);
}
}
return translations;
}
getFunctionTranslation(key) {
const val = this.functions[key];
if (val === undefined) {
throw new _errors__WEBPACK_IMPORTED_MODULE_1__.MissingTranslationError(`functions.${key}`);
} else {
return val;
}
}
getMaybeFunctionTranslation(key) {
return this.functions[key];
}
getErrorTranslation(key) {
if (key === _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.LIC) {
return `#${_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.LIC}!`;
}
const val = this.errors[key];
if (val === undefined) {
throw new _errors__WEBPACK_IMPORTED_MODULE_1__.MissingTranslationError(`errors.${key}`);
} else {
return val;
}
}
getUITranslation(key) {
const val = this.ui[key];
if (val === undefined) {
throw new _errors__WEBPACK_IMPORTED_MODULE_1__.MissingTranslationError(`ui.${key}`);
} else {
return val;
}
}
checkUI() {
for (const key of Object.values(_index__WEBPACK_IMPORTED_MODULE_2__.UIElement)) {
if (!(key in this.ui)) {
throw new _errors__WEBPACK_IMPORTED_MODULE_1__.MissingTranslationError(`ui.${key}`);
}
}
}
checkErrors() {
for (const key of Object.values(_Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType)) {
if (!(key in this.errors) && key !== _Cell__WEBPACK_IMPORTED_MODULE_0__.ErrorType.LIC) {
throw new _errors__WEBPACK_IMPORTED_MODULE_1__.MissingTranslationError(`errors.${key}`);
}
}
}
checkFunctionTranslations(functions) {
const functionNames = new Set(Object.getOwnPropertyNames(functions));
for (const protectedTranslation of Object.getOwnPropertyNames(this._protectedTranslations)) {
if (functionNames.has(protectedTranslation)) {
throw new _errors__WEBPACK_IMPORTED_MODULE_1__.ProtectedFunctionTranslationError(protectedTranslation);
}
}
}
}
function buildTranslationPackage(rawTranslationPackage) {
return new TranslationPackage(Object.assign({}, rawTranslationPackage.functions), Object.assign({}, rawTranslationPackage.errors), Object.assign({}, rawTranslationPackage.ui));
}
/***/ }),
/* 88 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ EmptyCellVertex: () => (/* binding */ EmptyCellVertex)
/* harmony export */ });
/* harmony import */ var _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(70);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* Represents singleton vertex bound to all empty cells
*/
class EmptyCellVertex {
constructor() {}
/**
* Retrieves cell value bound to that singleton
*/
getCellValue() {
return _interpreter_InterpreterValue__WEBPACK_IMPORTED_MODULE_0__.EmptyValue;
}
}
/***/ }),
/* 89 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ValueCellVertex: () => (/* binding */ ValueCellVertex)
/* harmony export */ });
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* Represents vertex which keeps static cell value
*/
class ValueCellVertex {
/** Static cell value. */
constructor(parsedValue, rawValue) {
this.parsedValue = parsedValue;
this.rawValue = rawValue;
}
getValues() {
return {
parsedValue: this.parsedValue,
rawValue: this.rawValue
};
}
setValues(values) {
this.parsedValue = values.parsedValue;
this.rawValue = values.rawValue;
}
/**
* Returns cell value stored in vertex
*/
getCellValue() {
return this.parsedValue;
}
setCellValue(_cellValue) {
throw Error('SetCellValue is deprecated for ValueCellVertex');
}
}
/***/ }),
/* 90 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ParsingErrorVertex: () => (/* binding */ ParsingErrorVertex)
/* harmony export */ });
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
class ParsingErrorVertex {
constructor(errors, rawInput) {
this.errors = errors;
this.rawInput = rawInput;
}
getCellValue() {
return _Cell__WEBPACK_IMPORTED_MODULE_0__.CellError.parsingError();
}
getFormula() {
return this.rawInput;
}
}
/***/ }),
/* 91 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ SparseStrategy: () => (/* binding */ SparseStrategy)
/* harmony export */ });
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* Mapping from cell addresses to vertices
*
* Uses Map to store addresses, having minimal memory usage for sparse sheets but not necessarily constant set/lookup.
*/
class SparseStrategy {
constructor(width, height) {
this.width = width;
this.height = height;
/**
* Map of Maps in which actual data is stored.
*
* Key of map in first level is column number.
* Key of map in second level is row number.
*/
this.mapping = new Map();
}
/** @inheritDoc */
getCell(address) {
var _a;
return (_a = this.mapping.get(address.col)) === null || _a === void 0 ? void 0 : _a.get(address.row);
}
/** @inheritDoc */
setCell(address, newVertex) {
this.width = Math.max(this.width, address.col + 1);
this.height = Math.max(this.height, address.row + 1);
let colMapping = this.mapping.get(address.col);
if (!colMapping) {
colMapping = new Map();
this.mapping.set(address.col, colMapping);
}
colMapping.set(address.row, newVertex);
}
/** @inheritDoc */
has(address) {
var _a;
return !!((_a = this.mapping.get(address.col)) === null || _a === void 0 ? void 0 : _a.get(address.row));
}
/** @inheritDoc */
getHeight() {
return this.height;
}
/** @inheritDoc */
getWidth() {
return this.width;
}
removeCell(address) {
var _a;
(_a = this.mapping.get(address.col)) === null || _a === void 0 ? void 0 : _a.delete(address.row);
}
addRows(row, numberOfRows) {
this.mapping.forEach(rowMapping => {
const tmpMapping = new Map();
rowMapping.forEach((vertex, rowNumber) => {
if (rowNumber >= row) {
tmpMapping.set(rowNumber + numberOfRows, vertex);
rowMapping.delete(rowNumber);
}
});
tmpMapping.forEach((vertex, rowNumber) => {
rowMapping.set(rowNumber, vertex);
});
});
this.height += numberOfRows;
}
addColumns(column, numberOfColumns) {
const tmpMapping = new Map();
this.mapping.forEach((rowMapping, colNumber) => {
if (colNumber >= column) {
tmpMapping.set(colNumber + numberOfColumns, rowMapping);
this.mapping.delete(colNumber);
}
});
tmpMapping.forEach((rowMapping, colNumber) => {
this.mapping.set(colNumber, rowMapping);
});
this.width += numberOfColumns;
}
removeRows(removedRows) {
this.mapping.forEach(rowMapping => {
const tmpMapping = new Map();
rowMapping.forEach((vertex, rowNumber) => {
if (rowNumber >= removedRows.rowStart) {
rowMapping.delete(rowNumber);
if (rowNumber > removedRows.rowEnd) {
tmpMapping.set(rowNumber - removedRows.numberOfRows, vertex);
}
}
});
tmpMapping.forEach((vertex, rowNumber) => {
rowMapping.set(rowNumber, vertex);
});
});
const rightmostRowRemoved = Math.min(this.height - 1, removedRows.rowEnd);
const numberOfRowsRemoved = Math.max(0, rightmostRowRemoved - removedRows.rowStart + 1);
this.height = Math.max(0, this.height - numberOfRowsRemoved);
}
removeColumns(removedColumns) {
const tmpMapping = new Map();
this.mapping.forEach((rowMapping, colNumber) => {
if (colNumber >= removedColumns.columnStart) {
this.mapping.delete(colNumber);
if (colNumber > removedColumns.columnEnd) {
tmpMapping.set(colNumber - removedColumns.numberOfColumns, rowMapping);
}
}
});
tmpMapping.forEach((rowMapping, colNumber) => {
this.mapping.set(colNumber, rowMapping);
});
const rightmostColumnRemoved = Math.min(this.width - 1, removedColumns.columnEnd);
const numberOfColumnsRemoved = Math.max(0, rightmostColumnRemoved - removedColumns.columnStart + 1);
this.width = Math.max(0, this.width - numberOfColumnsRemoved);
}
*getEntries(sheet) {
for (const [colNumber, col] of this.mapping) {
for (const [rowNumber, value] of col) {
yield [(0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, colNumber, rowNumber), value];
}
}
}
*verticesFromColumn(column) {
const colMapping = this.mapping.get(column);
if (colMapping === undefined) {
return;
}
for (const [_, vertex] of colMapping) {
yield vertex;
}
}
*verticesFromRow(row) {
for (const colMapping of this.mapping.values()) {
const rowVertex = colMapping.get(row);
if (rowVertex !== undefined) {
yield rowVertex;
}
}
}
*verticesFromColumnsSpan(columnsSpan) {
for (const column of columnsSpan.columns()) {
const colMapping = this.mapping.get(column);
if (colMapping === undefined) {
continue;
}
for (const [_, vertex] of colMapping) {
yield vertex;
}
}
}
*verticesFromRowsSpan(rowsSpan) {
for (const colMapping of this.mapping.values()) {
for (const row of rowsSpan.rows()) {
const rowVertex = colMapping.get(row);
if (rowVertex !== undefined) {
yield rowVertex;
}
}
}
}
*entriesFromRowsSpan(rowsSpan) {
for (const [col, colMapping] of this.mapping.entries()) {
for (const row of rowsSpan.rows()) {
const rowVertex = colMapping.get(row);
if (rowVertex !== undefined) {
yield [(0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(rowsSpan.sheet, col, row), rowVertex];
}
}
}
}
*entriesFromColumnsSpan(columnsSpan) {
for (const col of columnsSpan.columns()) {
const colMapping = this.mapping.get(col);
if (colMapping !== undefined) {
for (const [row, vertex] of colMapping.entries()) {
yield [(0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(columnsSpan.sheet, col, row), vertex];
}
}
}
}
*vertices() {
for (const [_, col] of this.mapping) {
for (const [_, value] of col) {
if (value !== undefined) {
yield value;
}
}
}
}
}
/***/ }),
/* 92 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ DenseStrategy: () => (/* binding */ DenseStrategy)
/* harmony export */ });
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
/**
* Mapping from cell addresses to vertices
*
* Uses Array to store addresses, having minimal memory usage for dense sheets and constant set/lookup.
*/
class DenseStrategy {
/**
* @param width - width of the stored sheet
* @param height - height of the stored sheet
*/
constructor(width, height) {
this.width = width;
this.height = height;
this.mapping = new Array(height);
for (let i = 0; i < height; i++) {
this.mapping[i] = new Array(width);
}
}
/** @inheritDoc */
getCell(address) {
return this.getCellVertex(address.col, address.row);
}
/** @inheritDoc */
setCell(address, newVertex) {
this.width = Math.max(this.width, address.col + 1);
this.height = Math.max(this.height, address.row + 1);
const rowMapping = this.mapping[address.row];
if (!rowMapping) {
this.mapping[address.row] = new Array(this.width);
}
this.mapping[address.row][address.col] = newVertex;
}
/** @inheritDoc */
has(address) {
const row = this.mapping[address.row];
if (!row) {
return false;
}
return !!row[address.col];
}
/** @inheritDoc */
getHeight() {
return this.height;
}
/** @inheritDoc */
getWidth() {
return this.width;
}
removeCell(address) {
if (this.mapping[address.row] !== undefined) {
delete this.mapping[address.row][address.col];
}
}
addRows(row, numberOfRows) {
const newRows = [];
for (let i = 0; i < numberOfRows; i++) {
newRows.push(new Array(this.width));
}
this.mapping.splice(row, 0, ...newRows);
this.height += numberOfRows;
}
addColumns(column, numberOfColumns) {
for (let i = 0; i < this.height; i++) {
this.mapping[i].splice(column, 0, ...new Array(numberOfColumns));
}
this.width += numberOfColumns;
}
removeRows(removedRows) {
this.mapping.splice(removedRows.rowStart, removedRows.numberOfRows);
const rightmostRowRemoved = Math.min(this.height - 1, removedRows.rowEnd);
const numberOfRowsRemoved = Math.max(0, rightmostRowRemoved - removedRows.rowStart + 1);
this.height = Math.max(0, this.height - numberOfRowsRemoved);
}
removeColumns(removedColumns) {
for (let i = 0; i < this.height; i++) {
this.mapping[i].splice(removedColumns.columnStart, removedColumns.numberOfColumns);
}
const rightmostColumnRemoved = Math.min(this.width - 1, removedColumns.columnEnd);
const numberOfColumnsRemoved = Math.max(0, rightmostColumnRemoved - removedColumns.columnStart + 1);
this.width = Math.max(0, this.width - numberOfColumnsRemoved);
}
*getEntries(sheet) {
for (let y = 0; y < this.height; ++y) {
for (let x = 0; x < this.width; ++x) {
const vertex = this.getCellVertex(x, y);
if (vertex) {
yield [(0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(sheet, x, y), vertex];
}
}
}
}
*verticesFromColumn(column) {
for (let y = 0; y < this.height; ++y) {
const vertex = this.getCellVertex(column, y);
if (vertex) {
yield vertex;
}
}
}
*verticesFromRow(row) {
for (let x = 0; x < this.width; ++x) {
const vertex = this.getCellVertex(x, row);
if (vertex) {
yield vertex;
}
}
}
*verticesFromColumnsSpan(columnsSpan) {
for (let x = columnsSpan.columnStart; x <= columnsSpan.columnEnd; ++x) {
for (let y = 0; y < this.height; ++y) {
const vertex = this.getCellVertex(x, y);
if (vertex) {
yield vertex;
}
}
}
}
*verticesFromRowsSpan(rowsSpan) {
for (let x = 0; x < this.width; ++x) {
for (let y = rowsSpan.rowStart; y <= rowsSpan.rowEnd; ++y) {
const vertex = this.getCellVertex(x, y);
if (vertex) {
yield vertex;
}
}
}
}
*entriesFromRowsSpan(rowsSpan) {
for (let x = 0; x < this.width; ++x) {
for (let y = rowsSpan.rowStart; y <= rowsSpan.rowEnd; ++y) {
const vertex = this.getCellVertex(x, y);
if (vertex) {
yield [(0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(rowsSpan.sheet, x, y), vertex];
}
}
}
}
*entriesFromColumnsSpan(columnsSpan) {
for (let x = columnsSpan.columnStart; x <= columnsSpan.columnEnd; ++x) {
for (let y = 0; y < this.height; ++y) {
const vertex = this.getCellVertex(x, y);
if (vertex) {
yield [(0,_Cell__WEBPACK_IMPORTED_MODULE_0__.simpleCellAddress)(columnsSpan.sheet, x, y), vertex];
}
}
}
}
*vertices() {
for (let y = 0; y < this.height; ++y) {
for (let x = 0; x < this.width; ++x) {
const vertex = this.getCellVertex(x, y);
if (vertex) {
yield vertex;
}
}
}
}
getCellVertex(x, y) {
var _a;
return (_a = this.mapping[y]) === null || _a === void 0 ? void 0 : _a[x];
}
}
/***/ }),
/* 93 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ InterpreterState: () => (/* binding */ InterpreterState)
/* harmony export */ });
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
class InterpreterState {
constructor(formulaAddress, arraysFlag, formulaVertex) {
this.formulaAddress = formulaAddress;
this.arraysFlag = arraysFlag;
this.formulaVertex = formulaVertex;
}
}
/***/ }),
/* 94 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ FunctionArgumentType: () => (/* binding */ FunctionArgumentType),
/* harmony export */ FunctionPlugin: () => (/* binding */ FunctionPlugin)
/* harmony export */ });
/* harmony import */ var _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61);
/* harmony import */ var _parser__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7);
/* harmony import */ var _ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(95);
/* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(70);
/* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(69);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
var FunctionArgumentType;
(function (FunctionArgumentType) {
/**
* String type.
*/
FunctionArgumentType["STRING"] = "STRING";
/**
* Floating point type.
*/
FunctionArgumentType["NUMBER"] = "NUMBER";
/**
* Boolean type.
*/
FunctionArgumentType["BOOLEAN"] = "BOOLEAN";
/**
* Any non-range value.
*/
FunctionArgumentType["SCALAR"] = "SCALAR";
/**
* Any non-range, no-error type.
*/
FunctionArgumentType["NOERROR"] = "NOERROR";
/**
* Range type.
*/
FunctionArgumentType["RANGE"] = "RANGE";
/**
* Integer type.
*/
FunctionArgumentType["INTEGER"] = "INTEGER";
/**
* String representing complex number.
*/
FunctionArgumentType["COMPLEX"] = "COMPLEX";
/**
* Range or scalar.
*/
FunctionArgumentType["ANY"] = "ANY";
})(FunctionArgumentType || (FunctionArgumentType = {}));
/**
* 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}
*/
class FunctionPlugin {
constructor(interpreter) {
this.coerceScalarToNumberOrError = arg => this.arithmeticHelper.coerceScalarToNumberOrError(arg);
/**
* A method that should wrap the logic of every built-in function and custom function. It:
* - Evaluates the function's arguments.
* - Validates the number of arguments against the [`parameters` array](#function-options).
* - Coerces the argument values to types set in the [`parameters` array](#argument-validation-options).
* - Handles optional arguments and default values according to options set in the [`parameters` array](#argument-validation-options).
* - Validates the function's arguments against the [argument validation options](#argument-validation-options).
* - Duplicates the arguments according to the [`repeatLastArgs` option](#function-options).
* - Handles the [array arithmetic mode](arrays.md#array-arithmetic-mode).
* - Performs [function vectorization](arrays.md#passing-arrays-to-scalar-functions-vectorization).
* - Performs [argument broadcasting](arrays.md#broadcasting).
*/
this.runFunction = (args, state, metadata, functionImplementation) => {
const evaluatedArguments = this.evaluateArguments(args, state, metadata);
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
const argumentValues = evaluatedArguments.map(([value, _]) => value);
const argumentIgnorableFlags = evaluatedArguments.map(([_, ignorable]) => ignorable);
const argumentMetadata = this.buildMetadataForEachArgumentValue(argumentValues.length, metadata);
const isVectorizationOn = state.arraysFlag && !metadata.vectorizationForbidden;
if (!this.isNumberOfArgumentValuesValid(argumentMetadata, argumentValues.length)) {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongArgNumber);
}
const [resultArrayHeight, resultArrayWidth] = isVectorizationOn ? this.calculateSizeOfVectorizedResultArray(argumentValues, argumentMetadata) : [1, 1];
if (resultArrayHeight === 1 && resultArrayWidth === 1) {
const vectorizedArguments = this.vectorizeAndBroadcastArgumentsIfNecessary(isVectorizationOn, argumentValues, argumentMetadata, 0, 0);
return this.calculateSingleCellOfResultArray(state, vectorizedArguments, argumentMetadata, argumentIgnorableFlags, functionImplementation, metadata.returnNumberType);
}
const resultArray = [...Array(resultArrayHeight).keys()].map(row => [...Array(resultArrayWidth).keys()].map(col => {
const vectorizedArguments = this.vectorizeAndBroadcastArgumentsIfNecessary(isVectorizationOn, argumentValues, argumentMetadata, row, col);
const result = this.calculateSingleCellOfResultArray(state, vectorizedArguments, argumentMetadata, argumentIgnorableFlags, functionImplementation, metadata.returnNumberType);
if (result instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue) {
throw new Error('Function returning array cannot be vectorized.');
}
return result;
}));
return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue.onlyValues(resultArray);
};
this.runFunctionWithReferenceArgument = (args, state, metadata, noArgCallback, referenceCallback, nonReferenceCallback = () => new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.CellRefExpected)) => {
if (args.length === 0) {
return this.returnNumberWrapper(noArgCallback(), metadata.returnNumberType);
} else if (args.length > 1) {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NA, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongArgNumber);
}
let arg = args[0];
while (arg.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.PARENTHESIS) {
arg = arg.expression;
}
let cellReference;
if (arg.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_REFERENCE) {
cellReference = arg.reference.toSimpleCellAddress(state.formulaAddress);
} else if (arg.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.CELL_RANGE || arg.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.COLUMN_RANGE || arg.type === _parser__WEBPACK_IMPORTED_MODULE_3__.AstNodeType.ROW_RANGE) {
try {
cellReference = _AbsoluteCellRange__WEBPACK_IMPORTED_MODULE_0__.AbsoluteCellRange.fromAst(arg, state.formulaAddress).start;
} catch (e) {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.REF, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.CellRefExpected);
}
}
if (cellReference !== undefined) {
return this.returnNumberWrapper(referenceCallback(cellReference), metadata.returnNumberType);
}
return this.runFunction(args, state, metadata, nonReferenceCallback);
};
this.interpreter = interpreter;
this.dependencyGraph = interpreter.dependencyGraph;
this.columnSearch = interpreter.columnSearch;
this.config = interpreter.config;
this.serialization = interpreter.serialization;
this.arraySizePredictor = interpreter.arraySizePredictor;
this.dateTimeHelper = interpreter.dateTimeHelper;
this.arithmeticHelper = interpreter.arithmeticHelper;
}
evaluateAst(ast, state) {
return this.interpreter.evaluateAst(ast, state);
}
arraySizeForAst(ast, state) {
return this.arraySizePredictor.checkArraySizeForAst(ast, state);
}
listOfScalarValues(asts, state) {
const ret = [];
for (const argAst of asts) {
const value = this.evaluateAst(argAst, state);
if (value instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue) {
for (const scalarValue of value.valuesFromTopLeftCorner()) {
ret.push([scalarValue, true]);
}
} else {
ret.push([value, false]);
}
}
return ret;
}
coerceToType(arg, coercedType, state) {
let ret;
if (arg instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue) {
switch (coercedType.argumentType) {
case FunctionArgumentType.RANGE:
case FunctionArgumentType.ANY:
ret = arg;
break;
default:
{
const coerce = (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__.coerceRangeToScalar)(arg, state);
if (coerce === undefined) {
return undefined;
}
arg = coerce;
}
}
}
if (!(arg instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue)) {
switch (coercedType.argumentType) {
case FunctionArgumentType.INTEGER:
case FunctionArgumentType.NUMBER:
// eslint-disable-next-line no-case-declarations
const coerced = this.coerceScalarToNumberOrError(arg);
if (!(0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.isExtendedNumber)(coerced)) {
ret = coerced;
break;
}
// eslint-disable-next-line no-case-declarations
const value = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.getRawValue)(coerced);
if (coercedType.maxValue !== undefined && value > coercedType.maxValue) {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ValueLarge);
}
if (coercedType.minValue !== undefined && value < coercedType.minValue) {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ValueSmall);
}
if (coercedType.lessThan !== undefined && value >= coercedType.lessThan) {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ValueLarge);
}
if (coercedType.greaterThan !== undefined && value <= coercedType.greaterThan) {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ValueSmall);
}
if (coercedType.argumentType === FunctionArgumentType.INTEGER && !Number.isInteger(value)) {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.IntegerExpected);
}
ret = coerced;
break;
case FunctionArgumentType.STRING:
ret = (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__.coerceScalarToString)(arg);
break;
case FunctionArgumentType.BOOLEAN:
ret = (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__.coerceScalarToBoolean)(arg);
break;
case FunctionArgumentType.SCALAR:
case FunctionArgumentType.NOERROR:
case FunctionArgumentType.ANY:
ret = arg;
break;
case FunctionArgumentType.RANGE:
if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return arg;
}
ret = (0,_ArithmeticHelper__WEBPACK_IMPORTED_MODULE_4__.coerceToRange)(arg);
break;
case FunctionArgumentType.COMPLEX:
return this.arithmeticHelper.coerceScalarToComplex((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.getRawValue)(arg));
}
}
if (coercedType.passSubtype || ret === undefined) {
return ret;
} else {
return (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.getRawValue)(ret);
}
}
calculateSingleCellOfResultArray(state, vectorizedArguments, argumentsMetadata, argumentIgnorableFlags, functionImplementation, returnNumberType) {
const coercedArguments = this.coerceArgumentsToRequiredTypes(state, vectorizedArguments, argumentsMetadata, argumentIgnorableFlags);
if (coercedArguments instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return coercedArguments;
}
const functionCalculationResult = functionImplementation(...coercedArguments);
return this.returnNumberWrapper(functionCalculationResult, returnNumberType);
}
coerceArgumentsToRequiredTypes(state, vectorizedArguments, argumentsMetadata, argumentIgnorableFlags) {
const coercedArguments = [];
for (let i = 0; i < argumentsMetadata.length; i++) {
const argumentMetadata = argumentsMetadata[i];
const argumentValue = vectorizedArguments[i] !== undefined ? vectorizedArguments[i] : argumentMetadata === null || argumentMetadata === void 0 ? void 0 : argumentMetadata.defaultValue;
if (argumentValue === undefined) {
coercedArguments.push(undefined);
continue;
}
const coercedValue = this.coerceToType(argumentValue, argumentMetadata, state);
if (coercedValue === undefined && !argumentIgnorableFlags[i]) {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.WrongType);
}
if (coercedValue instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError && argumentMetadata.argumentType !== FunctionArgumentType.SCALAR) {
return coercedValue;
}
coercedArguments.push(coercedValue);
}
return coercedArguments;
}
vectorizeAndBroadcastArgumentsIfNecessary(isVectorizationOn, argumentValues, argumentMetadata, row, col) {
return argumentValues.map((value, i) => isVectorizationOn && this.isRangePassedAsAScalarArgument(value, argumentMetadata[i]) ? this.vectorizeAndBroadcastRangeArgument(value, row, col) : value);
}
vectorizeAndBroadcastRangeArgument(argumentValue, rowNum, colNum) {
var _a;
const targetRowNum = argumentValue.height() === 1 ? 0 : rowNum;
const targetColNum = argumentValue.width() === 1 ? 0 : colNum;
return (_a = argumentValue.data[targetRowNum]) === null || _a === void 0 ? void 0 : _a[targetColNum];
}
evaluateArguments(args, state, metadata) {
return metadata.expandRanges ? this.listOfScalarValues(args, state) : args.map(ast => [this.evaluateAst(ast, state), false]);
}
buildMetadataForEachArgumentValue(numberOfArgumentValuesPassed, metadata) {
const argumentsMetadata = metadata.parameters ? [...metadata.parameters] : [];
const isRepeatLastArgsValid = metadata.repeatLastArgs !== undefined && Number.isInteger(metadata.repeatLastArgs) && metadata.repeatLastArgs > 0;
if (isRepeatLastArgsValid) {
while (numberOfArgumentValuesPassed > argumentsMetadata.length) {
argumentsMetadata.push(...argumentsMetadata.slice(argumentsMetadata.length - metadata.repeatLastArgs));
}
}
return argumentsMetadata;
}
isNumberOfArgumentValuesValid(argumentsMetadata, numberOfArgumentValuesPassed) {
if (numberOfArgumentValuesPassed > argumentsMetadata.length) {
return false;
}
if (numberOfArgumentValuesPassed < argumentsMetadata.length) {
const metadataForMissingArguments = argumentsMetadata.slice(numberOfArgumentValuesPassed);
const areMissingArgumentsOptional = metadataForMissingArguments.every(argMetadata => (argMetadata === null || argMetadata === void 0 ? void 0 : argMetadata.optionalArg) || (argMetadata === null || argMetadata === void 0 ? void 0 : argMetadata.defaultValue) !== undefined);
return areMissingArgumentsOptional;
}
return true;
}
calculateSizeOfVectorizedResultArray(argumentValues, argumentMetadata) {
const argumentsThatRequireVectorization = argumentValues.filter((value, i) => this.isRangePassedAsAScalarArgument(value, argumentMetadata[i]));
const height = Math.max(1, ...argumentsThatRequireVectorization.map(val => val.height()));
const width = Math.max(1, ...argumentsThatRequireVectorization.map(val => val.width()));
return [height, width];
}
isRangePassedAsAScalarArgument(argumentValue, argumentMetadata) {
if (argumentValue == null || argumentMetadata == null) {
return false;
}
return argumentValue instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_6__.SimpleRangeValue && ![FunctionArgumentType.RANGE, FunctionArgumentType.ANY].includes(argumentMetadata.argumentType);
}
metadata(name) {
const params = this.constructor.implementedFunctions[name];
if (params !== undefined) {
return params;
}
throw new Error(`No metadata for function ${name}.`);
}
returnNumberWrapper(val, type, format) {
if (type !== undefined && (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.isExtendedNumber)(val)) {
return this.arithmeticHelper.ExtendedNumberFactory((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_5__.getRawValue)(val), {
type,
format
});
} else {
return val;
}
}
}
/***/ }),
/* 95 */
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ ArithmeticHelper: () => (/* binding */ ArithmeticHelper),
/* harmony export */ coerceBooleanToNumber: () => (/* binding */ coerceBooleanToNumber),
/* harmony export */ coerceComplexToString: () => (/* binding */ coerceComplexToString),
/* harmony export */ coerceEmptyToValue: () => (/* binding */ coerceEmptyToValue),
/* harmony export */ coerceRangeToScalar: () => (/* binding */ coerceRangeToScalar),
/* harmony export */ coerceScalarToBoolean: () => (/* binding */ coerceScalarToBoolean),
/* harmony export */ coerceScalarToString: () => (/* binding */ coerceScalarToString),
/* harmony export */ coerceToRange: () => (/* binding */ coerceToRange),
/* harmony export */ coerceToRangeNumbersOrError: () => (/* binding */ coerceToRangeNumbersOrError),
/* harmony export */ fixNegativeZero: () => (/* binding */ fixNegativeZero),
/* harmony export */ forceNormalizeString: () => (/* binding */ forceNormalizeString),
/* harmony export */ isNumberOverflow: () => (/* binding */ isNumberOverflow),
/* harmony export */ normalizeString: () => (/* binding */ normalizeString),
/* harmony export */ numberCmp: () => (/* binding */ numberCmp),
/* harmony export */ zeroIfEmpty: () => (/* binding */ zeroIfEmpty)
/* harmony export */ });
/* harmony import */ var unorm__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(96);
/* harmony import */ var unorm__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(unorm__WEBPACK_IMPORTED_MODULE_0__);
/* harmony import */ var _Cell__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var _error_message__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(61);
/* harmony import */ var _StringHelper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(97);
/* harmony import */ var _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(70);
/* harmony import */ var _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(69);
/**
* @license
* Copyright (c) 2023 Handsoncode. All rights reserved.
*/
const COMPLEX_NUMBER_SYMBOL = 'i';
const complexParsingRegexp = /^\s*([+-]?)\s*(([\d\.,]+(e[+-]?\d+)?)\s*([ij]?)|([ij]))\s*(([+-])\s*([+-]?)\s*(([\d\.,]+(e[+-]?\d+)?)\s*([ij]?)|([ij])))?$/;
class ArithmeticHelper {
constructor(config, dateTimeHelper, numberLiteralsHelper) {
this.config = config;
this.dateTimeHelper = dateTimeHelper;
this.numberLiteralsHelper = numberLiteralsHelper;
this.lt = (left, right) => {
return this.compare(left, right) < 0;
};
this.leq = (left, right) => {
return this.compare(left, right) <= 0;
};
this.gt = (left, right) => {
return this.compare(left, right) > 0;
};
this.geq = (left, right) => {
return this.compare(left, right) >= 0;
};
this.eq = (left, right) => {
return this.compare(left, right) === 0;
};
this.neq = (left, right) => {
return this.compare(left, right) !== 0;
};
this.pow = (left, right) => {
return Math.pow((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(left), (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(right));
};
this.addWithEpsilonRaw = (left, right) => {
const ret = left + right;
if (Math.abs(ret) < this.actualEps * Math.abs(left)) {
return 0;
} else {
return ret;
}
};
this.addWithEpsilon = (left, right) => {
const typeOfResult = inferExtendedNumberTypeAdditive(left, right);
return this.ExtendedNumberFactory(this.addWithEpsilonRaw((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(left), (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(right)), typeOfResult);
};
this.unaryMinus = arg => {
return (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.cloneNumber)(arg, -(0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(arg));
};
this.unaryPlus = arg => arg;
this.unaryPercent = arg => {
return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.PercentNumber((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(arg) / 100);
};
this.concat = (left, right) => {
return left.concat(right);
};
this.nonstrictadd = (left, right) => {
if (left instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return left;
} else if (right instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return right;
} else if (typeof left === 'number') {
if (typeof right === 'number') {
return this.addWithEpsilonRaw(left, right);
} else {
return left;
}
} else if (typeof right === 'number') {
return right;
} else {
return 0;
}
};
/**
* Subtracts two numbers
*
* Implementation of subtracting which is used in interpreter.
*
* @param left - left operand of subtraction
* @param right - right operand of subtraction
* @param eps - precision of comparison
*/
this.subtract = (leftArg, rightArg) => {
const typeOfResult = inferExtendedNumberTypeAdditive(leftArg, rightArg);
const left = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(leftArg);
const right = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(rightArg);
let ret = left - right;
if (Math.abs(ret) < this.actualEps * Math.abs(left)) {
ret = 0;
}
return this.ExtendedNumberFactory(ret, typeOfResult);
};
this.divide = (leftArg, rightArg) => {
const left = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(leftArg);
const right = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(rightArg);
if (right === 0) {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.DIV_BY_ZERO);
} else {
const typeOfResult = inferExtendedNumberTypeMultiplicative(leftArg, rightArg);
return this.ExtendedNumberFactory(left / right, typeOfResult);
}
};
this.multiply = (left, right) => {
const typeOfResult = inferExtendedNumberTypeMultiplicative(left, right);
return this.ExtendedNumberFactory((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(left) * (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(right), typeOfResult);
};
this.manyToExactComplex = args => {
const ret = [];
for (const arg of args) {
if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return arg;
} else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(arg) || typeof arg === 'string') {
const coerced = this.coerceScalarToComplex(arg);
if (!(coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError)) {
ret.push(coerced);
}
}
}
return ret;
};
this.coerceNumbersExactRanges = args => this.manyToNumbers(args, this.manyToExactNumbers);
this.coerceNumbersCoerceRangesDropNulls = args => this.manyToNumbers(args, this.manyToCoercedNumbersDropNulls);
this.manyToExactNumbers = args => {
const ret = [];
for (const arg of args) {
if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return arg;
} else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(arg)) {
ret.push((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(arg));
}
}
return ret;
};
this.manyToOnlyNumbersDropNulls = args => {
const ret = [];
for (const arg of args) {
if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return arg;
} else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(arg)) {
ret.push((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(arg));
} else if (arg !== _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue) {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.NumberExpected);
}
}
return ret;
};
this.manyToCoercedNumbersDropNulls = args => {
const ret = [];
for (const arg of args) {
if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return arg;
}
if (arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue) {
continue;
}
const coerced = this.coerceScalarToNumberOrError(arg);
if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(coerced)) {
ret.push((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(coerced));
}
}
return ret;
};
this.collator = (0,_StringHelper__WEBPACK_IMPORTED_MODULE_3__.collatorFromConfig)(config);
this.actualEps = config.smartRounding ? config.precisionEpsilon : 0;
}
eqMatcherFunction(pattern) {
const regexp = this.buildRegex(pattern);
return cellValue => typeof cellValue === 'string' && regexp.test(this.normalizeString(cellValue));
}
neqMatcherFunction(pattern) {
const regexp = this.buildRegex(pattern);
return cellValue => {
return !(typeof cellValue === 'string') || !regexp.test(this.normalizeString(cellValue));
};
}
searchString(pattern, text) {
var _a;
const regexp = this.buildRegex(pattern, false);
const result = regexp.exec(text);
return (_a = result === null || result === void 0 ? void 0 : result.index) !== null && _a !== void 0 ? _a : -1;
}
requiresRegex(pattern) {
if (!this.config.useRegularExpressions && !this.config.useWildcards) {
return !this.config.matchWholeCell;
}
for (let i = 0; i < pattern.length; i++) {
const c = pattern.charAt(i);
if (isWildcard(c) || this.config.useRegularExpressions && needsEscape(c)) {
return true;
}
}
return false;
}
floatCmp(leftArg, rightArg) {
const left = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(leftArg);
const right = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(rightArg);
const mod = 1 + this.actualEps;
if (right >= 0 && left * mod >= right && left <= right * mod) {
return 0;
} else if (right <= 0 && left * mod <= right && left >= right * mod) {
return 0;
} else if (left > right) {
return 1;
} else {
return -1;
}
}
coerceScalarToNumberOrError(arg) {
var _a;
if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return arg;
}
return (_a = this.coerceToMaybeNumber(arg)) !== null && _a !== void 0 ? _a : new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.VALUE, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.NumberCoercion);
}
coerceToMaybeNumber(arg) {
var _a;
return (_a = this.coerceNonDateScalarToMaybeNumber(arg)) !== null && _a !== void 0 ? _a : typeof arg === 'string' ? this.dateTimeHelper.dateStringToDateNumber(arg) : undefined;
}
coerceNonDateScalarToMaybeNumber(arg) {
if (arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue) {
return 0;
} else if (typeof arg === 'string') {
if (arg === '') {
return 0;
}
const maybePercentNumber = this.coerceStringToMaybePercentNumber(arg);
if (maybePercentNumber !== undefined) {
return maybePercentNumber;
}
const maybeCurrencyNumber = this.coerceStringToMaybeCurrencyNumber(arg);
if (maybeCurrencyNumber !== undefined) {
return maybeCurrencyNumber;
}
return this.numberLiteralsHelper.numericStringToMaybeNumber(arg.trim());
} else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(arg)) {
return arg;
} else if (typeof arg === 'boolean') {
return Number(arg);
} else {
return undefined;
}
}
coerceStringToMaybePercentNumber(input) {
const trimmedInput = input.trim();
if (trimmedInput.endsWith('%')) {
const numOfPercents = trimmedInput.slice(0, trimmedInput.length - 1).trim();
const parsedNumOfPercents = this.numberLiteralsHelper.numericStringToMaybeNumber(numOfPercents);
if (parsedNumOfPercents !== undefined) {
return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.PercentNumber(parsedNumOfPercents / 100);
}
}
return undefined;
}
coerceStringToMaybeCurrencyNumber(input) {
const matchedCurrency = this.currencyMatcher(input.trim());
if (matchedCurrency !== undefined) {
const [currencySymbol, currencyValue] = matchedCurrency;
const parsedCurrencyValue = this.numberLiteralsHelper.numericStringToMaybeNumber(currencyValue);
if (parsedCurrencyValue !== undefined) {
return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.CurrencyNumber(parsedCurrencyValue, currencySymbol);
}
}
return undefined;
}
currencyMatcher(token) {
for (const currency of this.config.currencySymbol) {
if (token.startsWith(currency)) {
return [currency, token.slice(currency.length).trim()];
}
if (token.endsWith(currency)) {
return [currency, token.slice(0, token.length - currency.length).trim()];
}
}
return undefined;
}
coerceComplexExactRanges(args) {
const vals = [];
for (const arg of args) {
if (arg instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue) {
vals.push(arg);
} else if (arg !== _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue) {
const coerced = this.coerceScalarToComplex(arg);
if (coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return coerced;
} else {
vals.push(coerced);
}
}
}
const expandedVals = [];
for (const val of vals) {
if (val instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue) {
const arr = this.manyToExactComplex(val.valuesFromTopLeftCorner());
if (arr instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return arr;
} else {
expandedVals.push(...arr);
}
} else {
expandedVals.push(val);
}
}
return expandedVals;
}
coerceScalarToComplex(arg) {
if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return arg;
} else if (arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue) {
return [0, 0];
} else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(arg)) {
return [(0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(arg), 0];
} else if (typeof arg === 'string') {
return this.coerceStringToComplex(arg);
} else {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ComplexNumberExpected);
}
}
ExtendedNumberFactory(value, typeFormat) {
const {
type,
format
} = typeFormat;
switch (type) {
case _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_RAW:
return value;
case _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_CURRENCY:
{
return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.CurrencyNumber(value, format !== null && format !== void 0 ? format : this.config.currencySymbol[0]);
}
case _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATE:
return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.DateNumber(value, format);
case _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATETIME:
return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.DateTimeNumber(value, format);
case _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_TIME:
return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.TimeNumber(value, format);
case _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_PERCENT:
return new _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.PercentNumber(value, format);
}
}
buildRegex(pattern, matchWholeCell = true) {
pattern = this.normalizeString(pattern);
let regexpStr;
let useWildcards = this.config.useWildcards;
let useRegularExpressions = this.config.useRegularExpressions;
if (useRegularExpressions) {
try {
RegExp(pattern);
} catch (e) {
useRegularExpressions = false;
useWildcards = false;
}
}
if (useRegularExpressions) {
regexpStr = escapeNoCharacters(pattern, this.config.caseSensitive);
} else if (useWildcards) {
regexpStr = escapeNonWildcards(pattern, this.config.caseSensitive);
} else {
regexpStr = escapeAllCharacters(pattern, this.config.caseSensitive);
}
if (this.config.matchWholeCell && matchWholeCell) {
return RegExp('^(' + regexpStr + ')$');
} else {
return RegExp(regexpStr);
}
}
normalizeString(str) {
if (!this.config.caseSensitive) {
str = str.toLowerCase();
}
if (!this.config.accentSensitive) {
str = normalizeString(str, 'nfd').replace(/[\u0300-\u036f]/g, '');
}
return str;
}
compare(left, right) {
if (typeof left === 'string' || typeof right === 'string') {
const leftTmp = typeof left === 'string' ? this.dateTimeHelper.dateStringToDateNumber(left) : left;
const rightTmp = typeof right === 'string' ? this.dateTimeHelper.dateStringToDateNumber(right) : right;
if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(leftTmp) && (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(rightTmp)) {
return this.floatCmp(leftTmp, rightTmp);
}
}
if (left === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue) {
left = coerceEmptyToValue(right);
} else if (right === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue) {
right = coerceEmptyToValue(left);
}
if (typeof left === 'string' && typeof right === 'string') {
return this.stringCmp(left, right);
} else if (typeof left === 'boolean' && typeof right === 'boolean') {
return numberCmp(coerceBooleanToNumber(left), coerceBooleanToNumber(right));
} else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(left) && (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(right)) {
return this.floatCmp(left, right);
} else if (left === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue && right === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue) {
return 0;
} else {
return numberCmp((0,_Cell__WEBPACK_IMPORTED_MODULE_1__.CellValueTypeOrd)((0,_Cell__WEBPACK_IMPORTED_MODULE_1__.getCellValueType)(left)), (0,_Cell__WEBPACK_IMPORTED_MODULE_1__.CellValueTypeOrd)((0,_Cell__WEBPACK_IMPORTED_MODULE_1__.getCellValueType)(right)));
}
}
stringCmp(left, right) {
return this.collator.compare(left, right);
}
manyToNumbers(args, rangeFn) {
const vals = [];
for (const arg of args) {
if (arg instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue) {
vals.push(arg);
} else {
const coerced = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(this.coerceScalarToNumberOrError(arg));
if (coerced instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return coerced;
} else {
vals.push(coerced);
}
}
}
const expandedVals = [];
for (const val of vals) {
if (val instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue) {
const arr = rangeFn(val.valuesFromTopLeftCorner());
if (arr instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return arr;
} else {
expandedVals.push(...arr);
}
} else {
expandedVals.push(val);
}
}
return expandedVals;
}
coerceStringToComplex(arg) {
const match = complexParsingRegexp.exec(arg);
if (match === null) {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ComplexNumberExpected);
}
let val1;
if (match[6] !== undefined) {
val1 = match[1] === '-' ? [0, -1] : [0, 1];
} else {
val1 = this.parseComplexToken(match[1] + match[3], match[5]);
}
if (val1 instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return val1;
}
if (match[8] === undefined) {
return val1;
}
let val2;
if (match[14] !== undefined) {
val2 = match[9] === '-' ? [0, -1] : [0, 1];
} else {
val2 = this.parseComplexToken(match[9] + match[11], match[13]);
}
if (val2 instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return val2;
}
if (match[5] !== '' || match[13] === '') {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ComplexNumberExpected);
}
if (match[8] === '+') {
return [val1[0] + val2[0], val1[1] + val2[1]];
} else {
return [val1[0] - val2[0], val1[1] - val2[1]];
}
}
parseComplexToken(arg, mod) {
const val = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(this.coerceNonDateScalarToMaybeNumber(arg));
if (val === undefined) {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.ComplexNumberExpected);
}
if (mod === '') {
return [val, 0];
} else {
return [0, val];
}
}
}
function coerceComplexToString([re, im], symb) {
if (!isFinite(re) || !isFinite(im)) {
return new _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError(_Cell__WEBPACK_IMPORTED_MODULE_1__.ErrorType.NUM, _error_message__WEBPACK_IMPORTED_MODULE_2__.ErrorMessage.NaN);
}
symb = symb !== null && symb !== void 0 ? symb : COMPLEX_NUMBER_SYMBOL;
if (im === 0) {
return `${re}`;
}
const imStr = `${im === -1 || im === 1 ? '' : Math.abs(im)}${symb}`;
if (re === 0) {
return `${im < 0 ? '-' : ''}${imStr}`;
}
return `${re}${im < 0 ? '-' : '+'}${imStr}`;
}
function coerceToRange(arg) {
if (arg instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue) {
return arg;
} else {
return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue.fromScalar(arg);
}
}
function coerceToRangeNumbersOrError(arg) {
if (arg instanceof _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue && arg.hasOnlyNumbers() || arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError) {
return arg;
} else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(arg)) {
return _SimpleRangeValue__WEBPACK_IMPORTED_MODULE_5__.SimpleRangeValue.fromScalar(arg);
} else {
return null;
}
}
function coerceBooleanToNumber(arg) {
return Number(arg);
}
function coerceEmptyToValue(arg) {
if (typeof arg === 'string') {
return '';
} else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(arg)) {
return 0;
} else if (typeof arg === 'boolean') {
return false;
} else {
return _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue;
}
}
/**
* Coerce scalar value to boolean if possible, or error if value is an error
*
* @param arg
*/
function coerceScalarToBoolean(arg) {
if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError || typeof arg === 'boolean') {
return arg;
} else if (arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue) {
return false;
} else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(arg)) {
return (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(arg) !== 0;
} else {
const argUppered = arg.toUpperCase();
if (argUppered === 'TRUE') {
return true;
} else if (argUppered === 'FALSE') {
return false;
} else if (argUppered === '') {
return false;
} else {
return undefined;
}
}
}
function coerceScalarToString(arg) {
if (arg instanceof _Cell__WEBPACK_IMPORTED_MODULE_1__.CellError || typeof arg === 'string') {
return arg;
} else if (arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue) {
return '';
} else if ((0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.isExtendedNumber)(arg)) {
return (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(arg).toString();
} else {
return arg ? 'TRUE' : 'FALSE';
}
}
function zeroIfEmpty(arg) {
return arg === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.EmptyValue ? 0 : arg;
}
function numberCmp(leftArg, rightArg) {
const left = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(leftArg);
const right = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getRawValue)(rightArg);
if (left > right) {
return 1;
} else if (left < right) {
return -1;
} else {
return 0;
}
}
function isNumberOverflow(arg) {
return isNaN(arg) || arg === Infinity || arg === -Infinity;
}
function fixNegativeZero(arg) {
if (arg === 0) {
return 0;
} else {
return arg;
}
}
function isWildcard(c) {
return ['*', '?'].includes(c);
}
const escapedCharacters = ['{', '}', '[', ']', '(', ')', '<', '>', '=', '.', '+', '-', ',', '\\', '$', '^', '!'];
function needsEscape(c) {
return escapedCharacters.includes(c);
}
function escapeNonWildcards(pattern, caseSensitive) {
let str = '';
for (let i = 0; i < pattern.length; i++) {
const c = pattern.charAt(i);
if (c === '~') {
if (i == pattern.length - 1) {
str += '~';
continue;
}
const d = pattern.charAt(i + 1);
if (isWildcard(d) || needsEscape(d)) {
str += '\\' + d;
i++;
} else {
str += d;
i++;
}
} else if (isWildcard(c)) {
str += '.' + c;
} else if (needsEscape(c)) {
str += '\\' + c;
} else if (caseSensitive) {
str += c;
} else {
str += c.toLowerCase();
}
}
return str;
}
function escapeAllCharacters(pattern, caseSensitive) {
let str = '';
for (let i = 0; i < pattern.length; i++) {
const c = pattern.charAt(i);
if (isWildcard(c) || needsEscape(c)) {
str += '\\' + c;
} else if (caseSensitive) {
str += c;
} else {
str += c.toLowerCase();
}
}
return str;
}
function escapeNoCharacters(pattern, caseSensitive) {
let str = '';
for (let i = 0; i < pattern.length; i++) {
const c = pattern.charAt(i);
if (isWildcard(c) || needsEscape(c)) {
str += c;
} else if (caseSensitive) {
str += c;
} else {
str += c.toLowerCase();
}
}
return str;
}
function inferExtendedNumberTypeAdditive(leftArg, rightArg) {
const {
type: leftType,
format: leftFormat
} = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getTypeFormatOfExtendedNumber)(leftArg);
const {
type: rightType,
format: rightFormat
} = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getTypeFormatOfExtendedNumber)(rightArg);
if (leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_RAW) {
return {
type: rightType,
format: rightFormat
};
}
if (rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_RAW) {
return {
type: leftType,
format: leftFormat
};
}
if ((leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATETIME || leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATE) && (rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATETIME || rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATE)) {
return {
type: _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_RAW
};
}
if (leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_TIME) {
if (rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATE) {
return {
type: _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATETIME,
format: `${rightFormat} ${leftFormat}`
};
}
if (rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATETIME) {
return {
type: _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATETIME,
format: rightFormat
};
}
}
if (rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_TIME) {
if (leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATE) {
return {
type: _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATETIME,
format: `${leftFormat} ${rightFormat}`
};
}
if (leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATETIME) {
return {
type: _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_DATETIME,
format: leftFormat
};
}
}
return {
type: leftType,
format: leftFormat
};
}
function inferExtendedNumberTypeMultiplicative(leftArg, rightArg) {
let {
type: leftType,
format: leftFormat
} = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getTypeFormatOfExtendedNumber)(leftArg);
let {
type: rightType,
format: rightFormat
} = (0,_InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.getTypeFormatOfExtendedNumber)(rightArg);
if (leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_PERCENT) {
leftType = _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_RAW;
leftFormat = undefined;
}
if (rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_PERCENT) {
rightType = _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_RAW;
rightFormat = undefined;
}
if (leftType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_RAW) {
return {
type: rightType,
format: rightFormat
};
}
if (rightType === _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_RAW) {
return {
type: leftType,
format: leftFormat
};
}
return {
type: _InterpreterValue__WEBPACK_IMPORTED_MODULE_4__.NumberType.NUMBER_RAW
};
}
function forceNormalizeString(str) {
return normalizeString(str.toLowerCase(), 'nfd').replace(/[\u0300-\u036f]/g, '');
}
function coerceRangeToScalar(arg, state) {
var _a;
if (arg.isAdHoc()) {
return (_a = arg.data[0]) === null || _a === void 0 ? void 0 : _a[0];
}
const range = arg.range;
if (state.formulaAddress.sheet === range.sheet) {
if (range.width() === 1) {
const offset = state.formulaAddress.row - range.start.row;
if (offset >= 0 && offset < range.height()) {
return arg.data[offset][0];
}
} else if (range.height() === 1) {
const offset = state.formulaAddress.col - range.start.col;
if (offset >= 0 && offset < range.width()) {
return arg.data[0][offset];
}
}
}
return undefined;
}
function normalizeString(str, form) {
return typeof str.normalize === 'function' ? str.normalize(form.toUpperCase()) : (unorm__WEBPACK_IMPORTED_MODULE_0___default())[form](str);
}
/***/ }),
/* 96 */
/***/ (function(module) {
(function (root) {
"use strict";
/***** unorm.js *****/
/*
* UnicodeNormalizer 1.0.0
* Copyright (c) 2008 Matsuza
* Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.
* $Date: 2008-06-05 16:44:17 +0200 (Thu, 05 Jun 2008) $
* $Rev: 13309 $
*/
var DEFAULT_FEATURE = [null, 0, {}];
var CACHE_THRESHOLD = 10;
var SBase = 0xAC00, LBase = 0x1100, VBase = 0x1161, TBase = 0x11A7, LCount = 19, VCount = 21, TCount = 28;
var NCount = VCount * TCount; // 588
var SCount = LCount * NCount; // 11172
var UChar = function(cp, feature){
this.codepoint = cp;
this.feature = feature;
};
// Strategies
var cache = {};
var cacheCounter = [];
for (var i = 0; i <= 0xFF; ++i){
cacheCounter[i] = 0;
}
function fromCache(next, cp, needFeature){
var ret = cache[cp];
if(!ret){
ret = next(cp, needFeature);
if(!!ret.feature && ++cacheCounter[(cp >> 8) & 0xFF] > CACHE_THRESHOLD){
cache[cp] = ret;
}
}
return ret;
}
function fromData(next, cp, needFeature){
var hash = cp & 0xFF00;
var dunit = UChar.udata[hash] || {};
var f = dunit[cp];
return f ? new UChar(cp, f) : new UChar(cp, DEFAULT_FEATURE);
}
function fromCpOnly(next, cp, needFeature){
return !!needFeature ? next(cp, needFeature) : new UChar(cp, null);
}
function fromRuleBasedJamo(next, cp, needFeature){
var j;
if(cp < LBase || (LBase + LCount <= cp && cp < SBase) || (SBase + SCount < cp)){
return next(cp, needFeature);
}
if(LBase <= cp && cp < LBase + LCount){
var c = {};
var base = (cp - LBase) * VCount;
for (j = 0; j < VCount; ++j){
c[VBase + j] = SBase + TCount * (j + base);
}
return new UChar(cp, [,,c]);
}
var SIndex = cp - SBase;
var TIndex = SIndex % TCount;
var feature = [];
if(TIndex !== 0){
feature[0] = [SBase + SIndex - TIndex, TBase + TIndex];
} else {
feature[0] = [LBase + Math.floor(SIndex / NCount), VBase + Math.floor((SIndex % NCount) / TCount)];
feature[2] = {};
for (j = 1; j < TCount; ++j){
feature[2][TBase + j] = cp + j;
}
}
return new UChar(cp, feature);
}
function fromCpFilter(next, cp, needFeature){
return cp < 60 || 13311 < cp && cp < 42607 ? new UChar(cp, DEFAULT_FEATURE) : next(cp, needFeature);
}
var strategies = [fromCpFilter, fromCache, fromCpOnly, fromRuleBasedJamo, fromData];
UChar.fromCharCode = strategies.reduceRight(function (next, strategy) {
return function (cp, needFeature) {
return strategy(next, cp, needFeature);
};
}, null);
UChar.isHighSurrogate = function(cp){
return cp >= 0xD800 && cp <= 0xDBFF;
};
UChar.isLowSurrogate = function(cp){
return cp >= 0xDC00 && cp <= 0xDFFF;
};
UChar.prototype.prepFeature = function(){
if(!this.feature){
this.feature = UChar.fromCharCode(this.codepoint, true).feature;
}
};
UChar.prototype.toString = function(){
if(this.codepoint < 0x10000){
return String.fromCharCode(this.codepoint);
} else {
var x = this.codepoint - 0x10000;
return String.fromCharCode(Math.floor(x / 0x400) + 0xD800, x % 0x400 + 0xDC00);
}
};
UChar.prototype.getDecomp = function(){
this.prepFeature();
return this.feature[0] || null;
};
UChar.prototype.isCompatibility = function(){
this.prepFeature();
return !!this.feature[1] && (this.feature[1] & (1 << 8));
};
UChar.prototype.isExclude = function(){
this.prepFeature();
return !!this.feature[1] && (this.feature[1] & (1 << 9));
};
UChar.prototype.getCanonicalClass = function(){
this.prepFeature();
return !!this.feature[1] ? (this.feature[1] & 0xff) : 0;
};
UChar.prototype.getComposite = function(following){
this.prepFeature();
if(!this.feature[2]){
return null;
}
var cp = this.feature[2][following.codepoint];
return cp ? UChar.fromCharCode(cp) : null;
};
var UCharIterator = function(str){
this.str = str;
this.cursor = 0;
};
UCharIterator.prototype.next = function(){
if(!!this.str && this.cursor < this.str.length){
var cp = this.str.charCodeAt(this.cursor++);
var d;
if(UChar.isHighSurrogate(cp) && this.cursor < this.str.length && UChar.isLowSurrogate((d = this.str.charCodeAt(this.cursor)))){
cp = (cp - 0xD800) * 0x400 + (d -0xDC00) + 0x10000;
++this.cursor;
}
return UChar.fromCharCode(cp);
} else {
this.str = null;
return null;
}
};
var RecursDecompIterator = function(it, cano){
this.it = it;
this.canonical = cano;
this.resBuf = [];
};
RecursDecompIterator.prototype.next = function(){
function recursiveDecomp(cano, uchar){
var decomp = uchar.getDecomp();
if(!!decomp && !(cano && uchar.isCompatibility())){
var ret = [];
for(var i = 0; i < decomp.length; ++i){
var a = recursiveDecomp(cano, UChar.fromCharCode(decomp[i]));
ret = ret.concat(a);
}
return ret;
} else {
return [uchar];
}
}
if(this.resBuf.length === 0){
var uchar = this.it.next();
if(!uchar){
return null;
}
this.resBuf = recursiveDecomp(this.canonical, uchar);
}
return this.resBuf.shift();
};
var DecompIterator = function(it){
this.it = it;
this.resBuf = [];
};
DecompIterator.prototype.next = function(){
var cc;
if(this.resBuf.length === 0){
do{
var uchar = this.it.next();
if(!uchar){
break;
}
cc = uchar.getCanonicalClass();
var inspt = this.resBuf.length;
if(cc !== 0){
for(; inspt > 0; --inspt){
var uchar2 = this.resBuf[inspt - 1];
var cc2 = uchar2.getCanonicalClass();
if(cc2 <= cc){
break;
}
}
}
this.resBuf.splice(inspt, 0, uchar);
} while(cc !== 0);
}
return this.resBuf.shift();
};
var CompIterator = function(it){
this.it = it;
this.procBuf = [];
this.resBuf = [];
this.lastClass = null;
};
CompIterator.prototype.next = function(){
while(this.resBuf.length === 0){
var uchar = this.it.next();
if(!uchar){
this.resBuf = this.procBuf;
this.procBuf = [];
break;
}
if(this.procBuf.length === 0){
this.lastClass = uchar.getCanonicalClass();
this.procBuf.push(uchar);
} else {
var starter = this.procBuf[0];
var composite = starter.getComposite(uchar);
var cc = uchar.getCanonicalClass();
if(!!composite && (this.lastClass < cc || this.lastClass === 0)){
this.procBuf[0] = composite;
} else {
if(cc === 0){
this.resBuf = this.procBuf;
this.procBuf = [];
}
this.lastClass = cc;
this.procBuf.push(uchar);
}
}
}
return this.resBuf.shift();
};
var createIterator = function(mode, str){
switch(mode){
case "NFD":
return new DecompIterator(new RecursDecompIterator(new UCharIterator(str), true));
case "NFKD":
return new DecompIterator(new RecursDecompIterator(new UCharIterator(str), false));
case "NFC":
return new CompIterator(new DecompIterator(new RecursDecompIterator(new UCharIterator(str), true)));
case "NFKC":
return new CompIterator(new DecompIterator(new RecursDecompIterator(new UCharIterator(str), false)));
}
throw mode + " is invalid";
};
var normalize = function(mode, str){
var it = createIterator(mode, str);
var ret = "";
var uchar;
while(!!(uchar = it.next())){
ret += uchar.toString();
}
return ret;
};
/* API functions */
function nfd(str){
return normalize("NFD", str);
}
function nfkd(str){
return normalize("NFKD", str);
}
function nfc(str){
return normalize("NFC", str);
}
function nfkc(str){
return normalize("NFKC", str);
}
/* Unicode data */
UChar.udata={
0:{60:[,,{824:8814}],61:[,,{824:8800}],62:[,,{824:8815}],65:[,,{768:192,769:193,770:194,771:195,772:256,774:258,775:550,776:196,777:7842,778:197,780:461,783:512,785:514,803:7840,805:7680,808:260}],66:[,,{775:7682,803:7684,817:7686}],67:[,,{769:262,770:264,775:266,780:268,807:199}],68:[,,{775:7690,780:270,803:7692,807:7696,813:7698,817:7694}],69:[,,{768:200,769:201,770:202,771:7868,772:274,774:276,775:278,776:203,777:7866,780:282,783:516,785:518,803:7864,807:552,808:280,813:7704,816:7706}],70:[,,{775:7710}],71:[,,{769:500,770:284,772:7712,774:286,775:288,780:486,807:290}],72:[,,{770:292,775:7714,776:7718,780:542,803:7716,807:7720,814:7722}],73:[,,{768:204,769:205,770:206,771:296,772:298,774:300,775:304,776:207,777:7880,780:463,783:520,785:522,803:7882,808:302,816:7724}],74:[,,{770:308}],75:[,,{769:7728,780:488,803:7730,807:310,817:7732}],76:[,,{769:313,780:317,803:7734,807:315,813:7740,817:7738}],77:[,,{769:7742,775:7744,803:7746}],78:[,,{768:504,769:323,771:209,775:7748,780:327,803:7750,807:325,813:7754,817:7752}],79:[,,{768:210,769:211,770:212,771:213,772:332,774:334,775:558,776:214,777:7886,779:336,780:465,783:524,785:526,795:416,803:7884,808:490}],80:[,,{769:7764,775:7766}],82:[,,{769:340,775:7768,780:344,783:528,785:530,803:7770,807:342,817:7774}],83:[,,{769:346,770:348,775:7776,780:352,803:7778,806:536,807:350}],84:[,,{775:7786,780:356,803:7788,806:538,807:354,813:7792,817:7790}],85:[,,{768:217,769:218,770:219,771:360,772:362,774:364,776:220,777:7910,778:366,779:368,780:467,783:532,785:534,795:431,803:7908,804:7794,808:370,813:7798,816:7796}],86:[,,{771:7804,803:7806}],87:[,,{768:7808,769:7810,770:372,775:7814,776:7812,803:7816}],88:[,,{775:7818,776:7820}],89:[,,{768:7922,769:221,770:374,771:7928,772:562,775:7822,776:376,777:7926,803:7924}],90:[,,{769:377,770:7824,775:379,780:381,803:7826,817:7828}],97:[,,{768:224,769:225,770:226,771:227,772:257,774:259,775:551,776:228,777:7843,778:229,780:462,783:513,785:515,803:7841,805:7681,808:261}],98:[,,{775:7683,803:7685,817:7687}],99:[,,{769:263,770:265,775:267,780:269,807:231}],100:[,,{775:7691,780:271,803:7693,807:7697,813:7699,817:7695}],101:[,,{768:232,769:233,770:234,771:7869,772:275,774:277,775:279,776:235,777:7867,780:283,783:517,785:519,803:7865,807:553,808:281,813:7705,816:7707}],102:[,,{775:7711}],103:[,,{769:501,770:285,772:7713,774:287,775:289,780:487,807:291}],104:[,,{770:293,775:7715,776:7719,780:543,803:7717,807:7721,814:7723,817:7830}],105:[,,{768:236,769:237,770:238,771:297,772:299,774:301,776:239,777:7881,780:464,783:521,785:523,803:7883,808:303,816:7725}],106:[,,{770:309,780:496}],107:[,,{769:7729,780:489,803:7731,807:311,817:7733}],108:[,,{769:314,780:318,803:7735,807:316,813:7741,817:7739}],109:[,,{769:7743,775:7745,803:7747}],110:[,,{768:505,769:324,771:241,775:7749,780:328,803:7751,807:326,813:7755,817:7753}],111:[,,{768:242,769:243,770:244,771:245,772:333,774:335,775:559,776:246,777:7887,779:337,780:466,783:525,785:527,795:417,803:7885,808:491}],112:[,,{769:7765,775:7767}],114:[,,{769:341,775:7769,780:345,783:529,785:531,803:7771,807:343,817:7775}],115:[,,{769:347,770:349,775:7777,780:353,803:7779,806:537,807:351}],116:[,,{775:7787,776:7831,780:357,803:7789,806:539,807:355,813:7793,817:7791}],117:[,,{768:249,769:250,770:251,771:361,772:363,774:365,776:252,777:7911,778:367,779:369,780:468,783:533,785:535,795:432,803:7909,804:7795,808:371,813:7799,816:7797}],118:[,,{771:7805,803:7807}],119:[,,{768:7809,769:7811,770:373,775:7815,776:7813,778:7832,803:7817}],120:[,,{775:7819,776:7821}],121:[,,{768:7923,769:253,770:375,771:7929,772:563,775:7823,776:255,777:7927,778:7833,803:7925}],122:[,,{769:378,770:7825,775:380,780:382,803:7827,817:7829}],160:[[32],256],168:[[32,776],256,{768:8173,769:901,834:8129}],170:[[97],256],175:[[32,772],256],178:[[50],256],179:[[51],256],180:[[32,769],256],181:[[956],256],184:[[32,807],256],185:[[49],256],186:[[111],256],188:[[49,8260,52],256],189:[[49,8260,50],256],190:[[51,8260,52],256],192:[[65,768]],193:[[65,769]],194:[[65,770],,{768:7846,769:7844,771:7850,777:7848}],195:[[65,771]],196:[[65,776],,{772:478}],197:[[65,778],,{769:506}],198:[,,{769:508,772:482}],199:[[67,807],,{769:7688}],200:[[69,768]],201:[[69,769]],202:[[69,770],,{768:7872,769:7870,771:7876,777:7874}],203:[[69,776]],204:[[73,768]],205:[[73,769]],206:[[73,770]],207:[[73,776],,{769:7726}],209:[[78,771]],210:[[79,768]],211:[[79,769]],212:[[79,770],,{768:7890,769:7888,771:7894,777:7892}],213:[[79,771],,{769:7756,772:556,776:7758}],214:[[79,776],,{772:554}],216:[,,{769:510}],217:[[85,768]],218:[[85,769]],219:[[85,770]],220:[[85,776],,{768:475,769:471,772:469,780:473}],221:[[89,769]],224:[[97,768]],225:[[97,769]],226:[[97,770],,{768:7847,769:7845,771:7851,777:7849}],227:[[97,771]],228:[[97,776],,{772:479}],229:[[97,778],,{769:507}],230:[,,{769:509,772:483}],231:[[99,807],,{769:7689}],232:[[101,768]],233:[[101,769]],234:[[101,770],,{768:7873,769:7871,771:7877,777:7875}],235:[[101,776]],236:[[105,768]],237:[[105,769]],238:[[105,770]],239:[[105,776],,{769:7727}],241:[[110,771]],242:[[111,768]],243:[[111,769]],244:[[111,770],,{768:7891,769:7889,771:7895,777:7893}],245:[[111,771],,{769:7757,772:557,776:7759}],246:[[111,776],,{772:555}],248:[,,{769:511}],249:[[117,768]],250:[[117,769]],251:[[117,770]],252:[[117,776],,{768:476,769:472,772:470,780:474}],253:[[121,769]],255:[[121,776]]},
256:{256:[[65,772]],257:[[97,772]],258:[[65,774],,{768:7856,769:7854,771:7860,777:7858}],259:[[97,774],,{768:7857,769:7855,771:7861,777:7859}],260:[[65,808]],261:[[97,808]],262:[[67,769]],263:[[99,769]],264:[[67,770]],265:[[99,770]],266:[[67,775]],267:[[99,775]],268:[[67,780]],269:[[99,780]],270:[[68,780]],271:[[100,780]],274:[[69,772],,{768:7700,769:7702}],275:[[101,772],,{768:7701,769:7703}],276:[[69,774]],277:[[101,774]],278:[[69,775]],279:[[101,775]],280:[[69,808]],281:[[101,808]],282:[[69,780]],283:[[101,780]],284:[[71,770]],285:[[103,770]],286:[[71,774]],287:[[103,774]],288:[[71,775]],289:[[103,775]],290:[[71,807]],291:[[103,807]],292:[[72,770]],293:[[104,770]],296:[[73,771]],297:[[105,771]],298:[[73,772]],299:[[105,772]],300:[[73,774]],301:[[105,774]],302:[[73,808]],303:[[105,808]],304:[[73,775]],306:[[73,74],256],307:[[105,106],256],308:[[74,770]],309:[[106,770]],310:[[75,807]],311:[[107,807]],313:[[76,769]],314:[[108,769]],315:[[76,807]],316:[[108,807]],317:[[76,780]],318:[[108,780]],319:[[76,183],256],320:[[108,183],256],323:[[78,769]],324:[[110,769]],325:[[78,807]],326:[[110,807]],327:[[78,780]],328:[[110,780]],329:[[700,110],256],332:[[79,772],,{768:7760,769:7762}],333:[[111,772],,{768:7761,769:7763}],334:[[79,774]],335:[[111,774]],336:[[79,779]],337:[[111,779]],340:[[82,769]],341:[[114,769]],342:[[82,807]],343:[[114,807]],344:[[82,780]],345:[[114,780]],346:[[83,769],,{775:7780}],347:[[115,769],,{775:7781}],348:[[83,770]],349:[[115,770]],350:[[83,807]],351:[[115,807]],352:[[83,780],,{775:7782}],353:[[115,780],,{775:7783}],354:[[84,807]],355:[[116,807]],356:[[84,780]],357:[[116,780]],360:[[85,771],,{769:7800}],361:[[117,771],,{769:7801}],362:[[85,772],,{776:7802}],363:[[117,772],,{776:7803}],364:[[85,774]],365:[[117,774]],366:[[85,778]],367:[[117,778]],368:[[85,779]],369:[[117,779]],370:[[85,808]],371:[[117,808]],372:[[87,770]],373:[[119,770]],374:[[89,770]],375:[[121,770]],376:[[89,776]],377:[[90,769]],378:[[122,769]],379:[[90,775]],380:[[122,775]],381:[[90,780]],382:[[122,780]],383:[[115],256,{775:7835}],416:[[79,795],,{768:7900,769:7898,771:7904,777:7902,803:7906}],417:[[111,795],,{768:7901,769:7899,771:7905,777:7903,803:7907}],431:[[85,795],,{768:7914,769:7912,771:7918,777:7916,803:7920}],432:[[117,795],,{768:7915,769:7913,771:7919,777:7917,803:7921}],439:[,,{780:494}],452:[[68,381],256],453:[[68,382],256],454:[[100,382],256],455:[[76,74],256],456:[[76,106],256],457:[[108,106],256],458:[[78,74],256],459:[[78,106],256],460:[[110,106],256],461:[[65,780]],462:[[97,780]],463:[[73,780]],464:[[105,780]],465:[[79,780]],466:[[111,780]],467:[[85,780]],468:[[117,780]],469:[[220,772]],470:[[252,772]],471:[[220,769]],472:[[252,769]],473:[[220,780]],474:[[252,780]],475:[[220,768]],476:[[252,768]],478:[[196,772]],479:[[228,772]],480:[[550,772]],481:[[551,772]],482:[[198,772]],483:[[230,772]],486:[[71,780]],487:[[103,780]],488:[[75,780]],489:[[107,780]],490:[[79,808],,{772:492}],491:[[111,808],,{772:493}],492:[[490,772]],493:[[491,772]],494:[[439,780]],495:[[658,780]],496:[[106,780]],497:[[68,90],256],498:[[68,122],256],499:[[100,122],256],500:[[71,769]],501:[[103,769]],504:[[78,768]],505:[[110,768]],506:[[197,769]],507:[[229,769]],508:[[198,769]],509:[[230,769]],510:[[216,769]],511:[[248,769]],66045:[,220]},
512:{512:[[65,783]],513:[[97,783]],514:[[65,785]],515:[[97,785]],516:[[69,783]],517:[[101,783]],518:[[69,785]],519:[[101,785]],520:[[73,783]],521:[[105,783]],522:[[73,785]],523:[[105,785]],524:[[79,783]],525:[[111,783]],526:[[79,785]],527:[[111,785]],528:[[82,783]],529:[[114,783]],530:[[82,785]],531:[[114,785]],532:[[85,783]],533:[[117,783]],534:[[85,785]],535:[[117,785]],536:[[83,806]],537:[[115,806]],538:[[84,806]],539:[[116,806]],542:[[72,780]],543:[[104,780]],550:[[65,775],,{772:480}],551:[[97,775],,{772:481}],552:[[69,807],,{774:7708}],553:[[101,807],,{774:7709}],554:[[214,772]],555:[[246,772]],556:[[213,772]],557:[[245,772]],558:[[79,775],,{772:560}],559:[[111,775],,{772:561}],560:[[558,772]],561:[[559,772]],562:[[89,772]],563:[[121,772]],658:[,,{780:495}],688:[[104],256],689:[[614],256],690:[[106],256],691:[[114],256],692:[[633],256],693:[[635],256],694:[[641],256],695:[[119],256],696:[[121],256],728:[[32,774],256],729:[[32,775],256],730:[[32,778],256],731:[[32,808],256],732:[[32,771],256],733:[[32,779],256],736:[[611],256],737:[[108],256],738:[[115],256],739:[[120],256],740:[[661],256],66272:[,220]},
768:{768:[,230],769:[,230],770:[,230],771:[,230],772:[,230],773:[,230],774:[,230],775:[,230],776:[,230,{769:836}],777:[,230],778:[,230],779:[,230],780:[,230],781:[,230],782:[,230],783:[,230],784:[,230],785:[,230],786:[,230],787:[,230],788:[,230],789:[,232],790:[,220],791:[,220],792:[,220],793:[,220],794:[,232],795:[,216],796:[,220],797:[,220],798:[,220],799:[,220],800:[,220],801:[,202],802:[,202],803:[,220],804:[,220],805:[,220],806:[,220],807:[,202],808:[,202],809:[,220],810:[,220],811:[,220],812:[,220],813:[,220],814:[,220],815:[,220],816:[,220],817:[,220],818:[,220],819:[,220],820:[,1],821:[,1],822:[,1],823:[,1],824:[,1],825:[,220],826:[,220],827:[,220],828:[,220],829:[,230],830:[,230],831:[,230],832:[[768],230],833:[[769],230],834:[,230],835:[[787],230],836:[[776,769],230],837:[,240],838:[,230],839:[,220],840:[,220],841:[,220],842:[,230],843:[,230],844:[,230],845:[,220],846:[,220],848:[,230],849:[,230],850:[,230],851:[,220],852:[,220],853:[,220],854:[,220],855:[,230],856:[,232],857:[,220],858:[,220],859:[,230],860:[,233],861:[,234],862:[,234],863:[,233],864:[,234],865:[,234],866:[,233],867:[,230],868:[,230],869:[,230],870:[,230],871:[,230],872:[,230],873:[,230],874:[,230],875:[,230],876:[,230],877:[,230],878:[,230],879:[,230],884:[[697]],890:[[32,837],256],894:[[59]],900:[[32,769],256],901:[[168,769]],902:[[913,769]],903:[[183]],904:[[917,769]],905:[[919,769]],906:[[921,769]],908:[[927,769]],910:[[933,769]],911:[[937,769]],912:[[970,769]],913:[,,{768:8122,769:902,772:8121,774:8120,787:7944,788:7945,837:8124}],917:[,,{768:8136,769:904,787:7960,788:7961}],919:[,,{768:8138,769:905,787:7976,788:7977,837:8140}],921:[,,{768:8154,769:906,772:8153,774:8152,776:938,787:7992,788:7993}],927:[,,{768:8184,769:908,787:8008,788:8009}],929:[,,{788:8172}],933:[,,{768:8170,769:910,772:8169,774:8168,776:939,788:8025}],937:[,,{768:8186,769:911,787:8040,788:8041,837:8188}],938:[[921,776]],939:[[933,776]],940:[[945,769],,{837:8116}],941:[[949,769]],942:[[951,769],,{837:8132}],943:[[953,769]],944:[[971,769]],945:[,,{768:8048,769:940,772:8113,774:8112,787:7936,788:7937,834:8118,837:8115}],949:[,,{768:8050,769:941,787:7952,788:7953}],951:[,,{768:8052,769:942,787:7968,788:7969,834:8134,837:8131}],953:[,,{768:8054,769:943,772:8145,774:8144,776:970,787:7984,788:7985,834:8150}],959:[,,{768:8056,769:972,787:8000,788:8001}],961:[,,{787:8164,788:8165}],965:[,,{768:8058,769:973,772:8161,774:8160,776:971,787:8016,788:8017,834:8166}],969:[,,{768:8060,769:974,787:8032,788:8033,834:8182,837:8179}],970:[[953,776],,{768:8146,769:912,834:8151}],971:[[965,776],,{768:8162,769:944,834:8167}],972:[[959,769]],973:[[965,769]],974:[[969,769],,{837:8180}],976:[[946],256],977:[[952],256],978:[[933],256,{769:979,776:980}],979:[[978,769]],980:[[978,776]],981:[[966],256],982:[[960],256],1008:[[954],256],1009:[[961],256],1010:[[962],256],1012:[[920],256],1013:[[949],256],1017:[[931],256],66422:[,230],66423:[,230],66424:[,230],66425:[,230],66426:[,230]},
1024:{1024:[[1045,768]],1025:[[1045,776]],1027:[[1043,769]],1030:[,,{776:1031}],1031:[[1030,776]],1036:[[1050,769]],1037:[[1048,768]],1038:[[1059,774]],1040:[,,{774:1232,776:1234}],1043:[,,{769:1027}],1045:[,,{768:1024,774:1238,776:1025}],1046:[,,{774:1217,776:1244}],1047:[,,{776:1246}],1048:[,,{768:1037,772:1250,774:1049,776:1252}],1049:[[1048,774]],1050:[,,{769:1036}],1054:[,,{776:1254}],1059:[,,{772:1262,774:1038,776:1264,779:1266}],1063:[,,{776:1268}],1067:[,,{776:1272}],1069:[,,{776:1260}],1072:[,,{774:1233,776:1235}],1075:[,,{769:1107}],1077:[,,{768:1104,774:1239,776:1105}],1078:[,,{774:1218,776:1245}],1079:[,,{776:1247}],1080:[,,{768:1117,772:1251,774:1081,776:1253}],1081:[[1080,774]],1082:[,,{769:1116}],1086:[,,{776:1255}],1091:[,,{772:1263,774:1118,776:1265,779:1267}],1095:[,,{776:1269}],1099:[,,{776:1273}],1101:[,,{776:1261}],1104:[[1077,768]],1105:[[1077,776]],1107:[[1075,769]],1110:[,,{776:1111}],1111:[[1110,776]],1116:[[1082,769]],1117:[[1080,768]],1118:[[1091,774]],1140:[,,{783:1142}],1141:[,,{783:1143}],1142:[[1140,783]],1143:[[1141,783]],1155:[,230],1156:[,230],1157:[,230],1158:[,230],1159:[,230],1217:[[1046,774]],1218:[[1078,774]],1232:[[1040,774]],1233:[[1072,774]],1234:[[1040,776]],1235:[[1072,776]],1238:[[1045,774]],1239:[[1077,774]],1240:[,,{776:1242}],1241:[,,{776:1243}],1242:[[1240,776]],1243:[[1241,776]],1244:[[1046,776]],1245:[[1078,776]],1246:[[1047,776]],1247:[[1079,776]],1250:[[1048,772]],1251:[[1080,772]],1252:[[1048,776]],1253:[[1080,776]],1254:[[1054,776]],1255:[[1086,776]],1256:[,,{776:1258}],1257:[,,{776:1259}],1258:[[1256,776]],1259:[[1257,776]],1260:[[1069,776]],1261:[[1101,776]],1262:[[1059,772]],1263:[[1091,772]],1264:[[1059,776]],1265:[[1091,776]],1266:[[1059,779]],1267:[[1091,779]],1268:[[1063,776]],1269:[[1095,776]],1272:[[1067,776]],1273:[[1099,776]]},
1280:{1415:[[1381,1410],256],1425:[,220],1426:[,230],1427:[,230],1428:[,230],1429:[,230],1430:[,220],1431:[,230],1432:[,230],1433:[,230],1434:[,222],1435:[,220],1436:[,230],1437:[,230],1438:[,230],1439:[,230],1440:[,230],1441:[,230],1442:[,220],1443:[,220],1444:[,220],1445:[,220],1446:[,220],1447:[,220],1448:[,230],1449:[,230],1450:[,220],1451:[,230],1452:[,230],1453:[,222],1454:[,228],1455:[,230],1456:[,10],1457:[,11],1458:[,12],1459:[,13],1460:[,14],1461:[,15],1462:[,16],1463:[,17],1464:[,18],1465:[,19],1466:[,19],1467:[,20],1468:[,21],1469:[,22],1471:[,23],1473:[,24],1474:[,25],1476:[,230],1477:[,220],1479:[,18]},
1536:{1552:[,230],1553:[,230],1554:[,230],1555:[,230],1556:[,230],1557:[,230],1558:[,230],1559:[,230],1560:[,30],1561:[,31],1562:[,32],1570:[[1575,1619]],1571:[[1575,1620]],1572:[[1608,1620]],1573:[[1575,1621]],1574:[[1610,1620]],1575:[,,{1619:1570,1620:1571,1621:1573}],1608:[,,{1620:1572}],1610:[,,{1620:1574}],1611:[,27],1612:[,28],1613:[,29],1614:[,30],1615:[,31],1616:[,32],1617:[,33],1618:[,34],1619:[,230],1620:[,230],1621:[,220],1622:[,220],1623:[,230],1624:[,230],1625:[,230],1626:[,230],1627:[,230],1628:[,220],1629:[,230],1630:[,230],1631:[,220],1648:[,35],1653:[[1575,1652],256],1654:[[1608,1652],256],1655:[[1735,1652],256],1656:[[1610,1652],256],1728:[[1749,1620]],1729:[,,{1620:1730}],1730:[[1729,1620]],1746:[,,{1620:1747}],1747:[[1746,1620]],1749:[,,{1620:1728}],1750:[,230],1751:[,230],1752:[,230],1753:[,230],1754:[,230],1755:[,230],1756:[,230],1759:[,230],1760:[,230],1761:[,230],1762:[,230],1763:[,220],1764:[,230],1767:[,230],1768:[,230],1770:[,220],1771:[,230],1772:[,230],1773:[,220]},
1792:{1809:[,36],1840:[,230],1841:[,220],1842:[,230],1843:[,230],1844:[,220],1845:[,230],1846:[,230],1847:[,220],1848:[,220],1849:[,220],1850:[,230],1851:[,220],1852:[,220],1853:[,230],1854:[,220],1855:[,230],1856:[,230],1857:[,230],1858:[,220],1859:[,230],1860:[,220],1861:[,230],1862:[,220],1863:[,230],1864:[,220],1865:[,230],1866:[,230],2027:[,230],2028:[,230],2029:[,230],2030:[,230],2031:[,230],2032:[,230],2033:[,230],2034:[,220],2035:[,230]},
2048:{2070:[,230],2071:[,230],2072:[,230],2073:[,230],2075:[,230],2076:[,230],2077:[,230],2078:[,230],2079:[,230],2080:[,230],2081:[,230],2082:[,230],2083:[,230],2085:[,230],2086:[,230],2087:[,230],2089:[,230],2090:[,230],2091:[,230],2092:[,230],2093:[,230],2137:[,220],2138:[,220],2139:[,220],2276:[,230],2277:[,230],2278:[,220],2279:[,230],2280:[,230],2281:[,220],2282:[,230],2283:[,230],2284:[,230],2285:[,220],2286:[,220],2287:[,220],2288:[,27],2289:[,28],2290:[,29],2291:[,230],2292:[,230],2293:[,230],2294:[,220],2295:[,230],2296:[,230],2297:[,220],2298:[,220],2299:[,230],2300:[,230],2301:[,230],2302:[,230],2303:[,230]},
2304:{2344:[,,{2364:2345}],2345:[[2344,2364]],2352:[,,{2364:2353}],2353:[[2352,2364]],2355:[,,{2364:2356}],2356:[[2355,2364]],2364:[,7],2381:[,9],2385:[,230],2386:[,220],2387:[,230],2388:[,230],2392:[[2325,2364],512],2393:[[2326,2364],512],2394:[[2327,2364],512],2395:[[2332,2364],512],2396:[[2337,2364],512],2397:[[2338,2364],512],2398:[[2347,2364],512],2399:[[2351,2364],512],2492:[,7],2503:[,,{2494:2507,2519:2508}],2507:[[2503,2494]],2508:[[2503,2519]],2509:[,9],2524:[[2465,2492],512],2525:[[2466,2492],512],2527:[[2479,2492],512]},
2560:{2611:[[2610,2620],512],2614:[[2616,2620],512],2620:[,7],2637:[,9],2649:[[2582,2620],512],2650:[[2583,2620],512],2651:[[2588,2620],512],2654:[[2603,2620],512],2748:[,7],2765:[,9],68109:[,220],68111:[,230],68152:[,230],68153:[,1],68154:[,220],68159:[,9],68325:[,230],68326:[,220]},
2816:{2876:[,7],2887:[,,{2878:2891,2902:2888,2903:2892}],2888:[[2887,2902]],2891:[[2887,2878]],2892:[[2887,2903]],2893:[,9],2908:[[2849,2876],512],2909:[[2850,2876],512],2962:[,,{3031:2964}],2964:[[2962,3031]],3014:[,,{3006:3018,3031:3020}],3015:[,,{3006:3019}],3018:[[3014,3006]],3019:[[3015,3006]],3020:[[3014,3031]],3021:[,9]},
3072:{3142:[,,{3158:3144}],3144:[[3142,3158]],3149:[,9],3157:[,84],3158:[,91],3260:[,7],3263:[,,{3285:3264}],3264:[[3263,3285]],3270:[,,{3266:3274,3285:3271,3286:3272}],3271:[[3270,3285]],3272:[[3270,3286]],3274:[[3270,3266],,{3285:3275}],3275:[[3274,3285]],3277:[,9]},
3328:{3398:[,,{3390:3402,3415:3404}],3399:[,,{3390:3403}],3402:[[3398,3390]],3403:[[3399,3390]],3404:[[3398,3415]],3405:[,9],3530:[,9],3545:[,,{3530:3546,3535:3548,3551:3550}],3546:[[3545,3530]],3548:[[3545,3535],,{3530:3549}],3549:[[3548,3530]],3550:[[3545,3551]]},
3584:{3635:[[3661,3634],256],3640:[,103],3641:[,103],3642:[,9],3656:[,107],3657:[,107],3658:[,107],3659:[,107],3763:[[3789,3762],256],3768:[,118],3769:[,118],3784:[,122],3785:[,122],3786:[,122],3787:[,122],3804:[[3755,3737],256],3805:[[3755,3745],256]},
3840:{3852:[[3851],256],3864:[,220],3865:[,220],3893:[,220],3895:[,220],3897:[,216],3907:[[3906,4023],512],3917:[[3916,4023],512],3922:[[3921,4023],512],3927:[[3926,4023],512],3932:[[3931,4023],512],3945:[[3904,4021],512],3953:[,129],3954:[,130],3955:[[3953,3954],512],3956:[,132],3957:[[3953,3956],512],3958:[[4018,3968],512],3959:[[4018,3969],256],3960:[[4019,3968],512],3961:[[4019,3969],256],3962:[,130],3963:[,130],3964:[,130],3965:[,130],3968:[,130],3969:[[3953,3968],512],3970:[,230],3971:[,230],3972:[,9],3974:[,230],3975:[,230],3987:[[3986,4023],512],3997:[[3996,4023],512],4002:[[4001,4023],512],4007:[[4006,4023],512],4012:[[4011,4023],512],4025:[[3984,4021],512],4038:[,220]},
4096:{4133:[,,{4142:4134}],4134:[[4133,4142]],4151:[,7],4153:[,9],4154:[,9],4237:[,220],4348:[[4316],256],69702:[,9],69759:[,9],69785:[,,{69818:69786}],69786:[[69785,69818]],69787:[,,{69818:69788}],69788:[[69787,69818]],69797:[,,{69818:69803}],69803:[[69797,69818]],69817:[,9],69818:[,7]},
4352:{69888:[,230],69889:[,230],69890:[,230],69934:[[69937,69927]],69935:[[69938,69927]],69937:[,,{69927:69934}],69938:[,,{69927:69935}],69939:[,9],69940:[,9],70003:[,7],70080:[,9]},
4608:{70197:[,9],70198:[,7],70377:[,7],70378:[,9]},
4864:{4957:[,230],4958:[,230],4959:[,230],70460:[,7],70471:[,,{70462:70475,70487:70476}],70475:[[70471,70462]],70476:[[70471,70487]],70477:[,9],70502:[,230],70503:[,230],70504:[,230],70505:[,230],70506:[,230],70507:[,230],70508:[,230],70512:[,230],70513:[,230],70514:[,230],70515:[,230],70516:[,230]},
5120:{70841:[,,{70832:70844,70842:70843,70845:70846}],70843:[[70841,70842]],70844:[[70841,70832]],70846:[[70841,70845]],70850:[,9],70851:[,7]},
5376:{71096:[,,{71087:71098}],71097:[,,{71087:71099}],71098:[[71096,71087]],71099:[[71097,71087]],71103:[,9],71104:[,7]},
5632:{71231:[,9],71350:[,9],71351:[,7]},
5888:{5908:[,9],5940:[,9],6098:[,9],6109:[,230]},
6144:{6313:[,228]},
6400:{6457:[,222],6458:[,230],6459:[,220]},
6656:{6679:[,230],6680:[,220],6752:[,9],6773:[,230],6774:[,230],6775:[,230],6776:[,230],6777:[,230],6778:[,230],6779:[,230],6780:[,230],6783:[,220],6832:[,230],6833:[,230],6834:[,230],6835:[,230],6836:[,230],6837:[,220],6838:[,220],6839:[,220],6840:[,220],6841:[,220],6842:[,220],6843:[,230],6844:[,230],6845:[,220]},
6912:{6917:[,,{6965:6918}],6918:[[6917,6965]],6919:[,,{6965:6920}],6920:[[6919,6965]],6921:[,,{6965:6922}],6922:[[6921,6965]],6923:[,,{6965:6924}],6924:[[6923,6965]],6925:[,,{6965:6926}],6926:[[6925,6965]],6929:[,,{6965:6930}],6930:[[6929,6965]],6964:[,7],6970:[,,{6965:6971}],6971:[[6970,6965]],6972:[,,{6965:6973}],6973:[[6972,6965]],6974:[,,{6965:6976}],6975:[,,{6965:6977}],6976:[[6974,6965]],6977:[[6975,6965]],6978:[,,{6965:6979}],6979:[[6978,6965]],6980:[,9],7019:[,230],7020:[,220],7021:[,230],7022:[,230],7023:[,230],7024:[,230],7025:[,230],7026:[,230],7027:[,230],7082:[,9],7083:[,9],7142:[,7],7154:[,9],7155:[,9]},
7168:{7223:[,7],7376:[,230],7377:[,230],7378:[,230],7380:[,1],7381:[,220],7382:[,220],7383:[,220],7384:[,220],7385:[,220],7386:[,230],7387:[,230],7388:[,220],7389:[,220],7390:[,220],7391:[,220],7392:[,230],7394:[,1],7395:[,1],7396:[,1],7397:[,1],7398:[,1],7399:[,1],7400:[,1],7405:[,220],7412:[,230],7416:[,230],7417:[,230]},
7424:{7468:[[65],256],7469:[[198],256],7470:[[66],256],7472:[[68],256],7473:[[69],256],7474:[[398],256],7475:[[71],256],7476:[[72],256],7477:[[73],256],7478:[[74],256],7479:[[75],256],7480:[[76],256],7481:[[77],256],7482:[[78],256],7484:[[79],256],7485:[[546],256],7486:[[80],256],7487:[[82],256],7488:[[84],256],7489:[[85],256],7490:[[87],256],7491:[[97],256],7492:[[592],256],7493:[[593],256],7494:[[7426],256],7495:[[98],256],7496:[[100],256],7497:[[101],256],7498:[[601],256],7499:[[603],256],7500:[[604],256],7501:[[103],256],7503:[[107],256],7504:[[109],256],7505:[[331],256],7506:[[111],256],7507:[[596],256],7508:[[7446],256],7509:[[7447],256],7510:[[112],256],7511:[[116],256],7512:[[117],256],7513:[[7453],256],7514:[[623],256],7515:[[118],256],7516:[[7461],256],7517:[[946],256],7518:[[947],256],7519:[[948],256],7520:[[966],256],7521:[[967],256],7522:[[105],256],7523:[[114],256],7524:[[117],256],7525:[[118],256],7526:[[946],256],7527:[[947],256],7528:[[961],256],7529:[[966],256],7530:[[967],256],7544:[[1085],256],7579:[[594],256],7580:[[99],256],7581:[[597],256],7582:[[240],256],7583:[[604],256],7584:[[102],256],7585:[[607],256],7586:[[609],256],7587:[[613],256],7588:[[616],256],7589:[[617],256],7590:[[618],256],7591:[[7547],256],7592:[[669],256],7593:[[621],256],7594:[[7557],256],7595:[[671],256],7596:[[625],256],7597:[[624],256],7598:[[626],256],7599:[[627],256],7600:[[628],256],7601:[[629],256],7602:[[632],256],7603:[[642],256],7604:[[643],256],7605:[[427],256],7606:[[649],256],7607:[[650],256],7608:[[7452],256],7609:[[651],256],7610:[[652],256],7611:[[122],256],7612:[[656],256],7613:[[657],256],7614:[[658],256],7615:[[952],256],7616:[,230],7617:[,230],7618:[,220],7619:[,230],7620:[,230],7621:[,230],7622:[,230],7623:[,230],7624:[,230],7625:[,230],7626:[,220],7627:[,230],7628:[,230],7629:[,234],7630:[,214],7631:[,220],7632:[,202],7633:[,230],7634:[,230],7635:[,230],7636:[,230],7637:[,230],7638:[,230],7639:[,230],7640:[,230],7641:[,230],7642:[,230],7643:[,230],7644:[,230],7645:[,230],7646:[,230],7647:[,230],7648:[,230],7649:[,230],7650:[,230],7651:[,230],7652:[,230],7653:[,230],7654:[,230],7655:[,230],7656:[,230],7657:[,230],7658:[,230],7659:[,230],7660:[,230],7661:[,230],7662:[,230],7663:[,230],7664:[,230],7665:[,230],7666:[,230],7667:[,230],7668:[,230],7669:[,230],7676:[,233],7677:[,220],7678:[,230],7679:[,220]},
7680:{7680:[[65,805]],7681:[[97,805]],7682:[[66,775]],7683:[[98,775]],7684:[[66,803]],7685:[[98,803]],7686:[[66,817]],7687:[[98,817]],7688:[[199,769]],7689:[[231,769]],7690:[[68,775]],7691:[[100,775]],7692:[[68,803]],7693:[[100,803]],7694:[[68,817]],7695:[[100,817]],7696:[[68,807]],7697:[[100,807]],7698:[[68,813]],7699:[[100,813]],7700:[[274,768]],7701:[[275,768]],7702:[[274,769]],7703:[[275,769]],7704:[[69,813]],7705:[[101,813]],7706:[[69,816]],7707:[[101,816]],7708:[[552,774]],7709:[[553,774]],7710:[[70,775]],7711:[[102,775]],7712:[[71,772]],7713:[[103,772]],7714:[[72,775]],7715:[[104,775]],7716:[[72,803]],7717:[[104,803]],7718:[[72,776]],7719:[[104,776]],7720:[[72,807]],7721:[[104,807]],7722:[[72,814]],7723:[[104,814]],7724:[[73,816]],7725:[[105,816]],7726:[[207,769]],7727:[[239,769]],7728:[[75,769]],7729:[[107,769]],7730:[[75,803]],7731:[[107,803]],7732:[[75,817]],7733:[[107,817]],7734:[[76,803],,{772:7736}],7735:[[108,803],,{772:7737}],7736:[[7734,772]],7737:[[7735,772]],7738:[[76,817]],7739:[[108,817]],7740:[[76,813]],7741:[[108,813]],7742:[[77,769]],7743:[[109,769]],7744:[[77,775]],7745:[[109,775]],7746:[[77,803]],7747:[[109,803]],7748:[[78,775]],7749:[[110,775]],7750:[[78,803]],7751:[[110,803]],7752:[[78,817]],7753:[[110,817]],7754:[[78,813]],7755:[[110,813]],7756:[[213,769]],7757:[[245,769]],7758:[[213,776]],7759:[[245,776]],7760:[[332,768]],7761:[[333,768]],7762:[[332,769]],7763:[[333,769]],7764:[[80,769]],7765:[[112,769]],7766:[[80,775]],7767:[[112,775]],7768:[[82,775]],7769:[[114,775]],7770:[[82,803],,{772:7772}],7771:[[114,803],,{772:7773}],7772:[[7770,772]],7773:[[7771,772]],7774:[[82,817]],7775:[[114,817]],7776:[[83,775]],7777:[[115,775]],7778:[[83,803],,{775:7784}],7779:[[115,803],,{775:7785}],7780:[[346,775]],7781:[[347,775]],7782:[[352,775]],7783:[[353,775]],7784:[[7778,775]],7785:[[7779,775]],7786:[[84,775]],7787:[[116,775]],7788:[[84,803]],7789:[[116,803]],7790:[[84,817]],7791:[[116,817]],7792:[[84,813]],7793:[[116,813]],7794:[[85,804]],7795:[[117,804]],7796:[[85,816]],7797:[[117,816]],7798:[[85,813]],7799:[[117,813]],7800:[[360,769]],7801:[[361,769]],7802:[[362,776]],7803:[[363,776]],7804:[[86,771]],7805:[[118,771]],7806:[[86,803]],7807:[[118,803]],7808:[[87,768]],7809:[[119,768]],7810:[[87,769]],7811:[[119,769]],7812:[[87,776]],7813:[[119,776]],7814:[[87,775]],7815:[[119,775]],7816:[[87,803]],7817:[[119,803]],7818:[[88,775]],7819:[[120,775]],7820:[[88,776]],7821:[[120,776]],7822:[[89,775]],7823:[[121,775]],7824:[[90,770]],7825:[[122,770]],7826:[[90,803]],7827:[[122,803]],7828:[[90,817]],7829:[[122,817]],7830:[[104,817]],7831:[[116,776]],7832:[[119,778]],7833:[[121,778]],7834:[[97,702],256],7835:[[383,775]],7840:[[65,803],,{770:7852,774:7862}],7841:[[97,803],,{770:7853,774:7863}],7842:[[65,777]],7843:[[97,777]],7844:[[194,769]],7845:[[226,769]],7846:[[194,768]],7847:[[226,768]],7848:[[194,777]],7849:[[226,777]],7850:[[194,771]],7851:[[226,771]],7852:[[7840,770]],7853:[[7841,770]],7854:[[258,769]],7855:[[259,769]],7856:[[258,768]],7857:[[259,768]],7858:[[258,777]],7859:[[259,777]],7860:[[258,771]],7861:[[259,771]],7862:[[7840,774]],7863:[[7841,774]],7864:[[69,803],,{770:7878}],7865:[[101,803],,{770:7879}],7866:[[69,777]],7867:[[101,777]],7868:[[69,771]],7869:[[101,771]],7870:[[202,769]],7871:[[234,769]],7872:[[202,768]],7873:[[234,768]],7874:[[202,777]],7875:[[234,777]],7876:[[202,771]],7877:[[234,771]],7878:[[7864,770]],7879:[[7865,770]],7880:[[73,777]],7881:[[105,777]],7882:[[73,803]],7883:[[105,803]],7884:[[79,803],,{770:7896}],7885:[[111,803],,{770:7897}],7886:[[79,777]],7887:[[111,777]],7888:[[212,769]],7889:[[244,769]],7890:[[212,768]],7891:[[244,768]],7892:[[212,777]],7893:[[244,777]],7894:[[212,771]],7895:[[244,771]],7896:[[7884,770]],7897:[[7885,770]],7898:[[416,769]],7899:[[417,769]],7900:[[416,768]],7901:[[417,768]],7902:[[416,777]],7903:[[417,777]],7904:[[416,771]],7905:[[417,771]],7906:[[416,803]],7907:[[417,803]],7908:[[85,803]],7909:[[117,803]],7910:[[85,777]],7911:[[117,777]],7912:[[431,769]],7913:[[432,769]],7914:[[431,768]],7915:[[432,768]],7916:[[431,777]],7917:[[432,777]],7918:[[431,771]],7919:[[432,771]],7920:[[431,803]],7921:[[432,803]],7922:[[89,768]],7923:[[121,768]],7924:[[89,803]],7925:[[121,803]],7926:[[89,777]],7927:[[121,777]],7928:[[89,771]],7929:[[121,771]]},
7936:{7936:[[945,787],,{768:7938,769:7940,834:7942,837:8064}],7937:[[945,788],,{768:7939,769:7941,834:7943,837:8065}],7938:[[7936,768],,{837:8066}],7939:[[7937,768],,{837:8067}],7940:[[7936,769],,{837:8068}],7941:[[7937,769],,{837:8069}],7942:[[7936,834],,{837:8070}],7943:[[7937,834],,{837:8071}],7944:[[913,787],,{768:7946,769:7948,834:7950,837:8072}],7945:[[913,788],,{768:7947,769:7949,834:7951,837:8073}],7946:[[7944,768],,{837:8074}],7947:[[7945,768],,{837:8075}],7948:[[7944,769],,{837:8076}],7949:[[7945,769],,{837:8077}],7950:[[7944,834],,{837:8078}],7951:[[7945,834],,{837:8079}],7952:[[949,787],,{768:7954,769:7956}],7953:[[949,788],,{768:7955,769:7957}],7954:[[7952,768]],7955:[[7953,768]],7956:[[7952,769]],7957:[[7953,769]],7960:[[917,787],,{768:7962,769:7964}],7961:[[917,788],,{768:7963,769:7965}],7962:[[7960,768]],7963:[[7961,768]],7964:[[7960,769]],7965:[[7961,769]],7968:[[951,787],,{768:7970,769:7972,834:7974,837:8080}],7969:[[951,788],,{768:7971,769:7973,834:7975,837:8081}],7970:[[7968,768],,{837:8082}],7971:[[7969,768],,{837:8083}],7972:[[7968,769],,{837:8084}],7973:[[7969,769],,{837:8085}],7974:[[7968,834],,{837:8086}],7975:[[7969,834],,{837:8087}],7976:[[919,787],,{768:7978,769:7980,834:7982,837:8088}],7977:[[919,788],,{768:7979,769:7981,834:7983,837:8089}],7978:[[7976,768],,{837:8090}],7979:[[7977,768],,{837:8091}],7980:[[7976,769],,{837:8092}],7981:[[7977,769],,{837:8093}],7982:[[7976,834],,{837:8094}],7983:[[7977,834],,{837:8095}],7984:[[953,787],,{768:7986,769:7988,834:7990}],7985:[[953,788],,{768:7987,769:7989,834:7991}],7986:[[7984,768]],7987:[[7985,768]],7988:[[7984,769]],7989:[[7985,769]],7990:[[7984,834]],7991:[[7985,834]],7992:[[921,787],,{768:7994,769:7996,834:7998}],7993:[[921,788],,{768:7995,769:7997,834:7999}],7994:[[7992,768]],7995:[[7993,768]],7996:[[7992,769]],7997:[[7993,769]],7998:[[7992,834]],7999:[[7993,834]],8000:[[959,787],,{768:8002,769:8004}],8001:[[959,788],,{768:8003,769:8005}],8002:[[8000,768]],8003:[[8001,768]],8004:[[8000,769]],8005:[[8001,769]],8008:[[927,787],,{768:8010,769:8012}],8009:[[927,788],,{768:8011,769:8013}],8010:[[8008,768]],8011:[[8009,768]],8012:[[8008,769]],8013:[[8009,769]],8016:[[965,787],,{768:8018,769:8020,834:8022}],8017:[[965,788],,{768:8019,769:8021,834:8023}],8018:[[8016,768]],8019:[[8017,768]],8020:[[8016,769]],8021:[[8017,769]],8022:[[8016,834]],8023:[[8017,834]],8025:[[933,788],,{768:8027,769:8029,834:8031}],8027:[[8025,768]],8029:[[8025,769]],8031:[[8025,834]],8032:[[969,787],,{768:8034,769:8036,834:8038,837:8096}],8033:[[969,788],,{768:8035,769:8037,834:8039,837:8097}],8034:[[8032,768],,{837:8098}],8035:[[8033,768],,{837:8099}],8036:[[8032,769],,{837:8100}],8037:[[8033,769],,{837:8101}],8038:[[8032,834],,{837:8102}],8039:[[8033,834],,{837:8103}],8040:[[937,787],,{768:8042,769:8044,834:8046,837:8104}],8041:[[937,788],,{768:8043,769:8045,834:8047,837:8105}],8042:[[8040,768],,{837:8106}],8043:[[8041,768],,{837:8107}],8044:[[8040,769],,{837:8108}],8045:[[8041,769],,{837:8109}],8046:[[8040,834],,{837:8110}],8047:[[8041,834],,{837:8111}],8048:[[945,768],,{837:8114}],8049:[[940]],8050:[[949,768]],8051:[[941]],8052:[[951,768],,{837:8130}],8053:[[942]],8054:[[953,768]],8055:[[943]],8056:[[959,768]],8057:[[972]],8058:[[965,768]],8059:[[973]],8060:[[969,768],,{837:8178}],8061:[[974]],8064:[[7936,837]],8065:[[7937,837]],8066:[[7938,837]],8067:[[7939,837]],8068:[[7940,837]],8069:[[7941,837]],8070:[[7942,837]],8071:[[7943,837]],8072:[[7944,837]],8073:[[7945,837]],8074:[[7946,837]],8075:[[7947,837]],8076:[[7948,837]],8077:[[7949,837]],8078:[[7950,837]],8079:[[7951,837]],8080:[[7968,837]],8081:[[7969,837]],8082:[[7970,837]],8083:[[7971,837]],8084:[[7972,837]],8085:[[7973,837]],8086:[[7974,837]],8087:[[7975,837]],8088:[[7976,837]],8089:[[7977,837]],8090:[[7978,837]],8091:[[7979,837]],8092:[[7980,837]],8093:[[7981,837]],8094:[[7982,837]],8095:[[7983,837]],8096:[[8032,837]],8097:[[8033,837]],8098:[[8034,837]],8099:[[8035,837]],8100:[[8036,837]],8101:[[8037,837]],8102:[[8038,837]],8103:[[8039,837]],8104:[[8040,837]],8105:[[8041,837]],8106:[[8042,837]],8107:[[8043,837]],8108:[[8044,837]],8109:[[8045,837]],8110:[[8046,837]],8111:[[8047,837]],8112:[[945,774]],8113:[[945,772]],8114:[[8048,837]],8115:[[945,837]],8116:[[940,837]],8118:[[945,834],,{837:8119}],8119:[[8118,837]],8120:[[913,774]],8121:[[913,772]],8122:[[913,768]],8123:[[902]],8124:[[913,837]],8125:[[32,787],256],8126:[[953]],8127:[[32,787],256,{768:8141,769:8142,834:8143}],8128:[[32,834],256],8129:[[168,834]],8130:[[8052,837]],8131:[[951,837]],8132:[[942,837]],8134:[[951,834],,{837:8135}],8135:[[8134,837]],8136:[[917,768]],8137:[[904]],8138:[[919,768]],8139:[[905]],8140:[[919,837]],8141:[[8127,768]],8142:[[8127,769]],8143:[[8127,834]],8144:[[953,774]],8145:[[953,772]],8146:[[970,768]],8147:[[912]],8150:[[953,834]],8151:[[970,834]],8152:[[921,774]],8153:[[921,772]],8154:[[921,768]],8155:[[906]],8157:[[8190,768]],8158:[[8190,769]],8159:[[8190,834]],8160:[[965,774]],8161:[[965,772]],8162:[[971,768]],8163:[[944]],8164:[[961,787]],8165:[[961,788]],8166:[[965,834]],8167:[[971,834]],8168:[[933,774]],8169:[[933,772]],8170:[[933,768]],8171:[[910]],8172:[[929,788]],8173:[[168,768]],8174:[[901]],8175:[[96]],8178:[[8060,837]],8179:[[969,837]],8180:[[974,837]],8182:[[969,834],,{837:8183}],8183:[[8182,837]],8184:[[927,768]],8185:[[908]],8186:[[937,768]],8187:[[911]],8188:[[937,837]],8189:[[180]],8190:[[32,788],256,{768:8157,769:8158,834:8159}]},
8192:{8192:[[8194]],8193:[[8195]],8194:[[32],256],8195:[[32],256],8196:[[32],256],8197:[[32],256],8198:[[32],256],8199:[[32],256],8200:[[32],256],8201:[[32],256],8202:[[32],256],8209:[[8208],256],8215:[[32,819],256],8228:[[46],256],8229:[[46,46],256],8230:[[46,46,46],256],8239:[[32],256],8243:[[8242,8242],256],8244:[[8242,8242,8242],256],8246:[[8245,8245],256],8247:[[8245,8245,8245],256],8252:[[33,33],256],8254:[[32,773],256],8263:[[63,63],256],8264:[[63,33],256],8265:[[33,63],256],8279:[[8242,8242,8242,8242],256],8287:[[32],256],8304:[[48],256],8305:[[105],256],8308:[[52],256],8309:[[53],256],8310:[[54],256],8311:[[55],256],8312:[[56],256],8313:[[57],256],8314:[[43],256],8315:[[8722],256],8316:[[61],256],8317:[[40],256],8318:[[41],256],8319:[[110],256],8320:[[48],256],8321:[[49],256],8322:[[50],256],8323:[[51],256],8324:[[52],256],8325:[[53],256],8326:[[54],256],8327:[[55],256],8328:[[56],256],8329:[[57],256],8330:[[43],256],8331:[[8722],256],8332:[[61],256],8333:[[40],256],8334:[[41],256],8336:[[97],256],8337:[[101],256],8338:[[111],256],8339:[[120],256],8340:[[601],256],8341:[[104],256],8342:[[107],256],8343:[[108],256],8344:[[109],256],8345:[[110],256],8346:[[112],256],8347:[[115],256],8348:[[116],256],8360:[[82,115],256],8400:[,230],8401:[,230],8402:[,1],8403:[,1],8404:[,230],8405:[,230],8406:[,230],8407:[,230],8408:[,1],8409:[,1],8410:[,1],8411:[,230],8412:[,230],8417:[,230],8421:[,1],8422:[,1],8423:[,230],8424:[,220],8425:[,230],8426:[,1],8427:[,1],8428:[,220],8429:[,220],8430:[,220],8431:[,220],8432:[,230]},
8448:{8448:[[97,47,99],256],8449:[[97,47,115],256],8450:[[67],256],8451:[[176,67],256],8453:[[99,47,111],256],8454:[[99,47,117],256],8455:[[400],256],8457:[[176,70],256],8458:[[103],256],8459:[[72],256],8460:[[72],256],8461:[[72],256],8462:[[104],256],8463:[[295],256],8464:[[73],256],8465:[[73],256],8466:[[76],256],8467:[[108],256],8469:[[78],256],8470:[[78,111],256],8473:[[80],256],8474:[[81],256],8475:[[82],256],8476:[[82],256],8477:[[82],256],8480:[[83,77],256],8481:[[84,69,76],256],8482:[[84,77],256],8484:[[90],256],8486:[[937]],8488:[[90],256],8490:[[75]],8491:[[197]],8492:[[66],256],8493:[[67],256],8495:[[101],256],8496:[[69],256],8497:[[70],256],8499:[[77],256],8500:[[111],256],8501:[[1488],256],8502:[[1489],256],8503:[[1490],256],8504:[[1491],256],8505:[[105],256],8507:[[70,65,88],256],8508:[[960],256],8509:[[947],256],8510:[[915],256],8511:[[928],256],8512:[[8721],256],8517:[[68],256],8518:[[100],256],8519:[[101],256],8520:[[105],256],8521:[[106],256],8528:[[49,8260,55],256],8529:[[49,8260,57],256],8530:[[49,8260,49,48],256],8531:[[49,8260,51],256],8532:[[50,8260,51],256],8533:[[49,8260,53],256],8534:[[50,8260,53],256],8535:[[51,8260,53],256],8536:[[52,8260,53],256],8537:[[49,8260,54],256],8538:[[53,8260,54],256],8539:[[49,8260,56],256],8540:[[51,8260,56],256],8541:[[53,8260,56],256],8542:[[55,8260,56],256],8543:[[49,8260],256],8544:[[73],256],8545:[[73,73],256],8546:[[73,73,73],256],8547:[[73,86],256],8548:[[86],256],8549:[[86,73],256],8550:[[86,73,73],256],8551:[[86,73,73,73],256],8552:[[73,88],256],8553:[[88],256],8554:[[88,73],256],8555:[[88,73,73],256],8556:[[76],256],8557:[[67],256],8558:[[68],256],8559:[[77],256],8560:[[105],256],8561:[[105,105],256],8562:[[105,105,105],256],8563:[[105,118],256],8564:[[118],256],8565:[[118,105],256],8566:[[118,105,105],256],8567:[[118,105,105,105],256],8568:[[105,120],256],8569:[[120],256],8570:[[120,105],256],8571:[[120,105,105],256],8572:[[108],256],8573:[[99],256],8574:[[100],256],8575:[[109],256],8585:[[48,8260,51],256],8592:[,,{824:8602}],8594:[,,{824:8603}],8596:[,,{824:8622}],8602:[[8592,824]],8603:[[8594,824]],8622:[[8596,824]],8653:[[8656,824]],8654:[[8660,824]],8655:[[8658,824]],8656:[,,{824:8653}],8658:[,,{824:8655}],8660:[,,{824:8654}]},
8704:{8707:[,,{824:8708}],8708:[[8707,824]],8712:[,,{824:8713}],8713:[[8712,824]],8715:[,,{824:8716}],8716:[[8715,824]],8739:[,,{824:8740}],8740:[[8739,824]],8741:[,,{824:8742}],8742:[[8741,824]],8748:[[8747,8747],256],8749:[[8747,8747,8747],256],8751:[[8750,8750],256],8752:[[8750,8750,8750],256],8764:[,,{824:8769}],8769:[[8764,824]],8771:[,,{824:8772}],8772:[[8771,824]],8773:[,,{824:8775}],8775:[[8773,824]],8776:[,,{824:8777}],8777:[[8776,824]],8781:[,,{824:8813}],8800:[[61,824]],8801:[,,{824:8802}],8802:[[8801,824]],8804:[,,{824:8816}],8805:[,,{824:8817}],8813:[[8781,824]],8814:[[60,824]],8815:[[62,824]],8816:[[8804,824]],8817:[[8805,824]],8818:[,,{824:8820}],8819:[,,{824:8821}],8820:[[8818,824]],8821:[[8819,824]],8822:[,,{824:8824}],8823:[,,{824:8825}],8824:[[8822,824]],8825:[[8823,824]],8826:[,,{824:8832}],8827:[,,{824:8833}],8828:[,,{824:8928}],8829:[,,{824:8929}],8832:[[8826,824]],8833:[[8827,824]],8834:[,,{824:8836}],8835:[,,{824:8837}],8836:[[8834,824]],8837:[[8835,824]],8838:[,,{824:8840}],8839:[,,{824:8841}],8840:[[8838,824]],8841:[[8839,824]],8849:[,,{824:8930}],8850:[,,{824:8931}],8866:[,,{824:8876}],8872:[,,{824:8877}],8873:[,,{824:8878}],8875:[,,{824:8879}],8876:[[8866,824]],8877:[[8872,824]],8878:[[8873,824]],8879:[[8875,824]],8882:[,,{824:8938}],8883:[,,{824:8939}],8884:[,,{824:8940}],8885:[,,{824:8941}],8928:[[8828,824]],8929:[[8829,824]],8930:[[8849,824]],8931:[[8850,824]],8938:[[8882,824]],8939:[[8883,824]],8940:[[8884,824]],8941:[[8885,824]]},
8960:{9001:[[12296]],9002:[[12297]]},
9216:{9312:[[49],256],9313:[[50],256],9314:[[51],256],9315:[[52],256],9316:[[53],256],9317:[[54],256],9318:[[55],256],9319:[[56],256],9320:[[57],256],9321:[[49,48],256],9322:[[49,49],256],9323:[[49,50],256],9324:[[49,51],256],9325:[[49,52],256],9326:[[49,53],256],9327:[[49,54],256],9328:[[49,55],256],9329:[[49,56],256],9330:[[49,57],256],9331:[[50,48],256],9332:[[40,49,41],256],9333:[[40,50,41],256],9334:[[40,51,41],256],9335:[[40,52,41],256],9336:[[40,53,41],256],9337:[[40,54,41],256],9338:[[40,55,41],256],9339:[[40,56,41],256],9340:[[40,57,41],256],9341:[[40,49,48,41],256],9342:[[40,49,49,41],256],9343:[[40,49,50,41],256],9344:[[40,49,51,41],256],9345:[[40,49,52,41],256],9346:[[40,49,53,41],256],9347:[[40,49,54,41],256],9348:[[40,49,55,41],256],9349:[[40,49,56,41],256],9350:[[40,49,57,41],256],9351:[[40,50,48,41],256],9352:[[49,46],256],9353:[[50,46],256],9354:[[51,46],256],9355:[[52,46],256],9356:[[53,46],256],9357:[[54,46],256],9358:[[55,46],256],9359:[[56,46],256],9360:[[57,46],256],9361:[[49,48,46],256],9362:[[49,49,46],256],9363:[[49,50,46],256],9364:[[49,51,46],256],9365:[[49,52,46],256],9366:[[49,53,46],256],9367:[[49,54,46],256],9368:[[49,55,46],256],9369:[[49,56,46],256],9370:[[49,57,46],256],9371:[[50,48,46],256],9372:[[40,97,41],256],9373:[[40,98,41],256],9374:[[40,99,41],256],9375:[[40,100,41],256],9376:[[40,101,41],256],9377:[[40,102,41],256],9378:[[40,103,41],256],9379:[[40,104,41],256],9380:[[40,105,41],256],9381:[[40,106,41],256],9382:[[40,107,41],256],9383:[[40,108,41],256],9384:[[40,109,41],256],9385:[[40,110,41],256],9386:[[40,111,41],256],9387:[[40,112,41],256],9388:[[40,113,41],256],9389:[[40,114,41],256],9390:[[40,115,41],256],9391:[[40,116,41],256],9392:[[40,117,41],256],9393:[[40,118,41],256],9394:[[40,119,41],256],9395:[[40,120,41],256],9396:[[40,121,41],256],9397:[[40,122,41],256],9398:[[65],256],9399:[[66],256],9400:[[67],256],9401:[[68],256],9402:[[69],256],9403:[[70],256],9404:[[71],256],9405:[[72],256],9406:[[73],256],9407:[[74],256],9408:[[75],256],9409:[[76],256],9410:[[77],256],9411:[[78],256],9412:[[79],256],9413:[[80],256],9414:[[81],256],9415:[[82],256],9416:[[83],256],9417:[[84],256],9418:[[85],256],9419:[[86],256],9420:[[87],256],9421:[[88],256],9422:[[89],256],9423:[[90],256],9424:[[97],256],9425:[[98],256],9426:[[99],256],9427:[[100],256],9428:[[101],256],9429:[[102],256],9430:[[103],256],9431:[[104],256],9432:[[105],256],9433:[[106],256],9434:[[107],256],9435:[[108],256],9436:[[109],256],9437:[[110],256],9438:[[111],256],9439:[[112],256],9440:[[113],256],9441:[[114],256],9442:[[115],256],9443:[[116],256],9444:[[117],256],9445:[[118],256],9446:[[119],256],9447:[[120],256],9448:[[121],256],9449:[[122],256],9450:[[48],256]},
10752:{10764:[[8747,8747,8747,8747],256],10868:[[58,58,61],256],10869:[[61,61],256],10870:[[61,61,61],256],10972:[[10973,824],512]},
11264:{11388:[[106],256],11389:[[86],256],11503:[,230],11504:[,230],11505:[,230]},
11520:{11631:[[11617],256],11647:[,9],11744:[,230],11745:[,230],11746:[,230],11747:[,230],11748:[,230],11749:[,2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment