diff --git a/docs/bundle.min.js b/docs/bundle.min.js index 6cfcdaf..47e709d 100644 --- a/docs/bundle.min.js +++ b/docs/bundle.min.js @@ -1,9153 +1,2 @@ -/******/ (function(modules) { // webpackBootstrap -/******/ // The module cache -/******/ var installedModules = {}; -/******/ -/******/ // The require function -/******/ function __webpack_require__(moduleId) { -/******/ -/******/ // Check if module is in cache -/******/ if(installedModules[moduleId]) { -/******/ return installedModules[moduleId].exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = installedModules[moduleId] = { -/******/ i: moduleId, -/******/ l: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); -/******/ -/******/ // Flag the module as loaded -/******/ module.l = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/******/ -/******/ // expose the modules object (__webpack_modules__) -/******/ __webpack_require__.m = modules; -/******/ -/******/ // expose the module cache -/******/ __webpack_require__.c = installedModules; -/******/ -/******/ // define getter function for harmony exports -/******/ __webpack_require__.d = function(exports, name, getter) { -/******/ if(!__webpack_require__.o(exports, name)) { -/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); -/******/ } -/******/ }; -/******/ -/******/ // define __esModule on exports -/******/ __webpack_require__.r = function(exports) { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ -/******/ // create a fake namespace object -/******/ // mode & 1: value is a module id, require it -/******/ // mode & 2: merge all properties of value into the ns -/******/ // mode & 4: return value when already ns object -/******/ // mode & 8|1: behave like require -/******/ __webpack_require__.t = function(value, mode) { -/******/ if(mode & 1) value = __webpack_require__(value); -/******/ if(mode & 8) return value; -/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; -/******/ var ns = Object.create(null); -/******/ __webpack_require__.r(ns); -/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); -/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); -/******/ return ns; -/******/ }; -/******/ -/******/ // getDefaultExport function for compatibility with non-harmony modules -/******/ __webpack_require__.n = function(module) { -/******/ var getter = module && module.__esModule ? -/******/ function getDefault() { return module['default']; } : -/******/ function getModuleExports() { return module; }; -/******/ __webpack_require__.d(getter, 'a', getter); -/******/ return getter; -/******/ }; -/******/ -/******/ // Object.prototype.hasOwnProperty.call -/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; -/******/ -/******/ // __webpack_public_path__ -/******/ __webpack_require__.p = ""; -/******/ -/******/ -/******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 3); -/******/ }) -/************************************************************************/ -/******/ ([ -/* 0 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "A", function() { return isEmpty; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "G", function() { return keys; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "U", function() { return values; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "J", function() { return mapValues; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "I", function() { return map; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "t", function() { return flatten; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "s", function() { return first; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "H", function() { return last; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "u", function() { return forEach; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "E", function() { return isString; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "F", function() { return isUndefined; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "B", function() { return isFunction; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return drop; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "n", function() { return dropRight; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "p", function() { return filter; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "P", function() { return reject; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "N", function() { return pick; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "w", function() { return has; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return contains; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return cloneArr; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return cloneObj; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "q", function() { return find; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "r", function() { return findAll; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "O", function() { return reduce; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return compact; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "T", function() { return uniq; }); -/* unused harmony export partial */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "y", function() { return isArray; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "D", function() { return isRegExp; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "C", function() { return isObject; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "o", function() { return every; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return difference; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Q", function() { return some; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "x", function() { return indexOf; }); -/* unused harmony export sortBy */ -/* unused harmony export zipObject */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return assign; }); -/* unused harmony export assignNoOverwrite */ -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return defaults; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "v", function() { return groupBy; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "K", function() { return merge; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return NOOP; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return IDENTITY; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "L", function() { return packArray; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return PRINT_ERROR; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return PRINT_WARNING; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "z", function() { return isES2015MapSupported; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return applyMixins; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "S", function() { return toFastProperties; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "M", function() { return peek; }); -/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "R", function() { return timer; }); -/* - 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]; - 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 - -/***/ }), -/* 1 */ -/***/ (function(module, exports, __webpack_require__) { - -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", - loc: { begin: this.idx, end: input.length }, - 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, - loc: this.loc(0) - } - } - - RegExpParser.prototype.disjunction = function() { - var alts = [] - var begin = this.idx - - alts.push(this.alternative()) - - while (this.peekChar() === "|") { - this.consumeChar("|") - alts.push(this.alternative()) - } - - return { type: "Disjunction", value: alts, loc: this.loc(begin) } - } - - RegExpParser.prototype.alternative = function() { - var terms = [] - var begin = this.idx - - while (this.isTerm()) { - terms.push(this.term()) - } - - return { type: "Alternative", value: terms, loc: this.loc(begin) } - } - - RegExpParser.prototype.term = function() { - if (this.isAssertion()) { - return this.assertion() - } else { - return this.atom() - } - } - - RegExpParser.prototype.assertion = function() { - var begin = this.idx - switch (this.popChar()) { - case "^": - return { - type: "StartAnchor", - loc: this.loc(begin) - } - case "$": - return { type: "EndAnchor", loc: this.loc(begin) } - // '\b' or '\B' - case "\\": - switch (this.popChar()) { - case "b": - return { - type: "WordBoundary", - loc: this.loc(begin) - } - case "B": - return { - type: "NonWordBoundary", - loc: this.loc(begin) - } - } - // 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, - loc: this.loc(begin) - } - } - // istanbul ignore next - ASSERT_NEVER_REACH_HERE() - } - - RegExpParser.prototype.quantifier = function(isBacktracking) { - var range - var begin = this.idx - 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" - range.loc = this.loc(begin) - return range - } - - RegExpParser.prototype.atom = function() { - var atom - var begin = this.idx - 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) - - atom.loc = this.loc(begin) - - 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++ - } - - RegExpParser.prototype.loc = function(begin) { - return { begin: begin, end: 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.5.0" - } - } -) - - -/***/ }), -/* 2 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -// ESM COMPAT FLAG -__webpack_require__.r(__webpack_exports__); - -// EXPORTS -__webpack_require__.d(__webpack_exports__, "VERSION", function() { return /* reexport */ VERSION; }); -__webpack_require__.d(__webpack_exports__, "CstParser", function() { return /* reexport */ parser_CstParser; }); -__webpack_require__.d(__webpack_exports__, "EmbeddedActionsParser", function() { return /* reexport */ parser_EmbeddedActionsParser; }); -__webpack_require__.d(__webpack_exports__, "ParserDefinitionErrorType", function() { return /* reexport */ ParserDefinitionErrorType; }); -__webpack_require__.d(__webpack_exports__, "EMPTY_ALT", function() { return /* reexport */ EMPTY_ALT; }); -__webpack_require__.d(__webpack_exports__, "Lexer", function() { return /* reexport */ lexer_public_Lexer; }); -__webpack_require__.d(__webpack_exports__, "LexerDefinitionErrorType", function() { return /* reexport */ LexerDefinitionErrorType; }); -__webpack_require__.d(__webpack_exports__, "createToken", function() { return /* reexport */ createToken; }); -__webpack_require__.d(__webpack_exports__, "createTokenInstance", function() { return /* reexport */ createTokenInstance; }); -__webpack_require__.d(__webpack_exports__, "EOF", function() { return /* reexport */ EOF; }); -__webpack_require__.d(__webpack_exports__, "tokenLabel", function() { return /* reexport */ tokenLabel; }); -__webpack_require__.d(__webpack_exports__, "tokenMatcher", function() { return /* reexport */ tokens_public_tokenMatcher; }); -__webpack_require__.d(__webpack_exports__, "tokenName", function() { return /* reexport */ tokenName; }); -__webpack_require__.d(__webpack_exports__, "defaultGrammarResolverErrorProvider", function() { return /* reexport */ defaultGrammarResolverErrorProvider; }); -__webpack_require__.d(__webpack_exports__, "defaultGrammarValidatorErrorProvider", function() { return /* reexport */ defaultGrammarValidatorErrorProvider; }); -__webpack_require__.d(__webpack_exports__, "defaultParserErrorProvider", function() { return /* reexport */ defaultParserErrorProvider; }); -__webpack_require__.d(__webpack_exports__, "EarlyExitException", function() { return /* reexport */ EarlyExitException; }); -__webpack_require__.d(__webpack_exports__, "isRecognitionException", function() { return /* reexport */ isRecognitionException; }); -__webpack_require__.d(__webpack_exports__, "MismatchedTokenException", function() { return /* reexport */ MismatchedTokenException; }); -__webpack_require__.d(__webpack_exports__, "NotAllInputParsedException", function() { return /* reexport */ NotAllInputParsedException; }); -__webpack_require__.d(__webpack_exports__, "NoViableAltException", function() { return /* reexport */ NoViableAltException; }); -__webpack_require__.d(__webpack_exports__, "defaultLexerErrorProvider", function() { return /* reexport */ defaultLexerErrorProvider; }); -__webpack_require__.d(__webpack_exports__, "Alternation", function() { return /* reexport */ gast_public_Alternation; }); -__webpack_require__.d(__webpack_exports__, "Alternative", function() { return /* reexport */ gast_public_Alternative; }); -__webpack_require__.d(__webpack_exports__, "NonTerminal", function() { return /* reexport */ gast_public_NonTerminal; }); -__webpack_require__.d(__webpack_exports__, "Option", function() { return /* reexport */ gast_public_Option; }); -__webpack_require__.d(__webpack_exports__, "Repetition", function() { return /* reexport */ gast_public_Repetition; }); -__webpack_require__.d(__webpack_exports__, "RepetitionMandatory", function() { return /* reexport */ gast_public_RepetitionMandatory; }); -__webpack_require__.d(__webpack_exports__, "RepetitionMandatoryWithSeparator", function() { return /* reexport */ gast_public_RepetitionMandatoryWithSeparator; }); -__webpack_require__.d(__webpack_exports__, "RepetitionWithSeparator", function() { return /* reexport */ gast_public_RepetitionWithSeparator; }); -__webpack_require__.d(__webpack_exports__, "Rule", function() { return /* reexport */ gast_public_Rule; }); -__webpack_require__.d(__webpack_exports__, "Terminal", function() { return /* reexport */ gast_public_Terminal; }); -__webpack_require__.d(__webpack_exports__, "serializeGrammar", function() { return /* reexport */ serializeGrammar; }); -__webpack_require__.d(__webpack_exports__, "serializeProduction", function() { return /* reexport */ serializeProduction; }); -__webpack_require__.d(__webpack_exports__, "GAstVisitor", function() { return /* reexport */ gast_visitor_public_GAstVisitor; }); -__webpack_require__.d(__webpack_exports__, "assignOccurrenceIndices", function() { return /* reexport */ assignOccurrenceIndices; }); -__webpack_require__.d(__webpack_exports__, "resolveGrammar", function() { return /* reexport */ gast_resolver_public_resolveGrammar; }); -__webpack_require__.d(__webpack_exports__, "validateGrammar", function() { return /* reexport */ gast_resolver_public_validateGrammar; }); -__webpack_require__.d(__webpack_exports__, "clearCache", function() { return /* binding */ clearCache; }); -__webpack_require__.d(__webpack_exports__, "createSyntaxDiagramsCode", function() { return /* reexport */ createSyntaxDiagramsCode; }); -__webpack_require__.d(__webpack_exports__, "generateParserFactory", function() { return /* reexport */ generateParserFactory; }); -__webpack_require__.d(__webpack_exports__, "generateParserModule", function() { return /* reexport */ generateParserModule; }); -__webpack_require__.d(__webpack_exports__, "Parser", function() { return /* binding */ api_Parser; }); - -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/version.js -// 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 = "7.0.2"; -//# sourceMappingURL=version.js.map -// EXTERNAL MODULE: ./node_modules/chevrotain/lib_esm/src/utils/utils.js -var utils = __webpack_require__(0); - -// EXTERNAL MODULE: ./node_modules/regexp-to-ast/lib/regexp-to-ast.js -var regexp_to_ast = __webpack_require__(1); - -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/scan/reg_exp_parser.js - -var regExpAstCache = {}; -var regExpParser = new regexp_to_ast["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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/scan/reg_exp.js -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 = 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) { - Object(utils["d" /* 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."; - } - Object(utils["c" /* PRINT_ERROR */])(failedOptimizationPrefixMsg + "\n" + - ("\tFailed parsing: < " + regExp.toString() + " >\n") + - ("\tUsing the regexp-to-ast library version: " + regexp_to_ast["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); - } - Object(utils["u" /* 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 < minOptimizationVal; rangeCode++) { - addOptimizedIdxToResult(rangeCode, result, ignoreCase); - } - // Less common charCode where we optimize for faster init time, by using larger "buckets" - if (range.to >= minOptimizationVal) { - var minUnOptVal = range.from >= minOptimizationVal - ? range.from - : minOptimizationVal; - var maxUnOptVal = range.to; - var minOptIdx = charCodeToOptimizedIndex(minUnOptVal); - var maxOptIdx = 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 Object(utils["U" /* values */])(result); -} -function addOptimizedIdxToResult(code, result, ignoreCase) { - var optimizedCharIdx = 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 = charCodeToOptimizedIndex(upperChar.charCodeAt(0)); - result[optimizedCharIdx] = optimizedCharIdx; - } - else { - var lowerChar = char.toLowerCase(); - if (lowerChar !== char) { - var optimizedCharIdx = charCodeToOptimizedIndex(lowerChar.charCodeAt(0)); - result[optimizedCharIdx] = optimizedCharIdx; - } - } -} -function findCode(setNode, targetCharCodes) { - return Object(utils["q" /* find */])(setNode.value, function (codeOrRange) { - if (typeof codeOrRange === "number") { - return Object(utils["j" /* contains */])(targetCharCodes, codeOrRange); - } - else { - // range - var range_1 = codeOrRange; - return (Object(utils["q" /* 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 Object(utils["y" /* isArray */])(ast.value) - ? Object(utils["o" /* every */])(ast.value, isWholeOptional) - : isWholeOptional(ast.value); -} -var reg_exp_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 (Object(utils["j" /* 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["BaseRegExpVisitor"])); -function canMatchCharCode(charCodes, pattern) { - if (pattern instanceof RegExp) { - var ast = getRegExpAst(pattern); - var charCodeFinder = new reg_exp_CharCodeFinder(charCodes); - charCodeFinder.visit(ast); - return charCodeFinder.found; - } - else { - return (Object(utils["q" /* find */])(pattern, function (char) { - return Object(utils["j" /* contains */])(charCodes, char.charCodeAt(0)); - }) !== undefined); - } -} -//# sourceMappingURL=reg_exp.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/scan/lexer.js -var lexer_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 = Object(utils["k" /* 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 = Object(utils["P" /* reject */])(tokenTypes, function (currType) { - return currType[PATTERN] === lexer_public_Lexer.NA; - }); - }); - var hasCustom = false; - var allTransformedPatterns; - tracer("Transform Patterns", function () { - hasCustom = false; - allTransformedPatterns = Object(utils["I" /* map */])(onlyRelevantTypes, function (currType) { - var currPattern = currType[PATTERN]; - /* istanbul ignore else */ - if (Object(utils["D" /* 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 !== "." && - !currPattern.ignoreCase) { - return regExpSource; - } - else if (regExpSource.length === 2 && - regExpSource[0] === "\\" && - // not a meta character - !Object(utils["j" /* 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 (Object(utils["B" /* isFunction */])(currPattern)) { - hasCustom = true; - // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object - return { exec: currPattern }; - } - else if (Object(utils["w" /* 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 = Object(utils["I" /* map */])(onlyRelevantTypes, function (currType) { return currType.tokenTypeIdx; }); - patternIdxToGroup = Object(utils["I" /* map */])(onlyRelevantTypes, function (clazz) { - var groupName = clazz.GROUP; - /* istanbul ignore next */ - if (groupName === lexer_public_Lexer.SKIPPED) { - return undefined; - } - else if (Object(utils["E" /* isString */])(groupName)) { - return groupName; - } - else if (Object(utils["F" /* isUndefined */])(groupName)) { - return false; - } - else { - throw Error("non exhaustive match"); - } - }); - patternIdxToLongerAltIdx = Object(utils["I" /* map */])(onlyRelevantTypes, function (clazz) { - var longerAltType = clazz.LONGER_ALT; - if (longerAltType) { - var longerAltIdx = Object(utils["x" /* indexOf */])(onlyRelevantTypes, longerAltType); - return longerAltIdx; - } - }); - patternIdxToPushMode = Object(utils["I" /* map */])(onlyRelevantTypes, function (clazz) { return clazz.PUSH_MODE; }); - patternIdxToPopMode = Object(utils["I" /* map */])(onlyRelevantTypes, function (clazz) { - return Object(utils["w" /* has */])(clazz, "POP_MODE"); - }); - }); - var patternIdxToCanLineTerminator; - tracer("Line Terminator Handling", function () { - var lineTerminatorCharCodes = getCharCodes(options.lineTerminatorCharacters); - patternIdxToCanLineTerminator = Object(utils["I" /* map */])(onlyRelevantTypes, function (tokType) { return false; }); - if (options.positionTracking !== "onlyOffset") { - patternIdxToCanLineTerminator = Object(utils["I" /* map */])(onlyRelevantTypes, function (tokType) { - if (Object(utils["w" /* has */])(tokType, "LINE_BREAKS")) { - return tokType.LINE_BREAKS; - } - else { - if (checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false) { - return canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN); - } - } - }); - } - }); - var patternIdxToIsCustom; - var patternIdxToShort; - var emptyGroups; - var patternIdxToConfig; - tracer("Misc Mapping #2", function () { - patternIdxToIsCustom = Object(utils["I" /* map */])(onlyRelevantTypes, isCustomPattern); - patternIdxToShort = Object(utils["I" /* map */])(allTransformedPatterns, isShortPattern); - emptyGroups = Object(utils["O" /* reduce */])(onlyRelevantTypes, function (acc, clazz) { - var groupName = clazz.GROUP; - if (Object(utils["E" /* isString */])(groupName) && !(groupName === lexer_public_Lexer.SKIPPED)) { - acc[groupName] = []; - } - return acc; - }, {}); - patternIdxToConfig = Object(utils["I" /* 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 = Object(utils["O" /* 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 (Object(utils["y" /* isArray */])(currTokType.START_CHARS_HINT)) { - var lastOptimizedIdx_1; - Object(utils["u" /* 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 - /* istanbul ignore else */ - // - Difficult to check this scenario effects as it is only a performance - // optimization that does not change correctness - if (lastOptimizedIdx_1 !== currOptimizedIdx) { - lastOptimizedIdx_1 = currOptimizedIdx; - addToMapOfArrays(result, currOptimizedIdx, patternIdxToConfig[idx]); - } - }); - } - else if (Object(utils["D" /* isRegExp */])(currTokType.PATTERN)) { - if (currTokType.PATTERN.unicode) { - canBeOptimized = false; - if (options.ensureOptimizations) { - Object(utils["c" /* PRINT_ERROR */])("" + 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 = 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 (Object(utils["A" /* 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; - } - Object(utils["u" /* forEach */])(optimizedCodes, function (code) { - addToMapOfArrays(result, code, patternIdxToConfig[idx]); - }); - } - } - else { - if (options.ensureOptimizations) { - Object(utils["c" /* PRINT_ERROR */])("" + failedOptimizationPrefixMsg + - ("\tTokenType: <" + currTokType.name + "> is using a custom token pattern without providing 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 = Object(utils["L" /* 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 = Object(utils["p" /* filter */])(tokenTypes, function (currTokType) { - return Object(utils["D" /* 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 = Object(utils["p" /* filter */])(tokenTypes, function (currType) { - return !Object(utils["w" /* has */])(currType, PATTERN); - }); - var errors = Object(utils["I" /* map */])(tokenTypesWithMissingPattern, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- missing static 'PATTERN' property", - type: LexerDefinitionErrorType.MISSING_PATTERN, - tokenTypes: [currType] - }; - }); - var valid = Object(utils["l" /* difference */])(tokenTypes, tokenTypesWithMissingPattern); - return { errors: errors, valid: valid }; -} -function findInvalidPatterns(tokenTypes) { - var tokenTypesWithInvalidPattern = Object(utils["p" /* filter */])(tokenTypes, function (currType) { - var pattern = currType[PATTERN]; - return (!Object(utils["D" /* isRegExp */])(pattern) && - !Object(utils["B" /* isFunction */])(pattern) && - !Object(utils["w" /* has */])(pattern, "exec") && - !Object(utils["E" /* isString */])(pattern)); - }); - var errors = Object(utils["I" /* 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: LexerDefinitionErrorType.INVALID_PATTERN, - tokenTypes: [currType] - }; - }); - var valid = Object(utils["l" /* difference */])(tokenTypes, tokenTypesWithInvalidPattern); - return { errors: errors, valid: valid }; -} -var end_of_input = /[^\\][\$]/; -function findEndOfInputAnchor(tokenTypes) { - var EndAnchorFinder = /** @class */ (function (_super) { - lexer_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["BaseRegExpVisitor"])); - var invalidRegex = Object(utils["p" /* filter */])(tokenTypes, function (currType) { - var pattern = currType[PATTERN]; - try { - var regexpAst = 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 = Object(utils["I" /* 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: LexerDefinitionErrorType.EOI_ANCHOR_FOUND, - tokenTypes: [currType] - }; - }); - return errors; -} -function findEmptyMatchRegExps(tokenTypes) { - var matchesEmptyString = Object(utils["p" /* filter */])(tokenTypes, function (currType) { - var pattern = currType[PATTERN]; - return pattern.test(""); - }); - var errors = Object(utils["I" /* map */])(matchesEmptyString, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'PATTERN' must not match an empty string", - type: LexerDefinitionErrorType.EMPTY_MATCH_PATTERN, - tokenTypes: [currType] - }; - }); - return errors; -} -var start_of_input = /[^\\[][\^]|^\^/; -function findStartOfInputAnchor(tokenTypes) { - var StartAnchorFinder = /** @class */ (function (_super) { - lexer_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["BaseRegExpVisitor"])); - var invalidRegex = Object(utils["p" /* filter */])(tokenTypes, function (currType) { - var pattern = currType[PATTERN]; - try { - var regexpAst = 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 = Object(utils["I" /* 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: LexerDefinitionErrorType.SOI_ANCHOR_FOUND, - tokenTypes: [currType] - }; - }); - return errors; -} -function findUnsupportedFlags(tokenTypes) { - var invalidFlags = Object(utils["p" /* filter */])(tokenTypes, function (currType) { - var pattern = currType[PATTERN]; - return pattern instanceof RegExp && (pattern.multiline || pattern.global); - }); - var errors = Object(utils["I" /* map */])(invalidFlags, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'PATTERN' may NOT contain global('g') or multiline('m')", - type: 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 = Object(utils["I" /* map */])(tokenTypes, function (outerType) { - return Object(utils["O" /* reduce */])(tokenTypes, function (result, innerType) { - if (outerType.PATTERN.source === innerType.PATTERN.source && - !Object(utils["j" /* contains */])(found, innerType) && - innerType.PATTERN !== lexer_public_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 = Object(utils["i" /* compact */])(identicalPatterns); - var duplicatePatterns = Object(utils["p" /* filter */])(identicalPatterns, function (currIdenticalSet) { - return currIdenticalSet.length > 1; - }); - var errors = Object(utils["I" /* map */])(duplicatePatterns, function (setOfIdentical) { - var tokenTypeNames = Object(utils["I" /* map */])(setOfIdentical, function (currType) { - return currType.name; - }); - var dupPatternSrc = Object(utils["s" /* first */])(setOfIdentical).PATTERN; - return { - message: "The same RegExp pattern ->" + dupPatternSrc + "<-" + - ("has been used in all of the following Token Types: " + tokenTypeNames.join(", ") + " <-"), - type: LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND, - tokenTypes: setOfIdentical - }; - }); - return errors; -} -function findInvalidGroupType(tokenTypes) { - var invalidTypes = Object(utils["p" /* filter */])(tokenTypes, function (clazz) { - if (!Object(utils["w" /* has */])(clazz, "GROUP")) { - return false; - } - var group = clazz.GROUP; - return group !== lexer_public_Lexer.SKIPPED && group !== lexer_public_Lexer.NA && !Object(utils["E" /* isString */])(group); - }); - var errors = Object(utils["I" /* map */])(invalidTypes, function (currType) { - return { - message: "Token Type: ->" + - currType.name + - "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String", - type: LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND, - tokenTypes: [currType] - }; - }); - return errors; -} -function findModesThatDoNotExist(tokenTypes, validModes) { - var invalidModes = Object(utils["p" /* filter */])(tokenTypes, function (clazz) { - return (clazz.PUSH_MODE !== undefined && !Object(utils["j" /* contains */])(validModes, clazz.PUSH_MODE)); - }); - var errors = Object(utils["I" /* 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: LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST, - tokenTypes: [tokType] - }; - }); - return errors; -} -function findUnreachablePatterns(tokenTypes) { - var errors = []; - var canBeTested = Object(utils["O" /* reduce */])(tokenTypes, function (result, tokType, idx) { - var pattern = tokType.PATTERN; - if (pattern === lexer_public_Lexer.NA) { - return result; - } - // a more comprehensive validation for all forms of regExps would require - // deeper regExp analysis capabilities - if (Object(utils["E" /* isString */])(pattern)) { - result.push({ str: pattern, idx: idx, tokenType: tokType }); - } - else if (Object(utils["D" /* isRegExp */])(pattern) && noMetaChar(pattern)) { - result.push({ str: pattern.source, idx: idx, tokenType: tokType }); - } - return result; - }, []); - Object(utils["u" /* forEach */])(tokenTypes, function (tokType, testIdx) { - Object(utils["u" /* 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: LexerDefinitionErrorType.UNREACHABLE_PATTERN, - tokenTypes: [tokType, tokenType] - }); - } - }); - }); - return errors; -} -function testTokenType(str, pattern) { - /* istanbul ignore else */ - if (Object(utils["D" /* isRegExp */])(pattern)) { - var regExpArray = pattern.exec(str); - return regExpArray !== null && regExpArray.index === 0; - } - else if (Object(utils["B" /* isFunction */])(pattern)) { - // maintain the API of custom patterns - return pattern(str, 0, [], {}); - } - else if (Object(utils["w" /* 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 (Object(utils["q" /* 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 (!Object(utils["w" /* has */])(lexerDefinition, DEFAULT_MODE)) { - errors.push({ - message: "A MultiMode Lexer cannot be initialized without a <" + - DEFAULT_MODE + - "> property in its definition\n", - type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE - }); - } - if (!Object(utils["w" /* has */])(lexerDefinition, MODES)) { - errors.push({ - message: "A MultiMode Lexer cannot be initialized without a <" + - MODES + - "> property in its definition\n", - type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY - }); - } - if (Object(utils["w" /* has */])(lexerDefinition, MODES) && - Object(utils["w" /* has */])(lexerDefinition, DEFAULT_MODE) && - !Object(utils["w" /* 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: LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST - }); - } - if (Object(utils["w" /* has */])(lexerDefinition, MODES)) { - Object(utils["u" /* forEach */])(lexerDefinition.modes, function (currModeValue, currModeName) { - Object(utils["u" /* forEach */])(currModeValue, function (currTokType, currIdx) { - if (Object(utils["F" /* isUndefined */])(currTokType)) { - errors.push({ - message: "A Lexer cannot be initialized using an undefined Token Type. Mode:" + - ("<" + currModeName + "> at index: <" + currIdx + ">\n"), - type: LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED - }); - } - }); - }); - } - return errors; -} -function performWarningRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) { - var warnings = []; - var hasAnyLineBreak = false; - var allTokenTypes = Object(utils["i" /* compact */])(Object(utils["t" /* flatten */])(Object(utils["J" /* mapValues */])(lexerDefinition.modes, function (tokTypes) { return tokTypes; }))); - var concreteTokenTypes = Object(utils["P" /* reject */])(allTokenTypes, function (currType) { return currType[PATTERN] === lexer_public_Lexer.NA; }); - var terminatorCharCodes = getCharCodes(lineTerminatorCharacters); - if (trackLines) { - Object(utils["u" /* 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 (Object(utils["w" /* has */])(tokType, "LINE_BREAKS")) { - if (tokType.LINE_BREAKS === true) { - hasAnyLineBreak = true; - } - } - else { - if (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: LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS - }); - } - return warnings; -} -function cloneEmptyGroups(emptyGroups) { - var clonedResult = {}; - var groupKeys = Object(utils["G" /* keys */])(emptyGroups); - Object(utils["u" /* forEach */])(groupKeys, function (currKey) { - var currGroupValue = emptyGroups[currKey]; - /* istanbul ignore else */ - if (Object(utils["y" /* 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 (Object(utils["D" /* isRegExp */])(pattern)) { - return false; - } - else if (Object(utils["B" /* isFunction */])(pattern)) { - // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object - return true; - } - else if (Object(utils["w" /* has */])(pattern, "exec")) { - // ICustomPattern - return true; - } - else if (Object(utils["E" /* isString */])(pattern)) { - return false; - } - else { - throw Error("non exhaustive match"); - } -} -function isShortPattern(pattern) { - if (Object(utils["E" /* 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 (Object(utils["w" /* 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 (Object(utils["D" /* isRegExp */])(tokType.PATTERN)) { - try { - canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN); - } - catch (e) { - /* istanbul ignore next - to test this we would have to mock to throw an error */ - return { - issue: LexerDefinitionErrorType.IDENTIFY_TERMINATOR, - errMsg: e.message - }; - } - return false; - } - else if (Object(utils["E" /* 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: LexerDefinitionErrorType.CUSTOM_LINE_BREAK }; - } - else { - throw Error("non exhaustive match"); - } - } -} -function buildLineBreakIssueMessage(tokType, details) { - /* istanbul ignore else */ - if (details.issue === 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 === LexerDefinitionErrorType.CUSTOM_LINE_BREAK) { - return ("Warning: A Custom Token Pattern should specify the 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 = Object(utils["I" /* map */])(charsOrCodes, function (numOrString) { - if (Object(utils["E" /* 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 (Object(utils["A" /* 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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/scan/tokens.js - -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); - Object(utils["u" /* forEach */])(tokenTypesAndParents, function (tokType) { - tokType.isParent = tokType.categoryMatches.length > 0; - }); -} -function expandCategories(tokenTypes) { - var result = Object(utils["g" /* cloneArr */])(tokenTypes); - var categories = tokenTypes; - var searching = true; - while (searching) { - categories = Object(utils["i" /* compact */])(Object(utils["t" /* flatten */])(Object(utils["I" /* map */])(categories, function (currTokType) { return currTokType.CATEGORIES; }))); - var newCategories = Object(utils["l" /* difference */])(categories, result); - result = result.concat(newCategories); - if (Object(utils["A" /* isEmpty */])(newCategories)) { - searching = false; - } - else { - categories = newCategories; - } - } - return result; -} -function assignTokenDefaultProps(tokenTypes) { - Object(utils["u" /* forEach */])(tokenTypes, function (currTokType) { - if (!hasShortKeyProperty(currTokType)) { - tokenIdxToClass[tokenShortNameIdx] = currTokType; - currTokType.tokenTypeIdx = tokenShortNameIdx++; - } - // CATEGORIES? : TokenType | TokenType[] - if (hasCategoriesProperty(currTokType) && - !Object(utils["y" /* 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) { - Object(utils["u" /* forEach */])(tokenTypes, function (currTokType) { - // avoid duplications - currTokType.categoryMatches = []; - Object(utils["u" /* forEach */])(currTokType.categoryMatchesMap, function (val, key) { - currTokType.categoryMatches.push(tokenIdxToClass[key].tokenTypeIdx); - }); - }); -} -function assignCategoriesMapProp(tokenTypes) { - Object(utils["u" /* forEach */])(tokenTypes, function (currTokType) { - singleAssignCategoriesToksMap([], currTokType); - }); -} -function singleAssignCategoriesToksMap(path, nextNode) { - Object(utils["u" /* forEach */])(path, function (pathNode) { - nextNode.categoryMatchesMap[pathNode.tokenTypeIdx] = true; - }); - Object(utils["u" /* forEach */])(nextNode.CATEGORIES, function (nextCategory) { - var newPath = path.concat(nextNode); - // avoids infinite loops due to cyclic categories. - if (!Object(utils["j" /* contains */])(newPath, nextCategory)) { - singleAssignCategoriesToksMap(newPath, nextCategory); - } - }); -} -function hasShortKeyProperty(tokType) { - return Object(utils["w" /* has */])(tokType, "tokenTypeIdx"); -} -function hasCategoriesProperty(tokType) { - return Object(utils["w" /* has */])(tokType, "CATEGORIES"); -} -function hasExtendingTokensTypesProperty(tokType) { - return Object(utils["w" /* has */])(tokType, "categoryMatches"); -} -function hasExtendingTokensTypesMapProperty(tokType) { - return Object(utils["w" /* has */])(tokType, "categoryMatchesMap"); -} -function isTokenType(tokType) { - return Object(utils["w" /* has */])(tokType, "tokenTypeIdx"); -} -//# sourceMappingURL=tokens.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/scan/lexer_errors_public.js -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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/scan/lexer_public.js - - - - - -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: defaultLexerErrorProvider, - traceInitPerf: false, - skipValidations: false -}; -Object.freeze(DEFAULT_LEXER_CONFIG); -var lexer_public_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 = Object(utils["K" /* 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 = LineTerminatorOptimizedTester; - } - else { - if (_this.config.lineTerminatorCharacters === - DEFAULT_LEXER_CONFIG.lineTerminatorCharacters) { - throw Error("Error: Missing 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 (Object(utils["y" /* isArray */])(lexerDefinition)) { - actualDefinition = { modes: {} }; - actualDefinition.modes[DEFAULT_MODE] = Object(utils["g" /* cloneArr */])(lexerDefinition); - actualDefinition[DEFAULT_MODE] = DEFAULT_MODE; - } - else { - // no conversion needed, input should already be a IMultiModeLexerDefinition - hasOnlySingleMode = false; - actualDefinition = Object(utils["h" /* cloneObj */])(lexerDefinition); - } - }); - if (_this.config.skipValidations === false) { - _this.TRACE_INIT("performRuntimeChecks", function () { - _this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat(performRuntimeChecks(actualDefinition, _this.trackStartLines, _this.config.lineTerminatorCharacters)); - }); - _this.TRACE_INIT("performWarningRuntimeChecks", function () { - _this.lexerDefinitionWarning = _this.lexerDefinitionWarning.concat(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. - Object(utils["u" /* forEach */])(actualDefinition.modes, function (currModeValue, currModeName) { - actualDefinition.modes[currModeName] = Object(utils["P" /* reject */])(currModeValue, function (currTokType) { return Object(utils["F" /* isUndefined */])(currTokType); }); - }); - var allModeNames = Object(utils["G" /* keys */])(actualDefinition.modes); - Object(utils["u" /* 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(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 (Object(utils["A" /* isEmpty */])(_this.lexerDefinitionErrors)) { - augmentTokenTypes(currModDef); - var currAnalyzeResult_1; - _this.TRACE_INIT("analyzeTokenTypes", function () { - currAnalyzeResult_1 = 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 = Object(utils["K" /* merge */])(_this.emptyGroups, currAnalyzeResult_1.emptyGroups); - _this.hasCustom = currAnalyzeResult_1.hasCustom || _this.hasCustom; - _this.canModeBeOptimized[currModName] = - currAnalyzeResult_1.canBeOptimized; - } - }); - }); - _this.defaultMode = actualDefinition.defaultMode; - if (!Object(utils["A" /* isEmpty */])(_this.lexerDefinitionErrors) && - !_this.config.deferDefinitionErrorsHandling) { - var allErrMessages = Object(utils["I" /* 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 - Object(utils["u" /* forEach */])(_this.lexerDefinitionWarning, function (warningDescriptor) { - Object(utils["d" /* 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 (SUPPORT_STICKY) { - _this.chopInput = utils["a" /* IDENTITY */]; - _this.match = _this.matchWithTest; - } - else { - _this.updateLastIndex = utils["b" /* NOOP */]; - _this.match = _this.matchWithExec; - } - if (hasOnlySingleMode) { - _this.handleModes = utils["b" /* NOOP */]; - } - if (_this.trackStartLines === false) { - _this.computeNewColumn = utils["a" /* IDENTITY */]; - } - if (_this.trackEndLines === false) { - _this.updateTokenEndLineColumnLocation = utils["b" /* 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 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 = Object(utils["O" /* reduce */])(_this.canModeBeOptimized, function (cannotBeOptimized, canBeOptimized, modeName) { - if (canBeOptimized === false) { - cannotBeOptimized.push(modeName); - } - return cannotBeOptimized; - }, []); - if (config.ensureOptimizations && !Object(utils["A" /* 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 () { - clearRegExpParserCache(); - }); - _this.TRACE_INIT("toFastProperties", function () { - Object(utils["S" /* toFastProperties */])(_this); - }); - }); - } - Lexer.prototype.tokenize = function (text, initialMode) { - if (initialMode === void 0) { initialMode = this.defaultMode; } - if (!Object(utils["A" /* isEmpty */])(this.lexerDefinitionErrors)) { - var allErrMessages = Object(utils["I" /* 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 = 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 = 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 = Object(utils["H" /* 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 = Object(utils["R" /* 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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/scan/tokens_public.js - - - -function tokenLabel(tokType) { - if (hasTokenLabel(tokType)) { - return tokType.LABEL; - } - else { - return tokType.name; - } -} -function tokenName(tokType) { - return tokType.name; -} -function hasTokenLabel(obj) { - return Object(utils["E" /* 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 (!Object(utils["F" /* isUndefined */])(pattern)) { - tokenType.PATTERN = pattern; - } - if (Object(utils["w" /* 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 (Object(utils["w" /* has */])(config, CATEGORIES)) { - // casting to ANY as this will be fixed inside `augmentTokenTypes`` - tokenType.CATEGORIES = config[CATEGORIES]; - } - augmentTokenTypes([tokenType]); - if (Object(utils["w" /* has */])(config, LABEL)) { - tokenType.LABEL = config[LABEL]; - } - if (Object(utils["w" /* has */])(config, GROUP)) { - tokenType.GROUP = config[GROUP]; - } - if (Object(utils["w" /* has */])(config, POP_MODE)) { - tokenType.POP_MODE = config[POP_MODE]; - } - if (Object(utils["w" /* has */])(config, PUSH_MODE)) { - tokenType.PUSH_MODE = config[PUSH_MODE]; - } - if (Object(utils["w" /* has */])(config, LONGER_ALT)) { - tokenType.LONGER_ALT = config[LONGER_ALT]; - } - if (Object(utils["w" /* has */])(config, LINE_BREAKS)) { - tokenType.LINE_BREAKS = config[LINE_BREAKS]; - } - if (Object(utils["w" /* has */])(config, START_CHARS_HINT)) { - tokenType.START_CHARS_HINT = config[START_CHARS_HINT]; - } - return tokenType; -} -var EOF = createToken({ name: "EOF", pattern: lexer_public_Lexer.NA }); -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 tokens_public_tokenMatcher(token, tokType) { - return tokenStructuredMatcher(token, tokType); -} -//# sourceMappingURL=tokens_public.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast_public.js -var gast_public_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 gast_public_AbstractProduction = /** @class */ (function () { - function AbstractProduction(definition) { - this.definition = definition; - } - AbstractProduction.prototype.accept = function (visitor) { - visitor.visit(this); - Object(utils["u" /* forEach */])(this.definition, function (prod) { - prod.accept(visitor); - }); - }; - return AbstractProduction; -}()); - -var gast_public_NonTerminal = /** @class */ (function (_super) { - gast_public_extends(NonTerminal, _super); - function NonTerminal(options) { - var _this = _super.call(this, []) || this; - _this.idx = 1; - Object(utils["f" /* assign */])(_this, Object(utils["N" /* 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: false, - 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; -}(gast_public_AbstractProduction)); - -var gast_public_Rule = /** @class */ (function (_super) { - gast_public_extends(Rule, _super); - function Rule(options) { - var _this = _super.call(this, options.definition) || this; - _this.orgText = ""; - Object(utils["f" /* assign */])(_this, Object(utils["N" /* pick */])(options, function (v) { return v !== undefined; })); - return _this; - } - return Rule; -}(gast_public_AbstractProduction)); - -var gast_public_Alternative = /** @class */ (function (_super) { - gast_public_extends(Alternative, _super); - function Alternative(options) { - var _this = _super.call(this, options.definition) || this; - _this.ignoreAmbiguities = false; - Object(utils["f" /* assign */])(_this, Object(utils["N" /* pick */])(options, function (v) { return v !== undefined; })); - return _this; - } - return Alternative; -}(gast_public_AbstractProduction)); - -var gast_public_Option = /** @class */ (function (_super) { - gast_public_extends(Option, _super); - function Option(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - Object(utils["f" /* assign */])(_this, Object(utils["N" /* pick */])(options, function (v) { return v !== undefined; })); - return _this; - } - return Option; -}(gast_public_AbstractProduction)); - -var gast_public_RepetitionMandatory = /** @class */ (function (_super) { - gast_public_extends(RepetitionMandatory, _super); - function RepetitionMandatory(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - Object(utils["f" /* assign */])(_this, Object(utils["N" /* pick */])(options, function (v) { return v !== undefined; })); - return _this; - } - return RepetitionMandatory; -}(gast_public_AbstractProduction)); - -var gast_public_RepetitionMandatoryWithSeparator = /** @class */ (function (_super) { - gast_public_extends(RepetitionMandatoryWithSeparator, _super); - function RepetitionMandatoryWithSeparator(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - Object(utils["f" /* assign */])(_this, Object(utils["N" /* pick */])(options, function (v) { return v !== undefined; })); - return _this; - } - return RepetitionMandatoryWithSeparator; -}(gast_public_AbstractProduction)); - -var gast_public_Repetition = /** @class */ (function (_super) { - gast_public_extends(Repetition, _super); - function Repetition(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - Object(utils["f" /* assign */])(_this, Object(utils["N" /* pick */])(options, function (v) { return v !== undefined; })); - return _this; - } - return Repetition; -}(gast_public_AbstractProduction)); - -var gast_public_RepetitionWithSeparator = /** @class */ (function (_super) { - gast_public_extends(RepetitionWithSeparator, _super); - function RepetitionWithSeparator(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - Object(utils["f" /* assign */])(_this, Object(utils["N" /* pick */])(options, function (v) { return v !== undefined; })); - return _this; - } - return RepetitionWithSeparator; -}(gast_public_AbstractProduction)); - -var gast_public_Alternation = /** @class */ (function (_super) { - gast_public_extends(Alternation, _super); - function Alternation(options) { - var _this = _super.call(this, options.definition) || this; - _this.idx = 1; - _this.ignoreAmbiguities = false; - _this.hasPredicates = false; - Object(utils["f" /* assign */])(_this, Object(utils["N" /* pick */])(options, function (v) { return v !== undefined; })); - return _this; - } - return Alternation; -}(gast_public_AbstractProduction)); - -var gast_public_Terminal = /** @class */ (function () { - function Terminal(options) { - this.idx = 1; - Object(utils["f" /* assign */])(this, Object(utils["N" /* pick */])(options, function (v) { return v !== undefined; })); - } - Terminal.prototype.accept = function (visitor) { - visitor.visit(this); - }; - return Terminal; -}()); - -function serializeGrammar(topRules) { - return Object(utils["I" /* map */])(topRules, serializeProduction); -} -function serializeProduction(node) { - function convertDefinition(definition) { - return Object(utils["I" /* map */])(definition, serializeProduction); - } - /* istanbul ignore else */ - if (node instanceof gast_public_NonTerminal) { - return { - type: "NonTerminal", - name: node.nonTerminalName, - idx: node.idx - }; - } - else if (node instanceof gast_public_Alternative) { - return { - type: "Alternative", - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof gast_public_Option) { - return { - type: "Option", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof gast_public_RepetitionMandatory) { - return { - type: "RepetitionMandatory", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof gast_public_RepetitionMandatoryWithSeparator) { - return { - type: "RepetitionMandatoryWithSeparator", - idx: node.idx, - separator: (serializeProduction(new gast_public_Terminal({ terminalType: node.separator }))), - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof gast_public_RepetitionWithSeparator) { - return { - type: "RepetitionWithSeparator", - idx: node.idx, - separator: (serializeProduction(new gast_public_Terminal({ terminalType: node.separator }))), - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof gast_public_Repetition) { - return { - type: "Repetition", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof gast_public_Alternation) { - return { - type: "Alternation", - idx: node.idx, - definition: convertDefinition(node.definition) - }; - } - else if (node instanceof gast_public_Terminal) { - var serializedTerminal = { - type: "Terminal", - name: node.terminalType.name, - label: tokenLabel(node.terminalType), - idx: node.idx - }; - var pattern = node.terminalType.PATTERN; - if (node.terminalType.PATTERN) { - serializedTerminal.pattern = Object(utils["D" /* isRegExp */])(pattern) - ? pattern.source - : pattern; - } - return serializedTerminal; - } - else if (node instanceof gast_public_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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/grammar/rest.js - - -/** - * A Grammar Walker that computes the "remaining" grammar "after" a productions in the grammar. - */ -var rest_RestWalker = /** @class */ (function () { - function RestWalker() { - } - RestWalker.prototype.walk = function (prod, prevRest) { - var _this = this; - if (prevRest === void 0) { prevRest = []; } - Object(utils["u" /* forEach */])(prod.definition, function (subProd, index) { - var currRest = Object(utils["m" /* drop */])(prod.definition, index + 1); - /* istanbul ignore else */ - if (subProd instanceof gast_public_NonTerminal) { - _this.walkProdRef(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_public_Terminal) { - _this.walkTerminal(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_public_Alternative) { - _this.walkFlat(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_public_Option) { - _this.walkOption(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_public_RepetitionMandatory) { - _this.walkAtLeastOne(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_public_RepetitionMandatoryWithSeparator) { - _this.walkAtLeastOneSep(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_public_RepetitionWithSeparator) { - _this.walkManySep(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_public_Repetition) { - _this.walkMany(subProd, currRest, prevRest); - } - else if (subProd instanceof gast_public_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_public_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_public_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 - Object(utils["u" /* 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_public_Alternative({ definition: [alt] }); - _this.walk(prodWrapper, fullOrRest); - }); - }; - return RestWalker; -}()); - -function restForRepetitionWithSeparator(repSepProd, currRest, prevRest) { - var repSepRest = [ - new gast_public_Option({ - definition: [new gast_public_Terminal({ terminalType: repSepProd.separator })].concat(repSepProd.definition) - }) - ]; - var fullRepSepRest = repSepRest.concat(currRest, prevRest); - return fullRepSepRest; -} -//# sourceMappingURL=rest.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast_visitor_public.js - -var gast_visitor_public_GAstVisitor = /** @class */ (function () { - function GAstVisitor() { - } - GAstVisitor.prototype.visit = function (node) { - var nodeAny = node; - switch (nodeAny.constructor) { - case gast_public_NonTerminal: - return this.visitNonTerminal(nodeAny); - case gast_public_Alternative: - return this.visitAlternative(nodeAny); - case gast_public_Option: - return this.visitOption(nodeAny); - case gast_public_RepetitionMandatory: - return this.visitRepetitionMandatory(nodeAny); - case gast_public_RepetitionMandatoryWithSeparator: - return this.visitRepetitionMandatoryWithSeparator(nodeAny); - case gast_public_RepetitionWithSeparator: - return this.visitRepetitionWithSeparator(nodeAny); - case gast_public_Repetition: - return this.visitRepetition(nodeAny); - case gast_public_Alternation: - return this.visitAlternation(nodeAny); - case gast_public_Terminal: - return this.visitTerminal(nodeAny); - case gast_public_Rule: - return this.visitRule(nodeAny); - /* istanbul ignore next */ - default: - throw Error("non exhaustive match"); - } - }; - GAstVisitor.prototype.visitNonTerminal = function (node) { }; - GAstVisitor.prototype.visitAlternative = 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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast.js -var gast_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_Alternative || - prod instanceof gast_public_Option || - prod instanceof gast_public_Repetition || - prod instanceof gast_public_RepetitionMandatory || - prod instanceof gast_public_RepetitionMandatoryWithSeparator || - prod instanceof gast_public_RepetitionWithSeparator || - prod instanceof gast_public_Terminal || - prod instanceof gast_public_Rule); -} -function isOptionalProd(prod, alreadyVisited) { - if (alreadyVisited === void 0) { alreadyVisited = []; } - var isDirectlyOptional = prod instanceof gast_public_Option || - prod instanceof gast_public_Repetition || - prod instanceof gast_public_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_Alternation) { - // for OR its enough for just one of the alternatives to be optional - return Object(utils["Q" /* some */])(prod.definition, function (subProd) { - return isOptionalProd(subProd, alreadyVisited); - }); - } - else if (prod instanceof gast_public_NonTerminal && Object(utils["j" /* contains */])(alreadyVisited, prod)) { - // avoiding stack overflow due to infinite recursion - return false; - } - else if (prod instanceof gast_public_AbstractProduction) { - if (prod instanceof gast_public_NonTerminal) { - alreadyVisited.push(prod); - } - return Object(utils["o" /* every */])(prod.definition, function (subProd) { - return isOptionalProd(subProd, alreadyVisited); - }); - } - else { - return false; - } -} -function isBranchingProd(prod) { - return prod instanceof gast_public_Alternation; -} -function getProductionDslName(prod) { - /* istanbul ignore else */ - if (prod instanceof gast_public_NonTerminal) { - return "SUBRULE"; - } - else if (prod instanceof gast_public_Option) { - return "OPTION"; - } - else if (prod instanceof gast_public_Alternation) { - return "OR"; - } - else if (prod instanceof gast_public_RepetitionMandatory) { - return "AT_LEAST_ONE"; - } - else if (prod instanceof gast_public_RepetitionMandatoryWithSeparator) { - return "AT_LEAST_ONE_SEP"; - } - else if (prod instanceof gast_public_RepetitionWithSeparator) { - return "MANY_SEP"; - } - else if (prod instanceof gast_public_Repetition) { - return "MANY"; - } - else if (prod instanceof gast_public_Terminal) { - return "CONSUME"; - } - else { - throw Error("non exhaustive match"); - } -} -var gast_DslMethodsCollectorVisitor = /** @class */ (function (_super) { - gast_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 (!Object(utils["w" /* 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 (!Object(utils["w" /* 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_GAstVisitor)); - -var gast_collectorVisitor = new gast_DslMethodsCollectorVisitor(); -function collectMethods(rule) { - gast_collectorVisitor.reset(); - rule.accept(gast_collectorVisitor); - var dslMethods = gast_collectorVisitor.dslMethods; - // avoid uncleaned references - gast_collectorVisitor.reset(); - return dslMethods; -} -//# sourceMappingURL=gast.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/grammar/first.js - - - -function first(prod) { - /* istanbul ignore else */ - if (prod instanceof gast_public_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_public_Terminal) { - return firstForTerminal(prod); - } - else if (isSequenceProd(prod)) { - return firstForSequence(prod); - } - else if (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 = isOptionalProd(currSubProd); - firstSet = firstSet.concat(first(currSubProd)); - nextSubProdIdx = nextSubProdIdx + 1; - hasInnerProdsRemaining = seq.length > nextSubProdIdx; - } - return Object(utils["T" /* uniq */])(firstSet); -} -function firstForBranching(prod) { - var allAlternativesFirsts = Object(utils["I" /* map */])(prod.definition, function (innerProd) { - return first(innerProd); - }); - return Object(utils["T" /* uniq */])(Object(utils["t" /* flatten */])(allAlternativesFirsts)); -} -function firstForTerminal(terminal) { - return [terminal.terminalType]; -} -//# sourceMappingURL=first.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/constants.js -// TODO: can this be removed? where is it used? -var IN = "_~IN~_"; -//# sourceMappingURL=constants.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/grammar/follow.js -var follow_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 follow_ResyncFollowsWalker = /** @class */ (function (_super) { - follow_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_public_Alternative({ definition: fullRest }); - var t_in_topProd_follows = first(restProd); - this.follows[followName] = t_in_topProd_follows; - }; - return ResyncFollowsWalker; -}(rest_RestWalker)); - -function computeAllProdsFollows(topProductions) { - var reSyncFollows = {}; - Object(utils["u" /* forEach */])(topProductions, function (topProd) { - var currRefsFollow = new follow_ResyncFollowsWalker(topProd).startWalking(); - Object(utils["f" /* assign */])(reSyncFollows, currRefsFollow); - }); - return reSyncFollows; -} -function buildBetweenProdsFollowPrefix(inner, occurenceInParent) { - return inner.name + occurenceInParent + IN; -} -function buildInProdFollowPrefix(terminal) { - var terminalName = terminal.terminalType.name; - return terminalName + terminal.idx + IN; -} -//# sourceMappingURL=follow.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/errors_public.js - - - - - -var defaultParserErrorProvider = { - buildMismatchTokenMessage: function (_a) { - var expected = _a.expected, actual = _a.actual, previous = _a.previous, ruleName = _a.ruleName; - var hasLabel = hasTokenLabel(expected); - var expectedMsg = hasLabel - ? "--> " + 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 = Object(utils["s" /* first */])(actual).image; - var errSuffix = "\nbut found: '" + actualText + "'"; - if (customUserDescription) { - return errPrefix + customUserDescription + errSuffix; - } - else { - var allLookAheadPaths = Object(utils["O" /* reduce */])(expectedPathsPerAlt, function (result, currAltPaths) { return result.concat(currAltPaths); }, []); - var nextValidTokenSequences = Object(utils["I" /* map */])(allLookAheadPaths, function (currPath) { - return "[" + Object(utils["I" /* map */])(currPath, function (currTokenType) { return tokenLabel(currTokenType); }).join(", ") + "]"; - }); - var nextValidSequenceItems = Object(utils["I" /* 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 = Object(utils["s" /* first */])(actual).image; - var errSuffix = "\nbut found: '" + actualText + "'"; - if (customUserDescription) { - return errPrefix + customUserDescription + errSuffix; - } - else { - var nextValidTokenSequences = Object(utils["I" /* map */])(expectedIterationPaths, function (currPath) { - return "[" + Object(utils["I" /* map */])(currPath, function (currTokenType) { return 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 gast_public_Terminal) { - return prod.terminalType.name; - } - else if (prod instanceof gast_public_NonTerminal) { - return prod.nonTerminalName; - } - else { - return ""; - } - } - var topLevelName = topLevelRule.name; - var duplicateProd = Object(utils["s" /* first */])(duplicateProds); - var index = duplicateProd.idx; - var dslName = 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; - }, - 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 = Object(utils["I" /* map */])(options.prefixPath, function (currTok) { - return 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 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 = Object(utils["I" /* map */])(options.prefixPath, function (currtok) { - return tokenLabel(currtok); - }).join(", "); - var occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx; - var currMessage = "Ambiguous Alternatives Detected: <" + options.ambiguityIndices.join(" ,") + "> in " + - (" 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 = 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 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" + - (" 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["I" /* 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 gast_public_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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/grammar/resolver.js -var resolver_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 resolver_GastRefResolverVisitor(topLevels, errMsgProvider); - refResolver.resolveRefs(); - return refResolver.errors; -} -var resolver_GastRefResolverVisitor = /** @class */ (function (_super) { - resolver_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; - Object(utils["u" /* forEach */])(Object(utils["U" /* 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: ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF, - ruleName: this.currTopLevel.name, - unresolvedRefName: node.nonTerminalName - }); - } - else { - node.referencedRule = ref; - } - }; - return GastRefResolverVisitor; -}(gast_visitor_public_GAstVisitor)); - -//# sourceMappingURL=resolver.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/grammar/interpreter.js -var interpreter_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 interpreter_AbstractNextPossibleTokensWalker = /** @class */ (function (_super) { - interpreter_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 = Object(utils["g" /* cloneArr */])(this.path.ruleStack).reverse(); // intelij bug requires assertion - this.occurrenceStack = Object(utils["g" /* 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 (Object(utils["A" /* 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_RestWalker)); - -var interpreter_NextAfterTokenWalker = /** @class */ (function (_super) { - interpreter_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_public_Alternative({ definition: fullRest }); - this.possibleTokTypes = first(restProd); - this.found = true; - } - }; - return NextAfterTokenWalker; -}(interpreter_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) { - interpreter_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_RestWalker)); - -var interpreter_NextTerminalAfterManyWalker = /** @class */ (function (_super) { - interpreter_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 = Object(utils["s" /* first */])(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterMany === undefined; - if (firstAfterMany instanceof gast_public_Terminal) { - this.result.token = firstAfterMany.terminalType; - this.result.occurrence = firstAfterMany.idx; - } - } - else { - _super.prototype.walkMany.call(this, manyProd, currRest, prevRest); - } - }; - return NextTerminalAfterManyWalker; -}(AbstractNextTerminalAfterProductionWalker)); - -var interpreter_NextTerminalAfterManySepWalker = /** @class */ (function (_super) { - interpreter_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 = Object(utils["s" /* first */])(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterManySep === undefined; - if (firstAfterManySep instanceof gast_public_Terminal) { - this.result.token = firstAfterManySep.terminalType; - this.result.occurrence = firstAfterManySep.idx; - } - } - else { - _super.prototype.walkManySep.call(this, manySepProd, currRest, prevRest); - } - }; - return NextTerminalAfterManySepWalker; -}(AbstractNextTerminalAfterProductionWalker)); - -var interpreter_NextTerminalAfterAtLeastOneWalker = /** @class */ (function (_super) { - interpreter_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 = Object(utils["s" /* first */])(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterAtLeastOne === undefined; - if (firstAfterAtLeastOne instanceof gast_public_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 interpreter_NextTerminalAfterAtLeastOneSepWalker = /** @class */ (function (_super) { - interpreter_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 = Object(utils["s" /* first */])(currRest.concat(prevRest)); - this.result.isEndOfRule = firstAfterfirstAfterAtLeastOneSep === undefined; - if (firstAfterfirstAfterAtLeastOneSep instanceof gast_public_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 = Object(utils["g" /* cloneArr */])(currPath); - var result = []; - var i = 0; - // TODO: avoid inner funcs - function remainingPathWith(nextDef) { - return nextDef.concat(Object(utils["m" /* 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_public_Alternative) { - return getAlternativesForProd(prod.definition); - } - else if (prod instanceof gast_public_NonTerminal) { - return getAlternativesForProd(prod.definition); - } - else if (prod instanceof gast_public_Option) { - result = getAlternativesForProd(prod.definition); - } - else if (prod instanceof gast_public_RepetitionMandatory) { - var newDef = prod.definition.concat([ - new gast_public_Repetition({ - definition: prod.definition - }) - ]); - return getAlternativesForProd(newDef); - } - else if (prod instanceof gast_public_RepetitionMandatoryWithSeparator) { - var newDef = [ - new gast_public_Alternative({ definition: prod.definition }), - new gast_public_Repetition({ - definition: [new gast_public_Terminal({ terminalType: prod.separator })].concat(prod.definition) - }) - ]; - return getAlternativesForProd(newDef); - } - else if (prod instanceof gast_public_RepetitionWithSeparator) { - var newDef = prod.definition.concat([ - new gast_public_Repetition({ - definition: [new gast_public_Terminal({ terminalType: prod.separator })].concat(prod.definition) - }) - ]); - result = getAlternativesForProd(newDef); - } - else if (prod instanceof gast_public_Repetition) { - var newDef = prod.definition.concat([ - new gast_public_Repetition({ - definition: prod.definition - }) - ]); - result = getAlternativesForProd(newDef); - } - else if (prod instanceof gast_public_Alternation) { - Object(utils["u" /* forEach */])(prod.definition, function (currAlt) { - // TODO: this is a limited check for empty alternatives - // It would prevent a common case of infinite loops during parser initialization. - // However **in-directly** empty alternatives may still cause issues. - if (Object(utils["A" /* isEmpty */])(currAlt.definition) === false) { - result = getAlternativesForProd(currAlt.definition); - } - }); - return result; - } - else if (prod instanceof gast_public_Terminal) { - currPath.push(prod.terminalType); - } - else { - throw Error("non exhaustive match"); - } - i++; - } - result.push({ - partialPath: currPath, - suffixDef: Object(utils["m" /* 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 (!Object(utils["A" /* 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 && - Object(utils["H" /* 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 (Object(utils["A" /* isEmpty */])(currDef)) { - continue; - } - var prod = currDef[0]; - /* istanbul ignore else */ - if (prod === EXIT_NON_TERMINAL) { - var nextPath = { - idx: currIdx, - def: Object(utils["m" /* drop */])(currDef), - ruleStack: Object(utils["n" /* dropRight */])(currRuleStack), - occurrenceStack: Object(utils["n" /* dropRight */])(currOccurrenceStack) - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof gast_public_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: Object(utils["m" /* 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_public_NonTerminal) { - var newRuleStack = Object(utils["g" /* cloneArr */])(currRuleStack); - newRuleStack.push(prod.nonTerminalName); - var newOccurrenceStack = Object(utils["g" /* cloneArr */])(currOccurrenceStack); - newOccurrenceStack.push(prod.idx); - var nextPath = { - idx: currIdx, - def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, Object(utils["m" /* drop */])(currDef)), - ruleStack: newRuleStack, - occurrenceStack: newOccurrenceStack - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof gast_public_Option) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - var nextPathWithout = { - idx: currIdx, - def: Object(utils["m" /* 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(Object(utils["m" /* drop */])(currDef)), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWith); - } - else if (prod instanceof gast_public_RepetitionMandatory) { - // TODO:(THE NEW operators here take a while...) (convert once?) - var secondIteration = new gast_public_Repetition({ - definition: prod.definition, - idx: prod.idx - }); - var nextDef = prod.definition.concat([secondIteration], Object(utils["m" /* drop */])(currDef)); - var nextPath = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof gast_public_RepetitionMandatoryWithSeparator) { - // TODO:(THE NEW operators here take a while...) (convert once?) - var separatorGast = new gast_public_Terminal({ - terminalType: prod.separator - }); - var secondIteration = new gast_public_Repetition({ - definition: [separatorGast].concat(prod.definition), - idx: prod.idx - }); - var nextDef = prod.definition.concat([secondIteration], Object(utils["m" /* drop */])(currDef)); - var nextPath = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPath); - } - else if (prod instanceof gast_public_RepetitionWithSeparator) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - var nextPathWithout = { - idx: currIdx, - def: Object(utils["m" /* 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_public_Terminal({ - terminalType: prod.separator - }); - var nthRepetition = new gast_public_Repetition({ - definition: [separatorGast].concat(prod.definition), - idx: prod.idx - }); - var nextDef = prod.definition.concat([nthRepetition], Object(utils["m" /* drop */])(currDef)); - var nextPathWith = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWith); - } - else if (prod instanceof gast_public_Repetition) { - // the order of alternatives is meaningful, FILO (Last path will be traversed first). - var nextPathWithout = { - idx: currIdx, - def: Object(utils["m" /* 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_public_Repetition({ - definition: prod.definition, - idx: prod.idx - }); - var nextDef = prod.definition.concat([nthRepetition], Object(utils["m" /* drop */])(currDef)); - var nextPathWith = { - idx: currIdx, - def: nextDef, - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(nextPathWith); - } - else if (prod instanceof gast_public_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(Object(utils["m" /* drop */])(currDef)), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }; - possiblePaths.push(currAltPath); - possiblePaths.push(EXIT_ALTERNATIVE); - } - } - else if (prod instanceof gast_public_Alternative) { - possiblePaths.push({ - idx: currIdx, - def: prod.definition.concat(Object(utils["m" /* drop */])(currDef)), - ruleStack: currRuleStack, - occurrenceStack: currOccurrenceStack - }); - } - else if (prod instanceof gast_public_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 = Object(utils["g" /* cloneArr */])(currRuleStack); - newRuleStack.push(topRule.name); - var newCurrOccurrenceStack = Object(utils["g" /* 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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/grammar/lookahead.js -var lookahead_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_public_Option) { - return PROD_TYPE.OPTION; - } - else if (prod instanceof gast_public_Repetition) { - return PROD_TYPE.REPETITION; - } - else if (prod instanceof gast_public_RepetitionMandatory) { - return PROD_TYPE.REPETITION_MANDATORY; - } - else if (prod instanceof gast_public_RepetitionMandatoryWithSeparator) { - return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR; - } - else if (prod instanceof gast_public_RepetitionWithSeparator) { - return PROD_TYPE.REPETITION_WITH_SEPARATOR; - } - else if (prod instanceof gast_public_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) - ? tokenStructuredMatcherNoCategories - : 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) - ? tokenStructuredMatcherNoCategories - : tokenStructuredMatcher; - return lookaheadBuilder(lookAheadPaths[0], tokenMatcher, dynamicTokensEnabled); -} -function buildAlternativesLookAheadFunc(alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) { - var numOfAlts = alts.length; - var areAllOneTokenLookahead = Object(utils["o" /* every */])(alts, function (currAlt) { - return Object(utils["o" /* 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 = Object(utils["I" /* 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 = Object(utils["I" /* map */])(alts, function (currAlt) { - return Object(utils["t" /* flatten */])(currAlt); - }); - var choiceToAlt_1 = Object(utils["O" /* reduce */])(singleTokenAlts, function (result, currAlt, idx) { - Object(utils["u" /* forEach */])(currAlt, function (currTokType) { - if (!Object(utils["w" /* has */])(result, currTokType.tokenTypeIdx)) { - result[currTokType.tokenTypeIdx] = idx; - } - Object(utils["u" /* forEach */])(currTokType.categoryMatches, function (currExtendingType) { - if (!Object(utils["w" /* 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 = Object(utils["o" /* 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 = Object(utils["t" /* flatten */])(alt); - if (singleTokensTypes.length === 1 && - Object(utils["A" /* 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 = Object(utils["O" /* reduce */])(singleTokensTypes, function (result, currTokType, idx) { - result[currTokType.tokenTypeIdx] = true; - Object(utils["u" /* 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) { - lookahead_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_RestWalker)); -/** - * Returns the definition of a target production in a top level level rule. - */ -var InsideDefinitionFinderVisitor = /** @class */ (function (_super) { - lookahead_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_visitor_public_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 = Object(utils["I" /* map */])(altsDefs, function (currAlt) { return possiblePathsFrom([currAlt], 1); }); - var finalResult = initializeArrayOfArrays(partialAlts.length); - var altsHashes = Object(utils["I" /* map */])(partialAlts, function (currAltPaths) { - var dict = {}; - Object(utils["u" /* forEach */])(currAltPaths, function (item) { - var keys = pathToHashKeys(item.partialPath); - Object(utils["u" /* 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 || Object(utils["A" /* 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 = possiblePathsFrom(suffixDef, pathLength + 1, currPathPrefix); - newData[altIdx] = newData[altIdx].concat(newPartialPathsAndSuffixes); - // Update keys for new known paths - Object(utils["u" /* forEach */])(newPartialPathsAndSuffixes, function (item) { - var prefixKeys = pathToHashKeys(item.partialPath); - Object(utils["u" /* 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_public_Alternative({ definition: insideDef }); - var afterFlat = new gast_public_Alternative({ 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 && - Object(utils["o" /* every */])(prefix, function (tokType, idx) { - var otherTokType = other[idx]; - return (tokType === otherTokType || - otherTokType.categoryMatchesMap[tokType.tokenTypeIdx]); - })); -} -function areTokenCategoriesNotUsed(lookAheadPaths) { - return Object(utils["o" /* every */])(lookAheadPaths, function (singleAltPaths) { - return Object(utils["o" /* every */])(singleAltPaths, function (singlePath) { - return Object(utils["o" /* every */])(singlePath, function (token) { return Object(utils["A" /* isEmpty */])(token.categoryMatches); }); - }); - }); -} -//# sourceMappingURL=lookahead.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/grammar/checks.js -var checks_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, errMsgProvider, grammarName) { - var duplicateErrors = utils["I" /* map */](topLevels, function (currTopLevel) { - return validateDuplicateProductions(currTopLevel, errMsgProvider); - }); - var leftRecursionErrors = utils["I" /* 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 (Object(utils["o" /* every */])(leftRecursionErrors, utils["A" /* isEmpty */])) { - emptyAltErrors = Object(utils["I" /* map */])(topLevels, function (currTopRule) { - return validateEmptyOrAlternative(currTopRule, errMsgProvider); - }); - ambiguousAltsErrors = Object(utils["I" /* map */])(topLevels, function (currTopRule) { - return validateAmbiguousAlternationAlternatives(currTopRule, globalMaxLookahead, errMsgProvider); - }); - emptyRepetitionErrors = validateSomeNonEmptyLookaheadPath(topLevels, globalMaxLookahead, errMsgProvider); - } - var termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider); - var tokenNameErrors = utils["I" /* map */](tokenTypes, function (currTokType) { - return validateTokenName(currTokType, errMsgProvider); - }); - var tooManyAltsErrors = Object(utils["I" /* map */])(topLevels, function (curRule) { - return validateTooManyAlts(curRule, errMsgProvider); - }); - var ruleNameErrors = Object(utils["I" /* map */])(topLevels, function (curRule) { - return validateRuleName(curRule, errMsgProvider); - }); - var duplicateRulesError = Object(utils["I" /* map */])(topLevels, function (curRule) { - return validateRuleDoesNotAlreadyExist(curRule, topLevels, grammarName, errMsgProvider); - }); - return (utils["t" /* flatten */](duplicateErrors.concat(tokenNameErrors, emptyRepetitionErrors, leftRecursionErrors, emptyAltErrors, ambiguousAltsErrors, termsNamespaceConflictErrors, tooManyAltsErrors, ruleNameErrors, duplicateRulesError))); -} -function validateDuplicateProductions(topLevelRule, errMsgProvider) { - var collectorVisitor = new OccurrenceValidationCollector(); - topLevelRule.accept(collectorVisitor); - var allRuleProductions = collectorVisitor.allProductions; - var productionGroups = utils["v" /* groupBy */](allRuleProductions, identifyProductionForDuplicates); - var duplicates = utils["N" /* pick */](productionGroups, function (currGroup) { - return currGroup.length > 1; - }); - var errors = utils["I" /* map */](utils["U" /* values */](duplicates), function (currDuplicates) { - var firstProd = utils["s" /* first */](currDuplicates); - var msg = errMsgProvider.buildDuplicateFoundError(topLevelRule, currDuplicates); - var dslName = getProductionDslName(firstProd); - var defError = { - message: msg, - type: ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS, - ruleName: topLevelRule.name, - dslName: dslName, - occurrence: firstProd.idx - }; - var param = checks_getExtraProductionArgument(firstProd); - if (param) { - defError.parameter = param; - } - return defError; - }); - return errors; -} -function identifyProductionForDuplicates(prod) { - return getProductionDslName(prod) + "_#_" + prod.idx + "_#_" + checks_getExtraProductionArgument(prod); -} -function checks_getExtraProductionArgument(prod) { - if (prod instanceof gast_public_Terminal) { - return prod.terminalType.name; - } - else if (prod instanceof gast_public_NonTerminal) { - return prod.nonTerminalName; - } - else { - return ""; - } -} -var OccurrenceValidationCollector = /** @class */ (function (_super) { - checks_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_visitor_public_GAstVisitor)); - -var validTermsPattern = /^[a-zA-Z_]\w*$/; -// 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: ParserDefinitionErrorType.INVALID_RULE_NAME, - ruleName: ruleName - }); - } - 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: ParserDefinitionErrorType.INVALID_TOKEN_NAME - }); - } - return errors; -} -function validateRuleDoesNotAlreadyExist(rule, allRules, className, errMsgProvider) { - var errors = []; - var occurrences = Object(utils["O" /* 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: 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["j" /* 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: 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["A" /* isEmpty */](nextNonTerminals)) { - return []; - } - else { - var ruleName = topRule.name; - var foundLeftRecursion = utils["j" /* contains */](nextNonTerminals, topRule); - if (foundLeftRecursion) { - errors.push({ - message: errMsgProvider.buildLeftRecursionError({ - topLevelRule: topRule, - leftRecursionPath: path - }), - type: 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["l" /* difference */](nextNonTerminals, path.concat([topRule])); - var errorsFromNextSteps = utils["I" /* map */](validNextSteps, function (currRefRule) { - var newPath = utils["g" /* cloneArr */](path); - newPath.push(currRefRule); - return validateNoLeftRecursion(topRule, currRefRule, errMsgProvider, newPath); - }); - return errors.concat(utils["t" /* flatten */](errorsFromNextSteps)); - } -} -function getFirstNoneTerminal(definition) { - var result = []; - if (utils["A" /* isEmpty */](definition)) { - return result; - } - var firstProd = utils["s" /* first */](definition); - /* istanbul ignore else */ - if (firstProd instanceof gast_public_NonTerminal) { - result.push(firstProd.referencedRule); - } - else if (firstProd instanceof gast_public_Alternative || - firstProd instanceof gast_public_Option || - firstProd instanceof gast_public_RepetitionMandatory || - firstProd instanceof gast_public_RepetitionMandatoryWithSeparator || - firstProd instanceof gast_public_RepetitionWithSeparator || - firstProd instanceof gast_public_Repetition) { - result = result.concat(getFirstNoneTerminal(firstProd.definition)); - } - else if (firstProd instanceof gast_public_Alternation) { - // each sub definition in alternation is a FLAT - result = utils["t" /* flatten */](utils["I" /* map */](firstProd.definition, function (currSubDef) { - return getFirstNoneTerminal(currSubDef.definition); - })); - } - else if (firstProd instanceof gast_public_Terminal) { - // nothing to see, move along - } - else { - throw Error("non exhaustive match"); - } - var isFirstOptional = isOptionalProd(firstProd); - var hasMore = definition.length > 1; - if (isFirstOptional && hasMore) { - var rest = utils["m" /* drop */](definition); - return result.concat(getFirstNoneTerminal(rest)); - } - else { - return result; - } -} -var OrCollector = /** @class */ (function (_super) { - checks_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_visitor_public_GAstVisitor)); -function validateEmptyOrAlternative(topLevelRule, errMsgProvider) { - var orCollector = new OrCollector(); - topLevelRule.accept(orCollector); - var ors = orCollector.alternations; - var errors = utils["O" /* reduce */](ors, function (errors, currOr) { - var exceptLast = utils["n" /* dropRight */](currOr.definition); - var currErrors = utils["I" /* map */](exceptLast, function (currAlternative, currAltIdx) { - var possibleFirstInAlt = nextPossibleTokensAfter([currAlternative], [], null, 1); - if (utils["A" /* isEmpty */](possibleFirstInAlt)) { - return { - message: errMsgProvider.buildEmptyAlternationError({ - topLevelRule: topLevelRule, - alternation: currOr, - emptyChoiceIdx: currAltIdx - }), - type: ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT, - ruleName: topLevelRule.name, - occurrence: currOr.idx, - alternative: currAltIdx + 1 - }; - } - else { - return null; - } - }); - return errors.concat(utils["i" /* compact */](currErrors)); - }, []); - return errors; -} -function validateAmbiguousAlternationAlternatives(topLevelRule, globalMaxLookahead, errMsgProvider) { - var orCollector = new OrCollector(); - topLevelRule.accept(orCollector); - var ors = orCollector.alternations; - // New Handling of ignoring ambiguities - // - https://github.com/SAP/chevrotain/issues/869 - ors = Object(utils["P" /* reject */])(ors, function (currOr) { return currOr.ignoreAmbiguities === true; }); - var errors = utils["O" /* reduce */](ors, function (result, currOr) { - var currOccurrence = currOr.idx; - var actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead; - var alternatives = 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) { - checks_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_visitor_public_GAstVisitor)); - -function validateTooManyAlts(topLevelRule, errMsgProvider) { - var orCollector = new OrCollector(); - topLevelRule.accept(orCollector); - var ors = orCollector.alternations; - var errors = utils["O" /* reduce */](ors, function (errors, currOr) { - if (currOr.definition.length > 255) { - errors.push({ - message: errMsgProvider.buildTooManyAlternativesError({ - topLevelRule: topLevelRule, - alternation: currOr - }), - type: ParserDefinitionErrorType.TOO_MANY_ALTS, - ruleName: topLevelRule.name, - occurrence: currOr.idx - }); - } - return errors; - }, []); - return errors; -} -function validateSomeNonEmptyLookaheadPath(topLevelRules, maxLookahead, errMsgProvider) { - var errors = []; - Object(utils["u" /* forEach */])(topLevelRules, function (currTopRule) { - var collectorVisitor = new RepetionCollector(); - currTopRule.accept(collectorVisitor); - var allRuleProductions = collectorVisitor.allProductions; - Object(utils["u" /* forEach */])(allRuleProductions, function (currProd) { - var prodType = getProdType(currProd); - var actualMaxLookahead = currProd.maxLookahead || maxLookahead; - var currOccurrence = currProd.idx; - var paths = getLookaheadPathsForOptionalProd(currOccurrence, currTopRule, prodType, actualMaxLookahead); - var pathsInsideProduction = paths[0]; - if (Object(utils["A" /* isEmpty */])(Object(utils["t" /* flatten */])(pathsInsideProduction))) { - var errMsg = errMsgProvider.buildEmptyRepetitionError({ - topLevelRule: currTopRule, - repetition: currProd - }); - errors.push({ - message: errMsg, - type: ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD, - ruleName: currTopRule.name - }); - } - }); - }); - return errors; -} -function checkAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) { - var foundAmbiguousPaths = []; - var identicalAmbiguities = Object(utils["O" /* reduce */])(alternatives, function (result, currAlt, currAltIdx) { - // ignore (skip) ambiguities with this alternative - if (alternation.definition[currAltIdx].ignoreAmbiguities === true) { - return result; - } - Object(utils["u" /* forEach */])(currAlt, function (currPath) { - var altsCurrPathAppearsIn = [currAltIdx]; - Object(utils["u" /* forEach */])(alternatives, function (currOtherAlt, currOtherAltIdx) { - if (currAltIdx !== currOtherAltIdx && - containsPath(currOtherAlt, currPath) && - // ignore (skip) ambiguities with this "other" alternative - alternation.definition[currOtherAltIdx].ignoreAmbiguities !== true) { - altsCurrPathAppearsIn.push(currOtherAltIdx); - } - }); - if (altsCurrPathAppearsIn.length > 1 && - !containsPath(foundAmbiguousPaths, currPath)) { - foundAmbiguousPaths.push(currPath); - result.push({ - alts: altsCurrPathAppearsIn, - path: currPath - }); - } - }); - return result; - }, []); - var currErrors = utils["I" /* map */](identicalAmbiguities, function (currAmbDescriptor) { - var ambgIndices = Object(utils["I" /* 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: 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 = Object(utils["O" /* reduce */])(alternatives, function (result, currAlt, idx) { - var currPathsAndIdx = Object(utils["I" /* map */])(currAlt, function (currPath) { - return { idx: idx, path: currPath }; - }); - return result.concat(currPathsAndIdx); - }, []); - Object(utils["u" /* 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 = Object(utils["r" /* 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. - isStrictPrefixOfPath(searchPathAndIdx.path, targetPath)); - }); - var currPathPrefixErrors = Object(utils["I" /* 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: 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 = Object(utils["I" /* map */])(tokenTypes, function (currToken) { return currToken.name; }); - Object(utils["u" /* forEach */])(topLevels, function (currRule) { - var currRuleName = currRule.name; - if (Object(utils["j" /* contains */])(tokenNames, currRuleName)) { - var errMsg = errMsgProvider.buildNamespaceConflictError(currRule); - errors.push({ - message: errMsg, - type: ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE, - ruleName: currRuleName - }); - } - }); - return errors; -} -//# sourceMappingURL=checks.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast_resolver_public.js - - - - - -function gast_resolver_public_resolveGrammar(options) { - options = Object(utils["k" /* defaults */])(options, { - errMsgProvider: defaultGrammarResolverErrorProvider - }); - var topRulesTable = {}; - Object(utils["u" /* forEach */])(options.rules, function (rule) { - topRulesTable[rule.name] = rule; - }); - return resolveGrammar(topRulesTable, options.errMsgProvider); -} -function gast_resolver_public_validateGrammar(options) { - options = Object(utils["k" /* defaults */])(options, { - errMsgProvider: defaultGrammarValidatorErrorProvider - }); - return validateGrammar(options.rules, options.maxLookahead, options.tokenTypes, options.errMsgProvider, options.grammarName); -} -function assignOccurrenceIndices(options) { - Object(utils["u" /* forEach */])(options.rules, function (currRule) { - var methodsCollector = new gast_DslMethodsCollectorVisitor(); - currRule.accept(methodsCollector); - Object(utils["u" /* forEach */])(methodsCollector.dslMethods, function (methods) { - Object(utils["u" /* forEach */])(methods, function (currMethod, arrIdx) { - currMethod.idx = arrIdx + 1; - }); - }); - }); -} -//# sourceMappingURL=gast_resolver_public.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/exceptions_public.js - -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 Object(utils["j" /* 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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/parser/traits/recoverable.js - - - - - -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_Recoverable = /** @class */ (function () { - function Recoverable() { - } - Recoverable.prototype.initRecoverable = function (config) { - this.firstAfterRepMap = {}; - this.resyncFollows = {}; - this.recoveryEnabled = Object(utils["w" /* has */])(config, "recoveryEnabled") - ? config.recoveryEnabled - : 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 = 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 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 = Object(utils["n" /* 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 (Object(utils["A" /* isEmpty */])(follows)) { - return false; - } - var mismatchedTok = this.LA(1); - var isMisMatchedTokInFollows = Object(utils["q" /* 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 Object(utils["j" /* 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 (Object(utils["j" /* 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; - return Object(utils["I" /* 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 = Object(utils["I" /* map */])(this.buildFullFollowKeyStack(), function (currKey) { - return _this.getFollowSetFromFollowKey(currKey); - }); - return Object(utils["t" /* flatten */])(followStack); - }; - Recoverable.prototype.getFollowSetFromFollowKey = function (followKey) { - if (followKey === EOF_FOLLOW_KEY) { - return [EOF]; - } - var followName = followKey.ruleName + followKey.idxInCallingRule + 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, 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 Object(utils["n" /* 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 = Object(utils["g" /* cloneArr */])(this.RULE_OCCURRENCE_STACK); - var grammarPath = { - ruleStack: pathRuleStack, - occurrenceStack: pathOccurrenceStack, - lastTok: tokType, - lastTokOccurrence: tokIdxInRule - }; - return grammarPath; - }; - Recoverable.prototype.getHumanReadableRuleStack = function () { - var _this = this; - return Object(utils["I" /* 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 = 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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/grammar/keys.js -// 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; -//# sourceMappingURL=keys.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/parser/traits/looksahead.js - - - - - -/** - * Trait responsible for the lookahead related utilities and optimizations. - */ -var looksahead_LooksAhead = /** @class */ (function () { - function LooksAhead() { - } - LooksAhead.prototype.initLooksAhead = function (config) { - this.dynamicTokensEnabled = Object(utils["w" /* has */])(config, "dynamicTokensEnabled") - ? config.dynamicTokensEnabled - : DEFAULT_PARSER_CONFIG.dynamicTokensEnabled; - this.maxLookahead = Object(utils["w" /* has */])(config, "maxLookahead") - ? config.maxLookahead - : DEFAULT_PARSER_CONFIG.maxLookahead; - /* istanbul ignore next - Using plain array as dictionary will be tested on older node.js versions and IE11 */ - this.lookAheadFuncsCache = Object(utils["z" /* 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 (Object(utils["z" /* 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; - Object(utils["u" /* forEach */])(rules, function (currRule) { - _this.TRACE_INIT(currRule.name + " Rule Lookahead", function () { - var _a = collectMethods(currRule), alternation = _a.alternation, repetition = _a.repetition, option = _a.option, repetitionMandatory = _a.repetitionMandatory, repetitionMandatoryWithSeparator = _a.repetitionMandatoryWithSeparator, repetitionWithSeparator = _a.repetitionWithSeparator; - Object(utils["u" /* forEach */])(alternation, function (currProd) { - var prodIdx = currProd.idx === 0 ? "" : currProd.idx; - _this.TRACE_INIT("" + getProductionDslName(currProd) + prodIdx, function () { - var laFunc = buildLookaheadFuncForOr(currProd.idx, currRule, currProd.maxLookahead || _this.maxLookahead, currProd.hasPredicates, _this.dynamicTokensEnabled, _this.lookAheadBuilderForAlternatives); - var key = getKeyForAutomaticLookahead(_this.fullRuleNameToShort[currRule.name], OR_IDX, currProd.idx); - _this.setLaFuncCache(key, laFunc); - }); - }); - Object(utils["u" /* forEach */])(repetition, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, MANY_IDX, PROD_TYPE.REPETITION, currProd.maxLookahead, getProductionDslName(currProd)); - }); - Object(utils["u" /* forEach */])(option, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, OPTION_IDX, PROD_TYPE.OPTION, currProd.maxLookahead, getProductionDslName(currProd)); - }); - Object(utils["u" /* forEach */])(repetitionMandatory, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, AT_LEAST_ONE_IDX, PROD_TYPE.REPETITION_MANDATORY, currProd.maxLookahead, getProductionDslName(currProd)); - }); - Object(utils["u" /* forEach */])(repetitionMandatoryWithSeparator, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, AT_LEAST_ONE_SEP_IDX, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currProd.maxLookahead, getProductionDslName(currProd)); - }); - Object(utils["u" /* forEach */])(repetitionWithSeparator, function (currProd) { - _this.computeLookaheadFunc(currRule, currProd.idx, MANY_SEP_IDX, PROD_TYPE.REPETITION_WITH_SEPARATOR, currProd.maxLookahead, 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 = buildLookaheadFuncForOptionalProd(prodOccurrence, rule, prodMaxLookahead || _this.maxLookahead, _this.dynamicTokensEnabled, prodType, _this.lookAheadBuilderForOptional); - var key = getKeyForAutomaticLookahead(_this.fullRuleNameToShort[rule.name], prodKey, prodOccurrence); - _this.setLaFuncCache(key, laFunc); - }); - }; - LooksAhead.prototype.lookAheadBuilderForOptional = function (alt, tokenMatcher, dynamicTokensEnabled) { - return buildSingleAlternativeLookaheadFunction(alt, tokenMatcher, dynamicTokensEnabled); - }; - LooksAhead.prototype.lookAheadBuilderForAlternatives = function (alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) { - return 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 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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/cst/cst.js -/** - * 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); - } -} -//# sourceMappingURL=cst.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/lang/lang_extensions.js - -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 (Object(utils["F" /* 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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/cst/cst_visitor.js - - - -function defaultVisit(ctx, param) { - var childrenNames = Object(utils["G" /* 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) { - 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 - defineNameProp(derivedConstructor, grammarName + "BaseSemantics"); - var semanticProto = { - visit: function (cstNode, param) { - // enables writing more concise visitor methods when CstNode has only a single child - if (Object(utils["y" /* 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 (Object(utils["F" /* isUndefined */])(cstNode)) { - return undefined; - } - return this[cstNode.name](cstNode.children, param); - }, - validateVisitor: function () { - var semanticDefinitionErrors = validateVisitor(this, ruleNames); - if (!Object(utils["A" /* isEmpty */])(semanticDefinitionErrors)) { - var errorMessages = Object(utils["I" /* map */])(semanticDefinitionErrors, function (currDefError) { return currDefError.msg; }); - throw Error("Errors Detected in CST Visitor <" + 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 - defineNameProp(derivedConstructor, grammarName + "BaseSemanticsWithDefaults"); - var withDefaultsProto = Object.create(baseConstructor.prototype); - Object(utils["u" /* 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 = Object(utils["I" /* map */])(ruleNames, function (currRuleName) { - if (!Object(utils["B" /* isFunction */])(visitorInstance[currRuleName])) { - return { - msg: "Missing visitor method: <" + currRuleName + "> on " + functionName(visitorInstance.constructor) + " CST Visitor.", - type: CstVisitorDefinitionError.MISSING_METHOD, - methodName: currRuleName - }; - } - }); - return Object(utils["i" /* compact */])(errors); -} -var VALID_PROP_NAMES = ["constructor", "visit", "validateVisitor"]; -function validateRedundantMethods(visitorInstance, ruleNames) { - var errors = []; - for (var prop in visitorInstance) { - if (validTermsPattern.test(prop) && - Object(utils["B" /* isFunction */])(visitorInstance[prop]) && - !Object(utils["j" /* contains */])(VALID_PROP_NAMES, prop) && - !Object(utils["j" /* contains */])(ruleNames, prop)) { - errors.push({ - msg: "Redundant visitor method: <" + prop + "> on " + 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 /" + validTermsPattern.source + "/."), - type: CstVisitorDefinitionError.REDUNDANT_METHOD, - methodName: prop - }); - } - } - return errors; -} -//# sourceMappingURL=cst_visitor.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/parser/traits/tree_builder.js - - - - -/** - * This trait is responsible for the CST building logic. - */ -var tree_builder_TreeBuilder = /** @class */ (function () { - function TreeBuilder() { - } - TreeBuilder.prototype.initTreeBuilder = function (config) { - this.CST_STACK = []; - // outputCst is no longer exposed/defined in the pubic API - this.outputCst = config.outputCst; - this.nodeLocationTracking = Object(utils["w" /* has */])(config, "nodeLocationTracking") - ? config.nodeLocationTracking - : DEFAULT_PARSER_CONFIG.nodeLocationTracking; - if (!this.outputCst) { - this.cstInvocationStateUpdate = utils["b" /* NOOP */]; - this.cstFinallyStateUpdate = utils["b" /* NOOP */]; - this.cstPostTerminal = utils["b" /* NOOP */]; - this.cstPostNonTerminal = utils["b" /* NOOP */]; - this.cstPostRule = utils["b" /* NOOP */]; - } - else { - if (/full/i.test(this.nodeLocationTracking)) { - if (this.recoveryEnabled) { - this.setNodeLocationFromToken = setNodeLocationFull; - this.setNodeLocationFromNode = setNodeLocationFull; - this.cstPostRule = utils["b" /* NOOP */]; - this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery; - } - else { - this.setNodeLocationFromToken = utils["b" /* NOOP */]; - this.setNodeLocationFromNode = utils["b" /* NOOP */]; - this.cstPostRule = this.cstPostRuleFull; - this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular; - } - } - else if (/onlyOffset/i.test(this.nodeLocationTracking)) { - if (this.recoveryEnabled) { - this.setNodeLocationFromToken = setNodeLocationOnlyOffset; - this.setNodeLocationFromNode = setNodeLocationOnlyOffset; - this.cstPostRule = utils["b" /* NOOP */]; - this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery; - } - else { - this.setNodeLocationFromToken = utils["b" /* NOOP */]; - this.setNodeLocationFromNode = utils["b" /* NOOP */]; - this.cstPostRule = this.cstPostRuleOnlyOffset; - this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular; - } - } - else if (/none/i.test(this.nodeLocationTracking)) { - this.setNodeLocationFromToken = utils["b" /* NOOP */]; - this.setNodeLocationFromNode = utils["b" /* NOOP */]; - this.cstPostRule = utils["b" /* NOOP */]; - this.setInitialNodeLocation = utils["b" /* NOOP */]; - } - else { - throw Error("Invalid 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 - }; - }; - TreeBuilder.prototype.cstInvocationStateUpdate = function (fullRuleName, shortName) { - var cstNode = { - name: fullRuleName, - children: {} - }; - this.setInitialNodeLocation(cstNode); - this.CST_STACK.push(cstNode); - }; - TreeBuilder.prototype.cstFinallyStateUpdate = function () { - this.CST_STACK.pop(); - }; - 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. - 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. - 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]; - 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) { - var preCstNode = this.CST_STACK[this.CST_STACK.length - 1]; - 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 (Object(utils["F" /* isUndefined */])(this.baseCstVisitorConstructor)) { - var newBaseCstVisitorConstructor = createBaseSemanticVisitorConstructor(this.className, Object(utils["G" /* keys */])(this.gastProductionsCache)); - this.baseCstVisitorConstructor = newBaseCstVisitorConstructor; - return newBaseCstVisitorConstructor; - } - return this.baseCstVisitorConstructor; - }; - TreeBuilder.prototype.getBaseCstVisitorConstructorWithDefaults = function () { - if (Object(utils["F" /* isUndefined */])(this.baseCstVisitorWithDefaultsConstructor)) { - var newConstructor = createBaseVisitorConstructorWithDefaults(this.className, Object(utils["G" /* keys */])(this.gastProductionsCache), this.getBaseCstVisitorConstructor()); - this.baseCstVisitorWithDefaultsConstructor = newConstructor; - return newConstructor; - } - return this.baseCstVisitorWithDefaultsConstructor; - }; - TreeBuilder.prototype.getLastExplicitRuleShortName = function () { - var ruleStack = this.RULE_STACK; - return ruleStack[ruleStack.length - 1]; - }; - TreeBuilder.prototype.getPreviousExplicitRuleShortName = function () { - var ruleStack = this.RULE_STACK; - return ruleStack[ruleStack.length - 2]; - }; - TreeBuilder.prototype.getLastExplicitRuleOccurrenceIndex = function () { - var occurrenceStack = this.RULE_OCCURRENCE_STACK; - return occurrenceStack[occurrenceStack.length - 1]; - }; - return TreeBuilder; -}()); - -//# sourceMappingURL=tree_builder.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/parser/traits/lexer_adapter.js - -/** - * 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 lexer_adapter_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) { - // @ts-ignore - `this parameter` not supported in setters/getters - // - https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters - if (this.selfAnalysisDone !== true) { - throw Error("Missing invocation at the end of the Parser's constructor."); - } - // @ts-ignore - `this parameter` not supported in setters/getters - // - https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters - this.reset(); - this.tokVector = newInput; - this.tokVectorLength = newInput.length; - }, - enumerable: false, - 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 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 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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/parser/traits/recognizer_api.js - - - - - - -/** - * This trait is responsible for implementing the public API - * for defining Chevrotain parsers, i.e: - * - CONSUME - * - RULE - * - OPTION - * - ... - */ -var recognizer_api_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 = DEFAULT_RULE_CONFIG; } - if (Object(utils["j" /* contains */])(this.definedRulesNames, name)) { - var errMsg = defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({ - topLevelRule: name, - grammarName: this.className - }); - var error = { - message: errMsg, - type: 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 = DEFAULT_RULE_CONFIG; } - var ruleErrors = []; - ruleErrors = ruleErrors.concat(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 (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 serializeGrammar(Object(utils["U" /* values */])(this.gastProductionsCache)); - }; - return RecognizerApi; -}()); - -//# sourceMappingURL=recognizer_api.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/parser/traits/recognizer_engine.js - - - - - - - - - - -/** - * This trait is responsible for the runtime parsing engine - * Used by the official API (recognizer_api.ts) - */ -var recognizer_engine_RecognizerEngine = /** @class */ (function () { - function RecognizerEngine() { - } - RecognizerEngine.prototype.initRecognizerEngine = function (tokenVocabulary, config) { - this.className = 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 = tokenStructuredMatcherNoCategories; - this.definedRulesNames = []; - this.tokensMap = {}; - this.isBackTrackingStack = []; - this.RULE_STACK = []; - this.RULE_OCCURRENCE_STACK = []; - this.gastProductionsCache = {}; - if (Object(utils["w" /* has */])(config, "serializedGrammar")) { - throw Error("The Parser's configuration can no longer contain a property.\n" + - "\tSee: https://sap.github.io/chevrotain/docs/changes/BREAKING_CHANGES.html#_6-0-0\n" + - "\tFor Further details."); - } - if (Object(utils["y" /* 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 (Object(utils["A" /* 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 (Object(utils["y" /* isArray */])(tokenVocabulary)) { - this.tokensMap = Object(utils["O" /* reduce */])(tokenVocabulary, function (acc, tokType) { - acc[tokType.name] = tokType; - return acc; - }, {}); - } - else if (Object(utils["w" /* has */])(tokenVocabulary, "modes") && - Object(utils["o" /* every */])(Object(utils["t" /* flatten */])(Object(utils["U" /* values */])(tokenVocabulary.modes)), isTokenType)) { - var allTokenTypes = Object(utils["t" /* flatten */])(Object(utils["U" /* values */])(tokenVocabulary.modes)); - var uniqueTokens = Object(utils["T" /* uniq */])(allTokenTypes); - this.tokensMap = Object(utils["O" /* reduce */])(uniqueTokens, function (acc, tokType) { - acc[tokType.name] = tokType; - return acc; - }, {}); - } - else if (Object(utils["C" /* isObject */])(tokenVocabulary)) { - this.tokensMap = Object(utils["h" /* cloneObj */])(tokenVocabulary); - } - else { - throw new Error(" 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"] = EOF; - // TODO: This check may not be accurate for multi mode lexers - var noTokenCategoriesUsed = Object(utils["o" /* every */])(Object(utils["U" /* values */])(tokenVocabulary), function (tokenConstructor) { return Object(utils["A" /* isEmpty */])(tokenConstructor.categoryMatches); }); - this.tokenMatcher = noTokenCategoriesUsed - ? tokenStructuredMatcherNoCategories - : 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 - augmentTokenTypes(Object(utils["U" /* 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 = Object(utils["w" /* has */])(config, "resyncEnabled") - ? config.resyncEnabled - : DEFAULT_RULE_CONFIG.resyncEnabled; - var recoveryValueFunc = Object(utils["w" /* has */])(config, "recoveryValueFunc") - ? config.recoveryValueFunc - : 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 << (BITS_FOR_METHOD_TYPE + 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 (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(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(AT_LEAST_ONE_IDX, prodOccurrence); - return this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, laKey); - }; - 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, 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, AT_LEAST_ONE_IDX, prodOccurrence, interpreter_NextTerminalAfterAtLeastOneWalker); - }; - RecognizerEngine.prototype.atLeastOneSepFirstInternal = function (prodOccurrence, options) { - var laKey = this.getKeyForAutomaticLookahead(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, - interpreter_NextTerminalAfterAtLeastOneSepWalker - ], separatorLookAheadFunc, AT_LEAST_ONE_SEP_IDX, prodOccurrence, interpreter_NextTerminalAfterAtLeastOneSepWalker); - } - else { - throw this.raiseEarlyExitException(prodOccurrence, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, options.ERR_MSG); - } - }; - RecognizerEngine.prototype.manyInternal = function (prodOccurrence, actionORMethodDef) { - var laKey = this.getKeyForAutomaticLookahead(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, MANY_IDX, prodOccurrence, interpreter_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(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, - interpreter_NextTerminalAfterManySepWalker - ], separatorLookAheadFunc, MANY_SEP_IDX, prodOccurrence, interpreter_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, 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.orInternal = function (altsOrOpts, occurrence) { - var laKey = this.getKeyForAutomaticLookahead(OR_IDX, occurrence); - var alts = Object(utils["y" /* isArray */])(altsOrOpts) - ? altsOrOpts - : altsOrOpts.DEF; - 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.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 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 (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 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 === 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 = Object(utils["g" /* cloneArr */])(this.RULE_STACK); - return { - errors: savedErrors, - lexerState: this.exportLexerState(), - RULE_STACK: savedRuleStack, - CST_STACK: this.CST_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), EOF); - }; - RecognizerEngine.prototype.reset = function () { - this.resetLexerState(); - this.isBackTrackingStack = []; - this.errors = []; - this.RULE_STACK = []; - // TODO: extract a specific reset for TreeBuilder trait - this.CST_STACK = []; - this.RULE_OCCURRENCE_STACK = []; - }; - return RecognizerEngine; -}()); - -//# sourceMappingURL=recognizer_engine.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/parser/traits/error_handler.js - - - - -/** - * Trait responsible for runtime parsing errors. - */ -var error_handler_ErrorHandler = /** @class */ (function () { - function ErrorHandler() { - } - ErrorHandler.prototype.initErrorHandler = function (config) { - this._errors = []; - this.errorMessageProvider = Object(utils["w" /* has */])(config, "errorMessageProvider") - ? config.errorMessageProvider - : DEFAULT_PARSER_CONFIG.errorMessageProvider; - }; - ErrorHandler.prototype.SAVE_ERROR = function (error) { - if (isRecognitionException(error)) { - error.context = { - ruleStack: this.getHumanReadableRuleStack(), - ruleOccurrenceStack: Object(utils["g" /* 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", { - get: function () { - return Object(utils["g" /* cloneArr */])(this._errors); - }, - set: function (newErrors) { - this._errors = newErrors; - }, - enumerable: false, - 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 = 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 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 = 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 NoViableAltException(errMsg, this.LA(1), previousToken)); - }; - return ErrorHandler; -}()); - -//# sourceMappingURL=error_handler.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/parser/traits/context_assist.js - - -var context_assist_ContentAssist = /** @class */ (function () { - function ContentAssist() { - } - ContentAssist.prototype.initContentAssist = function () { }; - ContentAssist.prototype.computeContentAssist = function (startRuleName, precedingInput) { - var startRuleGast = this.gastProductionsCache[startRuleName]; - if (Object(utils["F" /* isUndefined */])(startRuleGast)) { - throw Error("Rule ->" + startRuleName + "<- does not exist in this grammar."); - } - return 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 = Object(utils["s" /* first */])(grammarPath.ruleStack); - var gastProductions = this.getGAstProductions(); - var topProduction = gastProductions[topRuleName]; - var nextPossibleTokenTypes = new interpreter_NextAfterTokenWalker(topProduction, grammarPath).startWalking(); - return nextPossibleTokenTypes; - }; - return ContentAssist; -}()); - -//# sourceMappingURL=context_assist.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/parser/traits/gast_recorder.js - - - - - - - -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, BITS_FOR_OCCURRENCE_IDX) - 1; -var RFT = createToken({ name: "RECORDING_PHASE_TOKEN", pattern: lexer_public_Lexer.NA }); -augmentTokenTypes([RFT]); -var RECORDING_PHASE_TOKEN = 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 gast_recorder_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 END_OF_FILE; - }; - GastRecorder.prototype.topLevelRuleRecord = function (name, def) { - try { - var newTopLevelRule = new gast_public_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, gast_public_Option, actionORMethodDef, occurrence); - }; - GastRecorder.prototype.atLeastOneInternalRecord = function (occurrence, actionORMethodDef) { - recordProd.call(this, gast_public_RepetitionMandatory, actionORMethodDef, occurrence); - }; - GastRecorder.prototype.atLeastOneSepFirstInternalRecord = function (occurrence, options) { - recordProd.call(this, gast_public_RepetitionMandatoryWithSeparator, options, occurrence, HANDLE_SEPARATOR); - }; - GastRecorder.prototype.manyInternalRecord = function (occurrence, actionORMethodDef) { - recordProd.call(this, gast_public_Repetition, actionORMethodDef, occurrence); - }; - GastRecorder.prototype.manySepFirstInternalRecord = function (occurrence, options) { - recordProd.call(this, gast_public_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 || Object(utils["w" /* has */])(ruleToCall, "ruleName") === false) { - var error = new Error(" 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 = Object(utils["M" /* peek */])(this.recordingProdStack); - var ruleName = ruleToCall["ruleName"]; - var newNoneTerminal = new gast_public_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 (!hasShortKeyProperty(tokType)) { - var error = new Error(" 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 = Object(utils["M" /* peek */])(this.recordingProdStack); - var newNoneTerminal = new gast_public_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 = Object(utils["M" /* peek */])(this.recordingProdStack); - var grammarAction = Object(utils["B" /* isFunction */])(mainProdArg) ? mainProdArg : mainProdArg.DEF; - var newProd = new prodConstructor({ definition: [], idx: occurrence }); - if (handleSep) { - newProd.separator = mainProdArg.SEP; - } - if (Object(utils["w" /* 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 = Object(utils["M" /* peek */])(this.recordingProdStack); - // Only an array of alternatives - var hasOptions = Object(utils["y" /* isArray */])(mainProdArg) === false; - var alts = hasOptions === false ? mainProdArg : mainProdArg.DEF; - var newOrProd = new gast_public_Alternation({ - definition: [], - idx: occurrence, - ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true - }); - if (Object(utils["w" /* has */])(mainProdArg, "MAX_LOOKAHEAD")) { - newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD; - } - var hasPredicates = Object(utils["Q" /* some */])(alts, function (currAlt) { return Object(utils["B" /* isFunction */])(currAlt.GATE); }); - newOrProd.hasPredicates = hasPredicates; - prevProd.definition.push(newOrProd); - Object(utils["u" /* forEach */])(alts, function (currAlt) { - var currAltFlat = new gast_public_Alternative({ definition: [] }); - newOrProd.definition.push(currAltFlat); - if (Object(utils["w" /* has */])(currAlt, "IGNORE_AMBIGUITIES")) { - currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES; - } - // **implicit** ignoreAmbiguities due to usage of gate - else if (Object(utils["w" /* 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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/parser/traits/perf_tracer.js - - -/** - * Trait responsible for runtime parsing errors. - */ -var perf_tracer_PerformanceTracer = /** @class */ (function () { - function PerformanceTracer() { - } - PerformanceTracer.prototype.initPerformanceTracer = function (config) { - if (Object(utils["w" /* 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 = 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 = Object(utils["R" /* 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 -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/parse/parser/parser.js -var parser_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 = createTokenInstance(EOF, "", NaN, NaN, NaN, NaN, NaN, NaN); -Object.freeze(END_OF_FILE); -var DEFAULT_PARSER_CONFIG = Object.freeze({ - recoveryEnabled: false, - maxLookahead: 3, - dynamicTokensEnabled: false, - outputCst: true, - errorMessageProvider: 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["NO_NON_EMPTY_LOOKAHEAD"] = 10] = "NO_NON_EMPTY_LOOKAHEAD"; - ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_PREFIX_ALTS"] = 11] = "AMBIGUOUS_PREFIX_ALTS"; - ParserDefinitionErrorType[ParserDefinitionErrorType["TOO_MANY_ALTS"] = 12] = "TOO_MANY_ALTS"; -})(ParserDefinitionErrorType || (ParserDefinitionErrorType = {})); -function EMPTY_ALT(value) { - if (value === void 0) { value = undefined; } - return function () { - return value; - }; -} -var parser_Parser = /** @class */ (function () { - function Parser(tokenVocabulary, config) { - 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); - if (Object(utils["w" /* has */])(config, "ignoredIssues")) { - throw new Error("The IParserConfig property has been deprecated.\n\t" + - "Please use the flag on the relevant DSL method instead.\n\t" + - "See: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES\n\t" + - "For further details."); - } - this.skipValidations = Object(utils["w" /* has */])(config, "skipValidations") - ? config.skipValidations - : DEFAULT_PARSER_CONFIG.skipValidations; - } - /** - * @deprecated use the **instance** method with the same name instead - */ - Parser.performSelfAnalysis = function (parserInstance) { - throw Error("The **static** `performSelfAnalysis` method has been deprecated." + - "\t\nUse the **instance** method with the same name instead."); - }; - 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. - Object(utils["S" /* toFastProperties */])(_this); - }); - _this.TRACE_INIT("Grammar Recording", function () { - try { - _this.enableRecording(); - // Building the GAST - Object(utils["u" /* 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 = gast_resolver_public_resolveGrammar({ - rules: Object(utils["U" /* 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 (Object(utils["A" /* isEmpty */])(resolverErrors) && _this.skipValidations === false) { - var validationErrors = gast_resolver_public_validateGrammar({ - rules: Object(utils["U" /* values */])(_this.gastProductionsCache), - maxLookahead: _this.maxLookahead, - tokenTypes: Object(utils["U" /* values */])(_this.tokensMap), - errMsgProvider: 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 (Object(utils["A" /* 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 = computeAllProdsFollows(Object(utils["U" /* values */])(_this.gastProductionsCache)); - _this.resyncFollows = allFollows; - }); - } - _this.TRACE_INIT("ComputeLookaheadFunctions", function () { - _this.preComputeLookaheadFunctions(Object(utils["U" /* values */])(_this.gastProductionsCache)); - }); - } - if (!Parser.DEFER_DEFINITION_ERRORS_HANDLING && - !Object(utils["A" /* isEmpty */])(_this.definitionErrors)) { - defErrorsMsgs = Object(utils["I" /* 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; -}()); - -Object(utils["e" /* applyMixins */])(parser_Parser, [ - recoverable_Recoverable, - looksahead_LooksAhead, - tree_builder_TreeBuilder, - lexer_adapter_LexerAdapter, - recognizer_engine_RecognizerEngine, - recognizer_api_RecognizerApi, - error_handler_ErrorHandler, - context_assist_ContentAssist, - gast_recorder_GastRecorder, - perf_tracer_PerformanceTracer -]); -var parser_CstParser = /** @class */ (function (_super) { - parser_extends(CstParser, _super); - function CstParser(tokenVocabulary, config) { - if (config === void 0) { config = DEFAULT_PARSER_CONFIG; } - var _this = this; - var configClone = Object(utils["h" /* cloneObj */])(config); - configClone.outputCst = true; - _this = _super.call(this, tokenVocabulary, configClone) || this; - return _this; - } - return CstParser; -}(parser_Parser)); - -var parser_EmbeddedActionsParser = /** @class */ (function (_super) { - parser_extends(EmbeddedActionsParser, _super); - function EmbeddedActionsParser(tokenVocabulary, config) { - if (config === void 0) { config = DEFAULT_PARSER_CONFIG; } - var _this = this; - var configClone = Object(utils["h" /* cloneObj */])(config); - configClone.outputCst = false; - _this = _super.call(this, tokenVocabulary, configClone) || this; - return _this; - } - return EmbeddedActionsParser; -}(parser_Parser)); - -//# sourceMappingURL=parser.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/diagrams/render_public.js - -function createSyntaxDiagramsCode(grammar, _a) { - var _b = _a === void 0 ? {} : _a, _c = _b.resourceBase, resourceBase = _c === void 0 ? "https://unpkg.com/chevrotain@" + VERSION + "/diagrams/" : _c, _d = _b.css, css = _d === void 0 ? "https://unpkg.com/chevrotain@" + VERSION + "/diagrams/diagrams.css" : _d; - var header = "\n\n\n\n\n\n"; - var cssHtml = "\n\n"; - var scripts = "\n\n\n\n\n"; - var diagramsDiv = "\n
\n"; - var serializedGrammar = "\n\n"; - var initLogic = "\n\n"; - return (header + cssHtml + scripts + diagramsDiv + serializedGrammar + initLogic); -} -//# sourceMappingURL=render_public.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/generate/generate.js - - -/** - * 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 = Object(utils["I" /* map */])(rules, function (currRule) { - return genRule(currRule, 1); - }); - return rulesText.join("\n"); -} -function genRule(prod, n) { - var result = generate_indent(n, "$.RULE(\"" + prod.name + "\", function() {") + NL; - result += genDefinition(prod.definition, n + 1); - result += generate_indent(n + 1, "})") + NL; - return result; -} -function genTerminal(prod, n) { - var name = prod.terminalType.name; - // TODO: potential performance optimization, avoid tokenMap Dictionary access - return generate_indent(n, "$.CONSUME" + prod.idx + "(this.tokensMap." + name + ")" + NL); -} -function genNonTerminal(prod, n) { - return generate_indent(n, "$.SUBRULE" + prod.idx + "($." + prod.nonTerminalName + ")" + NL); -} -function genAlternation(prod, n) { - var result = generate_indent(n, "$.OR" + prod.idx + "([") + NL; - var alts = Object(utils["I" /* map */])(prod.definition, function (altDef) { return genSingleAlt(altDef, n + 1); }); - result += alts.join("," + NL); - result += NL + generate_indent(n, "])" + NL); - return result; -} -function genSingleAlt(prod, n) { - var result = generate_indent(n, "{") + NL; - result += generate_indent(n + 1, "ALT: function() {") + NL; - result += genDefinition(prod.definition, n + 1); - result += generate_indent(n + 1, "}") + NL; - result += generate_indent(n, "}"); - return result; -} -function genProd(prod, n) { - /* istanbul ignore else */ - if (prod instanceof gast_public_NonTerminal) { - return genNonTerminal(prod, n); - } - else if (prod instanceof gast_public_Option) { - return genDSLRule("OPTION", prod, n); - } - else if (prod instanceof gast_public_RepetitionMandatory) { - return genDSLRule("AT_LEAST_ONE", prod, n); - } - else if (prod instanceof gast_public_RepetitionMandatoryWithSeparator) { - return genDSLRule("AT_LEAST_ONE_SEP", prod, n); - } - else if (prod instanceof gast_public_RepetitionWithSeparator) { - return genDSLRule("MANY_SEP", prod, n); - } - else if (prod instanceof gast_public_Repetition) { - return genDSLRule("MANY", prod, n); - } - else if (prod instanceof gast_public_Alternation) { - return genAlternation(prod, n); - } - else if (prod instanceof gast_public_Terminal) { - return genTerminal(prod, n); - } - else if (prod instanceof gast_public_Alternative) { - return genDefinition(prod.definition, n); - } - else { - throw Error("non exhaustive match"); - } -} -function genDSLRule(dslName, prod, n) { - var result = generate_indent(n, "$." + (dslName + prod.idx) + "("); - if (prod.separator) { - result += "{" + NL; - result += - generate_indent(n + 1, "SEP: this.tokensMap." + prod.separator.name) + "," + NL; - result += "DEF: " + genDefFunction(prod.definition, n + 2) + NL; - result += generate_indent(n, "}") + NL; - } - else { - result += genDefFunction(prod.definition, n + 1); - } - result += generate_indent(n, ")") + NL; - return result; -} -function genDefFunction(definition, n) { - var def = "function() {" + NL; - def += genDefinition(definition, n); - def += generate_indent(n, "}") + NL; - return def; -} -function genDefinition(def, n) { - var result = ""; - Object(utils["u" /* forEach */])(def, function (prod) { - result += genProd(prod, n + 1); - }); - return result; -} -function generate_indent(howMuch, text) { - var spaces = Array(howMuch * 4 + 1).join(" "); - return spaces + text; -} -//# sourceMappingURL=generate.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/generate/generate_public.js - -function generateParserFactory(options) { - var wrapperText = 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__(2)); - }; -} -function generateParserModule(options) { - return genUmdModule({ name: options.name, rules: options.rules }); -} -//# sourceMappingURL=generate_public.js.map -// CONCATENATED MODULE: ./node_modules/chevrotain/lib_esm/src/api.js -/* istanbul ignore file - tricky to import some things from this module during testing */ -// 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"); -} - - -var api_Parser = /** @class */ (function () { - function Parser() { - throw new Error("The Parser class has been deprecated, use CstParser or EmbeddedActionsParser instead.\t\n" + - "See: https://sap.github.io/chevrotain/docs/changes/BREAKING_CHANGES.html#_7-0-0"); - } - return Parser; -}()); - -//# sourceMappingURL=api.js.map - -/***/ }), -/* 3 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -Object.defineProperty(exports, "__esModule", { value: true }); -__webpack_require__(4); -const tokenizer_1 = __webpack_require__(5); -/* -$(function() { - -}); -*/ -const result = tokenizer_1.Human2RegexLexer.tokenize(` -// H2R supports // # and /**/ as comments -// A group is only captured if given a name. -// You can use "and", "or", "not" to specify "[]" regex -// You can use "then" to combine match statements, however I find using multiple "match" statements easier to read - -// exact matching means use a ^ and $ to signify the start and end of the string - -using global and exact matching -create an optional group called "protocol" - match "http" - optionally match "s" - match "://" -create a group called "subdomain" - repeat - match 1+ words - match "." -create a group called "domain" - match 1+ words or "_" or "-" - match "." - match a word -# port, but we don't care about it, so ignore it -optionally match ":" then 0+ digits -create an optional group called "path" - repeat - match "/" - match 0+ words or "_" or "-" -create an optional group - # we don't want to capture the '?', so don't name the group until afterwards - match "?" - create a group called "query" - repeat - match 1+ words or "_" or "-" - match "=" - match 1+ words or "_" or "-" -create an optional group - # fragment, again, we don't care, so ignore everything afterwards - match "#" - match 0+ any thing -`); -for (const r of result.tokens) { - console.log(r); -} -console.log(result.errors); - - -/***/ }), -/* 4 */ -/***/ (function(module, __webpack_exports__, __webpack_require__) { - -"use strict"; -__webpack_require__.r(__webpack_exports__); -// extracted by mini-css-extract-plugin - - -/***/ }), -/* 5 */ -/***/ (function(module, exports, __webpack_require__) { - -"use strict"; - -/*! Copyright (c) 2020 Patrick Demian; Licensed under MIT */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Human2RegexLexer = exports.AllTokens = exports.StringLiteral = exports.NumberLiteral = exports.Identifier = exports.MultilineComment = exports.SingleLineComment = exports.WhiteSpace = exports.EndOfLine = exports.Indent = exports.OrMore = exports.CaseSensitive = exports.CaseInsensitive = exports.CarriageReturn = exports.Neither = exports.None = exports.Newline = exports.Repeat = exports.Called = exports.Create = exports.To = exports.From = exports.exclusive = exports.Inclusive = exports.Exactly = exports.The = exports.A = exports.By = exports.Group = exports.Linefeed = exports.Tab = exports.Between = exports.Not = exports.Nothing = exports.Matching = exports.Exact = exports.Multiline = exports.Global = exports.Using = exports.More = exports.While = exports.Unless = exports.Else = exports.Otherwise = exports.Ends = exports.With = exports.Start = exports.If = exports.As = exports.Multiple = exports.Number = exports.Whitespace = exports.Character = exports.Digit = exports.Word = exports.And = exports.Or = exports.Of = exports.Anything = exports.Then = exports.Match = exports.Optional = exports.Ten = exports.Nine = exports.Eight = exports.Seven = exports.Six = exports.Five = exports.Four = exports.Three = exports.Two = exports.One = exports.Zero = void 0; -const chevrotain_1 = __webpack_require__(2); -exports.Zero = chevrotain_1.createToken({ name: "Zero", pattern: /zero/i }); -exports.One = chevrotain_1.createToken({ name: "One", pattern: /one/i }); -exports.Two = chevrotain_1.createToken({ name: "Two", pattern: /two/i }); -exports.Three = chevrotain_1.createToken({ name: "Three", pattern: /three/i }); -exports.Four = chevrotain_1.createToken({ name: "Four", pattern: /four/i }); -exports.Five = chevrotain_1.createToken({ name: "Five", pattern: /five/i }); -exports.Six = chevrotain_1.createToken({ name: "Six", pattern: /six/i }); -exports.Seven = chevrotain_1.createToken({ name: "Seven", pattern: /seven/i }); -exports.Eight = chevrotain_1.createToken({ name: "Eight", pattern: /eight/i }); -exports.Nine = chevrotain_1.createToken({ name: "Nine", pattern: /nine/i }); -exports.Ten = chevrotain_1.createToken({ name: "Ten", pattern: /ten/i }); -exports.Optional = chevrotain_1.createToken({ name: "Optional", pattern: /optional(ly)?/i }); -exports.Match = chevrotain_1.createToken({ name: "Match", pattern: /match(es)?/i }); -exports.Then = chevrotain_1.createToken({ name: "Then", pattern: /then/i }); -exports.Anything = chevrotain_1.createToken({ name: "Anything", pattern: /(any|anything|any thing)(s)?/i }); -exports.Of = chevrotain_1.createToken({ name: "Of", pattern: /of/i }); -exports.Or = chevrotain_1.createToken({ name: "Or", pattern: /or/i }); -exports.And = chevrotain_1.createToken({ name: "And", pattern: /and/i }); -exports.Word = chevrotain_1.createToken({ name: "WordSpecifier", pattern: /word(s)?/i }); -exports.Digit = chevrotain_1.createToken({ name: "DigitSpecifier", pattern: /digit(s)?/i }); -exports.Character = chevrotain_1.createToken({ name: "CharacterSpecifier", pattern: /character(s)?/i }); -exports.Whitespace = chevrotain_1.createToken({ name: "WhitespaceSpecifier", pattern: /(white space|whitespace)(s)?/i }); -exports.Number = chevrotain_1.createToken({ name: "NumberSpecifier", pattern: /number(s)?/i }); -exports.Multiple = chevrotain_1.createToken({ name: "Multiple", pattern: /multiple/i }); -exports.As = chevrotain_1.createToken({ name: "As", pattern: /as/i }); -exports.If = chevrotain_1.createToken({ name: "If", pattern: /if/i }); -exports.Start = chevrotain_1.createToken({ name: "Start", pattern: /start(s)?/i }); -exports.With = chevrotain_1.createToken({ name: "With", pattern: /with/i }); -exports.Ends = chevrotain_1.createToken({ name: "Ends", pattern: /end(s)?/i }); -exports.Otherwise = chevrotain_1.createToken({ name: "Otherwise", pattern: /(other wise|otherwise)/i }); -exports.Else = chevrotain_1.createToken({ name: "Else", pattern: /else/i }); -exports.Unless = chevrotain_1.createToken({ name: "Unless", pattern: /unless/i }); -exports.While = chevrotain_1.createToken({ name: "While", pattern: /while/i }); -exports.More = chevrotain_1.createToken({ name: "More", pattern: /more/i }); -exports.Using = chevrotain_1.createToken({ name: "Using", pattern: /using/i }); -exports.Global = chevrotain_1.createToken({ name: "Global", pattern: /global/i }); -exports.Multiline = chevrotain_1.createToken({ name: "Multiline", pattern: /(multi line|multiline)/i }); -exports.Exact = chevrotain_1.createToken({ name: "Exact", pattern: /exact/i }); -exports.Matching = chevrotain_1.createToken({ name: "Matching", pattern: /matching/i }); -exports.Nothing = chevrotain_1.createToken({ name: "Nothing", pattern: /nothing/i }); -exports.Not = chevrotain_1.createToken({ name: "Not", pattern: /not/i }); //, longer_alt: Nothing}); -exports.Between = chevrotain_1.createToken({ name: "Between", pattern: /between/i }); -exports.Tab = chevrotain_1.createToken({ name: "Tab", pattern: /tab/i }); -exports.Linefeed = chevrotain_1.createToken({ name: "Linefeed", pattern: /(line feed|linefeed)/i }); -exports.Group = chevrotain_1.createToken({ name: "Group", pattern: /group/i }); -exports.By = chevrotain_1.createToken({ name: "By", pattern: /by/i }); -exports.A = chevrotain_1.createToken({ name: "A", pattern: /a(n)?/i }); //, longer_alt: Anything}); -exports.The = chevrotain_1.createToken({ name: "The", pattern: /the/i }); //, longer_alt: Then}); -exports.Exactly = chevrotain_1.createToken({ name: "Exactly", pattern: /exact(ly)?/i }); -exports.Inclusive = chevrotain_1.createToken({ name: "Inclusive", pattern: /inclusive(ly)?/i }); -exports.exclusive = chevrotain_1.createToken({ name: "Exclusive", pattern: /exclusive(ly)?/i }); -exports.From = chevrotain_1.createToken({ name: "From", pattern: /from/i }); -exports.To = chevrotain_1.createToken({ name: "To", pattern: /(to|\-|\.\.|\.\.\.)/i }); -exports.Create = chevrotain_1.createToken({ name: "Create", pattern: /create(s)?/i }); -exports.Called = chevrotain_1.createToken({ name: "Called", pattern: /called/i }); -exports.Repeat = chevrotain_1.createToken({ name: "Repeat", pattern: /repeat(s|ing)?/i }); -exports.Newline = chevrotain_1.createToken({ name: "Newline", pattern: /(new line|newline)/i }); -exports.None = chevrotain_1.createToken({ name: "None", pattern: /none/i }); -exports.Neither = chevrotain_1.createToken({ name: "Neither", pattern: /neither/i }); -exports.CarriageReturn = chevrotain_1.createToken({ name: "CarriageReturn", pattern: /carriage return/i }); -exports.CaseInsensitive = chevrotain_1.createToken({ name: "CaseInsensitive", pattern: /case insensitive/i }); -exports.CaseSensitive = chevrotain_1.createToken({ name: "CaseSensitive", pattern: /case sensitive/i }); -exports.OrMore = chevrotain_1.createToken({ name: "OrMore", pattern: /\+/ }); -exports.Indent = chevrotain_1.createToken({ name: "Indent", pattern: /(( ){4}\t)/ }); -exports.EndOfLine = chevrotain_1.createToken({ name: "EOL", pattern: /\n/ }); -exports.WhiteSpace = chevrotain_1.createToken({ name: "WhiteSpace", pattern: /\s+/, group: chevrotain_1.Lexer.SKIPPED }); -exports.SingleLineComment = chevrotain_1.createToken({ name: "SingleLineComment", pattern: /(#|\/\/).*/, group: chevrotain_1.Lexer.SKIPPED }); -exports.MultilineComment = chevrotain_1.createToken({ name: "MultiLineComment", pattern: /\/\*(.*)\*\//, line_breaks: true, group: chevrotain_1.Lexer.SKIPPED }); -exports.Identifier = chevrotain_1.createToken({ name: "Identifier", pattern: /[a-z]\w*/i }); -exports.NumberLiteral = chevrotain_1.createToken({ name: "NumberLiteral", pattern: /-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/ }); -exports.StringLiteral = chevrotain_1.createToken({ name: "StringLiteral", pattern: /"(?:[^\\"]|\\(?:[bfnrtv"\\/]|u[0-9a-f]{4}|U[0-9a-f]{8}))*"/i }); -exports.AllTokens = [ - exports.Zero, - exports.One, - exports.Two, - exports.Three, - exports.Four, - exports.Five, - exports.Six, - exports.Seven, - exports.Eight, - exports.Nine, - exports.Ten, - exports.Optional, - exports.Matching, - exports.Match, - exports.Then, - exports.Anything, - exports.Of, - exports.Or, - exports.And, - exports.Word, - exports.Digit, - exports.Character, - exports.Whitespace, - exports.Number, - exports.Multiple, - exports.As, - exports.If, - exports.Start, - exports.With, - exports.Ends, - exports.Otherwise, - exports.Else, - exports.Unless, - exports.While, - exports.More, - exports.Using, - exports.Global, - exports.Multiline, - exports.Exact, - exports.Nothing, - exports.Not, - exports.Between, - exports.Tab, - exports.Linefeed, - exports.Group, - exports.By, - exports.A, - exports.The, - exports.Exactly, - exports.Inclusive, - exports.exclusive, - exports.From, - exports.Create, - exports.Called, - exports.Repeat, - exports.Newline, - exports.None, - exports.Neither, - exports.CarriageReturn, - exports.CaseInsensitive, - exports.CaseSensitive, - exports.OrMore, - exports.To, - exports.Indent, - exports.EndOfLine, - exports.WhiteSpace, - exports.SingleLineComment, - exports.MultilineComment, - exports.Identifier, - exports.NumberLiteral, - exports.StringLiteral, -]; -exports.Human2RegexLexer = new chevrotain_1.Lexer(exports.AllTokens, { ensureOptimizations: true }); - - -/***/ }) -/******/ ]); \ No newline at end of file +!function(t){var e={};function n(r){if(e[r])return e[r].exports;var i=e[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}n.m=t,n.c=e,n.d=function(t,e,r){n.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},n.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},n.t=function(t,e){if(1&e&&(t=n(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var i in t)n.d(r,i,function(e){return t[e]}.bind(null,i));return r},n.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return n.d(e,"a",e),e},n.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},n.p="",n(n.s=3)}([function(t,e,n){"use strict";function r(t){return t&&0===t.length}function i(t){return null==t?[]:Object.keys(t)}function o(t){for(var e=[],n=Object.keys(t),r=0;r=this.input.length)throw Error("Unexpected end of input");this.idx++},t.prototype.loc=function(t){return{begin:t,end:this.idx}};var e,n=/[0-9a-fA-F]/,r=/[0-9]/,i=/[1-9]/;function o(t){return t.charCodeAt(0)}function a(t,e){void 0!==t.length?t.forEach((function(t){e.push(t)})):e.push(t)}function s(t,e){if(!0===t[e])throw"duplicate flag "+e;t[e]=!0}function c(t){if(void 0===t)throw Error("Internal Error - Should never get here!")}var u=[];for(e=o("0");e<=o("9");e++)u.push(e);var p=[o("_")].concat(u);for(e=o("a");e<=o("z");e++)p.push(e);for(e=o("A");e<=o("Z");e++)p.push(e);var l=[o(" "),o("\f"),o("\n"),o("\r"),o("\t"),o("\v"),o("\t"),o(" "),o(" "),o(" "),o(" "),o(" "),o(" "),o(" "),o(" "),o(" "),o(" "),o(" "),o(" "),o(" "),o("\u2028"),o("\u2029"),o(" "),o(" "),o(" "),o("\ufeff")];function h(){}return h.prototype.visitChildren=function(t){for(var e in t){var n=t[e];t.hasOwnProperty(e)&&(void 0!==n.type?this.visit(n):Array.isArray(n)&&n.forEach((function(t){this.visit(t)}),this))}},h.prototype.visit=function(t){switch(t.type){case"Pattern":this.visitPattern(t);break;case"Flags":this.visitFlags(t);break;case"Disjunction":this.visitDisjunction(t);break;case"Alternative":this.visitAlternative(t);break;case"StartAnchor":this.visitStartAnchor(t);break;case"EndAnchor":this.visitEndAnchor(t);break;case"WordBoundary":this.visitWordBoundary(t);break;case"NonWordBoundary":this.visitNonWordBoundary(t);break;case"Lookahead":this.visitLookahead(t);break;case"NegativeLookahead":this.visitNegativeLookahead(t);break;case"Character":this.visitCharacter(t);break;case"Set":this.visitSet(t);break;case"Group":this.visitGroup(t);break;case"GroupBackReference":this.visitGroupBackReference(t);break;case"Quantifier":this.visitQuantifier(t)}this.visitChildren(t)},h.prototype.visitPattern=function(t){},h.prototype.visitFlags=function(t){},h.prototype.visitDisjunction=function(t){},h.prototype.visitAlternative=function(t){},h.prototype.visitStartAnchor=function(t){},h.prototype.visitEndAnchor=function(t){},h.prototype.visitWordBoundary=function(t){},h.prototype.visitNonWordBoundary=function(t){},h.prototype.visitLookahead=function(t){},h.prototype.visitNegativeLookahead=function(t){},h.prototype.visitCharacter=function(t){},h.prototype.visitSet=function(t){},h.prototype.visitGroup=function(t){},h.prototype.visitGroupBackReference=function(t){},h.prototype.visitQuantifier=function(t){},{RegExpParser:t,BaseRegExpVisitor:h,VERSION:"0.5.0"}})?r.apply(e,i):r)||(t.exports=o)},function(t,e,n){"use strict";n.r(e),n.d(e,"VERSION",(function(){return r})),n.d(e,"CstParser",(function(){return rn})),n.d(e,"EmbeddedActionsParser",(function(){return on})),n.d(e,"ParserDefinitionErrorType",(function(){return Qe})),n.d(e,"EMPTY_ALT",(function(){return en})),n.d(e,"Lexer",(function(){return X})),n.d(e,"LexerDefinitionErrorType",(function(){return V})),n.d(e,"createToken",(function(){return Q})),n.d(e,"createTokenInstance",(function(){return tt})),n.d(e,"EOF",(function(){return J})),n.d(e,"tokenLabel",(function(){return q})),n.d(e,"tokenMatcher",(function(){return et})),n.d(e,"tokenName",(function(){return $})),n.d(e,"defaultGrammarResolverErrorProvider",(function(){return St})),n.d(e,"defaultGrammarValidatorErrorProvider",(function(){return Lt})),n.d(e,"defaultParserErrorProvider",(function(){return _t})),n.d(e,"EarlyExitException",(function(){return Oe})),n.d(e,"isRecognitionException",(function(){return fe})),n.d(e,"MismatchedTokenException",(function(){return de})),n.d(e,"NotAllInputParsedException",(function(){return ve})),n.d(e,"NoViableAltException",(function(){return me})),n.d(e,"defaultLexerErrorProvider",(function(){return z})),n.d(e,"Alternation",(function(){return ht})),n.d(e,"Alternative",(function(){return at})),n.d(e,"NonTerminal",(function(){return it})),n.d(e,"Option",(function(){return st})),n.d(e,"Repetition",(function(){return pt})),n.d(e,"RepetitionMandatory",(function(){return ct})),n.d(e,"RepetitionMandatoryWithSeparator",(function(){return ut})),n.d(e,"RepetitionWithSeparator",(function(){return lt})),n.d(e,"Rule",(function(){return ot})),n.d(e,"Terminal",(function(){return ft})),n.d(e,"serializeGrammar",(function(){return dt})),n.d(e,"serializeProduction",(function(){return mt})),n.d(e,"GAstVisitor",(function(){return Tt})),n.d(e,"assignOccurrenceIndices",(function(){return le})),n.d(e,"resolveGrammar",(function(){return ue})),n.d(e,"validateGrammar",(function(){return pe})),n.d(e,"clearCache",(function(){return On})),n.d(e,"createSyntaxDiagramsCode",(function(){return an})),n.d(e,"generateParserFactory",(function(){return mn})),n.d(e,"generateParserModule",(function(){return vn})),n.d(e,"Parser",(function(){return Tn}));var r="7.0.2",i=n(0),o=n(1),a={},s=new o.RegExpParser;function c(t){var e=t.toString();if(a.hasOwnProperty(e))return a[e];var n=s.pattern(e);return a[e]=n,n}var u,p=(u=function(t,e){return(u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)},function(t,e){function n(){this.constructor=t}u(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}),l='Unable to use "first char" lexer optimizations:\n';function h(t,e){void 0===e&&(e=!1);try{var n=c(t);return function t(e,n,r){switch(e.type){case"Disjunction":for(var o=0;o=P)for(var o=e.from>=P?e.from:P,a=e.to,s=w(o),c=w(a),u=s;u<=c;u++)n[u]=u}}}));break;case"Group":t(c.value,n,r);break;default:throw Error("Non Exhaustive Match")}var u=void 0!==c.quantifier&&0===c.quantifier.atLeast;if("Group"===c.type&&!1===m(c)||"Group"!==c.type&&!1===u)break}break;default:throw Error("non exhaustive match!")}return Object(i.U)(n)}(n.value,{},n.flags.ignoreCase)}catch(n){if("Complement Sets are not supported for first char optimization"===n.message)e&&Object(i.d)(l+"\tUnable to optimize: < "+t.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 r="";e&&(r="\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."),Object(i.c)(l+"\n\tFailed parsing: < "+t.toString()+" >\n\tUsing the regexp-to-ast library version: "+o.VERSION+"\n\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues"+r)}}return[]}function f(t,e,n){var r=w(t);e[r]=r,!0===n&&function(t,e){var n=String.fromCharCode(t),r=n.toUpperCase();if(r!==n){var i=w(r.charCodeAt(0));e[i]=i}else{var o=n.toLowerCase();if(o!==n){i=w(o.charCodeAt(0));e[i]=i}}}(t,e)}function d(t,e){return Object(i.q)(t.value,(function(t){if("number"==typeof t)return Object(i.j)(e,t);var n=t;return void 0!==Object(i.q)(e,(function(t){return n.from<=t&&t<=n.to}))}))}function m(t){return!(!t.quantifier||0!==t.quantifier.atLeast)||!!t.value&&(Object(i.y)(t.value)?Object(i.o)(t.value,m):m(t.value))}var v=function(t){function e(e){var n=t.call(this)||this;return n.targetCharCodes=e,n.found=!1,n}return p(e,t),e.prototype.visitChildren=function(e){if(!0!==this.found){switch(e.type){case"Lookahead":return void this.visitLookahead(e);case"NegativeLookahead":return void this.visitNegativeLookahead(e)}t.prototype.visitChildren.call(this,e)}},e.prototype.visitCharacter=function(t){Object(i.j)(this.targetCharCodes,t.value)&&(this.found=!0)},e.prototype.visitSet=function(t){t.complement?void 0===d(t,this.targetCharCodes)&&(this.found=!0):void 0!==d(t,this.targetCharCodes)&&(this.found=!0)},e}(o.BaseRegExpVisitor);function O(t,e){if(e instanceof RegExp){var n=c(e),r=new v(t);return r.visit(n),r.found}return void 0!==Object(i.q)(e,(function(e){return Object(i.j)(t,e.charCodeAt(0))}))}var T=function(){var t=function(e,n){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(e,n)};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),y="PATTERN",E="boolean"==typeof new RegExp("(?:)").sticky;function g(t,e){var n,r=(e=Object(i.k)(e,{useSticky:E,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r","\n"],tracer:function(t,e){return e()}})).tracer;r("initCharCodeToOptimizedIndexMap",(function(){!function(){if(Object(i.A)(M)){M=new Array(65536);for(var t=0;t<65536;t++)M[t]=t>255?255+~~(t/255):t}}()})),r("Reject Lexer.NA",(function(){n=Object(i.P)(t,(function(t){return t[y]===X.NA}))}));var o,a,s,c,u,p,f,d,m,v,T,g=!1;r("Transform Patterns",(function(){g=!1,o=Object(i.I)(n,(function(t){var n=t[y];if(Object(i.D)(n)){var r=n.source;return 1!==r.length||"^"===r||"$"===r||"."===r||n.ignoreCase?2!==r.length||"\\"!==r[0]||Object(i.j)(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],r[1])?e.useSticky?R(n):N(n):r[1]:r}if(Object(i.B)(n))return g=!0,{exec:n};if(Object(i.w)(n,"exec"))return g=!0,n;if("string"==typeof n){if(1===n.length)return n;var o=n.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),a=new RegExp(o);return e.useSticky?R(a):N(a)}throw Error("non exhaustive match")}))})),r("misc mapping",(function(){a=Object(i.I)(n,(function(t){return t.tokenTypeIdx})),s=Object(i.I)(n,(function(t){var e=t.GROUP;if(e!==X.SKIPPED){if(Object(i.E)(e))return e;if(Object(i.F)(e))return!1;throw Error("non exhaustive match")}})),c=Object(i.I)(n,(function(t){var e=t.LONGER_ALT;if(e)return Object(i.x)(n,e)})),u=Object(i.I)(n,(function(t){return t.PUSH_MODE})),p=Object(i.I)(n,(function(t){return Object(i.w)(t,"POP_MODE")}))})),r("Line Terminator Handling",(function(){var t=x(e.lineTerminatorCharacters);f=Object(i.I)(n,(function(t){return!1})),"onlyOffset"!==e.positionTracking&&(f=Object(i.I)(n,(function(e){return Object(i.w)(e,"LINE_BREAKS")?e.LINE_BREAKS:!1===C(e,t)?O(t,e.PATTERN):void 0})))})),r("Misc Mapping #2",(function(){d=Object(i.I)(n,_),m=Object(i.I)(o,S),v=Object(i.O)(n,(function(t,e){var n=e.GROUP;return Object(i.E)(n)&&n!==X.SKIPPED&&(t[n]=[]),t}),{}),T=Object(i.I)(o,(function(t,e){return{pattern:o[e],longerAlt:c[e],canLineTerminator:f[e],isCustom:d[e],short:m[e],group:s[e],push:u[e],pop:p[e],tokenTypeIdx:a[e],tokenType:n[e]}}))}));var I=!0,b=[];return e.safeMode||r("First Char Optimization",(function(){b=Object(i.O)(n,(function(t,n,r){if("string"==typeof n.PATTERN){var o=w(n.PATTERN.charCodeAt(0));j(t,o,T[r])}else if(Object(i.y)(n.START_CHARS_HINT)){var a;Object(i.u)(n.START_CHARS_HINT,(function(e){var n=w("string"==typeof e?e.charCodeAt(0):e);a!==n&&(a=n,j(t,n,T[r]))}))}else if(Object(i.D)(n.PATTERN))if(n.PATTERN.unicode)I=!1,e.ensureOptimizations&&Object(i.c)(l+"\tUnable to analyze < "+n.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 s=h(n.PATTERN,e.ensureOptimizations);Object(i.A)(s)&&(I=!1),Object(i.u)(s,(function(e){j(t,e,T[r])}))}else e.ensureOptimizations&&Object(i.c)(l+"\tTokenType: <"+n.name+"> is using a custom token pattern without providing 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"),I=!1;return t}),[])})),r("ArrayPacking",(function(){b=Object(i.L)(b)})),{emptyGroups:v,patternIdxToConfig:T,charCodeToPatternIdxToConfig:b,hasCustom:g,canBeOptimized:I}}function I(t,e){var n=[],r=function(t){var e=Object(i.p)(t,(function(t){return!Object(i.w)(t,y)})),n=Object(i.I)(e,(function(t){return{message:"Token Type: ->"+t.name+"<- missing static 'PATTERN' property",type:V.MISSING_PATTERN,tokenTypes:[t]}})),r=Object(i.l)(t,e);return{errors:n,valid:r}}(t);n=n.concat(r.errors);var a=function(t){var e=Object(i.p)(t,(function(t){var e=t[y];return!(Object(i.D)(e)||Object(i.B)(e)||Object(i.w)(e,"exec")||Object(i.E)(e))})),n=Object(i.I)(e,(function(t){return{message:"Token Type: ->"+t.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:V.INVALID_PATTERN,tokenTypes:[t]}})),r=Object(i.l)(t,e);return{errors:n,valid:r}}(r.valid),s=a.valid;return n=(n=(n=(n=(n=n.concat(a.errors)).concat(function(t){var e=[],n=Object(i.p)(t,(function(t){return Object(i.D)(t[y])}));return e=(e=(e=(e=(e=e.concat(function(t){var e=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.found=!1,e}return T(e,t),e.prototype.visitEndAnchor=function(t){this.found=!0},e}(o.BaseRegExpVisitor),n=Object(i.p)(t,(function(t){var n=t[y];try{var r=c(n),i=new e;return i.visit(r),i.found}catch(t){return b.test(n.source)}}));return Object(i.I)(n,(function(t){return{message:"Unexpected RegExp Anchor Error:\n\tToken Type: ->"+t.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:V.EOI_ANCHOR_FOUND,tokenTypes:[t]}}))}(n))).concat(function(t){var e=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.found=!1,e}return T(e,t),e.prototype.visitStartAnchor=function(t){this.found=!0},e}(o.BaseRegExpVisitor),n=Object(i.p)(t,(function(t){var n=t[y];try{var r=c(n),i=new e;return i.visit(r),i.found}catch(t){return A.test(n.source)}}));return Object(i.I)(n,(function(t){return{message:"Unexpected RegExp Anchor Error:\n\tToken Type: ->"+t.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:V.SOI_ANCHOR_FOUND,tokenTypes:[t]}}))}(n))).concat(function(t){var e=Object(i.p)(t,(function(t){var e=t[y];return e instanceof RegExp&&(e.multiline||e.global)}));return Object(i.I)(e,(function(t){return{message:"Token Type: ->"+t.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:V.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[t]}}))}(n))).concat(function(t){var e=[],n=Object(i.I)(t,(function(n){return Object(i.O)(t,(function(t,r){return n.PATTERN.source!==r.PATTERN.source||Object(i.j)(e,r)||r.PATTERN===X.NA||(e.push(r),t.push(r)),t}),[])}));n=Object(i.i)(n);var r=Object(i.p)(n,(function(t){return t.length>1}));return Object(i.I)(r,(function(t){var e=Object(i.I)(t,(function(t){return t.name}));return{message:"The same RegExp pattern ->"+Object(i.s)(t).PATTERN+"<-has been used in all of the following Token Types: "+e.join(", ")+" <-",type:V.DUPLICATE_PATTERNS_FOUND,tokenTypes:t}}))}(n))).concat(function(t){var e=Object(i.p)(t,(function(t){return t[y].test("")}));return Object(i.I)(e,(function(t){return{message:"Token Type: ->"+t.name+"<- static 'PATTERN' must not match an empty string",type:V.EMPTY_MATCH_PATTERN,tokenTypes:[t]}}))}(n))}(s))).concat(function(t){var e=Object(i.p)(t,(function(t){if(!Object(i.w)(t,"GROUP"))return!1;var e=t.GROUP;return e!==X.SKIPPED&&e!==X.NA&&!Object(i.E)(e)}));return Object(i.I)(e,(function(t){return{message:"Token Type: ->"+t.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:V.INVALID_GROUP_TYPE_FOUND,tokenTypes:[t]}}))}(s))).concat(function(t,e){var n=Object(i.p)(t,(function(t){return void 0!==t.PUSH_MODE&&!Object(i.j)(e,t.PUSH_MODE)}));return Object(i.I)(n,(function(t){return{message:"Token Type: ->"+t.name+"<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->"+t.PUSH_MODE+"<-which does not exist",type:V.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[t]}}))}(s,e))).concat(function(t){var e=[],n=Object(i.O)(t,(function(t,e,n){var r,o=e.PATTERN;return o===X.NA||(Object(i.E)(o)?t.push({str:o,idx:n,tokenType:e}):Object(i.D)(o)&&(r=o,void 0===Object(i.q)([".","\\","[","]","|","^","$","(",")","?","*","+","{"],(function(t){return-1!==r.source.indexOf(t)})))&&t.push({str:o.source,idx:n,tokenType:e})),t}),[]);return Object(i.u)(t,(function(t,r){Object(i.u)(n,(function(n){var o=n.str,a=n.idx,s=n.tokenType;if(r"+t.name+"<-in the lexer's definition.\nSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#UNREACHABLE";e.push({message:c,type:V.UNREACHABLE_PATTERN,tokenTypes:[t,s]})}}))})),e}(s))}var b=/[^\\][\$]/;var A=/[^\\[][\^]|^\^/;function N(t){var e=t.ignoreCase?"i":"";return new RegExp("^(?:"+t.source+")",e)}function R(t){var e=t.ignoreCase?"iy":"y";return new RegExp(""+t.source,e)}function k(t,e,n){var r=[],o=!1,a=Object(i.i)(Object(i.t)(Object(i.J)(t.modes,(function(t){return t})))),s=Object(i.P)(a,(function(t){return t[y]===X.NA})),c=x(n);return e&&Object(i.u)(s,(function(t){var e=C(t,c);if(!1!==e){var n={message:function(t,e){if(e.issue===V.IDENTIFY_TERMINATOR)return"Warning: unable to identify line terminator usage in pattern.\n\tThe problem is in the <"+t.name+"> Token Type\n\t Root cause: "+e.errMsg+".\n\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR";if(e.issue===V.CUSTOM_LINE_BREAK)return"Warning: A Custom Token Pattern should specify the option.\n\tThe problem is in the <"+t.name+"> Token Type\n\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK";throw Error("non exhaustive match")}(t,e),type:e.issue,tokenType:t};r.push(n)}else Object(i.w)(t,"LINE_BREAKS")?!0===t.LINE_BREAKS&&(o=!0):O(c,t.PATTERN)&&(o=!0)})),e&&!o&&r.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:V.NO_LINE_BREAKS_FLAGS}),r}function _(t){var e=t.PATTERN;if(Object(i.D)(e))return!1;if(Object(i.B)(e))return!0;if(Object(i.w)(e,"exec"))return!0;if(Object(i.E)(e))return!1;throw Error("non exhaustive match")}function S(t){return!(!Object(i.E)(t)||1!==t.length)&&t.charCodeAt(0)}var L={test:function(t){for(var e=t.length,n=this.lastIndex;n0?t.charCodeAt(0):t}))}function j(t,e,n){void 0===t[e]?t[e]=[n]:t[e].push(n)}var P=256;function w(t){return t0}))}function K(t){return Object(i.w)(t,"tokenTypeIdx")}function W(t){return Object(i.w)(t,"CATEGORIES")}function H(t){return Object(i.w)(t,"tokenTypeIdx")}var V,z={buildUnableToPopLexerModeMessage:function(t){return"Unable to pop Lexer Mode after encountering Token ->"+t.image+"<- The Mode Stack is empty"},buildUnexpectedCharactersMessage:function(t,e,n,r,i){return"unexpected character: ->"+t.charAt(e)+"<- at offset: "+e+", skipped "+n+" characters."}};!function(t){t[t.MISSING_PATTERN=0]="MISSING_PATTERN",t[t.INVALID_PATTERN=1]="INVALID_PATTERN",t[t.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",t[t.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",t[t.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",t[t.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",t[t.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",t[t.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",t[t.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",t[t.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",t[t.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",t[t.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",t[t.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",t[t.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",t[t.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",t[t.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",t[t.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK"}(V||(V={}));var Y={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:["\n","\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:z,traceInitPerf:!1,skipValidations:!1};Object.freeze(Y);var X=function(){function t(t,e){var n=this;if(void 0===e&&(e=Y),this.lexerDefinition=t,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.config=void 0,this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},"boolean"==typeof e)throw Error("The second argument to the Lexer constructor is now an ILexerConfig Object.\na boolean 2nd argument is no longer supported");this.config=Object(i.K)(Y,e);var r=this.config.traceInitPerf;!0===r?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):"number"==typeof r&&(this.traceInitMaxIdent=r,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",(function(){var r,o=!0;n.TRACE_INIT("Lexer Config handling",(function(){if(n.config.lineTerminatorsPattern===Y.lineTerminatorsPattern)n.config.lineTerminatorsPattern=L;else if(n.config.lineTerminatorCharacters===Y.lineTerminatorCharacters)throw Error("Error: Missing 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(e.safeMode&&e.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');n.trackStartLines=/full|onlyStart/i.test(n.config.positionTracking),n.trackEndLines=/full/i.test(n.config.positionTracking),Object(i.y)(t)?((r={modes:{}}).modes.defaultMode=Object(i.g)(t),r.defaultMode="defaultMode"):(o=!1,r=Object(i.h)(t))})),!1===n.config.skipValidations&&(n.TRACE_INIT("performRuntimeChecks",(function(){n.lexerDefinitionErrors=n.lexerDefinitionErrors.concat(function(t,e,n){var r=[];return Object(i.w)(t,"defaultMode")||r.push({message:"A MultiMode Lexer cannot be initialized without a property in its definition\n",type:V.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),Object(i.w)(t,"modes")||r.push({message:"A MultiMode Lexer cannot be initialized without a property in its definition\n",type:V.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),Object(i.w)(t,"modes")&&Object(i.w)(t,"defaultMode")&&!Object(i.w)(t.modes,t.defaultMode)&&r.push({message:"A MultiMode Lexer cannot be initialized with a defaultMode: <"+t.defaultMode+">which does not exist\n",type:V.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),Object(i.w)(t,"modes")&&Object(i.u)(t.modes,(function(t,e){Object(i.u)(t,(function(t,n){Object(i.F)(t)&&r.push({message:"A Lexer cannot be initialized using an undefined Token Type. Mode:<"+e+"> at index: <"+n+">\n",type:V.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED})}))})),r}(r,n.trackStartLines,n.config.lineTerminatorCharacters))})),n.TRACE_INIT("performWarningRuntimeChecks",(function(){n.lexerDefinitionWarning=n.lexerDefinitionWarning.concat(k(r,n.trackStartLines,n.config.lineTerminatorCharacters))}))),r.modes=r.modes?r.modes:{},Object(i.u)(r.modes,(function(t,e){r.modes[e]=Object(i.P)(t,(function(t){return Object(i.F)(t)}))}));var s=Object(i.G)(r.modes);if(Object(i.u)(r.modes,(function(t,r){n.TRACE_INIT("Mode: <"+r+"> processing",(function(){var o;(n.modes.push(r),!1===n.config.skipValidations&&n.TRACE_INIT("validatePatterns",(function(){n.lexerDefinitionErrors=n.lexerDefinitionErrors.concat(I(t,s))})),Object(i.A)(n.lexerDefinitionErrors))&&(G(t),n.TRACE_INIT("analyzeTokenTypes",(function(){o=g(t,{lineTerminatorCharacters:n.config.lineTerminatorCharacters,positionTracking:e.positionTracking,ensureOptimizations:e.ensureOptimizations,safeMode:e.safeMode,tracer:n.TRACE_INIT.bind(n)})})),n.patternIdxToConfig[r]=o.patternIdxToConfig,n.charCodeToPatternIdxToConfig[r]=o.charCodeToPatternIdxToConfig,n.emptyGroups=Object(i.K)(n.emptyGroups,o.emptyGroups),n.hasCustom=o.hasCustom||n.hasCustom,n.canModeBeOptimized[r]=o.canBeOptimized)}))})),n.defaultMode=r.defaultMode,!Object(i.A)(n.lexerDefinitionErrors)&&!n.config.deferDefinitionErrorsHandling){var c=Object(i.I)(n.lexerDefinitionErrors,(function(t){return t.message})).join("-----------------------\n");throw new Error("Errors detected in definition of Lexer:\n"+c)}Object(i.u)(n.lexerDefinitionWarning,(function(t){Object(i.d)(t.message)})),n.TRACE_INIT("Choosing sub-methods implementations",(function(){if(E?(n.chopInput=i.a,n.match=n.matchWithTest):(n.updateLastIndex=i.b,n.match=n.matchWithExec),o&&(n.handleModes=i.b),!1===n.trackStartLines&&(n.computeNewColumn=i.a),!1===n.trackEndLines&&(n.updateTokenEndLineColumnLocation=i.b),/full/i.test(n.config.positionTracking))n.createTokenInstance=n.createFullToken;else if(/onlyStart/i.test(n.config.positionTracking))n.createTokenInstance=n.createStartOnlyToken;else{if(!/onlyOffset/i.test(n.config.positionTracking))throw Error('Invalid config option: "'+n.config.positionTracking+'"');n.createTokenInstance=n.createOffsetOnlyToken}n.hasCustom?(n.addToken=n.addTokenUsingPush,n.handlePayload=n.handlePayloadWithCustom):(n.addToken=n.addTokenUsingMemberAccess,n.handlePayload=n.handlePayloadNoCustom)})),n.TRACE_INIT("Failed Optimization Warnings",(function(){var t=Object(i.O)(n.canModeBeOptimized,(function(t,e,n){return!1===e&&t.push(n),t}),[]);if(e.ensureOptimizations&&!Object(i.A)(t))throw Error("Lexer Modes: < "+t.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.')})),n.TRACE_INIT("clearRegExpParserCache",(function(){a={}})),n.TRACE_INIT("toFastProperties",(function(){Object(i.S)(n)}))}))}return t.prototype.tokenize=function(t,e){if(void 0===e&&(e=this.defaultMode),!Object(i.A)(this.lexerDefinitionErrors)){var n=Object(i.I)(this.lexerDefinitionErrors,(function(t){return t.message})).join("-----------------------\n");throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n"+n)}return this.tokenizeInternal(t,e)},t.prototype.tokenizeInternal=function(t,e){var n,r,o,a,s,c,u,p,l,h,f,d,m,v,O,T,y,E=this,g=t,I=g.length,b=0,A=0,N=this.hasCustom?0:Math.floor(t.length/10),R=new Array(N),k=[],_=this.trackStartLines?1:void 0,S=this.trackStartLines?1:void 0,L=(O=this.emptyGroups,T={},y=Object(i.G)(O),Object(i.u)(y,(function(t){var e=O[t];if(!Object(i.y)(e))throw Error("non exhaustive match");T[t]=[]})),T),C=this.trackStartLines,x=this.config.lineTerminatorsPattern,j=0,P=[],M=[],F=[],U=[];Object.freeze(U);var D=void 0;function B(){return P}function G(t){var e=w(t),n=M[e];return void 0===n?U:n}var K,W=function(t){if(1===F.length&&void 0===t.tokenType.PUSH_MODE){var e=E.config.errorMessageProvider.buildUnableToPopLexerModeMessage(t);k.push({offset:t.startOffset,line:void 0!==t.startLine?t.startLine:void 0,column:void 0!==t.startColumn?t.startColumn:void 0,length:t.image.length,message:e})}else{F.pop();var n=Object(i.H)(F);P=E.patternIdxToConfig[n],M=E.charCodeToPatternIdxToConfig[n],j=P.length;var r=E.canModeBeOptimized[n]&&!1===E.config.safeMode;D=M&&r?G:B}};function H(t){F.push(t),M=this.charCodeToPatternIdxToConfig[t],P=this.patternIdxToConfig[t],j=P.length,j=P.length;var e=this.canModeBeOptimized[t]&&!1===this.config.safeMode;D=M&&e?G:B}for(H.call(this,e);bs.length&&(s=o,c=u,K=q)}break}}if(null!==s){if(p=s.length,void 0!==(l=K.group)&&(h=K.tokenTypeIdx,f=this.createTokenInstance(s,b,h,K.tokenType,_,S,p),this.handlePayload(f,c),!1===l?A=this.addToken(R,A,f):L[l].push(f)),t=this.chopInput(t,p),b+=p,S=this.computeNewColumn(S,p),!0===C&&!0===K.canLineTerminator){var Z=0,Q=void 0,J=void 0;x.lastIndex=0;do{!0===(Q=x.test(s))&&(J=x.lastIndex-1,Z++)}while(!0===Q);0!==Z&&(_+=Z,S=p-J,this.updateTokenEndLineColumnLocation(f,l,J,Z,_,S,p))}this.handleModes(K,W,H,f)}else{for(var tt=b,et=_,nt=S,rt=!1;!rt&&b");var r=Object(i.R)(e),o=r.time,a=r.value,s=o>10?console.warn:console.log;return this.traceInitIndent time: "+o+"ms"),this.traceInitIndent--,a}return e()},t.SKIPPED="This marks a skipped Token pattern, this means each token identified by it willbe consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.",t.NA=/NOT_APPLICABLE/,t}();function q(t){return Z(t)?t.LABEL:t.name}function $(t){return t.name}function Z(t){return Object(i.E)(t.LABEL)&&""!==t.LABEL}function Q(t){return function(t){var e=t.pattern,n={};n.name=t.name,Object(i.F)(e)||(n.PATTERN=e);if(Object(i.w)(t,"parent"))throw"The parent property is no longer supported.\nSee: https://github.com/SAP/chevrotain/issues/564#issuecomment-349062346 for details.";Object(i.w)(t,"categories")&&(n.CATEGORIES=t.categories);G([n]),Object(i.w)(t,"label")&&(n.LABEL=t.label);Object(i.w)(t,"group")&&(n.GROUP=t.group);Object(i.w)(t,"pop_mode")&&(n.POP_MODE=t.pop_mode);Object(i.w)(t,"push_mode")&&(n.PUSH_MODE=t.push_mode);Object(i.w)(t,"longer_alt")&&(n.LONGER_ALT=t.longer_alt);Object(i.w)(t,"line_breaks")&&(n.LINE_BREAKS=t.line_breaks);Object(i.w)(t,"start_chars_hint")&&(n.START_CHARS_HINT=t.start_chars_hint);return n}(t)}var J=Q({name:"EOF",pattern:X.NA});function tt(t,e,n,r,i,o,a,s){return{image:e,startOffset:n,endOffset:r,startLine:i,endLine:o,startColumn:a,endColumn:s,tokenTypeIdx:t.tokenTypeIdx,tokenType:t}}function et(t,e){return F(t,e)}G([J]);var nt=function(){var t=function(e,n){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(e,n)};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),rt=function(){function t(t){this.definition=t}return t.prototype.accept=function(t){t.visit(this),Object(i.u)(this.definition,(function(e){e.accept(t)}))},t}(),it=function(t){function e(e){var n=t.call(this,[])||this;return n.idx=1,Object(i.f)(n,Object(i.N)(e,(function(t){return void 0!==t}))),n}return nt(e,t),Object.defineProperty(e.prototype,"definition",{get:function(){return void 0!==this.referencedRule?this.referencedRule.definition:[]},set:function(t){},enumerable:!1,configurable:!0}),e.prototype.accept=function(t){t.visit(this)},e}(rt),ot=function(t){function e(e){var n=t.call(this,e.definition)||this;return n.orgText="",Object(i.f)(n,Object(i.N)(e,(function(t){return void 0!==t}))),n}return nt(e,t),e}(rt),at=function(t){function e(e){var n=t.call(this,e.definition)||this;return n.ignoreAmbiguities=!1,Object(i.f)(n,Object(i.N)(e,(function(t){return void 0!==t}))),n}return nt(e,t),e}(rt),st=function(t){function e(e){var n=t.call(this,e.definition)||this;return n.idx=1,Object(i.f)(n,Object(i.N)(e,(function(t){return void 0!==t}))),n}return nt(e,t),e}(rt),ct=function(t){function e(e){var n=t.call(this,e.definition)||this;return n.idx=1,Object(i.f)(n,Object(i.N)(e,(function(t){return void 0!==t}))),n}return nt(e,t),e}(rt),ut=function(t){function e(e){var n=t.call(this,e.definition)||this;return n.idx=1,Object(i.f)(n,Object(i.N)(e,(function(t){return void 0!==t}))),n}return nt(e,t),e}(rt),pt=function(t){function e(e){var n=t.call(this,e.definition)||this;return n.idx=1,Object(i.f)(n,Object(i.N)(e,(function(t){return void 0!==t}))),n}return nt(e,t),e}(rt),lt=function(t){function e(e){var n=t.call(this,e.definition)||this;return n.idx=1,Object(i.f)(n,Object(i.N)(e,(function(t){return void 0!==t}))),n}return nt(e,t),e}(rt),ht=function(t){function e(e){var n=t.call(this,e.definition)||this;return n.idx=1,n.ignoreAmbiguities=!1,n.hasPredicates=!1,Object(i.f)(n,Object(i.N)(e,(function(t){return void 0!==t}))),n}return nt(e,t),e}(rt),ft=function(){function t(t){this.idx=1,Object(i.f)(this,Object(i.N)(t,(function(t){return void 0!==t})))}return t.prototype.accept=function(t){t.visit(this)},t}();function dt(t){return Object(i.I)(t,mt)}function mt(t){function e(t){return Object(i.I)(t,mt)}if(t instanceof it)return{type:"NonTerminal",name:t.nonTerminalName,idx:t.idx};if(t instanceof at)return{type:"Alternative",definition:e(t.definition)};if(t instanceof st)return{type:"Option",idx:t.idx,definition:e(t.definition)};if(t instanceof ct)return{type:"RepetitionMandatory",idx:t.idx,definition:e(t.definition)};if(t instanceof ut)return{type:"RepetitionMandatoryWithSeparator",idx:t.idx,separator:mt(new ft({terminalType:t.separator})),definition:e(t.definition)};if(t instanceof lt)return{type:"RepetitionWithSeparator",idx:t.idx,separator:mt(new ft({terminalType:t.separator})),definition:e(t.definition)};if(t instanceof pt)return{type:"Repetition",idx:t.idx,definition:e(t.definition)};if(t instanceof ht)return{type:"Alternation",idx:t.idx,definition:e(t.definition)};if(t instanceof ft){var n={type:"Terminal",name:t.terminalType.name,label:q(t.terminalType),idx:t.idx},r=t.terminalType.PATTERN;return t.terminalType.PATTERN&&(n.pattern=Object(i.D)(r)?r.source:r),n}if(t instanceof ot)return{type:"Rule",name:t.name,orgText:t.orgText,definition:e(t.definition)};throw Error("non exhaustive match")}var vt=function(){function t(){}return t.prototype.walk=function(t,e){var n=this;void 0===e&&(e=[]),Object(i.u)(t.definition,(function(r,o){var a=Object(i.m)(t.definition,o+1);if(r instanceof it)n.walkProdRef(r,a,e);else if(r instanceof ft)n.walkTerminal(r,a,e);else if(r instanceof at)n.walkFlat(r,a,e);else if(r instanceof st)n.walkOption(r,a,e);else if(r instanceof ct)n.walkAtLeastOne(r,a,e);else if(r instanceof ut)n.walkAtLeastOneSep(r,a,e);else if(r instanceof lt)n.walkManySep(r,a,e);else if(r instanceof pt)n.walkMany(r,a,e);else{if(!(r instanceof ht))throw Error("non exhaustive match");n.walkOr(r,a,e)}}))},t.prototype.walkTerminal=function(t,e,n){},t.prototype.walkProdRef=function(t,e,n){},t.prototype.walkFlat=function(t,e,n){var r=e.concat(n);this.walk(t,r)},t.prototype.walkOption=function(t,e,n){var r=e.concat(n);this.walk(t,r)},t.prototype.walkAtLeastOne=function(t,e,n){var r=[new st({definition:t.definition})].concat(e,n);this.walk(t,r)},t.prototype.walkAtLeastOneSep=function(t,e,n){var r=Ot(t,e,n);this.walk(t,r)},t.prototype.walkMany=function(t,e,n){var r=[new st({definition:t.definition})].concat(e,n);this.walk(t,r)},t.prototype.walkManySep=function(t,e,n){var r=Ot(t,e,n);this.walk(t,r)},t.prototype.walkOr=function(t,e,n){var r=this,o=e.concat(n);Object(i.u)(t.definition,(function(t){var e=new at({definition:[t]});r.walk(e,o)}))},t}();function Ot(t,e,n){return[new st({definition:[new ft({terminalType:t.separator})].concat(t.definition)})].concat(e,n)}var Tt=function(){function t(){}return t.prototype.visit=function(t){var e=t;switch(e.constructor){case it:return this.visitNonTerminal(e);case at:return this.visitAlternative(e);case st:return this.visitOption(e);case ct:return this.visitRepetitionMandatory(e);case ut:return this.visitRepetitionMandatoryWithSeparator(e);case lt:return this.visitRepetitionWithSeparator(e);case pt:return this.visitRepetition(e);case ht:return this.visitAlternation(e);case ft:return this.visitTerminal(e);case ot:return this.visitRule(e);default:throw Error("non exhaustive match")}},t.prototype.visitNonTerminal=function(t){},t.prototype.visitAlternative=function(t){},t.prototype.visitOption=function(t){},t.prototype.visitRepetition=function(t){},t.prototype.visitRepetitionMandatory=function(t){},t.prototype.visitRepetitionMandatoryWithSeparator=function(t){},t.prototype.visitRepetitionWithSeparator=function(t){},t.prototype.visitAlternation=function(t){},t.prototype.visitTerminal=function(t){},t.prototype.visitRule=function(t){},t}(),yt=function(){var t=function(e,n){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(e,n)};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();function Et(t,e){return void 0===e&&(e=[]),!!(t instanceof st||t instanceof pt||t instanceof lt)||(t instanceof ht?Object(i.Q)(t.definition,(function(t){return Et(t,e)})):!(t instanceof it&&Object(i.j)(e,t))&&(t instanceof rt&&(t instanceof it&&e.push(t),Object(i.o)(t.definition,(function(t){return Et(t,e)})))))}function gt(t){if(t instanceof it)return"SUBRULE";if(t instanceof st)return"OPTION";if(t instanceof ht)return"OR";if(t instanceof ct)return"AT_LEAST_ONE";if(t instanceof ut)return"AT_LEAST_ONE_SEP";if(t instanceof lt)return"MANY_SEP";if(t instanceof pt)return"MANY";if(t instanceof ft)return"CONSUME";throw Error("non exhaustive match")}var It=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.separator="-",e.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]},e}return yt(e,t),e.prototype.reset=function(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}},e.prototype.visitTerminal=function(t){var e=t.terminalType.name+this.separator+"Terminal";Object(i.w)(this.dslMethods,e)||(this.dslMethods[e]=[]),this.dslMethods[e].push(t)},e.prototype.visitNonTerminal=function(t){var e=t.nonTerminalName+this.separator+"Terminal";Object(i.w)(this.dslMethods,e)||(this.dslMethods[e]=[]),this.dslMethods[e].push(t)},e.prototype.visitOption=function(t){this.dslMethods.option.push(t)},e.prototype.visitRepetitionWithSeparator=function(t){this.dslMethods.repetitionWithSeparator.push(t)},e.prototype.visitRepetitionMandatory=function(t){this.dslMethods.repetitionMandatory.push(t)},e.prototype.visitRepetitionMandatoryWithSeparator=function(t){this.dslMethods.repetitionMandatoryWithSeparator.push(t)},e.prototype.visitRepetition=function(t){this.dslMethods.repetition.push(t)},e.prototype.visitAlternation=function(t){this.dslMethods.alternation.push(t)},e}(Tt),bt=new It;function At(t){if(t instanceof it)return At(t.referencedRule);if(t instanceof ft)return[t.terminalType];if(function(t){return t instanceof at||t instanceof st||t instanceof pt||t instanceof ct||t instanceof ut||t instanceof lt||t instanceof ft||t instanceof ot}(t))return function(t){var e,n=[],r=t.definition,o=0,a=r.length>o,s=!0;for(;a&&s;)e=r[o],s=Et(e),n=n.concat(At(e)),o+=1,a=r.length>o;return Object(i.T)(n)}(t);if(function(t){return t instanceof ht}(t))return function(t){var e=Object(i.I)(t.definition,(function(t){return At(t)}));return Object(i.T)(Object(i.t)(e))}(t);throw Error("non exhaustive match")}var Nt="_~IN~_",Rt=function(){var t=function(e,n){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(e,n)};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),kt=function(t){function e(e){var n=t.call(this)||this;return n.topProd=e,n.follows={},n}return Rt(e,t),e.prototype.startWalking=function(){return this.walk(this.topProd),this.follows},e.prototype.walkTerminal=function(t,e,n){},e.prototype.walkProdRef=function(t,e,n){var r,i,o=(r=t.referencedRule,i=t.idx,r.name+i+Nt+this.topProd.name),a=e.concat(n),s=At(new at({definition:a}));this.follows[o]=s},e}(vt);var _t={buildMismatchTokenMessage:function(t){var e=t.expected,n=t.actual;t.previous,t.ruleName;return"Expecting "+(Z(e)?"--\x3e "+q(e)+" <--":"token of type --\x3e "+e.name+" <--")+" but found --\x3e '"+n.image+"' <--"},buildNotAllInputParsedMessage:function(t){var e=t.firstRedundant;t.ruleName;return"Redundant input, expecting EOF but found: "+e.image},buildNoViableAltMessage:function(t){var e=t.expectedPathsPerAlt,n=t.actual,r=(t.previous,t.customUserDescription),o=(t.ruleName,"\nbut found: '"+Object(i.s)(n).image+"'");if(r)return"Expecting: "+r+o;var a=Object(i.O)(e,(function(t,e){return t.concat(e)}),[]),s=Object(i.I)(a,(function(t){return"["+Object(i.I)(t,(function(t){return q(t)})).join(", ")+"]"}));return"Expecting: "+("one of these possible Token sequences:\n"+Object(i.I)(s,(function(t,e){return" "+(e+1)+". "+t})).join("\n"))+o},buildEarlyExitMessage:function(t){var e=t.expectedIterationPaths,n=t.actual,r=t.customUserDescription,o=(t.ruleName,"\nbut found: '"+Object(i.s)(n).image+"'");return r?"Expecting: "+r+o:"Expecting: "+("expecting at least one iteration which starts with one of these possible Token sequences::\n <"+Object(i.I)(e,(function(t){return"["+Object(i.I)(t,(function(t){return q(t)})).join(",")+"]"})).join(" ,")+">")+o}};Object.freeze(_t);var St={buildRuleNotFoundError:function(t,e){return"Invalid grammar, reference to a rule which is not defined: ->"+e.nonTerminalName+"<-\ninside top level rule: ->"+t.name+"<-"}},Lt={buildDuplicateFoundError:function(t,e){var n,r=t.name,o=Object(i.s)(e),a=o.idx,s=gt(o),c=(n=o)instanceof ft?n.terminalType.name:n instanceof it?n.nonTerminalName:"",u="->"+s+(a>0?a:"")+"<- "+(c?"with argument: ->"+c+"<-":"")+"\n appears more than once ("+e.length+" times) in the top level rule: ->"+r+"<-. \n For further details see: https://sap.github.io/chevrotain/docs/FAQ.html#NUMERICAL_SUFFIXES \n ";return u=(u=u.replace(/[ \t]+/g," ")).replace(/\s\s+/g,"\n")},buildNamespaceConflictError:function(t){return"Namespace conflict found in grammar.\nThe grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <"+t.name+">.\nTo resolve this make sure each Terminal and Non-Terminal names are unique\nThis is easy to accomplish by using the convention that Terminal names start with an uppercase letter\nand Non-Terminal names start with a lower case letter."},buildAlternationPrefixAmbiguityError:function(t){var e=Object(i.I)(t.prefixPath,(function(t){return q(t)})).join(", "),n=0===t.alternation.idx?"":t.alternation.idx;return"Ambiguous alternatives: <"+t.ambiguityIndices.join(" ,")+"> due to common lookahead prefix\nin inside <"+t.topLevelRule.name+"> Rule,\n<"+e+"> may appears as a prefix path in all these alternatives.\nSee: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX\nFor Further details."},buildAlternationAmbiguityError:function(t){var e=Object(i.I)(t.prefixPath,(function(t){return q(t)})).join(", "),n=0===t.alternation.idx?"":t.alternation.idx,r="Ambiguous Alternatives Detected: <"+t.ambiguityIndices.join(" ,")+"> in inside <"+t.topLevelRule.name+"> Rule,\n<"+e+"> may appears as a prefix path in all these alternatives.\n";return r+="See: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\nFor Further details."},buildEmptyRepetitionError:function(t){var e=gt(t.repetition);return 0!==t.repetition.idx&&(e+=t.repetition.idx),"The repetition <"+e+"> within Rule <"+t.topLevelRule.name+"> can never consume any tokens.\nThis could lead to an infinite loop."},buildTokenNameError:function(t){return"Invalid Grammar Token name: ->"+t.tokenType.name+"<- it must match the pattern: ->"+t.expectedPattern.toString()+"<-"},buildEmptyAlternationError:function(t){return"Ambiguous empty alternative: <"+(t.emptyChoiceIdx+1)+"> in inside <"+t.topLevelRule.name+"> Rule.\nOnly the last alternative may be an empty alternative."},buildTooManyAlternativesError:function(t){return"An Alternation cannot have more than 256 alternatives:\n inside <"+t.topLevelRule.name+"> Rule.\n has "+(t.alternation.definition.length+1)+" alternatives."},buildLeftRecursionError:function(t){var e=t.topLevelRule.name;return"Left Recursion found in grammar.\nrule: <"+e+"> can be invoked from itself (directly or indirectly)\nwithout consuming any Tokens. The grammar path that causes this is: \n "+(e+" --\x3e "+i.I(t.leftRecursionPath,(function(t){return t.name})).concat([e]).join(" --\x3e "))+"\n To fix this refactor your grammar to remove the left recursion.\nsee: https://en.wikipedia.org/wiki/LL_parser#Left_Factoring."},buildInvalidRuleNameError:function(t){return"Invalid grammar rule name: ->"+t.topLevelRule.name+"<- it must match the pattern: ->"+t.expectedPattern.toString()+"<-"},buildDuplicateRuleNameError:function(t){return"Duplicate definition, rule: ->"+(t.topLevelRule instanceof ot?t.topLevelRule.name:t.topLevelRule)+"<- is already defined in the grammar: ->"+t.grammarName+"<-"}},Ct=function(){var t=function(e,n){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(e,n)};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();var xt=function(t){function e(e,n){var r=t.call(this)||this;return r.nameToTopRule=e,r.errMsgProvider=n,r.errors=[],r}return Ct(e,t),e.prototype.resolveRefs=function(){var t=this;Object(i.u)(Object(i.U)(this.nameToTopRule),(function(e){t.currTopLevel=e,e.accept(t)}))},e.prototype.visitNonTerminal=function(t){var e=this.nameToTopRule[t.nonTerminalName];if(e)t.referencedRule=e;else{var n=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,t);this.errors.push({message:n,type:Qe.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:t.nonTerminalName})}},e}(Tt),jt=function(){var t=function(e,n){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(e,n)};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Pt=function(t){function e(e,n){var r=t.call(this,e,n)||this;return r.path=n,r.nextTerminalName="",r.nextTerminalOccurrence=0,r.nextTerminalName=r.path.lastTok.name,r.nextTerminalOccurrence=r.path.lastTokOccurrence,r}return jt(e,t),e.prototype.walkTerminal=function(t,e,n){if(this.isAtEndOfPath&&t.terminalType.name===this.nextTerminalName&&t.idx===this.nextTerminalOccurrence&&!this.found){var r=e.concat(n),i=new at({definition:r});this.possibleTokTypes=At(i),this.found=!0}},e}(function(t){function e(e,n){var r=t.call(this)||this;return r.topProd=e,r.path=n,r.possibleTokTypes=[],r.nextProductionName="",r.nextProductionOccurrence=0,r.found=!1,r.isAtEndOfPath=!1,r}return jt(e,t),e.prototype.startWalking=function(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=Object(i.g)(this.path.ruleStack).reverse(),this.occurrenceStack=Object(i.g)(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes},e.prototype.walk=function(e,n){void 0===n&&(n=[]),this.found||t.prototype.walk.call(this,e,n)},e.prototype.walkProdRef=function(t,e,n){if(t.referencedRule.name===this.nextProductionName&&t.idx===this.nextProductionOccurrence){var r=e.concat(n);this.updateExpectedNext(),this.walk(t.referencedRule,r)}},e.prototype.updateExpectedNext=function(){Object(i.A)(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())},e}(vt)),wt=function(t){function e(e,n){var r=t.call(this)||this;return r.topRule=e,r.occurrence=n,r.result={token:void 0,occurrence:void 0,isEndOfRule:void 0},r}return jt(e,t),e.prototype.startWalking=function(){return this.walk(this.topRule),this.result},e}(vt),Mt=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return jt(e,t),e.prototype.walkMany=function(e,n,r){if(e.idx===this.occurrence){var o=Object(i.s)(n.concat(r));this.result.isEndOfRule=void 0===o,o instanceof ft&&(this.result.token=o.terminalType,this.result.occurrence=o.idx)}else t.prototype.walkMany.call(this,e,n,r)},e}(wt),Ft=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return jt(e,t),e.prototype.walkManySep=function(e,n,r){if(e.idx===this.occurrence){var o=Object(i.s)(n.concat(r));this.result.isEndOfRule=void 0===o,o instanceof ft&&(this.result.token=o.terminalType,this.result.occurrence=o.idx)}else t.prototype.walkManySep.call(this,e,n,r)},e}(wt),Ut=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return jt(e,t),e.prototype.walkAtLeastOne=function(e,n,r){if(e.idx===this.occurrence){var o=Object(i.s)(n.concat(r));this.result.isEndOfRule=void 0===o,o instanceof ft&&(this.result.token=o.terminalType,this.result.occurrence=o.idx)}else t.prototype.walkAtLeastOne.call(this,e,n,r)},e}(wt),Dt=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return jt(e,t),e.prototype.walkAtLeastOneSep=function(e,n,r){if(e.idx===this.occurrence){var o=Object(i.s)(n.concat(r));this.result.isEndOfRule=void 0===o,o instanceof ft&&(this.result.token=o.terminalType,this.result.occurrence=o.idx)}else t.prototype.walkAtLeastOneSep.call(this,e,n,r)},e}(wt);function Bt(t,e,n){void 0===n&&(n=[]),n=Object(i.g)(n);var r=[],o=0;function a(a){var s=Bt(a.concat(Object(i.m)(t,o+1)),e,n);return r.concat(s)}for(;n.length=0;R--){var k={idx:f,def:v.definition[R].definition.concat(Object(i.m)(h)),ruleStack:d,occurrenceStack:m};p.push(k),p.push("EXIT_ALTERNATIVE")}else if(v instanceof at)p.push({idx:f,def:v.definition.concat(Object(i.m)(h)),ruleStack:d,occurrenceStack:m});else{if(!(v instanceof ot))throw Error("non exhaustive match");p.push(Kt(v,f,d,m))}}}else a&&Object(i.H)(p).idx<=c&&p.pop()}return u}function Kt(t,e,n,r){var o=Object(i.g)(n);o.push(t.name);var a=Object(i.g)(r);return a.push(1),{idx:e,def:t.definition,ruleStack:o,occurrenceStack:a}}var Wt,Ht=function(){var t=function(e,n){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(e,n)};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();!function(t){t[t.OPTION=0]="OPTION",t[t.REPETITION=1]="REPETITION",t[t.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",t[t.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",t[t.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",t[t.ALTERNATION=5]="ALTERNATION"}(Wt||(Wt={}));var Vt=function(t){function e(e,n,r){var i=t.call(this)||this;return i.topProd=e,i.targetOccurrence=n,i.targetProdType=r,i}return Ht(e,t),e.prototype.startWalking=function(){return this.walk(this.topProd),this.restDef},e.prototype.checkIsTarget=function(t,e,n,r){return t.idx===this.targetOccurrence&&this.targetProdType===e&&(this.restDef=n.concat(r),!0)},e.prototype.walkOption=function(e,n,r){this.checkIsTarget(e,Wt.OPTION,n,r)||t.prototype.walkOption.call(this,e,n,r)},e.prototype.walkAtLeastOne=function(e,n,r){this.checkIsTarget(e,Wt.REPETITION_MANDATORY,n,r)||t.prototype.walkOption.call(this,e,n,r)},e.prototype.walkAtLeastOneSep=function(e,n,r){this.checkIsTarget(e,Wt.REPETITION_MANDATORY_WITH_SEPARATOR,n,r)||t.prototype.walkOption.call(this,e,n,r)},e.prototype.walkMany=function(e,n,r){this.checkIsTarget(e,Wt.REPETITION,n,r)||t.prototype.walkOption.call(this,e,n,r)},e.prototype.walkManySep=function(e,n,r){this.checkIsTarget(e,Wt.REPETITION_WITH_SEPARATOR,n,r)||t.prototype.walkOption.call(this,e,n,r)},e}(vt),zt=function(t){function e(e,n,r){var i=t.call(this)||this;return i.targetOccurrence=e,i.targetProdType=n,i.targetRef=r,i.result=[],i}return Ht(e,t),e.prototype.checkIsTarget=function(t,e){t.idx!==this.targetOccurrence||this.targetProdType!==e||void 0!==this.targetRef&&t!==this.targetRef||(this.result=t.definition)},e.prototype.visitOption=function(t){this.checkIsTarget(t,Wt.OPTION)},e.prototype.visitRepetition=function(t){this.checkIsTarget(t,Wt.REPETITION)},e.prototype.visitRepetitionMandatory=function(t){this.checkIsTarget(t,Wt.REPETITION_MANDATORY)},e.prototype.visitRepetitionMandatoryWithSeparator=function(t){this.checkIsTarget(t,Wt.REPETITION_MANDATORY_WITH_SEPARATOR)},e.prototype.visitRepetitionWithSeparator=function(t){this.checkIsTarget(t,Wt.REPETITION_WITH_SEPARATOR)},e.prototype.visitAlternation=function(t){this.checkIsTarget(t,Wt.ALTERNATION)},e}(Tt);function Yt(t){for(var e=new Array(t),n=0;n1}));return i.I(i.U(a),(function(n){var r=i.s(n),o=e.buildDuplicateFoundError(t,n),a=gt(r),s={message:o,type:Qe.DUPLICATE_PRODUCTIONS,ruleName:t.name,dslName:a,occurrence:r.idx},c=ie(r);return c&&(s.parameter=c),s}))}(t,r)})),s=i.I(t,(function(t){return function t(e,n,r,o){void 0===o&&(o=[]);var a=[],s=function t(e){var n=[];if(i.A(e))return n;var r=i.s(e);if(r instanceof it)n.push(r.referencedRule);else if(r instanceof at||r instanceof st||r instanceof ct||r instanceof ut||r instanceof lt||r instanceof pt)n=n.concat(t(r.definition));else if(r instanceof ht)n=i.t(i.I(r.definition,(function(e){return t(e.definition)})));else if(!(r instanceof ft))throw Error("non exhaustive match");var o=Et(r),a=e.length>1;if(o&&a){var s=i.m(e);return n.concat(t(s))}return n}(n.definition);if(i.A(s))return[];var c=e.name;i.j(s,e)&&a.push({message:r.buildLeftRecursionError({topLevelRule:e,leftRecursionPath:o}),type:Qe.LEFT_RECURSION,ruleName:c});var u=i.l(s,o.concat([e])),p=i.I(u,(function(n){var a=i.g(o);return a.push(n),t(e,n,r,a)}));return a.concat(i.t(p))}(t,t,r)})),c=[],u=[],p=[];Object(i.o)(s,i.A)&&(c=Object(i.I)(t,(function(t){return function(t,e){var n=new se;t.accept(n);var r=n.alternations;return i.O(r,(function(n,r){var o=i.n(r.definition),a=i.I(o,(function(n,o){var a=Gt([n],[],null,1);return i.A(a)?{message:e.buildEmptyAlternationError({topLevelRule:t,alternation:r,emptyChoiceIdx:o}),type:Qe.NONE_LAST_EMPTY_ALT,ruleName:t.name,occurrence:r.idx,alternative:o+1}:null}));return n.concat(i.i(a))}),[])}(t,r)})),u=Object(i.I)(t,(function(t){return function(t,e,n){var r=new se;t.accept(r);var o=r.alternations;return o=Object(i.P)(o,(function(t){return!0===t.ignoreAmbiguities})),i.O(o,(function(r,o){var a=o.idx,s=o.maxLookahead||e,c=Zt(a,t,s,o),u=function(t,e,n,r){var o=[],a=Object(i.O)(t,(function(n,r,a){return!0===e.definition[a].ignoreAmbiguities||Object(i.u)(r,(function(r){var s=[a];Object(i.u)(t,(function(t,n){a!==n&&Jt(t,r)&&!0!==e.definition[n].ignoreAmbiguities&&s.push(n)})),s.length>1&&!Jt(o,r)&&(o.push(r),n.push({alts:s,path:r}))})),n}),[]);return i.I(a,(function(t){var o=Object(i.I)(t.alts,(function(t){return t+1}));return{message:r.buildAlternationAmbiguityError({topLevelRule:n,alternation:e,ambiguityIndices:o,prefixPath:t.path}),type:Qe.AMBIGUOUS_ALTS,ruleName:n.name,occurrence:e.idx,alternatives:[t.alts]}}))}(c,o,t,n),p=function(t,e,n,r){var o=[],a=Object(i.O)(t,(function(t,e,n){var r=Object(i.I)(e,(function(t){return{idx:n,path:t}}));return t.concat(r)}),[]);return Object(i.u)(a,(function(t){if(!0!==e.definition[t.idx].ignoreAmbiguities){var s=t.idx,c=t.path,u=Object(i.r)(a,(function(t){return!0!==e.definition[t.idx].ignoreAmbiguities&&t.idx255&&n.push({message:e.buildTooManyAlternativesError({topLevelRule:t,alternation:r}),type:Qe.TOO_MANY_ALTS,ruleName:t.name,occurrence:r.idx}),n}),[])}(t,r)})),d=Object(i.I)(t,(function(t){return function(t,e){var n=[],r=t.name;r.match(ae)||n.push({message:e.buildInvalidRuleNameError({topLevelRule:t,expectedPattern:ae}),type:Qe.INVALID_RULE_NAME,ruleName:r});return n}(t,r)})),m=Object(i.I)(t,(function(e){return function(t,e,n,r){var o=[];if(Object(i.O)(e,(function(e,n){return n.name===t.name?e+1:e}),0)>1){var a=r.buildDuplicateRuleNameError({topLevelRule:t,grammarName:n});o.push({message:a,type:Qe.DUPLICATE_RULE_NAME,ruleName:t.name})}return o}(e,t,o,r)}));return i.t(a.concat(h,p,s,c,u,l,f,d,m))}function re(t){return gt(t)+"_#_"+t.idx+"_#_"+ie(t)}function ie(t){return t instanceof ft?t.terminalType.name:t instanceof it?t.nonTerminalName:""}var oe=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.allProductions=[],e}return ee(e,t),e.prototype.visitNonTerminal=function(t){this.allProductions.push(t)},e.prototype.visitOption=function(t){this.allProductions.push(t)},e.prototype.visitRepetitionWithSeparator=function(t){this.allProductions.push(t)},e.prototype.visitRepetitionMandatory=function(t){this.allProductions.push(t)},e.prototype.visitRepetitionMandatoryWithSeparator=function(t){this.allProductions.push(t)},e.prototype.visitRepetition=function(t){this.allProductions.push(t)},e.prototype.visitAlternation=function(t){this.allProductions.push(t)},e.prototype.visitTerminal=function(t){this.allProductions.push(t)},e}(Tt),ae=/^[a-zA-Z_]\w*$/;var se=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.alternations=[],e}return ee(e,t),e.prototype.visitAlternation=function(t){this.alternations.push(t)},e}(Tt);var ce=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.allProductions=[],e}return ee(e,t),e.prototype.visitRepetitionWithSeparator=function(t){this.allProductions.push(t)},e.prototype.visitRepetitionMandatory=function(t){this.allProductions.push(t)},e.prototype.visitRepetitionMandatoryWithSeparator=function(t){this.allProductions.push(t)},e.prototype.visitRepetition=function(t){this.allProductions.push(t)},e}(Tt);function ue(t){t=Object(i.k)(t,{errMsgProvider:St});var e,n,r,o={};return Object(i.u)(t.rules,(function(t){o[t.name]=t})),e=o,n=t.errMsgProvider,(r=new xt(e,n)).resolveRefs(),r.errors}function pe(t){return ne((t=Object(i.k)(t,{errMsgProvider:Lt})).rules,t.maxLookahead,t.tokenTypes,t.errMsgProvider,t.grammarName)}function le(t){Object(i.u)(t.rules,(function(t){var e=new It;t.accept(e),Object(i.u)(e.dslMethods,(function(t){Object(i.u)(t,(function(t,e){t.idx=e+1}))}))}))}var he=["MismatchedTokenException","NoViableAltException","EarlyExitException","NotAllInputParsedException"];function fe(t){return Object(i.j)(he,t.name)}function de(t,e,n){this.name="MismatchedTokenException",this.message=t,this.token=e,this.previousToken=n,this.resyncedTokens=[]}function me(t,e,n){this.name="NoViableAltException",this.message=t,this.token=e,this.previousToken=n,this.resyncedTokens=[]}function ve(t,e){this.name="NotAllInputParsedException",this.message=t,this.token=e,this.resyncedTokens=[]}function Oe(t,e,n){this.name="EarlyExitException",this.message=t,this.token=e,this.previousToken=n,this.resyncedTokens=[]}Object.freeze(he),de.prototype=Error.prototype,me.prototype=Error.prototype,ve.prototype=Error.prototype,Oe.prototype=Error.prototype;var Te={};function ye(t){this.name="InRuleRecoveryException",this.message=t}ye.prototype=Error.prototype;var Ee=function(){function t(){}return t.prototype.initRecoverable=function(t){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=Object(i.w)(t,"recoveryEnabled")?t.recoveryEnabled:Je.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=ge)},t.prototype.getTokenToInsert=function(t){var e=tt(t,"",NaN,NaN,NaN,NaN,NaN,NaN);return e.isInsertedInRecovery=!0,e},t.prototype.canTokenTypeBeInsertedInRecovery=function(t){return!0},t.prototype.tryInRepetitionRecovery=function(t,e,n,r){for(var o=this,a=this.findReSyncTokenType(),s=this.exportLexerState(),c=[],u=!1,p=this.LA(1),l=this.LA(1),h=function(){var t=o.LA(0),e=new de(o.errorMessageProvider.buildMismatchTokenMessage({expected:r,actual:p,previous:t,ruleName:o.getCurrRuleFullName()}),p,o.LA(0));e.resyncedTokens=Object(i.n)(c),o.SAVE_ERROR(e)};!u;){if(this.tokenMatcher(l,r))return void h();if(n.call(this))return h(),void t.apply(this,e);this.tokenMatcher(l,a)?u=!0:(l=this.SKIP_TOKEN(),this.addToResyncTokens(l,c))}this.importLexerState(s)},t.prototype.shouldInRepetitionRecoveryBeTried=function(t,e,n){return!1!==n&&(void 0!==t&&void 0!==e&&(!this.tokenMatcher(this.LA(1),t)&&(!this.isBackTracking()&&!this.canPerformInRuleRecovery(t,this.getFollowsForInRuleRecovery(t,e)))))},t.prototype.getFollowsForInRuleRecovery=function(t,e){var n=this.getCurrentGrammarPath(t,e);return this.getNextPossibleTokenTypes(n)},t.prototype.tryInRuleRecovery=function(t,e){if(this.canRecoverWithSingleTokenInsertion(t,e))return this.getTokenToInsert(t);if(this.canRecoverWithSingleTokenDeletion(t)){var n=this.SKIP_TOKEN();return this.consumeToken(),n}throw new ye("sad sad panda")},t.prototype.canPerformInRuleRecovery=function(t,e){return this.canRecoverWithSingleTokenInsertion(t,e)||this.canRecoverWithSingleTokenDeletion(t)},t.prototype.canRecoverWithSingleTokenInsertion=function(t,e){var n=this;if(!this.canTokenTypeBeInsertedInRecovery(t))return!1;if(Object(i.A)(e))return!1;var r=this.LA(1);return void 0!==Object(i.q)(e,(function(t){return n.tokenMatcher(r,t)}))},t.prototype.canRecoverWithSingleTokenDeletion=function(t){return this.tokenMatcher(this.LA(2),t)},t.prototype.isInCurrentRuleReSyncSet=function(t){var e=this.getCurrFollowKey(),n=this.getFollowSetFromFollowKey(e);return Object(i.j)(n,t)},t.prototype.findReSyncTokenType=function(){for(var t=this.flattenFollowSet(),e=this.LA(1),n=2;;){var r=e.tokenType;if(Object(i.j)(t,r))return r;e=this.LA(n),n++}},t.prototype.getCurrFollowKey=function(){if(1===this.RULE_STACK.length)return Te;var t=this.getLastExplicitRuleShortName(),e=this.getLastExplicitRuleOccurrenceIndex(),n=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(t),idxInCallingRule:e,inRule:this.shortRuleNameToFullName(n)}},t.prototype.buildFullFollowKeyStack=function(){var t=this,e=this.RULE_STACK,n=this.RULE_OCCURRENCE_STACK;return Object(i.I)(e,(function(r,i){return 0===i?Te:{ruleName:t.shortRuleNameToFullName(r),idxInCallingRule:n[i],inRule:t.shortRuleNameToFullName(e[i-1])}}))},t.prototype.flattenFollowSet=function(){var t=this,e=Object(i.I)(this.buildFullFollowKeyStack(),(function(e){return t.getFollowSetFromFollowKey(e)}));return Object(i.t)(e)},t.prototype.getFollowSetFromFollowKey=function(t){if(t===Te)return[J];var e=t.ruleName+t.idxInCallingRule+Nt+t.inRule;return this.resyncFollows[e]},t.prototype.addToResyncTokens=function(t,e){return this.tokenMatcher(t,J)||e.push(t),e},t.prototype.reSyncTo=function(t){for(var e=[],n=this.LA(1);!1===this.tokenMatcher(n,t);)n=this.SKIP_TOKEN(),this.addToResyncTokens(n,e);return Object(i.n)(e)},t.prototype.attemptInRepetitionRecovery=function(t,e,n,r,i,o,a){},t.prototype.getCurrentGrammarPath=function(t,e){return{ruleStack:this.getHumanReadableRuleStack(),occurrenceStack:Object(i.g)(this.RULE_OCCURRENCE_STACK),lastTok:t,lastTokOccurrence:e}},t.prototype.getHumanReadableRuleStack=function(){var t=this;return Object(i.I)(this.RULE_STACK,(function(e){return t.shortRuleNameToFullName(e)}))},t}();function ge(t,e,n,r,i,o,a){var s=this.getKeyForAutomaticLookahead(r,i),c=this.firstAfterRepMap[s];if(void 0===c){var u=this.getCurrRuleFullName();c=new o(this.getGAstProductions()[u],i).startWalking(),this.firstAfterRepMap[s]=c}var p=c.token,l=c.occurrence,h=c.isEndOfRule;1===this.RULE_STACK.length&&h&&void 0===p&&(p=J,l=1),this.shouldInRepetitionRecoveryBeTried(p,l,a)&&this.tryInRepetitionRecovery(t,e,n,p)}function Ie(t,e,n){return n|e|t}var be=function(){function t(){}return t.prototype.initLooksAhead=function(t){this.dynamicTokensEnabled=Object(i.w)(t,"dynamicTokensEnabled")?t.dynamicTokensEnabled:Je.dynamicTokensEnabled,this.maxLookahead=Object(i.w)(t,"maxLookahead")?t.maxLookahead:Je.maxLookahead,this.lookAheadFuncsCache=Object(i.z)()?new Map:[],Object(i.z)()?(this.getLaFuncFromCache=this.getLaFuncFromMap,this.setLaFuncCache=this.setLaFuncCacheUsingMap):(this.getLaFuncFromCache=this.getLaFuncFromObj,this.setLaFuncCache=this.setLaFuncUsingObj)},t.prototype.preComputeLookaheadFunctions=function(t){var e=this;Object(i.u)(t,(function(t){e.TRACE_INIT(t.name+" Rule Lookahead",(function(){var n=function(t){bt.reset(),t.accept(bt);var e=bt.dslMethods;return bt.reset(),e}(t),r=n.alternation,o=n.repetition,a=n.option,s=n.repetitionMandatory,c=n.repetitionMandatoryWithSeparator,u=n.repetitionWithSeparator;Object(i.u)(r,(function(n){var r=0===n.idx?"":n.idx;e.TRACE_INIT(""+gt(n)+r,(function(){var r,i,o,a,s,c,u,p=(r=n.idx,i=t,o=n.maxLookahead||e.maxLookahead,a=n.hasPredicates,s=e.dynamicTokensEnabled,c=e.lookAheadBuilderForAlternatives,u=Zt(r,i,o),c(u,a,te(u)?U:F,s)),l=Ie(e.fullRuleNameToShort[t.name],256,n.idx);e.setLaFuncCache(l,p)}))})),Object(i.u)(o,(function(n){e.computeLookaheadFunc(t,n.idx,768,Wt.REPETITION,n.maxLookahead,gt(n))})),Object(i.u)(a,(function(n){e.computeLookaheadFunc(t,n.idx,512,Wt.OPTION,n.maxLookahead,gt(n))})),Object(i.u)(s,(function(n){e.computeLookaheadFunc(t,n.idx,1024,Wt.REPETITION_MANDATORY,n.maxLookahead,gt(n))})),Object(i.u)(c,(function(n){e.computeLookaheadFunc(t,n.idx,1536,Wt.REPETITION_MANDATORY_WITH_SEPARATOR,n.maxLookahead,gt(n))})),Object(i.u)(u,(function(n){e.computeLookaheadFunc(t,n.idx,1280,Wt.REPETITION_WITH_SEPARATOR,n.maxLookahead,gt(n))}))}))}))},t.prototype.computeLookaheadFunc=function(t,e,n,r,i,o){var a=this;this.TRACE_INIT(""+o+(0===e?"":e),(function(){var o=function(t,e,n,r,i,o){var a=Qt(t,e,i,n),s=te(a)?U:F;return o(a[0],s,r)}(e,t,i||a.maxLookahead,a.dynamicTokensEnabled,r,a.lookAheadBuilderForOptional),s=Ie(a.fullRuleNameToShort[t.name],n,e);a.setLaFuncCache(s,o)}))},t.prototype.lookAheadBuilderForOptional=function(t,e,n){return function(t,e,n){var r=Object(i.o)(t,(function(t){return 1===t.length})),o=t.length;if(r&&!n){var a=Object(i.t)(t);if(1===a.length&&Object(i.A)(a[0].categoryMatches)){var s=a[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===s}}var c=Object(i.O)(a,(function(t,e,n){return t[e.tokenTypeIdx]=!0,Object(i.u)(e.categoryMatches,(function(e){t[e]=!0})),t}),[]);return function(){var t=this.LA(1);return!0===c[t.tokenTypeIdx]}}return function(){t:for(var n=0;n on "+_e(t.constructor)+" CST Visitor.",type:Re.MISSING_METHOD,methodName:e}}));return Object(i.i)(n)}(t,e),r=function(t,e){var n=[];for(var r in t)ae.test(r)&&Object(i.B)(t[r])&&!Object(i.j)(xe,r)&&!Object(i.j)(e,r)&&n.push({msg:"Redundant visitor method: <"+r+"> on "+_e(t.constructor)+" CST Visitor\nThere is no Grammar Rule corresponding to this method's name.\nFor utility methods on visitor classes use methods names that do not match /"+ae.source+"/.",type:Re.REDUNDANT_METHOD,methodName:r});return n}(t,e);return n.concat(r)}(this,e);if(!Object(i.A)(t)){var n=Object(i.I)(t,(function(t){return t.msg}));throw Error("Errors Detected in CST Visitor <"+_e(this.constructor)+">:\n\t"+n.join("\n\n").replace(/\n/g,"\n\t"))}}}).constructor=n,n._RULE_NAMES=e,n}!function(t){t[t.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",t[t.MISSING_METHOD=1]="MISSING_METHOD"}(Re||(Re={}));var xe=["constructor","visit","validateVisitor"];var je=function(){function t(){}return t.prototype.initTreeBuilder=function(t){if(this.CST_STACK=[],this.outputCst=t.outputCst,this.nodeLocationTracking=Object(i.w)(t,"nodeLocationTracking")?t.nodeLocationTracking:Je.nodeLocationTracking,this.outputCst)if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Ne,this.setNodeLocationFromNode=Ne,this.cstPostRule=i.b,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=i.b,this.setNodeLocationFromNode=i.b,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Ae,this.setNodeLocationFromNode=Ae,this.cstPostRule=i.b,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=i.b,this.setNodeLocationFromNode=i.b,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else{if(!/none/i.test(this.nodeLocationTracking))throw Error('Invalid config option: "'+t.nodeLocationTracking+'"');this.setNodeLocationFromToken=i.b,this.setNodeLocationFromNode=i.b,this.cstPostRule=i.b,this.setInitialNodeLocation=i.b}else this.cstInvocationStateUpdate=i.b,this.cstFinallyStateUpdate=i.b,this.cstPostTerminal=i.b,this.cstPostNonTerminal=i.b,this.cstPostRule=i.b},t.prototype.setInitialNodeLocationOnlyOffsetRecovery=function(t){t.location={startOffset:NaN,endOffset:NaN}},t.prototype.setInitialNodeLocationOnlyOffsetRegular=function(t){t.location={startOffset:this.LA(1).startOffset,endOffset:NaN}},t.prototype.setInitialNodeLocationFullRecovery=function(t){t.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}},t.prototype.setInitialNodeLocationFullRegular=function(t){var e=this.LA(1);t.location={startOffset:e.startOffset,startLine:e.startLine,startColumn:e.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}},t.prototype.cstInvocationStateUpdate=function(t,e){var n={name:t,children:{}};this.setInitialNodeLocation(n),this.CST_STACK.push(n)},t.prototype.cstFinallyStateUpdate=function(){this.CST_STACK.pop()},t.prototype.cstPostRuleFull=function(t){var e=this.LA(0),n=t.location;n.startOffset<=e.startOffset==!0?(n.endOffset=e.endOffset,n.endLine=e.endLine,n.endColumn=e.endColumn):(n.startOffset=NaN,n.startLine=NaN,n.startColumn=NaN)},t.prototype.cstPostRuleOnlyOffset=function(t){var e=this.LA(0),n=t.location;n.startOffset<=e.startOffset==!0?n.endOffset=e.endOffset:n.startOffset=NaN},t.prototype.cstPostTerminal=function(t,e){var n,r,i,o=this.CST_STACK[this.CST_STACK.length-1];r=e,i=t,void 0===(n=o).children[i]?n.children[i]=[r]:n.children[i].push(r),this.setNodeLocationFromToken(o.location,e)},t.prototype.cstPostNonTerminal=function(t,e){var n=this.CST_STACK[this.CST_STACK.length-1];!function(t,e,n){void 0===t.children[e]?t.children[e]=[n]:t.children[e].push(n)}(n,e,t),this.setNodeLocationFromNode(n.location,t.location)},t.prototype.getBaseCstVisitorConstructor=function(){if(Object(i.F)(this.baseCstVisitorConstructor)){var t=Ce(this.className,Object(i.G)(this.gastProductionsCache));return this.baseCstVisitorConstructor=t,t}return this.baseCstVisitorConstructor},t.prototype.getBaseCstVisitorConstructorWithDefaults=function(){if(Object(i.F)(this.baseCstVisitorWithDefaultsConstructor)){var t=function(t,e,n){var r=function(){};Se(r,t+"BaseSemanticsWithDefaults");var o=Object.create(n.prototype);return Object(i.u)(e,(function(t){o[t]=Le})),(r.prototype=o).constructor=r,r}(this.className,Object(i.G)(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=t,t}return this.baseCstVisitorWithDefaultsConstructor},t.prototype.getLastExplicitRuleShortName=function(){var t=this.RULE_STACK;return t[t.length-1]},t.prototype.getPreviousExplicitRuleShortName=function(){var t=this.RULE_STACK;return t[t.length-2]},t.prototype.getLastExplicitRuleOccurrenceIndex=function(){var t=this.RULE_OCCURRENCE_STACK;return t[t.length-1]},t}(),Pe=function(){function t(){}return t.prototype.initLexerAdapter=function(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1},Object.defineProperty(t.prototype,"input",{get:function(){return this.tokVector},set:function(t){if(!0!==this.selfAnalysisDone)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=t,this.tokVectorLength=t.length},enumerable:!1,configurable:!0}),t.prototype.SKIP_TOKEN=function(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):Ze},t.prototype.LA=function(t){var e=this.currIdx+t;return e<0||this.tokVectorLength<=e?Ze:this.tokVector[e]},t.prototype.consumeToken=function(){this.currIdx++},t.prototype.exportLexerState=function(){return this.currIdx},t.prototype.importLexerState=function(t){this.currIdx=t},t.prototype.resetLexerState=function(){this.currIdx=-1},t.prototype.moveToTerminatedState=function(){this.currIdx=this.tokVector.length-1},t.prototype.getLexerPosition=function(){return this.exportLexerState()},t}(),we=function(){function t(){}return t.prototype.ACTION=function(t){return t.call(this)},t.prototype.consume=function(t,e,n){return this.consumeInternal(e,t,n)},t.prototype.subrule=function(t,e,n){return this.subruleInternal(e,t,n)},t.prototype.option=function(t,e){return this.optionInternal(e,t)},t.prototype.or=function(t,e){return this.orInternal(e,t)},t.prototype.many=function(t,e){return this.manyInternal(t,e)},t.prototype.atLeastOne=function(t,e){return this.atLeastOneInternal(t,e)},t.prototype.CONSUME=function(t,e){return this.consumeInternal(t,0,e)},t.prototype.CONSUME1=function(t,e){return this.consumeInternal(t,1,e)},t.prototype.CONSUME2=function(t,e){return this.consumeInternal(t,2,e)},t.prototype.CONSUME3=function(t,e){return this.consumeInternal(t,3,e)},t.prototype.CONSUME4=function(t,e){return this.consumeInternal(t,4,e)},t.prototype.CONSUME5=function(t,e){return this.consumeInternal(t,5,e)},t.prototype.CONSUME6=function(t,e){return this.consumeInternal(t,6,e)},t.prototype.CONSUME7=function(t,e){return this.consumeInternal(t,7,e)},t.prototype.CONSUME8=function(t,e){return this.consumeInternal(t,8,e)},t.prototype.CONSUME9=function(t,e){return this.consumeInternal(t,9,e)},t.prototype.SUBRULE=function(t,e){return this.subruleInternal(t,0,e)},t.prototype.SUBRULE1=function(t,e){return this.subruleInternal(t,1,e)},t.prototype.SUBRULE2=function(t,e){return this.subruleInternal(t,2,e)},t.prototype.SUBRULE3=function(t,e){return this.subruleInternal(t,3,e)},t.prototype.SUBRULE4=function(t,e){return this.subruleInternal(t,4,e)},t.prototype.SUBRULE5=function(t,e){return this.subruleInternal(t,5,e)},t.prototype.SUBRULE6=function(t,e){return this.subruleInternal(t,6,e)},t.prototype.SUBRULE7=function(t,e){return this.subruleInternal(t,7,e)},t.prototype.SUBRULE8=function(t,e){return this.subruleInternal(t,8,e)},t.prototype.SUBRULE9=function(t,e){return this.subruleInternal(t,9,e)},t.prototype.OPTION=function(t){return this.optionInternal(t,0)},t.prototype.OPTION1=function(t){return this.optionInternal(t,1)},t.prototype.OPTION2=function(t){return this.optionInternal(t,2)},t.prototype.OPTION3=function(t){return this.optionInternal(t,3)},t.prototype.OPTION4=function(t){return this.optionInternal(t,4)},t.prototype.OPTION5=function(t){return this.optionInternal(t,5)},t.prototype.OPTION6=function(t){return this.optionInternal(t,6)},t.prototype.OPTION7=function(t){return this.optionInternal(t,7)},t.prototype.OPTION8=function(t){return this.optionInternal(t,8)},t.prototype.OPTION9=function(t){return this.optionInternal(t,9)},t.prototype.OR=function(t){return this.orInternal(t,0)},t.prototype.OR1=function(t){return this.orInternal(t,1)},t.prototype.OR2=function(t){return this.orInternal(t,2)},t.prototype.OR3=function(t){return this.orInternal(t,3)},t.prototype.OR4=function(t){return this.orInternal(t,4)},t.prototype.OR5=function(t){return this.orInternal(t,5)},t.prototype.OR6=function(t){return this.orInternal(t,6)},t.prototype.OR7=function(t){return this.orInternal(t,7)},t.prototype.OR8=function(t){return this.orInternal(t,8)},t.prototype.OR9=function(t){return this.orInternal(t,9)},t.prototype.MANY=function(t){this.manyInternal(0,t)},t.prototype.MANY1=function(t){this.manyInternal(1,t)},t.prototype.MANY2=function(t){this.manyInternal(2,t)},t.prototype.MANY3=function(t){this.manyInternal(3,t)},t.prototype.MANY4=function(t){this.manyInternal(4,t)},t.prototype.MANY5=function(t){this.manyInternal(5,t)},t.prototype.MANY6=function(t){this.manyInternal(6,t)},t.prototype.MANY7=function(t){this.manyInternal(7,t)},t.prototype.MANY8=function(t){this.manyInternal(8,t)},t.prototype.MANY9=function(t){this.manyInternal(9,t)},t.prototype.MANY_SEP=function(t){this.manySepFirstInternal(0,t)},t.prototype.MANY_SEP1=function(t){this.manySepFirstInternal(1,t)},t.prototype.MANY_SEP2=function(t){this.manySepFirstInternal(2,t)},t.prototype.MANY_SEP3=function(t){this.manySepFirstInternal(3,t)},t.prototype.MANY_SEP4=function(t){this.manySepFirstInternal(4,t)},t.prototype.MANY_SEP5=function(t){this.manySepFirstInternal(5,t)},t.prototype.MANY_SEP6=function(t){this.manySepFirstInternal(6,t)},t.prototype.MANY_SEP7=function(t){this.manySepFirstInternal(7,t)},t.prototype.MANY_SEP8=function(t){this.manySepFirstInternal(8,t)},t.prototype.MANY_SEP9=function(t){this.manySepFirstInternal(9,t)},t.prototype.AT_LEAST_ONE=function(t){this.atLeastOneInternal(0,t)},t.prototype.AT_LEAST_ONE1=function(t){return this.atLeastOneInternal(1,t)},t.prototype.AT_LEAST_ONE2=function(t){this.atLeastOneInternal(2,t)},t.prototype.AT_LEAST_ONE3=function(t){this.atLeastOneInternal(3,t)},t.prototype.AT_LEAST_ONE4=function(t){this.atLeastOneInternal(4,t)},t.prototype.AT_LEAST_ONE5=function(t){this.atLeastOneInternal(5,t)},t.prototype.AT_LEAST_ONE6=function(t){this.atLeastOneInternal(6,t)},t.prototype.AT_LEAST_ONE7=function(t){this.atLeastOneInternal(7,t)},t.prototype.AT_LEAST_ONE8=function(t){this.atLeastOneInternal(8,t)},t.prototype.AT_LEAST_ONE9=function(t){this.atLeastOneInternal(9,t)},t.prototype.AT_LEAST_ONE_SEP=function(t){this.atLeastOneSepFirstInternal(0,t)},t.prototype.AT_LEAST_ONE_SEP1=function(t){this.atLeastOneSepFirstInternal(1,t)},t.prototype.AT_LEAST_ONE_SEP2=function(t){this.atLeastOneSepFirstInternal(2,t)},t.prototype.AT_LEAST_ONE_SEP3=function(t){this.atLeastOneSepFirstInternal(3,t)},t.prototype.AT_LEAST_ONE_SEP4=function(t){this.atLeastOneSepFirstInternal(4,t)},t.prototype.AT_LEAST_ONE_SEP5=function(t){this.atLeastOneSepFirstInternal(5,t)},t.prototype.AT_LEAST_ONE_SEP6=function(t){this.atLeastOneSepFirstInternal(6,t)},t.prototype.AT_LEAST_ONE_SEP7=function(t){this.atLeastOneSepFirstInternal(7,t)},t.prototype.AT_LEAST_ONE_SEP8=function(t){this.atLeastOneSepFirstInternal(8,t)},t.prototype.AT_LEAST_ONE_SEP9=function(t){this.atLeastOneSepFirstInternal(9,t)},t.prototype.RULE=function(t,e,n){if(void 0===n&&(n=tn),Object(i.j)(this.definedRulesNames,t)){var r={message:Lt.buildDuplicateRuleNameError({topLevelRule:t,grammarName:this.className}),type:Qe.DUPLICATE_RULE_NAME,ruleName:t};this.definitionErrors.push(r)}this.definedRulesNames.push(t);var o=this.defineRule(t,e,n);return this[t]=o,o},t.prototype.OVERRIDE_RULE=function(t,e,n){void 0===n&&(n=tn);var r,o,a,s,c,u=[];u=u.concat((r=t,o=this.definedRulesNames,a=this.className,c=[],i.j(o,r)||(s="Invalid rule override, rule: ->"+r+"<- cannot be overridden in the grammar: ->"+a+"<-as it is not defined in any of the super grammars ",c.push({message:s,type:Qe.INVALID_RULE_OVERRIDE,ruleName:r})),c)),this.definitionErrors.push.apply(this.definitionErrors,u);var p=this.defineRule(t,e,n);return this[t]=p,p},t.prototype.BACKTRACK=function(t,e){return function(){this.isBackTrackingStack.push(1);var n=this.saveRecogState();try{return t.apply(this,e),!0}catch(t){if(fe(t))return!1;throw t}finally{this.reloadRecogState(n),this.isBackTrackingStack.pop()}}},t.prototype.getGAstProductions=function(){return this.gastProductionsCache},t.prototype.getSerializedGastProductions=function(){return dt(Object(i.U)(this.gastProductionsCache))},t}(),Me=function(){function t(){}return t.prototype.initRecognizerEngine=function(t,e){if(this.className=_e(this.constructor),this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=U,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},Object(i.w)(e,"serializedGrammar"))throw Error("The Parser's configuration can no longer contain a property.\n\tSee: https://sap.github.io/chevrotain/docs/changes/BREAKING_CHANGES.html#_6-0-0\n\tFor Further details.");if(Object(i.y)(t)){if(Object(i.A)(t))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("number"==typeof t[0].startOffset)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(Object(i.y)(t))this.tokensMap=Object(i.O)(t,(function(t,e){return t[e.name]=e,t}),{});else if(Object(i.w)(t,"modes")&&Object(i.o)(Object(i.t)(Object(i.U)(t.modes)),H)){var n=Object(i.t)(Object(i.U)(t.modes)),r=Object(i.T)(n);this.tokensMap=Object(i.O)(r,(function(t,e){return t[e.name]=e,t}),{})}else{if(!Object(i.C)(t))throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap=Object(i.h)(t)}this.tokensMap.EOF=J;var o=Object(i.o)(Object(i.U)(t),(function(t){return Object(i.A)(t.categoryMatches)}));this.tokenMatcher=o?U:F,G(Object(i.U)(this.tokensMap))},t.prototype.defineRule=function(t,e,n){if(this.selfAnalysisDone)throw Error("Grammar rule <"+t+"> may not be defined after the 'performSelfAnalysis' method has been called'\nMake sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.");var r,o=Object(i.w)(n,"resyncEnabled")?n.resyncEnabled:tn.resyncEnabled,a=Object(i.w)(n,"recoveryValueFunc")?n.recoveryValueFunc:tn.recoveryValueFunc,s=this.ruleShortNameIdx<<12;function c(t){try{if(!0===this.outputCst){e.apply(this,t);var n=this.CST_STACK[this.CST_STACK.length-1];return this.cstPostRule(n),n}return e.apply(this,t)}catch(t){return this.invokeRuleCatch(t,o,a)}finally{this.ruleFinallyStateUpdate()}}this.ruleShortNameIdx++,this.shortRuleNameToFull[s]=t,this.fullRuleNameToShort[t]=s;return(r=function(e,n){return void 0===e&&(e=0),this.ruleInvocationStateUpdate(s,t,e),c.call(this,n)}).ruleName=t,r.originalGrammarAction=e,r},t.prototype.invokeRuleCatch=function(t,e,n){var r=1===this.RULE_STACK.length,i=e&&!this.isBackTracking()&&this.recoveryEnabled;if(fe(t)){var o=t;if(i){var a,s=this.findReSyncTokenType();if(this.isInCurrentRuleReSyncSet(s))return o.resyncedTokens=this.reSyncTo(s),this.outputCst?((a=this.CST_STACK[this.CST_STACK.length-1]).recoveredNode=!0,a):n();throw this.outputCst&&((a=this.CST_STACK[this.CST_STACK.length-1]).recoveredNode=!0,o.partialCstResult=a),o}if(r)return this.moveToTerminatedState(),n();throw o}throw t},t.prototype.optionInternal=function(t,e){var n=this.getKeyForAutomaticLookahead(512,e);return this.optionInternalLogic(t,e,n)},t.prototype.optionInternalLogic=function(t,e,n){var r,i,o=this,a=this.getLaFuncFromCache(n);if(void 0!==t.DEF){if(r=t.DEF,void 0!==(i=t.GATE)){var s=a;a=function(){return i.call(o)&&s.call(o)}}}else r=t;if(!0===a.call(this))return r.call(this)},t.prototype.atLeastOneInternal=function(t,e){var n=this.getKeyForAutomaticLookahead(1024,t);return this.atLeastOneInternalLogic(t,e,n)},t.prototype.atLeastOneInternalLogic=function(t,e,n){var r,i,o=this,a=this.getLaFuncFromCache(n);if(void 0!==e.DEF){if(r=e.DEF,void 0!==(i=e.GATE)){var s=a;a=function(){return i.call(o)&&s.call(o)}}}else r=e;if(!0!==a.call(this))throw this.raiseEarlyExitException(t,Wt.REPETITION_MANDATORY,e.ERR_MSG);for(var c=this.doSingleRepetition(r);!0===a.call(this)&&!0===c;)c=this.doSingleRepetition(r);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[t,e],a,1024,t,Ut)},t.prototype.atLeastOneSepFirstInternal=function(t,e){var n=this.getKeyForAutomaticLookahead(1536,t);this.atLeastOneSepFirstInternalLogic(t,e,n)},t.prototype.atLeastOneSepFirstInternalLogic=function(t,e,n){var r=this,i=e.DEF,o=e.SEP;if(!0!==this.getLaFuncFromCache(n).call(this))throw this.raiseEarlyExitException(t,Wt.REPETITION_MANDATORY_WITH_SEPARATOR,e.ERR_MSG);i.call(this);for(var a=function(){return r.tokenMatcher(r.LA(1),o)};!0===this.tokenMatcher(this.LA(1),o);)this.CONSUME(o),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[t,o,a,i,Dt],a,1536,t,Dt)},t.prototype.manyInternal=function(t,e){var n=this.getKeyForAutomaticLookahead(768,t);return this.manyInternalLogic(t,e,n)},t.prototype.manyInternalLogic=function(t,e,n){var r,i,o=this,a=this.getLaFuncFromCache(n);if(void 0!==e.DEF){if(r=e.DEF,void 0!==(i=e.GATE)){var s=a;a=function(){return i.call(o)&&s.call(o)}}}else r=e;for(var c=!0;!0===a.call(this)&&!0===c;)c=this.doSingleRepetition(r);this.attemptInRepetitionRecovery(this.manyInternal,[t,e],a,768,t,Mt,c)},t.prototype.manySepFirstInternal=function(t,e){var n=this.getKeyForAutomaticLookahead(1280,t);this.manySepFirstInternalLogic(t,e,n)},t.prototype.manySepFirstInternalLogic=function(t,e,n){var r=this,i=e.DEF,o=e.SEP;if(!0===this.getLaFuncFromCache(n).call(this)){i.call(this);for(var a=function(){return r.tokenMatcher(r.LA(1),o)};!0===this.tokenMatcher(this.LA(1),o);)this.CONSUME(o),i.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[t,o,a,i,Ft],a,1280,t,Ft)}},t.prototype.repetitionSepSecondInternal=function(t,e,n,r,i){for(;n();)this.CONSUME(e),r.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[t,e,n,r,i],n,1536,t,i)},t.prototype.doSingleRepetition=function(t){var e=this.getLexerPosition();return t.call(this),this.getLexerPosition()>e},t.prototype.orInternal=function(t,e){var n=this.getKeyForAutomaticLookahead(256,e),r=Object(i.y)(t)?t:t.DEF,o=this.getLaFuncFromCache(n).call(this,r);if(void 0!==o)return r[o].ALT.call(this);this.raiseNoAltException(e,t.ERR_MSG)},t.prototype.ruleFinallyStateUpdate=function(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),0===this.RULE_STACK.length&&!1===this.isAtEndOfInput()){var t=this.LA(1),e=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:t,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new ve(e,t))}},t.prototype.subruleInternal=function(t,e,n){var r;try{var i=void 0!==n?n.ARGS:void 0;return r=t.call(this,e,i),this.cstPostNonTerminal(r,void 0!==n&&void 0!==n.LABEL?n.LABEL:t.ruleName),r}catch(e){this.subruleInternalError(e,n,t.ruleName)}},t.prototype.subruleInternalError=function(t,e,n){throw fe(t)&&void 0!==t.partialCstResult&&(this.cstPostNonTerminal(t.partialCstResult,void 0!==e&&void 0!==e.LABEL?e.LABEL:n),delete t.partialCstResult),t},t.prototype.consumeInternal=function(t,e,n){var r;try{var i=this.LA(1);!0===this.tokenMatcher(i,t)?(this.consumeToken(),r=i):this.consumeInternalError(t,i,n)}catch(n){r=this.consumeInternalRecovery(t,e,n)}return this.cstPostTerminal(void 0!==n&&void 0!==n.LABEL?n.LABEL:t.name,r),r},t.prototype.consumeInternalError=function(t,e,n){var r,i=this.LA(0);throw r=void 0!==n&&n.ERR_MSG?n.ERR_MSG:this.errorMessageProvider.buildMismatchTokenMessage({expected:t,actual:e,previous:i,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new de(r,e,i))},t.prototype.consumeInternalRecovery=function(t,e,n){if(!this.recoveryEnabled||"MismatchedTokenException"!==n.name||this.isBackTracking())throw n;var r=this.getFollowsForInRuleRecovery(t,e);try{return this.tryInRuleRecovery(t,r)}catch(t){throw"InRuleRecoveryException"===t.name?n:t}},t.prototype.saveRecogState=function(){var t=this.errors,e=Object(i.g)(this.RULE_STACK);return{errors:t,lexerState:this.exportLexerState(),RULE_STACK:e,CST_STACK:this.CST_STACK}},t.prototype.reloadRecogState=function(t){this.errors=t.errors,this.importLexerState(t.lexerState),this.RULE_STACK=t.RULE_STACK},t.prototype.ruleInvocationStateUpdate=function(t,e,n){this.RULE_OCCURRENCE_STACK.push(n),this.RULE_STACK.push(t),this.cstInvocationStateUpdate(e,t)},t.prototype.isBackTracking=function(){return 0!==this.isBackTrackingStack.length},t.prototype.getCurrRuleFullName=function(){var t=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[t]},t.prototype.shortRuleNameToFullName=function(t){return this.shortRuleNameToFull[t]},t.prototype.isAtEndOfInput=function(){return this.tokenMatcher(this.LA(1),J)},t.prototype.reset=function(){this.resetLexerState(),this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]},t}(),Fe=function(){function t(){}return t.prototype.initErrorHandler=function(t){this._errors=[],this.errorMessageProvider=Object(i.w)(t,"errorMessageProvider")?t.errorMessageProvider:Je.errorMessageProvider},t.prototype.SAVE_ERROR=function(t){if(fe(t))return t.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:Object(i.g)(this.RULE_OCCURRENCE_STACK)},this._errors.push(t),t;throw Error("Trying to save an Error which is not a RecognitionException")},Object.defineProperty(t.prototype,"errors",{get:function(){return Object(i.g)(this._errors)},set:function(t){this._errors=t},enumerable:!1,configurable:!0}),t.prototype.raiseEarlyExitException=function(t,e,n){for(var r=this.getCurrRuleFullName(),i=Qt(t,this.getGAstProductions()[r],e,this.maxLookahead)[0],o=[],a=1;a<=this.maxLookahead;a++)o.push(this.LA(a));var s=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:i,actual:o,previous:this.LA(0),customUserDescription:n,ruleName:r});throw this.SAVE_ERROR(new Oe(s,this.LA(1),this.LA(0)))},t.prototype.raiseNoAltException=function(t,e){for(var n=this.getCurrRuleFullName(),r=Zt(t,this.getGAstProductions()[n],this.maxLookahead),i=[],o=1;o<=this.maxLookahead;o++)i.push(this.LA(o));var a=this.LA(0),s=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:r,actual:i,previous:a,customUserDescription:e,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new me(s,this.LA(1),a))},t}(),Ue=function(){function t(){}return t.prototype.initContentAssist=function(){},t.prototype.computeContentAssist=function(t,e){var n=this.gastProductionsCache[t];if(Object(i.F)(n))throw Error("Rule ->"+t+"<- does not exist in this grammar.");return Gt([n],e,this.tokenMatcher,this.maxLookahead)},t.prototype.getNextPossibleTokenTypes=function(t){var e=Object(i.s)(t.ruleStack),n=this.getGAstProductions()[e];return new Pt(n,t).startWalking()},t}(),De={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(De);var Be=Math.pow(2,8)-1,Ge=Q({name:"RECORDING_PHASE_TOKEN",pattern:X.NA});G([Ge]);var Ke=tt(Ge,"This IToken indicates the Parser is in Recording Phase\n\tSee: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details",-1,-1,-1,-1,-1,-1);Object.freeze(Ke);var We={name:"This CSTNode indicates the Parser is in Recording Phase\n\tSee: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details",children:{}},He=function(){function t(){}return t.prototype.initGastRecorder=function(t){this.recordingProdStack=[],this.RECORDING_PHASE=!1},t.prototype.enableRecording=function(){var t=this;this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",(function(){for(var e=function(e){var n=e>0?e:"";t["CONSUME"+n]=function(t,n){return this.consumeInternalRecord(t,e,n)},t["SUBRULE"+n]=function(t,n){return this.subruleInternalRecord(t,e,n)},t["OPTION"+n]=function(t){return this.optionInternalRecord(t,e)},t["OR"+n]=function(t){return this.orInternalRecord(t,e)},t["MANY"+n]=function(t){this.manyInternalRecord(e,t)},t["MANY_SEP"+n]=function(t){this.manySepFirstInternalRecord(e,t)},t["AT_LEAST_ONE"+n]=function(t){this.atLeastOneInternalRecord(e,t)},t["AT_LEAST_ONE_SEP"+n]=function(t){this.atLeastOneSepFirstInternalRecord(e,t)}},n=0;n<10;n++)e(n);t.consume=function(t,e,n){return this.consumeInternalRecord(e,t,n)},t.subrule=function(t,e,n){return this.subruleInternalRecord(e,t,n)},t.option=function(t,e){return this.optionInternalRecord(e,t)},t.or=function(t,e){return this.orInternalRecord(e,t)},t.many=function(t,e){this.manyInternalRecord(t,e)},t.atLeastOne=function(t,e){this.atLeastOneInternalRecord(t,e)},t.ACTION=t.ACTION_RECORD,t.BACKTRACK=t.BACKTRACK_RECORD,t.LA=t.LA_RECORD}))},t.prototype.disableRecording=function(){var t=this;this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",(function(){for(var e=0;e<10;e++){var n=e>0?e:"";delete t["CONSUME"+n],delete t["SUBRULE"+n],delete t["OPTION"+n],delete t["OR"+n],delete t["MANY"+n],delete t["MANY_SEP"+n],delete t["AT_LEAST_ONE"+n],delete t["AT_LEAST_ONE_SEP"+n]}delete t.consume,delete t.subrule,delete t.option,delete t.or,delete t.many,delete t.atLeastOne,delete t.ACTION,delete t.BACKTRACK,delete t.LA}))},t.prototype.ACTION_RECORD=function(t){},t.prototype.BACKTRACK_RECORD=function(t,e){return function(){return!0}},t.prototype.LA_RECORD=function(t){return Ze},t.prototype.topLevelRuleRecord=function(t,e){try{var n=new ot({definition:[],name:t});return n.name=t,this.recordingProdStack.push(n),e.call(this),this.recordingProdStack.pop(),n}catch(t){if(!0!==t.KNOWN_RECORDER_ERROR)try{t.message=t.message+'\n\t This error was thrown during the "grammar recording phase" For more info see:\n\thttps://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording'}catch(e){throw t}throw t}},t.prototype.optionInternalRecord=function(t,e){return Ve.call(this,st,t,e)},t.prototype.atLeastOneInternalRecord=function(t,e){Ve.call(this,ct,e,t)},t.prototype.atLeastOneSepFirstInternalRecord=function(t,e){Ve.call(this,ut,e,t,!0)},t.prototype.manyInternalRecord=function(t,e){Ve.call(this,pt,e,t)},t.prototype.manySepFirstInternalRecord=function(t,e){Ve.call(this,lt,e,t,!0)},t.prototype.orInternalRecord=function(t,e){return ze.call(this,t,e)},t.prototype.subruleInternalRecord=function(t,e,n){if(Xe(e),!t||!1===Object(i.w)(t,"ruleName")){var r=new Error(" argument is invalid expecting a Parser method reference but got: <"+JSON.stringify(t)+">\n inside top level rule: <"+this.recordingProdStack[0].name+">");throw r.KNOWN_RECORDER_ERROR=!0,r}var o=Object(i.M)(this.recordingProdStack),a=t.ruleName,s=new it({idx:e,nonTerminalName:a,referencedRule:void 0});return o.definition.push(s),this.outputCst?We:De},t.prototype.consumeInternalRecord=function(t,e,n){if(Xe(e),!K(t)){var r=new Error(" argument is invalid expecting a TokenType reference but got: <"+JSON.stringify(t)+">\n inside top level rule: <"+this.recordingProdStack[0].name+">");throw r.KNOWN_RECORDER_ERROR=!0,r}var o=Object(i.M)(this.recordingProdStack),a=new ft({idx:e,terminalType:t});return o.definition.push(a),Ke},t}();function Ve(t,e,n,r){void 0===r&&(r=!1),Xe(n);var o=Object(i.M)(this.recordingProdStack),a=Object(i.B)(e)?e:e.DEF,s=new t({definition:[],idx:n});return r&&(s.separator=e.SEP),Object(i.w)(e,"MAX_LOOKAHEAD")&&(s.maxLookahead=e.MAX_LOOKAHEAD),this.recordingProdStack.push(s),a.call(this),o.definition.push(s),this.recordingProdStack.pop(),De}function ze(t,e){var n=this;Xe(e);var r=Object(i.M)(this.recordingProdStack),o=!1===Object(i.y)(t),a=!1===o?t:t.DEF,s=new ht({definition:[],idx:e,ignoreAmbiguities:o&&!0===t.IGNORE_AMBIGUITIES});Object(i.w)(t,"MAX_LOOKAHEAD")&&(s.maxLookahead=t.MAX_LOOKAHEAD);var c=Object(i.Q)(a,(function(t){return Object(i.B)(t.GATE)}));return s.hasPredicates=c,r.definition.push(s),Object(i.u)(a,(function(t){var e=new at({definition:[]});s.definition.push(e),Object(i.w)(t,"IGNORE_AMBIGUITIES")?e.ignoreAmbiguities=t.IGNORE_AMBIGUITIES:Object(i.w)(t,"GATE")&&(e.ignoreAmbiguities=!0),n.recordingProdStack.push(e),t.ALT.call(n),n.recordingProdStack.pop()})),De}function Ye(t){return 0===t?"":""+t}function Xe(t){if(t<0||t>Be){var e=new Error("Invalid DSL Method idx value: <"+t+">\n\tIdx value must be a none negative value smaller than "+(Be+1));throw e.KNOWN_RECORDER_ERROR=!0,e}}var qe=function(){function t(){}return t.prototype.initPerformanceTracer=function(t){if(Object(i.w)(t,"traceInitPerf")){var e=t.traceInitPerf,n="number"==typeof e;this.traceInitMaxIdent=n?e:1/0,this.traceInitPerf=n?e>0:e}else this.traceInitMaxIdent=0,this.traceInitPerf=Je.traceInitPerf;this.traceInitIndent=-1},t.prototype.TRACE_INIT=function(t,e){if(!0===this.traceInitPerf){this.traceInitIndent++;var n=new Array(this.traceInitIndent+1).join("\t");this.traceInitIndent");var r=Object(i.R)(e),o=r.time,a=r.value,s=o>10?console.warn:console.log;return this.traceInitIndent time: "+o+"ms"),this.traceInitIndent--,a}return e()},t}(),$e=function(){var t=function(e,n){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(e,n)};return function(e,n){function r(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}(),Ze=tt(J,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(Ze);var Qe,Je=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:_t,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),tn=Object.freeze({recoveryValueFunc:function(){},resyncEnabled:!0});function en(t){return void 0===t&&(t=void 0),function(){return t}}!function(t){t[t.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",t[t.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",t[t.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",t[t.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",t[t.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",t[t.LEFT_RECURSION=5]="LEFT_RECURSION",t[t.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",t[t.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",t[t.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",t[t.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",t[t.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",t[t.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",t[t.TOO_MANY_ALTS=12]="TOO_MANY_ALTS"}(Qe||(Qe={}));var nn=function(){function t(t,e){this.definitionErrors=[],this.selfAnalysisDone=!1;if(this.initErrorHandler(e),this.initLexerAdapter(),this.initLooksAhead(e),this.initRecognizerEngine(t,e),this.initRecoverable(e),this.initTreeBuilder(e),this.initContentAssist(),this.initGastRecorder(e),this.initPerformanceTracer(e),Object(i.w)(e,"ignoredIssues"))throw new Error("The IParserConfig property has been deprecated.\n\tPlease use the flag on the relevant DSL method instead.\n\tSee: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES\n\tFor further details.");this.skipValidations=Object(i.w)(e,"skipValidations")?e.skipValidations:Je.skipValidations}return t.performSelfAnalysis=function(t){throw Error("The **static** `performSelfAnalysis` method has been deprecated.\t\nUse the **instance** method with the same name instead.")},t.prototype.performSelfAnalysis=function(){var e=this;this.TRACE_INIT("performSelfAnalysis",(function(){var n;e.selfAnalysisDone=!0;var r=e.className;e.TRACE_INIT("toFastProps",(function(){Object(i.S)(e)})),e.TRACE_INIT("Grammar Recording",(function(){try{e.enableRecording(),Object(i.u)(e.definedRulesNames,(function(t){var n=e[t].originalGrammarAction,r=void 0;e.TRACE_INIT(t+" Rule",(function(){r=e.topLevelRuleRecord(t,n)})),e.gastProductionsCache[t]=r}))}finally{e.disableRecording()}}));var o=[];if(e.TRACE_INIT("Grammar Resolving",(function(){o=ue({rules:Object(i.U)(e.gastProductionsCache)}),e.definitionErrors.push.apply(e.definitionErrors,o)})),e.TRACE_INIT("Grammar Validations",(function(){if(Object(i.A)(o)&&!1===e.skipValidations){var t=pe({rules:Object(i.U)(e.gastProductionsCache),maxLookahead:e.maxLookahead,tokenTypes:Object(i.U)(e.tokensMap),errMsgProvider:Lt,grammarName:r});e.definitionErrors.push.apply(e.definitionErrors,t)}})),Object(i.A)(e.definitionErrors)&&(e.recoveryEnabled&&e.TRACE_INIT("computeAllProdsFollows",(function(){var t,n,r=(t=Object(i.U)(e.gastProductionsCache),n={},Object(i.u)(t,(function(t){var e=new kt(t).startWalking();Object(i.f)(n,e)})),n);e.resyncFollows=r})),e.TRACE_INIT("ComputeLookaheadFunctions",(function(){e.preComputeLookaheadFunctions(Object(i.U)(e.gastProductionsCache))}))),!t.DEFER_DEFINITION_ERRORS_HANDLING&&!Object(i.A)(e.definitionErrors))throw n=Object(i.I)(e.definitionErrors,(function(t){return t.message})),new Error("Parser Definition Errors detected:\n "+n.join("\n-------------------------------\n"))}))},t.DEFER_DEFINITION_ERRORS_HANDLING=!1,t}();Object(i.e)(nn,[Ee,be,je,Pe,Me,we,Fe,Ue,He,qe]);var rn=function(t){function e(e,n){void 0===n&&(n=Je);var r=Object(i.h)(n);return r.outputCst=!0,t.call(this,e,r)||this}return $e(e,t),e}(nn),on=function(t){function e(e,n){void 0===n&&(n=Je);var r=Object(i.h)(n);return r.outputCst=!1,t.call(this,e,r)||this}return $e(e,t),e}(nn);function an(t,e){var n=void 0===e?{}:e,i=n.resourceBase,o=void 0===i?"https://unpkg.com/chevrotain@"+r+"/diagrams/":i,a=n.css;return'\n\x3c!-- This is a generated file --\x3e\n\n\n\n\n'+("\n\n")+("\n