chevrotain
Version:
Chevrotain is a high performance fault tolerant javascript parsing DSL for building recursive decent parsers
1,414 lines (1,393 loc) • 360 kB
JavaScript
/*! chevrotain - v2.0.1 */
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("chevrotain", [], factory);
else if(typeof exports === 'object')
exports["chevrotain"] = factory();
else
root["chevrotain"] = factory();
})(typeof self !== 'undefined' ? self : this, function() {
return /******/ (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, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // 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 = 15);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/*
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;
}
exports.isEmpty = isEmpty;
function keys(obj) {
if (obj === undefined || obj === null) {
return [];
}
return Object.keys(obj);
}
exports.keys = keys;
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;
}
exports.values = values;
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;
}
exports.mapValues = mapValues;
function map(arr, callback) {
var result = [];
for (var idx = 0; idx < arr.length; idx++) {
result.push(callback.call(null, arr[idx], idx));
}
return result;
}
exports.map = map;
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;
}
exports.flatten = flatten;
function first(arr) {
return isEmpty(arr) ? undefined : arr[0];
}
exports.first = first;
function last(arr) {
var len = arr && arr.length;
return len ? arr[len - 1] : undefined;
}
exports.last = last;
function forEach(collection, iteratorCallback) {
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 {
/* istanbul ignore next */
throw Error("non exhaustive match");
}
}
exports.forEach = forEach;
function isString(item) {
return typeof item === "string";
}
exports.isString = isString;
function isUndefined(item) {
return item === undefined;
}
exports.isUndefined = isUndefined;
function isFunction(item) {
return item instanceof Function;
}
exports.isFunction = isFunction;
function drop(arr, howMuch) {
if (howMuch === void 0) { howMuch = 1; }
return arr.slice(howMuch, arr.length);
}
exports.drop = drop;
function dropRight(arr, howMuch) {
if (howMuch === void 0) { howMuch = 1; }
return arr.slice(0, arr.length - howMuch);
}
exports.dropRight = dropRight;
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;
}
exports.filter = filter;
function reject(arr, predicate) {
return filter(arr, function (item) { return !predicate(item); });
}
exports.reject = reject;
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;
}
exports.pick = pick;
function has(obj, prop) {
if (isObject(obj)) {
return obj.hasOwnProperty(prop);
}
return false;
}
exports.has = has;
function contains(arr, item) {
return find(arr, function (currItem) { return currItem === item; }) !== undefined ? true : false;
}
exports.contains = contains;
/**
* shallow clone
*/
function cloneArr(arr) {
var newArr = [];
for (var i = 0; i < arr.length; i++) {
newArr.push(arr[i]);
}
return newArr;
}
exports.cloneArr = cloneArr;
/**
* 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;
}
exports.cloneObj = cloneObj;
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;
}
exports.find = find;
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;
}
exports.findAll = findAll;
function reduce(arrOrObj, iterator, initial) {
var vals = Array.isArray(arrOrObj)
? arrOrObj
: values(arrOrObj);
var accumulator = initial;
for (var i = 0; i < vals.length; i++) {
accumulator = iterator.call(null, accumulator, vals[i], i);
}
return accumulator;
}
exports.reduce = reduce;
function compact(arr) {
return reject(arr, function (item) { return item === null || item === undefined; });
}
exports.compact = compact;
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);
}
}, []);
}
exports.uniq = uniq;
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);
}
exports.partial = partial;
function isArray(obj) {
return Array.isArray(obj);
}
exports.isArray = isArray;
function isRegExp(obj) {
return obj instanceof RegExp;
}
exports.isRegExp = isRegExp;
function isObject(obj) {
return obj instanceof Object;
}
exports.isObject = isObject;
function every(arr, predicate) {
for (var i = 0; i < arr.length; i++) {
if (!predicate(arr[i], i)) {
return false;
}
}
return true;
}
exports.every = every;
function difference(arr, values) {
return reject(arr, function (item) { return contains(values, item); });
}
exports.difference = difference;
function some(arr, predicate) {
for (var i = 0; i < arr.length; i++) {
if (predicate(arr[i])) {
return true;
}
}
return false;
}
exports.some = some;
function indexOf(arr, value) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === value) {
return i;
}
}
return -1;
}
exports.indexOf = indexOf;
function sortBy(arr, orderFunc) {
var result = cloneArr(arr);
result.sort(function (a, b) { return orderFunc(a) - orderFunc(b); });
return result;
}
exports.sortBy = sortBy;
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;
}
exports.zipObject = zipObject;
/**
* 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;
}
exports.assign = assign;
/**
* mutates! (and returns) target
*/
function assignNoOverwrite(target) {
var sources = [];
for (var _i = 1; _i < arguments.length; _i++) {
sources[_i - 1] = arguments[_i];
}
for (var i = 0; i < sources.length; i++) {
var curSource = sources[i];
if (isUndefined(curSource)) {
continue;
}
var currSourceKeys = keys(curSource);
for (var j = 0; j < currSourceKeys.length; j++) {
var currKey = currSourceKeys[j];
if (!has(target, currKey)) {
target[currKey] = curSource[currKey];
}
}
}
return target;
}
exports.assignNoOverwrite = assignNoOverwrite;
function defaults() {
var sources = [];
for (var _i = 0; _i < arguments.length; _i++) {
sources[_i] = arguments[_i];
}
return assignNoOverwrite.apply(null, [{}].concat(sources));
}
exports.defaults = defaults;
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;
}
exports.groupBy = groupBy;
/**
* 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;
}
exports.merge = merge;
function NOOP() { }
exports.NOOP = NOOP;
function IDENTITY(item) {
return item;
}
exports.IDENTITY = IDENTITY;
//# sourceMappingURL=utils.js.map
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var 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 function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = __webpack_require__(0);
var tokens_public_1 = __webpack_require__(2);
var AbstractProduction = /** @class */ (function () {
function AbstractProduction(definition) {
this.definition = definition;
}
AbstractProduction.prototype.accept = function (visitor) {
visitor.visit(this);
utils_1.forEach(this.definition, function (prod) {
prod.accept(visitor);
});
};
return AbstractProduction;
}());
exports.AbstractProduction = AbstractProduction;
var NonTerminal = /** @class */ (function (_super) {
__extends(NonTerminal, _super);
function NonTerminal(options) {
var _this = _super.call(this, []) || this;
_this.idx = 1;
utils_1.assign(_this, options);
return _this;
}
Object.defineProperty(NonTerminal.prototype, "definition", {
get: function () {
if (this.referencedRule !== undefined) {
return this.referencedRule.definition;
}
return [];
},
set: function (definition) {
// immutable
},
enumerable: true,
configurable: true
});
NonTerminal.prototype.accept = function (visitor) {
visitor.visit(this);
// don't visit children of a reference, we will get cyclic infinite loops if we do so
};
return NonTerminal;
}(AbstractProduction));
exports.NonTerminal = NonTerminal;
var Rule = /** @class */ (function (_super) {
__extends(Rule, _super);
function Rule(options) {
var _this = _super.call(this, options.definition) || this;
_this.orgText = "";
utils_1.assign(_this, options);
return _this;
}
return Rule;
}(AbstractProduction));
exports.Rule = Rule;
var Flat = /** @class */ (function (_super) {
__extends(Flat, _super);
// A named Flat production is used to indicate a Nested Rule in an alternation
function Flat(options) {
var _this = _super.call(this, options.definition) || this;
utils_1.assign(_this, options);
return _this;
}
return Flat;
}(AbstractProduction));
exports.Flat = Flat;
var Option = /** @class */ (function (_super) {
__extends(Option, _super);
function Option(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
utils_1.assign(_this, options);
return _this;
}
return Option;
}(AbstractProduction));
exports.Option = Option;
var RepetitionMandatory = /** @class */ (function (_super) {
__extends(RepetitionMandatory, _super);
function RepetitionMandatory(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
utils_1.assign(_this, options);
return _this;
}
return RepetitionMandatory;
}(AbstractProduction));
exports.RepetitionMandatory = RepetitionMandatory;
var RepetitionMandatoryWithSeparator = /** @class */ (function (_super) {
__extends(RepetitionMandatoryWithSeparator, _super);
function RepetitionMandatoryWithSeparator(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
utils_1.assign(_this, options);
return _this;
}
return RepetitionMandatoryWithSeparator;
}(AbstractProduction));
exports.RepetitionMandatoryWithSeparator = RepetitionMandatoryWithSeparator;
var Repetition = /** @class */ (function (_super) {
__extends(Repetition, _super);
function Repetition(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
utils_1.assign(_this, options);
return _this;
}
return Repetition;
}(AbstractProduction));
exports.Repetition = Repetition;
var RepetitionWithSeparator = /** @class */ (function (_super) {
__extends(RepetitionWithSeparator, _super);
function RepetitionWithSeparator(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
utils_1.assign(_this, options);
return _this;
}
return RepetitionWithSeparator;
}(AbstractProduction));
exports.RepetitionWithSeparator = RepetitionWithSeparator;
var Alternation = /** @class */ (function (_super) {
__extends(Alternation, _super);
function Alternation(options) {
var _this = _super.call(this, options.definition) || this;
_this.idx = 1;
utils_1.assign(_this, options);
return _this;
}
return Alternation;
}(AbstractProduction));
exports.Alternation = Alternation;
var Terminal = /** @class */ (function () {
function Terminal(options) {
this.idx = 1;
utils_1.assign(this, options);
}
Terminal.prototype.accept = function (visitor) {
visitor.visit(this);
};
return Terminal;
}());
exports.Terminal = Terminal;
function serializeGrammar(topRules) {
return utils_1.map(topRules, serializeProduction);
}
exports.serializeGrammar = serializeGrammar;
function serializeProduction(node) {
function convertDefinition(definition) {
return utils_1.map(definition, serializeProduction);
}
if (node instanceof NonTerminal) {
return {
type: "NonTerminal",
name: node.nonTerminalName,
idx: node.idx
};
}
else if (node instanceof Flat) {
return {
type: "Flat",
definition: convertDefinition(node.definition)
};
}
else if (node instanceof Option) {
return {
type: "Option",
definition: convertDefinition(node.definition)
};
}
else if (node instanceof RepetitionMandatory) {
return {
type: "RepetitionMandatory",
definition: convertDefinition(node.definition)
};
}
else if (node instanceof RepetitionMandatoryWithSeparator) {
return {
type: "RepetitionMandatoryWithSeparator",
separator: serializeProduction(new Terminal({ terminalType: node.separator })),
definition: convertDefinition(node.definition)
};
}
else if (node instanceof RepetitionWithSeparator) {
return {
type: "RepetitionWithSeparator",
separator: serializeProduction(new Terminal({ terminalType: node.separator })),
definition: convertDefinition(node.definition)
};
}
else if (node instanceof Repetition) {
return {
type: "Repetition",
definition: convertDefinition(node.definition)
};
}
else if (node instanceof Alternation) {
return {
type: "Alternation",
definition: convertDefinition(node.definition)
};
}
else if (node instanceof Terminal) {
var serializedTerminal = {
type: "Terminal",
name: tokens_public_1.tokenName(node.terminalType),
label: tokens_public_1.tokenLabel(node.terminalType),
idx: node.idx
};
var pattern = node.terminalType.PATTERN;
if (node.terminalType.PATTERN) {
serializedTerminal.pattern = utils_1.isRegExp(pattern)
? pattern.source
: pattern;
}
return serializedTerminal;
}
else if (node instanceof Rule) {
// IGNORE ABOVE ELSE
return {
type: "Rule",
name: node.name,
definition: convertDefinition(node.definition)
};
}
else {
/* istanbul ignore next */
throw Error("non exhaustive match");
}
}
exports.serializeProduction = serializeProduction;
//# sourceMappingURL=gast_public.js.map
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = __webpack_require__(0);
var lang_extensions_1 = __webpack_require__(3);
var lexer_public_1 = __webpack_require__(11);
var tokens_1 = __webpack_require__(8);
/**
* This can be used to improve the quality/readability of error messages or syntax diagrams.
*
* @param {TokenType} clazz - A constructor for a Token subclass
* @returns {string} - The Human readable label for a Token if it exists.
*/
function tokenLabel(clazz) {
if (hasTokenLabel(clazz)) {
return clazz.LABEL;
}
else {
return tokenName(clazz);
}
}
exports.tokenLabel = tokenLabel;
function hasTokenLabel(obj) {
return utils_1.isString(obj.LABEL) && obj.LABEL !== "";
}
exports.hasTokenLabel = hasTokenLabel;
function tokenName(obj) {
// The tokenName property is needed under some old versions of node.js (0.10/0.12)
// where the Function.prototype.name property is not defined as a 'configurable' property
// enable producing readable error messages.
/* istanbul ignore if -> will only run in old versions of node.js */
if (utils_1.isObject(obj) &&
obj.hasOwnProperty("tokenName") &&
utils_1.isString(obj.tokenName)) {
return obj.tokenName;
}
else {
return lang_extensions_1.functionName(obj);
}
}
exports.tokenName = tokenName;
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";
/**
* @param {ITokenConfig} config - The configuration for
* @returns {TokenType} - A constructor for the new Token subclass
*/
function createToken(config) {
return createTokenInternal(config);
}
exports.createToken = createToken;
function createTokenInternal(config) {
var tokenName = config.name;
var pattern = config.pattern;
var tokenType = {};
// 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
/* istanbul ignore if -> will only run in old versions of node.js */
if (!lang_extensions_1.defineNameProp(tokenType, tokenName)) {
// hack to save the tokenName in situations where the constructor's name property cannot be reconfigured
tokenType.tokenName = tokenName;
}
if (!utils_1.isUndefined(pattern)) {
tokenType.PATTERN = pattern;
}
if (utils_1.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 (utils_1.has(config, CATEGORIES)) {
tokenType.CATEGORIES = config[CATEGORIES];
}
tokens_1.augmentTokenTypes([tokenType]);
if (utils_1.has(config, LABEL)) {
tokenType.LABEL = config[LABEL];
}
if (utils_1.has(config, GROUP)) {
tokenType.GROUP = config[GROUP];
}
if (utils_1.has(config, POP_MODE)) {
tokenType.POP_MODE = config[POP_MODE];
}
if (utils_1.has(config, PUSH_MODE)) {
tokenType.PUSH_MODE = config[PUSH_MODE];
}
if (utils_1.has(config, LONGER_ALT)) {
tokenType.LONGER_ALT = config[LONGER_ALT];
}
if (utils_1.has(config, LINE_BREAKS)) {
tokenType.LINE_BREAKS = config[LINE_BREAKS];
}
return tokenType;
}
exports.EOF = createToken({ name: "EOF", pattern: lexer_public_1.Lexer.NA });
tokens_1.augmentTokenTypes([exports.EOF]);
/**
* Utility to create Chevrotain Token "instances"
* Note that Chevrotain tokens are not real instances, and thus the instanceOf cannot be used.
*
* @param tokType
* @param image
* @param startOffset
* @param endOffset
* @param startLine
* @param endLine
* @param startColumn
* @param endColumn
* @returns {{image: string,
* startOffset: number,
* endOffset: number,
* startLine: number,
* endLine: number,
* startColumn: number,
* endColumn: number,
* tokenType}}
*/
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
};
}
exports.createTokenInstance = createTokenInstance;
/**
* A Utility method to check if a token is of the type of the argument Token class.
* This utility is needed because Chevrotain tokens support "categories" which means
* A TokenType may have multiple categories, so a TokenType for the "true" literal in JavaScript
* May be both a Keyword Token and a Literal Token.
*
* @param token {IToken}
* @param tokType {TokenType}
* @returns {boolean}
*/
function tokenMatcher(token, tokType) {
return tokens_1.tokenStructuredMatcher(token, tokType);
}
exports.tokenMatcher = tokenMatcher;
//# sourceMappingURL=tokens_public.js.map
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var utils = __webpack_require__(0);
var utils_1 = __webpack_require__(0);
function classNameFromInstance(instance) {
return functionName(instance.constructor);
}
exports.classNameFromInstance = classNameFromInstance;
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;
}
exports.functionName = functionName;
/**
* @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 (utils_1.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;
}
exports.defineNameProp = defineNameProp;
/**
* simple Hashtable between a string and some generic value
* this should be removed once typescript supports ES6 style Hashtable
*/
var HashTable = /** @class */ (function () {
function HashTable() {
this._state = {};
}
HashTable.prototype.keys = function () {
return utils.keys(this._state);
};
HashTable.prototype.values = function () {
return utils.values(this._state);
};
HashTable.prototype.put = function (key, value) {
this._state[key] = value;
};
HashTable.prototype.putAll = function (other) {
this._state = utils.assign(this._state, other._state);
};
HashTable.prototype.get = function (key) {
// To avoid edge case with a key called "hasOwnProperty" we need to perform the commented out check below
// -> if (Object.prototype.hasOwnProperty.call(this._state, key)) { ... } <-
// however this costs nearly 25% of the parser's runtime.
// if someone decides to name their Parser class "hasOwnProperty" they deserve what they will get :)
return this._state[key];
};
HashTable.prototype.containsKey = function (key) {
return utils.has(this._state, key);
};
HashTable.prototype.clear = function () {
this._state = {};
};
return HashTable;
}());
exports.HashTable = HashTable;
//# sourceMappingURL=lang_extensions.js.map
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var gast_public_1 = __webpack_require__(1);
var GAstVisitor = /** @class */ (function () {
function GAstVisitor() {
}
GAstVisitor.prototype.visit = function (node) {
if (node instanceof gast_public_1.NonTerminal) {
return this.visitNonTerminal(node);
}
else if (node instanceof gast_public_1.Flat) {
return this.visitFlat(node);
}
else if (node instanceof gast_public_1.Option) {
return this.visitOption(node);
}
else if (node instanceof gast_public_1.RepetitionMandatory) {
return this.visitRepetitionMandatory(node);
}
else if (node instanceof gast_public_1.RepetitionMandatoryWithSeparator) {
return this.visitRepetitionMandatoryWithSeparator(node);
}
else if (node instanceof gast_public_1.RepetitionWithSeparator) {
return this.visitRepetitionWithSeparator(node);
}
else if (node instanceof gast_public_1.Repetition) {
return this.visitRepetition(node);
}
else if (node instanceof gast_public_1.Alternation) {
return this.visitAlternation(node);
}
else if (node instanceof gast_public_1.Terminal) {
return this.visitTerminal(node);
}
else if (node instanceof gast_public_1.Rule) {
return this.visitRule(node);
}
else {
/* istanbul ignore next */
throw Error("non exhaustive match");
}
};
GAstVisitor.prototype.visitNonTerminal = function (node) { };
GAstVisitor.prototype.visitFlat = function (node) { };
GAstVisitor.prototype.visitOption = function (node) { };
GAstVisitor.prototype.visitRepetition = function (node) { };
GAstVisitor.prototype.visitRepetitionMandatory = function (node) { };
GAstVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { };
GAstVisitor.prototype.visitRepetitionWithSeparator = function (node) { };
GAstVisitor.prototype.visitAlternation = function (node) { };
GAstVisitor.prototype.visitTerminal = function (node) { };
GAstVisitor.prototype.visitRule = function (node) { };
return GAstVisitor;
}());
exports.GAstVisitor = GAstVisitor;
//# sourceMappingURL=gast_visitor_public.js.map
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __extends = (this && this.__extends) || (function () {
var 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 function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var utils_1 = __webpack_require__(0);
var gast_public_1 = __webpack_require__(1);
var gast_visitor_public_1 = __webpack_require__(4);
var tokens_public_1 = __webpack_require__(2);
function isSequenceProd(prod) {
return (prod instanceof gast_public_1.Flat ||
prod instanceof gast_public_1.Option ||
prod instanceof gast_public_1.Repetition ||
prod instanceof gast_public_1.RepetitionMandatory ||
prod instanceof gast_public_1.RepetitionMandatoryWithSeparator ||
prod instanceof gast_public_1.RepetitionWithSeparator ||
prod instanceof gast_public_1.Terminal ||
prod instanceof gast_public_1.Rule);
}
exports.isSequenceProd = isSequenceProd;
function isOptionalProd(prod, alreadyVisited) {
if (alreadyVisited === void 0) { alreadyVisited = []; }
var isDirectlyOptional = prod instanceof gast_public_1.Option ||
prod instanceof gast_public_1.Repetition ||
prod instanceof gast_public_1.RepetitionWithSeparator;
if (isDirectlyOptional) {
return true;
}
// note that this can cause infinite loop if one optional empty TOP production has a cyclic dependency with another
// empty optional top rule
// may be indirectly optional ((A?B?C?) | (D?E?F?))
if (prod instanceof gast_public_1.Alternation) {
// for OR its enough for just one of the alternatives to be optional
return utils_1.some(prod.definition, function (subProd) {
return isOptionalProd(subProd, alreadyVisited);
});
}
else if (prod instanceof gast_public_1.NonTerminal && utils_1.contains(alreadyVisited, prod)) {
// avoiding stack overflow due to infinite recursion
return false;
}
else if (prod instanceof gast_public_1.AbstractProduction) {
if (prod instanceof gast_public_1.NonTerminal) {
alreadyVisited.push(prod);
}
return utils_1.every(prod.definition, function (subProd) {
return isOptionalProd(subProd, alreadyVisited);
});
}
else {
return false;
}
}
exports.isOptionalProd = isOptionalProd;
function isBranchingProd(prod) {
return prod instanceof gast_public_1.Alternation;
}
exports.isBranchingProd = isBranchingProd;
function getProductionDslName(prod) {
if (prod instanceof gast_public_1.NonTerminal) {
return "SUBRULE";
}
else if (prod instanceof gast_public_1.Option) {
return "OPTION";
}
else if (prod instanceof gast_public_1.Alternation) {
return "OR";
}
else if (prod instanceof gast_public_1.RepetitionMandatory) {
return "AT_LEAST_ONE";
}
else if (prod instanceof gast_public_1.RepetitionMandatoryWithSeparator) {
return "AT_LEAST_ONE_SEP";
}
else if (prod instanceof gast_public_1.RepetitionWithSeparator) {
return "MANY_SEP";
}
else if (prod instanceof gast_public_1.Repetition) {
return "MANY";
}
else if (prod instanceof gast_public_1.Terminal) {
return "CONSUME";
}
else {
/* istanbul ignore next */
throw Error("non exhaustive match");
}
}
exports.getProductionDslName = getProductionDslName;
var GastCloneVisitor = /** @class */ (function (_super) {
__extends(GastCloneVisitor, _super);
function GastCloneVisitor() {
return _super !== null && _super.apply(this, arguments) || this;
}
GastCloneVisitor.prototype.visitNonTerminal = function (node) {
return new gast_public_1.NonTerminal({
nonTerminalName: node.nonTerminalName,
idx: node.idx
});
};
GastCloneVisitor.prototype.visitFlat = function (node) {
var _this = this;
var definition = utils_1.map(node.definition, function (currSubDef) {
return _this.visit(currSubDef);
});
return new gast_public_1.Flat({ definition: definition, name: node.name });
};
GastCloneVisitor.prototype.visitOption = function (node) {
var _this = this;
var definition = utils_1.map(node.definition, function (currSubDef) {
return _this.visit(currSubDef);
});
return new gast_public_1.Option({
definition: definition,
idx: node.idx,
name: node.name
});
};
GastCloneVisitor.prototype.visitRepetition = function (node) {
var _this = this;
var definition = utils_1.map(node.definition, function (currSubDef) {
return _this.visit(currSubDef);
});
return new gast_public_1.Repetition({
definition: definition,
idx: node.idx,
name: node.name
});
};
GastCloneVisitor.prototype.visitRepetitionMandatory = function (node) {
var _this = this;
var definition = utils_1.map(node.definition, function (currSubDef) {
return _this.visit(currSubDef);
});
return new gast_public_1.RepetitionMandatory({
definition: definition,
idx: node.idx,
name: node.name
});
};
GastCloneVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) {
var _this = this;
var definition = utils_1.map(node.definition, function (currSubDef) {
return _this.visit(currSubDef);
});
return new gast_public_1.RepetitionMandatoryWithSeparator({
definition: definition,
separator: node.separator,
idx: node.idx,
name: node.name
});
};
GastCloneVisitor.prototype.visitRepetitionWithSeparator = function (node) {
var _this = this;
var definition = utils_1.map(node.definition, function (currSubDef) {
return _this.visit(currSubDef);
});
return new gast_public_1.RepetitionWithSeparator({
definition: definition,
separator: node.separator,
idx: node.idx,
name: node.name
});
};
GastCloneVisitor.prototype.visitAlternation = function (node) {
var _this = this;
var definition = utils_1.map(node.definition, function (currSubDef) {
return _this.visit(currSubDef);
});
return new gast_public_1.Alternation({
definition: definition,
idx: node.idx,
name: node.name
});
};
GastCloneVisitor.prototype.visitTerminal = function (node) {
return new gast_public_1.Terminal({
terminalType: node.terminalType,
idx: node.idx
});
};
GastCloneVisitor.prototype.visitRule = function (node) {
var _this = this;
var definition = utils_1.map(node.definition, function (currSubDef) {
return _this.visit(currSubDef);
});
return new gast_public_1.Rule({
name: node.name,
definition: definition,
orgText: node.orgText
});
};
return GastCloneVisitor;
}(gast_visitor_public_1.GAstVisitor));
function cloneProduction(prod) {
var cloningVisitor = new GastCloneVisitor();
return cloningVisitor.visit(prod);
}
exports.cloneProduction = cloneProduction;
var DslMethodsCollectorVisitor = /** @class */ (function (_super) {
__extends(DslMethodsCollectorVisitor, _super);
function DslMethodsCollectorVisitor() {
var _this = _super !== null && _super.apply(this, arguments) || this;
// A minus is never valid in an identifier name
_this.separator = "-";
_this.dslMethods = {
option: [],
alternation: [],
repetition: [],
repetitionWithSeparator: [],
repetitionMandatory: [],
repetitionMandatoryWithSeparator: []
};
return _this;
}
DslMethodsCollectorVisitor.prototype.visitTerminal = function (terminal) {
var key = tokens_public_1.tokenName(terminal.terminalType) + this.separator + "Terminal";
if (!utils_1.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 (!utils_1.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_1.GAstVisitor));
exports.DslMethodsCollectorVisitor = DslMethodsCollectorVisitor;
//# sourceMappingURL=gast.js.map
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var tokens_public_1 = __webpack_require__(2);
var utils = __webpack_require__(0);
var utils_1 = __webpack_require__(0);
var gast_public_1 = __webpack_require__(1);
var gast_1 = __webpack_require__(5);
var checks_1 = __webpack_require__(7);
var version_1 = __webpack_require__(14);
/**
* This is the default logic Chevrotain uses to construct error messages.
* When constructing a custom error message provider it may be used as a reference
* or reused.
*/
exports.defaultParserErrorProvider = {
buildMismatchTokenMessage: function (_a) {
var expected = _a.expected, actual = _a.actual, ruleName = _a.ruleName;
var hasLabel = tokens_public_1.hasTokenLabel(expected);
var expectedMsg = hasLabel
? "--> " + tokens_public_1.tokenLabel(expected) + " <--"
: "token of type --> " + tokens_public_1.tokenName(expected) + " <--";
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, customUserDescription = _a.customUserDescription, ruleName = _a.ruleName;
var errPrefix = "Expecting: ";
// TODO: issue: No Viable Alternative Error may have incomplete details. #502
var actualText = utils_1.first(actual).image;
var errSuffix = "\nbut found: '" + actualText + "'";
if (customUserDescription) {
return errPrefix + customUserDescription + errSuffix;
}
else {
var allLookAheadPaths = utils_1.reduce(expectedPathsPerAlt, function (result, currAltPaths) { return result.concat(currAltPaths); }, []);
var nextValidTokenSequences = utils_1.map(allLookAheadPaths, function (currPath) {
return "[" + utils_1.map(currPath, function (currTokenType) {
return tokens_public_1.tokenLabel(currTokenType);
}).join(", ") + "]";
});
var nextValidSequenceItems = utils_1.map(nextValidTokenSequences, function (itemMsg, idx) { return " " + (idx + 1) + ". " + itemMsg; });
var calculatedDescription = "one of these possible Token sequences:\n" + nextValidSequenceItems.join("\n");
return errPrefix + calculatedDescription + errSuffix;
}
},
buildEarlyExitMessage: function (_a) {
var expectedIterationPaths = _a.expectedIterationPaths, actual = _a.actual, customUserDescription = _a.customUserDescription, ruleName = _a.ruleName;
var errPrefix = "Expecting: ";
// TODO: issue: No Viable Alternative Error may have incomplete details. #502
var actualText = utils_1.first(actual).image;
var errSuffix = "\nbut found: '" + actualText + "'";
if (customUserDescription) {
return errPrefix + customUserDescription + errSuffix;
}
else {
var nextValidTokenSequences = utils_1.map(expectedIterationPaths, function (currPath) {
return "[" + utils_1.map(currPath, function (currTokenType) {
return tokens_public_1.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(exports.defaultParserErrorProvider);
exports.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;
}
};
exports.defaultGrammarValidatorErrorProvider = {
buildDuplicateFoundError: function (topLevelRule, duplicateProds) {
function getExtraProductionArgument(prod) {
if (prod instanceof gast_public_1.Terminal) {
return tokens_public_1.tokenName(prod.terminalType);
}
else if (prod instanceof gast_public_1.NonTerminal) {
return prod.nonTerminalName;
}
else {
return "";
}
}
var topLevelName = topLevelRule.name;
var duplicateProd = utils_1.first(duplicateProds);
var index = duplicateProd.idx;
var dslName = gast_1.getProductionDslName(duplicateProd);
var extraArgument = getExtraProductionArgument(duplicateProd);
var msg = "->" + dslName + "<- with numerical suffix: ->" + index + "<-\n " + (extraArgument ? "and argument: ->" + extraArgument + "<-" : "") + "\n appears more than once (" + duplicateProds.length + " times) in the top level rule: ->" + topLevelName + "<-.\n " + (index === 0
? "Also note that numerical suffix 0 means " + dslName + " without any suffix."
: "") + "\n To fix this make sure each usage of " + dslName + " " + (extraArgument ? "with the argument: ->" + extraArgument + "<-" : "") + "\n in the rule ->" + topLevelName + "<- has a different occurrence index (0-5), as that combination acts as a unique\n position key in the grammar, which is needed by the parsing engine.\n \n For further details see: http://sap.github.io/chevrotain/website/FAQ.html#NUMERICAL_SUFFIXES \n ";
// white space trimming time! better to trim afterwards as it allows to use WELL formatted multi line template strings...
msg = msg.replace(/[ \t]+/g, " ");
msg = msg.replace(/\s\s+/g, "\n");
return msg;
},
buildInvalidNestedRuleNameError: function (topLevelRule, nestedProd) {
var msg = "Invalid nested rule name: ->" + nestedProd.name + "<- inside rule: ->" + topLevelRule.name + "<-\n" +
("it must match the pattern: ->" + checks_1.validNestedRuleName.toString() + "<-.\n") +
"Note that this means a nested rule name must start with the '$'(dollar) sign.";
return msg;
},
buildDuplicateNestedRuleNameError: function (topLevelRule, nestedProd) {
var duplicateName = utils_1.first(nestedProd).name;
var errMsg = "Duplicate nested rule name: ->" + duplicateName + "<- inside rule: ->" + topLevelRule.name + "<-\n" +
"A nested name must be unique in the scope of a top level grammar rule.";
return errMsg;
},
buildNamespaceConflictError: