diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..aa09d23
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,110 @@
+# Created by .ignore support plugin (hsz.mobi)
+### Java template
+# Compiled class file
+*.class
+src/main/java/Credentials/*.java
+src/main/java/Data/*.json
+node_modules
+
+# Log file
+*.log
+
+# BlueJ files
+*.ctxt
+
+# Mobile Tools for Java (J2ME)
+.mtj.tmp/
+
+# Package Files #
+*.jar
+*.war
+*.nar
+*.ear
+*.zip
+*.tar.gz
+*.rar
+*.json
+
+# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
+hs_err_pid*
+
+### Intellij ###
+# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
+# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
+
+# User-specific stuff
+.idea/**/workspace.xml
+.idea/**/tasks.xml
+.idea/**/usage.statistics.xml
+.idea/**/dictionaries
+.idea/**/shelf
+
+# Generated files
+.idea/**/contentModel.xml
+
+# Sensitive or high-churn files
+.idea/**/dataSources/
+.idea/**/dataSources.ids
+.idea/**/dataSources.local.xml
+.idea/**/sqlDataSources.xml
+.idea/**/dynamic.xml
+.idea/**/uiDesigner.xml
+.idea/**/dbnavigator.xml
+
+# Gradle
+.idea/**/gradle.xml
+.idea/**/libraries
+
+# Gradle and Maven with auto-import
+# When using Gradle or Maven with auto-import, you should exclude module files,
+# since they will be recreated, and may cause churn. Uncomment if using
+# auto-import.
+.idea/modules.xml
+.idea/*.iml
+.idea/modules
+
+# CMake
+cmake-build-*/
+
+# Mongo Explorer plugin
+.idea/**/mongoSettings.xml
+
+# File-based project format
+*.iws
+
+# IntelliJ
+out/
+
+# mpeltonen/sbt-idea plugin
+.idea_modules/
+
+
+# JIRA plugin
+atlassian-ide-plugin.xml
+
+# Cursive Clojure plugin
+.idea/replstate.xml
+
+# Crashlytics plugin (for Android Studio and IntelliJ)
+com_crashlytics_export_strings.xml
+crashlytics.properties
+crashlytics-build.properties
+fabric.properties
+
+# Editor-based Rest Client
+.idea/httpRequests
+
+# Android studio 3.1+ serialized cache file
+.idea/caches/build_file_checksums.ser
+
+# JetBrains templates
+**___jb_tmp___
+
+*.iml
+modules.xml
+.idea/misc.xml
+*.ipr
+
+
+# Sonarlint plugin
+.idea/sonarlint
diff --git a/.idea/.gitignore b/.idea/.gitignore
new file mode 100644
index 0000000..5c98b42
--- /dev/null
+++ b/.idea/.gitignore
@@ -0,0 +1,2 @@
+# Default ignored files
+/workspace.xml
\ No newline at end of file
diff --git a/.idea/codeStyles/codeStyleConfig.xml b/.idea/codeStyles/codeStyleConfig.xml
new file mode 100644
index 0000000..a55e7a1
--- /dev/null
+++ b/.idea/codeStyles/codeStyleConfig.xml
@@ -0,0 +1,5 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/compiler.xml b/.idea/compiler.xml
new file mode 100644
index 0000000..e1db647
--- /dev/null
+++ b/.idea/compiler.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/copyright/Kevin_Shehu.xml b/.idea/copyright/Kevin_Shehu.xml
new file mode 100644
index 0000000..0e5e24b
--- /dev/null
+++ b/.idea/copyright/Kevin_Shehu.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml
new file mode 100644
index 0000000..e29a48a
--- /dev/null
+++ b/.idea/jarRepositories.xml
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/jpa-buddy.xml b/.idea/jpa-buddy.xml
new file mode 100644
index 0000000..d08f400
--- /dev/null
+++ b/.idea/jpa-buddy.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/runConfigurations.xml b/.idea/runConfigurations.xml
new file mode 100644
index 0000000..797acea
--- /dev/null
+++ b/.idea/runConfigurations.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 0000000..94a25f7
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..4ebd422
--- /dev/null
+++ b/README.md
@@ -0,0 +1,39 @@
+### **Gardeners Green Thumb Decision Support System** (GGD-DDS)
+
+The service of decision support system is inferring knowledge from the available data of the greenhouse, the user input, and historical data what a user/the gardener should do & which action a gardener should execute to be successful with the growing process of the plants.
+These actions are called goals.
+The list of inferred active goals is offered to other services of the system.
+ The approach of the DSS is based on three eu.hsrw.ias.ggd.MainExe concepts:
+
+**Fact knowledge (Knowledgebase)**
+
+1. Hardware Information(sensor data info)
+2. Data information was given by an expert that is overwriting sensor data
+3. User Input (We assume that the user is every time honest and that input is every time correct)
+
+**Rules (General structure, if premises then consequence)**
+1. Explicit given by expert (before and during runtime)
+ 1. Battery
+ 2. Dielectric Permittivity
+ 3. Precipitation
+ 4. Soil Conductivity
+ 5. Soil Moisture
+ 6. Soil Temperature
+ 7. Temperature
+2. All this information is considered as facts which are part of the entire knowledge graph
+3. One particular rule can be fire on multiple rules can be fired. User defined.
+
+**Goals**
+1. Goals are active rules which are able to change the fact
+2. Goals can be activated and deactivated based on the user preferences
+3. Goals can have priorities
+
+#### **Build**
+Run the MainExe.java which is part of the eu.hsrw.ias.ggd package
+#### **Usage**
+You can reuse the project by changing the UserCredentials.java file located on the Credentials package.
+It is possible to create new rules tailored to the needs.
+#### **Examples**
+For each sensor mentioned in the list of rules an example is given. You may change the values based on the needs of the expert/user.
+#### **Dependencies**
+drools.org
\ No newline at end of file
diff --git a/node_modules/.bin/prettier b/node_modules/.bin/prettier
new file mode 100644
index 0000000..3e9eb4b
--- /dev/null
+++ b/node_modules/.bin/prettier
@@ -0,0 +1,12 @@
+#!/bin/sh
+basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
+
+case `uname` in
+ *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;;
+esac
+
+if [ -x "$basedir/node" ]; then
+ exec "$basedir/node" "$basedir/../prettier/bin-prettier.js" "$@"
+else
+ exec node "$basedir/../prettier/bin-prettier.js" "$@"
+fi
diff --git a/node_modules/.bin/prettier.cmd b/node_modules/.bin/prettier.cmd
new file mode 100644
index 0000000..b101ae4
--- /dev/null
+++ b/node_modules/.bin/prettier.cmd
@@ -0,0 +1,17 @@
+@ECHO off
+GOTO start
+:find_dp0
+SET dp0=%~dp0
+EXIT /b
+:start
+SETLOCAL
+CALL :find_dp0
+
+IF EXIST "%dp0%\node.exe" (
+ SET "_prog=%dp0%\node.exe"
+) ELSE (
+ SET "_prog=node"
+ SET PATHEXT=%PATHEXT:;.JS;=;%
+)
+
+endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\prettier\bin-prettier.js" %*
diff --git a/node_modules/.bin/prettier.ps1 b/node_modules/.bin/prettier.ps1
new file mode 100644
index 0000000..a584fce
--- /dev/null
+++ b/node_modules/.bin/prettier.ps1
@@ -0,0 +1,28 @@
+#!/usr/bin/env pwsh
+$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
+
+$exe=""
+if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
+ # Fix case when both the Windows and Linux builds of Node
+ # are installed in the same directory
+ $exe=".exe"
+}
+$ret=0
+if (Test-Path "$basedir/node$exe") {
+ # Support pipeline input
+ if ($MyInvocation.ExpectingInput) {
+ $input | & "$basedir/node$exe" "$basedir/../prettier/bin-prettier.js" $args
+ } else {
+ & "$basedir/node$exe" "$basedir/../prettier/bin-prettier.js" $args
+ }
+ $ret=$LASTEXITCODE
+} else {
+ # Support pipeline input
+ if ($MyInvocation.ExpectingInput) {
+ $input | & "node$exe" "$basedir/../prettier/bin-prettier.js" $args
+ } else {
+ & "node$exe" "$basedir/../prettier/bin-prettier.js" $args
+ }
+ $ret=$LASTEXITCODE
+}
+exit $ret
diff --git a/node_modules/chevrotain/CHANGELOG.md b/node_modules/chevrotain/CHANGELOG.md
new file mode 100644
index 0000000..8e426e7
--- /dev/null
+++ b/node_modules/chevrotain/CHANGELOG.md
@@ -0,0 +1,2 @@
+The [ChangeLog](./docs/changes/CHANGELOG.md) has moved
+to the docs folder.
diff --git a/node_modules/chevrotain/LICENSE.txt b/node_modules/chevrotain/LICENSE.txt
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/node_modules/chevrotain/LICENSE.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/node_modules/chevrotain/README.md b/node_modules/chevrotain/README.md
new file mode 100644
index 0000000..8845a85
--- /dev/null
+++ b/node_modules/chevrotain/README.md
@@ -0,0 +1,20 @@
+# Chevrotain
+
+For details see:
+
+- Chevrotain's [website](https://sap.github.io/chevrotain/docs/).
+- Chevrotain's root [README](https://github.com/SAP/chevrotain).
+
+## Install
+
+Using npm:
+
+```sh
+npm install chevrotain
+```
+
+or using yarn:
+
+```sh
+yarn add chevrotain
+```
diff --git a/node_modules/chevrotain/diagrams/README.md b/node_modules/chevrotain/diagrams/README.md
new file mode 100644
index 0000000..418931b
--- /dev/null
+++ b/node_modules/chevrotain/diagrams/README.md
@@ -0,0 +1 @@
+See [online docs](https://sap.github.io/chevrotain/docs/guide/generating_syntax_diagrams.html).
diff --git a/node_modules/chevrotain/diagrams/diagrams.css b/node_modules/chevrotain/diagrams/diagrams.css
new file mode 100644
index 0000000..66c924e
--- /dev/null
+++ b/node_modules/chevrotain/diagrams/diagrams.css
@@ -0,0 +1,85 @@
+svg.railroad-diagram path {
+ stroke-width: 3;
+ stroke: black;
+ fill: rgba(0, 0, 0, 0);
+}
+
+svg.railroad-diagram text {
+ font: bold 14px monospace;
+ text-anchor: middle;
+}
+
+svg.railroad-diagram text.label {
+ text-anchor: start;
+}
+
+svg.railroad-diagram text.comment {
+ font: italic 12px monospace;
+}
+
+svg.railroad-diagram g.non-terminal rect {
+ fill: hsl(223, 100%, 83%);
+}
+
+svg.railroad-diagram rect {
+ stroke-width: 3;
+ stroke: black;
+ fill: hsl(190, 100%, 83%);
+}
+
+.diagramHeader {
+ display: inline-block;
+ -webkit-touch-callout: default;
+ -webkit-user-select: text;
+ -khtml-user-select: text;
+ -moz-user-select: text;
+ -ms-user-select: text;
+ user-select: text;
+ font-weight: bold;
+ font-family: monospace;
+ font-size: 18px;
+ margin-bottom: -8px;
+ text-align: center;
+}
+
+.diagramHeaderDef {
+ background-color: lightgreen;
+}
+
+svg.railroad-diagram text {
+ -webkit-touch-callout: default;
+ -webkit-user-select: text;
+ -khtml-user-select: text;
+ -moz-user-select: text;
+ -ms-user-select: text;
+ user-select: text;
+}
+
+svg.railroad-diagram g.non-terminal rect.diagramRectUsage {
+ color: green;
+ fill: yellow;
+ stroke: 5;
+}
+
+svg.railroad-diagram g.terminal rect.diagramRectUsage {
+ color: green;
+ fill: yellow;
+ stroke: 5;
+}
+
+div {
+ -webkit-touch-callout: none;
+ -webkit-user-select: none;
+ -khtml-user-select: none;
+ -moz-user-select: none;
+ -ms-user-select: none;
+ user-select: none;
+}
+
+svg {
+ width: 100%;
+}
+
+svg.railroad-diagram g.non-terminal text {
+ cursor: pointer;
+}
\ No newline at end of file
diff --git a/node_modules/chevrotain/diagrams/src/diagrams_behavior.js b/node_modules/chevrotain/diagrams/src/diagrams_behavior.js
new file mode 100644
index 0000000..cf781f1
--- /dev/null
+++ b/node_modules/chevrotain/diagrams/src/diagrams_behavior.js
@@ -0,0 +1,225 @@
+;(function(root, factory) {
+ if (typeof define === "function" && define.amd) {
+ // AMD. Register as an anonymous module.
+ define([], factory)
+ } else if (typeof module === "object" && module.exports) {
+ // Node. Does not work with strict CommonJS, but
+ // only CommonJS-like environments that support module.exports,
+ // like Node.
+ module.exports = factory()
+ } else {
+ // Browser globals (root is window)
+ root.diagrams_behavior = factory()
+ }
+})(this, function() {
+ /**
+ * @param [scrollingEnabled=true] {boolean} - Is the scrolling from a non-terminal usage to it's definition
+ * enabled. it is enabled by default, but this flow is not relevant in all use cases (playground) and thus
+ * it is parametrized.
+ */
+ function initDiagramsBehavior(scrollingEnabled) {
+ if (scrollingEnabled === undefined) {
+ scrollingEnabled = true
+ }
+
+ var diagramHeaders = toArr(
+ document.getElementsByClassName("diagramHeader")
+ )
+ diagramHeaders.forEach(function(header) {
+ header.addEventListener(
+ "mouseover",
+ toggleNonTerminalUsageAndDef_fromHeader
+ )
+ header.addEventListener(
+ "mouseout",
+ toggleNonTerminalUsageAndDef_fromHeader
+ )
+ })
+
+ var noneTerminals = toArr(
+ document.getElementsByClassName("non-terminal")
+ )
+ var noneTerminalsText = findDomChildrenByTagName(noneTerminals, "text")
+ noneTerminalsText.forEach(function(nonTerminal) {
+ nonTerminal.addEventListener(
+ "mouseover",
+ toggleNonTerminalUsageAndDef_fromNoneTerminal
+ )
+ nonTerminal.addEventListener(
+ "mouseout",
+ toggleNonTerminalUsageAndDef_fromNoneTerminal
+ )
+
+ if (scrollingEnabled) {
+ nonTerminal.addEventListener("click", jumpToNoneTerminalDef)
+ }
+ })
+
+ var terminals = toArr(document.getElementsByClassName("terminal"))
+ var terminalsText = findDomChildrenByTagName(terminals, "text")
+ terminalsText.forEach(function(terminal) {
+ terminal.addEventListener("mouseover", toggleTerminalUsage)
+ terminal.addEventListener("mouseout", toggleTerminalUsage)
+ })
+ }
+
+ function toggleTerminalUsage(mouseEvent) {
+ var terminalName = mouseEvent.target.getAttribute("label")
+ var rects = getUsageSvgRect(terminalName, "terminal", "label")
+ toggleClassForNodes(rects, "diagramRectUsage")
+ }
+
+ function toggleNonTerminalUsageAndDef_fromNoneTerminal(mouseEvent) {
+ var rectsHeaderAndRuleName = getUsageRectAndDefHeader(mouseEvent.target)
+ toggleClassForNodes(rectsHeaderAndRuleName.rects, "diagramRectUsage")
+ toggleClass(rectsHeaderAndRuleName.header, "diagramHeaderDef")
+ }
+
+ function jumpToNoneTerminalDef(mouseEvent) {
+ var header = findHeader(mouseEvent.target.getAttribute("rulename"))
+ scrollToY(header.offsetTop, 666, "easeInOutQuint")
+ }
+
+ function toggleNonTerminalUsageAndDef_fromHeader(mouseEvent) {
+ toggleClass(mouseEvent.target, "diagramHeaderDef")
+ // this does not work on an svg DOM element so its ok to use innerHTML.
+ var definitionName = mouseEvent.target.innerHTML
+ var rects = getUsageSvgRect(definitionName, "non-terminal", "rulename")
+ toggleClassForNodes(rects, "diagramRectUsage")
+ }
+
+ function getUsageSvgRect(definitionName, className, attributeName) {
+ var classDomElements = toArr(document.getElementsByClassName(className))
+ var rects = findDomChildrenByTagName(classDomElements, "rect")
+ return rects.filter(function(currRect) {
+ var textNode = currRect.parentNode.getElementsByTagName("text")[0]
+ return textNode.getAttribute(attributeName) === definitionName
+ })
+ }
+
+ function findHeader(headerName) {
+ var headers = toArr(document.getElementsByClassName("diagramHeader"))
+ var header = headers.find(function(currHeader) {
+ // this works on H2 dom elements and not SVG elements so innerHTML usage is safe.
+ return currHeader.innerHTML === headerName
+ })
+ return header
+ }
+
+ function getUsageRectAndDefHeader(target) {
+ var headerName = target.getAttribute("rulename")
+ var rects = getUsageSvgRect(headerName, "non-terminal", "rulename")
+ var header = findHeader(headerName)
+ return {
+ rects: rects,
+ header: header,
+ ruleName: headerName
+ }
+ }
+
+ // utils
+
+ // IE 10/11 does not support this on svg elements.
+ // I'm uncertain I really care... :)
+ // https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
+ function toggleClass(domNode, className) {
+ if (domNode.classList.contains(className)) {
+ domNode.classList.remove(className)
+ } else {
+ domNode.classList.add(className)
+ }
+ }
+
+ function toggleClassForNodes(domNodes, className) {
+ domNodes.forEach(function(currDomNode) {
+ toggleClass(currDomNode, className)
+ })
+ }
+
+ function toArr(htmlCollection) {
+ return Array.prototype.slice.call(htmlCollection)
+ }
+
+ // first add raf shim
+ // http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
+ var requestAnimFrame = (function() {
+ return (
+ window.requestAnimationFrame ||
+ window.webkitRequestAnimationFrame ||
+ window.mozRequestAnimationFrame ||
+ function(callback) {
+ window.setTimeout(callback, 1000 / 60)
+ }
+ )
+ })()
+
+ // https://stackoverflow.com/questions/8917921/cross-browser-javascript-not-jquery-scroll-to-top-animation
+ function scrollToY(scrollTargetY, speed, easing) {
+ // scrollTargetY: the target scrollY property of the window
+ // speed: time in pixels per second
+ // easing: easing equation to use
+
+ var scrollY = window.scrollY,
+ scrollTargetY = scrollTargetY || 0,
+ speed = speed || 2000,
+ easing = easing || "easeOutSine",
+ currentTime = 0
+
+ // min time .1, max time .8 seconds
+ var time = Math.max(
+ 0.1,
+ Math.min(Math.abs(scrollY - scrollTargetY) / speed, 0.8)
+ )
+
+ // easing equations from https://github.com/danro/easing-js/blob/master/easing.js
+ var PI_D2 = Math.PI / 2,
+ easingEquations = {
+ easeOutSine: function(pos) {
+ return Math.sin(pos * (Math.PI / 2))
+ },
+ easeInOutSine: function(pos) {
+ return -0.5 * (Math.cos(Math.PI * pos) - 1)
+ },
+ easeInOutQuint: function(pos) {
+ if ((pos /= 0.5) < 1) {
+ return 0.5 * Math.pow(pos, 5)
+ }
+ return 0.5 * (Math.pow(pos - 2, 5) + 2)
+ }
+ }
+
+ // add animation loop
+ function tick() {
+ currentTime += 1 / 60
+
+ var p = currentTime / time
+ var t = easingEquations[easing](p)
+
+ if (p < 1) {
+ requestAnimFrame(tick)
+
+ window.scrollTo(0, scrollY + (scrollTargetY - scrollY) * t)
+ } else {
+ window.scrollTo(0, scrollTargetY)
+ }
+ }
+
+ // call it once to get started
+ tick()
+ }
+
+ function findDomChildrenByTagName(domElements, tagName) {
+ var elemsFound = []
+ domElements.forEach(function(currDomNode) {
+ toArr(currDomNode.children).forEach(function(currChild) {
+ if (currChild.tagName === tagName) {
+ elemsFound.push(currChild)
+ }
+ })
+ })
+ return elemsFound
+ }
+ return {
+ initDiagramsBehavior: initDiagramsBehavior
+ }
+})
diff --git a/node_modules/chevrotain/diagrams/src/diagrams_builder.js b/node_modules/chevrotain/diagrams/src/diagrams_builder.js
new file mode 100644
index 0000000..cdf484f
--- /dev/null
+++ b/node_modules/chevrotain/diagrams/src/diagrams_builder.js
@@ -0,0 +1,211 @@
+;(function(root, factory) {
+ if (typeof define === "function" && define.amd) {
+ // AMD. Register as an anonymous module.
+ // TODO: remove dependency to Chevrotain
+ define(["../vendor/railroad-diagrams"], factory)
+ } else if (typeof module === "object" && module.exports) {
+ // Node. Does not work with strict CommonJS, but
+ // only CommonJS-like environments that support module.exports,
+ // like Node.
+ // TODO: remove dependency to Chevrotain
+ module.exports = factory(require("../vendor/railroad-diagrams"))
+ } else {
+ // Browser globals (root is window)
+ root.diagrams_builder = factory(root.railroad)
+ }
+})(this, function(railroad) {
+ var Diagram = railroad.Diagram
+ var Sequence = railroad.Sequence
+ var Choice = railroad.Choice
+ var Optional = railroad.Optional
+ var OneOrMore = railroad.OneOrMore
+ var ZeroOrMore = railroad.ZeroOrMore
+ var Terminal = railroad.Terminal
+ var NonTerminal = railroad.NonTerminal
+
+ /**
+ * @param {chevrotain.gast.ISerializedGast} topRules
+ *
+ * @returns {string} - The htmlText that will render the diagrams
+ */
+ function buildSyntaxDiagramsText(topRules) {
+ var diagramsHtml = ""
+
+ topRules.forEach(function(production) {
+ var currDiagramHtml = convertProductionToDiagram(
+ production,
+ production.name
+ )
+ diagramsHtml +=
+ '
' +
+ production.name +
+ "
" +
+ currDiagramHtml
+ })
+
+ return diagramsHtml
+ }
+
+ function definitionsToSubDiagrams(definitions, topRuleName) {
+ var subDiagrams = definitions.map(function(subProd) {
+ return convertProductionToDiagram(subProd, topRuleName)
+ })
+ return subDiagrams
+ }
+
+ /**
+ * @param {chevrotain.gast.ISerializedTerminal} prod
+ * @param {string} topRuleName
+ * @param {string} dslRuleName
+ *
+ * @return {RailRoadDiagram.Terminal}
+ */
+ function createTerminalFromSerializedGast(prod, topRuleName, dslRuleName) {
+ // PATTERN static property will not exist when using custom lexers (hand built or other lexer generators)
+ var toolTipTitle = undefined
+ // avoid trying to use a custom token pattern as the title.
+ if (
+ typeof prod.pattern === "string" ||
+ Object.prototype.toString.call(prod.pattern) === "[object RegExp]"
+ ) {
+ toolTipTitle = prod.pattern
+ }
+
+ return railroad.Terminal(
+ prod.label,
+ undefined,
+ toolTipTitle,
+ prod.occurrenceInParent,
+ topRuleName,
+ dslRuleName,
+ prod.name
+ )
+ }
+
+ /**
+ * @param prod
+ * @param topRuleName
+ *
+ * Converts a single Chevrotain Grammar production to a RailRoad Diagram.
+ * This is also exported to allow custom logic in the creation of the diagrams.
+ * @returns {*}
+ */
+ function convertProductionToDiagram(prod, topRuleName) {
+ if (prod.type === "NonTerminal") {
+ // must handle NonTerminal separately from the other AbstractProductions as we do not want to expand the subDefinition
+ // of a reference and cause infinite loops
+ return NonTerminal(
+ getNonTerminalName(prod),
+ undefined,
+ prod.occurrenceInParent,
+ topRuleName
+ )
+ } else if (prod.type !== "Terminal") {
+ var subDiagrams = definitionsToSubDiagrams(
+ prod.definition,
+ topRuleName
+ )
+ if (prod.type === "Rule") {
+ return Diagram.apply(this, subDiagrams)
+ } else if (prod.type === "Flat") {
+ return Sequence.apply(this, subDiagrams)
+ } else if (prod.type === "Option") {
+ if (subDiagrams.length > 1) {
+ return Optional(Sequence.apply(this, subDiagrams))
+ } else if (subDiagrams.length === 1) {
+ return Optional(subDiagrams[0])
+ } else {
+ throw Error("Empty Optional production, OOPS!")
+ }
+ } else if (prod.type === "Repetition") {
+ if (subDiagrams.length > 1) {
+ return ZeroOrMore(Sequence.apply(this, subDiagrams))
+ } else if (subDiagrams.length === 1) {
+ return ZeroOrMore(subDiagrams[0])
+ } else {
+ throw Error("Empty Optional production, OOPS!")
+ }
+ } else if (prod.type === "Alternation") {
+ // todo: what does the first argument of choice (the index 0 means?)
+ return Choice.apply(this, [0].concat(subDiagrams))
+ } else if (prod.type === "RepetitionMandatory") {
+ if (subDiagrams.length > 1) {
+ return OneOrMore(Sequence.apply(this, subDiagrams))
+ } else if (subDiagrams.length === 1) {
+ return OneOrMore(subDiagrams[0])
+ } else {
+ throw Error("Empty Optional production, OOPS!")
+ }
+ } else if (prod.type === "RepetitionWithSeparator") {
+ if (subDiagrams.length > 0) {
+ // MANY_SEP(separator, definition) === (definition (separator definition)*)?
+ return Optional(
+ Sequence.apply(
+ this,
+ subDiagrams.concat([
+ ZeroOrMore(
+ Sequence.apply(
+ this,
+ [
+ createTerminalFromSerializedGast(
+ prod.separator,
+ topRuleName,
+ "many_sep"
+ )
+ ].concat(subDiagrams)
+ )
+ )
+ ])
+ )
+ )
+ } else {
+ throw Error("Empty Optional production, OOPS!")
+ }
+ } else if (prod.type === "RepetitionMandatoryWithSeparator") {
+ if (subDiagrams.length > 0) {
+ // AT_LEAST_ONE_SEP(separator, definition) === definition (separator definition)*
+ return Sequence.apply(
+ this,
+ subDiagrams.concat([
+ ZeroOrMore(
+ Sequence.apply(
+ this,
+ [
+ createTerminalFromSerializedGast(
+ prod.separator,
+ topRuleName,
+ "at_least_one_sep"
+ )
+ ].concat(subDiagrams)
+ )
+ )
+ ])
+ )
+ } else {
+ throw Error("Empty Optional production, OOPS!")
+ }
+ }
+ } else if (prod.type === "Terminal") {
+ return createTerminalFromSerializedGast(
+ prod,
+ topRuleName,
+ "consume"
+ )
+ } else {
+ throw Error("non exhaustive match")
+ }
+ }
+
+ function getNonTerminalName(prod) {
+ if (prod.nonTerminalName !== undefined) {
+ return prod.nonTerminalName
+ } else {
+ return prod.name
+ }
+ }
+
+ return {
+ buildSyntaxDiagramsText: buildSyntaxDiagramsText,
+ convertProductionToDiagram: convertProductionToDiagram
+ }
+})
diff --git a/node_modules/chevrotain/diagrams/src/diagrams_serializer.js b/node_modules/chevrotain/diagrams/src/diagrams_serializer.js
new file mode 100644
index 0000000..181e160
--- /dev/null
+++ b/node_modules/chevrotain/diagrams/src/diagrams_serializer.js
@@ -0,0 +1,20 @@
+/**
+ * @param {string} targetFilePath - The path and file name to serialize to.
+ * @param {string} varName - The name of the global variable to expose the serialized contents/
+ * @param {chevrotain.Parser} parserInstance - A parser instance whose grammar will be serialized.
+ */
+function serializeGrammarToFile(targetFilePath, varName, parserInstance) {
+ var fs = require("fs")
+ var serializedGrammar = parserInstance.getSerializedGastProductions()
+ var serializedGrammarText = JSON.stringify(serializedGrammar, null, "\t")
+
+ // generated a JavaScript file which exports the serialized grammar on the global scope (Window)
+ fs.writeFileSync(
+ targetFilePath,
+ "var " + varName + " = " + serializedGrammarText
+ )
+}
+
+module.exports = {
+ serializeGrammarToFile: serializeGrammarToFile
+}
diff --git a/node_modules/chevrotain/diagrams/src/main.js b/node_modules/chevrotain/diagrams/src/main.js
new file mode 100644
index 0000000..d9a197e
--- /dev/null
+++ b/node_modules/chevrotain/diagrams/src/main.js
@@ -0,0 +1,38 @@
+;(function(root, factory) {
+ if (typeof define === "function" && define.amd) {
+ // AMD. Register as an anonymous module.
+ define(["./diagrams_builder", "./diagrams_behavior"], factory)
+ } else if (typeof module === "object" && module.exports) {
+ // Node. Does not work with strict CommonJS, but
+ // only CommonJS-like environments that support module.exports,
+ // like Node.
+ module.exports = factory(
+ require("./diagrams_builder"),
+ require("./diagrams_behavior")
+ )
+ } else {
+ // Browser globals (root is window)
+ root.main = factory(root.diagrams_builder, root.diagrams_behavior)
+ }
+})(this, function(builder, behavior) {
+ return {
+ drawDiagramsFromParserInstance: function(
+ parserInstanceToDraw,
+ targetDiv
+ ) {
+ var topRules = parserInstanceToDraw.getSerializedGastProductions()
+ targetDiv.innerHTML = builder.buildSyntaxDiagramsText(topRules)
+ behavior.initDiagramsBehavior()
+ },
+
+ drawDiagramsFromSerializedGrammar: function(
+ serializedGrammar,
+ targetDiv
+ ) {
+ targetDiv.innerHTML = builder.buildSyntaxDiagramsText(
+ serializedGrammar
+ )
+ behavior.initDiagramsBehavior()
+ }
+ }
+})
diff --git a/node_modules/chevrotain/diagrams/vendor/railroad-diagrams.js b/node_modules/chevrotain/diagrams/vendor/railroad-diagrams.js
new file mode 100644
index 0000000..e979527
--- /dev/null
+++ b/node_modules/chevrotain/diagrams/vendor/railroad-diagrams.js
@@ -0,0 +1,1042 @@
+/*
+ Railroad Diagrams
+ by Tab Atkins Jr. (and others)
+ http://xanthir.com
+ http://twitter.com/tabatkins
+ http://github.com/tabatkins/railroad-diagrams
+
+ This document and all associated files in the github project are licensed under CC0: http://creativecommons.org/publicdomain/zero/1.0/
+ This means you can reuse, remix, or otherwise appropriate this project for your own use WITHOUT RESTRICTION.
+ (The actual legal meaning can be found at the above link.)
+ Don't ask me for permission to use any part of this project, JUST USE IT.
+ I would appreciate attribution, but that is not required by the license.
+ */
+
+/*
+ This file uses a module pattern to avoid leaking names into the global scope.
+ The only accidental leakage is the name "temp".
+ The exported names can be found at the bottom of this file;
+ simply change the names in the array of strings to change what they are called in your application.
+
+ As well, several configuration constants are passed into the module function at the bottom of this file.
+ At runtime, these constants can be found on the Diagram class.
+ */
+
+;(function(options) {
+ function subclassOf(baseClass, superClass) {
+ baseClass.prototype = Object.create(superClass.prototype)
+ baseClass.prototype.$super = superClass.prototype
+ }
+
+ function unnull(/* children */) {
+ return [].slice.call(arguments).reduce(function(sofar, x) {
+ return sofar !== undefined ? sofar : x
+ })
+ }
+
+ function determineGaps(outer, inner) {
+ var diff = outer - inner
+ switch (Diagram.INTERNAL_ALIGNMENT) {
+ case "left":
+ return [0, diff]
+ break
+ case "right":
+ return [diff, 0]
+ break
+ case "center":
+ default:
+ return [diff / 2, diff / 2]
+ break
+ }
+ }
+
+ function wrapString(value) {
+ return typeof value == "string" ? new Terminal(value) : value
+ }
+
+ function stackAtIllegalPosition(items) {
+ /* The height of the last line of the Stack is determined by the last child and
+ therefore any element outside the Stack could overlap with other elements.
+ If the Stack is the last element no overlap can occur. */
+ for (var i = 0; i < items.length; i++) {
+ if (items[i] instanceof Stack && i !== items.length - 1) {
+ return true
+ }
+ }
+ return false
+ }
+
+ function SVG(name, attrs, text) {
+ attrs = attrs || {}
+ text = text || ""
+ var el = document.createElementNS("http://www.w3.org/2000/svg", name)
+ for (var attr in attrs) {
+ if (attr === "xlink:href")
+ el.setAttributeNS(
+ "http://www.w3.org/1999/xlink",
+ "href",
+ attrs[attr]
+ )
+ else el.setAttribute(attr, attrs[attr])
+ }
+ el.textContent = text
+ return el
+ }
+
+ function FakeSVG(tagName, attrs, text) {
+ if (!(this instanceof FakeSVG)) return new FakeSVG(tagName, attrs, text)
+ if (text) this.children = text
+ else this.children = []
+ this.tagName = tagName
+ this.attrs = unnull(attrs, {})
+ return this
+ }
+ FakeSVG.prototype.format = function(x, y, width) {
+ // Virtual
+ }
+ FakeSVG.prototype.addTo = function(parent) {
+ if (parent instanceof FakeSVG) {
+ parent.children.push(this)
+ return this
+ } else {
+ var svg = this.toSVG()
+ parent.appendChild(svg)
+ return svg
+ }
+ }
+ FakeSVG.prototype.escapeString = function(string) {
+ // Escape markdown and HTML special characters
+ return string.replace(/[*_\`\[\]<&]/g, function(charString) {
+ return "" + charString.charCodeAt(0) + ";"
+ })
+ }
+ FakeSVG.prototype.toSVG = function() {
+ var el = SVG(this.tagName, this.attrs)
+ if (typeof this.children == "string") {
+ el.textContent = this.children
+ } else {
+ this.children.forEach(function(e) {
+ el.appendChild(e.toSVG())
+ })
+ }
+ return el
+ }
+ FakeSVG.prototype.toString = function() {
+ var str = "<" + this.tagName
+ var group = this.tagName == "g" || this.tagName == "svg"
+ for (var attr in this.attrs) {
+ str +=
+ " " +
+ attr +
+ '="' +
+ (this.attrs[attr] + "")
+ .replace(/&/g, "&")
+ .replace(/"/g, """) +
+ '"'
+ }
+ str += ">"
+ if (group) str += "\n"
+ if (typeof this.children == "string") {
+ str += FakeSVG.prototype.escapeString(this.children)
+ } else {
+ this.children.forEach(function(e) {
+ str += e
+ })
+ }
+ str += "" + this.tagName + ">\n"
+ return str
+ }
+
+ function Path(x, y) {
+ if (!(this instanceof Path)) return new Path(x, y)
+ FakeSVG.call(this, "path")
+ this.attrs.d = "M" + x + " " + y
+ }
+ subclassOf(Path, FakeSVG)
+ Path.prototype.m = function(x, y) {
+ this.attrs.d += "m" + x + " " + y
+ return this
+ }
+ Path.prototype.h = function(val) {
+ this.attrs.d += "h" + val
+ return this
+ }
+ Path.prototype.right = Path.prototype.h
+ Path.prototype.left = function(val) {
+ return this.h(-val)
+ }
+ Path.prototype.v = function(val) {
+ this.attrs.d += "v" + val
+ return this
+ }
+ Path.prototype.down = Path.prototype.v
+ Path.prototype.up = function(val) {
+ return this.v(-val)
+ }
+ Path.prototype.arc = function(sweep) {
+ var x = Diagram.ARC_RADIUS
+ var y = Diagram.ARC_RADIUS
+ if (sweep[0] == "e" || sweep[1] == "w") {
+ x *= -1
+ }
+ if (sweep[0] == "s" || sweep[1] == "n") {
+ y *= -1
+ }
+ if (sweep == "ne" || sweep == "es" || sweep == "sw" || sweep == "wn") {
+ var cw = 1
+ } else {
+ var cw = 0
+ }
+ this.attrs.d +=
+ "a" +
+ Diagram.ARC_RADIUS +
+ " " +
+ Diagram.ARC_RADIUS +
+ " 0 0 " +
+ cw +
+ " " +
+ x +
+ " " +
+ y
+ return this
+ }
+ Path.prototype.format = function() {
+ // All paths in this library start/end horizontally.
+ // The extra .5 ensures a minor overlap, so there's no seams in bad rasterizers.
+ this.attrs.d += "h.5"
+ return this
+ }
+
+ function Diagram(items) {
+ if (!(this instanceof Diagram))
+ return new Diagram([].slice.call(arguments))
+ FakeSVG.call(this, "svg", { class: Diagram.DIAGRAM_CLASS })
+ if (stackAtIllegalPosition(items)) {
+ throw new RangeError(
+ "Stack() must only occur at the very last position of Diagram()."
+ )
+ }
+ this.items = items.map(wrapString)
+ this.items.unshift(new Start())
+ this.items.push(new End())
+ this.width =
+ this.items.reduce(function(sofar, el) {
+ return sofar + el.width + (el.needsSpace ? 20 : 0)
+ }, 0) + 1
+ this.height = this.items.reduce(function(sofar, el) {
+ return sofar + el.height
+ }, 0)
+ this.up = Math.max.apply(
+ null,
+ this.items.map(function(x) {
+ return x.up
+ })
+ )
+ this.down = Math.max.apply(
+ null,
+ this.items.map(function(x) {
+ return x.down
+ })
+ )
+ this.formatted = false
+ }
+ subclassOf(Diagram, FakeSVG)
+ for (var option in options) {
+ Diagram[option] = options[option]
+ }
+ Diagram.prototype.format = function(
+ paddingt,
+ paddingr,
+ paddingb,
+ paddingl
+ ) {
+ paddingt = unnull(paddingt, 20)
+ paddingr = unnull(paddingr, paddingt, 20)
+ paddingb = unnull(paddingb, paddingt, 20)
+ paddingl = unnull(paddingl, paddingr, 20)
+ var x = paddingl
+ var y = paddingt
+ y += this.up
+ var g = FakeSVG(
+ "g",
+ Diagram.STROKE_ODD_PIXEL_LENGTH
+ ? { transform: "translate(.5 .5)" }
+ : {}
+ )
+ for (var i = 0; i < this.items.length; i++) {
+ var item = this.items[i]
+ if (item.needsSpace) {
+ Path(x, y)
+ .h(10)
+ .addTo(g)
+ x += 10
+ }
+ item.format(x, y, item.width + item.offsetX).addTo(g)
+ x += item.width + item.offsetX
+ y += item.height
+ if (item.needsSpace) {
+ Path(x, y)
+ .h(10)
+ .addTo(g)
+ x += 10
+ }
+ }
+ this.attrs.width = this.width + paddingl + paddingr
+ this.attrs.height =
+ this.up + this.height + this.down + paddingt + paddingb
+ this.attrs.viewBox = "0 0 " + this.attrs.width + " " + this.attrs.height
+ g.addTo(this)
+ this.formatted = true
+ return this
+ }
+ Diagram.prototype.addTo = function(parent) {
+ var scriptTag = document.getElementsByTagName("script")
+ scriptTag = scriptTag[scriptTag.length - 1]
+ var parentTag = scriptTag.parentNode
+ parent = parent || parentTag
+ return this.$super.addTo.call(this, parent)
+ }
+ Diagram.prototype.toSVG = function() {
+ if (!this.formatted) {
+ this.format()
+ }
+ return this.$super.toSVG.call(this)
+ }
+ Diagram.prototype.toString = function() {
+ if (!this.formatted) {
+ this.format()
+ }
+ return this.$super.toString.call(this)
+ }
+
+ function ComplexDiagram() {
+ var diagram = new Diagram([].slice.call(arguments))
+ var items = diagram.items
+ items.shift()
+ items.pop()
+ items.unshift(new Start(false))
+ items.push(new End(false))
+ diagram.items = items
+ return diagram
+ }
+
+ function Sequence(items) {
+ if (!(this instanceof Sequence))
+ return new Sequence([].slice.call(arguments))
+ FakeSVG.call(this, "g")
+ if (stackAtIllegalPosition(items)) {
+ throw new RangeError(
+ "Stack() must only occur at the very last position of Sequence()."
+ )
+ }
+ this.items = items.map(wrapString)
+ this.width = this.items.reduce(function(sofar, el) {
+ return sofar + el.width + (el.needsSpace ? 20 : 0)
+ }, 0)
+ this.offsetX = 0
+ this.height = this.items.reduce(function(sofar, el) {
+ return sofar + el.height
+ }, 0)
+ this.up = this.items.reduce(function(sofar, el) {
+ return Math.max(sofar, el.up)
+ }, 0)
+ this.down = this.items.reduce(function(sofar, el) {
+ return Math.max(sofar, el.down)
+ }, 0)
+ }
+ subclassOf(Sequence, FakeSVG)
+ Sequence.prototype.format = function(x, y, width) {
+ // Hook up the two sides if this is narrower than its stated width.
+ var gaps = determineGaps(width, this.width)
+ Path(x, y)
+ .h(gaps[0])
+ .addTo(this)
+ Path(x + gaps[0] + this.width, y + this.height)
+ .h(gaps[1])
+ .addTo(this)
+ x += gaps[0]
+
+ for (var i = 0; i < this.items.length; i++) {
+ var item = this.items[i]
+ if (item.needsSpace) {
+ Path(x, y)
+ .h(10)
+ .addTo(this)
+ x += 10
+ }
+ item.format(x, y, item.width).addTo(this)
+ x += item.width
+ y += item.height
+ if (item.needsSpace) {
+ Path(x, y)
+ .h(10)
+ .addTo(this)
+ x += 10
+ }
+ }
+ return this
+ }
+
+ function Stack(items) {
+ if (!(this instanceof Stack)) return new Stack([].slice.call(arguments))
+ FakeSVG.call(this, "g")
+ if (stackAtIllegalPosition(items)) {
+ throw new RangeError(
+ "Stack() must only occur at the very last position of Stack()."
+ )
+ }
+ if (items.length === 0) {
+ throw new RangeError("Stack() must have at least one child.")
+ }
+ this.items = items.map(wrapString)
+ this.width = this.items.reduce(function(sofar, el) {
+ return Math.max(sofar, el.width + (el.needsSpace ? 20 : 0))
+ }, 0)
+ if (this.items.length > 1) {
+ this.width += Diagram.ARC_RADIUS * 2
+ }
+
+ this.up = this.items[0].up
+ this.down = this.items[this.items.length - 1].down
+
+ this.height = 0
+ for (var i = 0; i < this.items.length; i++) {
+ this.height += this.items[i].height
+ if (i !== this.items.length - 1) {
+ this.height +=
+ Math.max(this.items[i].down, Diagram.VERTICAL_SEPARATION) +
+ Math.max(
+ this.items[i + 1].up,
+ Diagram.VERTICAL_SEPARATION
+ ) +
+ Diagram.ARC_RADIUS * 4
+ }
+ }
+
+ if (this.items.length === 0) {
+ this.offsetX = 0
+ } else {
+ // the value is usually negative because the linebreak resets the x value for the next element
+ this.offsetX = -(
+ this.width -
+ this.items[this.items.length - 1].width -
+ this.items[this.items.length - 1].offsetX -
+ (this.items[this.items.length - 1].needsSpace ? 20 : 0)
+ )
+ if (this.items.length > 1) {
+ this.offsetX += Diagram.ARC_RADIUS * 2
+ }
+ }
+ }
+ subclassOf(Stack, FakeSVG)
+ Stack.prototype.format = function(x, y, width) {
+ var xIntitial = x
+
+ for (var i = 0; i < this.items.length; i++) {
+ var item = this.items[i]
+ if (item.needsSpace) {
+ Path(x, y)
+ .h(10)
+ .addTo(this)
+ x += 10
+ }
+ item.format(
+ x,
+ y,
+ Math.max(item.width + item.offsetX, Diagram.ARC_RADIUS * 2)
+ ).addTo(this)
+ x += Math.max(item.width + item.offsetX, Diagram.ARC_RADIUS * 2)
+ y += item.height
+ if (item.needsSpace) {
+ Path(x, y)
+ .h(10)
+ .addTo(this)
+ x += 10
+ }
+
+ if (i !== this.items.length - 1) {
+ Path(x, y)
+ .arc("ne")
+ .down(Math.max(item.down, Diagram.VERTICAL_SEPARATION))
+ .arc("es")
+ .left(x - xIntitial - Diagram.ARC_RADIUS * 2)
+ .arc("nw")
+ .down(
+ Math.max(
+ this.items[i + 1].up,
+ Diagram.VERTICAL_SEPARATION
+ )
+ )
+ .arc("ws")
+ .addTo(this)
+
+ y +=
+ Math.max(item.down, Diagram.VERTICAL_SEPARATION) +
+ Math.max(
+ this.items[i + 1].up,
+ Diagram.VERTICAL_SEPARATION
+ ) +
+ Diagram.ARC_RADIUS * 4
+ x = xIntitial + Diagram.ARC_RADIUS * 2
+ }
+ }
+
+ Path(x, y)
+ .h(width - (this.width + this.offsetX))
+ .addTo(this)
+
+ return this
+ }
+
+ function Choice(normal, items) {
+ if (!(this instanceof Choice))
+ return new Choice(normal, [].slice.call(arguments, 1))
+ FakeSVG.call(this, "g")
+ if (typeof normal !== "number" || normal !== Math.floor(normal)) {
+ throw new TypeError(
+ "The first argument of Choice() must be an integer."
+ )
+ } else if (normal < 0 || normal >= items.length) {
+ throw new RangeError(
+ "The first argument of Choice() must be an index for one of the items."
+ )
+ } else {
+ this.normal = normal
+ }
+ this.items = items.map(wrapString)
+ this.width =
+ this.items.reduce(function(sofar, el) {
+ return Math.max(sofar, el.width)
+ }, 0) +
+ Diagram.ARC_RADIUS * 4
+ this.offsetX = 0
+ this.height = this.items[normal].height
+ this.up = this.down = 0
+ for (var i = 0; i < this.items.length; i++) {
+ var item = this.items[i]
+ if (i < normal) {
+ this.up += Math.max(
+ Diagram.ARC_RADIUS,
+ item.up +
+ item.height +
+ item.down +
+ Diagram.VERTICAL_SEPARATION
+ )
+ }
+ if (i == normal) {
+ this.up += Math.max(Diagram.ARC_RADIUS, item.up)
+ this.down += Math.max(Diagram.ARC_RADIUS, item.down)
+ }
+ if (i > normal) {
+ this.down += Math.max(
+ Diagram.ARC_RADIUS,
+ Diagram.VERTICAL_SEPARATION +
+ item.up +
+ item.down +
+ item.height
+ )
+ }
+ }
+ }
+ subclassOf(Choice, FakeSVG)
+ Choice.prototype.format = function(x, y, width) {
+ // Hook up the two sides if this is narrower than its stated width.
+ var gaps = determineGaps(width, this.width)
+ Path(x, y)
+ .h(gaps[0])
+ .addTo(this)
+ Path(x + gaps[0] + this.width, y + this.height)
+ .h(gaps[1])
+ .addTo(this)
+ x += gaps[0]
+
+ var last = this.items.length - 1
+ var innerWidth = this.width - Diagram.ARC_RADIUS * 4
+
+ // Do the elements that curve above
+ for (var i = this.normal - 1; i >= 0; i--) {
+ var item = this.items[i]
+ if (i == this.normal - 1) {
+ var distanceFromY = Math.max(
+ Diagram.ARC_RADIUS * 2,
+ this.items[i + 1].up +
+ Diagram.VERTICAL_SEPARATION +
+ item.height +
+ item.down
+ )
+ }
+ Path(x, y)
+ .arc("se")
+ .up(distanceFromY - Diagram.ARC_RADIUS * 2)
+ .arc("wn")
+ .addTo(this)
+ item.format(
+ x + Diagram.ARC_RADIUS * 2,
+ y - distanceFromY,
+ innerWidth
+ ).addTo(this)
+ Path(
+ x + Diagram.ARC_RADIUS * 2 + innerWidth,
+ y - distanceFromY + item.height
+ )
+ .arc("ne")
+ .down(
+ distanceFromY -
+ item.height +
+ this.items[this.normal].height -
+ Diagram.ARC_RADIUS * 2
+ )
+ .arc("ws")
+ .addTo(this)
+ distanceFromY += Math.max(
+ Diagram.ARC_RADIUS,
+ item.up +
+ Diagram.VERTICAL_SEPARATION +
+ (i == 0
+ ? 0
+ : this.items[i - 1].down + this.items[i - 1].height)
+ )
+ }
+
+ // Do the straight-line path.
+ Path(x, y)
+ .right(Diagram.ARC_RADIUS * 2)
+ .addTo(this)
+ this.items[this.normal]
+ .format(x + Diagram.ARC_RADIUS * 2, y, innerWidth)
+ .addTo(this)
+ Path(x + Diagram.ARC_RADIUS * 2 + innerWidth, y + this.height)
+ .right(Diagram.ARC_RADIUS * 2)
+ .addTo(this)
+
+ // Do the elements that curve below
+ for (var i = this.normal + 1; i <= last; i++) {
+ var item = this.items[i]
+ if (i == this.normal + 1) {
+ var distanceFromY = Math.max(
+ Diagram.ARC_RADIUS * 2,
+ this.items[i - 1].height +
+ this.items[i - 1].down +
+ Diagram.VERTICAL_SEPARATION +
+ item.up
+ )
+ }
+ Path(x, y)
+ .arc("ne")
+ .down(distanceFromY - Diagram.ARC_RADIUS * 2)
+ .arc("ws")
+ .addTo(this)
+ item.format(
+ x + Diagram.ARC_RADIUS * 2,
+ y + distanceFromY,
+ innerWidth
+ ).addTo(this)
+ Path(
+ x + Diagram.ARC_RADIUS * 2 + innerWidth,
+ y + distanceFromY + item.height
+ )
+ .arc("se")
+ .up(
+ distanceFromY -
+ Diagram.ARC_RADIUS * 2 +
+ item.height -
+ this.items[this.normal].height
+ )
+ .arc("wn")
+ .addTo(this)
+ distanceFromY += Math.max(
+ Diagram.ARC_RADIUS,
+ item.height +
+ item.down +
+ Diagram.VERTICAL_SEPARATION +
+ (i == last ? 0 : this.items[i + 1].up)
+ )
+ }
+
+ return this
+ }
+
+ function Optional(item, skip) {
+ if (skip === undefined) return Choice(1, Skip(), item)
+ else if (skip === "skip") return Choice(0, Skip(), item)
+ else throw "Unknown value for Optional()'s 'skip' argument."
+ }
+
+ function OneOrMore(item, rep) {
+ if (!(this instanceof OneOrMore)) return new OneOrMore(item, rep)
+ FakeSVG.call(this, "g")
+ rep = rep || new Skip()
+ this.item = wrapString(item)
+ this.rep = wrapString(rep)
+ this.width =
+ Math.max(this.item.width, this.rep.width) + Diagram.ARC_RADIUS * 2
+ this.offsetX = 0
+ this.height = this.item.height
+ this.up = this.item.up
+ this.down = Math.max(
+ Diagram.ARC_RADIUS * 2,
+ this.item.down +
+ Diagram.VERTICAL_SEPARATION +
+ this.rep.up +
+ this.rep.height +
+ this.rep.down
+ )
+ }
+ subclassOf(OneOrMore, FakeSVG)
+ OneOrMore.prototype.needsSpace = true
+ OneOrMore.prototype.format = function(x, y, width) {
+ // Hook up the two sides if this is narrower than its stated width.
+ var gaps = determineGaps(width, this.width)
+ Path(x, y)
+ .h(gaps[0])
+ .addTo(this)
+ Path(x + gaps[0] + this.width, y + this.height)
+ .h(gaps[1])
+ .addTo(this)
+ x += gaps[0]
+
+ // Draw item
+ Path(x, y)
+ .right(Diagram.ARC_RADIUS)
+ .addTo(this)
+ this.item
+ .format(
+ x + Diagram.ARC_RADIUS,
+ y,
+ this.width - Diagram.ARC_RADIUS * 2
+ )
+ .addTo(this)
+ Path(x + this.width - Diagram.ARC_RADIUS, y + this.height)
+ .right(Diagram.ARC_RADIUS)
+ .addTo(this)
+
+ // Draw repeat arc
+ var distanceFromY = Math.max(
+ Diagram.ARC_RADIUS * 2,
+ this.item.height +
+ this.item.down +
+ Diagram.VERTICAL_SEPARATION +
+ this.rep.up
+ )
+ Path(x + Diagram.ARC_RADIUS, y)
+ .arc("nw")
+ .down(distanceFromY - Diagram.ARC_RADIUS * 2)
+ .arc("ws")
+ .addTo(this)
+ this.rep
+ .format(
+ x + Diagram.ARC_RADIUS,
+ y + distanceFromY,
+ this.width - Diagram.ARC_RADIUS * 2
+ )
+ .addTo(this)
+ Path(
+ x + this.width - Diagram.ARC_RADIUS,
+ y + distanceFromY + this.rep.height
+ )
+ .arc("se")
+ .up(
+ distanceFromY -
+ Diagram.ARC_RADIUS * 2 +
+ this.rep.height -
+ this.item.height
+ )
+ .arc("en")
+ .addTo(this)
+
+ return this
+ }
+
+ function ZeroOrMore(item, rep, skip) {
+ return Optional(OneOrMore(item, rep), skip)
+ }
+
+ function Start(simpleType) {
+ if (!(this instanceof Start)) return new Start()
+ FakeSVG.call(this, "path")
+ this.width = 20
+ this.height = 0
+ this.offsetX = 0
+ this.up = 10
+ this.down = 10
+ this.simpleType = simpleType
+ }
+ subclassOf(Start, FakeSVG)
+ Start.prototype.format = function(x, y) {
+ if (this.simpleType === false) {
+ this.attrs.d = "M " + x + " " + (y - 10) + " v 20 m 0 -10 h 20.5"
+ } else {
+ this.attrs.d =
+ "M " +
+ x +
+ " " +
+ (y - 10) +
+ " v 20 m 10 -20 v 20 m -10 -10 h 20.5"
+ }
+ return this
+ }
+
+ function End(simpleType) {
+ if (!(this instanceof End)) return new End()
+ FakeSVG.call(this, "path")
+ this.width = 20
+ this.height = 0
+ this.offsetX = 0
+ this.up = 10
+ this.down = 10
+ this.simpleType = simpleType
+ }
+ subclassOf(End, FakeSVG)
+ End.prototype.format = function(x, y) {
+ if (this.simpleType === false) {
+ this.attrs.d = "M " + x + " " + y + " h 20 m 0 -10 v 20"
+ } else {
+ this.attrs.d =
+ "M " + x + " " + y + " h 20 m -10 -10 v 20 m 10 -20 v 20"
+ }
+ return this
+ }
+
+ function Terminal(
+ text,
+ href,
+ title,
+ occurrenceIdx,
+ topRuleName,
+ dslRuleName,
+ tokenName
+ ) {
+ if (!(this instanceof Terminal))
+ return new Terminal(
+ text,
+ href,
+ title,
+ occurrenceIdx,
+ topRuleName,
+ dslRuleName,
+ tokenName
+ )
+ FakeSVG.call(this, "g", { class: "terminal" })
+ this.text = text
+ this.label = text
+ this.href = href
+ this.title = title
+ this.occurrenceIdx = occurrenceIdx
+ this.topRuleName = topRuleName
+ this.dslRuleName = dslRuleName
+ this.tokenName = tokenName
+ this.width =
+ text.length * 8 +
+ 20 /* Assume that each char is .5em, and that the em is 16px */
+ this.height = 0
+ this.offsetX = 0
+ this.up = 11
+ this.down = 11
+ }
+ subclassOf(Terminal, FakeSVG)
+ Terminal.prototype.needsSpace = true
+ Terminal.prototype.format = function(x, y, width) {
+ // Hook up the two sides if this is narrower than its stated width.
+ var gaps = determineGaps(width, this.width)
+ Path(x, y)
+ .h(gaps[0])
+ .addTo(this)
+ Path(x + gaps[0] + this.width, y)
+ .h(gaps[1])
+ .addTo(this)
+ x += gaps[0]
+
+ FakeSVG("rect", {
+ x: x,
+ y: y - 11,
+ width: this.width,
+ height: this.up + this.down,
+ rx: 10,
+ ry: 10
+ }).addTo(this)
+
+ var text = FakeSVG(
+ "text",
+ {
+ x: x + this.width / 2,
+ y: y + 4,
+ occurrenceIdx: this.occurrenceIdx,
+ topRuleName: this.topRuleName,
+ dslRuleName: this.dslRuleName,
+ tokenName: this.tokenName,
+ label: this.label
+ },
+ this.text
+ )
+ var title = FakeSVG("title", {}, this.title)
+ if (this.href)
+ FakeSVG("a", { "xlink:href": this.href }, [text]).addTo(this)
+ else {
+ text.addTo(this)
+ if (this.title !== undefined) {
+ title.addTo(this)
+ }
+ }
+ return this
+ }
+
+ function NonTerminal(text, href, occurrenceIdx, topRuleName) {
+ if (!(this instanceof NonTerminal))
+ return new NonTerminal(text, href, occurrenceIdx, topRuleName)
+ FakeSVG.call(this, "g", { class: "non-terminal" })
+ this.text = text
+ this.ruleName = text
+ this.href = href
+ this.occurrenceIdx = occurrenceIdx
+ this.topRuleName = topRuleName
+ this.width = text.length * 8 + 20
+ this.height = 0
+ this.offsetX = 0
+ this.up = 11
+ this.down = 11
+ }
+ subclassOf(NonTerminal, FakeSVG)
+ NonTerminal.prototype.needsSpace = true
+ NonTerminal.prototype.format = function(x, y, width) {
+ // Hook up the two sides if this is narrower than its stated width.
+ var gaps = determineGaps(width, this.width)
+ Path(x, y)
+ .h(gaps[0])
+ .addTo(this)
+ Path(x + gaps[0] + this.width, y)
+ .h(gaps[1])
+ .addTo(this)
+ x += gaps[0]
+
+ FakeSVG("rect", {
+ x: x,
+ y: y - 11,
+ width: this.width,
+ height: this.up + this.down
+ }).addTo(this)
+ var text = FakeSVG(
+ "text",
+ {
+ x: x + this.width / 2,
+ y: y + 4,
+ occurrenceIdx: this.occurrenceIdx,
+ topRuleName: this.topRuleName,
+ ruleName: this.ruleName
+ },
+ this.text
+ )
+ if (this.href)
+ FakeSVG("a", { "xlink:href": this.href }, [text]).addTo(this)
+ else text.addTo(this)
+ return this
+ }
+
+ function Comment(text) {
+ if (!(this instanceof Comment)) return new Comment(text)
+ FakeSVG.call(this, "g")
+ this.text = text
+ this.width = text.length * 7 + 10
+ this.height = 0
+ this.offsetX = 0
+ this.up = 11
+ this.down = 11
+ }
+ subclassOf(Comment, FakeSVG)
+ Comment.prototype.needsSpace = true
+ Comment.prototype.format = function(x, y, width) {
+ // Hook up the two sides if this is narrower than its stated width.
+ var gaps = determineGaps(width, this.width)
+ Path(x, y)
+ .h(gaps[0])
+ .addTo(this)
+ Path(x + gaps[0] + this.width, y + this.height)
+ .h(gaps[1])
+ .addTo(this)
+ x += gaps[0]
+
+ FakeSVG(
+ "text",
+ {
+ x: x + this.width / 2,
+ y: y + 5,
+ class: "comment"
+ },
+ this.text
+ ).addTo(this)
+ return this
+ }
+
+ function Skip() {
+ if (!(this instanceof Skip)) return new Skip()
+ FakeSVG.call(this, "g")
+ this.width = 0
+ this.height = 0
+ this.offsetX = 0
+ this.up = 0
+ this.down = 0
+ }
+ subclassOf(Skip, FakeSVG)
+ Skip.prototype.format = function(x, y, width) {
+ Path(x, y)
+ .right(width)
+ .addTo(this)
+ return this
+ }
+
+ var root
+ if (typeof define === "function" && define.amd) {
+ // AMD. Register as an anonymous module.
+ root = {}
+ define([], function() {
+ return root
+ })
+ } else if (typeof exports === "object") {
+ // CommonJS for node
+ root = exports
+ } else {
+ // Browser globals (root is window.railroad)
+ this.railroad = {}
+ root = this.railroad
+ }
+
+ var temp = [
+ Diagram,
+ ComplexDiagram,
+ Sequence,
+ Stack,
+ Choice,
+ Optional,
+ OneOrMore,
+ ZeroOrMore,
+ Terminal,
+ NonTerminal,
+ Comment,
+ Skip
+ ]
+ /*
+ These are the names that the internal classes are exported as.
+ If you would like different names, adjust them here.
+ */
+ ;[
+ "Diagram",
+ "ComplexDiagram",
+ "Sequence",
+ "Stack",
+ "Choice",
+ "Optional",
+ "OneOrMore",
+ "ZeroOrMore",
+ "Terminal",
+ "NonTerminal",
+ "Comment",
+ "Skip"
+ ].forEach(function(e, i) {
+ root[e] = temp[i]
+ })
+}.call(this, {
+ VERTICAL_SEPARATION: 8,
+ ARC_RADIUS: 10,
+ DIAGRAM_CLASS: "railroad-diagram",
+ STROKE_ODD_PIXEL_LENGTH: true,
+ INTERNAL_ALIGNMENT: "center"
+}))
diff --git a/node_modules/chevrotain/lib/chevrotain.d.ts b/node_modules/chevrotain/lib/chevrotain.d.ts
new file mode 100644
index 0000000..f41e5fa
--- /dev/null
+++ b/node_modules/chevrotain/lib/chevrotain.d.ts
@@ -0,0 +1,2961 @@
+export as namespace chevrotain
+
+export declare const VERSION: string
+
+/**
+ * This class does not actually exists nor is exposed at runtime.
+ * This is just a helper to avoid duplications in the Type Definitions
+ * Of `CstParser` and `EmbeddedActionsParser`
+ */
+declare abstract class BaseParser {
+ /**
+ * This must be called at the end of a Parser constructor.
+ * See: http://sap.github.io/chevrotain/docs/tutorial/step2_parsing.html#under-the-hood
+ */
+ protected performSelfAnalysis(): void
+
+ /**
+ * It is recommended to reuse the same Parser instance
+ * by passing an empty array to the input argument
+ * and only later setting the input by using the input property.
+ * See: http://sap.github.io/chevrotain/docs/FAQ.html#major-performance-benefits
+ *
+ * @param tokenVocabulary - A data structure containing all the Tokens used by the Parser.
+ * @param config - The Parser's configuration.
+ */
+ constructor(tokenVocabulary: TokenVocabulary, config?: IParserConfig)
+
+ errors: IRecognitionException[]
+
+ /**
+ * Flag indicating the Parser is at the recording phase.
+ * Can be used to implement methods similar to {@link BaseParser.ACTION}
+ * Or any other logic to requires knowledge of the recording phase.
+ * See:
+ * - https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording
+ * to learn more on the recording phase and how Chevrotain works.
+ */
+ RECORDING_PHASE: boolean
+
+ /**
+ * Resets the parser state, should be overridden for custom parsers which "carry" additional state.
+ * When overriding, remember to also invoke the super implementation!
+ */
+ reset(): void
+
+ getBaseCstVisitorConstructor(): {
+ new (...args: any[]): ICstVisitor
+ }
+
+ getBaseCstVisitorConstructorWithDefaults(): {
+ new (...args: any[]): ICstVisitor
+ }
+
+ getGAstProductions(): Record
+
+ getSerializedGastProductions(): ISerializedGast[]
+
+ /**
+ * @param startRuleName
+ * @param precedingInput - The token vector up to (not including) the content assist point
+ */
+ computeContentAssist(
+ startRuleName: string,
+ precedingInput: IToken[]
+ ): ISyntacticContentAssistPath[]
+
+ /**
+ * @param grammarRule - The rule to try and parse in backtracking mode.
+ * @param args - argumens to be passed to the grammar rule execution
+ *
+ * @return a lookahead function that will try to parse the given grammarRule and will return true if succeed.
+ */
+ protected BACKTRACK(
+ grammarRule: (...args: any[]) => T,
+ args?: any[]
+ ): () => boolean
+
+ /**
+ * The Semantic Actions wrapper.
+ * Should be used to wrap semantic actions that either:
+ * - May fail when executing in "recording phase".
+ * - Have global side effects that should be avoided during "recording phase".
+ *
+ * For more information see:
+ * - https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording
+ */
+ protected ACTION(impl: () => T): T
+
+ /**
+ * Like `CONSUME` with the numerical suffix as a parameter, e.g:
+ * consume(0, X) === CONSUME(X)
+ * consume(1, X) === CONSUME1(X)
+ * consume(2, X) === CONSUME2(X)
+ * ...
+ * @see CONSUME
+ */
+ protected consume(
+ idx: number,
+ tokType: TokenType,
+ options?: ConsumeMethodOpts
+ ): IToken
+
+ /**
+ * Like `OPTION` with the numerical suffix as a parameter, e.g:
+ * option(0, X) === OPTION(X)
+ * option(1, X) === OPTION1(X)
+ * option(2, X) === OPTION2(X)
+ * ...
+ * @see SUBRULE
+ */
+ protected option(
+ idx: number,
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): OUT
+
+ /**
+ * Like `OR` with the numerical suffix as a parameter, e.g:
+ * or(0, X) === OR(X)
+ * or(1, X) === OR1(X)
+ * or(2, X) === OR2(X)
+ * ...
+ * @see OR
+ */
+ protected or(idx: number, altsOrOpts: IOrAlt[] | OrMethodOpts): any
+
+ /**
+ * Like `MANY` with the numerical suffix as a parameter, e.g:
+ * many(0, X) === MANY(X)
+ * many(1, X) === MANY1(X)
+ * many(2, X) === MANY2(X)
+ * ...
+ * @see MANY
+ */
+ protected many(
+ idx: number,
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): void
+
+ /**
+ * Like `AT_LEAST_ONE` with the numerical suffix as a parameter, e.g:
+ * atLeastOne(0, X) === AT_LEAST_ONE(X)
+ * atLeastOne(1, X) === AT_LEAST_ONE1(X)
+ * atLeastOne(2, X) === AT_LEAST_ONE2(X)
+ * ...
+ * @see AT_LEAST_ONE
+ */
+ protected atLeastOne(
+ idx: number,
+ actionORMethodDef: GrammarAction | DSLMethodOptsWithErr
+ ): void
+
+ /**
+ *
+ * A Parsing DSL method use to consume a single Token.
+ * In EBNF terms this is equivalent to a Terminal.
+ *
+ * A Token will be consumed, IFF the next token in the token vector matches .
+ * otherwise the parser may attempt to perform error recovery (if enabled).
+ *
+ * The index in the method name indicates the unique occurrence of a terminal consumption
+ * inside a the top level rule. What this means is that if a terminal appears
+ * more than once in a single rule, each appearance must have a **different** index.
+ *
+ * For example:
+ * ```
+ * this.RULE("qualifiedName", () => {
+ * this.CONSUME1(Identifier);
+ * this.MANY(() => {
+ * this.CONSUME1(Dot);
+ * // here we use CONSUME2 because the terminal
+ * // 'Identifier' has already appeared previously in the
+ * // the rule 'parseQualifiedName'
+ * this.CONSUME2(Identifier);
+ * });
+ * })
+ * ```
+ *
+ * - See more details on the [unique suffixes requirement](http://sap.github.io/chevrotain/docs/FAQ.html#NUMERICAL_SUFFIXES).
+ *
+ * @param tokType - The Type of the token to be consumed.
+ * @param options - optional properties to modify the behavior of CONSUME.
+ */
+ protected CONSUME(
+ tokType: TokenType,
+ options?: ConsumeMethodOpts
+ ): IToken
+
+ /**
+ * @see CONSUME
+ * @hidden
+ */
+ protected CONSUME1(
+ tokType: TokenType,
+ options?: ConsumeMethodOpts
+ ): IToken
+
+ /**
+ * @see CONSUME
+ * @hidden
+ */
+ protected CONSUME2(
+ tokType: TokenType,
+ options?: ConsumeMethodOpts
+ ): IToken
+
+ /**
+ * @see CONSUME
+ * @hidden
+ */
+ protected CONSUME3(
+ tokType: TokenType,
+ options?: ConsumeMethodOpts
+ ): IToken
+
+ /**
+ * @see CONSUME
+ * @hidden
+ */
+ protected CONSUME4(
+ tokType: TokenType,
+ options?: ConsumeMethodOpts
+ ): IToken
+
+ /**
+ * @see CONSUME
+ * @hidden
+ */
+ protected CONSUME5(
+ tokType: TokenType,
+ options?: ConsumeMethodOpts
+ ): IToken
+
+ /**
+ * @see CONSUME
+ * @hidden
+ */
+ protected CONSUME6(
+ tokType: TokenType,
+ options?: ConsumeMethodOpts
+ ): IToken
+
+ /**
+ * @see CONSUME
+ * @hidden
+ */
+ protected CONSUME7(
+ tokType: TokenType,
+ options?: ConsumeMethodOpts
+ ): IToken
+
+ /**
+ * @see CONSUME
+ * @hidden
+ */
+ protected CONSUME8(
+ tokType: TokenType,
+ options?: ConsumeMethodOpts
+ ): IToken
+
+ /**
+ * @see CONSUME
+ * @hidden
+ */
+ protected CONSUME9(
+ tokType: TokenType,
+ options?: ConsumeMethodOpts
+ ): IToken
+
+ /**
+ * Parsing DSL Method that Indicates an Optional production.
+ * in EBNF notation this is equivalent to: "[...]".
+ *
+ * Note that there are two syntax forms:
+ * - Passing the grammar action directly:
+ * ```
+ * this.OPTION(() => {
+ * this.CONSUME(Digit)}
+ * );
+ * ```
+ *
+ * - using an "options" object:
+ * ```
+ * this.OPTION({
+ * GATE:predicateFunc,
+ * DEF: () => {
+ * this.CONSUME(Digit)
+ * }});
+ * ```
+ *
+ * The optional 'GATE' property in "options" object form can be used to add constraints
+ * to invoking the grammar action.
+ *
+ * As in CONSUME the index in the method name indicates the occurrence
+ * of the optional production in it's top rule.
+ *
+ * @param actionORMethodDef - The grammar action to optionally invoke once
+ * or an "OPTIONS" object describing the grammar action and optional properties.
+ */
+ // TODO: return `OUT | undefined` explicitly
+ protected OPTION(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): OUT
+
+ /**
+ * @see OPTION
+ * @hidden
+ */
+ protected OPTION1(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): OUT
+
+ /**
+ * @see OPTION
+ * @hidden
+ */
+ protected OPTION2(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): OUT
+
+ /**
+ * @see OPTION
+ * @hidden
+ */
+ protected OPTION3(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): OUT
+
+ /**
+ * @see OPTION
+ * @hidden
+ */
+ protected OPTION4(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): OUT
+
+ /**
+ * @see OPTION
+ * @hidden
+ */
+ protected OPTION5(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): OUT
+
+ /**
+ * @see OPTION
+ * @hidden
+ */
+ protected OPTION6(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): OUT
+
+ /**
+ * @see OPTION
+ * @hidden
+ */
+ protected OPTION7(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): OUT
+
+ /**
+ * @see OPTION
+ * @hidden
+ */
+ protected OPTION8(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): OUT
+
+ /**
+ * @see OPTION
+ * @hidden
+ */
+ protected OPTION9(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): OUT
+
+ /**
+ * Parsing DSL method that indicates a choice between a set of alternatives must be made.
+ * This is equivalent to an EBNF alternation (A | B | C | D ...), except
+ * that the alternatives are ordered like in a PEG grammar.
+ * This means that the **first** matching alternative is always chosen.
+ *
+ * There are several forms for the inner alternatives array:
+ *
+ * - Passing alternatives array directly:
+ * ```
+ * this.OR([
+ * { ALT:() => { this.CONSUME(One) }},
+ * { ALT:() => { this.CONSUME(Two) }},
+ * { ALT:() => { this.CONSUME(Three) }}
+ * ])
+ * ```
+ *
+ * - Passing alternative array directly with predicates (GATE):
+ * ```
+ * this.OR([
+ * { GATE: predicateFunc1, ALT:() => { this.CONSUME(One) }},
+ * { GATE: predicateFuncX, ALT:() => { this.CONSUME(Two) }},
+ * { GATE: predicateFuncX, ALT:() => { this.CONSUME(Three) }}
+ * ])
+ * ```
+ *
+ * - These syntax forms can also be mixed:
+ * ```
+ * this.OR([
+ * {
+ * GATE: predicateFunc1,
+ * ALT:() => { this.CONSUME(One) }
+ * },
+ * { ALT:() => { this.CONSUME(Two) }},
+ * { ALT:() => { this.CONSUME(Three) }}
+ * ])
+ * ```
+ *
+ * - Additionally an "options" object may be used:
+ * ```
+ * this.OR({
+ * DEF:[
+ * { ALT:() => { this.CONSUME(One) }},
+ * { ALT:() => { this.CONSUME(Two) }},
+ * { ALT:() => { this.CONSUME(Three) }}
+ * ],
+ * // OPTIONAL property
+ * ERR_MSG: "A Number"
+ * })
+ * ```
+ *
+ * The 'predicateFuncX' in the long form can be used to add constraints to choosing the alternative.
+ *
+ * As in CONSUME the index in the method name indicates the occurrence
+ * of the alternation production in it's top rule.
+ *
+ * @param altsOrOpts - A set of alternatives or an "OPTIONS" object describing the alternatives and optional properties.
+ *
+ * @returns The result of invoking the chosen alternative.
+ */
+ protected OR(altsOrOpts: IOrAlt[] | OrMethodOpts): any
+
+ /**
+ * @see OR
+ * @hidden
+ */
+ protected OR1(altsOrOpts: IOrAlt[] | OrMethodOpts): any
+
+ /**
+ * @see OR
+ * @hidden
+ */
+ protected OR2(altsOrOpts: IOrAlt[] | OrMethodOpts): any
+
+ /**
+ * @see OR
+ * @hidden
+ */
+ protected OR3(altsOrOpts: IOrAlt[] | OrMethodOpts): any
+
+ /**
+ * @see OR
+ * @hidden
+ */
+ protected OR4(altsOrOpts: IOrAlt[] | OrMethodOpts): any
+
+ /**
+ * @see OR
+ * @hidden
+ */
+ protected OR5(altsOrOpts: IOrAlt[] | OrMethodOpts): any
+
+ /**
+ * @see OR
+ * @hidden
+ */
+ protected OR6(altsOrOpts: IOrAlt[] | OrMethodOpts): any
+
+ /**
+ * @see OR
+ * @hidden
+ */
+ protected OR7(altsOrOpts: IOrAlt[] | OrMethodOpts): any
+
+ /**
+ * @see OR
+ * @hidden
+ */
+ protected OR8(altsOrOpts: IOrAlt[] | OrMethodOpts): any
+
+ /**
+ * @see OR
+ * @hidden
+ */
+ protected OR9(altsOrOpts: IOrAlt[] | OrMethodOpts): any
+
+ /**
+ * Parsing DSL method, that indicates a repetition of zero or more.
+ * This is equivalent to EBNF repetition {...}.
+ *
+ * Note that there are two syntax forms:
+ * - Passing the grammar action directly:
+ * ```
+ * this.MANY(() => {
+ * this.CONSUME(Comma)
+ * this.CONSUME(Digit)
+ * })
+ * ```
+ *
+ * - using an "options" object:
+ * ```
+ * this.MANY({
+ * GATE: predicateFunc,
+ * DEF: () => {
+ * this.CONSUME(Comma)
+ * this.CONSUME(Digit)
+ * }
+ * });
+ * ```
+ *
+ * The optional 'GATE' property in "options" object form can be used to add constraints
+ * to invoking the grammar action.
+ *
+ * As in CONSUME the index in the method name indicates the occurrence
+ * of the repetition production in it's top rule.
+ *
+ * @param actionORMethodDef - The grammar action to optionally invoke multiple times
+ * or an "OPTIONS" object describing the grammar action and optional properties.
+ *
+ */
+ protected MANY(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): void
+
+ /**
+ * @see MANY
+ * @hidden
+ */
+ protected MANY1(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): void
+
+ /**
+ * @see MANY
+ * @hidden
+ */
+ protected MANY2(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): void
+
+ /**
+ * @see MANY
+ * @hidden
+ */
+ protected MANY3(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): void
+
+ /**
+ * @see MANY
+ * @hidden
+ */
+ protected MANY4(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): void
+
+ /**
+ * @see MANY
+ * @hidden
+ */
+ protected MANY5(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): void
+
+ /**
+ * @see MANY
+ * @hidden
+ */
+ protected MANY6(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): void
+
+ /**
+ * @see MANY
+ * @hidden
+ */
+ protected MANY7(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): void
+
+ /**
+ * @see MANY
+ * @hidden
+ */
+ protected MANY8(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): void
+
+ /**
+ * @see MANY
+ * @hidden
+ */
+ protected MANY9(
+ actionORMethodDef: GrammarAction | DSLMethodOpts
+ ): void
+
+ /**
+ * Parsing DSL method, that indicates a repetition of zero or more with a separator
+ * Token between the repetitions.
+ *
+ * Example:
+ *
+ * ```
+ * this.MANY_SEP({
+ * SEP:Comma,
+ * DEF: () => {
+ * this.CONSUME(Number};
+ * // ...
+ * })
+ * ```
+ *
+ * Note that because this DSL method always requires more than one argument the options object is always required
+ * and it is not possible to use a shorter form like in the MANY DSL method.
+ *
+ * Note that for the purposes of deciding on whether or not another iteration exists
+ * Only a single Token is examined (The separator). Therefore if the grammar being implemented is
+ * so "crazy" to require multiple tokens to identify an item separator please use the more basic DSL methods
+ * to implement it.
+ *
+ * As in CONSUME the index in the method name indicates the occurrence
+ * of the repetition production in it's top rule.
+ *
+ * @param options - An object defining the grammar of each iteration and the separator between iterations
+ *
+ */
+ protected MANY_SEP(options: ManySepMethodOpts): void
+
+ /**
+ * @see MANY_SEP
+ * @hidden
+ */
+ protected MANY_SEP1(options: ManySepMethodOpts): void
+
+ /**
+ * @see MANY_SEP
+ * @hidden
+ */
+ protected MANY_SEP2(options: ManySepMethodOpts): void
+
+ /**
+ * @see MANY_SEP
+ * @hidden
+ */
+ protected MANY_SEP3(options: ManySepMethodOpts): void
+
+ /**
+ * @see MANY_SEP
+ * @hidden
+ */
+ protected MANY_SEP4(options: ManySepMethodOpts): void
+
+ /**
+ * @see MANY_SEP
+ * @hidden
+ */
+ protected MANY_SEP5(options: ManySepMethodOpts): void
+
+ /**
+ * @see MANY_SEP
+ * @hidden
+ */
+ protected MANY_SEP6(options: ManySepMethodOpts): void
+
+ /**
+ * @see MANY_SEP
+ * @hidden
+ */
+ protected MANY_SEP7(options: ManySepMethodOpts): void
+
+ /**
+ * @see MANY_SEP
+ * @hidden
+ */
+ protected MANY_SEP8(options: ManySepMethodOpts): void
+
+ /**
+ * @see MANY_SEP
+ * @hidden
+ */
+ protected MANY_SEP9(options: ManySepMethodOpts): void
+
+ /**
+ * Convenience method, same as MANY but the repetition is of one or more.
+ * failing to match at least one repetition will result in a parsing error and
+ * cause a parsing error.
+ *
+ * @see MANY
+ *
+ * @param actionORMethodDef - The grammar action to optionally invoke multiple times
+ * or an "OPTIONS" object describing the grammar action and optional properties.
+ *
+ */
+ protected AT_LEAST_ONE(
+ actionORMethodDef: GrammarAction | DSLMethodOptsWithErr
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE
+ * @hidden
+ */
+ protected AT_LEAST_ONE1(
+ actionORMethodDef: GrammarAction | DSLMethodOptsWithErr
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE
+ * @hidden
+ */
+ protected AT_LEAST_ONE2(
+ actionORMethodDef: GrammarAction | DSLMethodOptsWithErr
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE
+ * @hidden
+ */
+ protected AT_LEAST_ONE3(
+ actionORMethodDef: GrammarAction | DSLMethodOptsWithErr
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE
+ * @hidden
+ */
+ protected AT_LEAST_ONE4(
+ actionORMethodDef: GrammarAction | DSLMethodOptsWithErr
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE
+ * @hidden
+ */
+ protected AT_LEAST_ONE5(
+ actionORMethodDef: GrammarAction | DSLMethodOptsWithErr
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE
+ * @hidden
+ */
+ protected AT_LEAST_ONE6(
+ actionORMethodDef: GrammarAction | DSLMethodOptsWithErr
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE
+ * @hidden
+ */
+ protected AT_LEAST_ONE7(
+ actionORMethodDef: GrammarAction | DSLMethodOptsWithErr
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE
+ * @hidden
+ */
+ protected AT_LEAST_ONE8(
+ actionORMethodDef: GrammarAction | DSLMethodOptsWithErr
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE
+ * @hidden
+ */
+ protected AT_LEAST_ONE9(
+ actionORMethodDef: GrammarAction | DSLMethodOptsWithErr
+ ): void
+
+ /**
+ * Convenience method, same as MANY_SEP but the repetition is of one or more.
+ * failing to match at least one repetition will result in a parsing error and
+ * cause the parser to attempt error recovery.
+ *
+ * Note that an additional optional property ERR_MSG can be used to provide custom error messages.
+ *
+ * @see MANY_SEP
+ *
+ * @param options - An object defining the grammar of each iteration and the separator between iterations
+ *
+ * @return {ISeparatedIterationResult}
+ */
+ protected AT_LEAST_ONE_SEP(
+ options: AtLeastOneSepMethodOpts
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE_SEP
+ * @hidden
+ */
+ protected AT_LEAST_ONE_SEP1(
+ options: AtLeastOneSepMethodOpts
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE_SEP
+ * @hidden
+ */
+ protected AT_LEAST_ONE_SEP2(
+ options: AtLeastOneSepMethodOpts
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE_SEP
+ * @hidden
+ */
+ protected AT_LEAST_ONE_SEP3(
+ options: AtLeastOneSepMethodOpts
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE_SEP
+ * @hidden
+ */
+ protected AT_LEAST_ONE_SEP4(
+ options: AtLeastOneSepMethodOpts
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE_SEP
+ * @hidden
+ */
+ protected AT_LEAST_ONE_SEP5(
+ options: AtLeastOneSepMethodOpts
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE_SEP
+ * @hidden
+ */
+ protected AT_LEAST_ONE_SEP6(
+ options: AtLeastOneSepMethodOpts
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE_SEP
+ * @hidden
+ */
+ protected AT_LEAST_ONE_SEP7(
+ options: AtLeastOneSepMethodOpts
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE_SEP
+ * @hidden
+ */
+ protected AT_LEAST_ONE_SEP8(
+ options: AtLeastOneSepMethodOpts
+ ): void
+
+ /**
+ * @see AT_LEAST_ONE_SEP
+ * @hidden
+ */
+ protected AT_LEAST_ONE_SEP9(
+ options: AtLeastOneSepMethodOpts
+ ): void
+
+ /**
+ * Returns an "imaginary" Token to insert when Single Token Insertion is done
+ * Override this if you require special behavior in your grammar.
+ * For example if an IntegerToken is required provide one with the image '0' so it would be valid syntactically.
+ */
+ protected getTokenToInsert(tokType: TokenType): IToken
+
+ /**
+ * By default all tokens type may be inserted. This behavior may be overridden in inheriting Recognizers
+ * for example: One may decide that only punctuation tokens may be inserted automatically as they have no additional
+ * semantic value. (A mandatory semicolon has no additional semantic meaning, but an Integer may have additional meaning
+ * depending on its int value and context (Inserting an integer 0 in cardinality: "[1..]" will cause semantic issues
+ * as the max of the cardinality will be greater than the min value (and this is a false error!).
+ */
+ protected canTokenTypeBeInsertedInRecovery(
+ tokType: TokenType
+ ): boolean
+
+ /**
+ * @deprecated - will be removed in the future
+ */
+ protected getNextPossibleTokenTypes(
+ grammarPath: ITokenGrammarPath
+ ): TokenType[]
+
+ input: IToken[]
+
+ protected SKIP_TOKEN(): IToken
+
+ /**
+ * Look-Ahead for the Token Vector
+ * LA(1) is the next Token ahead.
+ * LA(n) is the nth Token ahead.
+ * LA(0) is the previously consumed Token.
+ *
+ * Looking beyond the end of the Token Vector or before its begining
+ * will return in an IToken of type EOF {@link EOF}.
+ * This behavior can be used to avoid infinite loops.
+ *
+ * This is often used to implement custom lookahead logic for GATES.
+ * https://sap.github.io/chevrotain/docs/features/gates.html
+ */
+ protected LA(howMuch: number): IToken
+}
+
+/**
+ * @deprecated Soft deprecated, CstParser or EmbeddedActionsParser instead.
+ * - {@link CstParser}
+ * - {@link EmbeddedActionsParser}
+ */
+export declare class Parser extends BaseParser {
+ /**
+ * @deprecated use {@link Parser.performSelfAnalysis} **instance** method instead.
+ */
+ protected static performSelfAnalysis(parserInstance: Parser): void
+
+ /**
+ *
+ * @param name - The name of the rule.
+ * @param implementation - The implementation of the rule.
+ * @param [config] - The rule's optional configuration.
+ *
+ * @returns - The parsing rule which is the production implementation wrapped with the parsing logic that handles
+ * Parser state / error recovery&reporting/ ...
+ */
+ protected RULE(
+ name: string,
+ implementation: (...implArgs: any[]) => T,
+ config?: IRuleConfig
+ ): (idxInCallingRule?: number, ...args: any[]) => T | any
+
+ /**
+ * Same as {@link Parser.RULE}, but should only be used in
+ * "extending" grammars to override rules/productions from the super grammar.
+ * See [Parser Inheritance Example](https://github.com/SAP/chevrotain/tree/master/examples/parser/inheritance).
+ */
+ protected OVERRIDE_RULE(
+ name: string,
+ impl: (...implArgs: any[]) => T,
+ config?: IRuleConfig
+ ): (idxInCallingRule?: number, ...args: any[]) => T | any
+
+ protected SUBRULE(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE1(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE2(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE3(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE4(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE5(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE6(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE7(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE8(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE9(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+}
+
+/**
+ * A Parser that outputs a Concrete Syntax Tree.
+ * See:
+ * - https://sap.github.io/chevrotain/docs/tutorial/step3_adding_actions_root.html#alternatives
+ * - https://sap.github.io/chevrotain/docs/guide/concrete_syntax_tree.html
+ * For in depth docs.
+ */
+export declare class CstParser extends BaseParser {
+ // TODO: remove `outputCST` from the config options in the constructor
+ /**
+ * @deprecated use {@link Parser.performSelfAnalysis} **instance** method instead.
+ */
+ protected static performSelfAnalysis(parserInstance: Parser): void
+
+ /**
+ * Creates a Grammar Rule
+ */
+ protected RULE(
+ name: string,
+ implementation: (...implArgs: any[]) => any,
+ config?: IRuleConfig
+ ): (idxInCallingRule?: number, ...args: any[]) => CstNode
+
+ /**
+ * Overrides a Grammar Rule
+ * See usage example in: https://github.com/SAP/chevrotain/blob/master/examples/parser/versioning/versioning.js
+ */
+ protected OVERRIDE_RULE(
+ name: string,
+ implementation: (...implArgs: any[]) => any,
+ config?: IRuleConfig
+ ): (idxInCallingRule?: number, ...args: any[]) => CstNode
+
+ /**
+ * Like `SUBRULE` with the numerical suffix as a parameter, e.g:
+ * subrule(0, X) === SUBRULE(X)
+ * subrule(1, X) === SUBRULE1(X)
+ * subrule(2, X) === SUBRULE2(X)
+ * ...
+ * @see SUBRULE
+ */
+ protected subrule(
+ idx: number,
+ ruleToCall: (idx: number) => CstNode,
+ options?: SubruleMethodOpts
+ ): CstNode
+
+ /**
+ * The Parsing DSL Method is used by one rule to call another.
+ * It is equivalent to a non-Terminal in EBNF notation.
+ *
+ * This may seem redundant as it does not actually do much.
+ * However using it is **mandatory** for all sub rule invocations.
+ *
+ * Calling another rule without wrapping in SUBRULE(...)
+ * will cause errors/mistakes in the Parser's self analysis phase,
+ * which will lead to errors in error recovery/automatic lookahead calculation
+ * and any other functionality relying on the Parser's self analysis
+ * output.
+ *
+ * As in CONSUME the index in the method name indicates the occurrence
+ * of the sub rule invocation in its rule.
+ *
+ */
+ protected SUBRULE(
+ ruleToCall: (idx: number) => CstNode,
+ options?: SubruleMethodOpts
+ ): CstNode
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE1(
+ ruleToCall: (idx: number) => CstNode,
+ options?: SubruleMethodOpts
+ ): CstNode
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE2(
+ ruleToCall: (idx: number) => CstNode,
+ options?: SubruleMethodOpts
+ ): CstNode
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE3(
+ ruleToCall: (idx: number) => CstNode,
+ options?: SubruleMethodOpts
+ ): CstNode
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE4(
+ ruleToCall: (idx: number) => CstNode,
+ options?: SubruleMethodOpts
+ ): CstNode
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE5(
+ ruleToCall: (idx: number) => CstNode,
+ options?: SubruleMethodOpts
+ ): CstNode
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE6(
+ ruleToCall: (idx: number) => CstNode,
+ options?: SubruleMethodOpts
+ ): CstNode
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE7(
+ ruleToCall: (idx: number) => CstNode,
+ options?: SubruleMethodOpts
+ ): CstNode
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE8(
+ ruleToCall: (idx: number) => CstNode,
+ options?: SubruleMethodOpts
+ ): CstNode
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE9(
+ ruleToCall: (idx: number) => CstNode,
+ options?: SubruleMethodOpts
+ ): CstNode
+}
+
+/**
+ * A Parser that relies on end user's embedded actions to control its output.
+ * For more details see:
+ * - https://sap.github.io/chevrotain/docs/tutorial/step3_adding_actions_root.html#alternatives
+ * - https://sap.github.io/chevrotain/docs/tutorial/step3b_adding_actions_embedded.html#simple-example
+ */
+export declare class EmbeddedActionsParser extends BaseParser {
+ /**
+ * @deprecated use {@link Parser.performSelfAnalysis} **instance** method instead.
+ */
+ protected static performSelfAnalysis(parserInstance: Parser): void
+
+ // TODO: remove `outputCST` from the config options in the constructor
+
+ /**
+ * Creates a Grammar Rule
+ */
+ protected RULE(
+ name: string,
+ implementation: (...implArgs: any[]) => T,
+ config?: IRuleConfig
+ ): (idxInCallingRule?: number, ...args: any[]) => T
+
+ /**
+ * Overrides a Grammar Rule
+ * See usage example in: https://github.com/SAP/chevrotain/blob/master/examples/parser/versioning/versioning.js
+ */
+ protected OVERRIDE_RULE(
+ name: string,
+ impl: (...implArgs: any[]) => T,
+ config?: IRuleConfig
+ ): (idxInCallingRule?: number, ...args: any[]) => T
+
+ /**
+ * Like `SUBRULE` with the numerical suffix as a parameter, e.g:
+ * subrule(0, X) === SUBRULE(X)
+ * subrule(1, X) === SUBRULE1(X)
+ * subrule(2, X) === SUBRULE2(X)
+ * ...
+ * @see SUBRULE
+ */
+ protected subrule(
+ idx: number,
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * The Parsing DSL Method is used by one rule to call another.
+ * It is equivalent to a non-Terminal in EBNF notation.
+ *
+ * This may seem redundant as it does not actually do much.
+ * However using it is **mandatory** for all sub rule invocations.
+ *
+ * Calling another rule without wrapping in SUBRULE(...)
+ * will cause errors/mistakes in the Parser's self analysis phase,
+ * which will lead to errors in error recovery/automatic lookahead calculation
+ * and any other functionality relying on the Parser's self analysis
+ * output.
+ *
+ * As in CONSUME the index in the method name indicates the occurrence
+ * of the sub rule invocation in its rule.
+ *
+ */
+ protected SUBRULE(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE1(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE2(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE3(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE4(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE5(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE6(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE7(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE8(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+
+ /**
+ * @see SUBRULE
+ * @hidden
+ */
+ protected SUBRULE9(
+ ruleToCall: (idx: number) => T,
+ options?: SubruleMethodOpts
+ ): T
+}
+
+export declare enum ParserDefinitionErrorType {
+ INVALID_RULE_NAME = 0,
+ DUPLICATE_RULE_NAME = 1,
+ INVALID_RULE_OVERRIDE = 2,
+ DUPLICATE_PRODUCTIONS = 3,
+ UNRESOLVED_SUBRULE_REF = 4,
+ LEFT_RECURSION = 5,
+ NONE_LAST_EMPTY_ALT = 6,
+ AMBIGUOUS_ALTS = 7,
+ CONFLICT_TOKENS_RULES_NAMESPACE = 8,
+ INVALID_TOKEN_NAME = 9,
+ INVALID_NESTED_RULE_NAME = 10,
+ DUPLICATE_NESTED_NAME = 11,
+ NO_NON_EMPTY_LOOKAHEAD = 12,
+ AMBIGUOUS_PREFIX_ALTS = 13,
+ TOO_MANY_ALTS = 14
+}
+
+export interface ILexerDefinitionError {
+ message: string
+ type: LexerDefinitionErrorType
+ tokenTypes?: TokenType[]
+}
+
+export declare class Lexer {
+ static SKIPPED: string
+
+ /**
+ * A Constant to mark "abstract" TokenTypes that are used
+ * purely as token categories.
+ * See: {@link createToken.categories}
+ */
+ static NA: RegExp
+ lexerDefinitionErrors: ILexerDefinitionError[]
+
+ /**
+ * @param lexerDefinition -
+ * Structure composed of Tokens Types this lexer will identify.
+ *
+ * In the simple case the structure is an array of TokenTypes.
+ * In the case of {@link IMultiModeLexerDefinition} the structure is an object with two properties:
+ * 1. a "modes" property where each value is an array of TokenTypes.
+ * 2. a "defaultMode" property specifying the initial lexer mode.
+ *
+ * for example:
+ *
+ * ```
+ * {
+ * modes : {
+ * modeX : [Token1, Token2],
+ * modeY : [Token3, Token4]
+ * },
+ *
+ * defaultMode : "modeY"
+ * }
+ * ```
+ *
+ * A lexer with {@link MultiModesDefinition} is simply multiple Lexers where only one Lexer(mode) can be active at the same time.
+ * This is useful for lexing languages where there are different lexing rules depending on context.
+ *
+ * The current lexing mode is selected via a "mode stack".
+ * The last (peek) value in the stack will be the current mode of the lexer.
+ * Defining entering and exiting lexer modes is done using the "push_mode" and "pop_mode" properites
+ * of the {@link createToken.config} parameter.
+ *
+ * - The Lexer will match the **first** pattern that matches, Therefor the order of Token Types is significant.
+ * For example when one pattern may match a prefix of another pattern.
+ *
+ * Note that there are situations in which we may wish to order the longer pattern after the shorter one.
+ * For example: [keywords vs Identifiers](https://github.com/SAP/chevrotain/tree/master/examples/lexer/keywords_vs_identifiers).
+ */
+ constructor(
+ lexerDefinition: TokenType[] | IMultiModeLexerDefinition,
+ config?: ILexerConfig
+ )
+
+ /**
+ * Will lex(Tokenize) a string.
+ * Note that this can be called repeatedly on different strings as this method
+ * does not modify the state of the Lexer.
+ *
+ * @param text - The string to lex
+ * @param [initialMode] - The initial Lexer Mode to start with, by default this will be the first mode in the lexer's
+ * definition. If the lexer has no explicit modes it will be the implicit single 'default_mode' mode.
+ */
+ tokenize(text: string, initialMode?: string): ILexingResult
+}
+
+export interface ILexingResult {
+ tokens: IToken[]
+ groups: {
+ [groupName: string]: IToken[]
+ }
+ errors: ILexingError[]
+}
+
+export interface ILexingError {
+ offset: number
+ line: number
+ column: number
+ length: number
+ message: string
+}
+
+export interface ILexerConfig {
+ /**
+ * An optional flag indicating that lexer definition errors
+ * should not automatically cause an error to be raised.
+ * This can be useful when wishing to indicate lexer errors in another manner
+ * than simply throwing an error (for example in an online playground).
+ */
+ deferDefinitionErrorsHandling?: boolean
+
+ /**
+ * "full" location information means all six combinations of /(end|start)(Line|Column|Offset)/ properties.
+ * "onlyStart" means that only startLine, startColumn and startOffset will be tracked
+ * "onlyOffset" means that only the startOffset will be tracked.
+ *
+ * The less position tracking the faster the Lexer will be and the less memory used.
+ * However the difference is not large (~10% On V8), thus reduced location tracking options should only be used
+ * in edge cases where every last ounce of performance is needed.
+ */
+ // TODO: consider renaming this to LocationTracking to align with NodeLocationTracking option on the ParserConfig.
+ positionTracking?: "full" | "onlyStart" | "onlyOffset"
+
+ /**
+ * A regExp defining custom line terminators.
+ * This will be used to calculate the line and column information.
+ *
+ * Note that the regExp should use the global flag, for example: /\n/g
+ *
+ * The default is: /\n|\r\n?/g
+ *
+ * But some grammars have a different definition, for example in ECMAScript:
+ * https://www.ecma-international.org/ecma-262/8.0/index.html#sec-line-terminators
+ * U+2028 and U+2029 are also treated as line terminators.
+ *
+ * In that case we would use /\n|\r|\u2028|\u2029/g
+ *
+ * Note that it is also possible to supply an optimized RegExp like implementation
+ * as only a subset of the RegExp APIs is needed, {@link ILineTerminatorsTester}
+ * for details.
+ *
+ * keep in mind that for the default pattern: /\n|\r\n?/g an optimized implementation is already built-in.
+ * This means the optimization is only relevant for lexers overriding the default pattern.
+ */
+ lineTerminatorsPattern?: RegExp | ILineTerminatorsTester
+
+ /**
+ * Characters or CharCodes that represent line terminators for this lexer.
+ * This always needs to be provided when using a custom {@link ILexerConfig.lineTerminatorsPattern}.
+ * In the future this duplication may be removed or reduced.
+ */
+ lineTerminatorCharacters?: (number | string)[]
+
+ /**
+ * When true this flag will cause the Lexer to throw an Error
+ * When it is unable to perform all of its performance optimizations.
+ *
+ * In addition error messages will be printed to the console with details
+ * how to resolve the optimizations issues.
+ *
+ * Use this flag to guarantee higher lexer performance.
+ * The optimizations can boost the lexer's performance anywhere from 30%
+ * to 100%+ depending on the number of TokenTypes used.
+ */
+ ensureOptimizations?: boolean
+
+ /**
+ * Can be used to disable lexer optimizations
+ * If there is a suspicion they are causing incorrect behavior.
+ * Note that this would have negative performance implications.
+ */
+ safeMode?: boolean
+
+ /**
+ * A custom error message provider.
+ * Can be used to override the default error messages.
+ * For example:
+ * - Translating the error messages to a different languages.
+ * - Changing the formatting.
+ */
+ errorMessageProvider?: ILexerErrorMessageProvider
+
+ /**
+ * Enabling this flag will print performance tracing logs during lexer
+ * Initialization (constructor invocation), this is useful to narrow down the cause
+ * of the initialization performance problem.
+ *
+ * You can also pass a numerical value which affects the verbosity
+ * of the traces, this number is the maximum nesting level of the traces, e.g:
+ * 0: Traces disabled === 'false'
+ * 1: Top Level traces only.
+ * 2: One level of nested inner traces.
+ * ...
+ *
+ * Note that passing the boolean `true` is identical to passing the numerical value `infinity`
+ */
+ traceInitPerf?: boolean | number
+
+ /**
+ * This flag will avoid running the Lexer validations during Lexer initialization.
+ *
+ * This can substantially improve the Lexer's initialization (constructor) time.
+ * @see ILexerConfig.traceInitPerf to measure the Lexer validations cost for your Lexer.
+ *
+ * Note that the Lexer validations are **extremely useful** during development time,
+ * e.g: Detecting empty/invalid regExp Patterns.
+ * So they should not be skipped during development flows.
+ * - For example: via a conditional that checks an env variable.
+ */
+ skipValidations?: boolean
+}
+
+export interface ILexerErrorMessageProvider {
+ /**
+ * An Unexpected Character Error occurs when the lexer is unable to match a range of one or more
+ * characters in the input text against any of the Token Types in it's Lexer definition
+ *
+ * @param fullText - Full original input text.
+ *
+ * @param startOffset - Offset in input text where error starts.
+ *
+ * @param length - Error length.
+ *
+ * @param line - Line number where the error occured. (optional)
+ * Will not be provided when lexer is not defined to track lines/columns
+ *
+ * @param column - Column number where the error occured. (optional)
+ * Will not be provided when lexer is not defined to track lines/columns
+ */
+ buildUnexpectedCharactersMessage(
+ fullText: string,
+ startOffset: number,
+ length: number,
+ line?: number,
+ column?: number
+ ): string
+
+ /**
+ * Unable To Pop Lexer Mode Error happens when lexer tries to pop the last remaining mode from the mode stack
+ * so that there is no longer any active lexer mode
+ * This error only relevant for multi-mode lexers
+ *
+ * @param token - The Token that requested pop mode.
+ */
+ buildUnableToPopLexerModeMessage(token: IToken): string
+}
+
+/**
+ * This is the default logic Chevrotain uses to construct lexing error messages.
+ * It can be used as a reference or as a starting point customize a lexer's
+ * error messages.
+ *
+ * - See: {@link ILexerConfig.errorMessageProvider}
+ */
+export declare const defaultLexerErrorProvider: ILexerErrorMessageProvider
+
+/**
+ * A subset of the regExp interface.
+ * Needed to compute line/column info by a chevrotain lexer.
+ */
+export interface ILineTerminatorsTester {
+ /**
+ * Just like regExp.test
+ */
+ test: (text: string) => boolean
+
+ /**
+ * Just like the regExp lastIndex with the global flag enabled
+ * It should be updated after every match to point to the offset where the next
+ * match attempt starts.
+ */
+ lastIndex: number
+}
+
+export type TokenPattern =
+ | RegExp
+ | string
+ | CustomPatternMatcherFunc
+ | ICustomPattern
+
+export interface ITokenConfig {
+ name: string
+
+ /**
+ * Categories enable polymorphism on Token Types.
+ * A TokenType X with categories C1, C2, ... ,Cn can
+ * be matched by the parser against any of those categories.
+ * In practical terms this means that:
+ * CONSUME(C1) can match a Token of type X.
+ */
+ categories?: TokenType | TokenType[]
+
+ /**
+ * The Label is a human readable name to be used
+ * in error messages and syntax diagrams.
+ *
+ * For example a TokenType may be called LCurly, which is
+ * short for "left curly brace". The much easier to understand
+ * label could simply be "{".
+ */
+ label?: string
+
+ /**
+ * This defines what sequence of characters would be matched
+ * To this TokenType when Lexing.
+ *
+ * For Custom Patterns see: http://sap.github.io/chevrotain/docs/guide/custom_token_patterns.html
+ */
+ pattern?: TokenPattern
+
+ /**
+ * The group property will cause the lexer to collect
+ * Tokens of this type separately from the other Tokens.
+ *
+ * For example this could be used to collect comments for
+ * post processing.
+ *
+ * See: https://github.com/SAP/chevrotain/tree/master/examples/lexer/token_groups
+ */
+ group?: string
+
+ /**
+ * A name of a Lexer mode to "enter" once this Token Type has been matched.
+ * Lexer modes can be used to support different sets of possible Tokens Types
+ *
+ * Lexer Modes work as a stack of Lexers, so "entering" a mode means pushing it to the top of the stack.
+ *
+ * See: https://github.com/SAP/chevrotain/tree/master/examples/lexer/multi_mode_lexer
+ */
+ push_mode?: string
+
+ /**
+ * If "pop_mode" is true the Lexer will pop the last mode of the modes stack and
+ * continue lexing using the new mode at the top of the stack.
+ *
+ * See: https://github.com/SAP/chevrotain/tree/master/examples/lexer/multi_mode_lexer
+ */
+ pop_mode?: boolean
+
+ /**
+ * The "longer_alt" property will cause the Lexer to attempt matching against another Token Type
+ * every time this Token Type has been matched.
+ *
+ * This feature can be useful when two Token Types have common prefixes which
+ * cannot be resolved (only) by the ordering of the Tokens in the lexer definition.
+ *
+ * For example see: https://github.com/SAP/chevrotain/tree/master/examples/lexer/keywords_vs_identifiers
+ * For resolving the keywords vs Identifier ambiguity.
+ */
+ longer_alt?: TokenType
+
+ /**
+ * Can a String matching this Token Type's pattern possibly contain a line terminator?
+ * If true and the line_breaks property is not also true this will cause inaccuracies in the Lexer's line / column tracking.
+ */
+ line_breaks?: boolean
+
+ /**
+ * Possible starting characters or charCodes of the pattern.
+ * These will be used to optimize the Lexer's performance.
+ *
+ * These are normally **automatically** computed, however the option to explicitly
+ * specify those can enable optimizations even when the automatic analysis fails.
+ *
+ * e.g:
+ * * strings hints should be one character long.
+ * ```
+ * { start_chars_hint: ["a", "b"] }
+ * ```
+ *
+ * * number hints are the result of running ".charCodeAt(0)" on the strings.
+ * ```
+ * { start_chars_hint: [97, 98] }
+ * ```
+ *
+ * * For unicode characters outside the BMP use the first of their surrogate pairs.
+ * for example: The '💩' character is represented by surrogate pairs: '\uD83D\uDCA9'
+ * and D83D is 55357 in decimal.
+ * * Note that "💩".charCodeAt(0) === 55357
+ */
+ start_chars_hint?: (string | number)[]
+}
+
+/**
+ * Creates a new TokenType which can then be used
+ * to define a Lexer and Parser
+ */
+export declare function createToken(config: ITokenConfig): TokenType
+
+/**
+ * Utility to create Chevrotain IToken "instances"
+ * Note that Chevrotain tokens are not real TokenTypes instances
+ * and thus the instanceOf cannot be used with them.
+ */
+export declare function createTokenInstance(
+ tokType: TokenType,
+ image: string,
+ startOffset: number,
+ endOffset: number,
+ startLine: number,
+ endLine: number,
+ startColumn: number,
+ endColumn: number
+): IToken
+
+/**
+ * API #1 [Custom Token Patterns](http://sap.github.io/chevrotain/docs/guide/custom_token_patterns.html).
+ */
+export declare type CustomPatternMatcherFunc = (
+ /**
+ * The full input string.
+ */
+ text: string,
+ /**
+ * The offset at which to attempt a match
+ */
+ offset: number,
+ /**
+ * Previously scanned Tokens
+ */
+ tokens: IToken[],
+ /**
+ * Token Groups
+ */
+ groups: {
+ [groupName: string]: IToken[]
+ }
+) => CustomPatternMatcherReturn | RegExpExecArray | null // RegExpExecArray included for legacy reasons
+
+export type CustomPatternMatcherReturn = [string] & { payload?: any }
+
+export interface TokenType {
+ name: string
+ GROUP?: string
+ PATTERN?: TokenPattern
+ LABEL?: string
+ LONGER_ALT?: TokenType
+ POP_MODE?: boolean
+ PUSH_MODE?: string
+ LINE_BREAKS?: boolean
+ CATEGORIES?: TokenType[]
+ tokenTypeIdx?: number
+ categoryMatches?: number[]
+ categoryMatchesMap?: {
+ [tokType: number]: boolean
+ }
+ isParent?: boolean
+ START_CHARS_HINT?: (string | number)[]
+}
+
+/**
+ * API #2 for [Custom Token Patterns](http://sap.github.io/chevrotain/docs/guide/custom_token_patterns.html).
+ */
+interface ICustomPattern {
+ exec: CustomPatternMatcherFunc
+}
+
+/**
+ * Things to note:
+ * - The offset range is inclusive to exclusive.
+ *
+ * - A lineTerminator as the last character does not effect the Token's line numbering.
+ * In other words a new line only starts **after** a line terminator.
+ *
+ * - A Token's image is it's **literal** text.
+ * e.g unicode escaping is untouched.
+ */
+export interface IToken {
+ /** The textual representation of the Token as it appeared in the text. */
+ image: string
+ /** Offset of the first character of the Token. */
+ startOffset: number
+ /** Line of the first character of the Token. */
+ startLine?: number
+ /** Column of the first character of the Token. */
+ startColumn?: number
+ /** Offset of the last character of the Token. */
+ endOffset?: number
+ /** Line of the last character of the Token. */
+ endLine?: number
+ /** Column of the last character of the Token. */
+ endColumn?: number
+ /** this marks if a Token does not really exist and has been inserted "artificially" during parsing in rule error recovery. */
+ isInsertedInRecovery?: boolean
+ /** An number index representing the type of the Token use to get the Token Type from a token "instance" */
+ tokenTypeIdx: number
+ /**
+ * The actual Token Type of this Token "instance"
+ * This is the same Object returned by the "createToken" API.
+ * This property is very useful for debugging the Lexing and Parsing phases.
+ */
+ tokenType: TokenType
+
+ /**
+ * Custom Payload value, this is an optional feature of Custom Token Patterns
+ * For additional details see the docs:
+ * https://sap.github.io/chevrotain/docs/guide/custom_token_patterns.html#custom-payloads
+ */
+ payload?: any
+}
+
+export declare function tokenName(tokType: TokenType): string
+
+/**
+ * Returns a human readable label for a TokenType if such exists,
+ * otherwise will return the TokenType's name.
+ *
+ * Labels are useful in improving the readability of error messages and syntax diagrams.
+ * To define labels provide the label property in the {@link createToken} config parameter.
+ */
+export declare function tokenLabel(tokType: TokenType): string
+
+/**
+ * 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.
+ *
+ * This means a simple comparison using the {@link IToken.tokenType} property may not suffice.
+ * For example:
+ *
+ * ```
+ * import { createToken, tokenMatcher, Lexer } from "chevrotain"
+ *
+ * // An "abstract" Token used only for categorization purposes.
+ * const NumberTokType = createToken({ name: "NumberTokType", pattern: Lexer.NA })
+ *
+ * const IntegerTokType = createToken({
+ * name: "IntegerTokType",
+ * pattern: /\d+/,
+ * // Integer "Is A" Number
+ * categories: [NumberTokType]
+ * })
+ *
+ * const DecimalTokType = createToken({
+ * name: "DecimalTokType",
+ * pattern: /\d+\.\d+/,
+ * // Double "Is A" Number
+ * categories: [NumberTokType]
+ * })
+ *
+ * // Will always be false as the tokenType property can only
+ * // be Integer or Double Token Types as the Number TokenType is "abstract".
+ * if (myToken.tokenType === NumberTokType) { /* ... *\/ }
+ *
+ * // Will be true when myToken is of Type Integer or Double.
+ * // Because the hierarchy defined by the categories is taken into account.
+ * if (tokenMatcher(myToken, NumberTokType) { /* ... *\/ }
+ * ```
+ *
+ * @returns true iff the token matches the TokenType.
+ */
+export function tokenMatcher(token: IToken, tokType: TokenType): boolean
+
+export declare type MultiModesDefinition = {
+ [modeName: string]: TokenType[]
+}
+
+export interface IMultiModeLexerDefinition {
+ modes: MultiModesDefinition
+ defaultMode: string
+}
+
+export type TokenTypeDictionary = { [tokenName: string]: TokenType }
+
+export declare type TokenVocabulary =
+ | TokenTypeDictionary
+ | TokenType[]
+ | IMultiModeLexerDefinition
+
+export interface IRuleConfig {
+ /**
+ * The function which will be invoked to produce the returned value for a production that have not been
+ * successfully executed and the parser recovered from.
+ */
+ recoveryValueFunc?: () => T
+ /**
+ * Enable/Disable re-sync error recovery for this specific production.
+ */
+ resyncEnabled?: boolean
+}
+
+export interface DSLMethodOpts {
+ /**
+ * in-lined method name
+ */
+ NAME?: string
+ /**
+ * The Grammar to process in this method.
+ */
+ DEF: GrammarAction
+ /**
+ * A semantic constraint on this DSL method
+ * @see https://github.com/SAP/chevrotain/blob/master/examples/parser/predicate_lookahead/predicate_lookahead.js
+ * For farther details.
+ */
+ GATE?: () => boolean
+
+ /**
+ * Maximum number of "following tokens" which would be used to
+ * Choose between the alternatives.
+ *
+ * By default this value is determined by the {@link IParserConfig.maxLookahead} value.
+ * A Higher value may be used for a specific DSL method to resolve ambiguities
+ * And a lower value may be used to resolve slow initialization times issues.
+ *
+ * TODO: create full docs and link
+ */
+ MAX_LOOKAHEAD?: number
+}
+
+export interface DSLMethodOptsWithErr extends DSLMethodOpts {
+ /**
+ * Short title/classification to what is being matched.
+ * Will be used in the error message,.
+ * If none is provided, the error message will include the names of the expected
+ * Tokens sequences which start the method's inner grammar
+ */
+ ERR_MSG?: string
+}
+
+export interface OrMethodOpts {
+ NAME?: string
+ /**
+ * The set of alternatives,
+ * See detailed description in {@link Parser.OR}
+ */
+ DEF: IOrAlt[]
+ /**
+ * A description for the alternatives used in error messages
+ * If none is provided, the error message will include the names of the expected
+ * Tokens sequences which may start each alternative.
+ */
+ ERR_MSG?: string
+
+ /**
+ * A Flag indicating that **all** ambiguities in this alternation should
+ * be ignored.
+ *
+ * This flag should only be used in rare circumstances,
+ * As normally alternation ambiguities should be resolved in other ways:
+ * - Re-ordering the alternatives.
+ * - Re-factoring the grammar to extract common prefixes before alternation.
+ * - Using gates {@link IOrAlt.GATE} to implement custom lookahead logic.
+ * - Using the more granular {@link IOrAlt.IGNORE_AMBIGUITIES} on a **specific** alternative.
+ */
+ IGNORE_AMBIGUITIES?: boolean
+
+ /**
+ * Maximum number of "following tokens" which would be used to
+ * Choose between the alternatives.
+ *
+ * By default this value is determined by the {@link IParserConfig.maxLookahead} value.
+ * A Higher value may be used for a specific DSL method to resolve ambiguities
+ * And a lower value may be used to resolve slow initialization times issues.
+ *
+ * TODO: create full docs and link
+ */
+ MAX_LOOKAHEAD?: number
+}
+
+export interface ManySepMethodOpts {
+ NAME?: string
+ /**
+ * The grammar to process in each iteration.
+ */
+ DEF: GrammarAction
+ /**
+ * The separator between each iteration.
+ */
+ SEP: TokenType
+
+ /**
+ * @see DSLMethodOpts.MAX_LOOKAHEAD
+ */
+ MAX_LOOKAHEAD?: number
+}
+
+export interface AtLeastOneSepMethodOpts extends ManySepMethodOpts {
+ /**
+ * Short title/classification to what is being matched.
+ * Will be used in the error message,.
+ * If none is provided, the error message will include the names of the expected
+ * Tokens sequences which start the method's inner grammar.
+ */
+ ERR_MSG?: string
+}
+
+export interface ConsumeMethodOpts {
+ /**
+ * A custom Error message if the Token could not be consumed.
+ * This will override any error message provided by the parser's "errorMessageProvider"
+ */
+ ERR_MSG?: string
+ /**
+ * A label to be used instead of the TokenType name in the created CST.
+ */
+ LABEL?: string
+}
+
+export interface SubruleMethodOpts {
+ /**
+ * The arguments to parameterized rules, see:
+ * https://github.com/SAP/chevrotain/blob/master/examples/parser/parametrized_rules/parametrized.js
+ */
+ ARGS?: any[]
+ /**
+ * A label to be used instead of the subrule's name in the created CST.
+ */
+ LABEL?: string
+}
+
+export declare type GrammarAction = () => OUT
+
+/**
+ * TODO: remove this in next major version this `IOrAlt` is enough
+ * @deprecated
+ */
+export declare type IAnyOrAlt = any
+
+export interface IOrAlt {
+ NAME?: string
+ GATE?: () => boolean
+ ALT: () => any
+ /**
+ * A Flag indicating that any ambiguities involving this
+ * specific alternative Should be ignored.
+ *
+ * This flag will be **implicitly** enabled if a GATE is used
+ * as the assumption is that the GATE is used to resolve an ambiguity.
+ */
+ IGNORE_AMBIGUITIES?: boolean
+}
+
+export interface IOrAltWithGate extends IOrAlt {
+ // TODO: deprecate this interface
+}
+
+export interface ICstVisitor {
+ visit(cstNode: CstNode | CstNode[], param?: IN): OUT
+ validateVisitor(): void
+}
+
+/**
+ * A [Concrete Syntax Tree](http://sap.github.io/chevrotain/docs/guide/concrete_syntax_tree.html) Node.
+ * This structure represents the whole parse tree of the grammar
+ * This means that information on each and every Token is present.
+ * This is unlike an AST (Abstract Syntax Tree) where some of the syntactic information is missing.
+ *
+ * For example given an ECMAScript grammar, an AST would normally not contain information on the location
+ * of Commas, Semi colons, redundant parenthesis ect, however a CST would have that information.
+ */
+export interface CstNode {
+ readonly name: string
+ readonly children: CstChildrenDictionary
+ readonly recoveredNode?: boolean
+
+ /**
+ * Will only be present if the {@link IParserConfig.nodeLocationTracking} is
+ * **not** set to "none".
+ * See: http://sap.github.io/chevrotain/docs/guide/concrete_syntax_tree.html#cstnode-location
+ * For more details.
+ */
+ readonly location?: CstNodeLocation
+ /**
+ * Only relevant for [in-lined](http://sap.github.io/chevrotain/docs/guide/concrete_syntax_tree.html#in-lined-rules) rules.
+ * the fullName will **also** include the name of the top level rule containing this nested rule.
+ */
+ readonly fullName?: string
+}
+
+/**
+ * The Column/Line properties will only be present when
+ * The {@link IParserConfig.nodeLocationTracking} is set to "full".
+ */
+export interface CstNodeLocation {
+ startOffset: number
+ startLine: number
+ startColumn?: number
+ endOffset?: number
+ endLine?: number
+ endColumn?: number
+}
+
+export declare type CstChildrenDictionary = {
+ [identifier: string]: CstElement[]
+}
+
+export declare type CstElement = IToken | CstNode
+
+export declare type nodeLocationTrackingOptions = "full" | "onlyOffset" | "none"
+
+export interface IParserConfig {
+ /**
+ * Is the error recovery / fault tolerance of the Chevrotain Parser enabled.
+ */
+ recoveryEnabled?: boolean
+ /**
+ * Maximum number of tokens the parser will use to choose between alternatives.
+ * By default this value is `4`.
+ * In the future it may be reduced to `3` due to performance considerations.
+ */
+ maxLookahead?: number
+ /**
+ * @deprecated - use the IGNORE_AMBIGUITIES flag on the relevant DSL method instead
+ * - {@link IOrAlt.IGNORE_AMBIGUITIES}
+ * - {@link OrMethodOpts.IGNORE_AMBIGUITIES}
+ *
+ * Used to mark parser definition errors that should be ignored.
+ * For example:
+ *
+ * ```
+ * {
+ * myCustomRule : {
+ * OR3 : true
+ * },
+ * myOtherRule : {
+ * OPTION1 : true,
+ * OR4 : true
+ * }
+ * }
+ * ```
+ *
+ * Be careful when ignoring errors, they are usually there for a reason :).
+ */
+ ignoredIssues?: IgnoredParserIssues
+ /**
+ * Enable This Flag to to support Dynamically defined Tokens.
+ * This will disable performance optimizations which cannot work if the whole Token vocabulary is not known
+ * During Parser initialization.
+ *
+ * See [runnable example](https://github.com/SAP/chevrotain/tree/master/examples/parser/dynamic_tokens)
+ */
+ dynamicTokensEnabled?: boolean
+ /**
+ * @deprecated - extend either CstParser or EmbeddedActionsParser to control this flag instead
+ * - @see CstParser
+ * - @see EmbeddedActionsParser
+ *
+ * Enable automatic Concrete Syntax Tree creation
+ * For in-depth docs on [Concrete Syntax Trees](http://sap.github.io/chevrotain/docs/guide/concrete_syntax_tree.html):
+ */
+ outputCst?: boolean
+ /**
+ * Enable computation of CST nodes location.
+ * By default this is set to "none", meaning this feature is disabled.
+ * See: http://sap.github.io/chevrotain/docs/guide/concrete_syntax_tree.html#cstnode-location
+ * For more details.
+ */
+ nodeLocationTracking?: nodeLocationTrackingOptions
+ /**
+ * A custom error message provider.
+ * Can be used to override the default error messages.
+ * For example:
+ * - Translating the error messages to a different languages.
+ * - Changing the formatting.
+ * - Providing special error messages under certain conditions, e.g: missing semicolons.
+ */
+ errorMessageProvider?: IParserErrorMessageProvider
+ /**
+ * Enabling this flag will print performance tracing logs during parser
+ * Initialization (constructor invocation), this is useful to narrow down the cause
+ * of the initialization performance problem.
+ *
+ * You can also pass a numerical value which affects the verbosity
+ * of the traces, this number is the maximum nesting level of the traces, e.g:
+ * 0: Traces disabled === 'false'
+ * 1: Top Level traces only.
+ * 2: One level of nested inner traces.
+ * ...
+ *
+ * Note that passing the boolean `true` is identical to passing the numerical value `infinity`
+ */
+ traceInitPerf?: boolean | number
+ /**
+ * This flag will avoid running the grammar validations during Parser initialization.
+ *
+ * This can substantially improve the Parser's initialization (constructor) time.
+ * @see IParserConfig.traceInitPerf to measure the grammar validations cost for your parser.
+ *
+ * Note that the grammar validations are **extremely useful** during development time,
+ * e.g: detecting ambiguities / left recursion.
+ * So they should not be skipped during development flows.
+ * - For example: via a conditional that checks an env variable.
+ */
+ skipValidations?: boolean
+}
+
+/**
+ * See: {@link IParserConfig.ignoredIssues}
+ */
+export declare type IgnoredParserIssues = {
+ [ruleName: string]: IgnoredRuleIssues
+}
+
+/**
+ * See: {@link IParserConfig.ignoredIssues}
+ */
+export declare type IgnoredRuleIssues = {
+ [dslNameAndOccurrence: string]: boolean
+}
+
+export interface IParserErrorMessageProvider {
+ /**
+ * Mismatched Token Error happens when the parser attempted to consume a terminal and failed.
+ * It corresponds to a failed {@link Parser.CONSUME} in Chevrotain DSL terms.
+ *
+ * @param options.expected - The expected Token Type.
+ *
+ * @param options.actual - The actual Token "instance".
+ *
+ * @param options.previous - The previous Token "instance".
+ * This is useful if options.actual[0] is of type chevrotain.EOF and you need to know the last token parsed.
+ *
+ * @param options.ruleName - The rule in which the error occurred.
+ */
+ buildMismatchTokenMessage?(options: {
+ expected: TokenType
+ actual: IToken
+ previous: IToken
+ ruleName: string
+ }): string
+ /**
+ * A Redundant Input Error happens when the parser has completed parsing but there
+ * is still unprocessed input remaining.
+ *
+ * @param options.firstRedundant - The first unprocessed token "instance".
+ *
+ * @param options.ruleName - The rule in which the error occurred.
+ */
+ buildNotAllInputParsedMessage?(options: {
+ firstRedundant: IToken
+ ruleName: string
+ }): string
+ /**
+ * A No Viable Alternative Error happens when the parser cannot detect any valid alternative in an alternation.
+ * It corresponds to a failed {@link Parser.OR} in Chevrotain DSL terms.
+ *
+ * @param options.expectedPathsPerAlt - First level of the array represents each alternative
+ * The next two levels represent valid (expected) paths in each alternative.
+ *
+ * @param options.actual - The actual sequence of tokens encountered.
+ *
+ * @param options.previous - The previous Token "instance".
+ * This is useful if options.actual[0] is of type chevrotain.EOF and you need to know the last token parsed.
+ *
+ * @param options.customUserDescription - A user may provide custom error message descriptor in the {@link Parser.AT_LEAST_ONE} DSL method
+ * options parameter, this is that custom message.
+ *
+ * @param options.ruleName - The rule in which the error occurred.
+ */
+ buildNoViableAltMessage?(options: {
+ expectedPathsPerAlt: TokenType[][][]
+ actual: IToken[]
+ previous: IToken
+ customUserDescription: string
+ ruleName: string
+ }): string
+ /**
+ * An Early Exit Error happens when the parser cannot detect the first mandatory iteration of a repetition.
+ * It corresponds to a failed {@link Parser.AT_LEAST_ONE} or {@link Parser.AT_LEAST_ONE_SEP} in Chevrotain DSL terms.
+ *
+ * @param options.expectedIterationPaths - The valid (expected) paths in the first iteration.
+ *
+ * @param options.actual - The actual sequence of tokens encountered.
+ *
+ * @param options.previous - The previous Token "instance".
+ * This is useful if options.actual[0] is of type chevrotain.EOF and you need to know the last token parsed.
+ *
+ * @param options.customUserDescription - A user may provide custom error message descriptor in the {@link Parser.AT_LEAST_ONE} DSL method
+ * options parameter, this is that custom message.
+ *
+ * @param options.ruleName - The rule in which the error occurred.
+ */
+ buildEarlyExitMessage?(options: {
+ expectedIterationPaths: TokenType[][]
+ actual: IToken[]
+ previous: IToken
+ customUserDescription: string
+ ruleName: string
+ }): string
+}
+
+export interface IRecognizerContext {
+ /**
+ * A copy of the parser's rule stack at the "time" the RecognitionException occurred.
+ * This can be used to help debug parsing errors (How did we get here?).
+ */
+ ruleStack: string[]
+ /**
+ * A copy of the parser's rule occurrence stack at the "time" the RecognitionException occurred.
+ * This can be used to help debug parsing errors (How did we get here?).
+ */
+ ruleOccurrenceStack: number[]
+}
+
+export declare type ISeparatedIterationResult = {
+ values: OUT[]
+ separators: IToken[]
+}
+
+export interface ISerializedGast {
+ type:
+ | "NonTerminal"
+ | "Flat"
+ | "Option"
+ | "RepetitionMandatory"
+ | "RepetitionMandatoryWithSeparator"
+ | "Repetition"
+ | "RepetitionWithSeparator"
+ | "Alternation"
+ | "Terminal"
+ | "Rule"
+ definition?: ISerializedGast[]
+}
+
+/**
+ * Structure for the path the parser "took" to reach a certain position
+ * in the grammar.
+ */
+export interface IGrammarPath {
+ /**
+ * The Grammar rules invoked and still unterminated to reach this Grammar Path.
+ */
+ ruleStack: string[]
+ /**
+ * The occurrence index (SUBRULE1/2/3/5/...) of each Grammar rule invoked and still unterminated.
+ * Used to distinguish between **different** invocations of the same subrule at the same top level rule.
+ */
+ occurrenceStack: number[]
+}
+
+export interface ISyntacticContentAssistPath extends IGrammarPath {
+ nextTokenType: TokenType
+ nextTokenOccurrence: number
+}
+
+export interface ITokenGrammarPath extends IGrammarPath {
+ lastTok: TokenType
+ lastTokOccurrence: number
+}
+
+export declare enum LexerDefinitionErrorType {
+ MISSING_PATTERN = 0,
+ INVALID_PATTERN = 1,
+ EOI_ANCHOR_FOUND = 2,
+ UNSUPPORTED_FLAGS_FOUND = 3,
+ DUPLICATE_PATTERNS_FOUND = 4,
+ INVALID_GROUP_TYPE_FOUND = 5,
+ PUSH_MODE_DOES_NOT_EXIST = 6,
+ MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE = 7,
+ MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY = 8,
+ MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST = 9,
+ LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED = 10,
+ SOI_ANCHOR_FOUND = 11,
+ EMPTY_MATCH_PATTERN = 12,
+ NO_LINE_BREAKS_FLAGS = 13,
+ UNREACHABLE_PATTERN = 14,
+ IDENTIFY_TERMINATOR = 15,
+ CUSTOM_LINE_BREAK = 16
+}
+
+/**
+ * Type of End Of File Token.
+ */
+export declare const EOF: TokenType
+
+/**
+ * Convenience used to express an **empty** alternative in an OR (alternation).
+ * can be used to more clearly describe the intent in a case of empty alternation.
+ *
+ * For example:
+ *
+ * 1. without using EMPTY_ALT:
+ * ```
+ * this.OR([
+ * {ALT: () => {
+ * this.CONSUME1(OneTok)
+ * return "1"
+ * }},
+ * {ALT: () => {
+ * this.CONSUME1(TwoTok)
+ * return "2"
+ * }},
+ * // implicitly empty because there are no invoked grammar
+ * // rules (OR/MANY/CONSUME...) inside this alternative.
+ * {ALT: () => {
+ * return "666"
+ * }},
+ * ])
+ * ```
+ *
+ * 2. using EMPTY_ALT:
+ * ```
+ * this.OR([
+ * {ALT: () => {
+ * this.CONSUME1(OneTok)
+ * return "1"
+ * }},
+ * {ALT: () => {
+ * this.CONSUME1(TwoTok)
+ * return "2"
+ * }},
+ * // explicitly empty, clearer intent
+ * {ALT: EMPTY_ALT("666")},
+ * ])
+ * ```
+ */
+export declare function EMPTY_ALT(value?: T): () => T
+
+/**
+ * This is the default logic Chevrotain uses to construct error messages.
+ * It can be used as a reference or as a starting point customize a parser's
+ * error messages.
+ *
+ * - See: {@link IParserConfig.errorMessageProvider}
+ */
+export declare const defaultParserErrorProvider: IParserErrorMessageProvider
+
+/**
+ * A Chevrotain Parser runtime exception.
+ */
+export interface IRecognitionException {
+ name: string
+ message: string
+ /**
+ * The token which caused the parser error.
+ */
+ token: IToken
+ /**
+ * Additional tokens which have been re-synced in error recovery due to the original error.
+ * This information can be used the calculate the whole text area which has been skipped due to an error.
+ * For example for displaying with a red underline in a text editor.
+ */
+ resyncedTokens: IToken[]
+ context: IRecognizerContext
+}
+
+/**
+ * A utility to detect if an Error is a Chevrotain Parser's runtime exception.
+ */
+export declare function isRecognitionException(error: Error): boolean
+
+// TODO refactor exceptions constructors to classes
+
+/**
+ * An exception of this type will be saved in {@link Parser.errors} when {@link Parser.CONSUME}
+ * was called but failed to match the expected Token Type.
+ */
+export declare class MismatchedTokenException extends Error {
+ constructor(message: string, token: IToken, previousToken: IToken)
+}
+
+/**
+ * An exception of this type will be saved in {@link Parser.errors} when {@link Parser.OR}
+ * was called yet none of the possible alternatives could be matched.
+ */
+export declare class NoViableAltException extends Error {
+ constructor(message: string, token: IToken, previousToken: IToken)
+}
+
+/**
+ * An exception of this type will be saved in {@link Parser.errors} when
+ * the parser has finished yet there exists remaining input (tokens) that has not processed.
+ */
+export declare class NotAllInputParsedException extends Error {
+ constructor(message: string, token: IToken)
+}
+
+/**
+ * An exception of this type will be saved in {@link Parser.errors} when {@link Parser.AT_LEAST_ONE}
+ * or {@link Parser.AT_LEAST_ONE_SEP} was called but failed to match even a single iteration.
+ */
+export declare class EarlyExitException extends Error {
+ constructor(message: string, token: IToken, previousToken: IToken)
+}
+
+export interface IOptionallyNamedProduction {
+ name?: string
+}
+export interface IProduction {
+ accept(visitor: IGASTVisitor): void
+}
+
+export interface IProductionWithOccurrence extends IProduction {
+ idx: number
+}
+
+/**
+ * A very basic implementation of a Visitor Pattern
+ * For the Grammar AST structure.
+ *
+ * This may be useful for advanced users who create custom logic on the grammar AST.
+ * For example, custom validations or introspection.
+ */
+export abstract class GAstVisitor {
+ visit(node: IProduction): any
+
+ abstract visitNonTerminal(node: NonTerminal): any
+
+ abstract visitFlat(node: Flat): any
+
+ abstract visitOption(node: Option): any
+
+ abstract visitRepetition(node: Repetition): any
+
+ abstract visitRepetitionMandatory(node: RepetitionMandatory): any
+
+ abstract visitRepetitionMandatoryWithSeparator(
+ node: RepetitionMandatoryWithSeparator
+ ): any
+
+ abstract visitRepetitionWithSeparator(node: RepetitionWithSeparator): any
+
+ abstract visitAlternation(node: Alternation): any
+
+ abstract visitTerminal(node: Terminal): any
+
+ abstract visitRule(node: Rule): any
+}
+
+/**
+ * The Grammar AST class representing a top level {@link Parser.RULE} call.
+ */
+export declare class Rule {
+ name: string
+ orgText: string
+ definition: IProduction[]
+
+ constructor(options: {
+ name: string
+ definition: IProduction[]
+ orgText?: string
+ })
+
+ accept(visitor: IGASTVisitor): void
+}
+
+/**
+ * The Grammar AST class representing a top level {@link Parser.SUBRULE} call.
+ */
+export declare class NonTerminal implements IProductionWithOccurrence {
+ nonTerminalName: string
+ referencedRule: Rule
+ idx: number
+ constructor(options: {
+ nonTerminalName: string
+ referencedRule?: Rule
+ idx?: number
+ })
+ definition: IProduction[]
+ accept(visitor: IGASTVisitor): void
+}
+
+/**
+ * The Grammar AST class used to represent a sequence.
+ * This is normally only used in {@link Alternation} to distinguish
+ * between the different alternatives.
+ */
+export declare class Flat implements IOptionallyNamedProduction {
+ name: string
+ definition: IProduction[]
+
+ constructor(options: { definition: IProduction[]; name?: string })
+
+ accept(visitor: IGASTVisitor): void
+}
+
+/**
+ * The Grammar AST class representing a {@link Parser.OPTION} call.
+ */
+export declare class Option
+ implements IProductionWithOccurrence, IOptionallyNamedProduction {
+ idx: number
+ name?: string
+ definition: IProduction[]
+
+ constructor(options: {
+ definition: IProduction[]
+ idx?: number
+ name?: string
+ })
+
+ accept(visitor: IGASTVisitor): void
+}
+
+/**
+ * The Grammar AST class representing a {@link Parser.AT_LEAST_ONE} call.
+ */
+export declare class RepetitionMandatory
+ implements IProductionWithOccurrence, IOptionallyNamedProduction {
+ name: string
+ idx: number
+ definition: IProduction[]
+
+ constructor(options: {
+ definition: IProduction[]
+ idx?: number
+ name?: string
+ })
+
+ accept(visitor: IGASTVisitor): void
+}
+
+/**
+ * The Grammar AST class representing a {@link Parser.AT_LEAST_ONE_SEP} call.
+ */
+export declare class RepetitionMandatoryWithSeparator
+ implements IProductionWithOccurrence, IOptionallyNamedProduction {
+ separator: TokenType
+ idx: number
+ name: string
+ definition: IProduction[]
+
+ constructor(options: {
+ definition: IProduction[]
+ separator: TokenType
+ idx?: number
+ name?: string
+ })
+
+ accept(visitor: IGASTVisitor): void
+}
+
+/**
+ * The Grammar AST class representing a {@link Parser.MANY} call.
+ */
+export declare class Repetition
+ implements IProductionWithOccurrence, IOptionallyNamedProduction {
+ separator: TokenType
+ idx: number
+ name: string
+ definition: IProduction[]
+
+ constructor(options: {
+ definition: IProduction[]
+ idx?: number
+ name?: string
+ })
+
+ accept(visitor: IGASTVisitor): void
+}
+
+/**
+ * The Grammar AST class representing a {@link Parser.MANY_SEP} call.
+ */
+export declare class RepetitionWithSeparator
+ implements IProductionWithOccurrence, IOptionallyNamedProduction {
+ separator: TokenType
+ idx: number
+ name: string
+ definition: IProduction[]
+
+ constructor(options: {
+ definition: IProduction[]
+ separator: TokenType
+ idx?: number
+ name?: string
+ })
+
+ accept(visitor: IGASTVisitor): void
+}
+
+/**
+ * The Grammar AST class representing a {@link Parser.OR} call.
+ */
+export declare class Alternation
+ implements IProductionWithOccurrence, IOptionallyNamedProduction {
+ idx: number
+ name: string
+ definition: IProduction[]
+
+ constructor(options: {
+ definition: IProduction[]
+ idx?: number
+ name?: string
+ })
+
+ accept(visitor: IGASTVisitor): void
+}
+
+/**
+ * The Grammar AST class representing a {@link Parser.CONSUME} call.
+ */
+export declare class Terminal implements IProductionWithOccurrence {
+ terminalType: TokenType
+ idx: number
+ constructor(options: { terminalType: TokenType; idx?: number })
+ accept(visitor: IGASTVisitor): void
+}
+
+export interface IGASTVisitor {
+ visit(prod: IProduction): any
+}
+
+/**
+ * Serialize a Grammar to a JSON Object.
+ *
+ * This can be useful for scenarios requiring exporting the grammar structure
+ * for example drawing syntax diagrams.
+ */
+export declare function serializeGrammar(topRules: Rule[]): ISerializedGast[]
+
+/**
+ * Like {@link serializeGrammar} but for a single GAST Production instead of a set of Rules.
+ */
+export declare function serializeProduction(node: IProduction): ISerializedGast
+
+/**
+ * A utility to resolve a grammar AST (rules parameter).
+ * "Resolving" means assigning the appropiate value for all {@link NonTerminal.referencedRule}
+ * properties in the grammar AST.
+ *
+ * - See detailed docs for [Custom APIs](http://sap.github.io/chevrotain/docs/guide/custom_apis.html)
+ */
+export declare function resolveGrammar(options: {
+ rules: Rule[]
+ errMsgProvider?: IGrammarResolverErrorMessageProvider
+}): IParserDefinitionError[]
+
+/**
+ * A utility to validate a grammar AST (rules parameter).
+ * For example: left recursion detection, ambiguity detection, ...
+ *
+ * - See detailed docs for [Custom APIs](http://sap.github.io/chevrotain/docs/guide/custom_apis.html)
+ */
+export declare function validateGrammar(options: {
+ rules: Rule[]
+ /**
+ * The maximum lookahead used in the grammar.
+ * This number is needed to perform ambiguity detection.
+ */
+ maxLookahead: number
+ /**
+ * The Token Types used by the grammar.
+ */
+ tokenTypes: TokenType[]
+ grammarName: string
+ errMsgProvider: IGrammarValidatorErrorMessageProvider
+ ignoredIssues?: IgnoredParserIssues
+}): IParserDefinitionError[]
+
+/**
+ * A utility for assigning unique occurence indices to a grammar AST (rules parameter).
+ * This can be useful when using Chevrotain to create custom APIs.
+ *
+ * - FAQ: [Why are these unique occurences needed](http://sap.github.io/chevrotain/docs/FAQ.html#NUMERICAL_SUFFIXES)
+ * - See detailed docs for [Custom APIs](http://sap.github.io/chevrotain/docs/guide/custom_apis.html)
+ */
+export declare function assignOccurrenceIndices(options: {
+ rules: Rule[]
+}): void
+
+/**
+ * The default grammar validations errror message provider used by Chevrotain.
+ * this can be used as the basis for custom error providers when using Chevrotain's
+ * custom APIs.
+ *
+ * - See detailed docs for [Custom APIs](http://sap.github.io/chevrotain/docs/guide/custom_apis.html#grammar-validations)
+ */
+export declare const defaultGrammarValidatorErrorProvider: IGrammarValidatorErrorMessageProvider
+
+/**
+ * The default grammar resolver errror message provider used by Chevrotain.
+ * this can be used as the basis for custom error providers when using Chevrotain's
+ * custom APIs.
+ *
+ * - See detailed docs for [Custom APIs](http://sap.github.io/chevrotain/docs/guide/custom_apis.html#grammar-validations)
+ */
+export declare const defaultGrammarResolverErrorProvider: IGrammarResolverErrorMessageProvider
+
+/**
+ * Implementing this interface enables customizing grammar validation errors
+ * when using custom APIs.
+ *
+ * - See detailed docs for [Custom APIs](http://sap.github.io/chevrotain/docs/guide/custom_apis.html#grammar-validations)
+ */
+export interface IGrammarValidatorErrorMessageProvider {
+ buildDuplicateFoundError(
+ topLevelRule: Rule,
+ duplicateProds: IProductionWithOccurrence[]
+ ): string
+ buildInvalidNestedRuleNameError(
+ topLevelRule: Rule,
+ nestedProd: IOptionallyNamedProduction
+ ): string
+ buildDuplicateNestedRuleNameError(
+ topLevelRule: Rule,
+ nestedProd: IOptionallyNamedProduction[]
+ ): string
+ buildNamespaceConflictError(topLevelRule: Rule): string
+ buildAlternationPrefixAmbiguityError(options: {
+ topLevelRule: Rule
+ prefixPath: TokenType[]
+ ambiguityIndices: number[]
+ alternation: Alternation
+ }): string
+ buildAlternationAmbiguityError(options: {
+ topLevelRule: Rule
+ prefixPath: TokenType[]
+ ambiguityIndices: number[]
+ alternation: Alternation
+ }): string
+ buildEmptyRepetitionError(options: {
+ topLevelRule: Rule
+ repetition: IProductionWithOccurrence
+ }): string
+ buildTokenNameError(options: {
+ tokenType: TokenType
+ expectedPattern: RegExp
+ }): any
+ buildEmptyAlternationError(options: {
+ topLevelRule: Rule
+ alternation: Alternation
+ emptyChoiceIdx: number
+ }): any
+ buildTooManyAlternativesError(options: {
+ topLevelRule: Rule
+ alternation: Alternation
+ }): string
+ buildLeftRecursionError(options: {
+ topLevelRule: Rule
+ leftRecursionPath: Rule[]
+ }): string
+ buildInvalidRuleNameError(options: {
+ topLevelRule: Rule
+ expectedPattern: RegExp
+ }): string
+ buildDuplicateRuleNameError(options: {
+ topLevelRule: Rule | string
+ grammarName: string
+ }): string
+}
+
+/**
+ * Implementing this interface enables customizing grammar resolving errors
+ * when using custom APIs.
+ *
+ * - See detailed docs for [Custom APIs](http://sap.github.io/chevrotain/docs/guide/custom_apis.html#grammar-validations)
+ */
+export interface IGrammarResolverErrorMessageProvider {
+ buildRuleNotFoundError(
+ topLevelRule: Rule,
+ undefinedRule: NonTerminal
+ ): string
+}
+
+/**
+ * Structure of grammar validations errors.
+ *
+ * - See detailed docs for [Custom APIs](http://sap.github.io/chevrotain/docs/guide/custom_apis.html#grammar-validations)
+ */
+export interface IParserDefinitionError {
+ message: string
+ type: ParserDefinitionErrorType
+ ruleName?: string
+}
+
+/**
+ * @deprecated
+ * This function no longer does anything, Avoid using this function
+ * As it will be removed in future versions.
+ */
+export declare function clearCache(): void
+
+/**
+ * Structure of configuration object for {@link createSyntaxDiagramsCode}
+ */
+export interface ICreateSyntaxDiagramsConfig {
+ /**
+ * Base Url to load the runtime resources for rendering the diagrams
+ */
+ resourceBase?: string
+ /**
+ * Url to load the styleSheet, replace with your own for styling customization.
+ */
+ css?: string
+}
+
+/**
+ * Will generate an html source code (text).
+ * This html text will render syntax diagrams for the provided grammar.
+ *
+ * - See detailed docs for [Syntax Diagrams](http://sap.github.io/chevrotain/docs/guide/generating_syntax_diagrams.html).
+ */
+export declare function createSyntaxDiagramsCode(
+ grammar: ISerializedGast[],
+ config?: ICreateSyntaxDiagramsConfig
+): string
+
+/**
+ * Generate A Parser factory from a set of Rules.
+ *
+ * This variant will Create a factory function that once invoked with a IParserConfig will return
+ * a Parser Object.
+ *
+ * - Note that this happens using the Function constructor (a type of "eval") so it will not work in environments
+ * where content security policy is enabled, such as certain websites, Chrome extensions ect...
+ *
+ * This means this function is best used for development flows to reduce the feedback loops
+ * or for productive flows targeting node.js only.
+ *
+ * For productive flows targeting a browser runtime see {@link generateParserModule}.
+ *
+ * - See detailed docs for [Custom APIs](http://sap.github.io/chevrotain/docs/guide/custom_apis.html).
+ */
+export declare function generateParserFactory(options: {
+ name: string
+ rules: Rule[]
+ tokenVocabulary: TokenVocabulary
+}): (config?: IParserConfig) => Parser
+
+/**
+ * Generate A Parser's text from a set of Rules.
+ *
+ * This variant will generate the **string literal** for a UMD module https://github.com/umdjs/umd
+ * That exports a Parser Constructor.
+ *
+ * - Note that the constructor exposed by the generated module must receive the TokenVocabulary as the first
+ * argument, the IParser config can be passed as the second argument.
+ *
+ * - See detailed docs for [Custom APIs](http://sap.github.io/chevrotain/docs/guide/custom_apis.html).
+ */
+export declare function generateParserModule(options: {
+ name: string
+ rules: Rule[]
+}): string
diff --git a/node_modules/chevrotain/lib/chevrotain.js b/node_modules/chevrotain/lib/chevrotain.js
new file mode 100644
index 0000000..8ccabf8
--- /dev/null
+++ b/node_modules/chevrotain/lib/chevrotain.js
@@ -0,0 +1,9785 @@
+/*! chevrotain - v6.5.0 */
+(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, { 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 = 18);
+/******/ })
+/************************************************************************/
+/******/ ([
+/* 0 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+/*
+ 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...
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+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) {
+ /* 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");
+ }
+}
+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 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;
+}
+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;
+/**
+ * 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;
+}
+exports.packArray = packArray;
+function PRINT_ERROR(msg) {
+ /* istanbul ignore else - can't override global.console in node.js */
+ if (console && console.error) {
+ console.error("Error: " + msg);
+ }
+}
+exports.PRINT_ERROR = PRINT_ERROR;
+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);
+ }
+}
+exports.PRINT_WARNING = PRINT_WARNING;
+function isES2015MapSupported() {
+ return typeof Map === "function";
+}
+exports.isES2015MapSupported = isES2015MapSupported;
+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];
+ }
+ });
+ });
+}
+exports.applyMixins = applyMixins;
+// 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);
+}
+exports.toFastProperties = toFastProperties;
+function peek(arr) {
+ return arr[arr.length - 1];
+}
+exports.peek = peek;
+/* 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 };
+}
+exports.timer = timer;
+//# sourceMappingURL=utils.js.map
+
+/***/ }),
+/* 1 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+var tokens_public_1 = __webpack_require__(3);
+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, utils_1.pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ Object.defineProperty(NonTerminal.prototype, "definition", {
+ get: function () {
+ if (this.referencedRule !== undefined) {
+ return this.referencedRule.definition;
+ }
+ return [];
+ },
+ set: function (definition) {
+ // immutable
+ },
+ enumerable: true,
+ configurable: true
+ });
+ NonTerminal.prototype.accept = function (visitor) {
+ visitor.visit(this);
+ // don't visit children of a reference, we will get cyclic infinite loops if we do so
+ };
+ return NonTerminal;
+}(AbstractProduction));
+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, utils_1.pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ return Rule;
+}(AbstractProduction));
+exports.Rule = Rule;
+// TODO: is this only used in an Alternation?
+// Perhaps `Flat` should be renamed to `Alternative`?
+var Flat = /** @class */ (function (_super) {
+ __extends(Flat, _super);
+ // A named Flat production is used to indicate a Nested Rule in an alternation
+ function Flat(options) {
+ var _this = _super.call(this, options.definition) || this;
+ _this.ignoreAmbiguities = false;
+ utils_1.assign(_this, utils_1.pick(options, function (v) { return v !== undefined; }));
+ 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, utils_1.pick(options, function (v) { return v !== undefined; }));
+ 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, utils_1.pick(options, function (v) { return v !== undefined; }));
+ 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, utils_1.pick(options, function (v) { return v !== undefined; }));
+ 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, utils_1.pick(options, function (v) { return v !== undefined; }));
+ 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, utils_1.pick(options, function (v) { return v !== undefined; }));
+ 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;
+ _this.ignoreAmbiguities = false;
+ _this.hasPredicates = false;
+ utils_1.assign(_this, utils_1.pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ return Alternation;
+}(AbstractProduction));
+exports.Alternation = Alternation;
+var Terminal = /** @class */ (function () {
+ function Terminal(options) {
+ this.idx = 1;
+ utils_1.assign(this, utils_1.pick(options, function (v) { return v !== undefined; }));
+ }
+ 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);
+ }
+ /* istanbul ignore else */
+ if (node instanceof NonTerminal) {
+ return {
+ type: "NonTerminal",
+ name: node.nonTerminalName,
+ idx: node.idx
+ };
+ }
+ else if (node instanceof Flat) {
+ return {
+ type: "Flat",
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof Option) {
+ return {
+ type: "Option",
+ idx: node.idx,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof RepetitionMandatory) {
+ return {
+ type: "RepetitionMandatory",
+ name: node.name,
+ idx: node.idx,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof RepetitionMandatoryWithSeparator) {
+ return {
+ type: "RepetitionMandatoryWithSeparator",
+ name: node.name,
+ idx: node.idx,
+ separator: (serializeProduction(new Terminal({ terminalType: node.separator }))),
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof RepetitionWithSeparator) {
+ return {
+ type: "RepetitionWithSeparator",
+ name: node.name,
+ idx: node.idx,
+ separator: (serializeProduction(new Terminal({ terminalType: node.separator }))),
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof Repetition) {
+ return {
+ type: "Repetition",
+ name: node.name,
+ idx: node.idx,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof Alternation) {
+ return {
+ type: "Alternation",
+ name: node.name,
+ idx: node.idx,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof Terminal) {
+ var serializedTerminal = {
+ type: "Terminal",
+ name: node.terminalType.name,
+ label: 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) {
+ return {
+ type: "Rule",
+ name: node.name,
+ orgText: node.orgText,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+exports.serializeProduction = serializeProduction;
+//# sourceMappingURL=gast_public.js.map
+
+/***/ }),
+/* 2 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+var follow_1 = __webpack_require__(27);
+var tokens_public_1 = __webpack_require__(3);
+var cst_1 = __webpack_require__(17);
+var errors_public_1 = __webpack_require__(10);
+var gast_resolver_public_1 = __webpack_require__(24);
+var recoverable_1 = __webpack_require__(25);
+var looksahead_1 = __webpack_require__(30);
+var tree_builder_1 = __webpack_require__(31);
+var lexer_adapter_1 = __webpack_require__(33);
+var recognizer_api_1 = __webpack_require__(34);
+var recognizer_engine_1 = __webpack_require__(35);
+var error_handler_1 = __webpack_require__(36);
+var context_assist_1 = __webpack_require__(37);
+var gast_recorder_1 = __webpack_require__(38);
+var perf_tracer_1 = __webpack_require__(39);
+exports.END_OF_FILE = tokens_public_1.createTokenInstance(tokens_public_1.EOF, "", NaN, NaN, NaN, NaN, NaN, NaN);
+Object.freeze(exports.END_OF_FILE);
+exports.DEFAULT_PARSER_CONFIG = Object.freeze({
+ recoveryEnabled: false,
+ maxLookahead: 4,
+ ignoredIssues: {},
+ dynamicTokensEnabled: false,
+ outputCst: true,
+ errorMessageProvider: errors_public_1.defaultParserErrorProvider,
+ nodeLocationTracking: "none",
+ traceInitPerf: false,
+ skipValidations: false
+});
+exports.DEFAULT_RULE_CONFIG = Object.freeze({
+ recoveryValueFunc: function () { return undefined; },
+ resyncEnabled: true
+});
+var ParserDefinitionErrorType;
+(function (ParserDefinitionErrorType) {
+ ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_NAME"] = 0] = "INVALID_RULE_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_RULE_NAME"] = 1] = "DUPLICATE_RULE_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_OVERRIDE"] = 2] = "INVALID_RULE_OVERRIDE";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_PRODUCTIONS"] = 3] = "DUPLICATE_PRODUCTIONS";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["UNRESOLVED_SUBRULE_REF"] = 4] = "UNRESOLVED_SUBRULE_REF";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["LEFT_RECURSION"] = 5] = "LEFT_RECURSION";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["NONE_LAST_EMPTY_ALT"] = 6] = "NONE_LAST_EMPTY_ALT";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_ALTS"] = 7] = "AMBIGUOUS_ALTS";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["CONFLICT_TOKENS_RULES_NAMESPACE"] = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_TOKEN_NAME"] = 9] = "INVALID_TOKEN_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_NESTED_RULE_NAME"] = 10] = "INVALID_NESTED_RULE_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_NESTED_NAME"] = 11] = "DUPLICATE_NESTED_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["NO_NON_EMPTY_LOOKAHEAD"] = 12] = "NO_NON_EMPTY_LOOKAHEAD";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_PREFIX_ALTS"] = 13] = "AMBIGUOUS_PREFIX_ALTS";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["TOO_MANY_ALTS"] = 14] = "TOO_MANY_ALTS";
+})(ParserDefinitionErrorType = exports.ParserDefinitionErrorType || (exports.ParserDefinitionErrorType = {}));
+function EMPTY_ALT(value) {
+ if (value === void 0) { value = undefined; }
+ return function () {
+ return value;
+ };
+}
+exports.EMPTY_ALT = EMPTY_ALT;
+var Parser = /** @class */ (function () {
+ function Parser(tokenVocabulary, config) {
+ if (config === void 0) { config = exports.DEFAULT_PARSER_CONFIG; }
+ this.ignoredIssues = exports.DEFAULT_PARSER_CONFIG.ignoredIssues;
+ this.definitionErrors = [];
+ this.selfAnalysisDone = false;
+ var that = this;
+ that.initErrorHandler(config);
+ that.initLexerAdapter();
+ that.initLooksAhead(config);
+ that.initRecognizerEngine(tokenVocabulary, config);
+ that.initRecoverable(config);
+ that.initTreeBuilder(config);
+ that.initContentAssist();
+ that.initGastRecorder(config);
+ that.initPerformanceTracer(config);
+ /* istanbul ignore if - complete over-kill to test this, we should only add a test when we actually hard deprecate it and throw an error... */
+ if (utils_1.has(config, "ignoredIssues") &&
+ config.ignoredIssues !== exports.DEFAULT_PARSER_CONFIG.ignoredIssues) {
+ utils_1.PRINT_WARNING("The IParserConfig property is soft-deprecated and will be removed in future versions.\n\t" +
+ "Please use the flag on the relevant DSL method instead.");
+ }
+ this.ignoredIssues = utils_1.has(config, "ignoredIssues")
+ ? config.ignoredIssues
+ : exports.DEFAULT_PARSER_CONFIG.ignoredIssues;
+ this.skipValidations = utils_1.has(config, "skipValidations")
+ ? config.skipValidations
+ : exports.DEFAULT_PARSER_CONFIG.skipValidations;
+ }
+ /**
+ * @deprecated use the **instance** method with the same name instead
+ */
+ Parser.performSelfAnalysis = function (parserInstance) {
+ ;
+ parserInstance.performSelfAnalysis();
+ };
+ Parser.prototype.performSelfAnalysis = function () {
+ var _this = this;
+ this.TRACE_INIT("performSelfAnalysis", function () {
+ var defErrorsMsgs;
+ _this.selfAnalysisDone = true;
+ var className = _this.className;
+ _this.TRACE_INIT("toFastProps", function () {
+ // Without this voodoo magic the parser would be x3-x4 slower
+ // It seems it is better to invoke `toFastProperties` **before**
+ // Any manipulations of the `this` object done during the recording phase.
+ utils_1.toFastProperties(_this);
+ });
+ _this.TRACE_INIT("Grammar Recording", function () {
+ try {
+ _this.enableRecording();
+ // Building the GAST
+ utils_1.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_1.resolveGrammar({
+ rules: utils_1.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 (utils_1.isEmpty(resolverErrors) && _this.skipValidations === false) {
+ var validationErrors = gast_resolver_public_1.validateGrammar({
+ rules: utils_1.values(_this.gastProductionsCache),
+ maxLookahead: _this.maxLookahead,
+ tokenTypes: utils_1.values(_this.tokensMap),
+ ignoredIssues: _this.ignoredIssues,
+ errMsgProvider: errors_public_1.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 (utils_1.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 = follow_1.computeAllProdsFollows(utils_1.values(_this.gastProductionsCache));
+ _this.resyncFollows = allFollows;
+ });
+ }
+ _this.TRACE_INIT("ComputeLookaheadFunctions", function () {
+ _this.preComputeLookaheadFunctions(utils_1.values(_this.gastProductionsCache));
+ });
+ }
+ _this.TRACE_INIT("expandAllNestedRuleNames", function () {
+ // TODO: is this needed for EmbeddedActionsParser?
+ var cstAnalysisResult = cst_1.expandAllNestedRuleNames(utils_1.values(_this.gastProductionsCache), _this.fullRuleNameToShort);
+ _this.allRuleNames = cstAnalysisResult.allRuleNames;
+ });
+ if (!Parser.DEFER_DEFINITION_ERRORS_HANDLING &&
+ !utils_1.isEmpty(_this.definitionErrors)) {
+ defErrorsMsgs = utils_1.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;
+}());
+exports.Parser = Parser;
+utils_1.applyMixins(Parser, [
+ recoverable_1.Recoverable,
+ looksahead_1.LooksAhead,
+ tree_builder_1.TreeBuilder,
+ lexer_adapter_1.LexerAdapter,
+ recognizer_engine_1.RecognizerEngine,
+ recognizer_api_1.RecognizerApi,
+ error_handler_1.ErrorHandler,
+ context_assist_1.ContentAssist,
+ gast_recorder_1.GastRecorder,
+ perf_tracer_1.PerformanceTracer
+]);
+var CstParser = /** @class */ (function (_super) {
+ __extends(CstParser, _super);
+ function CstParser(tokenVocabulary, config) {
+ if (config === void 0) { config = exports.DEFAULT_PARSER_CONFIG; }
+ var _this = this;
+ var configClone = utils_1.cloneObj(config);
+ configClone.outputCst = true;
+ _this = _super.call(this, tokenVocabulary, configClone) || this;
+ return _this;
+ }
+ return CstParser;
+}(Parser));
+exports.CstParser = CstParser;
+var EmbeddedActionsParser = /** @class */ (function (_super) {
+ __extends(EmbeddedActionsParser, _super);
+ function EmbeddedActionsParser(tokenVocabulary, config) {
+ if (config === void 0) { config = exports.DEFAULT_PARSER_CONFIG; }
+ var _this = this;
+ var configClone = utils_1.cloneObj(config);
+ configClone.outputCst = false;
+ _this = _super.call(this, tokenVocabulary, configClone) || this;
+ return _this;
+ }
+ return EmbeddedActionsParser;
+}(Parser));
+exports.EmbeddedActionsParser = EmbeddedActionsParser;
+//# sourceMappingURL=parser.js.map
+
+/***/ }),
+/* 3 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+var lexer_public_1 = __webpack_require__(9);
+var tokens_1 = __webpack_require__(5);
+function tokenLabel(tokType) {
+ if (hasTokenLabel(tokType)) {
+ return tokType.LABEL;
+ }
+ else {
+ return tokType.name;
+ }
+}
+exports.tokenLabel = tokenLabel;
+function tokenName(tokType) {
+ return tokType.name;
+}
+exports.tokenName = tokenName;
+function hasTokenLabel(obj) {
+ return utils_1.isString(obj.LABEL) && obj.LABEL !== "";
+}
+exports.hasTokenLabel = hasTokenLabel;
+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);
+}
+exports.createToken = createToken;
+function createTokenInternal(config) {
+ var pattern = config.pattern;
+ var tokenType = {};
+ tokenType.name = config.name;
+ 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)) {
+ // casting to ANY as this will be fixed inside `augmentTokenTypes``
+ 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];
+ }
+ if (utils_1.has(config, START_CHARS_HINT)) {
+ tokenType.START_CHARS_HINT = config[START_CHARS_HINT];
+ }
+ return tokenType;
+}
+exports.EOF = createToken({ name: "EOF", pattern: lexer_public_1.Lexer.NA });
+tokens_1.augmentTokenTypes([exports.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
+ };
+}
+exports.createTokenInstance = createTokenInstance;
+function tokenMatcher(token, tokType) {
+ return tokens_1.tokenStructuredMatcher(token, tokType);
+}
+exports.tokenMatcher = tokenMatcher;
+//# sourceMappingURL=tokens_public.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) {
+ var nodeAny = node;
+ switch (nodeAny.constructor) {
+ case gast_public_1.NonTerminal:
+ return this.visitNonTerminal(nodeAny);
+ case gast_public_1.Flat:
+ return this.visitFlat(nodeAny);
+ case gast_public_1.Option:
+ return this.visitOption(nodeAny);
+ case gast_public_1.RepetitionMandatory:
+ return this.visitRepetitionMandatory(nodeAny);
+ case gast_public_1.RepetitionMandatoryWithSeparator:
+ return this.visitRepetitionMandatoryWithSeparator(nodeAny);
+ case gast_public_1.RepetitionWithSeparator:
+ return this.visitRepetitionWithSeparator(nodeAny);
+ case gast_public_1.Repetition:
+ return this.visitRepetition(nodeAny);
+ case gast_public_1.Alternation:
+ return this.visitAlternation(nodeAny);
+ case gast_public_1.Terminal:
+ return this.visitTerminal(nodeAny);
+ case gast_public_1.Rule:
+ return this.visitRule(nodeAny);
+ /* istanbul ignore next */
+ default:
+ throw Error("non exhaustive match");
+ }
+ };
+ GAstVisitor.prototype.visitNonTerminal = function (node) { };
+ GAstVisitor.prototype.visitFlat = function (node) { };
+ GAstVisitor.prototype.visitOption = function (node) { };
+ GAstVisitor.prototype.visitRepetition = function (node) { };
+ GAstVisitor.prototype.visitRepetitionMandatory = function (node) { };
+ GAstVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { };
+ GAstVisitor.prototype.visitRepetitionWithSeparator = function (node) { };
+ GAstVisitor.prototype.visitAlternation = function (node) { };
+ GAstVisitor.prototype.visitTerminal = function (node) { };
+ GAstVisitor.prototype.visitRule = function (node) { };
+ return GAstVisitor;
+}());
+exports.GAstVisitor = GAstVisitor;
+//# sourceMappingURL=gast_visitor_public.js.map
+
+/***/ }),
+/* 5 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+function tokenStructuredMatcher(tokInstance, tokConstructor) {
+ var instanceType = tokInstance.tokenTypeIdx;
+ if (instanceType === tokConstructor.tokenTypeIdx) {
+ return true;
+ }
+ else {
+ return (tokConstructor.isParent === true &&
+ tokConstructor.categoryMatchesMap[instanceType] === true);
+ }
+}
+exports.tokenStructuredMatcher = tokenStructuredMatcher;
+// 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;
+}
+exports.tokenStructuredMatcherNoCategories = tokenStructuredMatcherNoCategories;
+exports.tokenShortNameIdx = 1;
+exports.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);
+ utils_1.forEach(tokenTypesAndParents, function (tokType) {
+ tokType.isParent = tokType.categoryMatches.length > 0;
+ });
+}
+exports.augmentTokenTypes = augmentTokenTypes;
+function expandCategories(tokenTypes) {
+ var result = utils_1.cloneArr(tokenTypes);
+ var categories = tokenTypes;
+ var searching = true;
+ while (searching) {
+ categories = utils_1.compact(utils_1.flatten(utils_1.map(categories, function (currTokType) { return currTokType.CATEGORIES; })));
+ var newCategories = utils_1.difference(categories, result);
+ result = result.concat(newCategories);
+ if (utils_1.isEmpty(newCategories)) {
+ searching = false;
+ }
+ else {
+ categories = newCategories;
+ }
+ }
+ return result;
+}
+exports.expandCategories = expandCategories;
+function assignTokenDefaultProps(tokenTypes) {
+ utils_1.forEach(tokenTypes, function (currTokType) {
+ if (!hasShortKeyProperty(currTokType)) {
+ exports.tokenIdxToClass[exports.tokenShortNameIdx] = currTokType;
+ currTokType.tokenTypeIdx = exports.tokenShortNameIdx++;
+ }
+ // CATEGORIES? : TokenType | TokenType[]
+ if (hasCategoriesProperty(currTokType) &&
+ !utils_1.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 = {};
+ }
+ });
+}
+exports.assignTokenDefaultProps = assignTokenDefaultProps;
+function assignCategoriesTokensProp(tokenTypes) {
+ utils_1.forEach(tokenTypes, function (currTokType) {
+ // avoid duplications
+ currTokType.categoryMatches = [];
+ utils_1.forEach(currTokType.categoryMatchesMap, function (val, key) {
+ currTokType.categoryMatches.push(exports.tokenIdxToClass[key].tokenTypeIdx);
+ });
+ });
+}
+exports.assignCategoriesTokensProp = assignCategoriesTokensProp;
+function assignCategoriesMapProp(tokenTypes) {
+ utils_1.forEach(tokenTypes, function (currTokType) {
+ singleAssignCategoriesToksMap([], currTokType);
+ });
+}
+exports.assignCategoriesMapProp = assignCategoriesMapProp;
+function singleAssignCategoriesToksMap(path, nextNode) {
+ utils_1.forEach(path, function (pathNode) {
+ nextNode.categoryMatchesMap[pathNode.tokenTypeIdx] = true;
+ });
+ utils_1.forEach(nextNode.CATEGORIES, function (nextCategory) {
+ var newPath = path.concat(nextNode);
+ // avoids infinite loops due to cyclic categories.
+ if (!utils_1.contains(newPath, nextCategory)) {
+ singleAssignCategoriesToksMap(newPath, nextCategory);
+ }
+ });
+}
+exports.singleAssignCategoriesToksMap = singleAssignCategoriesToksMap;
+function hasShortKeyProperty(tokType) {
+ return utils_1.has(tokType, "tokenTypeIdx");
+}
+exports.hasShortKeyProperty = hasShortKeyProperty;
+function hasCategoriesProperty(tokType) {
+ return utils_1.has(tokType, "CATEGORIES");
+}
+exports.hasCategoriesProperty = hasCategoriesProperty;
+function hasExtendingTokensTypesProperty(tokType) {
+ return utils_1.has(tokType, "categoryMatches");
+}
+exports.hasExtendingTokensTypesProperty = hasExtendingTokensTypesProperty;
+function hasExtendingTokensTypesMapProperty(tokType) {
+ return utils_1.has(tokType, "categoryMatchesMap");
+}
+exports.hasExtendingTokensTypesMapProperty = hasExtendingTokensTypesMapProperty;
+function isTokenType(tokType) {
+ return utils_1.has(tokType, "tokenTypeIdx");
+}
+exports.isTokenType = isTokenType;
+//# sourceMappingURL=tokens.js.map
+
+/***/ }),
+/* 6 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var __extends = (this && this.__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 __());
+ };
+})();
+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);
+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) {
+ /* istanbul ignore else */
+ 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 {
+ throw Error("non exhaustive match");
+ }
+}
+exports.getProductionDslName = getProductionDslName;
+var DslMethodsCollectorVisitor = /** @class */ (function (_super) {
+ __extends(DslMethodsCollectorVisitor, _super);
+ function DslMethodsCollectorVisitor() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ // A minus is never valid in an identifier name
+ _this.separator = "-";
+ _this.dslMethods = {
+ option: [],
+ alternation: [],
+ repetition: [],
+ repetitionWithSeparator: [],
+ repetitionMandatory: [],
+ repetitionMandatoryWithSeparator: []
+ };
+ return _this;
+ }
+ DslMethodsCollectorVisitor.prototype.reset = function () {
+ this.dslMethods = {
+ option: [],
+ alternation: [],
+ repetition: [],
+ repetitionWithSeparator: [],
+ repetitionMandatory: [],
+ repetitionMandatoryWithSeparator: []
+ };
+ };
+ DslMethodsCollectorVisitor.prototype.visitTerminal = function (terminal) {
+ var key = terminal.terminalType.name + this.separator + "Terminal";
+ if (!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;
+var collectorVisitor = new DslMethodsCollectorVisitor();
+function collectMethods(rule) {
+ collectorVisitor.reset();
+ rule.accept(collectorVisitor);
+ var dslMethods = collectorVisitor.dslMethods;
+ // avoid uncleaned references
+ collectorVisitor.reset();
+ return dslMethods;
+}
+exports.collectMethods = collectMethods;
+//# sourceMappingURL=gast.js.map
+
+/***/ }),
+/* 7 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+// 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
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.BITS_FOR_METHOD_TYPE = 4;
+exports.BITS_FOR_OCCURRENCE_IDX = 8;
+exports.BITS_FOR_RULE_IDX = 12;
+// TODO: validation, this means that there may at most 2^8 --> 256 alternatives for an alternation.
+exports.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 */
+exports.OR_IDX = 1 << exports.BITS_FOR_OCCURRENCE_IDX;
+exports.OPTION_IDX = 2 << exports.BITS_FOR_OCCURRENCE_IDX;
+exports.MANY_IDX = 3 << exports.BITS_FOR_OCCURRENCE_IDX;
+exports.AT_LEAST_ONE_IDX = 4 << exports.BITS_FOR_OCCURRENCE_IDX;
+exports.MANY_SEP_IDX = 5 << exports.BITS_FOR_OCCURRENCE_IDX;
+exports.AT_LEAST_ONE_SEP_IDX = 6 << exports.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 */
+}
+exports.getKeyForAutomaticLookahead = getKeyForAutomaticLookahead;
+var BITS_START_FOR_ALT_IDX = 32 - exports.BITS_FOR_ALT_IDX;
+function getKeyForAltIndex(ruleIdx, dslMethodIdx, occurrence, altIdx) {
+ /* tslint:disable */
+ // alternative indices are zero based, thus must always add one (turn on one bit) to guarantee uniqueness.
+ var altIdxBitMap = (altIdx + 1) << BITS_START_FOR_ALT_IDX;
+ return (getKeyForAutomaticLookahead(ruleIdx, dslMethodIdx, occurrence) |
+ altIdxBitMap);
+ /* tslint:enable */
+}
+exports.getKeyForAltIndex = getKeyForAltIndex;
+//# sourceMappingURL=keys.js.map
+
+/***/ }),
+/* 8 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+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 utils_1.contains(RECOGNITION_EXCEPTION_NAMES, error.name);
+}
+exports.isRecognitionException = isRecognitionException;
+function MismatchedTokenException(message, token, previousToken) {
+ this.name = MISMATCHED_TOKEN_EXCEPTION;
+ this.message = message;
+ this.token = token;
+ this.previousToken = previousToken;
+ this.resyncedTokens = [];
+}
+exports.MismatchedTokenException = MismatchedTokenException;
+// 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 = [];
+}
+exports.NoViableAltException = NoViableAltException;
+NoViableAltException.prototype = Error.prototype;
+function NotAllInputParsedException(message, token) {
+ this.name = NOT_ALL_INPUT_PARSED_EXCEPTION;
+ this.message = message;
+ this.token = token;
+ this.resyncedTokens = [];
+}
+exports.NotAllInputParsedException = NotAllInputParsedException;
+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 = [];
+}
+exports.EarlyExitException = EarlyExitException;
+EarlyExitException.prototype = Error.prototype;
+//# sourceMappingURL=exceptions_public.js.map
+
+/***/ }),
+/* 9 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var lexer_1 = __webpack_require__(20);
+var utils_1 = __webpack_require__(0);
+var tokens_1 = __webpack_require__(5);
+var lexer_errors_public_1 = __webpack_require__(21);
+var reg_exp_parser_1 = __webpack_require__(16);
+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 = exports.LexerDefinitionErrorType || (exports.LexerDefinitionErrorType = {}));
+var DEFAULT_LEXER_CONFIG = {
+ deferDefinitionErrorsHandling: false,
+ positionTracking: "full",
+ lineTerminatorsPattern: /\n|\r\n?/g,
+ lineTerminatorCharacters: ["\n", "\r"],
+ ensureOptimizations: false,
+ safeMode: false,
+ errorMessageProvider: lexer_errors_public_1.defaultLexerErrorProvider,
+ traceInitPerf: false,
+ skipValidations: false
+};
+Object.freeze(DEFAULT_LEXER_CONFIG);
+var Lexer = /** @class */ (function () {
+ function Lexer(lexerDefinition, config) {
+ var _this = this;
+ if (config === void 0) { config = DEFAULT_LEXER_CONFIG; }
+ this.lexerDefinition = lexerDefinition;
+ this.lexerDefinitionErrors = [];
+ this.lexerDefinitionWarning = [];
+ this.patternIdxToConfig = {};
+ this.charCodeToPatternIdxToConfig = {};
+ this.modes = [];
+ this.emptyGroups = {};
+ this.config = undefined;
+ this.trackStartLines = true;
+ this.trackEndLines = true;
+ this.hasCustom = false;
+ this.canModeBeOptimized = {};
+ if (typeof config === "boolean") {
+ throw Error("The second argument to the Lexer constructor is now an ILexerConfig Object.\n" +
+ "a boolean 2nd argument is no longer supported");
+ }
+ // todo: defaults func?
+ this.config = utils_1.merge(DEFAULT_LEXER_CONFIG, config);
+ var traceInitVal = this.config.traceInitPerf;
+ if (traceInitVal === true) {
+ this.traceInitMaxIdent = Infinity;
+ this.traceInitPerf = true;
+ }
+ else if (typeof traceInitVal === "number") {
+ this.traceInitMaxIdent = traceInitVal;
+ this.traceInitPerf = true;
+ }
+ this.traceInitIndent = -1;
+ this.TRACE_INIT("Lexer Constructor", function () {
+ var actualDefinition;
+ var hasOnlySingleMode = true;
+ _this.TRACE_INIT("Lexer Config handling", function () {
+ if (_this.config.lineTerminatorsPattern ===
+ DEFAULT_LEXER_CONFIG.lineTerminatorsPattern) {
+ // optimized built-in implementation for the defaults definition of lineTerminators
+ _this.config.lineTerminatorsPattern = lexer_1.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 (utils_1.isArray(lexerDefinition)) {
+ actualDefinition = { modes: {} };
+ actualDefinition.modes[lexer_1.DEFAULT_MODE] = utils_1.cloneArr(lexerDefinition);
+ actualDefinition[lexer_1.DEFAULT_MODE] = lexer_1.DEFAULT_MODE;
+ }
+ else {
+ // no conversion needed, input should already be a IMultiModeLexerDefinition
+ hasOnlySingleMode = false;
+ actualDefinition = utils_1.cloneObj((lexerDefinition));
+ }
+ });
+ if (_this.config.skipValidations === false) {
+ _this.TRACE_INIT("performRuntimeChecks", function () {
+ _this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat(lexer_1.performRuntimeChecks(actualDefinition, _this.trackStartLines, _this.config.lineTerminatorCharacters));
+ });
+ _this.TRACE_INIT("performWarningRuntimeChecks", function () {
+ _this.lexerDefinitionWarning = _this.lexerDefinitionWarning.concat(lexer_1.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.
+ utils_1.forEach(actualDefinition.modes, function (currModeValue, currModeName) {
+ actualDefinition.modes[currModeName] = utils_1.reject(currModeValue, function (currTokType) { return utils_1.isUndefined(currTokType); });
+ });
+ var allModeNames = utils_1.keys(actualDefinition.modes);
+ utils_1.forEach(actualDefinition.modes, function (currModDef, currModName) {
+ _this.TRACE_INIT("Mode: <" + currModName + "> processing", function () {
+ _this.modes.push(currModName);
+ if (_this.config.skipValidations === false) {
+ _this.TRACE_INIT("validatePatterns", function () {
+ _this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat(lexer_1.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 (utils_1.isEmpty(_this.lexerDefinitionErrors)) {
+ tokens_1.augmentTokenTypes(currModDef);
+ var currAnalyzeResult_1;
+ _this.TRACE_INIT("analyzeTokenTypes", function () {
+ currAnalyzeResult_1 = lexer_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 = utils_1.merge(_this.emptyGroups, currAnalyzeResult_1.emptyGroups);
+ _this.hasCustom =
+ currAnalyzeResult_1.hasCustom || _this.hasCustom;
+ _this.canModeBeOptimized[currModName] =
+ currAnalyzeResult_1.canBeOptimized;
+ }
+ });
+ });
+ _this.defaultMode = actualDefinition.defaultMode;
+ if (!utils_1.isEmpty(_this.lexerDefinitionErrors) &&
+ !_this.config.deferDefinitionErrorsHandling) {
+ var allErrMessages = utils_1.map(_this.lexerDefinitionErrors, function (error) {
+ return error.message;
+ });
+ var allErrMessagesString = allErrMessages.join("-----------------------\n");
+ throw new Error("Errors detected in definition of Lexer:\n" +
+ allErrMessagesString);
+ }
+ // Only print warning if there are no errors, This will avoid pl
+ utils_1.forEach(_this.lexerDefinitionWarning, function (warningDescriptor) {
+ utils_1.PRINT_WARNING(warningDescriptor.message);
+ });
+ _this.TRACE_INIT("Choosing sub-methods implementations", function () {
+ // Choose the relevant internal implementations for this specific parser.
+ // These implementations should be in-lined by the JavaScript engine
+ // to provide optimal performance in each scenario.
+ if (lexer_1.SUPPORT_STICKY) {
+ _this.chopInput = utils_1.IDENTITY;
+ _this.match = _this.matchWithTest;
+ }
+ else {
+ _this.updateLastIndex = utils_1.NOOP;
+ _this.match = _this.matchWithExec;
+ }
+ if (hasOnlySingleMode) {
+ _this.handleModes = utils_1.NOOP;
+ }
+ if (_this.trackStartLines === false) {
+ _this.computeNewColumn = utils_1.IDENTITY;
+ }
+ if (_this.trackEndLines === false) {
+ _this.updateTokenEndLineColumnLocation = utils_1.NOOP;
+ }
+ if (/full/i.test(_this.config.positionTracking)) {
+ _this.createTokenInstance = _this.createFullToken;
+ }
+ else if (/onlyStart/i.test(_this.config.positionTracking)) {
+ _this.createTokenInstance = _this.createStartOnlyToken;
+ }
+ else if (/onlyOffset/i.test(_this.config.positionTracking)) {
+ _this.createTokenInstance = _this.createOffsetOnlyToken;
+ }
+ else {
+ throw Error("Invalid 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 = utils_1.reduce(_this.canModeBeOptimized, function (cannotBeOptimized, canBeOptimized, modeName) {
+ if (canBeOptimized === false) {
+ cannotBeOptimized.push(modeName);
+ }
+ return cannotBeOptimized;
+ }, []);
+ if (config.ensureOptimizations && !utils_1.isEmpty(unOptimizedModes)) {
+ throw Error("Lexer Modes: < " + unOptimizedModes.join(", ") + " > cannot be optimized.\n" +
+ '\t Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.\n' +
+ "\t Or inspect the console log for details on how to resolve these issues.");
+ }
+ });
+ _this.TRACE_INIT("clearRegExpParserCache", function () {
+ reg_exp_parser_1.clearRegExpParserCache();
+ });
+ _this.TRACE_INIT("toFastProperties", function () {
+ utils_1.toFastProperties(_this);
+ });
+ });
+ }
+ Lexer.prototype.tokenize = function (text, initialMode) {
+ if (initialMode === void 0) { initialMode = this.defaultMode; }
+ if (!utils_1.isEmpty(this.lexerDefinitionErrors)) {
+ var allErrMessages = utils_1.map(this.lexerDefinitionErrors, function (error) {
+ return error.message;
+ });
+ var allErrMessagesString = allErrMessages.join("-----------------------\n");
+ throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n" +
+ allErrMessagesString);
+ }
+ var lexResult = this.tokenizeInternal(text, initialMode);
+ return lexResult;
+ };
+ // There is quite a bit of duplication between this and "tokenizeInternalLazy"
+ // This is intentional due to performance considerations.
+ Lexer.prototype.tokenizeInternal = function (text, initialMode) {
+ var _this = this;
+ var i, j, matchAltImage, longerAltIdx, matchedImage, payload, altPayload, imageLength, group, tokType, newToken, errLength, droppedChar, msg, match;
+ var orgText = text;
+ var orgLength = orgText.length;
+ var offset = 0;
+ var matchedTokensIndex = 0;
+ // initializing the tokensArray to the "guessed" size.
+ // guessing too little will still reduce the number of array re-sizes on pushes.
+ // guessing too large (Tested by guessing x4 too large) may cost a bit more of memory
+ // but would still have a faster runtime by avoiding (All but one) array resizing.
+ var guessedNumberOfTokens = this.hasCustom
+ ? 0 // will break custom token pattern APIs the matchedTokens array will contain undefined elements.
+ : Math.floor(text.length / 10);
+ var matchedTokens = new Array(guessedNumberOfTokens);
+ var errors = [];
+ var line = this.trackStartLines ? 1 : undefined;
+ var column = this.trackStartLines ? 1 : undefined;
+ var groups = lexer_1.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 = lexer_1.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 = utils_1.last(modeStack);
+ patternIdxToConfig = _this.patternIdxToConfig[newMode];
+ currCharCodeToPatternIdxToConfig = _this
+ .charCodeToPatternIdxToConfig[newMode];
+ currModePatternsLength = patternIdxToConfig.length;
+ var modeCanBeOptimized = _this.canModeBeOptimized[newMode] &&
+ _this.config.safeMode === false;
+ if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {
+ getPossiblePatterns = getPossiblePatternsOptimized;
+ }
+ else {
+ getPossiblePatterns = getPossiblePatternsSlow;
+ }
+ }
+ };
+ function push_mode(newMode) {
+ modeStack.push(newMode);
+ currCharCodeToPatternIdxToConfig = this
+ .charCodeToPatternIdxToConfig[newMode];
+ patternIdxToConfig = this.patternIdxToConfig[newMode];
+ currModePatternsLength = patternIdxToConfig.length;
+ currModePatternsLength = patternIdxToConfig.length;
+ var modeCanBeOptimized = this.canModeBeOptimized[newMode] &&
+ this.config.safeMode === false;
+ if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {
+ getPossiblePatterns = getPossiblePatternsOptimized;
+ }
+ else {
+ getPossiblePatterns = getPossiblePatternsSlow;
+ }
+ }
+ // this pattern seems to avoid a V8 de-optimization, although that de-optimization does not
+ // seem to matter performance wise.
+ push_mode.call(this, initialMode);
+ var currConfig;
+ while (offset < orgLength) {
+ matchedImage = null;
+ var nextCharCode = orgText.charCodeAt(offset);
+ var chosenPatternIdxToConfig = getPossiblePatterns(nextCharCode);
+ var chosenPatternsLength = chosenPatternIdxToConfig.length;
+ for (i = 0; i < chosenPatternsLength; i++) {
+ currConfig = chosenPatternIdxToConfig[i];
+ var currPattern = currConfig.pattern;
+ payload = null;
+ // manually in-lined because > 600 chars won't be in-lined in V8
+ var singleCharCode = currConfig.short;
+ if (singleCharCode !== false) {
+ if (nextCharCode === singleCharCode) {
+ // single character string
+ matchedImage = currPattern;
+ }
+ }
+ else if (currConfig.isCustom === true) {
+ match = currPattern.exec(orgText, offset, matchedTokens, groups);
+ if (match !== null) {
+ matchedImage = match[0];
+ if (match.payload !== undefined) {
+ payload = match.payload;
+ }
+ }
+ else {
+ matchedImage = null;
+ }
+ }
+ else {
+ this.updateLastIndex(currPattern, offset);
+ matchedImage = this.match(currPattern, text, offset);
+ }
+ if (matchedImage !== null) {
+ // even though this pattern matched we must try a another longer alternative.
+ // this can be used to prioritize keywords over identifiers
+ longerAltIdx = currConfig.longerAlt;
+ if (longerAltIdx !== undefined) {
+ // TODO: micro optimize, avoid extra prop access
+ // by saving/linking longerAlt on the original config?
+ var longerAltConfig = patternIdxToConfig[longerAltIdx];
+ var longerAltPattern = longerAltConfig.pattern;
+ altPayload = null;
+ // single Char can never be a longer alt so no need to test it.
+ // manually in-lined because > 600 chars won't be in-lined in V8
+ if (longerAltConfig.isCustom === true) {
+ match = longerAltPattern.exec(orgText, offset, matchedTokens, groups);
+ if (match !== null) {
+ matchAltImage = match[0];
+ if (match.payload !== undefined) {
+ altPayload = match.payload;
+ }
+ }
+ else {
+ matchAltImage = null;
+ }
+ }
+ else {
+ this.updateLastIndex(longerAltPattern, offset);
+ matchAltImage = this.match(longerAltPattern, text, offset);
+ }
+ if (matchAltImage &&
+ matchAltImage.length > matchedImage.length) {
+ matchedImage = matchAltImage;
+ payload = altPayload;
+ currConfig = longerAltConfig;
+ }
+ }
+ break;
+ }
+ }
+ // successful match
+ if (matchedImage !== null) {
+ imageLength = matchedImage.length;
+ group = currConfig.group;
+ if (group !== undefined) {
+ tokType = currConfig.tokenTypeIdx;
+ // TODO: "offset + imageLength" and the new column may be computed twice in case of "full" location information inside
+ // createFullToken method
+ newToken = this.createTokenInstance(matchedImage, offset, tokType, currConfig.tokenType, line, column, imageLength);
+ this.handlePayload(newToken, payload);
+ // TODO: optimize NOOP in case there are no special groups?
+ if (group === false) {
+ matchedTokensIndex = this.addToken(matchedTokens, matchedTokensIndex, newToken);
+ }
+ else {
+ groups[group].push(newToken);
+ }
+ }
+ text = this.chopInput(text, imageLength);
+ offset = offset + imageLength;
+ // TODO: with newlines the column may be assigned twice
+ column = this.computeNewColumn(column, imageLength);
+ if (trackLines === true &&
+ currConfig.canLineTerminator === true) {
+ var numOfLTsInMatch = 0;
+ var foundTerminator = void 0;
+ var lastLTEndOffset = void 0;
+ lineTerminatorPattern.lastIndex = 0;
+ do {
+ foundTerminator = lineTerminatorPattern.test(matchedImage);
+ if (foundTerminator === true) {
+ lastLTEndOffset =
+ lineTerminatorPattern.lastIndex - 1;
+ numOfLTsInMatch++;
+ }
+ } while (foundTerminator === true);
+ if (numOfLTsInMatch !== 0) {
+ line = line + numOfLTsInMatch;
+ column = imageLength - lastLTEndOffset;
+ this.updateTokenEndLineColumnLocation(newToken, group, lastLTEndOffset, numOfLTsInMatch, line, column, imageLength);
+ }
+ }
+ // will be NOOP if no modes present
+ this.handleModes(currConfig, pop_mode, push_mode, newToken);
+ }
+ else {
+ // error recovery, drop characters until we identify a valid token's start point
+ var errorStartOffset = offset;
+ var errorLine = line;
+ var errorColumn = column;
+ var foundResyncPoint = false;
+ while (!foundResyncPoint && offset < orgLength) {
+ // drop chars until we succeed in matching something
+ droppedChar = orgText.charCodeAt(offset);
+ // Identity Func (when sticky flag is enabled)
+ text = this.chopInput(text, 1);
+ offset++;
+ for (j = 0; j < currModePatternsLength; j++) {
+ var currConfig_1 = patternIdxToConfig[j];
+ var currPattern = currConfig_1.pattern;
+ // manually in-lined because > 600 chars won't be in-lined in V8
+ var singleCharCode = currConfig_1.short;
+ if (singleCharCode !== false) {
+ if (orgText.charCodeAt(offset) === singleCharCode) {
+ // single character string
+ foundResyncPoint = true;
+ }
+ }
+ else if (currConfig_1.isCustom === true) {
+ foundResyncPoint =
+ currPattern.exec(orgText, offset, matchedTokens, groups) !== null;
+ }
+ else {
+ this.updateLastIndex(currPattern, offset);
+ foundResyncPoint = currPattern.exec(text) !== null;
+ }
+ if (foundResyncPoint === true) {
+ break;
+ }
+ }
+ }
+ errLength = offset - errorStartOffset;
+ // at this point we either re-synced or reached the end of the input text
+ msg = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(orgText, errorStartOffset, errLength, errorLine, errorColumn);
+ errors.push({
+ offset: errorStartOffset,
+ line: errorLine,
+ column: errorColumn,
+ length: errLength,
+ message: msg
+ });
+ }
+ }
+ // if we do have custom patterns which push directly into the
+ // TODO: custom tokens should not push directly??
+ if (!this.hasCustom) {
+ // if we guessed a too large size for the tokens array this will shrink it to the right size.
+ matchedTokens.length = matchedTokensIndex;
+ }
+ return {
+ tokens: matchedTokens,
+ groups: groups,
+ errors: errors
+ };
+ };
+ Lexer.prototype.handleModes = function (config, pop_mode, push_mode, newToken) {
+ if (config.pop === true) {
+ // need to save the PUSH_MODE property as if the mode is popped
+ // patternIdxToPopMode is updated to reflect the new mode after popping the stack
+ var pushMode = config.push;
+ pop_mode(newToken);
+ if (pushMode !== undefined) {
+ push_mode.call(this, pushMode);
+ }
+ }
+ else if (config.push !== undefined) {
+ push_mode.call(this, config.push);
+ }
+ };
+ Lexer.prototype.chopInput = function (text, length) {
+ return text.substring(length);
+ };
+ Lexer.prototype.updateLastIndex = function (regExp, newLastIndex) {
+ regExp.lastIndex = newLastIndex;
+ };
+ // TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler
+ Lexer.prototype.updateTokenEndLineColumnLocation = function (newToken, group, lastLTIdx, numOfLTsInMatch, line, column, imageLength) {
+ var lastCharIsLT, fixForEndingInLT;
+ if (group !== undefined) {
+ // a none skipped multi line Token, need to update endLine/endColumn
+ lastCharIsLT = lastLTIdx === imageLength - 1;
+ fixForEndingInLT = lastCharIsLT ? -1 : 0;
+ if (!(numOfLTsInMatch === 1 && lastCharIsLT === true)) {
+ // if a token ends in a LT that last LT only affects the line numbering of following Tokens
+ newToken.endLine = line + fixForEndingInLT;
+ // the last LT in a token does not affect the endColumn either as the [columnStart ... columnEnd)
+ // inclusive to exclusive range.
+ newToken.endColumn = column - 1 + -fixForEndingInLT;
+ }
+ // else single LT in the last character of a token, no need to modify the endLine/EndColumn
+ }
+ };
+ Lexer.prototype.computeNewColumn = function (oldColumn, imageLength) {
+ return oldColumn + imageLength;
+ };
+ // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime.
+ /* istanbul ignore next - place holder */
+ Lexer.prototype.createTokenInstance = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ return null;
+ };
+ Lexer.prototype.createOffsetOnlyToken = function (image, startOffset, tokenTypeIdx, tokenType) {
+ return {
+ image: image,
+ startOffset: startOffset,
+ tokenTypeIdx: tokenTypeIdx,
+ tokenType: tokenType
+ };
+ };
+ Lexer.prototype.createStartOnlyToken = function (image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn) {
+ return {
+ image: image,
+ startOffset: startOffset,
+ startLine: startLine,
+ startColumn: startColumn,
+ tokenTypeIdx: tokenTypeIdx,
+ tokenType: tokenType
+ };
+ };
+ Lexer.prototype.createFullToken = function (image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn, imageLength) {
+ return {
+ image: image,
+ startOffset: startOffset,
+ endOffset: startOffset + imageLength - 1,
+ startLine: startLine,
+ endLine: startLine,
+ startColumn: startColumn,
+ endColumn: startColumn + imageLength - 1,
+ tokenTypeIdx: tokenTypeIdx,
+ tokenType: tokenType
+ };
+ };
+ // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime.
+ /* istanbul ignore next - place holder */
+ Lexer.prototype.addToken = function (tokenVector, index, tokenToAdd) {
+ return 666;
+ };
+ Lexer.prototype.addTokenUsingPush = function (tokenVector, index, tokenToAdd) {
+ tokenVector.push(tokenToAdd);
+ return index;
+ };
+ Lexer.prototype.addTokenUsingMemberAccess = function (tokenVector, index, tokenToAdd) {
+ tokenVector[index] = tokenToAdd;
+ index++;
+ return index;
+ };
+ // Place holder, will be replaced by the correct variant according to the hasCustom flag option at runtime.
+ /* istanbul ignore next - place holder */
+ Lexer.prototype.handlePayload = function (token, payload) { };
+ Lexer.prototype.handlePayloadNoCustom = function (token, payload) { };
+ Lexer.prototype.handlePayloadWithCustom = function (token, payload) {
+ if (payload !== null) {
+ token.payload = payload;
+ }
+ };
+ /* istanbul ignore next - place holder to be replaced with chosen alternative at runtime */
+ Lexer.prototype.match = function (pattern, text, offset) {
+ return null;
+ };
+ Lexer.prototype.matchWithTest = function (pattern, text, offset) {
+ var found = pattern.test(text);
+ if (found === true) {
+ return text.substring(offset, pattern.lastIndex);
+ }
+ return null;
+ };
+ Lexer.prototype.matchWithExec = function (pattern, text) {
+ var regExpArray = pattern.exec(text);
+ return regExpArray !== null ? regExpArray[0] : regExpArray;
+ };
+ // Duplicated from the parser's perf trace trait to allow future extraction
+ // of the lexer to a separate package.
+ Lexer.prototype.TRACE_INIT = function (phaseDesc, phaseImpl) {
+ // No need to optimize this using NOOP pattern because
+ // It is not called in a hot spot...
+ if (this.traceInitPerf === true) {
+ this.traceInitIndent++;
+ var indent = new Array(this.traceInitIndent + 1).join("\t");
+ if (this.traceInitIndent < this.traceInitMaxIdent) {
+ console.log(indent + "--> <" + phaseDesc + ">");
+ }
+ var _a = utils_1.timer(phaseImpl), time = _a.time, value = _a.value;
+ /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */
+ var traceMethod = time > 10 ? console.warn : console.log;
+ if (this.traceInitIndent < this.traceInitMaxIdent) {
+ traceMethod(indent + "<-- <" + phaseDesc + "> time: " + time + "ms");
+ }
+ this.traceInitIndent--;
+ return value;
+ }
+ else {
+ return phaseImpl();
+ }
+ };
+ Lexer.SKIPPED = "This marks a skipped Token pattern, this means each token identified by it will" +
+ "be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.";
+ Lexer.NA = /NOT_APPLICABLE/;
+ return Lexer;
+}());
+exports.Lexer = Lexer;
+//# sourceMappingURL=lexer_public.js.map
+
+/***/ }),
+/* 10 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var tokens_public_1 = __webpack_require__(3);
+var utils = __webpack_require__(0);
+var utils_1 = __webpack_require__(0);
+var gast_public_1 = __webpack_require__(1);
+var gast_1 = __webpack_require__(6);
+var checks_1 = __webpack_require__(11);
+exports.defaultParserErrorProvider = {
+ buildMismatchTokenMessage: function (_a) {
+ var expected = _a.expected, actual = _a.actual, previous = _a.previous, ruleName = _a.ruleName;
+ var hasLabel = tokens_public_1.hasTokenLabel(expected);
+ var expectedMsg = hasLabel
+ ? "--> " + tokens_public_1.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 = 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 prod.terminalType.name;
+ }
+ 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 hasExplicitIndex = index > 0;
+ var msg = "->" + dslName + (hasExplicitIndex ? index : "") + "<- " + (extraArgument ? "with argument: ->" + extraArgument + "<-" : "") + "\n appears more than once (" + duplicateProds.length + " times) in the top level rule: ->" + topLevelName + "<-. \n For further details see: https://sap.github.io/chevrotain/docs/FAQ.html#NUMERICAL_SUFFIXES \n ";
+ // white space trimming time! better to trim afterwards as it allows to use WELL formatted multi line template strings...
+ msg = msg.replace(/[ \t]+/g, " ");
+ msg = msg.replace(/\s\s+/g, "\n");
+ return msg;
+ },
+ buildInvalidNestedRuleNameError: function (topLevelRule, nestedProd) {
+ var msg = "Invalid nested rule name: ->" + nestedProd.name + "<- inside rule: ->" + topLevelRule.name + "<-\n" +
+ ("it must match the pattern: ->" + 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: 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 = utils_1.map(options.prefixPath, function (currTok) {
+ return tokens_public_1.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 = utils_1.map(options.prefixPath, function (currtok) {
+ return tokens_public_1.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 = gast_1.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.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_1.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
+
+/***/ }),
+/* 11 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils = __webpack_require__(0);
+var utils_1 = __webpack_require__(0);
+var parser_1 = __webpack_require__(2);
+var gast_1 = __webpack_require__(6);
+var lookahead_1 = __webpack_require__(12);
+var cst_1 = __webpack_require__(17);
+var interpreter_1 = __webpack_require__(13);
+var gast_public_1 = __webpack_require__(1);
+var gast_visitor_public_1 = __webpack_require__(4);
+function validateGrammar(topLevels, globalMaxLookahead, tokenTypes, ignoredIssues, errMsgProvider, grammarName) {
+ var duplicateErrors = utils.map(topLevels, function (currTopLevel) {
+ return validateDuplicateProductions(currTopLevel, errMsgProvider);
+ });
+ var leftRecursionErrors = utils.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 (utils_1.every(leftRecursionErrors, utils_1.isEmpty)) {
+ emptyAltErrors = utils_1.map(topLevels, function (currTopRule) {
+ return validateEmptyOrAlternative(currTopRule, errMsgProvider);
+ });
+ ambiguousAltsErrors = utils_1.map(topLevels, function (currTopRule) {
+ return validateAmbiguousAlternationAlternatives(currTopRule, globalMaxLookahead, ignoredIssues, errMsgProvider);
+ });
+ emptyRepetitionErrors = validateSomeNonEmptyLookaheadPath(topLevels, globalMaxLookahead, errMsgProvider);
+ }
+ var termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider);
+ var tokenNameErrors = utils.map(tokenTypes, function (currTokType) {
+ return validateTokenName(currTokType, errMsgProvider);
+ });
+ var nestedRulesNameErrors = validateNestedRulesNames(topLevels, errMsgProvider);
+ var nestedRulesDuplicateErrors = validateDuplicateNestedRules(topLevels, errMsgProvider);
+ var tooManyAltsErrors = utils_1.map(topLevels, function (curRule) {
+ return validateTooManyAlts(curRule, errMsgProvider);
+ });
+ var ruleNameErrors = utils_1.map(topLevels, function (curRule) {
+ return validateRuleName(curRule, errMsgProvider);
+ });
+ var duplicateRulesError = utils_1.map(topLevels, function (curRule) {
+ return validateRuleDoesNotAlreadyExist(curRule, topLevels, grammarName, errMsgProvider);
+ });
+ return (utils.flatten(duplicateErrors.concat(tokenNameErrors, nestedRulesNameErrors, nestedRulesDuplicateErrors, emptyRepetitionErrors, leftRecursionErrors, emptyAltErrors, ambiguousAltsErrors, termsNamespaceConflictErrors, tooManyAltsErrors, ruleNameErrors, duplicateRulesError)));
+}
+exports.validateGrammar = validateGrammar;
+function validateNestedRulesNames(topLevels, errMsgProvider) {
+ var result = [];
+ utils_1.forEach(topLevels, function (curTopLevel) {
+ var namedCollectorVisitor = new cst_1.NamedDSLMethodsCollectorVisitor("");
+ curTopLevel.accept(namedCollectorVisitor);
+ var nestedProds = utils_1.map(namedCollectorVisitor.result, function (currItem) { return currItem.orgProd; });
+ result.push(utils_1.map(nestedProds, function (currNestedProd) {
+ return validateNestedRuleName(curTopLevel, currNestedProd, errMsgProvider);
+ }));
+ });
+ return utils_1.flatten(result);
+}
+function validateDuplicateProductions(topLevelRule, errMsgProvider) {
+ var collectorVisitor = new OccurrenceValidationCollector();
+ topLevelRule.accept(collectorVisitor);
+ var allRuleProductions = collectorVisitor.allProductions;
+ var productionGroups = utils.groupBy(allRuleProductions, identifyProductionForDuplicates);
+ var duplicates = utils.pick(productionGroups, function (currGroup) {
+ return currGroup.length > 1;
+ });
+ var errors = utils.map(utils.values(duplicates), function (currDuplicates) {
+ var firstProd = utils.first(currDuplicates);
+ var msg = errMsgProvider.buildDuplicateFoundError(topLevelRule, currDuplicates);
+ var dslName = gast_1.getProductionDslName(firstProd);
+ var defError = {
+ message: msg,
+ type: parser_1.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,
+ ruleName: topLevelRule.name,
+ dslName: dslName,
+ occurrence: firstProd.idx
+ };
+ var param = getExtraProductionArgument(firstProd);
+ if (param) {
+ defError.parameter = param;
+ }
+ return defError;
+ });
+ return errors;
+}
+function identifyProductionForDuplicates(prod) {
+ return gast_1.getProductionDslName(prod) + "_#_" + prod.idx + "_#_" + getExtraProductionArgument(prod);
+}
+exports.identifyProductionForDuplicates = identifyProductionForDuplicates;
+function getExtraProductionArgument(prod) {
+ if (prod instanceof gast_public_1.Terminal) {
+ return prod.terminalType.name;
+ }
+ else if (prod instanceof gast_public_1.NonTerminal) {
+ return prod.nonTerminalName;
+ }
+ else {
+ return "";
+ }
+}
+var OccurrenceValidationCollector = /** @class */ (function (_super) {
+ __extends(OccurrenceValidationCollector, _super);
+ function OccurrenceValidationCollector() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.allProductions = [];
+ return _this;
+ }
+ OccurrenceValidationCollector.prototype.visitNonTerminal = function (subrule) {
+ this.allProductions.push(subrule);
+ };
+ OccurrenceValidationCollector.prototype.visitOption = function (option) {
+ this.allProductions.push(option);
+ };
+ OccurrenceValidationCollector.prototype.visitRepetitionWithSeparator = function (manySep) {
+ this.allProductions.push(manySep);
+ };
+ OccurrenceValidationCollector.prototype.visitRepetitionMandatory = function (atLeastOne) {
+ this.allProductions.push(atLeastOne);
+ };
+ OccurrenceValidationCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) {
+ this.allProductions.push(atLeastOneSep);
+ };
+ OccurrenceValidationCollector.prototype.visitRepetition = function (many) {
+ this.allProductions.push(many);
+ };
+ OccurrenceValidationCollector.prototype.visitAlternation = function (or) {
+ this.allProductions.push(or);
+ };
+ OccurrenceValidationCollector.prototype.visitTerminal = function (terminal) {
+ this.allProductions.push(terminal);
+ };
+ return OccurrenceValidationCollector;
+}(gast_visitor_public_1.GAstVisitor));
+exports.OccurrenceValidationCollector = OccurrenceValidationCollector;
+exports.validTermsPattern = /^[a-zA-Z_]\w*$/;
+exports.validNestedRuleName = new RegExp(exports.validTermsPattern.source.replace("^", "^\\$"));
+// TODO: remove this limitation now that we use recorders
+function validateRuleName(rule, errMsgProvider) {
+ var errors = [];
+ var ruleName = rule.name;
+ if (!ruleName.match(exports.validTermsPattern)) {
+ errors.push({
+ message: errMsgProvider.buildInvalidRuleNameError({
+ topLevelRule: rule,
+ expectedPattern: exports.validTermsPattern
+ }),
+ type: parser_1.ParserDefinitionErrorType.INVALID_RULE_NAME,
+ ruleName: ruleName
+ });
+ }
+ return errors;
+}
+exports.validateRuleName = validateRuleName;
+// TODO: did the nested rule name regExp now change?
+function validateNestedRuleName(topLevel, nestedProd, errMsgProvider) {
+ var errors = [];
+ var errMsg;
+ if (!nestedProd.name.match(exports.validNestedRuleName)) {
+ errMsg = errMsgProvider.buildInvalidNestedRuleNameError(topLevel, nestedProd);
+ errors.push({
+ message: errMsg,
+ type: parser_1.ParserDefinitionErrorType.INVALID_NESTED_RULE_NAME,
+ ruleName: topLevel.name
+ });
+ }
+ return errors;
+}
+exports.validateNestedRuleName = validateNestedRuleName;
+// TODO: remove this limitation now that we use recorders
+function validateTokenName(tokenType, errMsgProvider) {
+ var errors = [];
+ var tokTypeName = tokenType.name;
+ if (!tokTypeName.match(exports.validTermsPattern)) {
+ errors.push({
+ message: errMsgProvider.buildTokenNameError({
+ tokenType: tokenType,
+ expectedPattern: exports.validTermsPattern
+ }),
+ type: parser_1.ParserDefinitionErrorType.INVALID_TOKEN_NAME
+ });
+ }
+ return errors;
+}
+exports.validateTokenName = validateTokenName;
+function validateRuleDoesNotAlreadyExist(rule, allRules, className, errMsgProvider) {
+ var errors = [];
+ var occurrences = utils_1.reduce(allRules, function (result, curRule) {
+ if (curRule.name === rule.name) {
+ return result + 1;
+ }
+ return result;
+ }, 0);
+ if (occurrences > 1) {
+ var errMsg = errMsgProvider.buildDuplicateRuleNameError({
+ topLevelRule: rule,
+ grammarName: className
+ });
+ errors.push({
+ message: errMsg,
+ type: parser_1.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,
+ ruleName: rule.name
+ });
+ }
+ return errors;
+}
+exports.validateRuleDoesNotAlreadyExist = validateRuleDoesNotAlreadyExist;
+// 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.contains(definedRulesNames, ruleName)) {
+ errMsg =
+ "Invalid rule override, rule: ->" + ruleName + "<- cannot be overridden in the grammar: ->" + className + "<-" +
+ "as it is not defined in any of the super grammars ";
+ errors.push({
+ message: errMsg,
+ type: parser_1.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,
+ ruleName: ruleName
+ });
+ }
+ return errors;
+}
+exports.validateRuleIsOverridden = validateRuleIsOverridden;
+function validateNoLeftRecursion(topRule, currRule, errMsgProvider, path) {
+ if (path === void 0) { path = []; }
+ var errors = [];
+ var nextNonTerminals = getFirstNoneTerminal(currRule.definition);
+ if (utils.isEmpty(nextNonTerminals)) {
+ return [];
+ }
+ else {
+ var ruleName = topRule.name;
+ var foundLeftRecursion = utils.contains(nextNonTerminals, topRule);
+ if (foundLeftRecursion) {
+ errors.push({
+ message: errMsgProvider.buildLeftRecursionError({
+ topLevelRule: topRule,
+ leftRecursionPath: path
+ }),
+ type: parser_1.ParserDefinitionErrorType.LEFT_RECURSION,
+ ruleName: ruleName
+ });
+ }
+ // we are only looking for cyclic paths leading back to the specific topRule
+ // other cyclic paths are ignored, we still need this difference to avoid infinite loops...
+ var validNextSteps = utils.difference(nextNonTerminals, path.concat([topRule]));
+ var errorsFromNextSteps = utils.map(validNextSteps, function (currRefRule) {
+ var newPath = utils.cloneArr(path);
+ newPath.push(currRefRule);
+ return validateNoLeftRecursion(topRule, currRefRule, errMsgProvider, newPath);
+ });
+ return errors.concat(utils.flatten(errorsFromNextSteps));
+ }
+}
+exports.validateNoLeftRecursion = validateNoLeftRecursion;
+function getFirstNoneTerminal(definition) {
+ var result = [];
+ if (utils.isEmpty(definition)) {
+ return result;
+ }
+ var firstProd = utils.first(definition);
+ /* istanbul ignore else */
+ if (firstProd instanceof gast_public_1.NonTerminal) {
+ result.push(firstProd.referencedRule);
+ }
+ else if (firstProd instanceof gast_public_1.Flat ||
+ firstProd instanceof gast_public_1.Option ||
+ firstProd instanceof gast_public_1.RepetitionMandatory ||
+ firstProd instanceof gast_public_1.RepetitionMandatoryWithSeparator ||
+ firstProd instanceof gast_public_1.RepetitionWithSeparator ||
+ firstProd instanceof gast_public_1.Repetition) {
+ result = result.concat(getFirstNoneTerminal(firstProd.definition));
+ }
+ else if (firstProd instanceof gast_public_1.Alternation) {
+ // each sub definition in alternation is a FLAT
+ result = utils.flatten(utils.map(firstProd.definition, function (currSubDef) {
+ return getFirstNoneTerminal(currSubDef.definition);
+ }));
+ }
+ else if (firstProd instanceof gast_public_1.Terminal) {
+ // nothing to see, move along
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ var isFirstOptional = gast_1.isOptionalProd(firstProd);
+ var hasMore = definition.length > 1;
+ if (isFirstOptional && hasMore) {
+ var rest = utils.drop(definition);
+ return result.concat(getFirstNoneTerminal(rest));
+ }
+ else {
+ return result;
+ }
+}
+exports.getFirstNoneTerminal = getFirstNoneTerminal;
+var OrCollector = /** @class */ (function (_super) {
+ __extends(OrCollector, _super);
+ function OrCollector() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.alternations = [];
+ return _this;
+ }
+ OrCollector.prototype.visitAlternation = function (node) {
+ this.alternations.push(node);
+ };
+ return OrCollector;
+}(gast_visitor_public_1.GAstVisitor));
+function validateEmptyOrAlternative(topLevelRule, errMsgProvider) {
+ var orCollector = new OrCollector();
+ topLevelRule.accept(orCollector);
+ var ors = orCollector.alternations;
+ var errors = utils.reduce(ors, function (errors, currOr) {
+ var exceptLast = utils.dropRight(currOr.definition);
+ var currErrors = utils.map(exceptLast, function (currAlternative, currAltIdx) {
+ var possibleFirstInAlt = interpreter_1.nextPossibleTokensAfter([currAlternative], [], null, 1);
+ if (utils.isEmpty(possibleFirstInAlt)) {
+ return {
+ message: errMsgProvider.buildEmptyAlternationError({
+ topLevelRule: topLevelRule,
+ alternation: currOr,
+ emptyChoiceIdx: currAltIdx
+ }),
+ type: parser_1.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,
+ ruleName: topLevelRule.name,
+ occurrence: currOr.idx,
+ alternative: currAltIdx + 1
+ };
+ }
+ else {
+ return null;
+ }
+ });
+ return errors.concat(utils.compact(currErrors));
+ }, []);
+ return errors;
+}
+exports.validateEmptyOrAlternative = validateEmptyOrAlternative;
+function validateAmbiguousAlternationAlternatives(topLevelRule, globalMaxLookahead, ignoredIssues, errMsgProvider) {
+ var orCollector = new OrCollector();
+ topLevelRule.accept(orCollector);
+ var ors = orCollector.alternations;
+ // TODO: this filtering should be deprecated once we remove the ignoredIssues
+ // IParserConfig property
+ var ignoredIssuesForCurrentRule = ignoredIssues[topLevelRule.name];
+ if (ignoredIssuesForCurrentRule) {
+ ors = utils_1.reject(ors, function (currOr) {
+ return ignoredIssuesForCurrentRule[gast_1.getProductionDslName(currOr) +
+ (currOr.idx === 0 ? "" : currOr.idx)];
+ });
+ }
+ // New Handling of ignoring ambiguities
+ // - https://github.com/SAP/chevrotain/issues/869
+ ors = utils_1.reject(ors, function (currOr) { return currOr.ignoreAmbiguities === true; });
+ var errors = utils.reduce(ors, function (result, currOr) {
+ var currOccurrence = currOr.idx;
+ var actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead;
+ var alternatives = lookahead_1.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;
+}
+exports.validateAmbiguousAlternationAlternatives = validateAmbiguousAlternationAlternatives;
+var RepetionCollector = /** @class */ (function (_super) {
+ __extends(RepetionCollector, _super);
+ function RepetionCollector() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.allProductions = [];
+ return _this;
+ }
+ RepetionCollector.prototype.visitRepetitionWithSeparator = function (manySep) {
+ this.allProductions.push(manySep);
+ };
+ RepetionCollector.prototype.visitRepetitionMandatory = function (atLeastOne) {
+ this.allProductions.push(atLeastOne);
+ };
+ RepetionCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) {
+ this.allProductions.push(atLeastOneSep);
+ };
+ RepetionCollector.prototype.visitRepetition = function (many) {
+ this.allProductions.push(many);
+ };
+ return RepetionCollector;
+}(gast_visitor_public_1.GAstVisitor));
+exports.RepetionCollector = RepetionCollector;
+function validateTooManyAlts(topLevelRule, errMsgProvider) {
+ var orCollector = new OrCollector();
+ topLevelRule.accept(orCollector);
+ var ors = orCollector.alternations;
+ var errors = utils.reduce(ors, function (errors, currOr) {
+ if (currOr.definition.length > 255) {
+ errors.push({
+ message: errMsgProvider.buildTooManyAlternativesError({
+ topLevelRule: topLevelRule,
+ alternation: currOr
+ }),
+ type: parser_1.ParserDefinitionErrorType.TOO_MANY_ALTS,
+ ruleName: topLevelRule.name,
+ occurrence: currOr.idx
+ });
+ }
+ return errors;
+ }, []);
+ return errors;
+}
+exports.validateTooManyAlts = validateTooManyAlts;
+function validateSomeNonEmptyLookaheadPath(topLevelRules, maxLookahead, errMsgProvider) {
+ var errors = [];
+ utils_1.forEach(topLevelRules, function (currTopRule) {
+ var collectorVisitor = new RepetionCollector();
+ currTopRule.accept(collectorVisitor);
+ var allRuleProductions = collectorVisitor.allProductions;
+ utils_1.forEach(allRuleProductions, function (currProd) {
+ var prodType = lookahead_1.getProdType(currProd);
+ var actualMaxLookahead = currProd.maxLookahead || maxLookahead;
+ var currOccurrence = currProd.idx;
+ var paths = lookahead_1.getLookaheadPathsForOptionalProd(currOccurrence, currTopRule, prodType, actualMaxLookahead);
+ var pathsInsideProduction = paths[0];
+ if (utils_1.isEmpty(utils_1.flatten(pathsInsideProduction))) {
+ var errMsg = errMsgProvider.buildEmptyRepetitionError({
+ topLevelRule: currTopRule,
+ repetition: currProd
+ });
+ errors.push({
+ message: errMsg,
+ type: parser_1.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,
+ ruleName: currTopRule.name
+ });
+ }
+ });
+ });
+ return errors;
+}
+exports.validateSomeNonEmptyLookaheadPath = validateSomeNonEmptyLookaheadPath;
+function checkAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) {
+ var foundAmbiguousPaths = [];
+ var identicalAmbiguities = utils_1.reduce(alternatives, function (result, currAlt, currAltIdx) {
+ // ignore (skip) ambiguities with this alternative
+ if (alternation.definition[currAltIdx].ignoreAmbiguities === true) {
+ return result;
+ }
+ utils_1.forEach(currAlt, function (currPath) {
+ var altsCurrPathAppearsIn = [currAltIdx];
+ utils_1.forEach(alternatives, function (currOtherAlt, currOtherAltIdx) {
+ if (currAltIdx !== currOtherAltIdx &&
+ lookahead_1.containsPath(currOtherAlt, currPath) &&
+ // ignore (skip) ambiguities with this "other" alternative
+ alternation.definition[currOtherAltIdx]
+ .ignoreAmbiguities !== true) {
+ altsCurrPathAppearsIn.push(currOtherAltIdx);
+ }
+ });
+ if (altsCurrPathAppearsIn.length > 1 &&
+ !lookahead_1.containsPath(foundAmbiguousPaths, currPath)) {
+ foundAmbiguousPaths.push(currPath);
+ result.push({
+ alts: altsCurrPathAppearsIn,
+ path: currPath
+ });
+ }
+ });
+ return result;
+ }, []);
+ var currErrors = utils.map(identicalAmbiguities, function (currAmbDescriptor) {
+ var ambgIndices = utils_1.map(currAmbDescriptor.alts, function (currAltIdx) { return currAltIdx + 1; });
+ var currMessage = errMsgProvider.buildAlternationAmbiguityError({
+ topLevelRule: rule,
+ alternation: alternation,
+ ambiguityIndices: ambgIndices,
+ prefixPath: currAmbDescriptor.path
+ });
+ return {
+ message: currMessage,
+ type: parser_1.ParserDefinitionErrorType.AMBIGUOUS_ALTS,
+ ruleName: rule.name,
+ occurrence: alternation.idx,
+ alternatives: [currAmbDescriptor.alts]
+ };
+ });
+ return currErrors;
+}
+function checkPrefixAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) {
+ var errors = [];
+ // flatten
+ var pathsAndIndices = utils_1.reduce(alternatives, function (result, currAlt, idx) {
+ var currPathsAndIdx = utils_1.map(currAlt, function (currPath) {
+ return { idx: idx, path: currPath };
+ });
+ return result.concat(currPathsAndIdx);
+ }, []);
+ utils_1.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 = utils_1.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.
+ lookahead_1.isStrictPrefixOfPath(searchPathAndIdx.path, targetPath));
+ });
+ var currPathPrefixErrors = utils_1.map(prefixAmbiguitiesPathsAndIndices, function (currAmbPathAndIdx) {
+ var ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1];
+ var occurrence = alternation.idx === 0 ? "" : alternation.idx;
+ var message = errMsgProvider.buildAlternationPrefixAmbiguityError({
+ topLevelRule: rule,
+ alternation: alternation,
+ ambiguityIndices: ambgIndices,
+ prefixPath: currAmbPathAndIdx.path
+ });
+ return {
+ message: message,
+ type: parser_1.ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS,
+ ruleName: rule.name,
+ occurrence: occurrence,
+ alternatives: ambgIndices
+ };
+ });
+ errors = errors.concat(currPathPrefixErrors);
+ });
+ return errors;
+}
+exports.checkPrefixAlternativesAmbiguities = checkPrefixAlternativesAmbiguities;
+function checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider) {
+ var errors = [];
+ var tokenNames = utils_1.map(tokenTypes, function (currToken) { return currToken.name; });
+ utils_1.forEach(topLevels, function (currRule) {
+ var currRuleName = currRule.name;
+ if (utils_1.contains(tokenNames, currRuleName)) {
+ var errMsg = errMsgProvider.buildNamespaceConflictError(currRule);
+ errors.push({
+ message: errMsg,
+ type: parser_1.ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,
+ ruleName: currRuleName
+ });
+ }
+ });
+ return errors;
+}
+function validateDuplicateNestedRules(topLevelRules, errMsgProvider) {
+ var errors = [];
+ utils_1.forEach(topLevelRules, function (currTopRule) {
+ var namedCollectorVisitor = new cst_1.NamedDSLMethodsCollectorVisitor("");
+ currTopRule.accept(namedCollectorVisitor);
+ var prodsByGroup = utils_1.groupBy(namedCollectorVisitor.result, function (item) { return item.name; });
+ var duplicates = utils_1.pick(prodsByGroup, function (currGroup) {
+ return currGroup.length > 1;
+ });
+ utils_1.forEach(utils_1.values(duplicates), function (currDupGroup) {
+ var currDupProds = utils_1.map(currDupGroup, function (dupGroup) { return dupGroup.orgProd; });
+ var errMsg = errMsgProvider.buildDuplicateNestedRuleNameError(currTopRule, currDupProds);
+ errors.push({
+ message: errMsg,
+ type: parser_1.ParserDefinitionErrorType.DUPLICATE_NESTED_NAME,
+ ruleName: currTopRule.name
+ });
+ });
+ });
+ return errors;
+}
+//# sourceMappingURL=checks.js.map
+
+/***/ }),
+/* 12 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+var interpreter_1 = __webpack_require__(13);
+var rest_1 = __webpack_require__(14);
+var tokens_1 = __webpack_require__(5);
+var gast_public_1 = __webpack_require__(1);
+var gast_visitor_public_1 = __webpack_require__(4);
+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 = exports.PROD_TYPE || (exports.PROD_TYPE = {}));
+function getProdType(prod) {
+ /* istanbul ignore else */
+ if (prod instanceof gast_public_1.Option) {
+ return PROD_TYPE.OPTION;
+ }
+ else if (prod instanceof gast_public_1.Repetition) {
+ return PROD_TYPE.REPETITION;
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatory) {
+ return PROD_TYPE.REPETITION_MANDATORY;
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatoryWithSeparator) {
+ return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR;
+ }
+ else if (prod instanceof gast_public_1.RepetitionWithSeparator) {
+ return PROD_TYPE.REPETITION_WITH_SEPARATOR;
+ }
+ else if (prod instanceof gast_public_1.Alternation) {
+ return PROD_TYPE.ALTERNATION;
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+exports.getProdType = getProdType;
+function buildLookaheadFuncForOr(occurrence, ruleGrammar, maxLookahead, hasPredicates, dynamicTokensEnabled, laFuncBuilder) {
+ var lookAheadPaths = getLookaheadPathsForOr(occurrence, ruleGrammar, maxLookahead);
+ var tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths)
+ ? tokens_1.tokenStructuredMatcherNoCategories
+ : tokens_1.tokenStructuredMatcher;
+ return laFuncBuilder(lookAheadPaths, hasPredicates, tokenMatcher, dynamicTokensEnabled);
+}
+exports.buildLookaheadFuncForOr = buildLookaheadFuncForOr;
+/**
+ * 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)
+ ? tokens_1.tokenStructuredMatcherNoCategories
+ : tokens_1.tokenStructuredMatcher;
+ return lookaheadBuilder(lookAheadPaths[0], tokenMatcher, dynamicTokensEnabled);
+}
+exports.buildLookaheadFuncForOptionalProd = buildLookaheadFuncForOptionalProd;
+function buildAlternativesLookAheadFunc(alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) {
+ var numOfAlts = alts.length;
+ var areAllOneTokenLookahead = utils_1.every(alts, function (currAlt) {
+ return utils_1.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 = utils_1.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 = utils_1.map(alts, function (currAlt) {
+ return utils_1.flatten(currAlt);
+ });
+ var choiceToAlt_1 = utils_1.reduce(singleTokenAlts, function (result, currAlt, idx) {
+ utils_1.forEach(currAlt, function (currTokType) {
+ if (!utils_1.has(result, currTokType.tokenTypeIdx)) {
+ result[currTokType.tokenTypeIdx] = idx;
+ }
+ utils_1.forEach(currTokType.categoryMatches, function (currExtendingType) {
+ if (!utils_1.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;
+ };
+ }
+}
+exports.buildAlternativesLookAheadFunc = buildAlternativesLookAheadFunc;
+function buildSingleAlternativeLookaheadFunction(alt, tokenMatcher, dynamicTokensEnabled) {
+ var areAllOneTokenLookahead = utils_1.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 = utils_1.flatten(alt);
+ if (singleTokensTypes.length === 1 &&
+ utils_1.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 = utils_1.reduce(singleTokensTypes, function (result, currTokType, idx) {
+ result[currTokType.tokenTypeIdx] = true;
+ utils_1.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;
+ };
+ }
+}
+exports.buildSingleAlternativeLookaheadFunction = buildSingleAlternativeLookaheadFunction;
+var RestDefinitionFinderWalker = /** @class */ (function (_super) {
+ __extends(RestDefinitionFinderWalker, _super);
+ function RestDefinitionFinderWalker(topProd, targetOccurrence, targetProdType) {
+ var _this = _super.call(this) || this;
+ _this.topProd = topProd;
+ _this.targetOccurrence = targetOccurrence;
+ _this.targetProdType = targetProdType;
+ return _this;
+ }
+ RestDefinitionFinderWalker.prototype.startWalking = function () {
+ this.walk(this.topProd);
+ return this.restDef;
+ };
+ RestDefinitionFinderWalker.prototype.checkIsTarget = function (node, expectedProdType, currRest, prevRest) {
+ if (node.idx === this.targetOccurrence &&
+ this.targetProdType === expectedProdType) {
+ this.restDef = currRest.concat(prevRest);
+ return true;
+ }
+ // performance optimization, do not iterate over the entire Grammar ast after we have found the target
+ return false;
+ };
+ RestDefinitionFinderWalker.prototype.walkOption = function (optionProd, currRest, prevRest) {
+ if (!this.checkIsTarget(optionProd, PROD_TYPE.OPTION, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, optionProd, currRest, prevRest);
+ }
+ };
+ RestDefinitionFinderWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) {
+ if (!this.checkIsTarget(atLeastOneProd, PROD_TYPE.REPETITION_MANDATORY, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, atLeastOneProd, currRest, prevRest);
+ }
+ };
+ RestDefinitionFinderWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) {
+ if (!this.checkIsTarget(atLeastOneSepProd, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, atLeastOneSepProd, currRest, prevRest);
+ }
+ };
+ RestDefinitionFinderWalker.prototype.walkMany = function (manyProd, currRest, prevRest) {
+ if (!this.checkIsTarget(manyProd, PROD_TYPE.REPETITION, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, manyProd, currRest, prevRest);
+ }
+ };
+ RestDefinitionFinderWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) {
+ if (!this.checkIsTarget(manySepProd, PROD_TYPE.REPETITION_WITH_SEPARATOR, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, manySepProd, currRest, prevRest);
+ }
+ };
+ return RestDefinitionFinderWalker;
+}(rest_1.RestWalker));
+/**
+ * Returns the definition of a target production in a top level level rule.
+ */
+var InsideDefinitionFinderVisitor = /** @class */ (function (_super) {
+ __extends(InsideDefinitionFinderVisitor, _super);
+ function InsideDefinitionFinderVisitor(targetOccurrence, targetProdType, targetRef) {
+ var _this = _super.call(this) || this;
+ _this.targetOccurrence = targetOccurrence;
+ _this.targetProdType = targetProdType;
+ _this.targetRef = targetRef;
+ _this.result = [];
+ return _this;
+ }
+ InsideDefinitionFinderVisitor.prototype.checkIsTarget = function (node, expectedProdName) {
+ if (node.idx === this.targetOccurrence &&
+ this.targetProdType === expectedProdName &&
+ (this.targetRef === undefined || node === this.targetRef)) {
+ this.result = node.definition;
+ }
+ };
+ InsideDefinitionFinderVisitor.prototype.visitOption = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.OPTION);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitRepetition = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.REPETITION);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatory = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitRepetitionWithSeparator = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.REPETITION_WITH_SEPARATOR);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitAlternation = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.ALTERNATION);
+ };
+ return InsideDefinitionFinderVisitor;
+}(gast_visitor_public_1.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 = utils_1.map(altsDefs, function (currAlt) { return interpreter_1.possiblePathsFrom([currAlt], 1); });
+ var finalResult = initializeArrayOfArrays(partialAlts.length);
+ var altsHashes = utils_1.map(partialAlts, function (currAltPaths) {
+ var dict = {};
+ utils_1.forEach(currAltPaths, function (item) {
+ var keys = pathToHashKeys(item.partialPath);
+ utils_1.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 ||
+ utils_1.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 = interpreter_1.possiblePathsFrom(suffixDef, pathLength + 1, currPathPrefix);
+ newData[altIdx] = newData[altIdx].concat(newPartialPathsAndSuffixes);
+ // Update keys for new known paths
+ utils_1.forEach(newPartialPathsAndSuffixes, function (item) {
+ var prefixKeys = pathToHashKeys(item.partialPath);
+ utils_1.forEach(prefixKeys, function (key) {
+ altsHashes[altIdx][key] = true;
+ });
+ });
+ }
+ }
+ };
+ // alternatives loop
+ for (var altIdx = 0; altIdx < currDataset.length; altIdx++) {
+ _loop_1(altIdx);
+ }
+ }
+ return finalResult;
+}
+exports.lookAheadSequenceFromAlternatives = lookAheadSequenceFromAlternatives;
+function getLookaheadPathsForOr(occurrence, ruleGrammar, k, orProd) {
+ var visitor = new InsideDefinitionFinderVisitor(occurrence, PROD_TYPE.ALTERNATION, orProd);
+ ruleGrammar.accept(visitor);
+ return lookAheadSequenceFromAlternatives(visitor.result, k);
+}
+exports.getLookaheadPathsForOr = getLookaheadPathsForOr;
+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_1.Flat({ definition: insideDef });
+ var afterFlat = new gast_public_1.Flat({ definition: afterDef });
+ return lookAheadSequenceFromAlternatives([insideFlat, afterFlat], k);
+}
+exports.getLookaheadPathsForOptionalProd = getLookaheadPathsForOptionalProd;
+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;
+}
+exports.containsPath = containsPath;
+function isStrictPrefixOfPath(prefix, other) {
+ return (prefix.length < other.length &&
+ utils_1.every(prefix, function (tokType, idx) {
+ var otherTokType = other[idx];
+ return (tokType === otherTokType ||
+ otherTokType.categoryMatchesMap[tokType.tokenTypeIdx]);
+ }));
+}
+exports.isStrictPrefixOfPath = isStrictPrefixOfPath;
+function areTokenCategoriesNotUsed(lookAheadPaths) {
+ return utils_1.every(lookAheadPaths, function (singleAltPaths) {
+ return utils_1.every(singleAltPaths, function (singlePath) {
+ return utils_1.every(singlePath, function (token) { return utils_1.isEmpty(token.categoryMatches); });
+ });
+ });
+}
+exports.areTokenCategoriesNotUsed = areTokenCategoriesNotUsed;
+//# sourceMappingURL=lookahead.js.map
+
+/***/ }),
+/* 13 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+/* istanbul ignore next */ var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var rest_1 = __webpack_require__(14);
+var utils_1 = __webpack_require__(0);
+var first_1 = __webpack_require__(22);
+var gast_public_1 = __webpack_require__(1);
+var AbstractNextPossibleTokensWalker = /** @class */ (function (_super) {
+ __extends(AbstractNextPossibleTokensWalker, _super);
+ function AbstractNextPossibleTokensWalker(topProd, path) {
+ var _this = _super.call(this) /* istanbul ignore next */ || 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 = utils_1.cloneArr(this.path.ruleStack).reverse(); // intelij bug requires assertion
+ this.occurrenceStack = utils_1.cloneArr(this.path.occurrenceStack).reverse(); // intelij bug requires assertion
+ // already verified that the first production is valid, we now seek the 2nd production
+ this.ruleStack.pop();
+ this.occurrenceStack.pop();
+ this.updateExpectedNext();
+ this.walk(this.topProd);
+ return this.possibleTokTypes;
+ };
+ AbstractNextPossibleTokensWalker.prototype.walk = function (prod, prevRest) {
+ if (prevRest === void 0) { prevRest = []; }
+ // stop scanning once we found the path
+ if (!this.found) {
+ _super.prototype.walk.call(this, prod, prevRest);
+ }
+ };
+ AbstractNextPossibleTokensWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) {
+ // found the next production, need to keep walking in it
+ if (refProd.referencedRule.name === this.nextProductionName &&
+ refProd.idx === this.nextProductionOccurrence) {
+ var fullRest = currRest.concat(prevRest);
+ this.updateExpectedNext();
+ this.walk(refProd.referencedRule, fullRest);
+ }
+ };
+ AbstractNextPossibleTokensWalker.prototype.updateExpectedNext = function () {
+ // need to consume the Terminal
+ if (utils_1.isEmpty(this.ruleStack)) {
+ // must reset nextProductionXXX to avoid walking down another Top Level production while what we are
+ // really seeking is the last Terminal...
+ this.nextProductionName = "";
+ this.nextProductionOccurrence = 0;
+ this.isAtEndOfPath = true;
+ }
+ else {
+ this.nextProductionName = this.ruleStack.pop();
+ this.nextProductionOccurrence = this.occurrenceStack.pop();
+ }
+ };
+ return AbstractNextPossibleTokensWalker;
+}(rest_1.RestWalker));
+exports.AbstractNextPossibleTokensWalker = AbstractNextPossibleTokensWalker;
+var NextAfterTokenWalker = /** @class */ (function (_super) {
+ __extends(NextAfterTokenWalker, _super);
+ function NextAfterTokenWalker(topProd, path) {
+ var _this = _super.call(this, topProd, path) /* istanbul ignore next */ || 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_1.Flat({ definition: fullRest });
+ this.possibleTokTypes = first_1.first(restProd);
+ this.found = true;
+ }
+ };
+ return NextAfterTokenWalker;
+}(AbstractNextPossibleTokensWalker));
+exports.NextAfterTokenWalker = NextAfterTokenWalker;
+/**
+ * This walker only "walks" a single "TOP" level in the Grammar Ast, this means
+ * it never "follows" production refs
+ */
+var AbstractNextTerminalAfterProductionWalker = /** @class */ (function (_super) {
+ __extends(AbstractNextTerminalAfterProductionWalker, _super);
+ function AbstractNextTerminalAfterProductionWalker(topRule, occurrence) {
+ var _this = _super.call(this) /* istanbul ignore next */ || 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_1.RestWalker));
+exports.AbstractNextTerminalAfterProductionWalker = AbstractNextTerminalAfterProductionWalker;
+var NextTerminalAfterManyWalker = /** @class */ (function (_super) {
+ __extends(NextTerminalAfterManyWalker, _super);
+ function NextTerminalAfterManyWalker() {
+ return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this;
+ }
+ NextTerminalAfterManyWalker.prototype.walkMany = function (manyProd, currRest, prevRest) {
+ if (manyProd.idx === this.occurrence) {
+ var firstAfterMany = utils_1.first(currRest.concat(prevRest));
+ this.result.isEndOfRule = firstAfterMany === undefined;
+ if (firstAfterMany instanceof gast_public_1.Terminal) {
+ this.result.token = firstAfterMany.terminalType;
+ this.result.occurrence = firstAfterMany.idx;
+ }
+ }
+ else {
+ _super.prototype.walkMany.call(this, manyProd, currRest, prevRest);
+ }
+ };
+ return NextTerminalAfterManyWalker;
+}(AbstractNextTerminalAfterProductionWalker));
+exports.NextTerminalAfterManyWalker = NextTerminalAfterManyWalker;
+var NextTerminalAfterManySepWalker = /** @class */ (function (_super) {
+ __extends(NextTerminalAfterManySepWalker, _super);
+ function NextTerminalAfterManySepWalker() {
+ return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this;
+ }
+ NextTerminalAfterManySepWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) {
+ if (manySepProd.idx === this.occurrence) {
+ var firstAfterManySep = utils_1.first(currRest.concat(prevRest));
+ this.result.isEndOfRule = firstAfterManySep === undefined;
+ if (firstAfterManySep instanceof gast_public_1.Terminal) {
+ this.result.token = firstAfterManySep.terminalType;
+ this.result.occurrence = firstAfterManySep.idx;
+ }
+ }
+ else {
+ _super.prototype.walkManySep.call(this, manySepProd, currRest, prevRest);
+ }
+ };
+ return NextTerminalAfterManySepWalker;
+}(AbstractNextTerminalAfterProductionWalker));
+exports.NextTerminalAfterManySepWalker = NextTerminalAfterManySepWalker;
+var NextTerminalAfterAtLeastOneWalker = /** @class */ (function (_super) {
+ __extends(NextTerminalAfterAtLeastOneWalker, _super);
+ function NextTerminalAfterAtLeastOneWalker() {
+ return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this;
+ }
+ NextTerminalAfterAtLeastOneWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) {
+ if (atLeastOneProd.idx === this.occurrence) {
+ var firstAfterAtLeastOne = utils_1.first(currRest.concat(prevRest));
+ this.result.isEndOfRule = firstAfterAtLeastOne === undefined;
+ if (firstAfterAtLeastOne instanceof gast_public_1.Terminal) {
+ this.result.token = firstAfterAtLeastOne.terminalType;
+ this.result.occurrence = firstAfterAtLeastOne.idx;
+ }
+ }
+ else {
+ _super.prototype.walkAtLeastOne.call(this, atLeastOneProd, currRest, prevRest);
+ }
+ };
+ return NextTerminalAfterAtLeastOneWalker;
+}(AbstractNextTerminalAfterProductionWalker));
+exports.NextTerminalAfterAtLeastOneWalker = NextTerminalAfterAtLeastOneWalker;
+// TODO: reduce code duplication in the AfterWalkers
+var NextTerminalAfterAtLeastOneSepWalker = /** @class */ (function (_super) {
+ __extends(NextTerminalAfterAtLeastOneSepWalker, _super);
+ function NextTerminalAfterAtLeastOneSepWalker() {
+ return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this;
+ }
+ NextTerminalAfterAtLeastOneSepWalker.prototype.walkAtLeastOneSep = function (atleastOneSepProd, currRest, prevRest) {
+ if (atleastOneSepProd.idx === this.occurrence) {
+ var firstAfterfirstAfterAtLeastOneSep = utils_1.first(currRest.concat(prevRest));
+ this.result.isEndOfRule =
+ firstAfterfirstAfterAtLeastOneSep === undefined;
+ if (firstAfterfirstAfterAtLeastOneSep instanceof gast_public_1.Terminal) {
+ this.result.token =
+ firstAfterfirstAfterAtLeastOneSep.terminalType;
+ this.result.occurrence = firstAfterfirstAfterAtLeastOneSep.idx;
+ }
+ }
+ else {
+ _super.prototype.walkAtLeastOneSep.call(this, atleastOneSepProd, currRest, prevRest);
+ }
+ };
+ return NextTerminalAfterAtLeastOneSepWalker;
+}(AbstractNextTerminalAfterProductionWalker));
+exports.NextTerminalAfterAtLeastOneSepWalker = NextTerminalAfterAtLeastOneSepWalker;
+function possiblePathsFrom(targetDef, maxLength, currPath) {
+ if (currPath === void 0) { currPath = []; }
+ // avoid side effects
+ currPath = utils_1.cloneArr(currPath);
+ var result = [];
+ var i = 0;
+ // TODO: avoid inner funcs
+ function remainingPathWith(nextDef) {
+ return nextDef.concat(utils_1.drop(targetDef, i + 1));
+ }
+ // TODO: avoid inner funcs
+ function getAlternativesForProd(definition) {
+ var alternatives = possiblePathsFrom(remainingPathWith(definition), maxLength, currPath);
+ return result.concat(alternatives);
+ }
+ /**
+ * Mandatory productions will halt the loop as the paths computed from their recursive calls will already contain the
+ * following (rest) of the targetDef.
+ *
+ * For optional productions (Option/Repetition/...) the loop will continue to represent the paths that do not include the
+ * the optional production.
+ */
+ while (currPath.length < maxLength && i < targetDef.length) {
+ var prod = targetDef[i];
+ /* istanbul ignore else */
+ if (prod instanceof gast_public_1.Flat) {
+ return getAlternativesForProd(prod.definition);
+ }
+ else if (prod instanceof gast_public_1.NonTerminal) {
+ return getAlternativesForProd(prod.definition);
+ }
+ else if (prod instanceof gast_public_1.Option) {
+ result = getAlternativesForProd(prod.definition);
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatory) {
+ var newDef = prod.definition.concat([
+ new gast_public_1.Repetition({
+ definition: prod.definition
+ })
+ ]);
+ return getAlternativesForProd(newDef);
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatoryWithSeparator) {
+ var newDef = [
+ new gast_public_1.Flat({ definition: prod.definition }),
+ new gast_public_1.Repetition({
+ definition: [
+ new gast_public_1.Terminal({ terminalType: prod.separator })
+ ].concat(prod.definition)
+ })
+ ];
+ return getAlternativesForProd(newDef);
+ }
+ else if (prod instanceof gast_public_1.RepetitionWithSeparator) {
+ var newDef = prod.definition.concat([
+ new gast_public_1.Repetition({
+ definition: [
+ new gast_public_1.Terminal({ terminalType: prod.separator })
+ ].concat(prod.definition)
+ })
+ ]);
+ result = getAlternativesForProd(newDef);
+ }
+ else if (prod instanceof gast_public_1.Repetition) {
+ var newDef = prod.definition.concat([
+ new gast_public_1.Repetition({
+ definition: prod.definition
+ })
+ ]);
+ result = getAlternativesForProd(newDef);
+ }
+ else if (prod instanceof gast_public_1.Alternation) {
+ utils_1.forEach(prod.definition, function (currAlt) {
+ result = getAlternativesForProd(currAlt.definition);
+ });
+ return result;
+ }
+ else if (prod instanceof gast_public_1.Terminal) {
+ currPath.push(prod.terminalType);
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ i++;
+ }
+ result.push({
+ partialPath: currPath,
+ suffixDef: utils_1.drop(targetDef, i)
+ });
+ return result;
+}
+exports.possiblePathsFrom = possiblePathsFrom;
+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 (!utils_1.isEmpty(possiblePaths)) {
+ var currPath = possiblePaths.pop();
+ // skip alternatives if no more results can be found (assuming deterministic grammar with fixed lookahead)
+ if (currPath === EXIT_ALTERNATIVE) {
+ if (foundCompletePath &&
+ utils_1.last(possiblePaths).idx <= minimalAlternativesIndex) {
+ // remove irrelevant alternative
+ possiblePaths.pop();
+ }
+ continue;
+ }
+ var currDef = currPath.def;
+ var currIdx = currPath.idx;
+ var currRuleStack = currPath.ruleStack;
+ var currOccurrenceStack = currPath.occurrenceStack;
+ // For Example: an empty path could exist in a valid grammar in the case of an EMPTY_ALT
+ if (utils_1.isEmpty(currDef)) {
+ continue;
+ }
+ var prod = currDef[0];
+ /* istanbul ignore else */
+ if (prod === EXIT_NON_TERMINAL) {
+ var nextPath = {
+ idx: currIdx,
+ def: utils_1.drop(currDef),
+ ruleStack: utils_1.dropRight(currRuleStack),
+ occurrenceStack: utils_1.dropRight(currOccurrenceStack)
+ };
+ possiblePaths.push(nextPath);
+ }
+ else if (prod instanceof gast_public_1.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: utils_1.drop(currDef),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPath);
+ }
+ // end of the line
+ }
+ else if (currIdx === tokenVectorLength - 1) {
+ // IGNORE ABOVE ELSE
+ result.push({
+ nextTokenType: prod.terminalType,
+ nextTokenOccurrence: prod.idx,
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ });
+ foundCompletePath = true;
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ }
+ else if (prod instanceof gast_public_1.NonTerminal) {
+ var newRuleStack = utils_1.cloneArr(currRuleStack);
+ newRuleStack.push(prod.nonTerminalName);
+ var newOccurrenceStack = utils_1.cloneArr(currOccurrenceStack);
+ newOccurrenceStack.push(prod.idx);
+ var nextPath = {
+ idx: currIdx,
+ def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, utils_1.drop(currDef)),
+ ruleStack: newRuleStack,
+ occurrenceStack: newOccurrenceStack
+ };
+ possiblePaths.push(nextPath);
+ }
+ else if (prod instanceof gast_public_1.Option) {
+ // the order of alternatives is meaningful, FILO (Last path will be traversed first).
+ var nextPathWithout = {
+ idx: currIdx,
+ def: utils_1.drop(currDef),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWithout);
+ // required marker to avoid backtracking paths whose higher priority alternatives already matched
+ possiblePaths.push(EXIT_ALTERNATIVE);
+ var nextPathWith = {
+ idx: currIdx,
+ def: prod.definition.concat(utils_1.drop(currDef)),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWith);
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatory) {
+ // TODO:(THE NEW operators here take a while...) (convert once?)
+ var secondIteration = new gast_public_1.Repetition({
+ definition: prod.definition,
+ idx: prod.idx
+ });
+ var nextDef = prod.definition.concat([secondIteration], utils_1.drop(currDef));
+ var nextPath = {
+ idx: currIdx,
+ def: nextDef,
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPath);
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatoryWithSeparator) {
+ // TODO:(THE NEW operators here take a while...) (convert once?)
+ var separatorGast = new gast_public_1.Terminal({
+ terminalType: prod.separator
+ });
+ var secondIteration = new gast_public_1.Repetition({
+ definition: [separatorGast].concat(prod.definition),
+ idx: prod.idx
+ });
+ var nextDef = prod.definition.concat([secondIteration], utils_1.drop(currDef));
+ var nextPath = {
+ idx: currIdx,
+ def: nextDef,
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPath);
+ }
+ else if (prod instanceof gast_public_1.RepetitionWithSeparator) {
+ // the order of alternatives is meaningful, FILO (Last path will be traversed first).
+ var nextPathWithout = {
+ idx: currIdx,
+ def: utils_1.drop(currDef),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWithout);
+ // required marker to avoid backtracking paths whose higher priority alternatives already matched
+ possiblePaths.push(EXIT_ALTERNATIVE);
+ var separatorGast = new gast_public_1.Terminal({
+ terminalType: prod.separator
+ });
+ var nthRepetition = new gast_public_1.Repetition({
+ definition: [separatorGast].concat(prod.definition),
+ idx: prod.idx
+ });
+ var nextDef = prod.definition.concat([nthRepetition], utils_1.drop(currDef));
+ var nextPathWith = {
+ idx: currIdx,
+ def: nextDef,
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWith);
+ }
+ else if (prod instanceof gast_public_1.Repetition) {
+ // the order of alternatives is meaningful, FILO (Last path will be traversed first).
+ var nextPathWithout = {
+ idx: currIdx,
+ def: utils_1.drop(currDef),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWithout);
+ // required marker to avoid backtracking paths whose higher priority alternatives already matched
+ possiblePaths.push(EXIT_ALTERNATIVE);
+ // TODO: an empty repetition will cause infinite loops here, will the parser detect this in selfAnalysis?
+ var nthRepetition = new gast_public_1.Repetition({
+ definition: prod.definition,
+ idx: prod.idx
+ });
+ var nextDef = prod.definition.concat([nthRepetition], utils_1.drop(currDef));
+ var nextPathWith = {
+ idx: currIdx,
+ def: nextDef,
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWith);
+ }
+ else if (prod instanceof gast_public_1.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(utils_1.drop(currDef)),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(currAltPath);
+ possiblePaths.push(EXIT_ALTERNATIVE);
+ }
+ }
+ else if (prod instanceof gast_public_1.Flat) {
+ possiblePaths.push({
+ idx: currIdx,
+ def: prod.definition.concat(utils_1.drop(currDef)),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ });
+ }
+ else if (prod instanceof gast_public_1.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;
+}
+exports.nextPossibleTokensAfter = nextPossibleTokensAfter;
+function expandTopLevelRule(topRule, currIdx, currRuleStack, currOccurrenceStack) {
+ var newRuleStack = utils_1.cloneArr(currRuleStack);
+ newRuleStack.push(topRule.name);
+ var newCurrOccurrenceStack = utils_1.cloneArr(currOccurrenceStack);
+ // top rule is always assumed to have been called with occurrence index 1
+ newCurrOccurrenceStack.push(1);
+ return {
+ idx: currIdx,
+ def: topRule.definition,
+ ruleStack: newRuleStack,
+ occurrenceStack: newCurrOccurrenceStack
+ };
+}
+//# sourceMappingURL=interpreter.js.map
+
+/***/ }),
+/* 14 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+var gast_public_1 = __webpack_require__(1);
+/**
+ * A Grammar Walker that computes the "remaining" grammar "after" a productions in the grammar.
+ */
+var RestWalker = /** @class */ (function () {
+ function RestWalker() {
+ }
+ RestWalker.prototype.walk = function (prod, prevRest) {
+ var _this = this;
+ if (prevRest === void 0) { prevRest = []; }
+ utils_1.forEach(prod.definition, function (subProd, index) {
+ var currRest = utils_1.drop(prod.definition, index + 1);
+ /* istanbul ignore else */
+ if (subProd instanceof gast_public_1.NonTerminal) {
+ _this.walkProdRef(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.Terminal) {
+ _this.walkTerminal(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.Flat) {
+ _this.walkFlat(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.Option) {
+ _this.walkOption(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.RepetitionMandatory) {
+ _this.walkAtLeastOne(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.RepetitionMandatoryWithSeparator) {
+ _this.walkAtLeastOneSep(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.RepetitionWithSeparator) {
+ _this.walkManySep(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.Repetition) {
+ _this.walkMany(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.Alternation) {
+ _this.walkOr(subProd, currRest, prevRest);
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ });
+ };
+ RestWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { };
+ RestWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { };
+ RestWalker.prototype.walkFlat = function (flatProd, currRest, prevRest) {
+ // ABCDEF => after the D the rest is EF
+ var fullOrRest = currRest.concat(prevRest);
+ this.walk(flatProd, fullOrRest);
+ };
+ RestWalker.prototype.walkOption = function (optionProd, currRest, prevRest) {
+ // ABC(DE)?F => after the (DE)? the rest is F
+ var fullOrRest = currRest.concat(prevRest);
+ this.walk(optionProd, fullOrRest);
+ };
+ RestWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) {
+ // ABC(DE)+F => after the (DE)+ the rest is (DE)?F
+ var fullAtLeastOneRest = [
+ new gast_public_1.Option({ definition: atLeastOneProd.definition })
+ ].concat(currRest, prevRest);
+ this.walk(atLeastOneProd, fullAtLeastOneRest);
+ };
+ RestWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) {
+ // ABC DE(,DE)* F => after the (,DE)+ the rest is (,DE)?F
+ var fullAtLeastOneSepRest = restForRepetitionWithSeparator(atLeastOneSepProd, currRest, prevRest);
+ this.walk(atLeastOneSepProd, fullAtLeastOneSepRest);
+ };
+ RestWalker.prototype.walkMany = function (manyProd, currRest, prevRest) {
+ // ABC(DE)*F => after the (DE)* the rest is (DE)?F
+ var fullManyRest = [
+ new gast_public_1.Option({ definition: manyProd.definition })
+ ].concat(currRest, prevRest);
+ this.walk(manyProd, fullManyRest);
+ };
+ RestWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) {
+ // ABC (DE(,DE)*)? F => after the (,DE)* the rest is (,DE)?F
+ var fullManySepRest = restForRepetitionWithSeparator(manySepProd, currRest, prevRest);
+ this.walk(manySepProd, fullManySepRest);
+ };
+ RestWalker.prototype.walkOr = function (orProd, currRest, prevRest) {
+ var _this = this;
+ // ABC(D|E|F)G => when finding the (D|E|F) the rest is G
+ var fullOrRest = currRest.concat(prevRest);
+ // walk all different alternatives
+ utils_1.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_1.Flat({ definition: [alt] });
+ _this.walk(prodWrapper, fullOrRest);
+ });
+ };
+ return RestWalker;
+}());
+exports.RestWalker = RestWalker;
+function restForRepetitionWithSeparator(repSepProd, currRest, prevRest) {
+ var repSepRest = [
+ new gast_public_1.Option({
+ definition: [
+ new gast_public_1.Terminal({ terminalType: repSepProd.separator })
+ ].concat(repSepProd.definition)
+ })
+ ];
+ var fullRepSepRest = repSepRest.concat(currRest, prevRest);
+ return fullRepSepRest;
+}
+//# sourceMappingURL=rest.js.map
+
+/***/ }),
+/* 15 */
+/***/ (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",
+ global: false,
+ ignoreCase: false,
+ multiLine: false,
+ unicode: false,
+ sticky: false
+ }
+
+ while (this.isRegExpFlag()) {
+ switch (this.popChar()) {
+ case "g":
+ addFlag(flags, "global")
+ break
+ case "i":
+ addFlag(flags, "ignoreCase")
+ break
+ case "m":
+ addFlag(flags, "multiLine")
+ break
+ case "u":
+ addFlag(flags, "unicode")
+ break
+ case "y":
+ addFlag(flags, "sticky")
+ break
+ }
+ }
+
+ if (this.idx !== this.input.length) {
+ throw Error(
+ "Redundant input: " + this.input.substring(this.idx)
+ )
+ }
+ return { type: "Pattern", flags: flags, value: value }
+ }
+
+ RegExpParser.prototype.disjunction = function() {
+ var alts = []
+ alts.push(this.alternative())
+
+ while (this.peekChar() === "|") {
+ this.consumeChar("|")
+ alts.push(this.alternative())
+ }
+
+ return { type: "Disjunction", value: alts }
+ }
+
+ RegExpParser.prototype.alternative = function() {
+ var terms = []
+
+ while (this.isTerm()) {
+ terms.push(this.term())
+ }
+
+ return { type: "Alternative", value: terms }
+ }
+
+ RegExpParser.prototype.term = function() {
+ if (this.isAssertion()) {
+ return this.assertion()
+ } else {
+ return this.atom()
+ }
+ }
+
+ RegExpParser.prototype.assertion = function() {
+ switch (this.popChar()) {
+ case "^":
+ return { type: "StartAnchor" }
+ case "$":
+ return { type: "EndAnchor" }
+ // '\b' or '\B'
+ case "\\":
+ switch (this.popChar()) {
+ case "b":
+ return { type: "WordBoundary" }
+ case "B":
+ return { type: "NonWordBoundary" }
+ }
+ // istanbul ignore next
+ throw Error("Invalid Assertion Escape")
+ // '(?=' or '(?!'
+ case "(":
+ this.consumeChar("?")
+
+ var type
+ switch (this.popChar()) {
+ case "=":
+ type = "Lookahead"
+ break
+ case "!":
+ type = "NegativeLookahead"
+ break
+ }
+ ASSERT_EXISTS(type)
+
+ var disjunction = this.disjunction()
+
+ this.consumeChar(")")
+
+ return { type: type, value: disjunction }
+ }
+ // istanbul ignore next
+ ASSERT_NEVER_REACH_HERE()
+ }
+
+ RegExpParser.prototype.quantifier = function(isBacktracking) {
+ var range
+ switch (this.popChar()) {
+ case "*":
+ range = {
+ atLeast: 0,
+ atMost: Infinity
+ }
+ break
+ case "+":
+ range = {
+ atLeast: 1,
+ atMost: Infinity
+ }
+ break
+ case "?":
+ range = {
+ atLeast: 0,
+ atMost: 1
+ }
+ break
+ case "{":
+ var atLeast = this.integerIncludingZero()
+ switch (this.popChar()) {
+ case "}":
+ range = {
+ atLeast: atLeast,
+ atMost: atLeast
+ }
+ break
+ case ",":
+ var atMost
+ if (this.isDigit()) {
+ atMost = this.integerIncludingZero()
+ range = {
+ atLeast: atLeast,
+ atMost: atMost
+ }
+ } else {
+ range = {
+ atLeast: atLeast,
+ atMost: Infinity
+ }
+ }
+ this.consumeChar("}")
+ break
+ }
+ // throwing exceptions from "ASSERT_EXISTS" during backtracking
+ // causes severe performance degradations
+ if (isBacktracking === true && range === undefined) {
+ return undefined
+ }
+ ASSERT_EXISTS(range)
+ break
+ }
+
+ // throwing exceptions from "ASSERT_EXISTS" during backtracking
+ // causes severe performance degradations
+ if (isBacktracking === true && range === undefined) {
+ return undefined
+ }
+
+ ASSERT_EXISTS(range)
+
+ if (this.peekChar(0) === "?") {
+ this.consumeChar("?")
+ range.greedy = false
+ } else {
+ range.greedy = true
+ }
+
+ range.type = "Quantifier"
+ return range
+ }
+
+ RegExpParser.prototype.atom = function() {
+ var atom
+ switch (this.peekChar()) {
+ case ".":
+ atom = this.dotAll()
+ break
+ case "\\":
+ atom = this.atomEscape()
+ break
+ case "[":
+ atom = this.characterClass()
+ break
+ case "(":
+ atom = this.group()
+ break
+ }
+
+ if (atom === undefined && this.isPatternCharacter()) {
+ atom = this.patternCharacter()
+ }
+
+ ASSERT_EXISTS(atom)
+
+ if (this.isQuantifier()) {
+ atom.quantifier = this.quantifier()
+ }
+
+ return atom
+ }
+
+ RegExpParser.prototype.dotAll = function() {
+ this.consumeChar(".")
+ return {
+ type: "Set",
+ complement: true,
+ value: [cc("\n"), cc("\r"), cc("\u2028"), cc("\u2029")]
+ }
+ }
+
+ RegExpParser.prototype.atomEscape = function() {
+ this.consumeChar("\\")
+
+ switch (this.peekChar()) {
+ case "1":
+ case "2":
+ case "3":
+ case "4":
+ case "5":
+ case "6":
+ case "7":
+ case "8":
+ case "9":
+ return this.decimalEscapeAtom()
+ case "d":
+ case "D":
+ case "s":
+ case "S":
+ case "w":
+ case "W":
+ return this.characterClassEscape()
+ case "f":
+ case "n":
+ case "r":
+ case "t":
+ case "v":
+ return this.controlEscapeAtom()
+ case "c":
+ return this.controlLetterEscapeAtom()
+ case "0":
+ return this.nulCharacterAtom()
+ case "x":
+ return this.hexEscapeSequenceAtom()
+ case "u":
+ return this.regExpUnicodeEscapeSequenceAtom()
+ default:
+ return this.identityEscapeAtom()
+ }
+ }
+
+ RegExpParser.prototype.decimalEscapeAtom = function() {
+ var value = this.positiveInteger()
+
+ return { type: "GroupBackReference", value: value }
+ }
+
+ RegExpParser.prototype.characterClassEscape = function() {
+ var set
+ var complement = false
+ switch (this.popChar()) {
+ case "d":
+ set = digitsCharCodes
+ break
+ case "D":
+ set = digitsCharCodes
+ complement = true
+ break
+ case "s":
+ set = whitespaceCodes
+ break
+ case "S":
+ set = whitespaceCodes
+ complement = true
+ break
+ case "w":
+ set = wordCharCodes
+ break
+ case "W":
+ set = wordCharCodes
+ complement = true
+ break
+ }
+
+ ASSERT_EXISTS(set)
+
+ return { type: "Set", value: set, complement: complement }
+ }
+
+ RegExpParser.prototype.controlEscapeAtom = function() {
+ var escapeCode
+ switch (this.popChar()) {
+ case "f":
+ escapeCode = cc("\f")
+ break
+ case "n":
+ escapeCode = cc("\n")
+ break
+ case "r":
+ escapeCode = cc("\r")
+ break
+ case "t":
+ escapeCode = cc("\t")
+ break
+ case "v":
+ escapeCode = cc("\v")
+ break
+ }
+ ASSERT_EXISTS(escapeCode)
+
+ return { type: "Character", value: escapeCode }
+ }
+
+ RegExpParser.prototype.controlLetterEscapeAtom = function() {
+ this.consumeChar("c")
+ var letter = this.popChar()
+ if (/[a-zA-Z]/.test(letter) === false) {
+ throw Error("Invalid ")
+ }
+
+ var letterCode = letter.toUpperCase().charCodeAt(0) - 64
+ return { type: "Character", value: letterCode }
+ }
+
+ RegExpParser.prototype.nulCharacterAtom = function() {
+ // TODO implement '[lookahead ∉ DecimalDigit]'
+ // TODO: for the deprecated octal escape sequence
+ this.consumeChar("0")
+ return { type: "Character", value: cc("\0") }
+ }
+
+ RegExpParser.prototype.hexEscapeSequenceAtom = function() {
+ this.consumeChar("x")
+ return this.parseHexDigits(2)
+ }
+
+ RegExpParser.prototype.regExpUnicodeEscapeSequenceAtom = function() {
+ this.consumeChar("u")
+ return this.parseHexDigits(4)
+ }
+
+ RegExpParser.prototype.identityEscapeAtom = function() {
+ // TODO: implement "SourceCharacter but not UnicodeIDContinue"
+ // // http://unicode.org/reports/tr31/#Specific_Character_Adjustments
+ var escapedChar = this.popChar()
+ return { type: "Character", value: cc(escapedChar) }
+ }
+
+ RegExpParser.prototype.classPatternCharacterAtom = function() {
+ switch (this.peekChar()) {
+ // istanbul ignore next
+ case "\n":
+ // istanbul ignore next
+ case "\r":
+ // istanbul ignore next
+ case "\u2028":
+ // istanbul ignore next
+ case "\u2029":
+ // istanbul ignore next
+ case "\\":
+ // istanbul ignore next
+ case "]":
+ throw Error("TBD")
+ default:
+ var nextChar = this.popChar()
+ return { type: "Character", value: cc(nextChar) }
+ }
+ }
+
+ RegExpParser.prototype.characterClass = function() {
+ var set = []
+ var complement = false
+ this.consumeChar("[")
+ if (this.peekChar(0) === "^") {
+ this.consumeChar("^")
+ complement = true
+ }
+
+ while (this.isClassAtom()) {
+ var from = this.classAtom()
+ var isFromSingleChar = from.type === "Character"
+ if (isFromSingleChar && this.isRangeDash()) {
+ this.consumeChar("-")
+ var to = this.classAtom()
+ var isToSingleChar = to.type === "Character"
+
+ // a range can only be used when both sides are single characters
+ if (isToSingleChar) {
+ if (to.value < from.value) {
+ throw Error("Range out of order in character class")
+ }
+ set.push({ from: from.value, to: to.value })
+ } else {
+ // literal dash
+ insertToSet(from.value, set)
+ set.push(cc("-"))
+ insertToSet(to.value, set)
+ }
+ } else {
+ insertToSet(from.value, set)
+ }
+ }
+
+ this.consumeChar("]")
+
+ return { type: "Set", complement: complement, value: set }
+ }
+
+ RegExpParser.prototype.classAtom = function() {
+ switch (this.peekChar()) {
+ // istanbul ignore next
+ case "]":
+ // istanbul ignore next
+ case "\n":
+ // istanbul ignore next
+ case "\r":
+ // istanbul ignore next
+ case "\u2028":
+ // istanbul ignore next
+ case "\u2029":
+ throw Error("TBD")
+ case "\\":
+ return this.classEscape()
+ default:
+ return this.classPatternCharacterAtom()
+ }
+ }
+
+ RegExpParser.prototype.classEscape = function() {
+ this.consumeChar("\\")
+ switch (this.peekChar()) {
+ // Matches a backspace.
+ // (Not to be confused with \b word boundary outside characterClass)
+ case "b":
+ this.consumeChar("b")
+ return { type: "Character", value: cc("\u0008") }
+ case "d":
+ case "D":
+ case "s":
+ case "S":
+ case "w":
+ case "W":
+ return this.characterClassEscape()
+ case "f":
+ case "n":
+ case "r":
+ case "t":
+ case "v":
+ return this.controlEscapeAtom()
+ case "c":
+ return this.controlLetterEscapeAtom()
+ case "0":
+ return this.nulCharacterAtom()
+ case "x":
+ return this.hexEscapeSequenceAtom()
+ case "u":
+ return this.regExpUnicodeEscapeSequenceAtom()
+ default:
+ return this.identityEscapeAtom()
+ }
+ }
+
+ RegExpParser.prototype.group = function() {
+ var capturing = true
+ this.consumeChar("(")
+ switch (this.peekChar(0)) {
+ case "?":
+ this.consumeChar("?")
+ this.consumeChar(":")
+ capturing = false
+ break
+ default:
+ this.groupIdx++
+ break
+ }
+ var value = this.disjunction()
+ this.consumeChar(")")
+
+ var groupAst = {
+ type: "Group",
+ capturing: capturing,
+ value: value
+ }
+
+ if (capturing) {
+ groupAst.idx = this.groupIdx
+ }
+
+ return groupAst
+ }
+
+ RegExpParser.prototype.positiveInteger = function() {
+ var number = this.popChar()
+
+ // istanbul ignore next - can't ever get here due to previous lookahead checks
+ // still implementing this error checking in case this ever changes.
+ if (decimalPatternNoZero.test(number) === false) {
+ throw Error("Expecting a positive integer")
+ }
+
+ while (decimalPattern.test(this.peekChar(0))) {
+ number += this.popChar()
+ }
+
+ return parseInt(number, 10)
+ }
+
+ RegExpParser.prototype.integerIncludingZero = function() {
+ var number = this.popChar()
+ if (decimalPattern.test(number) === false) {
+ throw Error("Expecting an integer")
+ }
+
+ while (decimalPattern.test(this.peekChar(0))) {
+ number += this.popChar()
+ }
+
+ return parseInt(number, 10)
+ }
+
+ RegExpParser.prototype.patternCharacter = function() {
+ var nextChar = this.popChar()
+ switch (nextChar) {
+ // istanbul ignore next
+ case "\n":
+ // istanbul ignore next
+ case "\r":
+ // istanbul ignore next
+ case "\u2028":
+ // istanbul ignore next
+ case "\u2029":
+ // istanbul ignore next
+ case "^":
+ // istanbul ignore next
+ case "$":
+ // istanbul ignore next
+ case "\\":
+ // istanbul ignore next
+ case ".":
+ // istanbul ignore next
+ case "*":
+ // istanbul ignore next
+ case "+":
+ // istanbul ignore next
+ case "?":
+ // istanbul ignore next
+ case "(":
+ // istanbul ignore next
+ case ")":
+ // istanbul ignore next
+ case "[":
+ // istanbul ignore next
+ case "|":
+ // istanbul ignore next
+ throw Error("TBD")
+ default:
+ return { type: "Character", value: cc(nextChar) }
+ }
+ }
+ RegExpParser.prototype.isRegExpFlag = function() {
+ switch (this.peekChar(0)) {
+ case "g":
+ case "i":
+ case "m":
+ case "u":
+ case "y":
+ return true
+ default:
+ return false
+ }
+ }
+
+ RegExpParser.prototype.isRangeDash = function() {
+ return this.peekChar() === "-" && this.isClassAtom(1)
+ }
+
+ RegExpParser.prototype.isDigit = function() {
+ return decimalPattern.test(this.peekChar(0))
+ }
+
+ RegExpParser.prototype.isClassAtom = function(howMuch) {
+ if (howMuch === undefined) {
+ howMuch = 0
+ }
+
+ switch (this.peekChar(howMuch)) {
+ case "]":
+ case "\n":
+ case "\r":
+ case "\u2028":
+ case "\u2029":
+ return false
+ default:
+ return true
+ }
+ }
+
+ RegExpParser.prototype.isTerm = function() {
+ return this.isAtom() || this.isAssertion()
+ }
+
+ RegExpParser.prototype.isAtom = function() {
+ if (this.isPatternCharacter()) {
+ return true
+ }
+
+ switch (this.peekChar(0)) {
+ case ".":
+ case "\\": // atomEscape
+ case "[": // characterClass
+ // TODO: isAtom must be called before isAssertion - disambiguate
+ case "(": // group
+ return true
+ default:
+ return false
+ }
+ }
+
+ RegExpParser.prototype.isAssertion = function() {
+ switch (this.peekChar(0)) {
+ case "^":
+ case "$":
+ return true
+ // '\b' or '\B'
+ case "\\":
+ switch (this.peekChar(1)) {
+ case "b":
+ case "B":
+ return true
+ default:
+ return false
+ }
+ // '(?=' or '(?!'
+ case "(":
+ return (
+ this.peekChar(1) === "?" &&
+ (this.peekChar(2) === "=" || this.peekChar(2) === "!")
+ )
+ default:
+ return false
+ }
+ }
+
+ RegExpParser.prototype.isQuantifier = function() {
+ var prevState = this.saveState()
+ try {
+ return this.quantifier(true) !== undefined
+ } catch (e) {
+ return false
+ } finally {
+ this.restoreState(prevState)
+ }
+ }
+
+ RegExpParser.prototype.isPatternCharacter = function() {
+ switch (this.peekChar()) {
+ case "^":
+ case "$":
+ case "\\":
+ case ".":
+ case "*":
+ case "+":
+ case "?":
+ case "(":
+ case ")":
+ case "[":
+ case "|":
+ case "/":
+ case "\n":
+ case "\r":
+ case "\u2028":
+ case "\u2029":
+ return false
+ default:
+ return true
+ }
+ }
+
+ RegExpParser.prototype.parseHexDigits = function(howMany) {
+ var hexString = ""
+ for (var i = 0; i < howMany; i++) {
+ var hexChar = this.popChar()
+ if (hexDigitPattern.test(hexChar) === false) {
+ throw Error("Expecting a HexDecimal digits")
+ }
+ hexString += hexChar
+ }
+ var charCode = parseInt(hexString, 16)
+ return { type: "Character", value: charCode }
+ }
+
+ RegExpParser.prototype.peekChar = function(howMuch) {
+ if (howMuch === undefined) {
+ howMuch = 0
+ }
+ return this.input[this.idx + howMuch]
+ }
+
+ RegExpParser.prototype.popChar = function() {
+ var nextChar = this.peekChar(0)
+ this.consumeChar()
+ return nextChar
+ }
+
+ RegExpParser.prototype.consumeChar = function(char) {
+ if (char !== undefined && this.input[this.idx] !== char) {
+ throw Error(
+ "Expected: '" +
+ char +
+ "' but found: '" +
+ this.input[this.idx] +
+ "' at offset: " +
+ this.idx
+ )
+ }
+
+ if (this.idx >= this.input.length) {
+ throw Error("Unexpected end of input")
+ }
+ this.idx++
+ }
+
+ // consts and utilities
+ var hexDigitPattern = /[0-9a-fA-F]/
+ var decimalPattern = /[0-9]/
+ var decimalPatternNoZero = /[1-9]/
+
+ function cc(char) {
+ return char.charCodeAt(0)
+ }
+
+ function insertToSet(item, set) {
+ if (item.length !== undefined) {
+ item.forEach(function(subItem) {
+ set.push(subItem)
+ })
+ } else {
+ set.push(item)
+ }
+ }
+
+ function addFlag(flagObj, flagKey) {
+ if (flagObj[flagKey] === true) {
+ throw "duplicate flag " + flagKey
+ }
+
+ flagObj[flagKey] = true
+ }
+
+ function ASSERT_EXISTS(obj) {
+ // istanbul ignore next
+ if (obj === undefined) {
+ throw Error("Internal Error - Should never get here!")
+ }
+ }
+
+ // istanbul ignore next
+ function ASSERT_NEVER_REACH_HERE() {
+ throw Error("Internal Error - Should never get here!")
+ }
+
+ var i
+ var digitsCharCodes = []
+ for (i = cc("0"); i <= cc("9"); i++) {
+ digitsCharCodes.push(i)
+ }
+
+ var wordCharCodes = [cc("_")].concat(digitsCharCodes)
+ for (i = cc("a"); i <= cc("z"); i++) {
+ wordCharCodes.push(i)
+ }
+
+ for (i = cc("A"); i <= cc("Z"); i++) {
+ wordCharCodes.push(i)
+ }
+
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp#character-classes
+ var whitespaceCodes = [
+ cc(" "),
+ cc("\f"),
+ cc("\n"),
+ cc("\r"),
+ cc("\t"),
+ cc("\v"),
+ cc("\t"),
+ cc("\u00a0"),
+ cc("\u1680"),
+ cc("\u2000"),
+ cc("\u2001"),
+ cc("\u2002"),
+ cc("\u2003"),
+ cc("\u2004"),
+ cc("\u2005"),
+ cc("\u2006"),
+ cc("\u2007"),
+ cc("\u2008"),
+ cc("\u2009"),
+ cc("\u200a"),
+ cc("\u2028"),
+ cc("\u2029"),
+ cc("\u202f"),
+ cc("\u205f"),
+ cc("\u3000"),
+ cc("\ufeff")
+ ]
+
+ function BaseRegExpVisitor() {}
+
+ BaseRegExpVisitor.prototype.visitChildren = function(node) {
+ for (var key in node) {
+ var child = node[key]
+ /* istanbul ignore else */
+ if (node.hasOwnProperty(key)) {
+ if (child.type !== undefined) {
+ this.visit(child)
+ } else if (Array.isArray(child)) {
+ child.forEach(function(subChild) {
+ this.visit(subChild)
+ }, this)
+ }
+ }
+ }
+ }
+
+ BaseRegExpVisitor.prototype.visit = function(node) {
+ switch (node.type) {
+ case "Pattern":
+ this.visitPattern(node)
+ break
+ case "Flags":
+ this.visitFlags(node)
+ break
+ case "Disjunction":
+ this.visitDisjunction(node)
+ break
+ case "Alternative":
+ this.visitAlternative(node)
+ break
+ case "StartAnchor":
+ this.visitStartAnchor(node)
+ break
+ case "EndAnchor":
+ this.visitEndAnchor(node)
+ break
+ case "WordBoundary":
+ this.visitWordBoundary(node)
+ break
+ case "NonWordBoundary":
+ this.visitNonWordBoundary(node)
+ break
+ case "Lookahead":
+ this.visitLookahead(node)
+ break
+ case "NegativeLookahead":
+ this.visitNegativeLookahead(node)
+ break
+ case "Character":
+ this.visitCharacter(node)
+ break
+ case "Set":
+ this.visitSet(node)
+ break
+ case "Group":
+ this.visitGroup(node)
+ break
+ case "GroupBackReference":
+ this.visitGroupBackReference(node)
+ break
+ case "Quantifier":
+ this.visitQuantifier(node)
+ break
+ }
+
+ this.visitChildren(node)
+ }
+
+ BaseRegExpVisitor.prototype.visitPattern = function(node) {}
+
+ BaseRegExpVisitor.prototype.visitFlags = function(node) {}
+
+ BaseRegExpVisitor.prototype.visitDisjunction = function(node) {}
+
+ BaseRegExpVisitor.prototype.visitAlternative = function(node) {}
+
+ // Assertion
+ BaseRegExpVisitor.prototype.visitStartAnchor = function(node) {}
+
+ BaseRegExpVisitor.prototype.visitEndAnchor = function(node) {}
+
+ BaseRegExpVisitor.prototype.visitWordBoundary = function(node) {}
+
+ BaseRegExpVisitor.prototype.visitNonWordBoundary = function(node) {}
+
+ BaseRegExpVisitor.prototype.visitLookahead = function(node) {}
+
+ BaseRegExpVisitor.prototype.visitNegativeLookahead = function(node) {}
+
+ // atoms
+ BaseRegExpVisitor.prototype.visitCharacter = function(node) {}
+
+ BaseRegExpVisitor.prototype.visitSet = function(node) {}
+
+ BaseRegExpVisitor.prototype.visitGroup = function(node) {}
+
+ BaseRegExpVisitor.prototype.visitGroupBackReference = function(node) {}
+
+ BaseRegExpVisitor.prototype.visitQuantifier = function(node) {}
+
+ return {
+ RegExpParser: RegExpParser,
+ BaseRegExpVisitor: BaseRegExpVisitor,
+ VERSION: "0.4.0"
+ }
+ }
+)
+
+
+/***/ }),
+/* 16 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var regexp_to_ast_1 = __webpack_require__(15);
+var regExpAstCache = {};
+var regExpParser = new regexp_to_ast_1.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;
+ }
+}
+exports.getRegExpAst = getRegExpAst;
+function clearRegExpParserCache() {
+ regExpAstCache = {};
+}
+exports.clearRegExpParserCache = clearRegExpParserCache;
+//# sourceMappingURL=reg_exp_parser.js.map
+
+/***/ }),
+/* 17 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+var keys_1 = __webpack_require__(7);
+var gast_public_1 = __webpack_require__(1);
+var gast_visitor_public_1 = __webpack_require__(4);
+/**
+ * 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;
+ }
+}
+exports.setNodeLocationOnlyOffset = setNodeLocationOnlyOffset;
+/**
+ * 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;
+ }
+}
+exports.setNodeLocationFull = setNodeLocationFull;
+function addTerminalToCst(node, token, tokenTypeName) {
+ if (node.children[tokenTypeName] === undefined) {
+ node.children[tokenTypeName] = [token];
+ }
+ else {
+ node.children[tokenTypeName].push(token);
+ }
+}
+exports.addTerminalToCst = addTerminalToCst;
+function addNoneTerminalToCst(node, ruleName, ruleResult) {
+ if (node.children[ruleName] === undefined) {
+ node.children[ruleName] = [ruleResult];
+ }
+ else {
+ node.children[ruleName].push(ruleResult);
+ }
+}
+exports.addNoneTerminalToCst = addNoneTerminalToCst;
+var NamedDSLMethodsCollectorVisitor = /** @class */ (function (_super) {
+ __extends(NamedDSLMethodsCollectorVisitor, _super);
+ function NamedDSLMethodsCollectorVisitor(ruleIdx) {
+ var _this = _super.call(this) || this;
+ _this.result = [];
+ _this.ruleIdx = ruleIdx;
+ return _this;
+ }
+ NamedDSLMethodsCollectorVisitor.prototype.collectNamedDSLMethod = function (node, newNodeConstructor, methodIdx) {
+ // TODO: better hack to copy what we need here...
+ if (!utils_1.isUndefined(node.name)) {
+ // copy without name so this will indeed be processed later.
+ var nameLessNode
+ /* istanbul ignore else */
+ = void 0;
+ /* istanbul ignore else */
+ if (node instanceof gast_public_1.Option ||
+ node instanceof gast_public_1.Repetition ||
+ node instanceof gast_public_1.RepetitionMandatory ||
+ node instanceof gast_public_1.Alternation) {
+ nameLessNode = new newNodeConstructor({
+ definition: node.definition,
+ idx: node.idx
+ });
+ }
+ else if (node instanceof gast_public_1.RepetitionMandatoryWithSeparator ||
+ node instanceof gast_public_1.RepetitionWithSeparator) {
+ nameLessNode = new newNodeConstructor({
+ definition: node.definition,
+ idx: node.idx,
+ separator: node.separator
+ });
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ var def = [nameLessNode];
+ var key = keys_1.getKeyForAutomaticLookahead(this.ruleIdx, methodIdx, node.idx);
+ this.result.push({ def: def, key: key, name: node.name, orgProd: node });
+ }
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitOption = function (node) {
+ this.collectNamedDSLMethod(node, gast_public_1.Option, keys_1.OPTION_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitRepetition = function (node) {
+ this.collectNamedDSLMethod(node, gast_public_1.Repetition, keys_1.MANY_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionMandatory = function (node) {
+ this.collectNamedDSLMethod(node, gast_public_1.RepetitionMandatory, keys_1.AT_LEAST_ONE_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) {
+ this.collectNamedDSLMethod(node, gast_public_1.RepetitionMandatoryWithSeparator, keys_1.AT_LEAST_ONE_SEP_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionWithSeparator = function (node) {
+ this.collectNamedDSLMethod(node, gast_public_1.RepetitionWithSeparator, keys_1.MANY_SEP_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitAlternation = function (node) {
+ var _this = this;
+ this.collectNamedDSLMethod(node, gast_public_1.Alternation, keys_1.OR_IDX);
+ var hasMoreThanOneAlternative = node.definition.length > 1;
+ utils_1.forEach(node.definition, function (currFlatAlt, altIdx) {
+ if (!utils_1.isUndefined(currFlatAlt.name)) {
+ var def = currFlatAlt.definition;
+ if (hasMoreThanOneAlternative) {
+ def = [new gast_public_1.Option({ definition: currFlatAlt.definition })];
+ }
+ else {
+ // mandatory
+ def = currFlatAlt.definition;
+ }
+ var key = keys_1.getKeyForAltIndex(_this.ruleIdx, keys_1.OR_IDX, node.idx, altIdx);
+ _this.result.push({
+ def: def,
+ key: key,
+ name: currFlatAlt.name,
+ orgProd: currFlatAlt
+ });
+ }
+ });
+ };
+ return NamedDSLMethodsCollectorVisitor;
+}(gast_visitor_public_1.GAstVisitor));
+exports.NamedDSLMethodsCollectorVisitor = NamedDSLMethodsCollectorVisitor;
+function expandAllNestedRuleNames(topRules, fullToShortName) {
+ var result = {
+ allRuleNames: []
+ };
+ utils_1.forEach(topRules, function (currTopRule) {
+ var currTopRuleShortName = fullToShortName[currTopRule.name];
+ result.allRuleNames.push(currTopRule.name);
+ var namedCollectorVisitor = new NamedDSLMethodsCollectorVisitor(currTopRuleShortName);
+ currTopRule.accept(namedCollectorVisitor);
+ utils_1.forEach(namedCollectorVisitor.result, function (_a) {
+ var def = _a.def, key = _a.key, name = _a.name;
+ result.allRuleNames.push(currTopRule.name + name);
+ });
+ });
+ return result;
+}
+exports.expandAllNestedRuleNames = expandAllNestedRuleNames;
+//# sourceMappingURL=cst.js.map
+
+/***/ }),
+/* 18 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+// semantic version
+var version_1 = __webpack_require__(19);
+exports.VERSION = version_1.VERSION;
+var parser_1 = __webpack_require__(2);
+exports.Parser = parser_1.Parser;
+exports.CstParser = parser_1.CstParser;
+exports.EmbeddedActionsParser = parser_1.EmbeddedActionsParser;
+exports.ParserDefinitionErrorType = parser_1.ParserDefinitionErrorType;
+exports.EMPTY_ALT = parser_1.EMPTY_ALT;
+var lexer_public_1 = __webpack_require__(9);
+exports.Lexer = lexer_public_1.Lexer;
+exports.LexerDefinitionErrorType = lexer_public_1.LexerDefinitionErrorType;
+// Tokens utilities
+var tokens_public_1 = __webpack_require__(3);
+exports.createToken = tokens_public_1.createToken;
+exports.createTokenInstance = tokens_public_1.createTokenInstance;
+exports.EOF = tokens_public_1.EOF;
+exports.tokenLabel = tokens_public_1.tokenLabel;
+exports.tokenMatcher = tokens_public_1.tokenMatcher;
+exports.tokenName = tokens_public_1.tokenName;
+// Other Utilities
+var errors_public_1 = __webpack_require__(10);
+exports.defaultGrammarResolverErrorProvider = errors_public_1.defaultGrammarResolverErrorProvider;
+exports.defaultGrammarValidatorErrorProvider = errors_public_1.defaultGrammarValidatorErrorProvider;
+exports.defaultParserErrorProvider = errors_public_1.defaultParserErrorProvider;
+var exceptions_public_1 = __webpack_require__(8);
+exports.EarlyExitException = exceptions_public_1.EarlyExitException;
+exports.isRecognitionException = exceptions_public_1.isRecognitionException;
+exports.MismatchedTokenException = exceptions_public_1.MismatchedTokenException;
+exports.NotAllInputParsedException = exceptions_public_1.NotAllInputParsedException;
+exports.NoViableAltException = exceptions_public_1.NoViableAltException;
+var lexer_errors_public_1 = __webpack_require__(21);
+exports.defaultLexerErrorProvider = lexer_errors_public_1.defaultLexerErrorProvider;
+// grammar reflection API
+var gast_public_1 = __webpack_require__(1);
+exports.Alternation = gast_public_1.Alternation;
+exports.Flat = gast_public_1.Flat;
+exports.NonTerminal = gast_public_1.NonTerminal;
+exports.Option = gast_public_1.Option;
+exports.Repetition = gast_public_1.Repetition;
+exports.RepetitionMandatory = gast_public_1.RepetitionMandatory;
+exports.RepetitionMandatoryWithSeparator = gast_public_1.RepetitionMandatoryWithSeparator;
+exports.RepetitionWithSeparator = gast_public_1.RepetitionWithSeparator;
+exports.Rule = gast_public_1.Rule;
+exports.Terminal = gast_public_1.Terminal;
+// GAST Utilities
+var gast_public_2 = __webpack_require__(1);
+exports.serializeGrammar = gast_public_2.serializeGrammar;
+exports.serializeProduction = gast_public_2.serializeProduction;
+var gast_visitor_public_1 = __webpack_require__(4);
+exports.GAstVisitor = gast_visitor_public_1.GAstVisitor;
+var gast_resolver_public_1 = __webpack_require__(24);
+exports.assignOccurrenceIndices = gast_resolver_public_1.assignOccurrenceIndices;
+exports.resolveGrammar = gast_resolver_public_1.resolveGrammar;
+exports.validateGrammar = gast_resolver_public_1.validateGrammar;
+/* 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");
+}
+exports.clearCache = clearCache;
+var render_public_1 = __webpack_require__(40);
+exports.createSyntaxDiagramsCode = render_public_1.createSyntaxDiagramsCode;
+var generate_public_1 = __webpack_require__(41);
+exports.generateParserFactory = generate_public_1.generateParserFactory;
+exports.generateParserModule = generate_public_1.generateParserModule;
+//# sourceMappingURL=api.js.map
+
+/***/ }),
+/* 19 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+// 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.
+exports.VERSION = "6.5.0";
+//# sourceMappingURL=version.js.map
+
+/***/ }),
+/* 20 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var regexp_to_ast_1 = __webpack_require__(15);
+var lexer_public_1 = __webpack_require__(9);
+var utils_1 = __webpack_require__(0);
+var reg_exp_1 = __webpack_require__(28);
+var reg_exp_parser_1 = __webpack_require__(16);
+var PATTERN = "PATTERN";
+exports.DEFAULT_MODE = "defaultMode";
+exports.MODES = "modes";
+exports.SUPPORT_STICKY = typeof new RegExp("(?:)").sticky === "boolean";
+function disableSticky() {
+ exports.SUPPORT_STICKY = false;
+}
+exports.disableSticky = disableSticky;
+function enableSticky() {
+ exports.SUPPORT_STICKY = true;
+}
+exports.enableSticky = enableSticky;
+function analyzeTokenTypes(tokenTypes, options) {
+ options = utils_1.defaults(options, {
+ useSticky: exports.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 = utils_1.reject(tokenTypes, function (currType) {
+ return currType[PATTERN] === lexer_public_1.Lexer.NA;
+ });
+ });
+ var hasCustom = false;
+ var allTransformedPatterns;
+ tracer("Transform Patterns", function () {
+ hasCustom = false;
+ allTransformedPatterns = utils_1.map(onlyRelevantTypes, function (currType) {
+ var currPattern = currType[PATTERN];
+ /* istanbul ignore else */
+ if (utils_1.isRegExp(currPattern)) {
+ var regExpSource = currPattern.source;
+ if (regExpSource.length === 1 &&
+ // only these regExp meta characters which can appear in a length one regExp
+ regExpSource !== "^" &&
+ regExpSource !== "$" &&
+ regExpSource !== ".") {
+ return regExpSource;
+ }
+ else if (regExpSource.length === 2 &&
+ regExpSource[0] === "\\" &&
+ // not a meta character
+ !utils_1.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 (utils_1.isFunction(currPattern)) {
+ hasCustom = true;
+ // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object
+ return { exec: currPattern };
+ }
+ else if (utils_1.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 = utils_1.map(onlyRelevantTypes, function (currType) { return currType.tokenTypeIdx; });
+ patternIdxToGroup = utils_1.map(onlyRelevantTypes, function (clazz) {
+ var groupName = clazz.GROUP;
+ /* istanbul ignore next */
+ if (groupName === lexer_public_1.Lexer.SKIPPED) {
+ return undefined;
+ }
+ else if (utils_1.isString(groupName)) {
+ return groupName;
+ }
+ else if (utils_1.isUndefined(groupName)) {
+ return false;
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ });
+ patternIdxToLongerAltIdx = utils_1.map(onlyRelevantTypes, function (clazz) {
+ var longerAltType = clazz.LONGER_ALT;
+ if (longerAltType) {
+ var longerAltIdx = utils_1.indexOf(onlyRelevantTypes, longerAltType);
+ return longerAltIdx;
+ }
+ });
+ patternIdxToPushMode = utils_1.map(onlyRelevantTypes, function (clazz) { return clazz.PUSH_MODE; });
+ patternIdxToPopMode = utils_1.map(onlyRelevantTypes, function (clazz) {
+ return utils_1.has(clazz, "POP_MODE");
+ });
+ });
+ var patternIdxToCanLineTerminator;
+ tracer("Line Terminator Handling", function () {
+ var lineTerminatorCharCodes = getCharCodes(options.lineTerminatorCharacters);
+ patternIdxToCanLineTerminator = utils_1.map(onlyRelevantTypes, function (tokType) { return false; });
+ if (options.positionTracking !== "onlyOffset") {
+ patternIdxToCanLineTerminator = utils_1.map(onlyRelevantTypes, function (tokType) {
+ if (utils_1.has(tokType, "LINE_BREAKS")) {
+ return tokType.LINE_BREAKS;
+ }
+ else {
+ if (checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false) {
+ return reg_exp_1.canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN);
+ }
+ }
+ });
+ }
+ });
+ var patternIdxToIsCustom;
+ var patternIdxToShort;
+ var emptyGroups;
+ var patternIdxToConfig;
+ tracer("Misc Mapping #2", function () {
+ patternIdxToIsCustom = utils_1.map(onlyRelevantTypes, isCustomPattern);
+ patternIdxToShort = utils_1.map(allTransformedPatterns, isShortPattern);
+ emptyGroups = utils_1.reduce(onlyRelevantTypes, function (acc, clazz) {
+ var groupName = clazz.GROUP;
+ if (utils_1.isString(groupName) && !(groupName === lexer_public_1.Lexer.SKIPPED)) {
+ acc[groupName] = [];
+ }
+ return acc;
+ }, {});
+ patternIdxToConfig = utils_1.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 = utils_1.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 (utils_1.isArray(currTokType.START_CHARS_HINT)) {
+ var lastOptimizedIdx_1;
+ utils_1.forEach(currTokType.START_CHARS_HINT, function (charOrInt) {
+ var charCode = typeof charOrInt === "string"
+ ? charOrInt.charCodeAt(0)
+ : charOrInt;
+ var currOptimizedIdx = charCodeToOptimizedIndex(charCode);
+ // Avoid adding the config multiple times
+ if (lastOptimizedIdx_1 !== currOptimizedIdx) {
+ lastOptimizedIdx_1 = currOptimizedIdx;
+ addToMapOfArrays(result, currOptimizedIdx, patternIdxToConfig[idx]);
+ }
+ });
+ }
+ else if (utils_1.isRegExp(currTokType.PATTERN)) {
+ if (currTokType.PATTERN.unicode) {
+ canBeOptimized = false;
+ if (options.ensureOptimizations) {
+ utils_1.PRINT_ERROR("" + reg_exp_1.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 = reg_exp_1.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 (utils_1.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;
+ }
+ utils_1.forEach(optimizedCodes, function (code) {
+ addToMapOfArrays(result, code, patternIdxToConfig[idx]);
+ });
+ }
+ }
+ else {
+ if (options.ensureOptimizations) {
+ utils_1.PRINT_ERROR("" + reg_exp_1.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 = utils_1.packArray(charCodeToPatternIdxToConfig);
+ });
+ return {
+ emptyGroups: emptyGroups,
+ patternIdxToConfig: patternIdxToConfig,
+ charCodeToPatternIdxToConfig: charCodeToPatternIdxToConfig,
+ hasCustom: hasCustom,
+ canBeOptimized: canBeOptimized
+ };
+}
+exports.analyzeTokenTypes = analyzeTokenTypes;
+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;
+}
+exports.validatePatterns = validatePatterns;
+function validateRegExpPattern(tokenTypes) {
+ var errors = [];
+ var withRegExpPatterns = utils_1.filter(tokenTypes, function (currTokType) {
+ return utils_1.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 = utils_1.filter(tokenTypes, function (currType) {
+ return !utils_1.has(currType, PATTERN);
+ });
+ var errors = utils_1.map(tokenTypesWithMissingPattern, function (currType) {
+ return {
+ message: "Token Type: ->" +
+ currType.name +
+ "<- missing static 'PATTERN' property",
+ type: lexer_public_1.LexerDefinitionErrorType.MISSING_PATTERN,
+ tokenTypes: [currType]
+ };
+ });
+ var valid = utils_1.difference(tokenTypes, tokenTypesWithMissingPattern);
+ return { errors: errors, valid: valid };
+}
+exports.findMissingPatterns = findMissingPatterns;
+function findInvalidPatterns(tokenTypes) {
+ var tokenTypesWithInvalidPattern = utils_1.filter(tokenTypes, function (currType) {
+ var pattern = currType[PATTERN];
+ return (!utils_1.isRegExp(pattern) &&
+ !utils_1.isFunction(pattern) &&
+ !utils_1.has(pattern, "exec") &&
+ !utils_1.isString(pattern));
+ });
+ var errors = utils_1.map(tokenTypesWithInvalidPattern, function (currType) {
+ return {
+ message: "Token Type: ->" +
+ currType.name +
+ "<- static 'PATTERN' can only be a RegExp, a" +
+ " Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",
+ type: lexer_public_1.LexerDefinitionErrorType.INVALID_PATTERN,
+ tokenTypes: [currType]
+ };
+ });
+ var valid = utils_1.difference(tokenTypes, tokenTypesWithInvalidPattern);
+ return { errors: errors, valid: valid };
+}
+exports.findInvalidPatterns = findInvalidPatterns;
+var end_of_input = /[^\\][\$]/;
+function findEndOfInputAnchor(tokenTypes) {
+ var EndAnchorFinder = /** @class */ (function (_super) {
+ __extends(EndAnchorFinder, _super);
+ function EndAnchorFinder() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.found = false;
+ return _this;
+ }
+ EndAnchorFinder.prototype.visitEndAnchor = function (node) {
+ this.found = true;
+ };
+ return EndAnchorFinder;
+ }(regexp_to_ast_1.BaseRegExpVisitor));
+ var invalidRegex = utils_1.filter(tokenTypes, function (currType) {
+ var pattern = currType[PATTERN];
+ try {
+ var regexpAst = reg_exp_parser_1.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 = utils_1.map(invalidRegex, function (currType) {
+ return {
+ message: "Unexpected RegExp Anchor Error:\n" +
+ "\tToken Type: ->" +
+ currType.name +
+ "<- static 'PATTERN' cannot contain end of input anchor '$'\n" +
+ "\tSee sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#ANCHORS" +
+ "\tfor details.",
+ type: lexer_public_1.LexerDefinitionErrorType.EOI_ANCHOR_FOUND,
+ tokenTypes: [currType]
+ };
+ });
+ return errors;
+}
+exports.findEndOfInputAnchor = findEndOfInputAnchor;
+function findEmptyMatchRegExps(tokenTypes) {
+ var matchesEmptyString = utils_1.filter(tokenTypes, function (currType) {
+ var pattern = currType[PATTERN];
+ return pattern.test("");
+ });
+ var errors = utils_1.map(matchesEmptyString, function (currType) {
+ return {
+ message: "Token Type: ->" +
+ currType.name +
+ "<- static 'PATTERN' must not match an empty string",
+ type: lexer_public_1.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,
+ tokenTypes: [currType]
+ };
+ });
+ return errors;
+}
+exports.findEmptyMatchRegExps = findEmptyMatchRegExps;
+var start_of_input = /[^\\[][\^]|^\^/;
+function findStartOfInputAnchor(tokenTypes) {
+ var StartAnchorFinder = /** @class */ (function (_super) {
+ __extends(StartAnchorFinder, _super);
+ function StartAnchorFinder() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.found = false;
+ return _this;
+ }
+ StartAnchorFinder.prototype.visitStartAnchor = function (node) {
+ this.found = true;
+ };
+ return StartAnchorFinder;
+ }(regexp_to_ast_1.BaseRegExpVisitor));
+ var invalidRegex = utils_1.filter(tokenTypes, function (currType) {
+ var pattern = currType[PATTERN];
+ try {
+ var regexpAst = reg_exp_parser_1.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 = utils_1.map(invalidRegex, function (currType) {
+ return {
+ message: "Unexpected RegExp Anchor Error:\n" +
+ "\tToken Type: ->" +
+ currType.name +
+ "<- static 'PATTERN' cannot contain start of input anchor '^'\n" +
+ "\tSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#ANCHORS" +
+ "\tfor details.",
+ type: lexer_public_1.LexerDefinitionErrorType.SOI_ANCHOR_FOUND,
+ tokenTypes: [currType]
+ };
+ });
+ return errors;
+}
+exports.findStartOfInputAnchor = findStartOfInputAnchor;
+function findUnsupportedFlags(tokenTypes) {
+ var invalidFlags = utils_1.filter(tokenTypes, function (currType) {
+ var pattern = currType[PATTERN];
+ return (pattern instanceof RegExp && (pattern.multiline || pattern.global));
+ });
+ var errors = utils_1.map(invalidFlags, function (currType) {
+ return {
+ message: "Token Type: ->" +
+ currType.name +
+ "<- static 'PATTERN' may NOT contain global('g') or multiline('m')",
+ type: lexer_public_1.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,
+ tokenTypes: [currType]
+ };
+ });
+ return errors;
+}
+exports.findUnsupportedFlags = findUnsupportedFlags;
+// This can only test for identical duplicate RegExps, not semantically equivalent ones.
+function findDuplicatePatterns(tokenTypes) {
+ var found = [];
+ var identicalPatterns = utils_1.map(tokenTypes, function (outerType) {
+ return utils_1.reduce(tokenTypes, function (result, innerType) {
+ if (outerType.PATTERN.source === innerType.PATTERN.source &&
+ !utils_1.contains(found, innerType) &&
+ innerType.PATTERN !== lexer_public_1.Lexer.NA) {
+ // this avoids duplicates in the result, each Token Type may only appear in one "set"
+ // in essence we are creating Equivalence classes on equality relation.
+ found.push(innerType);
+ result.push(innerType);
+ return result;
+ }
+ return result;
+ }, []);
+ });
+ identicalPatterns = utils_1.compact(identicalPatterns);
+ var duplicatePatterns = utils_1.filter(identicalPatterns, function (currIdenticalSet) {
+ return currIdenticalSet.length > 1;
+ });
+ var errors = utils_1.map(duplicatePatterns, function (setOfIdentical) {
+ var tokenTypeNames = utils_1.map(setOfIdentical, function (currType) {
+ return currType.name;
+ });
+ var dupPatternSrc = utils_1.first(setOfIdentical).PATTERN;
+ return {
+ message: "The same RegExp pattern ->" + dupPatternSrc + "<-" +
+ ("has been used in all of the following Token Types: " + tokenTypeNames.join(", ") + " <-"),
+ type: lexer_public_1.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,
+ tokenTypes: setOfIdentical
+ };
+ });
+ return errors;
+}
+exports.findDuplicatePatterns = findDuplicatePatterns;
+function findInvalidGroupType(tokenTypes) {
+ var invalidTypes = utils_1.filter(tokenTypes, function (clazz) {
+ if (!utils_1.has(clazz, "GROUP")) {
+ return false;
+ }
+ var group = clazz.GROUP;
+ return group !== lexer_public_1.Lexer.SKIPPED && group !== lexer_public_1.Lexer.NA && !utils_1.isString(group);
+ });
+ var errors = utils_1.map(invalidTypes, function (currType) {
+ return {
+ message: "Token Type: ->" +
+ currType.name +
+ "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",
+ type: lexer_public_1.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,
+ tokenTypes: [currType]
+ };
+ });
+ return errors;
+}
+exports.findInvalidGroupType = findInvalidGroupType;
+function findModesThatDoNotExist(tokenTypes, validModes) {
+ var invalidModes = utils_1.filter(tokenTypes, function (clazz) {
+ return (clazz.PUSH_MODE !== undefined &&
+ !utils_1.contains(validModes, clazz.PUSH_MODE));
+ });
+ var errors = utils_1.map(invalidModes, function (tokType) {
+ var msg = "Token Type: ->" + tokType.name + "<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->" + tokType.PUSH_MODE + "<-" +
+ "which does not exist";
+ return {
+ message: msg,
+ type: lexer_public_1.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,
+ tokenTypes: [tokType]
+ };
+ });
+ return errors;
+}
+exports.findModesThatDoNotExist = findModesThatDoNotExist;
+function findUnreachablePatterns(tokenTypes) {
+ var errors = [];
+ var canBeTested = utils_1.reduce(tokenTypes, function (result, tokType, idx) {
+ var pattern = tokType.PATTERN;
+ if (pattern === lexer_public_1.Lexer.NA) {
+ return result;
+ }
+ // a more comprehensive validation for all forms of regExps would require
+ // deeper regExp analysis capabilities
+ if (utils_1.isString(pattern)) {
+ result.push({ str: pattern, idx: idx, tokenType: tokType });
+ }
+ else if (utils_1.isRegExp(pattern) && noMetaChar(pattern)) {
+ result.push({ str: pattern.source, idx: idx, tokenType: tokType });
+ }
+ return result;
+ }, []);
+ utils_1.forEach(tokenTypes, function (tokType, testIdx) {
+ utils_1.forEach(canBeTested, function (_a) {
+ var str = _a.str, idx = _a.idx, tokenType = _a.tokenType;
+ if (testIdx < idx && testTokenType(str, tokType.PATTERN)) {
+ var msg = "Token: ->" + tokenType.name + "<- can never be matched.\n" +
+ ("Because it appears AFTER the Token Type ->" + tokType.name + "<-") +
+ "in the lexer's definition.\n" +
+ "See https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#UNREACHABLE";
+ errors.push({
+ message: msg,
+ type: lexer_public_1.LexerDefinitionErrorType.UNREACHABLE_PATTERN,
+ tokenTypes: [tokType, tokenType]
+ });
+ }
+ });
+ });
+ return errors;
+}
+exports.findUnreachablePatterns = findUnreachablePatterns;
+function testTokenType(str, pattern) {
+ /* istanbul ignore else */
+ if (utils_1.isRegExp(pattern)) {
+ var regExpArray = pattern.exec(str);
+ return regExpArray !== null && regExpArray.index === 0;
+ }
+ else if (utils_1.isFunction(pattern)) {
+ // maintain the API of custom patterns
+ return pattern(str, 0, [], {});
+ }
+ else if (utils_1.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 (utils_1.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);
+}
+exports.addStartOfInput = addStartOfInput;
+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);
+}
+exports.addStickyFlag = addStickyFlag;
+function performRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) {
+ var errors = [];
+ // some run time checks to help the end users.
+ if (!utils_1.has(lexerDefinition, exports.DEFAULT_MODE)) {
+ errors.push({
+ message: "A MultiMode Lexer cannot be initialized without a <" +
+ exports.DEFAULT_MODE +
+ "> property in its definition\n",
+ type: lexer_public_1.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE
+ });
+ }
+ if (!utils_1.has(lexerDefinition, exports.MODES)) {
+ errors.push({
+ message: "A MultiMode Lexer cannot be initialized without a <" +
+ exports.MODES +
+ "> property in its definition\n",
+ type: lexer_public_1.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY
+ });
+ }
+ if (utils_1.has(lexerDefinition, exports.MODES) &&
+ utils_1.has(lexerDefinition, exports.DEFAULT_MODE) &&
+ !utils_1.has(lexerDefinition.modes, lexerDefinition.defaultMode)) {
+ errors.push({
+ message: "A MultiMode Lexer cannot be initialized with a " + exports.DEFAULT_MODE + ": <" + lexerDefinition.defaultMode + ">" +
+ "which does not exist\n",
+ type: lexer_public_1.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST
+ });
+ }
+ if (utils_1.has(lexerDefinition, exports.MODES)) {
+ utils_1.forEach(lexerDefinition.modes, function (currModeValue, currModeName) {
+ utils_1.forEach(currModeValue, function (currTokType, currIdx) {
+ if (utils_1.isUndefined(currTokType)) {
+ errors.push({
+ message: "A Lexer cannot be initialized using an undefined Token Type. Mode:" +
+ ("<" + currModeName + "> at index: <" + currIdx + ">\n"),
+ type: lexer_public_1.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED
+ });
+ }
+ });
+ });
+ }
+ return errors;
+}
+exports.performRuntimeChecks = performRuntimeChecks;
+function performWarningRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) {
+ var warnings = [];
+ var hasAnyLineBreak = false;
+ var allTokenTypes = utils_1.compact(utils_1.flatten(utils_1.mapValues(lexerDefinition.modes, function (tokTypes) { return tokTypes; })));
+ var concreteTokenTypes = utils_1.reject(allTokenTypes, function (currType) { return currType[PATTERN] === lexer_public_1.Lexer.NA; });
+ var terminatorCharCodes = getCharCodes(lineTerminatorCharacters);
+ if (trackLines) {
+ utils_1.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 (utils_1.has(tokType, "LINE_BREAKS")) {
+ if (tokType.LINE_BREAKS === true) {
+ hasAnyLineBreak = true;
+ }
+ }
+ else {
+ if (reg_exp_1.canMatchCharCode(terminatorCharCodes, tokType.PATTERN)) {
+ hasAnyLineBreak = true;
+ }
+ }
+ }
+ });
+ }
+ if (trackLines && !hasAnyLineBreak) {
+ warnings.push({
+ message: "Warning: No LINE_BREAKS Found.\n" +
+ "\tThis Lexer has been defined to track line and column information,\n" +
+ "\tBut none of the Token Types can be identified as matching a line terminator.\n" +
+ "\tSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n" +
+ "\tfor details.",
+ type: lexer_public_1.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS
+ });
+ }
+ return warnings;
+}
+exports.performWarningRuntimeChecks = performWarningRuntimeChecks;
+function cloneEmptyGroups(emptyGroups) {
+ var clonedResult = {};
+ var groupKeys = utils_1.keys(emptyGroups);
+ utils_1.forEach(groupKeys, function (currKey) {
+ var currGroupValue = emptyGroups[currKey];
+ /* istanbul ignore else */
+ if (utils_1.isArray(currGroupValue)) {
+ clonedResult[currKey] = [];
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ });
+ return clonedResult;
+}
+exports.cloneEmptyGroups = cloneEmptyGroups;
+// TODO: refactor to avoid duplication
+function isCustomPattern(tokenType) {
+ var pattern = tokenType.PATTERN;
+ /* istanbul ignore else */
+ if (utils_1.isRegExp(pattern)) {
+ return false;
+ }
+ else if (utils_1.isFunction(pattern)) {
+ // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object
+ return true;
+ }
+ else if (utils_1.has(pattern, "exec")) {
+ // ICustomPattern
+ return true;
+ }
+ else if (utils_1.isString(pattern)) {
+ return false;
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+exports.isCustomPattern = isCustomPattern;
+function isShortPattern(pattern) {
+ if (utils_1.isString(pattern) && pattern.length === 1) {
+ return pattern.charCodeAt(0);
+ }
+ else {
+ return false;
+ }
+}
+exports.isShortPattern = isShortPattern;
+/**
+ * Faster than using a RegExp for default newline detection during lexing.
+ */
+exports.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 (utils_1.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 (utils_1.isRegExp(tokType.PATTERN)) {
+ try {
+ reg_exp_1.canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN);
+ }
+ catch (e) {
+ /* istanbul ignore next - to test this we would have to mock to throw an error */
+ return {
+ issue: lexer_public_1.LexerDefinitionErrorType.IDENTIFY_TERMINATOR,
+ errMsg: e.message
+ };
+ }
+ return false;
+ }
+ else if (utils_1.isString(tokType.PATTERN)) {
+ // string literal patterns can always be analyzed to detect line terminator usage
+ return false;
+ }
+ else if (isCustomPattern(tokType)) {
+ // custom token types
+ return { issue: lexer_public_1.LexerDefinitionErrorType.CUSTOM_LINE_BREAK };
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ }
+}
+function buildLineBreakIssueMessage(tokType, details) {
+ /* istanbul ignore else */
+ if (details.issue === lexer_public_1.LexerDefinitionErrorType.IDENTIFY_TERMINATOR) {
+ return ("Warning: unable to identify line terminator usage in pattern.\n" +
+ ("\tThe problem is in the <" + tokType.name + "> Token Type\n") +
+ ("\t Root cause: " + details.errMsg + ".\n") +
+ "\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR");
+ }
+ else if (details.issue === lexer_public_1.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");
+ }
+}
+exports.buildLineBreakIssueMessage = buildLineBreakIssueMessage;
+function getCharCodes(charsOrCodes) {
+ var charCodes = utils_1.map(charsOrCodes, function (numOrString) {
+ if (utils_1.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);
+ }
+}
+exports.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 < exports.minOptimizationVal
+ ? charCode
+ : charCodeToOptimizedIdxMap[charCode];
+}
+exports.charCodeToOptimizedIndex = charCodeToOptimizedIndex;
+/**
+ * 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 (utils_1.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
+
+/***/ }),
+/* 21 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.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
+
+/***/ }),
+/* 22 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+var gast_public_1 = __webpack_require__(1);
+var gast_1 = __webpack_require__(6);
+function first(prod) {
+ /* istanbul ignore else */
+ if (prod instanceof gast_public_1.NonTerminal) {
+ // this could in theory cause infinite loops if
+ // (1) prod A refs prod B.
+ // (2) prod B refs prod A
+ // (3) AB can match the empty set
+ // in other words a cycle where everything is optional so the first will keep
+ // looking ahead for the next optional part and will never exit
+ // currently there is no safeguard for this unique edge case because
+ // (1) not sure a grammar in which this can happen is useful for anything (productive)
+ return first(prod.referencedRule);
+ }
+ else if (prod instanceof gast_public_1.Terminal) {
+ return firstForTerminal(prod);
+ }
+ else if (gast_1.isSequenceProd(prod)) {
+ return firstForSequence(prod);
+ }
+ else if (gast_1.isBranchingProd(prod)) {
+ return firstForBranching(prod);
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+exports.first = first;
+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 = gast_1.isOptionalProd(currSubProd);
+ firstSet = firstSet.concat(first(currSubProd));
+ nextSubProdIdx = nextSubProdIdx + 1;
+ hasInnerProdsRemaining = seq.length > nextSubProdIdx;
+ }
+ return utils_1.uniq(firstSet);
+}
+exports.firstForSequence = firstForSequence;
+function firstForBranching(prod) {
+ var allAlternativesFirsts = utils_1.map(prod.definition, function (innerProd) {
+ return first(innerProd);
+ });
+ return utils_1.uniq(utils_1.flatten(allAlternativesFirsts));
+}
+exports.firstForBranching = firstForBranching;
+function firstForTerminal(terminal) {
+ return [terminal.terminalType];
+}
+exports.firstForTerminal = firstForTerminal;
+//# sourceMappingURL=first.js.map
+
+/***/ }),
+/* 23 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+// TODO: can this be removed? where is it used?
+exports.IN = "_~IN~_";
+//# sourceMappingURL=constants.js.map
+
+/***/ }),
+/* 24 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+var resolver_1 = __webpack_require__(29);
+var checks_1 = __webpack_require__(11);
+var errors_public_1 = __webpack_require__(10);
+var gast_1 = __webpack_require__(6);
+function resolveGrammar(options) {
+ options = utils_1.defaults(options, {
+ errMsgProvider: errors_public_1.defaultGrammarResolverErrorProvider
+ });
+ var topRulesTable = {};
+ utils_1.forEach(options.rules, function (rule) {
+ topRulesTable[rule.name] = rule;
+ });
+ return resolver_1.resolveGrammar(topRulesTable, options.errMsgProvider);
+}
+exports.resolveGrammar = resolveGrammar;
+function validateGrammar(options) {
+ options = utils_1.defaults(options, {
+ errMsgProvider: errors_public_1.defaultGrammarValidatorErrorProvider,
+ ignoredIssues: {}
+ });
+ return checks_1.validateGrammar(options.rules, options.maxLookahead, options.tokenTypes, options.ignoredIssues, options.errMsgProvider, options.grammarName);
+}
+exports.validateGrammar = validateGrammar;
+function assignOccurrenceIndices(options) {
+ utils_1.forEach(options.rules, function (currRule) {
+ var methodsCollector = new gast_1.DslMethodsCollectorVisitor();
+ currRule.accept(methodsCollector);
+ utils_1.forEach(methodsCollector.dslMethods, function (methods) {
+ utils_1.forEach(methods, function (currMethod, arrIdx) {
+ currMethod.idx = arrIdx + 1;
+ });
+ });
+ });
+}
+exports.assignOccurrenceIndices = assignOccurrenceIndices;
+//# sourceMappingURL=gast_resolver_public.js.map
+
+/***/ }),
+/* 25 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var tokens_public_1 = __webpack_require__(3);
+var utils_1 = __webpack_require__(0);
+var exceptions_public_1 = __webpack_require__(8);
+var constants_1 = __webpack_require__(23);
+var parser_1 = __webpack_require__(2);
+exports.EOF_FOLLOW_KEY = {};
+exports.IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException";
+function InRuleRecoveryException(message) {
+ this.name = exports.IN_RULE_RECOVERY_EXCEPTION;
+ this.message = message;
+}
+exports.InRuleRecoveryException = InRuleRecoveryException;
+InRuleRecoveryException.prototype = Error.prototype;
+/**
+ * This trait is responsible for the error recovery and fault tolerant logic
+ */
+var Recoverable = /** @class */ (function () {
+ function Recoverable() {
+ }
+ Recoverable.prototype.initRecoverable = function (config) {
+ this.firstAfterRepMap = {};
+ this.resyncFollows = {};
+ this.recoveryEnabled = utils_1.has(config, "recoveryEnabled")
+ ? config.recoveryEnabled
+ : parser_1.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 = tokens_public_1.createTokenInstance(tokType, "", NaN, NaN, NaN, NaN, NaN, NaN);
+ tokToInsert.isInsertedInRecovery = true;
+ return tokToInsert;
+ };
+ Recoverable.prototype.canTokenTypeBeInsertedInRecovery = function (tokType) {
+ return true;
+ };
+ Recoverable.prototype.tryInRepetitionRecovery = function (grammarRule, grammarRuleArgs, lookAheadFunc, expectedTokType) {
+ var _this = this;
+ // TODO: can the resyncTokenType be cached?
+ var reSyncTokType = this.findReSyncTokenType();
+ var savedLexerState = this.exportLexerState();
+ var resyncedTokens = [];
+ var passedResyncPoint = false;
+ var nextTokenWithoutResync = this.LA(1);
+ var currToken = this.LA(1);
+ var generateErrorMessage = function () {
+ var previousToken = _this.LA(0);
+ // we are preemptively re-syncing before an error has been detected, therefor we must reproduce
+ // the error that would have been thrown
+ var msg = _this.errorMessageProvider.buildMismatchTokenMessage({
+ expected: expectedTokType,
+ actual: nextTokenWithoutResync,
+ previous: previousToken,
+ ruleName: _this.getCurrRuleFullName()
+ });
+ var error = new exceptions_public_1.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 = utils_1.dropRight(resyncedTokens);
+ _this.SAVE_ERROR(error);
+ };
+ while (!passedResyncPoint) {
+ // re-synced to a point where we can safely exit the repetition/
+ if (this.tokenMatcher(currToken, expectedTokType)) {
+ generateErrorMessage();
+ return; // must return here to avoid reverting the inputIdx
+ }
+ else if (lookAheadFunc.call(this)) {
+ // we skipped enough tokens so we can resync right back into another iteration of the repetition grammar rule
+ generateErrorMessage();
+ // recursive invocation in other to support multiple re-syncs in the same top level repetition grammar rule
+ grammarRule.apply(this, grammarRuleArgs);
+ return; // must return here to avoid reverting the inputIdx
+ }
+ else if (this.tokenMatcher(currToken, reSyncTokType)) {
+ passedResyncPoint = true;
+ }
+ else {
+ currToken = this.SKIP_TOKEN();
+ this.addToResyncTokens(currToken, resyncedTokens);
+ }
+ }
+ // we were unable to find a CLOSER point to resync inside the Repetition, reset the state.
+ // The parsing exception we were trying to prevent will happen in the NEXT parsing step. it may be handled by
+ // "between rules" resync recovery later in the flow.
+ this.importLexerState(savedLexerState);
+ };
+ Recoverable.prototype.shouldInRepetitionRecoveryBeTried = function (expectTokAfterLastMatch, nextTokIdx, notStuck) {
+ // Edge case of arriving from a MANY repetition which is stuck
+ // Attempting recovery in this case could cause an infinite loop
+ if (notStuck === false) {
+ return false;
+ }
+ // arguments to try and perform resync into the next iteration of the many are missing
+ if (expectTokAfterLastMatch === undefined || nextTokIdx === undefined) {
+ return false;
+ }
+ // no need to recover, next token is what we expect...
+ if (this.tokenMatcher(this.LA(1), expectTokAfterLastMatch)) {
+ return false;
+ }
+ // error recovery is disabled during backtracking as it can make the parser ignore a valid grammar path
+ // and prefer some backtracking path that includes recovered errors.
+ if (this.isBackTracking()) {
+ return false;
+ }
+ // if we can perform inRule recovery (single token insertion or deletion) we always prefer that recovery algorithm
+ // because if it works, it makes the least amount of changes to the input stream (greedy algorithm)
+ //noinspection RedundantIfStatementJS
+ if (this.canPerformInRuleRecovery(expectTokAfterLastMatch, this.getFollowsForInRuleRecovery(expectTokAfterLastMatch, nextTokIdx))) {
+ return false;
+ }
+ return true;
+ };
+ // Error Recovery functionality
+ Recoverable.prototype.getFollowsForInRuleRecovery = function (tokType, tokIdxInRule) {
+ var grammarPath = this.getCurrentGrammarPath(tokType, tokIdxInRule);
+ var follows = this.getNextPossibleTokenTypes(grammarPath);
+ return follows;
+ };
+ Recoverable.prototype.tryInRuleRecovery = function (expectedTokType, follows) {
+ if (this.canRecoverWithSingleTokenInsertion(expectedTokType, follows)) {
+ var tokToInsert = this.getTokenToInsert(expectedTokType);
+ return tokToInsert;
+ }
+ if (this.canRecoverWithSingleTokenDeletion(expectedTokType)) {
+ var nextTok = this.SKIP_TOKEN();
+ this.consumeToken();
+ return nextTok;
+ }
+ throw new InRuleRecoveryException("sad sad panda");
+ };
+ Recoverable.prototype.canPerformInRuleRecovery = function (expectedToken, follows) {
+ return (this.canRecoverWithSingleTokenInsertion(expectedToken, follows) ||
+ this.canRecoverWithSingleTokenDeletion(expectedToken));
+ };
+ Recoverable.prototype.canRecoverWithSingleTokenInsertion = function (expectedTokType, follows) {
+ var _this = this;
+ if (!this.canTokenTypeBeInsertedInRecovery(expectedTokType)) {
+ return false;
+ }
+ // must know the possible following tokens to perform single token insertion
+ if (utils_1.isEmpty(follows)) {
+ return false;
+ }
+ var mismatchedTok = this.LA(1);
+ var isMisMatchedTokInFollows = utils_1.find(follows, function (possibleFollowsTokType) {
+ return _this.tokenMatcher(mismatchedTok, possibleFollowsTokType);
+ }) !== undefined;
+ return isMisMatchedTokInFollows;
+ };
+ Recoverable.prototype.canRecoverWithSingleTokenDeletion = function (expectedTokType) {
+ var isNextTokenWhatIsExpected = this.tokenMatcher(this.LA(2), expectedTokType);
+ return isNextTokenWhatIsExpected;
+ };
+ Recoverable.prototype.isInCurrentRuleReSyncSet = function (tokenTypeIdx) {
+ var followKey = this.getCurrFollowKey();
+ var currentRuleReSyncSet = this.getFollowSetFromFollowKey(followKey);
+ return utils_1.contains(currentRuleReSyncSet, tokenTypeIdx);
+ };
+ Recoverable.prototype.findReSyncTokenType = function () {
+ var allPossibleReSyncTokTypes = this.flattenFollowSet();
+ // this loop will always terminate as EOF is always in the follow stack and also always (virtually) in the input
+ var nextToken = this.LA(1);
+ var k = 2;
+ while (true) {
+ var nextTokenType = nextToken.tokenType;
+ if (utils_1.contains(allPossibleReSyncTokTypes, nextTokenType)) {
+ return nextTokenType;
+ }
+ nextToken = this.LA(k);
+ k++;
+ }
+ };
+ Recoverable.prototype.getCurrFollowKey = function () {
+ // the length is at least one as we always add the ruleName to the stack before invoking the rule.
+ if (this.RULE_STACK.length === 1) {
+ return exports.EOF_FOLLOW_KEY;
+ }
+ var currRuleShortName = this.getLastExplicitRuleShortName();
+ var currRuleIdx = this.getLastExplicitRuleOccurrenceIndex();
+ var prevRuleShortName = this.getPreviousExplicitRuleShortName();
+ return {
+ ruleName: this.shortRuleNameToFullName(currRuleShortName),
+ idxInCallingRule: currRuleIdx,
+ inRule: this.shortRuleNameToFullName(prevRuleShortName)
+ };
+ };
+ Recoverable.prototype.buildFullFollowKeyStack = function () {
+ var _this = this;
+ var explicitRuleStack = this.RULE_STACK;
+ var explicitOccurrenceStack = this.RULE_OCCURRENCE_STACK;
+ if (!utils_1.isEmpty(this.LAST_EXPLICIT_RULE_STACK)) {
+ explicitRuleStack = utils_1.map(this.LAST_EXPLICIT_RULE_STACK, function (idx) { return _this.RULE_STACK[idx]; });
+ explicitOccurrenceStack = utils_1.map(this.LAST_EXPLICIT_RULE_STACK, function (idx) { return _this.RULE_OCCURRENCE_STACK[idx]; });
+ }
+ // TODO: only iterate over explicit rules here
+ return utils_1.map(explicitRuleStack, function (ruleName, idx) {
+ if (idx === 0) {
+ return exports.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 = utils_1.map(this.buildFullFollowKeyStack(), function (currKey) {
+ return _this.getFollowSetFromFollowKey(currKey);
+ });
+ return utils_1.flatten(followStack);
+ };
+ Recoverable.prototype.getFollowSetFromFollowKey = function (followKey) {
+ if (followKey === exports.EOF_FOLLOW_KEY) {
+ return [tokens_public_1.EOF];
+ }
+ var followName = followKey.ruleName +
+ followKey.idxInCallingRule +
+ constants_1.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, tokens_public_1.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 utils_1.dropRight(resyncedTokens);
+ };
+ Recoverable.prototype.attemptInRepetitionRecovery = function (prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) {
+ // by default this is a NO-OP
+ // The actual implementation is with the function(not method) below
+ };
+ Recoverable.prototype.getCurrentGrammarPath = function (tokType, tokIdxInRule) {
+ var pathRuleStack = this.getHumanReadableRuleStack();
+ var pathOccurrenceStack = utils_1.cloneArr(this.RULE_OCCURRENCE_STACK);
+ var grammarPath = {
+ ruleStack: pathRuleStack,
+ occurrenceStack: pathOccurrenceStack,
+ lastTok: tokType,
+ lastTokOccurrence: tokIdxInRule
+ };
+ return grammarPath;
+ };
+ Recoverable.prototype.getHumanReadableRuleStack = function () {
+ var _this = this;
+ if (!utils_1.isEmpty(this.LAST_EXPLICIT_RULE_STACK)) {
+ return utils_1.map(this.LAST_EXPLICIT_RULE_STACK, function (currIdx) {
+ return _this.shortRuleNameToFullName(_this.RULE_STACK[currIdx]);
+ });
+ }
+ else {
+ return utils_1.map(this.RULE_STACK, function (currShortName) {
+ return _this.shortRuleNameToFullName(currShortName);
+ });
+ }
+ };
+ return Recoverable;
+}());
+exports.Recoverable = 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 = tokens_public_1.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);
+ }
+}
+exports.attemptInRepetitionRecovery = attemptInRepetitionRecovery;
+//# sourceMappingURL=recoverable.js.map
+
+/***/ }),
+/* 26 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+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;
+//# sourceMappingURL=lang_extensions.js.map
+
+/***/ }),
+/* 27 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var rest_1 = __webpack_require__(14);
+var first_1 = __webpack_require__(22);
+var utils_1 = __webpack_require__(0);
+var constants_1 = __webpack_require__(23);
+var gast_public_1 = __webpack_require__(1);
+// This ResyncFollowsWalker computes all of the follows required for RESYNC
+// (skipping reference production).
+var ResyncFollowsWalker = /** @class */ (function (_super) {
+ __extends(ResyncFollowsWalker, _super);
+ function ResyncFollowsWalker(topProd) {
+ var _this = _super.call(this) || this;
+ _this.topProd = topProd;
+ _this.follows = {};
+ return _this;
+ }
+ ResyncFollowsWalker.prototype.startWalking = function () {
+ this.walk(this.topProd);
+ return this.follows;
+ };
+ ResyncFollowsWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) {
+ // do nothing! just like in the public sector after 13:00
+ };
+ ResyncFollowsWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) {
+ var followName = buildBetweenProdsFollowPrefix(refProd.referencedRule, refProd.idx) +
+ this.topProd.name;
+ var fullRest = currRest.concat(prevRest);
+ var restProd = new gast_public_1.Flat({ definition: fullRest });
+ var t_in_topProd_follows = first_1.first(restProd);
+ this.follows[followName] = t_in_topProd_follows;
+ };
+ return ResyncFollowsWalker;
+}(rest_1.RestWalker));
+exports.ResyncFollowsWalker = ResyncFollowsWalker;
+function computeAllProdsFollows(topProductions) {
+ var reSyncFollows = {};
+ utils_1.forEach(topProductions, function (topProd) {
+ var currRefsFollow = new ResyncFollowsWalker(topProd).startWalking();
+ utils_1.assign(reSyncFollows, currRefsFollow);
+ });
+ return reSyncFollows;
+}
+exports.computeAllProdsFollows = computeAllProdsFollows;
+function buildBetweenProdsFollowPrefix(inner, occurenceInParent) {
+ return inner.name + occurenceInParent + constants_1.IN;
+}
+exports.buildBetweenProdsFollowPrefix = buildBetweenProdsFollowPrefix;
+function buildInProdFollowPrefix(terminal) {
+ var terminalName = terminal.terminalType.name;
+ return terminalName + terminal.idx + constants_1.IN;
+}
+exports.buildInProdFollowPrefix = buildInProdFollowPrefix;
+//# sourceMappingURL=follow.js.map
+
+/***/ }),
+/* 28 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var regexp_to_ast_1 = __webpack_require__(15);
+var utils_1 = __webpack_require__(0);
+var reg_exp_parser_1 = __webpack_require__(16);
+var lexer_1 = __webpack_require__(20);
+var complementErrorMessage = "Complement Sets are not supported for first char optimization";
+exports.failedOptimizationPrefixMsg = 'Unable to use "first char" lexer optimizations:\n';
+function getOptimizedStartCodesIndices(regExp, ensureOptimizations) {
+ if (ensureOptimizations === void 0) { ensureOptimizations = false; }
+ try {
+ var ast = reg_exp_parser_1.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) {
+ utils_1.PRINT_WARNING("" + exports.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.";
+ }
+ utils_1.PRINT_ERROR(exports.failedOptimizationPrefixMsg + "\n" +
+ ("\tFailed parsing: < " + regExp.toString() + " >\n") +
+ ("\tUsing the regexp-to-ast library version: " + regexp_to_ast_1.VERSION + "\n") +
+ "\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues" +
+ msgSuffix);
+ }
+ }
+ return [];
+}
+exports.getOptimizedStartCodesIndices = getOptimizedStartCodesIndices;
+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);
+ }
+ utils_1.forEach(atom.value, function (code) {
+ if (typeof code === "number") {
+ addOptimizedIdxToResult(code, result, ignoreCase);
+ }
+ else {
+ // range
+ var range = code;
+ // cannot optimize when ignoreCase is
+ if (ignoreCase === true) {
+ for (var rangeCode = range.from; rangeCode <= range.to; rangeCode++) {
+ addOptimizedIdxToResult(rangeCode, result, ignoreCase);
+ }
+ }
+ // Optimization (2 orders of magnitude less work for very large ranges)
+ else {
+ // handle unoptimized values
+ for (var rangeCode = range.from; rangeCode <= range.to &&
+ rangeCode < lexer_1.minOptimizationVal; rangeCode++) {
+ addOptimizedIdxToResult(rangeCode, result, ignoreCase);
+ }
+ // Less common charCode where we optimize for faster init time, by using larger "buckets"
+ if (range.to >= lexer_1.minOptimizationVal) {
+ var minUnOptVal = range.from >= lexer_1.minOptimizationVal
+ ? range.from
+ : lexer_1.minOptimizationVal;
+ var maxUnOptVal = range.to;
+ var minOptIdx = lexer_1.charCodeToOptimizedIndex(minUnOptVal);
+ var maxOptIdx = lexer_1.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 utils_1.values(result);
+}
+exports.firstCharOptimizedIndices = firstCharOptimizedIndices;
+function addOptimizedIdxToResult(code, result, ignoreCase) {
+ var optimizedCharIdx = lexer_1.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 = lexer_1.charCodeToOptimizedIndex(upperChar.charCodeAt(0));
+ result[optimizedCharIdx] = optimizedCharIdx;
+ }
+ else {
+ var lowerChar = char.toLowerCase();
+ if (lowerChar !== char) {
+ var optimizedCharIdx = lexer_1.charCodeToOptimizedIndex(lowerChar.charCodeAt(0));
+ result[optimizedCharIdx] = optimizedCharIdx;
+ }
+ }
+}
+function findCode(setNode, targetCharCodes) {
+ return utils_1.find(setNode.value, function (codeOrRange) {
+ if (typeof codeOrRange === "number") {
+ return utils_1.contains(targetCharCodes, codeOrRange);
+ }
+ else {
+ // range
+ var range_1 = codeOrRange;
+ return (utils_1.find(targetCharCodes, function (targetCode) {
+ return range_1.from <= targetCode && targetCode <= range_1.to;
+ }) !== undefined);
+ }
+ });
+}
+function isWholeOptional(ast) {
+ if (ast.quantifier && ast.quantifier.atLeast === 0) {
+ return true;
+ }
+ if (!ast.value) {
+ return false;
+ }
+ return utils_1.isArray(ast.value)
+ ? utils_1.every(ast.value, isWholeOptional)
+ : isWholeOptional(ast.value);
+}
+var CharCodeFinder = /** @class */ (function (_super) {
+ __extends(CharCodeFinder, _super);
+ function CharCodeFinder(targetCharCodes) {
+ var _this = _super.call(this) || this;
+ _this.targetCharCodes = targetCharCodes;
+ _this.found = false;
+ return _this;
+ }
+ CharCodeFinder.prototype.visitChildren = function (node) {
+ // No need to keep looking...
+ if (this.found === true) {
+ return;
+ }
+ // switch lookaheads as they do not actually consume any characters thus
+ // finding a charCode at lookahead context does not mean that regexp can actually contain it in a match.
+ switch (node.type) {
+ case "Lookahead":
+ this.visitLookahead(node);
+ return;
+ case "NegativeLookahead":
+ this.visitNegativeLookahead(node);
+ return;
+ }
+ _super.prototype.visitChildren.call(this, node);
+ };
+ CharCodeFinder.prototype.visitCharacter = function (node) {
+ if (utils_1.contains(this.targetCharCodes, node.value)) {
+ this.found = true;
+ }
+ };
+ CharCodeFinder.prototype.visitSet = function (node) {
+ if (node.complement) {
+ if (findCode(node, this.targetCharCodes) === undefined) {
+ this.found = true;
+ }
+ }
+ else {
+ if (findCode(node, this.targetCharCodes) !== undefined) {
+ this.found = true;
+ }
+ }
+ };
+ return CharCodeFinder;
+}(regexp_to_ast_1.BaseRegExpVisitor));
+function canMatchCharCode(charCodes, pattern) {
+ if (pattern instanceof RegExp) {
+ var ast = reg_exp_parser_1.getRegExpAst(pattern);
+ var charCodeFinder = new CharCodeFinder(charCodes);
+ charCodeFinder.visit(ast);
+ return charCodeFinder.found;
+ }
+ else {
+ return (utils_1.find(pattern, function (char) {
+ return utils_1.contains(charCodes, char.charCodeAt(0));
+ }) !== undefined);
+ }
+}
+exports.canMatchCharCode = canMatchCharCode;
+//# sourceMappingURL=reg_exp.js.map
+
+/***/ }),
+/* 29 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var parser_1 = __webpack_require__(2);
+var utils_1 = __webpack_require__(0);
+var gast_visitor_public_1 = __webpack_require__(4);
+function resolveGrammar(topLevels, errMsgProvider) {
+ var refResolver = new GastRefResolverVisitor(topLevels, errMsgProvider);
+ refResolver.resolveRefs();
+ return refResolver.errors;
+}
+exports.resolveGrammar = resolveGrammar;
+var GastRefResolverVisitor = /** @class */ (function (_super) {
+ __extends(GastRefResolverVisitor, _super);
+ function GastRefResolverVisitor(nameToTopRule, errMsgProvider) {
+ var _this = _super.call(this) || this;
+ _this.nameToTopRule = nameToTopRule;
+ _this.errMsgProvider = errMsgProvider;
+ _this.errors = [];
+ return _this;
+ }
+ GastRefResolverVisitor.prototype.resolveRefs = function () {
+ var _this = this;
+ utils_1.forEach(utils_1.values(this.nameToTopRule), function (prod) {
+ _this.currTopLevel = prod;
+ prod.accept(_this);
+ });
+ };
+ GastRefResolverVisitor.prototype.visitNonTerminal = function (node) {
+ var ref = this.nameToTopRule[node.nonTerminalName];
+ if (!ref) {
+ var msg = this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel, node);
+ this.errors.push({
+ message: msg,
+ type: parser_1.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,
+ ruleName: this.currTopLevel.name,
+ unresolvedRefName: node.nonTerminalName
+ });
+ }
+ else {
+ node.referencedRule = ref;
+ }
+ };
+ return GastRefResolverVisitor;
+}(gast_visitor_public_1.GAstVisitor));
+exports.GastRefResolverVisitor = GastRefResolverVisitor;
+//# sourceMappingURL=resolver.js.map
+
+/***/ }),
+/* 30 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var lookahead_1 = __webpack_require__(12);
+var utils_1 = __webpack_require__(0);
+var parser_1 = __webpack_require__(2);
+var keys_1 = __webpack_require__(7);
+var gast_1 = __webpack_require__(6);
+/**
+ * Trait responsible for the lookahead related utilities and optimizations.
+ */
+var LooksAhead = /** @class */ (function () {
+ function LooksAhead() {
+ }
+ LooksAhead.prototype.initLooksAhead = function (config) {
+ this.dynamicTokensEnabled = utils_1.has(config, "dynamicTokensEnabled")
+ ? config.dynamicTokensEnabled
+ : parser_1.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled;
+ this.maxLookahead = utils_1.has(config, "maxLookahead")
+ ? config.maxLookahead
+ : parser_1.DEFAULT_PARSER_CONFIG.maxLookahead;
+ /* istanbul ignore next - Using plain array as dictionary will be tested on older node.js versions and IE11 */
+ this.lookAheadFuncsCache = utils_1.isES2015MapSupported() ? new Map() : [];
+ // Performance optimization on newer engines that support ES6 Map
+ // For larger Maps this is slightly faster than using a plain object (array in our case).
+ /* istanbul ignore else - The else branch will be tested on older node.js versions and IE11 */
+ if (utils_1.isES2015MapSupported()) {
+ this.getLaFuncFromCache = this.getLaFuncFromMap;
+ this.setLaFuncCache = this.setLaFuncCacheUsingMap;
+ }
+ else {
+ this.getLaFuncFromCache = this.getLaFuncFromObj;
+ this.setLaFuncCache = this.setLaFuncUsingObj;
+ }
+ };
+ LooksAhead.prototype.preComputeLookaheadFunctions = function (rules) {
+ var _this = this;
+ utils_1.forEach(rules, function (currRule) {
+ _this.TRACE_INIT(currRule.name + " Rule Lookahead", function () {
+ var _a = gast_1.collectMethods(currRule), alternation = _a.alternation, repetition = _a.repetition, option = _a.option, repetitionMandatory = _a.repetitionMandatory, repetitionMandatoryWithSeparator = _a.repetitionMandatoryWithSeparator, repetitionWithSeparator = _a.repetitionWithSeparator;
+ utils_1.forEach(alternation, function (currProd) {
+ var prodIdx = currProd.idx === 0 ? "" : currProd.idx;
+ _this.TRACE_INIT("" + gast_1.getProductionDslName(currProd) + prodIdx, function () {
+ var laFunc = lookahead_1.buildLookaheadFuncForOr(currProd.idx, currRule, currProd.maxLookahead || _this.maxLookahead, currProd.hasPredicates, _this.dynamicTokensEnabled, _this.lookAheadBuilderForAlternatives);
+ var key = keys_1.getKeyForAutomaticLookahead(_this.fullRuleNameToShort[currRule.name], keys_1.OR_IDX, currProd.idx);
+ _this.setLaFuncCache(key, laFunc);
+ });
+ });
+ utils_1.forEach(repetition, function (currProd) {
+ _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.MANY_IDX, lookahead_1.PROD_TYPE.REPETITION, currProd.maxLookahead, gast_1.getProductionDslName(currProd));
+ });
+ utils_1.forEach(option, function (currProd) {
+ _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.OPTION_IDX, lookahead_1.PROD_TYPE.OPTION, currProd.maxLookahead, gast_1.getProductionDslName(currProd));
+ });
+ utils_1.forEach(repetitionMandatory, function (currProd) {
+ _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.AT_LEAST_ONE_IDX, lookahead_1.PROD_TYPE.REPETITION_MANDATORY, currProd.maxLookahead, gast_1.getProductionDslName(currProd));
+ });
+ utils_1.forEach(repetitionMandatoryWithSeparator, function (currProd) {
+ _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.AT_LEAST_ONE_SEP_IDX, lookahead_1.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currProd.maxLookahead, gast_1.getProductionDslName(currProd));
+ });
+ utils_1.forEach(repetitionWithSeparator, function (currProd) {
+ _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.MANY_SEP_IDX, lookahead_1.PROD_TYPE.REPETITION_WITH_SEPARATOR, currProd.maxLookahead, gast_1.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 = lookahead_1.buildLookaheadFuncForOptionalProd(prodOccurrence, rule, prodMaxLookahead || _this.maxLookahead, _this.dynamicTokensEnabled, prodType, _this.lookAheadBuilderForOptional);
+ var key = keys_1.getKeyForAutomaticLookahead(_this.fullRuleNameToShort[rule.name], prodKey, prodOccurrence);
+ _this.setLaFuncCache(key, laFunc);
+ });
+ };
+ LooksAhead.prototype.lookAheadBuilderForOptional = function (alt, tokenMatcher, dynamicTokensEnabled) {
+ return lookahead_1.buildSingleAlternativeLookaheadFunction(alt, tokenMatcher, dynamicTokensEnabled);
+ };
+ LooksAhead.prototype.lookAheadBuilderForAlternatives = function (alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) {
+ return lookahead_1.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 keys_1.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;
+}());
+exports.LooksAhead = LooksAhead;
+//# sourceMappingURL=looksahead.js.map
+
+/***/ }),
+/* 31 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var cst_1 = __webpack_require__(17);
+var utils_1 = __webpack_require__(0);
+var cst_visitor_1 = __webpack_require__(32);
+var keys_1 = __webpack_require__(7);
+var parser_1 = __webpack_require__(2);
+/**
+ * This trait is responsible for the CST building logic.
+ */
+var TreeBuilder = /** @class */ (function () {
+ function TreeBuilder() {
+ }
+ TreeBuilder.prototype.initTreeBuilder = function (config) {
+ this.LAST_EXPLICIT_RULE_STACK = [];
+ this.CST_STACK = [];
+ this.outputCst = utils_1.has(config, "outputCst")
+ ? config.outputCst
+ : parser_1.DEFAULT_PARSER_CONFIG.outputCst;
+ this.nodeLocationTracking = utils_1.has(config, "nodeLocationTracking")
+ ? config.nodeLocationTracking
+ : parser_1.DEFAULT_PARSER_CONFIG.nodeLocationTracking;
+ if (!this.outputCst) {
+ this.cstInvocationStateUpdate = utils_1.NOOP;
+ this.cstFinallyStateUpdate = utils_1.NOOP;
+ this.cstPostTerminal = utils_1.NOOP;
+ this.cstPostNonTerminal = utils_1.NOOP;
+ this.cstPostRule = utils_1.NOOP;
+ this.getLastExplicitRuleShortName = this.getLastExplicitRuleShortNameNoCst;
+ this.getPreviousExplicitRuleShortName = this.getPreviousExplicitRuleShortNameNoCst;
+ this.getLastExplicitRuleOccurrenceIndex = this.getLastExplicitRuleOccurrenceIndexNoCst;
+ this.manyInternal = this.manyInternalNoCst;
+ this.orInternal = this.orInternalNoCst;
+ this.optionInternal = this.optionInternalNoCst;
+ this.atLeastOneInternal = this.atLeastOneInternalNoCst;
+ this.manySepFirstInternal = this.manySepFirstInternalNoCst;
+ this.atLeastOneSepFirstInternal = this.atLeastOneSepFirstInternalNoCst;
+ }
+ else {
+ if (/full/i.test(this.nodeLocationTracking)) {
+ if (this.recoveryEnabled) {
+ this.setNodeLocationFromToken = cst_1.setNodeLocationFull;
+ this.setNodeLocationFromNode = cst_1.setNodeLocationFull;
+ this.cstPostRule = utils_1.NOOP;
+ this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery;
+ }
+ else {
+ this.setNodeLocationFromToken = utils_1.NOOP;
+ this.setNodeLocationFromNode = utils_1.NOOP;
+ this.cstPostRule = this.cstPostRuleFull;
+ this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular;
+ }
+ }
+ else if (/onlyOffset/i.test(this.nodeLocationTracking)) {
+ if (this.recoveryEnabled) {
+ this.setNodeLocationFromToken = (cst_1.setNodeLocationOnlyOffset);
+ this.setNodeLocationFromNode = (cst_1.setNodeLocationOnlyOffset);
+ this.cstPostRule = utils_1.NOOP;
+ this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery;
+ }
+ else {
+ this.setNodeLocationFromToken = utils_1.NOOP;
+ this.setNodeLocationFromNode = utils_1.NOOP;
+ this.cstPostRule = this.cstPostRuleOnlyOffset;
+ this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular;
+ }
+ }
+ else if (/none/i.test(this.nodeLocationTracking)) {
+ this.setNodeLocationFromToken = utils_1.NOOP;
+ this.setNodeLocationFromNode = utils_1.NOOP;
+ this.cstPostRule = utils_1.NOOP;
+ this.setInitialNodeLocation = utils_1.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
+ };
+ };
+ // CST
+ TreeBuilder.prototype.cstNestedInvocationStateUpdate = function (nestedName, shortName) {
+ var cstNode = {
+ name: nestedName,
+ fullName: this.shortRuleNameToFull[this.getLastExplicitRuleShortName()] +
+ nestedName,
+ children: {}
+ };
+ this.setInitialNodeLocation(cstNode);
+ this.CST_STACK.push(cstNode);
+ };
+ TreeBuilder.prototype.cstInvocationStateUpdate = function (fullRuleName, shortName) {
+ this.LAST_EXPLICIT_RULE_STACK.push(this.RULE_STACK.length - 1);
+ var cstNode = {
+ name: fullRuleName,
+ children: {}
+ };
+ this.setInitialNodeLocation(cstNode);
+ this.CST_STACK.push(cstNode);
+ };
+ TreeBuilder.prototype.cstFinallyStateUpdate = function () {
+ this.LAST_EXPLICIT_RULE_STACK.pop();
+ this.CST_STACK.pop();
+ };
+ TreeBuilder.prototype.cstNestedFinallyStateUpdate = function () {
+ var lastCstNode = this.CST_STACK.pop();
+ // TODO: the naming is bad, this should go directly to the
+ // (correct) cstLocation update method
+ // e.g if we put other logic in postRule...
+ this.cstPostRule(lastCstNode);
+ };
+ TreeBuilder.prototype.cstPostRuleFull = function (ruleCstNode) {
+ var prevToken = this.LA(0);
+ var loc = ruleCstNode.location;
+ // If this condition is true it means we consumed at least one Token
+ // In this CstNode or its nested children.
+ if (loc.startOffset <= prevToken.startOffset === true) {
+ loc.endOffset = prevToken.endOffset;
+ loc.endLine = prevToken.endLine;
+ loc.endColumn = prevToken.endColumn;
+ }
+ // "empty" CstNode edge case
+ else {
+ loc.startOffset = NaN;
+ loc.startLine = NaN;
+ loc.startColumn = NaN;
+ }
+ };
+ TreeBuilder.prototype.cstPostRuleOnlyOffset = function (ruleCstNode) {
+ var prevToken = this.LA(0);
+ var loc = ruleCstNode.location;
+ // If this condition is true it means we consumed at least one Token
+ // In this CstNode or its nested children.
+ if (loc.startOffset <= prevToken.startOffset === true) {
+ loc.endOffset = prevToken.endOffset;
+ }
+ // "empty" CstNode edge case
+ else {
+ loc.startOffset = NaN;
+ }
+ };
+ TreeBuilder.prototype.cstPostTerminal = function (key, consumedToken) {
+ var rootCst = this.CST_STACK[this.CST_STACK.length - 1];
+ cst_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) {
+ // Avoid side effects due to back tracking
+ // TODO: This costs a 2-3% in performance, A flag on IParserConfig
+ // could be used to get rid of this conditional, but not sure its worth the effort
+ // and API complexity.
+ if (this.isBackTracking() !== true) {
+ var preCstNode = this.CST_STACK[this.CST_STACK.length - 1];
+ cst_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 (utils_1.isUndefined(this.baseCstVisitorConstructor)) {
+ var newBaseCstVisitorConstructor = cst_visitor_1.createBaseSemanticVisitorConstructor(this.className, this.allRuleNames);
+ this.baseCstVisitorConstructor = newBaseCstVisitorConstructor;
+ return newBaseCstVisitorConstructor;
+ }
+ return this.baseCstVisitorConstructor;
+ };
+ TreeBuilder.prototype.getBaseCstVisitorConstructorWithDefaults = function () {
+ if (utils_1.isUndefined(this.baseCstVisitorWithDefaultsConstructor)) {
+ var newConstructor = cst_visitor_1.createBaseVisitorConstructorWithDefaults(this.className, this.allRuleNames, this.getBaseCstVisitorConstructor());
+ this.baseCstVisitorWithDefaultsConstructor = newConstructor;
+ return newConstructor;
+ }
+ return this.baseCstVisitorWithDefaultsConstructor;
+ };
+ TreeBuilder.prototype.nestedRuleBeforeClause = function (methodOpts, laKey) {
+ var nestedName;
+ if (methodOpts.NAME !== undefined) {
+ nestedName = methodOpts.NAME;
+ this.nestedRuleInvocationStateUpdate(nestedName, laKey);
+ return nestedName;
+ }
+ else {
+ return undefined;
+ }
+ };
+ TreeBuilder.prototype.nestedAltBeforeClause = function (methodOpts, occurrence, methodKeyIdx, altIdx) {
+ var ruleIdx = this.getLastExplicitRuleShortName();
+ var shortName = keys_1.getKeyForAltIndex(ruleIdx, methodKeyIdx, occurrence, altIdx);
+ var nestedName;
+ if (methodOpts.NAME !== undefined) {
+ nestedName = methodOpts.NAME;
+ this.nestedRuleInvocationStateUpdate(nestedName, shortName);
+ return {
+ shortName: shortName,
+ nestedName: nestedName
+ };
+ }
+ else {
+ return undefined;
+ }
+ };
+ TreeBuilder.prototype.nestedRuleFinallyClause = function (laKey, nestedName) {
+ var cstStack = this.CST_STACK;
+ var nestedRuleCst = cstStack[cstStack.length - 1];
+ this.nestedRuleFinallyStateUpdate();
+ // this return a different result than the previous invocation because "nestedRuleFinallyStateUpdate" pops the cst stack
+ var parentCstNode = cstStack[cstStack.length - 1];
+ cst_1.addNoneTerminalToCst(parentCstNode, nestedName, nestedRuleCst);
+ this.setNodeLocationFromNode(parentCstNode.location, nestedRuleCst.location);
+ };
+ TreeBuilder.prototype.getLastExplicitRuleShortName = function () {
+ var lastExplictIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 1];
+ return this.RULE_STACK[lastExplictIndex];
+ };
+ TreeBuilder.prototype.getLastExplicitRuleShortNameNoCst = function () {
+ var ruleStack = this.RULE_STACK;
+ return ruleStack[ruleStack.length - 1];
+ };
+ TreeBuilder.prototype.getPreviousExplicitRuleShortName = function () {
+ var lastExplicitIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 2];
+ return this.RULE_STACK[lastExplicitIndex];
+ };
+ TreeBuilder.prototype.getPreviousExplicitRuleShortNameNoCst = function () {
+ var ruleStack = this.RULE_STACK;
+ return ruleStack[ruleStack.length - 2];
+ };
+ TreeBuilder.prototype.getLastExplicitRuleOccurrenceIndex = function () {
+ var lastExplicitIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 1];
+ return this.RULE_OCCURRENCE_STACK[lastExplicitIndex];
+ };
+ TreeBuilder.prototype.getLastExplicitRuleOccurrenceIndexNoCst = function () {
+ var occurrenceStack = this.RULE_OCCURRENCE_STACK;
+ return occurrenceStack[occurrenceStack.length - 1];
+ };
+ TreeBuilder.prototype.nestedRuleInvocationStateUpdate = function (nestedRuleName, shortNameKey) {
+ this.RULE_OCCURRENCE_STACK.push(1);
+ this.RULE_STACK.push(shortNameKey);
+ this.cstNestedInvocationStateUpdate(nestedRuleName, shortNameKey);
+ };
+ TreeBuilder.prototype.nestedRuleFinallyStateUpdate = function () {
+ this.RULE_STACK.pop();
+ this.RULE_OCCURRENCE_STACK.pop();
+ // NOOP when cst is disabled
+ this.cstNestedFinallyStateUpdate();
+ };
+ return TreeBuilder;
+}());
+exports.TreeBuilder = TreeBuilder;
+//# sourceMappingURL=tree_builder.js.map
+
+/***/ }),
+/* 32 */
+/***/ (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__(26);
+var checks_1 = __webpack_require__(11);
+function defaultVisit(ctx, param) {
+ var childrenNames = utils_1.keys(ctx);
+ var childrenNamesLength = childrenNames.length;
+ for (var i = 0; i < childrenNamesLength; i++) {
+ var currChildName = childrenNames[i];
+ var currChildArray = ctx[currChildName];
+ var currChildArrayLength = currChildArray.length;
+ for (var j = 0; j < currChildArrayLength; j++) {
+ var currChild = currChildArray[j];
+ // distinction between Tokens Children and CstNode children
+ if (currChild.tokenTypeIdx === undefined) {
+ if (currChild.fullName !== undefined) {
+ this[currChild.fullName](currChild.children, param);
+ }
+ else {
+ this[currChild.name](currChild.children, param);
+ }
+ }
+ }
+ }
+ // defaultVisit does not support generic out param
+ return undefined;
+}
+exports.defaultVisit = defaultVisit;
+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
+ lang_extensions_1.defineNameProp(derivedConstructor, grammarName + "BaseSemantics");
+ var semanticProto = {
+ visit: function (cstNode, param) {
+ // enables writing more concise visitor methods when CstNode has only a single child
+ if (utils_1.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 (utils_1.isUndefined(cstNode)) {
+ return undefined;
+ }
+ if (cstNode.fullName !== undefined) {
+ return this[cstNode.fullName](cstNode.children, param);
+ }
+ else {
+ return this[cstNode.name](cstNode.children, param);
+ }
+ },
+ validateVisitor: function () {
+ var semanticDefinitionErrors = validateVisitor(this, ruleNames);
+ if (!utils_1.isEmpty(semanticDefinitionErrors)) {
+ var errorMessages = utils_1.map(semanticDefinitionErrors, function (currDefError) { return currDefError.msg; });
+ throw Error("Errors Detected in CST Visitor <" + lang_extensions_1.functionName(this.constructor) + ">:\n\t" +
+ ("" + errorMessages.join("\n\n").replace(/\n/g, "\n\t")));
+ }
+ }
+ };
+ derivedConstructor.prototype = semanticProto;
+ derivedConstructor.prototype.constructor = derivedConstructor;
+ derivedConstructor._RULE_NAMES = ruleNames;
+ return derivedConstructor;
+}
+exports.createBaseSemanticVisitorConstructor = createBaseSemanticVisitorConstructor;
+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
+ lang_extensions_1.defineNameProp(derivedConstructor, grammarName + "BaseSemanticsWithDefaults");
+ var withDefaultsProto = Object.create(baseConstructor.prototype);
+ utils_1.forEach(ruleNames, function (ruleName) {
+ withDefaultsProto[ruleName] = defaultVisit;
+ });
+ derivedConstructor.prototype = withDefaultsProto;
+ derivedConstructor.prototype.constructor = derivedConstructor;
+ return derivedConstructor;
+}
+exports.createBaseVisitorConstructorWithDefaults = createBaseVisitorConstructorWithDefaults;
+var CstVisitorDefinitionError;
+(function (CstVisitorDefinitionError) {
+ CstVisitorDefinitionError[CstVisitorDefinitionError["REDUNDANT_METHOD"] = 0] = "REDUNDANT_METHOD";
+ CstVisitorDefinitionError[CstVisitorDefinitionError["MISSING_METHOD"] = 1] = "MISSING_METHOD";
+})(CstVisitorDefinitionError = exports.CstVisitorDefinitionError || (exports.CstVisitorDefinitionError = {}));
+function validateVisitor(visitorInstance, ruleNames) {
+ var missingErrors = validateMissingCstMethods(visitorInstance, ruleNames);
+ var redundantErrors = validateRedundantMethods(visitorInstance, ruleNames);
+ return missingErrors.concat(redundantErrors);
+}
+exports.validateVisitor = validateVisitor;
+function validateMissingCstMethods(visitorInstance, ruleNames) {
+ var errors = utils_1.map(ruleNames, function (currRuleName) {
+ if (!utils_1.isFunction(visitorInstance[currRuleName])) {
+ return {
+ msg: "Missing visitor method: <" + currRuleName + "> on " + lang_extensions_1.functionName(visitorInstance.constructor) + " CST Visitor.",
+ type: CstVisitorDefinitionError.MISSING_METHOD,
+ methodName: currRuleName
+ };
+ }
+ });
+ return utils_1.compact(errors);
+}
+exports.validateMissingCstMethods = validateMissingCstMethods;
+var VALID_PROP_NAMES = ["constructor", "visit", "validateVisitor"];
+function validateRedundantMethods(visitorInstance, ruleNames) {
+ var errors = [];
+ for (var prop in visitorInstance) {
+ if (checks_1.validTermsPattern.test(prop) &&
+ utils_1.isFunction(visitorInstance[prop]) &&
+ !utils_1.contains(VALID_PROP_NAMES, prop) &&
+ !utils_1.contains(ruleNames, prop)) {
+ errors.push({
+ msg: "Redundant visitor method: <" + prop + "> on " + lang_extensions_1.functionName(visitorInstance.constructor) + " CST Visitor\n" +
+ "There is no Grammar Rule corresponding to this method's name.\n" +
+ ("For utility methods on visitor classes use methods names that do not match /" + checks_1.validTermsPattern.source + "/."),
+ type: CstVisitorDefinitionError.REDUNDANT_METHOD,
+ methodName: prop
+ });
+ }
+ }
+ return errors;
+}
+exports.validateRedundantMethods = validateRedundantMethods;
+//# sourceMappingURL=cst_visitor.js.map
+
+/***/ }),
+/* 33 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var parser_1 = __webpack_require__(2);
+/**
+ * Trait responsible abstracting over the interaction with Lexer output (Token vector).
+ *
+ * This could be generalized to support other kinds of lexers, e.g.
+ * - Just in Time Lexing / Lexer-Less parsing.
+ * - Streaming Lexer.
+ */
+var LexerAdapter = /** @class */ (function () {
+ function LexerAdapter() {
+ }
+ LexerAdapter.prototype.initLexerAdapter = function () {
+ this.tokVector = [];
+ this.tokVectorLength = 0;
+ this.currIdx = -1;
+ };
+ Object.defineProperty(LexerAdapter.prototype, "input", {
+ get: function () {
+ return this.tokVector;
+ },
+ set: function (newInput) {
+ if (this.selfAnalysisDone !== true) {
+ throw Error("Missing invocation at the end of the Parser's constructor.");
+ }
+ this.reset();
+ this.tokVector = newInput;
+ this.tokVectorLength = newInput.length;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ // skips a token and returns the next token
+ LexerAdapter.prototype.SKIP_TOKEN = function () {
+ if (this.currIdx <= this.tokVector.length - 2) {
+ this.consumeToken();
+ return this.LA(1);
+ }
+ else {
+ return parser_1.END_OF_FILE;
+ }
+ };
+ // Lexer (accessing Token vector) related methods which can be overridden to implement lazy lexers
+ // or lexers dependent on parser context.
+ LexerAdapter.prototype.LA = function (howMuch) {
+ var soughtIdx = this.currIdx + howMuch;
+ if (soughtIdx < 0 || this.tokVectorLength <= soughtIdx) {
+ return parser_1.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;
+}());
+exports.LexerAdapter = LexerAdapter;
+//# sourceMappingURL=lexer_adapter.js.map
+
+/***/ }),
+/* 34 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+var exceptions_public_1 = __webpack_require__(8);
+var parser_1 = __webpack_require__(2);
+var errors_public_1 = __webpack_require__(10);
+var checks_1 = __webpack_require__(11);
+var gast_public_1 = __webpack_require__(1);
+/**
+ * This trait is responsible for implementing the public API
+ * for defining Chevrotain parsers, i.e:
+ * - CONSUME
+ * - RULE
+ * - OPTION
+ * - ...
+ */
+var RecognizerApi = /** @class */ (function () {
+ function RecognizerApi() {
+ }
+ RecognizerApi.prototype.ACTION = function (impl) {
+ return impl.call(this);
+ };
+ RecognizerApi.prototype.consume = function (idx, tokType, options) {
+ return this.consumeInternal(tokType, idx, options);
+ };
+ RecognizerApi.prototype.subrule = function (idx, ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, idx, options);
+ };
+ RecognizerApi.prototype.option = function (idx, actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, idx);
+ };
+ RecognizerApi.prototype.or = function (idx, altsOrOpts) {
+ return this.orInternal(altsOrOpts, idx);
+ };
+ RecognizerApi.prototype.many = function (idx, actionORMethodDef) {
+ return this.manyInternal(idx, actionORMethodDef);
+ };
+ RecognizerApi.prototype.atLeastOne = function (idx, actionORMethodDef) {
+ return this.atLeastOneInternal(idx, actionORMethodDef);
+ };
+ RecognizerApi.prototype.CONSUME = function (tokType, options) {
+ return this.consumeInternal(tokType, 0, options);
+ };
+ RecognizerApi.prototype.CONSUME1 = function (tokType, options) {
+ return this.consumeInternal(tokType, 1, options);
+ };
+ RecognizerApi.prototype.CONSUME2 = function (tokType, options) {
+ return this.consumeInternal(tokType, 2, options);
+ };
+ RecognizerApi.prototype.CONSUME3 = function (tokType, options) {
+ return this.consumeInternal(tokType, 3, options);
+ };
+ RecognizerApi.prototype.CONSUME4 = function (tokType, options) {
+ return this.consumeInternal(tokType, 4, options);
+ };
+ RecognizerApi.prototype.CONSUME5 = function (tokType, options) {
+ return this.consumeInternal(tokType, 5, options);
+ };
+ RecognizerApi.prototype.CONSUME6 = function (tokType, options) {
+ return this.consumeInternal(tokType, 6, options);
+ };
+ RecognizerApi.prototype.CONSUME7 = function (tokType, options) {
+ return this.consumeInternal(tokType, 7, options);
+ };
+ RecognizerApi.prototype.CONSUME8 = function (tokType, options) {
+ return this.consumeInternal(tokType, 8, options);
+ };
+ RecognizerApi.prototype.CONSUME9 = function (tokType, options) {
+ return this.consumeInternal(tokType, 9, options);
+ };
+ RecognizerApi.prototype.SUBRULE = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 0, options);
+ };
+ RecognizerApi.prototype.SUBRULE1 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 1, options);
+ };
+ RecognizerApi.prototype.SUBRULE2 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 2, options);
+ };
+ RecognizerApi.prototype.SUBRULE3 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 3, options);
+ };
+ RecognizerApi.prototype.SUBRULE4 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 4, options);
+ };
+ RecognizerApi.prototype.SUBRULE5 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 5, options);
+ };
+ RecognizerApi.prototype.SUBRULE6 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 6, options);
+ };
+ RecognizerApi.prototype.SUBRULE7 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 7, options);
+ };
+ RecognizerApi.prototype.SUBRULE8 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 8, options);
+ };
+ RecognizerApi.prototype.SUBRULE9 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 9, options);
+ };
+ RecognizerApi.prototype.OPTION = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 0);
+ };
+ RecognizerApi.prototype.OPTION1 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 1);
+ };
+ RecognizerApi.prototype.OPTION2 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 2);
+ };
+ RecognizerApi.prototype.OPTION3 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 3);
+ };
+ RecognizerApi.prototype.OPTION4 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 4);
+ };
+ RecognizerApi.prototype.OPTION5 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 5);
+ };
+ RecognizerApi.prototype.OPTION6 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 6);
+ };
+ RecognizerApi.prototype.OPTION7 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 7);
+ };
+ RecognizerApi.prototype.OPTION8 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 8);
+ };
+ RecognizerApi.prototype.OPTION9 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 9);
+ };
+ RecognizerApi.prototype.OR = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 0);
+ };
+ RecognizerApi.prototype.OR1 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 1);
+ };
+ RecognizerApi.prototype.OR2 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 2);
+ };
+ RecognizerApi.prototype.OR3 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 3);
+ };
+ RecognizerApi.prototype.OR4 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 4);
+ };
+ RecognizerApi.prototype.OR5 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 5);
+ };
+ RecognizerApi.prototype.OR6 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 6);
+ };
+ RecognizerApi.prototype.OR7 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 7);
+ };
+ RecognizerApi.prototype.OR8 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 8);
+ };
+ RecognizerApi.prototype.OR9 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 9);
+ };
+ RecognizerApi.prototype.MANY = function (actionORMethodDef) {
+ this.manyInternal(0, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY1 = function (actionORMethodDef) {
+ this.manyInternal(1, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY2 = function (actionORMethodDef) {
+ this.manyInternal(2, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY3 = function (actionORMethodDef) {
+ this.manyInternal(3, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY4 = function (actionORMethodDef) {
+ this.manyInternal(4, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY5 = function (actionORMethodDef) {
+ this.manyInternal(5, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY6 = function (actionORMethodDef) {
+ this.manyInternal(6, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY7 = function (actionORMethodDef) {
+ this.manyInternal(7, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY8 = function (actionORMethodDef) {
+ this.manyInternal(8, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY9 = function (actionORMethodDef) {
+ this.manyInternal(9, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY_SEP = function (options) {
+ this.manySepFirstInternal(0, options);
+ };
+ RecognizerApi.prototype.MANY_SEP1 = function (options) {
+ this.manySepFirstInternal(1, options);
+ };
+ RecognizerApi.prototype.MANY_SEP2 = function (options) {
+ this.manySepFirstInternal(2, options);
+ };
+ RecognizerApi.prototype.MANY_SEP3 = function (options) {
+ this.manySepFirstInternal(3, options);
+ };
+ RecognizerApi.prototype.MANY_SEP4 = function (options) {
+ this.manySepFirstInternal(4, options);
+ };
+ RecognizerApi.prototype.MANY_SEP5 = function (options) {
+ this.manySepFirstInternal(5, options);
+ };
+ RecognizerApi.prototype.MANY_SEP6 = function (options) {
+ this.manySepFirstInternal(6, options);
+ };
+ RecognizerApi.prototype.MANY_SEP7 = function (options) {
+ this.manySepFirstInternal(7, options);
+ };
+ RecognizerApi.prototype.MANY_SEP8 = function (options) {
+ this.manySepFirstInternal(8, options);
+ };
+ RecognizerApi.prototype.MANY_SEP9 = function (options) {
+ this.manySepFirstInternal(9, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE = function (actionORMethodDef) {
+ this.atLeastOneInternal(0, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE1 = function (actionORMethodDef) {
+ return this.atLeastOneInternal(1, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE2 = function (actionORMethodDef) {
+ this.atLeastOneInternal(2, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE3 = function (actionORMethodDef) {
+ this.atLeastOneInternal(3, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE4 = function (actionORMethodDef) {
+ this.atLeastOneInternal(4, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE5 = function (actionORMethodDef) {
+ this.atLeastOneInternal(5, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE6 = function (actionORMethodDef) {
+ this.atLeastOneInternal(6, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE7 = function (actionORMethodDef) {
+ this.atLeastOneInternal(7, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE8 = function (actionORMethodDef) {
+ this.atLeastOneInternal(8, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE9 = function (actionORMethodDef) {
+ this.atLeastOneInternal(9, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP = function (options) {
+ this.atLeastOneSepFirstInternal(0, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP1 = function (options) {
+ this.atLeastOneSepFirstInternal(1, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP2 = function (options) {
+ this.atLeastOneSepFirstInternal(2, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP3 = function (options) {
+ this.atLeastOneSepFirstInternal(3, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP4 = function (options) {
+ this.atLeastOneSepFirstInternal(4, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP5 = function (options) {
+ this.atLeastOneSepFirstInternal(5, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP6 = function (options) {
+ this.atLeastOneSepFirstInternal(6, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP7 = function (options) {
+ this.atLeastOneSepFirstInternal(7, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP8 = function (options) {
+ this.atLeastOneSepFirstInternal(8, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP9 = function (options) {
+ this.atLeastOneSepFirstInternal(9, options);
+ };
+ RecognizerApi.prototype.RULE = function (name, implementation, config) {
+ if (config === void 0) { config = parser_1.DEFAULT_RULE_CONFIG; }
+ if (utils_1.contains(this.definedRulesNames, name)) {
+ var errMsg = errors_public_1.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({
+ topLevelRule: name,
+ grammarName: this.className
+ });
+ var error = {
+ message: errMsg,
+ type: parser_1.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,
+ ruleName: name
+ };
+ this.definitionErrors.push(error);
+ }
+ this.definedRulesNames.push(name);
+ var ruleImplementation = this.defineRule(name, implementation, config);
+ this[name] = ruleImplementation;
+ return ruleImplementation;
+ };
+ RecognizerApi.prototype.OVERRIDE_RULE = function (name, impl, config) {
+ if (config === void 0) { config = parser_1.DEFAULT_RULE_CONFIG; }
+ var ruleErrors = [];
+ ruleErrors = ruleErrors.concat(checks_1.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 (exceptions_public_1.isRecognitionException(e)) {
+ return false;
+ }
+ else {
+ throw e;
+ }
+ }
+ finally {
+ this.reloadRecogState(orgState);
+ this.isBackTrackingStack.pop();
+ }
+ };
+ };
+ // GAST export APIs
+ RecognizerApi.prototype.getGAstProductions = function () {
+ return this.gastProductionsCache;
+ };
+ RecognizerApi.prototype.getSerializedGastProductions = function () {
+ return gast_public_1.serializeGrammar(utils_1.values(this.gastProductionsCache));
+ };
+ return RecognizerApi;
+}());
+exports.RecognizerApi = RecognizerApi;
+//# sourceMappingURL=recognizer_api.js.map
+
+/***/ }),
+/* 35 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+var keys_1 = __webpack_require__(7);
+var exceptions_public_1 = __webpack_require__(8);
+var lookahead_1 = __webpack_require__(12);
+var interpreter_1 = __webpack_require__(13);
+var parser_1 = __webpack_require__(2);
+var recoverable_1 = __webpack_require__(25);
+var tokens_public_1 = __webpack_require__(3);
+var tokens_1 = __webpack_require__(5);
+var lang_extensions_1 = __webpack_require__(26);
+/**
+ * This trait is responsible for the runtime parsing engine
+ * Used by the official API (recognizer_api.ts)
+ */
+var RecognizerEngine = /** @class */ (function () {
+ function RecognizerEngine() {
+ }
+ RecognizerEngine.prototype.initRecognizerEngine = function (tokenVocabulary, config) {
+ this.className = lang_extensions_1.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 = tokens_1.tokenStructuredMatcherNoCategories;
+ this.definedRulesNames = [];
+ this.tokensMap = {};
+ this.allRuleNames = [];
+ this.isBackTrackingStack = [];
+ this.RULE_STACK = [];
+ this.RULE_OCCURRENCE_STACK = [];
+ this.gastProductionsCache = {};
+ if (utils_1.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 (utils_1.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 (utils_1.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 (utils_1.isArray(tokenVocabulary)) {
+ this.tokensMap = utils_1.reduce(tokenVocabulary, function (acc, tokType) {
+ acc[tokType.name] = tokType;
+ return acc;
+ }, {});
+ }
+ else if (utils_1.has(tokenVocabulary, "modes") &&
+ utils_1.every(utils_1.flatten(utils_1.values(tokenVocabulary.modes)), tokens_1.isTokenType)) {
+ var allTokenTypes = utils_1.flatten(utils_1.values(tokenVocabulary.modes));
+ var uniqueTokens = utils_1.uniq(allTokenTypes);
+ this.tokensMap = utils_1.reduce(uniqueTokens, function (acc, tokType) {
+ acc[tokType.name] = tokType;
+ return acc;
+ }, {});
+ }
+ else if (utils_1.isObject(tokenVocabulary)) {
+ this.tokensMap = utils_1.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"] = tokens_public_1.EOF;
+ // TODO: This check may not be accurate for multi mode lexers
+ var noTokenCategoriesUsed = utils_1.every(utils_1.values(tokenVocabulary), function (tokenConstructor) { return utils_1.isEmpty(tokenConstructor.categoryMatches); });
+ this.tokenMatcher = noTokenCategoriesUsed
+ ? tokens_1.tokenStructuredMatcherNoCategories
+ : tokens_1.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
+ tokens_1.augmentTokenTypes(utils_1.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 = utils_1.has(config, "resyncEnabled")
+ ? config.resyncEnabled
+ : parser_1.DEFAULT_RULE_CONFIG.resyncEnabled;
+ var recoveryValueFunc = utils_1.has(config, "recoveryValueFunc")
+ ? config.recoveryValueFunc
+ : parser_1.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 <<
+ (keys_1.BITS_FOR_METHOD_TYPE + keys_1.BITS_FOR_OCCURRENCE_IDX);
+ /* tslint:enable */
+ this.ruleShortNameIdx++;
+ this.shortRuleNameToFull[shortName] = ruleName;
+ this.fullRuleNameToShort[ruleName] = shortName;
+ function invokeRuleWithTry(args) {
+ try {
+ if (this.outputCst === true) {
+ impl.apply(this, args);
+ var cst = this.CST_STACK[this.CST_STACK.length - 1];
+ this.cstPostRule(cst);
+ return cst;
+ }
+ else {
+ return impl.apply(this, args);
+ }
+ }
+ catch (e) {
+ return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc);
+ }
+ finally {
+ this.ruleFinallyStateUpdate();
+ }
+ }
+ var wrappedGrammarRule;
+ wrappedGrammarRule = function (idxInCallingRule, args) {
+ if (idxInCallingRule === void 0) { idxInCallingRule = 0; }
+ this.ruleInvocationStateUpdate(shortName, ruleName, idxInCallingRule);
+ return invokeRuleWithTry.call(this, args);
+ };
+ var ruleNamePropName = "ruleName";
+ wrappedGrammarRule[ruleNamePropName] = ruleName;
+ wrappedGrammarRule["originalGrammarAction"] = impl;
+ return wrappedGrammarRule;
+ };
+ RecognizerEngine.prototype.invokeRuleCatch = function (e, resyncEnabledConfig, recoveryValueFunc) {
+ var isFirstInvokedRule = this.RULE_STACK.length === 1;
+ // note the reSync is always enabled for the first rule invocation, because we must always be able to
+ // reSync with EOF and just output some INVALID ParseTree
+ // during backtracking reSync recovery is disabled, otherwise we can't be certain the backtracking
+ // path is really the most valid one
+ var reSyncEnabled = resyncEnabledConfig &&
+ !this.isBackTracking() &&
+ this.recoveryEnabled;
+ if (exceptions_public_1.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(keys_1.OPTION_IDX, occurrence);
+ var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, key);
+ try {
+ return this.optionInternalLogic(actionORMethodDef, occurrence, key);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(key, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.optionInternalNoCst = function (actionORMethodDef, occurrence) {
+ var key = this.getKeyForAutomaticLookahead(keys_1.OPTION_IDX, occurrence);
+ return this.optionInternalLogic(actionORMethodDef, occurrence, key);
+ };
+ RecognizerEngine.prototype.optionInternalLogic = function (actionORMethodDef, occurrence, key) {
+ var _this = this;
+ var lookAheadFunc = this.getLaFuncFromCache(key);
+ var action;
+ var predicate;
+ if (actionORMethodDef.DEF !== undefined) {
+ action = actionORMethodDef.DEF;
+ predicate = actionORMethodDef.GATE;
+ // predicate present
+ if (predicate !== undefined) {
+ var orgLookaheadFunction_1 = lookAheadFunc;
+ lookAheadFunc = function () {
+ return (predicate.call(_this) && orgLookaheadFunction_1.call(_this));
+ };
+ }
+ }
+ else {
+ action = actionORMethodDef;
+ }
+ if (lookAheadFunc.call(this) === true) {
+ return action.call(this);
+ }
+ return undefined;
+ };
+ RecognizerEngine.prototype.atLeastOneInternal = function (prodOccurrence, actionORMethodDef) {
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.AT_LEAST_ONE_IDX, prodOccurrence);
+ var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, laKey);
+ try {
+ return this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, laKey);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.atLeastOneInternalNoCst = function (prodOccurrence, actionORMethodDef) {
+ var key = this.getKeyForAutomaticLookahead(keys_1.AT_LEAST_ONE_IDX, prodOccurrence);
+ this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, key);
+ };
+ RecognizerEngine.prototype.atLeastOneInternalLogic = function (prodOccurrence, actionORMethodDef, key) {
+ var _this = this;
+ var lookAheadFunc = this.getLaFuncFromCache(key);
+ var action;
+ var predicate;
+ if (actionORMethodDef.DEF !== undefined) {
+ action = actionORMethodDef.DEF;
+ predicate = actionORMethodDef.GATE;
+ // predicate present
+ if (predicate !== undefined) {
+ var orgLookaheadFunction_2 = lookAheadFunc;
+ lookAheadFunc = function () {
+ return (predicate.call(_this) && orgLookaheadFunction_2.call(_this));
+ };
+ }
+ }
+ else {
+ action = actionORMethodDef;
+ }
+ if (lookAheadFunc.call(this) === true) {
+ var notStuck = this.doSingleRepetition(action);
+ while (lookAheadFunc.call(this) === true &&
+ notStuck === true) {
+ notStuck = this.doSingleRepetition(action);
+ }
+ }
+ else {
+ throw this.raiseEarlyExitException(prodOccurrence, lookahead_1.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, keys_1.AT_LEAST_ONE_IDX, prodOccurrence, interpreter_1.NextTerminalAfterAtLeastOneWalker);
+ };
+ RecognizerEngine.prototype.atLeastOneSepFirstInternal = function (prodOccurrence, options) {
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.AT_LEAST_ONE_SEP_IDX, prodOccurrence);
+ var nestedName = this.nestedRuleBeforeClause(options, laKey);
+ try {
+ this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.atLeastOneSepFirstInternalNoCst = function (prodOccurrence, options) {
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.AT_LEAST_ONE_SEP_IDX, prodOccurrence);
+ this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey);
+ };
+ RecognizerEngine.prototype.atLeastOneSepFirstInternalLogic = function (prodOccurrence, options, key) {
+ var _this = this;
+ var action = options.DEF;
+ var separator = options.SEP;
+ var firstIterationLookaheadFunc = this.getLaFuncFromCache(key);
+ // 1st iteration
+ if (firstIterationLookaheadFunc.call(this) === true) {
+ ;
+ action.call(this);
+ // TODO: Optimization can move this function construction into "attemptInRepetitionRecovery"
+ // because it is only needed in error recovery scenarios.
+ var separatorLookAheadFunc = function () {
+ return _this.tokenMatcher(_this.LA(1), separator);
+ };
+ // 2nd..nth iterations
+ while (this.tokenMatcher(this.LA(1), separator) === true) {
+ // note that this CONSUME will never enter recovery because
+ // the separatorLookAheadFunc checks that the separator really does exist.
+ this.CONSUME(separator);
+ action.call(this);
+ }
+ // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled
+ this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [
+ prodOccurrence,
+ separator,
+ separatorLookAheadFunc,
+ action,
+ interpreter_1.NextTerminalAfterAtLeastOneSepWalker
+ ], separatorLookAheadFunc, keys_1.AT_LEAST_ONE_SEP_IDX, prodOccurrence, interpreter_1.NextTerminalAfterAtLeastOneSepWalker);
+ }
+ else {
+ throw this.raiseEarlyExitException(prodOccurrence, lookahead_1.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, options.ERR_MSG);
+ }
+ };
+ RecognizerEngine.prototype.manyInternal = function (prodOccurrence, actionORMethodDef) {
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.MANY_IDX, prodOccurrence);
+ var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, laKey);
+ try {
+ return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.manyInternalNoCst = function (prodOccurrence, actionORMethodDef) {
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.MANY_IDX, prodOccurrence);
+ return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey);
+ };
+ RecognizerEngine.prototype.manyInternalLogic = function (prodOccurrence, actionORMethodDef, key) {
+ var _this = this;
+ var lookaheadFunction = this.getLaFuncFromCache(key);
+ var action;
+ var predicate;
+ if (actionORMethodDef.DEF !== undefined) {
+ action = actionORMethodDef.DEF;
+ predicate = actionORMethodDef.GATE;
+ // predicate present
+ if (predicate !== undefined) {
+ var orgLookaheadFunction_3 = lookaheadFunction;
+ lookaheadFunction = function () {
+ return (predicate.call(_this) && orgLookaheadFunction_3.call(_this));
+ };
+ }
+ }
+ else {
+ action = actionORMethodDef;
+ }
+ var notStuck = true;
+ while (lookaheadFunction.call(this) === true && notStuck === true) {
+ notStuck = this.doSingleRepetition(action);
+ }
+ // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled
+ this.attemptInRepetitionRecovery(this.manyInternal, [prodOccurrence, actionORMethodDef], lookaheadFunction, keys_1.MANY_IDX, prodOccurrence, interpreter_1.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(keys_1.MANY_SEP_IDX, prodOccurrence);
+ var nestedName = this.nestedRuleBeforeClause(options, laKey);
+ try {
+ this.manySepFirstInternalLogic(prodOccurrence, options, laKey);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.manySepFirstInternalNoCst = function (prodOccurrence, options) {
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.MANY_SEP_IDX, prodOccurrence);
+ this.manySepFirstInternalLogic(prodOccurrence, options, laKey);
+ };
+ RecognizerEngine.prototype.manySepFirstInternalLogic = function (prodOccurrence, options, key) {
+ var _this = this;
+ var action = options.DEF;
+ var separator = options.SEP;
+ var firstIterationLaFunc = this.getLaFuncFromCache(key);
+ // 1st iteration
+ if (firstIterationLaFunc.call(this) === true) {
+ action.call(this);
+ var separatorLookAheadFunc = function () {
+ return _this.tokenMatcher(_this.LA(1), separator);
+ };
+ // 2nd..nth iterations
+ while (this.tokenMatcher(this.LA(1), separator) === true) {
+ // note that this CONSUME will never enter recovery because
+ // the separatorLookAheadFunc checks that the separator really does exist.
+ this.CONSUME(separator);
+ // No need for checking infinite loop here due to consuming the separator.
+ action.call(this);
+ }
+ // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled
+ this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [
+ prodOccurrence,
+ separator,
+ separatorLookAheadFunc,
+ action,
+ interpreter_1.NextTerminalAfterManySepWalker
+ ], separatorLookAheadFunc, keys_1.MANY_SEP_IDX, prodOccurrence, interpreter_1.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, keys_1.AT_LEAST_ONE_SEP_IDX, prodOccurrence, nextTerminalAfterWalker);
+ };
+ RecognizerEngine.prototype.doSingleRepetition = function (action) {
+ var beforeIteration = this.getLexerPosition();
+ action.call(this);
+ var afterIteration = this.getLexerPosition();
+ // This boolean will indicate if this repetition progressed
+ // or if we are "stuck" (potential infinite loop in the repetition).
+ return afterIteration > beforeIteration;
+ };
+ RecognizerEngine.prototype.orInternalNoCst = function (altsOrOpts, occurrence) {
+ var alts = utils_1.isArray(altsOrOpts)
+ ? altsOrOpts
+ : altsOrOpts.DEF;
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.OR_IDX, occurrence);
+ var laFunc = this.getLaFuncFromCache(laKey);
+ var altIdxToTake = laFunc.call(this, alts);
+ if (altIdxToTake !== undefined) {
+ var chosenAlternative = alts[altIdxToTake];
+ return chosenAlternative.ALT.call(this);
+ }
+ this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG);
+ };
+ RecognizerEngine.prototype.orInternal = function (altsOrOpts, occurrence) {
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.OR_IDX, occurrence);
+ var nestedName = this.nestedRuleBeforeClause(altsOrOpts, laKey);
+ try {
+ var alts = utils_1.isArray(altsOrOpts)
+ ? altsOrOpts
+ : altsOrOpts.DEF;
+ var laFunc = this.getLaFuncFromCache(laKey);
+ var altIdxToTake = laFunc.call(this, alts);
+ if (altIdxToTake !== undefined) {
+ var chosenAlternative = alts[altIdxToTake];
+ var nestedAltBeforeClauseResult = this.nestedAltBeforeClause(chosenAlternative, occurrence, keys_1.OR_IDX, altIdxToTake);
+ try {
+ return chosenAlternative.ALT.call(this);
+ }
+ finally {
+ if (nestedAltBeforeClauseResult !== undefined) {
+ this.nestedRuleFinallyClause(nestedAltBeforeClauseResult.shortName, nestedAltBeforeClauseResult.nestedName);
+ }
+ }
+ }
+ this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.ruleFinallyStateUpdate = function () {
+ this.RULE_STACK.pop();
+ this.RULE_OCCURRENCE_STACK.pop();
+ // NOOP when cst is disabled
+ this.cstFinallyStateUpdate();
+ if (this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) {
+ var firstRedundantTok = this.LA(1);
+ var errMsg = this.errorMessageProvider.buildNotAllInputParsedMessage({
+ firstRedundant: firstRedundantTok,
+ ruleName: this.getCurrRuleFullName()
+ });
+ this.SAVE_ERROR(new exceptions_public_1.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 (exceptions_public_1.isRecognitionException(e) && e.partialCstResult !== undefined) {
+ this.cstPostNonTerminal(e.partialCstResult, options !== undefined && options.LABEL !== undefined
+ ? options.LABEL
+ : ruleName);
+ delete e.partialCstResult;
+ }
+ throw e;
+ };
+ RecognizerEngine.prototype.consumeInternal = function (tokType, idx, options) {
+ var consumedToken;
+ try {
+ var nextToken = this.LA(1);
+ if (this.tokenMatcher(nextToken, tokType) === true) {
+ this.consumeToken();
+ consumedToken = nextToken;
+ }
+ else {
+ this.consumeInternalError(tokType, nextToken, options);
+ }
+ }
+ catch (eFromConsumption) {
+ consumedToken = this.consumeInternalRecovery(tokType, idx, eFromConsumption);
+ }
+ this.cstPostTerminal(options !== undefined && options.LABEL !== undefined
+ ? options.LABEL
+ : tokType.name, consumedToken);
+ return consumedToken;
+ };
+ RecognizerEngine.prototype.consumeInternalError = function (tokType, nextToken, options) {
+ var msg;
+ var previousToken = this.LA(0);
+ if (options !== undefined && options.ERR_MSG) {
+ msg = options.ERR_MSG;
+ }
+ else {
+ msg = this.errorMessageProvider.buildMismatchTokenMessage({
+ expected: tokType,
+ actual: nextToken,
+ previous: previousToken,
+ ruleName: this.getCurrRuleFullName()
+ });
+ }
+ throw this.SAVE_ERROR(new exceptions_public_1.MismatchedTokenException(msg, nextToken, previousToken));
+ };
+ RecognizerEngine.prototype.consumeInternalRecovery = function (tokType, idx, eFromConsumption) {
+ // no recovery allowed during backtracking, otherwise backtracking may recover invalid syntax and accept it
+ // but the original syntax could have been parsed successfully without any backtracking + recovery
+ if (this.recoveryEnabled &&
+ // TODO: more robust checking of the exception type. Perhaps Typescript extending expressions?
+ eFromConsumption.name === "MismatchedTokenException" &&
+ !this.isBackTracking()) {
+ var follows = this.getFollowsForInRuleRecovery(tokType, idx);
+ try {
+ return this.tryInRuleRecovery(tokType, follows);
+ }
+ catch (eFromInRuleRecovery) {
+ if (eFromInRuleRecovery.name === recoverable_1.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 = utils_1.cloneArr(this.RULE_STACK);
+ return {
+ errors: savedErrors,
+ lexerState: this.exportLexerState(),
+ RULE_STACK: savedRuleStack,
+ CST_STACK: this.CST_STACK,
+ LAST_EXPLICIT_RULE_STACK: this.LAST_EXPLICIT_RULE_STACK
+ };
+ };
+ RecognizerEngine.prototype.reloadRecogState = function (newState) {
+ this.errors = newState.errors;
+ this.importLexerState(newState.lexerState);
+ this.RULE_STACK = newState.RULE_STACK;
+ };
+ RecognizerEngine.prototype.ruleInvocationStateUpdate = function (shortName, fullName, idxInCallingRule) {
+ this.RULE_OCCURRENCE_STACK.push(idxInCallingRule);
+ this.RULE_STACK.push(shortName);
+ // NOOP when cst is disabled
+ this.cstInvocationStateUpdate(fullName, shortName);
+ };
+ RecognizerEngine.prototype.isBackTracking = function () {
+ return this.isBackTrackingStack.length !== 0;
+ };
+ RecognizerEngine.prototype.getCurrRuleFullName = function () {
+ var shortName = this.getLastExplicitRuleShortName();
+ return this.shortRuleNameToFull[shortName];
+ };
+ RecognizerEngine.prototype.shortRuleNameToFullName = function (shortName) {
+ return this.shortRuleNameToFull[shortName];
+ };
+ RecognizerEngine.prototype.isAtEndOfInput = function () {
+ return this.tokenMatcher(this.LA(1), tokens_public_1.EOF);
+ };
+ RecognizerEngine.prototype.reset = function () {
+ this.resetLexerState();
+ this.isBackTrackingStack = [];
+ this.errors = [];
+ this.RULE_STACK = [];
+ this.LAST_EXPLICIT_RULE_STACK = [];
+ // TODO: extract a specific rest for TreeBuilder trait
+ this.CST_STACK = [];
+ this.RULE_OCCURRENCE_STACK = [];
+ };
+ return RecognizerEngine;
+}());
+exports.RecognizerEngine = RecognizerEngine;
+//# sourceMappingURL=recognizer_engine.js.map
+
+/***/ }),
+/* 36 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var exceptions_public_1 = __webpack_require__(8);
+var utils_1 = __webpack_require__(0);
+var lookahead_1 = __webpack_require__(12);
+var parser_1 = __webpack_require__(2);
+/**
+ * Trait responsible for runtime parsing errors.
+ */
+var ErrorHandler = /** @class */ (function () {
+ function ErrorHandler() {
+ }
+ ErrorHandler.prototype.initErrorHandler = function (config) {
+ this._errors = [];
+ this.errorMessageProvider = utils_1.defaults(config.errorMessageProvider, parser_1.DEFAULT_PARSER_CONFIG.errorMessageProvider);
+ };
+ ErrorHandler.prototype.SAVE_ERROR = function (error) {
+ if (exceptions_public_1.isRecognitionException(error)) {
+ error.context = {
+ ruleStack: this.getHumanReadableRuleStack(),
+ ruleOccurrenceStack: utils_1.cloneArr(this.RULE_OCCURRENCE_STACK)
+ };
+ this._errors.push(error);
+ return error;
+ }
+ else {
+ throw Error("Trying to save an Error which is not a RecognitionException");
+ }
+ };
+ Object.defineProperty(ErrorHandler.prototype, "errors", {
+ // TODO: extract these methods to ErrorHandler Trait?
+ get: function () {
+ return utils_1.cloneArr(this._errors);
+ },
+ set: function (newErrors) {
+ this._errors = newErrors;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ // TODO: consider caching the error message computed information
+ ErrorHandler.prototype.raiseEarlyExitException = function (occurrence, prodType, userDefinedErrMsg) {
+ var ruleName = this.getCurrRuleFullName();
+ var ruleGrammar = this.getGAstProductions()[ruleName];
+ var lookAheadPathsPerAlternative = lookahead_1.getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, this.maxLookahead);
+ var insideProdPaths = lookAheadPathsPerAlternative[0];
+ var actualTokens = [];
+ for (var i = 1; i <= this.maxLookahead; i++) {
+ actualTokens.push(this.LA(i));
+ }
+ var msg = this.errorMessageProvider.buildEarlyExitMessage({
+ expectedIterationPaths: insideProdPaths,
+ actual: actualTokens,
+ previous: this.LA(0),
+ customUserDescription: userDefinedErrMsg,
+ ruleName: ruleName
+ });
+ throw this.SAVE_ERROR(new exceptions_public_1.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 = lookahead_1.getLookaheadPathsForOr(occurrence, ruleGrammar, this.maxLookahead);
+ var actualTokens = [];
+ for (var i = 1; i <= this.maxLookahead; i++) {
+ actualTokens.push(this.LA(i));
+ }
+ var previousToken = this.LA(0);
+ var errMsg = this.errorMessageProvider.buildNoViableAltMessage({
+ expectedPathsPerAlt: lookAheadPathsPerAlternative,
+ actual: actualTokens,
+ previous: previousToken,
+ customUserDescription: errMsgTypes,
+ ruleName: this.getCurrRuleFullName()
+ });
+ throw this.SAVE_ERROR(new exceptions_public_1.NoViableAltException(errMsg, this.LA(1), previousToken));
+ };
+ return ErrorHandler;
+}());
+exports.ErrorHandler = ErrorHandler;
+//# sourceMappingURL=error_handler.js.map
+
+/***/ }),
+/* 37 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var interpreter_1 = __webpack_require__(13);
+var utils_1 = __webpack_require__(0);
+var ContentAssist = /** @class */ (function () {
+ function ContentAssist() {
+ }
+ ContentAssist.prototype.initContentAssist = function () { };
+ ContentAssist.prototype.computeContentAssist = function (startRuleName, precedingInput) {
+ var startRuleGast = this.gastProductionsCache[startRuleName];
+ if (utils_1.isUndefined(startRuleGast)) {
+ throw Error("Rule ->" + startRuleName + "<- does not exist in this grammar.");
+ }
+ return interpreter_1.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 = utils_1.first(grammarPath.ruleStack);
+ var gastProductions = this.getGAstProductions();
+ var topProduction = gastProductions[topRuleName];
+ var nextPossibleTokenTypes = new interpreter_1.NextAfterTokenWalker(topProduction, grammarPath).startWalking();
+ return nextPossibleTokenTypes;
+ };
+ return ContentAssist;
+}());
+exports.ContentAssist = ContentAssist;
+//# sourceMappingURL=context_assist.js.map
+
+/***/ }),
+/* 38 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+var gast_public_1 = __webpack_require__(1);
+var lexer_public_1 = __webpack_require__(9);
+var tokens_1 = __webpack_require__(5);
+var tokens_public_1 = __webpack_require__(3);
+var parser_1 = __webpack_require__(2);
+var keys_1 = __webpack_require__(7);
+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, keys_1.BITS_FOR_OCCURRENCE_IDX) - 1;
+var RFT = tokens_public_1.createToken({ name: "RECORDING_PHASE_TOKEN", pattern: lexer_public_1.Lexer.NA });
+tokens_1.augmentTokenTypes([RFT]);
+var RECORDING_PHASE_TOKEN = tokens_public_1.createTokenInstance(RFT, "This IToken indicates the Parser is in Recording Phase\n\t" +
+ "" +
+ "See: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details",
+// Using "-1" instead of NaN (as in EOF) because an actual number is less likely to
+// cause errors if the output of LA or CONSUME would be (incorrectly) used during the recording phase.
+-1, -1, -1, -1, -1, -1);
+Object.freeze(RECORDING_PHASE_TOKEN);
+var RECORDING_PHASE_CSTNODE = {
+ name: "This CSTNode indicates the Parser is in Recording Phase\n\t" +
+ "See: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details",
+ children: {}
+};
+/**
+ * This trait handles the creation of the GAST structure for Chevrotain Grammars
+ */
+var GastRecorder = /** @class */ (function () {
+ function GastRecorder() {
+ }
+ GastRecorder.prototype.initGastRecorder = function (config) {
+ this.recordingProdStack = [];
+ this.RECORDING_PHASE = false;
+ };
+ GastRecorder.prototype.enableRecording = function () {
+ var _this = this;
+ this.RECORDING_PHASE = true;
+ this.TRACE_INIT("Enable Recording", function () {
+ var _loop_1 = function (i) {
+ var idx = i > 0 ? i : "";
+ _this["CONSUME" + idx] = function (arg1, arg2) {
+ return this.consumeInternalRecord(arg1, i, arg2);
+ };
+ _this["SUBRULE" + idx] = function (arg1, arg2) {
+ return this.subruleInternalRecord(arg1, i, arg2);
+ };
+ _this["OPTION" + idx] = function (arg1) {
+ return this.optionInternalRecord(arg1, i);
+ };
+ _this["OR" + idx] = function (arg1) {
+ return this.orInternalRecord(arg1, i);
+ };
+ _this["MANY" + idx] = function (arg1) {
+ this.manyInternalRecord(i, arg1);
+ };
+ _this["MANY_SEP" + idx] = function (arg1) {
+ this.manySepFirstInternalRecord(i, arg1);
+ };
+ _this["AT_LEAST_ONE" + idx] = function (arg1) {
+ this.atLeastOneInternalRecord(i, arg1);
+ };
+ _this["AT_LEAST_ONE_SEP" + idx] = function (arg1) {
+ this.atLeastOneSepFirstInternalRecord(i, arg1);
+ };
+ };
+ /**
+ * Warning Dark Voodoo Magic upcoming!
+ * We are "replacing" the public parsing DSL methods API
+ * With **new** alternative implementations on the Parser **instance**
+ *
+ * So far this is the only way I've found to avoid performance regressions during parsing time.
+ * - Approx 30% performance regression was measured on Chrome 75 Canary when attempting to replace the "internal"
+ * implementations directly instead.
+ */
+ for (var i = 0; i < 10; i++) {
+ _loop_1(i);
+ }
+ // DSL methods with the idx(suffix) as an argument
+ _this["consume"] = function (idx, arg1, arg2) {
+ return this.consumeInternalRecord(arg1, idx, arg2);
+ };
+ _this["subrule"] = function (idx, arg1, arg2) {
+ return this.subruleInternalRecord(arg1, idx, arg2);
+ };
+ _this["option"] = function (idx, arg1) {
+ return this.optionInternalRecord(arg1, idx);
+ };
+ _this["or"] = function (idx, arg1) {
+ return this.orInternalRecord(arg1, idx);
+ };
+ _this["many"] = function (idx, arg1) {
+ this.manyInternalRecord(idx, arg1);
+ };
+ _this["atLeastOne"] = function (idx, arg1) {
+ this.atLeastOneInternalRecord(idx, arg1);
+ };
+ _this.ACTION = _this.ACTION_RECORD;
+ _this.BACKTRACK = _this.BACKTRACK_RECORD;
+ _this.LA = _this.LA_RECORD;
+ });
+ };
+ GastRecorder.prototype.disableRecording = function () {
+ var _this = this;
+ this.RECORDING_PHASE = false;
+ // By deleting these **instance** properties, any future invocation
+ // will be deferred to the original methods on the **prototype** object
+ // This seems to get rid of any incorrect optimizations that V8 may
+ // do during the recording phase.
+ this.TRACE_INIT("Deleting Recording methods", function () {
+ for (var i = 0; i < 10; i++) {
+ var idx = i > 0 ? i : "";
+ delete _this["CONSUME" + idx];
+ delete _this["SUBRULE" + idx];
+ delete _this["OPTION" + idx];
+ delete _this["OR" + idx];
+ delete _this["MANY" + idx];
+ delete _this["MANY_SEP" + idx];
+ delete _this["AT_LEAST_ONE" + idx];
+ delete _this["AT_LEAST_ONE_SEP" + idx];
+ }
+ delete _this["consume"];
+ delete _this["subrule"];
+ delete _this["option"];
+ delete _this["or"];
+ delete _this["many"];
+ delete _this["atLeastOne"];
+ delete _this.ACTION;
+ delete _this.BACKTRACK;
+ delete _this.LA;
+ });
+ };
+ // TODO: is there any way to use this method to check no
+ // Parser methods are called inside an ACTION?
+ // Maybe try/catch/finally on ACTIONS while disabling the recorders state changes?
+ GastRecorder.prototype.ACTION_RECORD = function (impl) {
+ // NO-OP during recording
+ return;
+ };
+ // Executing backtracking logic will break our recording logic assumptions
+ GastRecorder.prototype.BACKTRACK_RECORD = function (grammarRule, args) {
+ return function () { return true; };
+ };
+ // LA is part of the official API and may be used for custom lookahead logic
+ // by end users who may forget to wrap it in ACTION or inside a GATE
+ GastRecorder.prototype.LA_RECORD = function (howMuch) {
+ // We cannot use the RECORD_PHASE_TOKEN here because someone may depend
+ // On LA return EOF at the end of the input so an infinite loop may occur.
+ return parser_1.END_OF_FILE;
+ };
+ GastRecorder.prototype.topLevelRuleRecord = function (name, def) {
+ try {
+ var newTopLevelRule = new gast_public_1.Rule({ definition: [], name: name });
+ newTopLevelRule.name = name;
+ this.recordingProdStack.push(newTopLevelRule);
+ def.call(this);
+ this.recordingProdStack.pop();
+ return newTopLevelRule;
+ }
+ catch (originalError) {
+ if (originalError.KNOWN_RECORDER_ERROR !== true) {
+ try {
+ originalError.message =
+ originalError.message +
+ '\n\t This error was thrown during the "grammar recording phase" For more info see:\n\t' +
+ "https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording";
+ }
+ catch (mutabilityError) {
+ // We may not be able to modify the original error object
+ throw originalError;
+ }
+ }
+ throw originalError;
+ }
+ };
+ // Implementation of parsing DSL
+ GastRecorder.prototype.optionInternalRecord = function (actionORMethodDef, occurrence) {
+ return recordProd.call(this, gast_public_1.Option, actionORMethodDef, occurrence);
+ };
+ GastRecorder.prototype.atLeastOneInternalRecord = function (occurrence, actionORMethodDef) {
+ recordProd.call(this, gast_public_1.RepetitionMandatory, actionORMethodDef, occurrence);
+ };
+ GastRecorder.prototype.atLeastOneSepFirstInternalRecord = function (occurrence, options) {
+ recordProd.call(this, gast_public_1.RepetitionMandatoryWithSeparator, options, occurrence, HANDLE_SEPARATOR);
+ };
+ GastRecorder.prototype.manyInternalRecord = function (occurrence, actionORMethodDef) {
+ recordProd.call(this, gast_public_1.Repetition, actionORMethodDef, occurrence);
+ };
+ GastRecorder.prototype.manySepFirstInternalRecord = function (occurrence, options) {
+ recordProd.call(this, gast_public_1.RepetitionWithSeparator, options, occurrence, HANDLE_SEPARATOR);
+ };
+ GastRecorder.prototype.orInternalRecord = function (altsOrOpts, occurrence) {
+ return recordOrProd.call(this, altsOrOpts, occurrence);
+ };
+ GastRecorder.prototype.subruleInternalRecord = function (ruleToCall, occurrence, options) {
+ assertMethodIdxIsValid(occurrence);
+ if (!ruleToCall || utils_1.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 = utils_1.peek(this.recordingProdStack);
+ var ruleName = ruleToCall["ruleName"];
+ var newNoneTerminal = new gast_public_1.NonTerminal({
+ idx: occurrence,
+ nonTerminalName: ruleName,
+ // The resolving of the `referencedRule` property will be done once all the Rule's GASTs have been created
+ referencedRule: undefined
+ });
+ prevProd.definition.push(newNoneTerminal);
+ return this.outputCst
+ ? RECORDING_PHASE_CSTNODE
+ : RECORDING_NULL_OBJECT;
+ };
+ GastRecorder.prototype.consumeInternalRecord = function (tokType, occurrence, options) {
+ assertMethodIdxIsValid(occurrence);
+ if (!tokens_1.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 = utils_1.peek(this.recordingProdStack);
+ var newNoneTerminal = new gast_public_1.Terminal({
+ idx: occurrence,
+ terminalType: tokType
+ });
+ prevProd.definition.push(newNoneTerminal);
+ return RECORDING_PHASE_TOKEN;
+ };
+ return GastRecorder;
+}());
+exports.GastRecorder = GastRecorder;
+function recordProd(prodConstructor, mainProdArg, occurrence, handleSep) {
+ if (handleSep === void 0) { handleSep = false; }
+ assertMethodIdxIsValid(occurrence);
+ var prevProd = utils_1.peek(this.recordingProdStack);
+ var grammarAction = utils_1.isFunction(mainProdArg)
+ ? mainProdArg
+ : mainProdArg.DEF;
+ var newProd = new prodConstructor({ definition: [], idx: occurrence });
+ if (utils_1.has(mainProdArg, "NAME")) {
+ newProd.name = mainProdArg.NAME;
+ }
+ if (handleSep) {
+ newProd.separator = mainProdArg.SEP;
+ }
+ if (utils_1.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 = utils_1.peek(this.recordingProdStack);
+ // Only an array of alternatives
+ var hasOptions = utils_1.isArray(mainProdArg) === false;
+ var alts = hasOptions === false ? mainProdArg : mainProdArg.DEF;
+ var newOrProd = new gast_public_1.Alternation({
+ definition: [],
+ idx: occurrence,
+ ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true
+ });
+ if (utils_1.has(mainProdArg, "NAME")) {
+ newOrProd.name = mainProdArg.NAME;
+ }
+ if (utils_1.has(mainProdArg, "MAX_LOOKAHEAD")) {
+ newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;
+ }
+ var hasPredicates = utils_1.some(alts, function (currAlt) { return utils_1.isFunction(currAlt.GATE); });
+ newOrProd.hasPredicates = hasPredicates;
+ prevProd.definition.push(newOrProd);
+ utils_1.forEach(alts, function (currAlt) {
+ var currAltFlat = new gast_public_1.Flat({ definition: [] });
+ newOrProd.definition.push(currAltFlat);
+ if (utils_1.has(currAlt, "NAME")) {
+ currAltFlat.name = currAlt.NAME;
+ }
+ if (utils_1.has(currAlt, "IGNORE_AMBIGUITIES")) {
+ currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES;
+ }
+ // **implicit** ignoreAmbiguities due to usage of gate
+ else if (utils_1.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
+
+/***/ }),
+/* 39 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+var parser_1 = __webpack_require__(2);
+/**
+ * Trait responsible for runtime parsing errors.
+ */
+var PerformanceTracer = /** @class */ (function () {
+ function PerformanceTracer() {
+ }
+ PerformanceTracer.prototype.initPerformanceTracer = function (config) {
+ if (utils_1.has(config, "traceInitPerf")) {
+ var userTraceInitPerf = config.traceInitPerf;
+ var traceIsNumber = typeof userTraceInitPerf === "number";
+ this.traceInitMaxIdent = traceIsNumber
+ ? userTraceInitPerf
+ : Infinity;
+ this.traceInitPerf = traceIsNumber
+ ? userTraceInitPerf > 0
+ : userTraceInitPerf;
+ }
+ else {
+ this.traceInitMaxIdent = 0;
+ this.traceInitPerf = parser_1.DEFAULT_PARSER_CONFIG.traceInitPerf;
+ }
+ this.traceInitIndent = -1;
+ };
+ PerformanceTracer.prototype.TRACE_INIT = function (phaseDesc, phaseImpl) {
+ // No need to optimize this using NOOP pattern because
+ // It is not called in a hot spot...
+ if (this.traceInitPerf === true) {
+ this.traceInitIndent++;
+ var indent = new Array(this.traceInitIndent + 1).join("\t");
+ if (this.traceInitIndent < this.traceInitMaxIdent) {
+ console.log(indent + "--> <" + phaseDesc + ">");
+ }
+ var _a = utils_1.timer(phaseImpl), time = _a.time, value = _a.value;
+ /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */
+ var traceMethod = time > 10 ? console.warn : console.log;
+ if (this.traceInitIndent < this.traceInitMaxIdent) {
+ traceMethod(indent + "<-- <" + phaseDesc + "> time: " + time + "ms");
+ }
+ this.traceInitIndent--;
+ return value;
+ }
+ else {
+ return phaseImpl();
+ }
+ };
+ return PerformanceTracer;
+}());
+exports.PerformanceTracer = PerformanceTracer;
+//# sourceMappingURL=perf_tracer.js.map
+
+/***/ }),
+/* 40 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var version_1 = __webpack_require__(19);
+function createSyntaxDiagramsCode(grammar, _a) {
+ var _b = _a === void 0 ? {} : _a, _c = _b.resourceBase, resourceBase = _c === void 0 ? "https://unpkg.com/chevrotain@" + version_1.VERSION + "/diagrams/" : _c, _d = _b.css, css = _d === void 0 ? "https://unpkg.com/chevrotain@" + version_1.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);
+}
+exports.createSyntaxDiagramsCode = createSyntaxDiagramsCode;
+//# sourceMappingURL=render_public.js.map
+
+/***/ }),
+/* 41 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var generate_1 = __webpack_require__(42);
+function generateParserFactory(options) {
+ var wrapperText = generate_1.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__(18));
+ };
+}
+exports.generateParserFactory = generateParserFactory;
+function generateParserModule(options) {
+ return generate_1.genUmdModule({ name: options.name, rules: options.rules });
+}
+exports.generateParserModule = generateParserModule;
+//# sourceMappingURL=generate_public.js.map
+
+/***/ }),
+/* 42 */
+/***/ (function(module, exports, __webpack_require__) {
+
+"use strict";
+
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = __webpack_require__(0);
+var gast_public_1 = __webpack_require__(1);
+/**
+ * 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";
+}
+exports.genUmdModule = genUmdModule;
+function genWrapperFunction(options) {
+ return " \n" + genClass(options) + "\nreturn new " + options.name + "(tokenVocabulary, config) \n";
+}
+exports.genWrapperFunction = genWrapperFunction;
+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;
+}
+exports.genClass = genClass;
+function genAllRules(rules) {
+ var rulesText = utils_1.map(rules, function (currRule) {
+ return genRule(currRule, 1);
+ });
+ return rulesText.join("\n");
+}
+exports.genAllRules = genAllRules;
+function genRule(prod, n) {
+ var result = indent(n, "$.RULE(\"" + prod.name + "\", function() {") + NL;
+ result += genDefinition(prod.definition, n + 1);
+ result += indent(n + 1, "})") + NL;
+ return result;
+}
+exports.genRule = genRule;
+function genTerminal(prod, n) {
+ var name = prod.terminalType.name;
+ // TODO: potential performance optimization, avoid tokenMap Dictionary access
+ return indent(n, "$.CONSUME" + prod.idx + "(this.tokensMap." + name + ")" + NL);
+}
+exports.genTerminal = genTerminal;
+function genNonTerminal(prod, n) {
+ return indent(n, "$.SUBRULE" + prod.idx + "($." + prod.nonTerminalName + ")" + NL);
+}
+exports.genNonTerminal = genNonTerminal;
+function genAlternation(prod, n) {
+ var result = indent(n, "$.OR" + prod.idx + "([") + NL;
+ var alts = utils_1.map(prod.definition, function (altDef) { return genSingleAlt(altDef, n + 1); });
+ result += alts.join("," + NL);
+ result += NL + indent(n, "])" + NL);
+ return result;
+}
+exports.genAlternation = genAlternation;
+function genSingleAlt(prod, n) {
+ var result = indent(n, "{") + NL;
+ if (prod.name) {
+ result += indent(n + 1, "NAME: \"" + prod.name + "\",") + NL;
+ }
+ result += indent(n + 1, "ALT: function() {") + NL;
+ result += genDefinition(prod.definition, n + 1);
+ result += indent(n + 1, "}") + NL;
+ result += indent(n, "}");
+ return result;
+}
+exports.genSingleAlt = genSingleAlt;
+function genProd(prod, n) {
+ /* istanbul ignore else */
+ if (prod instanceof gast_public_1.NonTerminal) {
+ return genNonTerminal(prod, n);
+ }
+ else if (prod instanceof gast_public_1.Option) {
+ return genDSLRule("OPTION", prod, n);
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatory) {
+ return genDSLRule("AT_LEAST_ONE", prod, n);
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatoryWithSeparator) {
+ return genDSLRule("AT_LEAST_ONE_SEP", prod, n);
+ }
+ else if (prod instanceof gast_public_1.RepetitionWithSeparator) {
+ return genDSLRule("MANY_SEP", prod, n);
+ }
+ else if (prod instanceof gast_public_1.Repetition) {
+ return genDSLRule("MANY", prod, n);
+ }
+ else if (prod instanceof gast_public_1.Alternation) {
+ return genAlternation(prod, n);
+ }
+ else if (prod instanceof gast_public_1.Terminal) {
+ return genTerminal(prod, n);
+ }
+ else if (prod instanceof gast_public_1.Flat) {
+ return genDefinition(prod.definition, n);
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+function genDSLRule(dslName, prod, n) {
+ var result = indent(n, "$." + (dslName + prod.idx) + "(");
+ if (prod.name || prod.separator) {
+ result += "{" + NL;
+ if (prod.name) {
+ result += indent(n + 1, "NAME: \"" + prod.name + "\"") + "," + NL;
+ }
+ if (prod.separator) {
+ result +=
+ indent(n + 1, "SEP: this.tokensMap." + prod.separator.name) +
+ "," +
+ NL;
+ }
+ result += "DEF: " + genDefFunction(prod.definition, n + 2) + NL;
+ result += indent(n, "}") + NL;
+ }
+ else {
+ result += genDefFunction(prod.definition, n + 1);
+ }
+ result += indent(n, ")") + NL;
+ return result;
+}
+function genDefFunction(definition, n) {
+ var def = "function() {" + NL;
+ def += genDefinition(definition, n);
+ def += indent(n, "}") + NL;
+ return def;
+}
+function genDefinition(def, n) {
+ var result = "";
+ utils_1.forEach(def, function (prod) {
+ result += genProd(prod, n + 1);
+ });
+ return result;
+}
+function indent(howMuch, text) {
+ var spaces = Array(howMuch * 4 + 1).join(" ");
+ return spaces + text;
+}
+//# sourceMappingURL=generate.js.map
+
+/***/ })
+/******/ ]);
+});
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/chevrotain.min.js b/node_modules/chevrotain/lib/chevrotain.min.js
new file mode 100644
index 0000000..26f3c6e
--- /dev/null
+++ b/node_modules/chevrotain/lib/chevrotain.min.js
@@ -0,0 +1,2 @@
+/*! chevrotain - v6.5.0 */
+!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("chevrotain",[],e):"object"==typeof exports?exports.chevrotain=e():t.chevrotain=e()}("undefined"!=typeof self?self:this,function(){return 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}return 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=18)}([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 IParserConfig property is soft-deprecated and will be removed in future versions.\n\tPlease use the flag on the relevant DSL method instead."),this.ignoredIssues=o.has(n,"ignoredIssues")?n.ignoredIssues:e.DEFAULT_PARSER_CONFIG.ignoredIssues,this.skipValidations=o.has(n,"skipValidations")?n.skipValidations:e.DEFAULT_PARSER_CONFIG.skipValidations}return t.performSelfAnalysis=function(t){t.performSelfAnalysis()},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(){o.toFastProperties(e)}),e.TRACE_INIT("Grammar Recording",function(){try{e.enableRecording(),o.forEach(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 i=[];if(e.TRACE_INIT("Grammar Resolving",function(){i=l.resolveGrammar({rules:o.values(e.gastProductionsCache)}),e.definitionErrors.push.apply(e.definitionErrors,i)}),e.TRACE_INIT("Grammar Validations",function(){if(o.isEmpty(i)&&!1===e.skipValidations){var t=l.validateGrammar({rules:o.values(e.gastProductionsCache),maxLookahead:e.maxLookahead,tokenTypes:o.values(e.tokensMap),ignoredIssues:e.ignoredIssues,errMsgProvider:u.defaultGrammarValidatorErrorProvider,grammarName:r});e.definitionErrors.push.apply(e.definitionErrors,t)}}),o.isEmpty(e.definitionErrors)&&(e.recoveryEnabled&&e.TRACE_INIT("computeAllProdsFollows",function(){var t=a.computeAllProdsFollows(o.values(e.gastProductionsCache));e.resyncFollows=t}),e.TRACE_INIT("ComputeLookaheadFunctions",function(){e.preComputeLookaheadFunctions(o.values(e.gastProductionsCache))})),e.TRACE_INIT("expandAllNestedRuleNames",function(){var t=c.expandAllNestedRuleNames(o.values(e.gastProductionsCache),e.fullRuleNameToShort);e.allRuleNames=t.allRuleNames}),!t.DEFER_DEFINITION_ERRORS_HANDLING&&!o.isEmpty(e.definitionErrors))throw n=o.map(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}();e.Parser=A,o.applyMixins(A,[p.Recoverable,h.LooksAhead,f.TreeBuilder,d.LexerAdapter,E.RecognizerEngine,m.RecognizerApi,T.ErrorHandler,y.ContentAssist,v.GastRecorder,R.PerformanceTracer]);var _=function(t){function n(n,r){void 0===r&&(r=e.DEFAULT_PARSER_CONFIG);var i=o.cloneObj(r);return i.outputCst=!0,t.call(this,n,i)||this}return i(n,t),n}(A);e.CstParser=_;var g=function(t){function n(n,r){void 0===r&&(r=e.DEFAULT_PARSER_CONFIG);var i=o.cloneObj(r);return i.outputCst=!1,t.call(this,n,i)||this}return i(n,t),n}(A);e.EmbeddedActionsParser=g},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(0),i=n(9),o=n(5);function a(t){return r.isString(t.LABEL)&&""!==t.LABEL}e.tokenLabel=function(t){return a(t)?t.LABEL:t.name},e.tokenName=function(t){return t.name},e.hasTokenLabel=a;var s="parent",c="categories",u="label",l="group",p="push_mode",h="pop_mode",f="longer_alt",d="line_breaks",m="start_chars_hint";function E(t){return function(t){var e=t.pattern,n={};n.name=t.name,r.isUndefined(e)||(n.PATTERN=e);if(r.has(t,s))throw"The parent property is no longer supported.\nSee: https://github.com/SAP/chevrotain/issues/564#issuecomment-349062346 for details.";r.has(t,c)&&(n.CATEGORIES=t[c]);o.augmentTokenTypes([n]),r.has(t,u)&&(n.LABEL=t[u]);r.has(t,l)&&(n.GROUP=t[l]);r.has(t,h)&&(n.POP_MODE=t[h]);r.has(t,p)&&(n.PUSH_MODE=t[p]);r.has(t,f)&&(n.LONGER_ALT=t[f]);r.has(t,d)&&(n.LINE_BREAKS=t[d]);r.has(t,m)&&(n.START_CHARS_HINT=t[m]);return n}(t)}e.createToken=E,e.EOF=E({name:"EOF",pattern:i.Lexer.NA}),o.augmentTokenTypes([e.EOF]),e.createTokenInstance=function(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}},e.tokenMatcher=function(t,e){return o.tokenStructuredMatcher(t,e)}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),i=function(){function t(){}return t.prototype.visit=function(t){var e=t;switch(e.constructor){case r.NonTerminal:return this.visitNonTerminal(e);case r.Flat:return this.visitFlat(e);case r.Option:return this.visitOption(e);case r.RepetitionMandatory:return this.visitRepetitionMandatory(e);case r.RepetitionMandatoryWithSeparator:return this.visitRepetitionMandatoryWithSeparator(e);case r.RepetitionWithSeparator:return this.visitRepetitionWithSeparator(e);case r.Repetition:return this.visitRepetition(e);case r.Alternation:return this.visitAlternation(e);case r.Terminal:return this.visitTerminal(e);case r.Rule:return this.visitRule(e);default:throw Error("non exhaustive match")}},t.prototype.visitNonTerminal=function(t){},t.prototype.visitFlat=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}();e.GAstVisitor=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(0);function i(t){for(var e=r.cloneArr(t),n=t,i=!0;i;){n=r.compact(r.flatten(r.map(n,function(t){return t.CATEGORIES})));var o=r.difference(n,e);e=e.concat(o),r.isEmpty(o)?i=!1:n=o}return e}function o(t){r.forEach(t,function(t){u(t)||(e.tokenIdxToClass[e.tokenShortNameIdx]=t,t.tokenTypeIdx=e.tokenShortNameIdx++),l(t)&&!r.isArray(t.CATEGORIES)&&(t.CATEGORIES=[t.CATEGORIES]),l(t)||(t.CATEGORIES=[]),p(t)||(t.categoryMatches=[]),h(t)||(t.categoryMatchesMap={})})}function a(t){r.forEach(t,function(t){t.categoryMatches=[],r.forEach(t.categoryMatchesMap,function(n,r){t.categoryMatches.push(e.tokenIdxToClass[r].tokenTypeIdx)})})}function s(t){r.forEach(t,function(t){c([],t)})}function c(t,e){r.forEach(t,function(t){e.categoryMatchesMap[t.tokenTypeIdx]=!0}),r.forEach(e.CATEGORIES,function(n){var i=t.concat(e);r.contains(i,n)||c(i,n)})}function u(t){return r.has(t,"tokenTypeIdx")}function l(t){return r.has(t,"CATEGORIES")}function p(t){return r.has(t,"categoryMatches")}function h(t){return r.has(t,"categoryMatchesMap")}e.tokenStructuredMatcher=function(t,e){var n=t.tokenTypeIdx;return n===e.tokenTypeIdx||!0===e.isParent&&!0===e.categoryMatchesMap[n]},e.tokenStructuredMatcherNoCategories=function(t,e){return t.tokenTypeIdx===e.tokenTypeIdx},e.tokenShortNameIdx=1,e.tokenIdxToClass={},e.augmentTokenTypes=function(t){var e=i(t);o(e),s(e),a(e),r.forEach(e,function(t){t.isParent=t.categoryMatches.length>0})},e.expandCategories=i,e.assignTokenDefaultProps=o,e.assignCategoriesTokensProp=a,e.assignCategoriesMapProp=s,e.singleAssignCategoriesToksMap=c,e.hasShortKeyProperty=u,e.hasCategoriesProperty=l,e.hasExtendingTokensTypesProperty=p,e.hasExtendingTokensTypesMapProperty=h,e.isTokenType=function(t){return r.has(t,"tokenTypeIdx")}},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=function(t,e){return(r=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}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(0),a=n(1),s=n(4);e.isSequenceProd=function(t){return t instanceof a.Flat||t instanceof a.Option||t instanceof a.Repetition||t instanceof a.RepetitionMandatory||t instanceof a.RepetitionMandatoryWithSeparator||t instanceof a.RepetitionWithSeparator||t instanceof a.Terminal||t instanceof a.Rule},e.isOptionalProd=function t(e,n){return void 0===n&&(n=[]),!!(e instanceof a.Option||e instanceof a.Repetition||e instanceof a.RepetitionWithSeparator)||(e instanceof a.Alternation?o.some(e.definition,function(e){return t(e,n)}):!(e instanceof a.NonTerminal&&o.contains(n,e))&&e instanceof a.AbstractProduction&&(e instanceof a.NonTerminal&&n.push(e),o.every(e.definition,function(e){return t(e,n)})))},e.isBranchingProd=function(t){return t instanceof a.Alternation},e.getProductionDslName=function(t){if(t instanceof a.NonTerminal)return"SUBRULE";if(t instanceof a.Option)return"OPTION";if(t instanceof a.Alternation)return"OR";if(t instanceof a.RepetitionMandatory)return"AT_LEAST_ONE";if(t instanceof a.RepetitionMandatoryWithSeparator)return"AT_LEAST_ONE_SEP";if(t instanceof a.RepetitionWithSeparator)return"MANY_SEP";if(t instanceof a.Repetition)return"MANY";if(t instanceof a.Terminal)return"CONSUME";throw Error("non exhaustive match")};var c=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 i(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";o.has(this.dslMethods,e)||(this.dslMethods[e]=[]),this.dslMethods[e].push(t)},e.prototype.visitNonTerminal=function(t){var e=t.nonTerminalName+this.separator+"Terminal";o.has(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}(s.GAstVisitor);e.DslMethodsCollectorVisitor=c;var u=new c;e.collectMethods=function(t){u.reset(),t.accept(u);var e=u.dslMethods;return u.reset(),e}},function(t,e,n){"use strict";function r(t,e,n){return n|e|t}Object.defineProperty(e,"__esModule",{value:!0}),e.BITS_FOR_METHOD_TYPE=4,e.BITS_FOR_OCCURRENCE_IDX=8,e.BITS_FOR_RULE_IDX=12,e.BITS_FOR_ALT_IDX=8,e.OR_IDX=1< 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),i.isArray(t)?((a={modes:{}}).modes[r.DEFAULT_MODE]=i.cloneArr(t),a[r.DEFAULT_MODE]=r.DEFAULT_MODE):(u=!1,a=i.cloneObj(t))}),!1===n.config.skipValidations&&(n.TRACE_INIT("performRuntimeChecks",function(){n.lexerDefinitionErrors=n.lexerDefinitionErrors.concat(r.performRuntimeChecks(a,n.trackStartLines,n.config.lineTerminatorCharacters))}),n.TRACE_INIT("performWarningRuntimeChecks",function(){n.lexerDefinitionWarning=n.lexerDefinitionWarning.concat(r.performWarningRuntimeChecks(a,n.trackStartLines,n.config.lineTerminatorCharacters))})),a.modes=a.modes?a.modes:{},i.forEach(a.modes,function(t,e){a.modes[e]=i.reject(t,function(t){return i.isUndefined(t)})});var l=i.keys(a.modes);if(i.forEach(a.modes,function(t,a){n.TRACE_INIT("Mode: <"+a+"> processing",function(){var s;(n.modes.push(a),!1===n.config.skipValidations&&n.TRACE_INIT("validatePatterns",function(){n.lexerDefinitionErrors=n.lexerDefinitionErrors.concat(r.validatePatterns(t,l))}),i.isEmpty(n.lexerDefinitionErrors))&&(o.augmentTokenTypes(t),n.TRACE_INIT("analyzeTokenTypes",function(){s=r.analyzeTokenTypes(t,{lineTerminatorCharacters:n.config.lineTerminatorCharacters,positionTracking:e.positionTracking,ensureOptimizations:e.ensureOptimizations,safeMode:e.safeMode,tracer:n.TRACE_INIT.bind(n)})}),n.patternIdxToConfig[a]=s.patternIdxToConfig,n.charCodeToPatternIdxToConfig[a]=s.charCodeToPatternIdxToConfig,n.emptyGroups=i.merge(n.emptyGroups,s.emptyGroups),n.hasCustom=s.hasCustom||n.hasCustom,n.canModeBeOptimized[a]=s.canBeOptimized)})}),n.defaultMode=a.defaultMode,!i.isEmpty(n.lexerDefinitionErrors)&&!n.config.deferDefinitionErrorsHandling){var p=i.map(n.lexerDefinitionErrors,function(t){return t.message}).join("-----------------------\n");throw new Error("Errors detected in definition of Lexer:\n"+p)}i.forEach(n.lexerDefinitionWarning,function(t){i.PRINT_WARNING(t.message)}),n.TRACE_INIT("Choosing sub-methods implementations",function(){if(r.SUPPORT_STICKY?(n.chopInput=i.IDENTITY,n.match=n.matchWithTest):(n.updateLastIndex=i.NOOP,n.match=n.matchWithExec),u&&(n.handleModes=i.NOOP),!1===n.trackStartLines&&(n.computeNewColumn=i.IDENTITY),!1===n.trackEndLines&&(n.updateTokenEndLineColumnLocation=i.NOOP),/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=i.reduce(n.canModeBeOptimized,function(t,e,n){return!1===e&&t.push(n),t},[]);if(e.ensureOptimizations&&!i.isEmpty(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(){s.clearRegExpParserCache()}),n.TRACE_INIT("toFastProperties",function(){i.toFastProperties(n)})})}return t.prototype.tokenize=function(t,e){if(void 0===e&&(e=this.defaultMode),!i.isEmpty(this.lexerDefinitionErrors)){var n=i.map(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,o,a,s,c,u,l,p,h,f,d,m,E,T,y=this,v=t,R=v.length,A=0,_=0,g=this.hasCustom?0:Math.floor(t.length/10),N=new Array(g),I=[],O=this.trackStartLines?1:void 0,S=this.trackStartLines?1:void 0,L=r.cloneEmptyGroups(this.emptyGroups),P=this.trackStartLines,C=this.config.lineTerminatorsPattern,k=0,x=[],M=[],F=[],b=[];Object.freeze(b);var D=void 0;function U(){return x}function w(t){var e=r.charCodeToOptimizedIndex(t),n=M[e];return void 0===n?b:n}var G,K=function(t){if(1===F.length&&void 0===t.tokenType.PUSH_MODE){var e=y.config.errorMessageProvider.buildUnableToPopLexerModeMessage(t);I.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=i.last(F);x=y.patternIdxToConfig[n],M=y.charCodeToPatternIdxToConfig[n],k=x.length;var r=y.canModeBeOptimized[n]&&!1===y.config.safeMode;D=M&&r?w:U}};function B(t){F.push(t),M=this.charCodeToPatternIdxToConfig[t],x=this.patternIdxToConfig[t],k=x.length,k=x.length;var e=this.canModeBeOptimized[t]&&!1===this.config.safeMode;D=M&&e?w:U}for(B.call(this,e);Ac.length&&(c=a,u=l,G=X)}break}}if(null!==c){if(p=c.length,void 0!==(h=G.group)&&(f=G.tokenTypeIdx,d=this.createTokenInstance(c,A,f,G.tokenType,O,S,p),this.handlePayload(d,u),!1===h?_=this.addToken(N,_,d):L[h].push(d)),t=this.chopInput(t,p),A+=p,S=this.computeNewColumn(S,p),!0===P&&!0===G.canLineTerminator){var H=0,q=void 0,$=void 0;C.lastIndex=0;do{!0===(q=C.test(c))&&($=C.lastIndex-1,H++)}while(!0===q);0!==H&&(O+=H,S=p-$,this.updateTokenEndLineColumnLocation(d,h,$,H,O,S,p))}this.handleModes(G,K,B,d)}else{for(var Z=A,Q=O,J=S,tt=!1;!tt&&A");var r=i.timer(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}();e.Lexer=u},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(3),i=n(0),o=n(0),a=n(1),s=n(6),c=n(11);e.defaultParserErrorProvider={buildMismatchTokenMessage:function(t){var e=t.expected,n=t.actual;t.previous,t.ruleName;return"Expecting "+(r.hasTokenLabel(e)?"--\x3e "+r.tokenLabel(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,i=(t.previous,t.customUserDescription),a=(t.ruleName,"\nbut found: '"+o.first(n).image+"'");if(i)return"Expecting: "+i+a;var s=o.reduce(e,function(t,e){return t.concat(e)},[]),c=o.map(s,function(t){return"["+o.map(t,function(t){return r.tokenLabel(t)}).join(", ")+"]"});return"Expecting: "+("one of these possible Token sequences:\n"+o.map(c,function(t,e){return" "+(e+1)+". "+t}).join("\n"))+a},buildEarlyExitMessage:function(t){var e=t.expectedIterationPaths,n=t.actual,i=t.customUserDescription,a=(t.ruleName,"\nbut found: '"+o.first(n).image+"'");return i?"Expecting: "+i+a:"Expecting: "+("expecting at least one iteration which starts with one of these possible Token sequences::\n <"+o.map(e,function(t){return"["+o.map(t,function(t){return r.tokenLabel(t)}).join(",")+"]"}).join(" ,")+">")+a}},Object.freeze(e.defaultParserErrorProvider),e.defaultGrammarResolverErrorProvider={buildRuleNotFoundError:function(t,e){return"Invalid grammar, reference to a rule which is not defined: ->"+e.nonTerminalName+"<-\ninside top level rule: ->"+t.name+"<-"}},e.defaultGrammarValidatorErrorProvider={buildDuplicateFoundError:function(t,e){var n,r=t.name,i=o.first(e),c=i.idx,u=s.getProductionDslName(i),l=(n=i)instanceof a.Terminal?n.terminalType.name:n instanceof a.NonTerminal?n.nonTerminalName:"",p="->"+u+(c>0?c:"")+"<- "+(l?"with argument: ->"+l+"<-":"")+"\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 p=(p=p.replace(/[ \t]+/g," ")).replace(/\s\s+/g,"\n")},buildInvalidNestedRuleNameError:function(t,e){return"Invalid nested rule name: ->"+e.name+"<- inside rule: ->"+t.name+"<-\nit must match the pattern: ->"+c.validNestedRuleName.toString()+"<-.\nNote that this means a nested rule name must start with the '$'(dollar) sign."},buildDuplicateNestedRuleNameError:function(t,e){return"Duplicate nested rule name: ->"+o.first(e).name+"<- inside rule: ->"+t.name+"<-\nA nested name must be unique in the scope of a top level grammar rule."},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=o.map(t.prefixPath,function(t){return r.tokenLabel(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=o.map(t.prefixPath,function(t){return r.tokenLabel(t)}).join(", "),n=0===t.alternation.idx?"":t.alternation.idx,i="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 i+="See: https://sap.github.io/chevrotain/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\nFor Further details."},buildEmptyRepetitionError:function(t){var e=s.getProductionDslName(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.map(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 a.Rule?t.topLevelRule.name:t.topLevelRule)+"<- is already defined in the grammar: ->"+t.grammarName+"<-"}}},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=function(t,e){return(r=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}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(0),a=n(0),s=n(2),c=n(6),u=n(12),l=n(17),p=n(13),h=n(1),f=n(4);function d(t){return c.getProductionDslName(t)+"_#_"+t.idx+"_#_"+m(t)}function m(t){return t instanceof h.Terminal?t.terminalType.name:t instanceof h.NonTerminal?t.nonTerminalName:""}e.validateGrammar=function(t,e,n,r,i,u){var p=o.map(t,function(t){return function(t,e){var n=new E;t.accept(n);var r=n.allProductions,i=o.groupBy(r,d),a=o.pick(i,function(t){return t.length>1});return o.map(o.values(a),function(n){var r=o.first(n),i=e.buildDuplicateFoundError(t,n),a=c.getProductionDslName(r),u={message:i,type:s.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,ruleName:t.name,dslName:a,occurrence:r.idx},l=m(r);return l&&(u.parameter=l),u})}(t,i)}),h=o.map(t,function(t){return A(t,t,i)}),f=[],_=[],g=[];a.every(h,a.isEmpty)&&(f=a.map(t,function(t){return N(t,i)}),_=a.map(t,function(t){return I(t,e,r,i)}),g=L(t,e,i));var O=function(t,e,n){var r=[],i=a.map(e,function(t){return t.name});return a.forEach(t,function(t){var e=t.name;if(a.contains(i,e)){var o=n.buildNamespaceConflictError(t);r.push({message:o,type:s.ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:e})}}),r}(t,n,i),P=o.map(n,function(t){return v(t,i)}),C=function(t,e){var n=[];return a.forEach(t,function(t){var r=new l.NamedDSLMethodsCollectorVisitor("");t.accept(r);var i=a.map(r.result,function(t){return t.orgProd});n.push(a.map(i,function(n){return y(t,n,e)}))}),a.flatten(n)}(t,i),k=function(t,e){var n=[];return a.forEach(t,function(t){var r=new l.NamedDSLMethodsCollectorVisitor("");t.accept(r);var i=a.groupBy(r.result,function(t){return t.name}),o=a.pick(i,function(t){return t.length>1});a.forEach(a.values(o),function(r){var i=a.map(r,function(t){return t.orgProd}),o=e.buildDuplicateNestedRuleNameError(t,i);n.push({message:o,type:s.ParserDefinitionErrorType.DUPLICATE_NESTED_NAME,ruleName:t.name})})}),n}(t,i),x=a.map(t,function(t){return S(t,i)}),M=a.map(t,function(t){return T(t,i)}),F=a.map(t,function(e){return R(e,t,u,i)});return o.flatten(p.concat(P,C,k,g,h,f,_,O,x,M,F))},e.identifyProductionForDuplicates=d;var E=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.allProductions=[],e}return i(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}(f.GAstVisitor);function T(t,n){var r=[],i=t.name;return i.match(e.validTermsPattern)||r.push({message:n.buildInvalidRuleNameError({topLevelRule:t,expectedPattern:e.validTermsPattern}),type:s.ParserDefinitionErrorType.INVALID_RULE_NAME,ruleName:i}),r}function y(t,n,r){var i,o=[];return n.name.match(e.validNestedRuleName)||(i=r.buildInvalidNestedRuleNameError(t,n),o.push({message:i,type:s.ParserDefinitionErrorType.INVALID_NESTED_RULE_NAME,ruleName:t.name})),o}function v(t,n){var r=[];return t.name.match(e.validTermsPattern)||r.push({message:n.buildTokenNameError({tokenType:t,expectedPattern:e.validTermsPattern}),type:s.ParserDefinitionErrorType.INVALID_TOKEN_NAME}),r}function R(t,e,n,r){var i=[];if(a.reduce(e,function(e,n){return n.name===t.name?e+1:e},0)>1){var o=r.buildDuplicateRuleNameError({topLevelRule:t,grammarName:n});i.push({message:o,type:s.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:t.name})}return i}function A(t,e,n,r){void 0===r&&(r=[]);var i=[],a=_(e.definition);if(o.isEmpty(a))return[];var c=t.name;o.contains(a,t)&&i.push({message:n.buildLeftRecursionError({topLevelRule:t,leftRecursionPath:r}),type:s.ParserDefinitionErrorType.LEFT_RECURSION,ruleName:c});var u=o.difference(a,r.concat([t])),l=o.map(u,function(e){var i=o.cloneArr(r);return i.push(e),A(t,e,n,i)});return i.concat(o.flatten(l))}function _(t){var e=[];if(o.isEmpty(t))return e;var n=o.first(t);if(n instanceof h.NonTerminal)e.push(n.referencedRule);else if(n instanceof h.Flat||n instanceof h.Option||n instanceof h.RepetitionMandatory||n instanceof h.RepetitionMandatoryWithSeparator||n instanceof h.RepetitionWithSeparator||n instanceof h.Repetition)e=e.concat(_(n.definition));else if(n instanceof h.Alternation)e=o.flatten(o.map(n.definition,function(t){return _(t.definition)}));else if(!(n instanceof h.Terminal))throw Error("non exhaustive match");var r=c.isOptionalProd(n),i=t.length>1;if(r&&i){var a=o.drop(t);return e.concat(_(a))}return e}e.OccurrenceValidationCollector=E,e.validTermsPattern=/^[a-zA-Z_]\w*$/,e.validNestedRuleName=new RegExp(e.validTermsPattern.source.replace("^","^\\$")),e.validateRuleName=T,e.validateNestedRuleName=y,e.validateTokenName=v,e.validateRuleDoesNotAlreadyExist=R,e.validateRuleIsOverridden=function(t,e,n){var r,i=[];return o.contains(e,t)||(r="Invalid rule override, rule: ->"+t+"<- cannot be overridden in the grammar: ->"+n+"<-as it is not defined in any of the super grammars ",i.push({message:r,type:s.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,ruleName:t})),i},e.validateNoLeftRecursion=A,e.getFirstNoneTerminal=_;var g=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.alternations=[],e}return i(e,t),e.prototype.visitAlternation=function(t){this.alternations.push(t)},e}(f.GAstVisitor);function N(t,e){var n=new g;t.accept(n);var r=n.alternations;return o.reduce(r,function(n,r){var i=o.dropRight(r.definition),a=o.map(i,function(n,i){var a=p.nextPossibleTokensAfter([n],[],null,1);return o.isEmpty(a)?{message:e.buildEmptyAlternationError({topLevelRule:t,alternation:r,emptyChoiceIdx:i}),type:s.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,ruleName:t.name,occurrence:r.idx,alternative:i+1}:null});return n.concat(o.compact(a))},[])}function I(t,e,n,r){var i=new g;t.accept(i);var l=i.alternations,p=n[t.name];return p&&(l=a.reject(l,function(t){return p[c.getProductionDslName(t)+(0===t.idx?"":t.idx)]})),l=a.reject(l,function(t){return!0===t.ignoreAmbiguities}),o.reduce(l,function(n,i){var c=i.idx,l=i.maxLookahead||e,p=u.getLookaheadPathsForOr(c,t,l,i),h=function(t,e,n,r){var i=[],c=a.reduce(t,function(n,r,o){return!0===e.definition[o].ignoreAmbiguities?n:(a.forEach(r,function(r){var s=[o];a.forEach(t,function(t,n){o!==n&&u.containsPath(t,r)&&!0!==e.definition[n].ignoreAmbiguities&&s.push(n)}),s.length>1&&!u.containsPath(i,r)&&(i.push(r),n.push({alts:s,path:r}))}),n)},[]);return o.map(c,function(t){var i=a.map(t.alts,function(t){return t+1}),o=r.buildAlternationAmbiguityError({topLevelRule:n,alternation:e,ambiguityIndices:i,prefixPath:t.path});return{message:o,type:s.ParserDefinitionErrorType.AMBIGUOUS_ALTS,ruleName:n.name,occurrence:e.idx,alternatives:[t.alts]}})}(p,i,t,r),f=P(p,i,t,r);return n.concat(h,f)},[])}e.validateEmptyOrAlternative=N,e.validateAmbiguousAlternationAlternatives=I;var O=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.allProductions=[],e}return i(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}(f.GAstVisitor);function S(t,e){var n=new g;t.accept(n);var r=n.alternations;return o.reduce(r,function(n,r){return r.definition.length>255&&n.push({message:e.buildTooManyAlternativesError({topLevelRule:t,alternation:r}),type:s.ParserDefinitionErrorType.TOO_MANY_ALTS,ruleName:t.name,occurrence:r.idx}),n},[])}function L(t,e,n){var r=[];return a.forEach(t,function(t){var i=new O;t.accept(i);var o=i.allProductions;a.forEach(o,function(i){var o=u.getProdType(i),c=i.maxLookahead||e,l=i.idx,p=u.getLookaheadPathsForOptionalProd(l,t,o,c)[0];if(a.isEmpty(a.flatten(p))){var h=n.buildEmptyRepetitionError({topLevelRule:t,repetition:i});r.push({message:h,type:s.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,ruleName:t.name})}})}),r}function P(t,e,n,r){var i=[],o=a.reduce(t,function(t,e,n){var r=a.map(e,function(t){return{idx:n,path:t}});return t.concat(r)},[]);return a.forEach(o,function(t){if(!0!==e.definition[t.idx].ignoreAmbiguities){var c=t.idx,l=t.path,p=a.findAll(o,function(t){return!0!==e.definition[t.idx].ignoreAmbiguities&&t.idx=0;L--){var P={idx:d,def:y.definition[L].definition.concat(a.drop(f)),ruleStack:m,occurrenceStack:T};p.push(P),p.push("EXIT_ALTERNATIVE")}else if(y instanceof c.Flat)p.push({idx:d,def:y.definition.concat(a.drop(f)),ruleStack:m,occurrenceStack:T});else{if(!(y instanceof c.Rule))throw Error("non exhaustive match");p.push(E(y,d,m,T))}}}else o&&a.last(p).idx<=u&&p.pop()}return l}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(0),i=n(1),o=function(){function t(){}return t.prototype.walk=function(t,e){var n=this;void 0===e&&(e=[]),r.forEach(t.definition,function(o,a){var s=r.drop(t.definition,a+1);if(o instanceof i.NonTerminal)n.walkProdRef(o,s,e);else if(o instanceof i.Terminal)n.walkTerminal(o,s,e);else if(o instanceof i.Flat)n.walkFlat(o,s,e);else if(o instanceof i.Option)n.walkOption(o,s,e);else if(o instanceof i.RepetitionMandatory)n.walkAtLeastOne(o,s,e);else if(o instanceof i.RepetitionMandatoryWithSeparator)n.walkAtLeastOneSep(o,s,e);else if(o instanceof i.RepetitionWithSeparator)n.walkManySep(o,s,e);else if(o instanceof i.Repetition)n.walkMany(o,s,e);else{if(!(o instanceof i.Alternation))throw Error("non exhaustive match");n.walkOr(o,s,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 i.Option({definition:t.definition})].concat(e,n);this.walk(t,r)},t.prototype.walkAtLeastOneSep=function(t,e,n){var r=a(t,e,n);this.walk(t,r)},t.prototype.walkMany=function(t,e,n){var r=[new i.Option({definition:t.definition})].concat(e,n);this.walk(t,r)},t.prototype.walkManySep=function(t,e,n){var r=a(t,e,n);this.walk(t,r)},t.prototype.walkOr=function(t,e,n){var o=this,a=e.concat(n);r.forEach(t.definition,function(t){var e=new i.Flat({definition:[t]});o.walk(e,a)})},t}();function a(t,e,n){return[new i.Option({definition:[new i.Terminal({terminalType:t.separator})].concat(t.definition)})].concat(e,n)}e.RestWalker=o},function(t,e,n){var r,i,o;"undefined"!=typeof self&&self,i=[],void 0===(o="function"==typeof(r=function(){function t(){}t.prototype.saveState=function(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}},t.prototype.restoreState=function(t){this.idx=t.idx,this.input=t.input,this.groupIdx=t.groupIdx},t.prototype.pattern=function(t){this.idx=0,this.input=t,this.groupIdx=0,this.consumeChar("/");var e=this.disjunction();this.consumeChar("/");for(var n={type:"Flags",global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};this.isRegExpFlag();)switch(this.popChar()){case"g":s(n,"global");break;case"i":s(n,"ignoreCase");break;case"m":s(n,"multiLine");break;case"u":s(n,"unicode");break;case"y":s(n,"sticky")}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:n,value:e}},t.prototype.disjunction=function(){var t=[];for(t.push(this.alternative());"|"===this.peekChar();)this.consumeChar("|"),t.push(this.alternative());return{type:"Disjunction",value:t}},t.prototype.alternative=function(){for(var t=[];this.isTerm();)t.push(this.term());return{type:"Alternative",value:t}},t.prototype.term=function(){return this.isAssertion()?this.assertion():this.atom()},t.prototype.assertion=function(){switch(this.popChar()){case"^":return{type:"StartAnchor"};case"$":return{type:"EndAnchor"};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary"};case"B":return{type:"NonWordBoundary"}}throw Error("Invalid Assertion Escape");case"(":var t;switch(this.consumeChar("?"),this.popChar()){case"=":t="Lookahead";break;case"!":t="NegativeLookahead"}c(t);var e=this.disjunction();return this.consumeChar(")"),{type:t,value:e}}!function(){throw Error("Internal Error - Should never get here!")}()},t.prototype.quantifier=function(t){var e;switch(this.popChar()){case"*":e={atLeast:0,atMost:1/0};break;case"+":e={atLeast:1,atMost:1/0};break;case"?":e={atLeast:0,atMost:1};break;case"{":var n=this.integerIncludingZero();switch(this.popChar()){case"}":e={atLeast:n,atMost:n};break;case",":var r;this.isDigit()?(r=this.integerIncludingZero(),e={atLeast:n,atMost:r}):e={atLeast:n,atMost:1/0},this.consumeChar("}")}if(!0===t&&void 0===e)return;c(e)}if(!0!==t||void 0!==e)return c(e),"?"===this.peekChar(0)?(this.consumeChar("?"),e.greedy=!1):e.greedy=!0,e.type="Quantifier",e},t.prototype.atom=function(){var t;switch(this.peekChar()){case".":t=this.dotAll();break;case"\\":t=this.atomEscape();break;case"[":t=this.characterClass();break;case"(":t=this.group()}return void 0===t&&this.isPatternCharacter()&&(t=this.patternCharacter()),c(t),this.isQuantifier()&&(t.quantifier=this.quantifier()),t},t.prototype.dotAll=function(){return this.consumeChar("."),{type:"Set",complement:!0,value:[o("\n"),o("\r"),o("\u2028"),o("\u2029")]}},t.prototype.atomEscape=function(){switch(this.consumeChar("\\"),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()}},t.prototype.decimalEscapeAtom=function(){var t=this.positiveInteger();return{type:"GroupBackReference",value:t}},t.prototype.characterClassEscape=function(){var t,e=!1;switch(this.popChar()){case"d":t=u;break;case"D":t=u,e=!0;break;case"s":t=p;break;case"S":t=p,e=!0;break;case"w":t=l;break;case"W":t=l,e=!0}return c(t),{type:"Set",value:t,complement:e}},t.prototype.controlEscapeAtom=function(){var t;switch(this.popChar()){case"f":t=o("\f");break;case"n":t=o("\n");break;case"r":t=o("\r");break;case"t":t=o("\t");break;case"v":t=o("\v")}return c(t),{type:"Character",value:t}},t.prototype.controlLetterEscapeAtom=function(){this.consumeChar("c");var t=this.popChar();if(!1===/[a-zA-Z]/.test(t))throw Error("Invalid ");var e=t.toUpperCase().charCodeAt(0)-64;return{type:"Character",value:e}},t.prototype.nulCharacterAtom=function(){return this.consumeChar("0"),{type:"Character",value:o("\0")}},t.prototype.hexEscapeSequenceAtom=function(){return this.consumeChar("x"),this.parseHexDigits(2)},t.prototype.regExpUnicodeEscapeSequenceAtom=function(){return this.consumeChar("u"),this.parseHexDigits(4)},t.prototype.identityEscapeAtom=function(){var t=this.popChar();return{type:"Character",value:o(t)}},t.prototype.classPatternCharacterAtom=function(){switch(this.peekChar()){case"\n":case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:var t=this.popChar();return{type:"Character",value:o(t)}}},t.prototype.characterClass=function(){var t=[],e=!1;for(this.consumeChar("["),"^"===this.peekChar(0)&&(this.consumeChar("^"),e=!0);this.isClassAtom();){var n=this.classAtom(),r="Character"===n.type;if(r&&this.isRangeDash()){this.consumeChar("-");var i=this.classAtom(),s="Character"===i.type;if(s){if(i.value=this.input.length)throw Error("Unexpected end of input");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 l=[o("_")].concat(u);for(e=o("a");e<=o("z");e++)l.push(e);for(e=o("A");e<=o("Z");e++)l.push(e);var p=[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.4.0"}})?r.apply(e,i):r)||(t.exports=o)},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(15),i={},o=new r.RegExpParser;e.getRegExpAst=function(t){var e=t.toString();if(i.hasOwnProperty(e))return i[e];var n=o.pattern(e);return i[e]=n,n},e.clearRegExpParserCache=function(){i={}}},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=function(t,e){return(r=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}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(0),a=n(7),s=n(1),c=n(4);e.setNodeLocationOnlyOffset=function(t,e){!0===isNaN(t.startOffset)?(t.startOffset=e.startOffset,t.endOffset=e.endOffset):t.endOffset1;o.forEach(t.definition,function(r,i){if(!o.isUndefined(r.name)){var c=r.definition;c=n?[new s.Option({definition:r.definition})]:r.definition;var u=a.getKeyForAltIndex(e.ruleIdx,a.OR_IDX,t.idx,i);e.result.push({def:c,key:u,name:r.name,orgProd:r})}})},e}(c.GAstVisitor);e.NamedDSLMethodsCollectorVisitor=u,e.expandAllNestedRuleNames=function(t,e){var n={allRuleNames:[]};return o.forEach(t,function(t){var r=e[t.name];n.allRuleNames.push(t.name);var i=new u(r);t.accept(i),o.forEach(i.result,function(e){e.def,e.key;var r=e.name;n.allRuleNames.push(t.name+r)})}),n}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(19);e.VERSION=r.VERSION;var i=n(2);e.Parser=i.Parser,e.CstParser=i.CstParser,e.EmbeddedActionsParser=i.EmbeddedActionsParser,e.ParserDefinitionErrorType=i.ParserDefinitionErrorType,e.EMPTY_ALT=i.EMPTY_ALT;var o=n(9);e.Lexer=o.Lexer,e.LexerDefinitionErrorType=o.LexerDefinitionErrorType;var a=n(3);e.createToken=a.createToken,e.createTokenInstance=a.createTokenInstance,e.EOF=a.EOF,e.tokenLabel=a.tokenLabel,e.tokenMatcher=a.tokenMatcher,e.tokenName=a.tokenName;var s=n(10);e.defaultGrammarResolverErrorProvider=s.defaultGrammarResolverErrorProvider,e.defaultGrammarValidatorErrorProvider=s.defaultGrammarValidatorErrorProvider,e.defaultParserErrorProvider=s.defaultParserErrorProvider;var c=n(8);e.EarlyExitException=c.EarlyExitException,e.isRecognitionException=c.isRecognitionException,e.MismatchedTokenException=c.MismatchedTokenException,e.NotAllInputParsedException=c.NotAllInputParsedException,e.NoViableAltException=c.NoViableAltException;var u=n(21);e.defaultLexerErrorProvider=u.defaultLexerErrorProvider;var l=n(1);e.Alternation=l.Alternation,e.Flat=l.Flat,e.NonTerminal=l.NonTerminal,e.Option=l.Option,e.Repetition=l.Repetition,e.RepetitionMandatory=l.RepetitionMandatory,e.RepetitionMandatoryWithSeparator=l.RepetitionMandatoryWithSeparator,e.RepetitionWithSeparator=l.RepetitionWithSeparator,e.Rule=l.Rule,e.Terminal=l.Terminal;var p=n(1);e.serializeGrammar=p.serializeGrammar,e.serializeProduction=p.serializeProduction;var h=n(4);e.GAstVisitor=h.GAstVisitor;var f=n(24);e.assignOccurrenceIndices=f.assignOccurrenceIndices,e.resolveGrammar=f.resolveGrammar,e.validateGrammar=f.validateGrammar,e.clearCache=function(){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 d=n(40);e.createSyntaxDiagramsCode=d.createSyntaxDiagramsCode;var m=n(41);e.generateParserFactory=m.generateParserFactory,e.generateParserModule=m.generateParserModule},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.VERSION="6.5.0"},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=function(t,e){return(r=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}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(15),a=n(9),s=n(0),c=n(28),u=n(16),l="PATTERN";function p(t){var e=s.filter(t,function(t){return!s.has(t,l)});return{errors:s.map(e,function(t){return{message:"Token Type: ->"+t.name+"<- missing static 'PATTERN' property",type:a.LexerDefinitionErrorType.MISSING_PATTERN,tokenTypes:[t]}}),valid:s.difference(t,e)}}function h(t){var e=s.filter(t,function(t){var e=t[l];return!(s.isRegExp(e)||s.isFunction(e)||s.has(e,"exec")||s.isString(e))});return{errors:s.map(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:a.LexerDefinitionErrorType.INVALID_PATTERN,tokenTypes:[t]}}),valid:s.difference(t,e)}}e.DEFAULT_MODE="defaultMode",e.MODES="modes",e.SUPPORT_STICKY="boolean"==typeof new RegExp("(?:)").sticky,e.disableSticky=function(){e.SUPPORT_STICKY=!1},e.enableSticky=function(){e.SUPPORT_STICKY=!0},e.analyzeTokenTypes=function(t,n){var r,i=(n=s.defaults(n,{useSticky:e.SUPPORT_STICKY,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r","\n"],tracer:function(t,e){return e()}})).tracer;i("initCharCodeToOptimizedIndexMap",function(){!function(){if(s.isEmpty(x)){x=new Array(65536);for(var t=0;t<65536;t++)x[t]=t>255?255+~~(t/255):t}}()}),i("Reject Lexer.NA",function(){r=s.reject(t,function(t){return t[l]===a.Lexer.NA})});var o,u,p,h,f,d,m,E,T,y,v,R=!1;i("Transform Patterns",function(){R=!1,o=s.map(r,function(t){var e=t[l];if(s.isRegExp(e)){var r=e.source;return 1===r.length&&"^"!==r&&"$"!==r&&"."!==r?r:2!==r.length||"\\"!==r[0]||s.contains(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],r[1])?n.useSticky?N(e):g(e):r[1]}if(s.isFunction(e))return R=!0,{exec:e};if(s.has(e,"exec"))return R=!0,e;if("string"==typeof e){if(1===e.length)return e;var i=e.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),o=new RegExp(i);return n.useSticky?N(o):g(o)}throw Error("non exhaustive match")})}),i("misc mapping",function(){u=s.map(r,function(t){return t.tokenTypeIdx}),p=s.map(r,function(t){var e=t.GROUP;if(e!==a.Lexer.SKIPPED){if(s.isString(e))return e;if(s.isUndefined(e))return!1;throw Error("non exhaustive match")}}),h=s.map(r,function(t){var e=t.LONGER_ALT;if(e)return s.indexOf(r,e)}),f=s.map(r,function(t){return t.PUSH_MODE}),d=s.map(r,function(t){return s.has(t,"POP_MODE")})}),i("Line Terminator Handling",function(){var t=P(n.lineTerminatorCharacters);m=s.map(r,function(t){return!1}),"onlyOffset"!==n.positionTracking&&(m=s.map(r,function(e){return s.has(e,"LINE_BREAKS")?e.LINE_BREAKS:!1===S(e,t)?c.canMatchCharCode(t,e.PATTERN):void 0}))}),i("Misc Mapping #2",function(){E=s.map(r,I),T=s.map(o,O),y=s.reduce(r,function(t,e){var n=e.GROUP;return s.isString(n)&&n!==a.Lexer.SKIPPED&&(t[n]=[]),t},{}),v=s.map(o,function(t,e){return{pattern:o[e],longerAlt:h[e],canLineTerminator:m[e],isCustom:E[e],short:T[e],group:p[e],push:f[e],pop:d[e],tokenTypeIdx:u[e],tokenType:r[e]}})});var A=!0,_=[];return n.safeMode||i("First Char Optimization",function(){_=s.reduce(r,function(t,e,r){if("string"==typeof e.PATTERN){var i=k(e.PATTERN.charCodeAt(0));C(t,i,v[r])}else if(s.isArray(e.START_CHARS_HINT)){var o;s.forEach(e.START_CHARS_HINT,function(e){var n=k("string"==typeof e?e.charCodeAt(0):e);o!==n&&(o=n,C(t,n,v[r]))})}else if(s.isRegExp(e.PATTERN))if(e.PATTERN.unicode)A=!1,n.ensureOptimizations&&s.PRINT_ERROR(c.failedOptimizationPrefixMsg+"\tUnable to analyze < "+e.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 a=c.getOptimizedStartCodesIndices(e.PATTERN,n.ensureOptimizations);s.isEmpty(a)&&(A=!1),s.forEach(a,function(e){C(t,e,v[r])})}else n.ensureOptimizations&&s.PRINT_ERROR(c.failedOptimizationPrefixMsg+"\tTokenType: <"+e.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"),A=!1;return t},[])}),i("ArrayPacking",function(){_=s.packArray(_)}),{emptyGroups:y,patternIdxToConfig:v,charCodeToPatternIdxToConfig:_,hasCustom:R,canBeOptimized:A}},e.validatePatterns=function(t,e){var n=[],r=p(t);n=n.concat(r.errors);var i=h(r.valid),o=i.valid;return n=(n=(n=(n=(n=n.concat(i.errors)).concat(function(t){var e=[],n=s.filter(t,function(t){return s.isRegExp(t[l])});return e=(e=(e=(e=(e=e.concat(d(n))).concat(T(n))).concat(y(n))).concat(v(n))).concat(m(n))}(o))).concat(R(o))).concat(A(o,e))).concat(_(o))},e.findMissingPatterns=p,e.findInvalidPatterns=h;var f=/[^\\][\$]/;function d(t){var e=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.found=!1,e}return i(e,t),e.prototype.visitEndAnchor=function(t){this.found=!0},e}(o.BaseRegExpVisitor),n=s.filter(t,function(t){var n=t[l];try{var r=u.getRegExpAst(n),i=new e;return i.visit(r),i.found}catch(t){return f.test(n.source)}});return s.map(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:a.LexerDefinitionErrorType.EOI_ANCHOR_FOUND,tokenTypes:[t]}})}function m(t){var e=s.filter(t,function(t){return t[l].test("")});return s.map(e,function(t){return{message:"Token Type: ->"+t.name+"<- static 'PATTERN' must not match an empty string",type:a.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,tokenTypes:[t]}})}e.findEndOfInputAnchor=d,e.findEmptyMatchRegExps=m;var E=/[^\\[][\^]|^\^/;function T(t){var e=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.found=!1,e}return i(e,t),e.prototype.visitStartAnchor=function(t){this.found=!0},e}(o.BaseRegExpVisitor),n=s.filter(t,function(t){var n=t[l];try{var r=u.getRegExpAst(n),i=new e;return i.visit(r),i.found}catch(t){return E.test(n.source)}});return s.map(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:a.LexerDefinitionErrorType.SOI_ANCHOR_FOUND,tokenTypes:[t]}})}function y(t){var e=s.filter(t,function(t){var e=t[l];return e instanceof RegExp&&(e.multiline||e.global)});return s.map(e,function(t){return{message:"Token Type: ->"+t.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:a.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[t]}})}function v(t){var e=[],n=s.map(t,function(n){return s.reduce(t,function(t,r){return n.PATTERN.source!==r.PATTERN.source||s.contains(e,r)||r.PATTERN===a.Lexer.NA?t:(e.push(r),t.push(r),t)},[])});n=s.compact(n);var r=s.filter(n,function(t){return t.length>1});return s.map(r,function(t){var e=s.map(t,function(t){return t.name});return{message:"The same RegExp pattern ->"+s.first(t).PATTERN+"<-has been used in all of the following Token Types: "+e.join(", ")+" <-",type:a.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,tokenTypes:t}})}function R(t){var e=s.filter(t,function(t){if(!s.has(t,"GROUP"))return!1;var e=t.GROUP;return e!==a.Lexer.SKIPPED&&e!==a.Lexer.NA&&!s.isString(e)});return s.map(e,function(t){return{message:"Token Type: ->"+t.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:a.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,tokenTypes:[t]}})}function A(t,e){var n=s.filter(t,function(t){return void 0!==t.PUSH_MODE&&!s.contains(e,t.PUSH_MODE)});return s.map(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:a.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[t]}})}function _(t){var e=[],n=s.reduce(t,function(t,e,n){var r,i=e.PATTERN;return i===a.Lexer.NA?t:(s.isString(i)?t.push({str:i,idx:n,tokenType:e}):s.isRegExp(i)&&(r=i,void 0===s.find([".","\\","[","]","|","^","$","(",")","?","*","+","{"],function(t){return-1!==r.source.indexOf(t)}))&&t.push({str:i.source,idx:n,tokenType:e}),t)},[]);return s.forEach(t,function(t,r){s.forEach(n,function(n){var i=n.str,o=n.idx,c=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:u,type:a.LexerDefinitionErrorType.UNREACHABLE_PATTERN,tokenTypes:[t,c]})}})}),e}function g(t){var e=t.ignoreCase?"i":"";return new RegExp("^(?:"+t.source+")",e)}function N(t){var e=t.ignoreCase?"iy":"y";return new RegExp(""+t.source,e)}function I(t){var e=t.PATTERN;if(s.isRegExp(e))return!1;if(s.isFunction(e))return!0;if(s.has(e,"exec"))return!0;if(s.isString(e))return!1;throw Error("non exhaustive match")}function O(t){return!(!s.isString(t)||1!==t.length)&&t.charCodeAt(0)}function S(t,e){if(s.has(t,"LINE_BREAKS"))return!1;if(s.isRegExp(t.PATTERN)){try{c.canMatchCharCode(e,t.PATTERN)}catch(t){return{issue:a.LexerDefinitionErrorType.IDENTIFY_TERMINATOR,errMsg:t.message}}return!1}if(s.isString(t.PATTERN))return!1;if(I(t))return{issue:a.LexerDefinitionErrorType.CUSTOM_LINE_BREAK};throw Error("non exhaustive match")}function L(t,e){if(e.issue===a.LexerDefinitionErrorType.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===a.LexerDefinitionErrorType.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")}function P(t){return s.map(t,function(t){return s.isString(t)&&t.length>0?t.charCodeAt(0):t})}function C(t,e,n){void 0===t[e]?t[e]=[n]:t[e].push(n)}function k(t){return t property in its definition\n",type:a.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),s.has(t,e.MODES)||i.push({message:"A MultiMode Lexer cannot be initialized without a <"+e.MODES+"> property in its definition\n",type:a.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),s.has(t,e.MODES)&&s.has(t,e.DEFAULT_MODE)&&!s.has(t.modes,t.defaultMode)&&i.push({message:"A MultiMode Lexer cannot be initialized with a "+e.DEFAULT_MODE+": <"+t.defaultMode+">which does not exist\n",type:a.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),s.has(t,e.MODES)&&s.forEach(t.modes,function(t,e){s.forEach(t,function(t,n){s.isUndefined(t)&&i.push({message:"A Lexer cannot be initialized using an undefined Token Type. Mode:<"+e+"> at index: <"+n+">\n",type:a.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED})})}),i},e.performWarningRuntimeChecks=function(t,e,n){var r=[],i=!1,o=s.compact(s.flatten(s.mapValues(t.modes,function(t){return t}))),u=s.reject(o,function(t){return t[l]===a.Lexer.NA}),p=P(n);return e&&s.forEach(u,function(t){var e=S(t,p);if(!1!==e){var n={message:L(t,e),type:e.issue,tokenType:t};r.push(n)}else s.has(t,"LINE_BREAKS")?!0===t.LINE_BREAKS&&(i=!0):c.canMatchCharCode(p,t.PATTERN)&&(i=!0)}),e&&!i&&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:a.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS}),r},e.cloneEmptyGroups=function(t){var e={},n=s.keys(t);return s.forEach(n,function(n){var r=t[n];if(!s.isArray(r))throw Error("non exhaustive match");e[n]=[]}),e},e.isCustomPattern=I,e.isShortPattern=O,e.LineTerminatorOptimizedTester={test:function(t){for(var e=t.length,n=this.lastIndex;n"+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,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(0),i=n(1),o=n(6);function a(t){if(t instanceof i.NonTerminal)return a(t.referencedRule);if(t instanceof i.Terminal)return u(t);if(o.isSequenceProd(t))return s(t);if(o.isBranchingProd(t))return c(t);throw Error("non exhaustive match")}function s(t){for(var e,n=[],i=t.definition,s=0,c=i.length>s,u=!0;c&&u;)e=i[s],u=o.isOptionalProd(e),n=n.concat(a(e)),s+=1,c=i.length>s;return r.uniq(n)}function c(t){var e=r.map(t.definition,function(t){return a(t)});return r.uniq(r.flatten(e))}function u(t){return[t.terminalType]}e.first=a,e.firstForSequence=s,e.firstForBranching=c,e.firstForTerminal=u},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.IN="_~IN~_"},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(0),i=n(29),o=n(11),a=n(10),s=n(6);e.resolveGrammar=function(t){t=r.defaults(t,{errMsgProvider:a.defaultGrammarResolverErrorProvider});var e={};return r.forEach(t.rules,function(t){e[t.name]=t}),i.resolveGrammar(e,t.errMsgProvider)},e.validateGrammar=function(t){return t=r.defaults(t,{errMsgProvider:a.defaultGrammarValidatorErrorProvider,ignoredIssues:{}}),o.validateGrammar(t.rules,t.maxLookahead,t.tokenTypes,t.ignoredIssues,t.errMsgProvider,t.grammarName)},e.assignOccurrenceIndices=function(t){r.forEach(t.rules,function(t){var e=new s.DslMethodsCollectorVisitor;t.accept(e),r.forEach(e.dslMethods,function(t){r.forEach(t,function(t,e){t.idx=e+1})})})}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(3),i=n(0),o=n(8),a=n(23),s=n(2);function c(t){this.name=e.IN_RULE_RECOVERY_EXCEPTION,this.message=t}e.EOF_FOLLOW_KEY={},e.IN_RULE_RECOVERY_EXCEPTION="InRuleRecoveryException",e.InRuleRecoveryException=c,c.prototype=Error.prototype;var u=function(){function t(){}return t.prototype.initRecoverable=function(t){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=i.has(t,"recoveryEnabled")?t.recoveryEnabled:s.DEFAULT_PARSER_CONFIG.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=l)},t.prototype.getTokenToInsert=function(t){var e=r.createTokenInstance(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 a=this,s=this.findReSyncTokenType(),c=this.exportLexerState(),u=[],l=!1,p=this.LA(1),h=this.LA(1),f=function(){var t=a.LA(0),e=a.errorMessageProvider.buildMismatchTokenMessage({expected:r,actual:p,previous:t,ruleName:a.getCurrRuleFullName()}),n=new o.MismatchedTokenException(e,p,a.LA(0));n.resyncedTokens=i.dropRight(u),a.SAVE_ERROR(n)};!l;){if(this.tokenMatcher(h,r))return void f();if(n.call(this))return f(),void t.apply(this,e);this.tokenMatcher(h,s)?l=!0:(h=this.SKIP_TOKEN(),this.addToResyncTokens(h,u))}this.importLexerState(c)},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 c("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(i.isEmpty(e))return!1;var r=this.LA(1);return void 0!==i.find(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 i.contains(n,t)},t.prototype.findReSyncTokenType=function(){for(var t=this.flattenFollowSet(),e=this.LA(1),n=2;;){var r=e.tokenType;if(i.contains(t,r))return r;e=this.LA(n),n++}},t.prototype.getCurrFollowKey=function(){if(1===this.RULE_STACK.length)return e.EOF_FOLLOW_KEY;var t=this.getLastExplicitRuleShortName(),n=this.getLastExplicitRuleOccurrenceIndex(),r=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(t),idxInCallingRule:n,inRule:this.shortRuleNameToFullName(r)}},t.prototype.buildFullFollowKeyStack=function(){var t=this,n=this.RULE_STACK,r=this.RULE_OCCURRENCE_STACK;return i.isEmpty(this.LAST_EXPLICIT_RULE_STACK)||(n=i.map(this.LAST_EXPLICIT_RULE_STACK,function(e){return t.RULE_STACK[e]}),r=i.map(this.LAST_EXPLICIT_RULE_STACK,function(e){return t.RULE_OCCURRENCE_STACK[e]})),i.map(n,function(i,o){return 0===o?e.EOF_FOLLOW_KEY:{ruleName:t.shortRuleNameToFullName(i),idxInCallingRule:r[o],inRule:t.shortRuleNameToFullName(n[o-1])}})},t.prototype.flattenFollowSet=function(){var t=this,e=i.map(this.buildFullFollowKeyStack(),function(e){return t.getFollowSetFromFollowKey(e)});return i.flatten(e)},t.prototype.getFollowSetFromFollowKey=function(t){if(t===e.EOF_FOLLOW_KEY)return[r.EOF];var n=t.ruleName+t.idxInCallingRule+a.IN+t.inRule;return this.resyncFollows[n]},t.prototype.addToResyncTokens=function(t,e){return this.tokenMatcher(t,r.EOF)||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 i.dropRight(e)},t.prototype.attemptInRepetitionRecovery=function(t,e,n,r,i,o,a){},t.prototype.getCurrentGrammarPath=function(t,e){return{ruleStack:this.getHumanReadableRuleStack(),occurrenceStack:i.cloneArr(this.RULE_OCCURRENCE_STACK),lastTok:t,lastTokOccurrence:e}},t.prototype.getHumanReadableRuleStack=function(){var t=this;return i.isEmpty(this.LAST_EXPLICIT_RULE_STACK)?i.map(this.RULE_STACK,function(e){return t.shortRuleNameToFullName(e)}):i.map(this.LAST_EXPLICIT_RULE_STACK,function(e){return t.shortRuleNameToFullName(t.RULE_STACK[e])})},t}();function l(t,e,n,i,o,a,s){var c=this.getKeyForAutomaticLookahead(i,o),u=this.firstAfterRepMap[c];if(void 0===u){var l=this.getCurrRuleFullName();u=new a(this.getGAstProductions()[l],o).startWalking(),this.firstAfterRepMap[c]=u}var p=u.token,h=u.occurrence,f=u.isEndOfRule;1===this.RULE_STACK.length&&f&&void 0===p&&(p=r.EOF,h=1),this.shouldInRepetitionRecoveryBeTried(p,h,s)&&this.tryInRepetitionRecovery(t,e,n,p)}e.Recoverable=u,e.attemptInRepetitionRecovery=l},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(0);e.classNameFromInstance=function(t){return a(t.constructor)};var i=/^\s*function\s*(\S*)\s*\(/,o="name";function a(t){var e=t.name;return e||t.toString().match(i)[1]}e.functionName=a,e.defineNameProp=function(t,e){var n=Object.getOwnPropertyDescriptor(t,o);return!(!r.isUndefined(n)&&!n.configurable||(Object.defineProperty(t,o,{enumerable:!1,configurable:!0,writable:!1,value:e}),0))}},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=function(t,e){return(r=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}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(14),a=n(22),s=n(0),c=n(23),u=n(1),l=function(t){function e(e){var n=t.call(this)||this;return n.topProd=e,n.follows={},n}return i(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=p(t.referencedRule,t.idx)+this.topProd.name,i=e.concat(n),o=new u.Flat({definition:i}),s=a.first(o);this.follows[r]=s},e}(o.RestWalker);function p(t,e){return t.name+e+c.IN}e.ResyncFollowsWalker=l,e.computeAllProdsFollows=function(t){var e={};return s.forEach(t,function(t){var n=new l(t).startWalking();s.assign(e,n)}),e},e.buildBetweenProdsFollowPrefix=p,e.buildInProdFollowPrefix=function(t){return t.terminalType.name+t.idx+c.IN}},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=function(t,e){return(r=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}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(15),a=n(0),s=n(16),c=n(20),u="Complement Sets are not supported for first char optimization";function l(t,e,n){switch(t.type){case"Disjunction":for(var r=0;r=c.minOptimizationVal)for(var o=r.from>=c.minOptimizationVal?r.from:c.minOptimizationVal,a=r.to,s=c.charCodeToOptimizedIndex(o),u=c.charCodeToOptimizedIndex(a),l=s;l<=u;l++)e[l]=l}}});break;case"Group":l(s.value,e,n);break;default:throw Error("Non Exhaustive Match")}var h=void 0!==s.quantifier&&0===s.quantifier.atLeast;if("Group"===s.type&&!1===f(s)||"Group"!==s.type&&!1===h)break}break;default:throw Error("non exhaustive match!")}return a.values(e)}function p(t,e,n){var r=c.charCodeToOptimizedIndex(t);e[r]=r,!0===n&&function(t,e){var n=String.fromCharCode(t),r=n.toUpperCase();if(r!==n){var i=c.charCodeToOptimizedIndex(r.charCodeAt(0));e[i]=i}else{var o=n.toLowerCase();if(o!==n){var i=c.charCodeToOptimizedIndex(o.charCodeAt(0));e[i]=i}}}(t,e)}function h(t,e){return a.find(t.value,function(t){if("number"==typeof t)return a.contains(e,t);var n=t;return void 0!==a.find(e,function(t){return n.from<=t&&t<=n.to})})}function f(t){return!(!t.quantifier||0!==t.quantifier.atLeast)||!!t.value&&(a.isArray(t.value)?a.every(t.value,f):f(t.value))}e.failedOptimizationPrefixMsg='Unable to use "first char" lexer optimizations:\n',e.getOptimizedStartCodesIndices=function(t,n){void 0===n&&(n=!1);try{var r=s.getRegExpAst(t);return l(r.value,{},r.flags.ignoreCase)}catch(r){if(r.message===u)n&&a.PRINT_WARNING(e.failedOptimizationPrefixMsg+"\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 i="";n&&(i="\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."),a.PRINT_ERROR(e.failedOptimizationPrefixMsg+"\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"+i)}}return[]},e.firstCharOptimizedIndices=l;var d=function(t){function e(e){var n=t.call(this)||this;return n.targetCharCodes=e,n.found=!1,n}return i(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){a.contains(this.targetCharCodes,t.value)&&(this.found=!0)},e.prototype.visitSet=function(t){t.complement?void 0===h(t,this.targetCharCodes)&&(this.found=!0):void 0!==h(t,this.targetCharCodes)&&(this.found=!0)},e}(o.BaseRegExpVisitor);e.canMatchCharCode=function(t,e){if(e instanceof RegExp){var n=s.getRegExpAst(e),r=new d(t);return r.visit(n),r.found}return void 0!==a.find(e,function(e){return a.contains(t,e.charCodeAt(0))})}},function(t,e,n){"use strict";var r,i=this&&this.__extends||(r=function(t,e){return(r=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}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)});Object.defineProperty(e,"__esModule",{value:!0});var o=n(2),a=n(0),s=n(4);e.resolveGrammar=function(t,e){var n=new c(t,e);return n.resolveRefs(),n.errors};var c=function(t){function e(e,n){var r=t.call(this)||this;return r.nameToTopRule=e,r.errMsgProvider=n,r.errors=[],r}return i(e,t),e.prototype.resolveRefs=function(){var t=this;a.forEach(a.values(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:o.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:t.nonTerminalName})}},e}(s.GAstVisitor);e.GastRefResolverVisitor=c},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(12),i=n(0),o=n(2),a=n(7),s=n(6),c=function(){function t(){}return t.prototype.initLooksAhead=function(t){this.dynamicTokensEnabled=i.has(t,"dynamicTokensEnabled")?t.dynamicTokensEnabled:o.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled,this.maxLookahead=i.has(t,"maxLookahead")?t.maxLookahead:o.DEFAULT_PARSER_CONFIG.maxLookahead,this.lookAheadFuncsCache=i.isES2015MapSupported()?new Map:[],i.isES2015MapSupported()?(this.getLaFuncFromCache=this.getLaFuncFromMap,this.setLaFuncCache=this.setLaFuncCacheUsingMap):(this.getLaFuncFromCache=this.getLaFuncFromObj,this.setLaFuncCache=this.setLaFuncUsingObj)},t.prototype.preComputeLookaheadFunctions=function(t){var e=this;i.forEach(t,function(t){e.TRACE_INIT(t.name+" Rule Lookahead",function(){var n=s.collectMethods(t),o=n.alternation,c=n.repetition,u=n.option,l=n.repetitionMandatory,p=n.repetitionMandatoryWithSeparator,h=n.repetitionWithSeparator;i.forEach(o,function(n){var i=0===n.idx?"":n.idx;e.TRACE_INIT(""+s.getProductionDslName(n)+i,function(){var i=r.buildLookaheadFuncForOr(n.idx,t,n.maxLookahead||e.maxLookahead,n.hasPredicates,e.dynamicTokensEnabled,e.lookAheadBuilderForAlternatives),o=a.getKeyForAutomaticLookahead(e.fullRuleNameToShort[t.name],a.OR_IDX,n.idx);e.setLaFuncCache(o,i)})}),i.forEach(c,function(n){e.computeLookaheadFunc(t,n.idx,a.MANY_IDX,r.PROD_TYPE.REPETITION,n.maxLookahead,s.getProductionDslName(n))}),i.forEach(u,function(n){e.computeLookaheadFunc(t,n.idx,a.OPTION_IDX,r.PROD_TYPE.OPTION,n.maxLookahead,s.getProductionDslName(n))}),i.forEach(l,function(n){e.computeLookaheadFunc(t,n.idx,a.AT_LEAST_ONE_IDX,r.PROD_TYPE.REPETITION_MANDATORY,n.maxLookahead,s.getProductionDslName(n))}),i.forEach(p,function(n){e.computeLookaheadFunc(t,n.idx,a.AT_LEAST_ONE_SEP_IDX,r.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR,n.maxLookahead,s.getProductionDslName(n))}),i.forEach(h,function(n){e.computeLookaheadFunc(t,n.idx,a.MANY_SEP_IDX,r.PROD_TYPE.REPETITION_WITH_SEPARATOR,n.maxLookahead,s.getProductionDslName(n))})})})},t.prototype.computeLookaheadFunc=function(t,e,n,i,o,s){var c=this;this.TRACE_INIT(""+s+(0===e?"":e),function(){var s=r.buildLookaheadFuncForOptionalProd(e,t,o||c.maxLookahead,c.dynamicTokensEnabled,i,c.lookAheadBuilderForOptional),u=a.getKeyForAutomaticLookahead(c.fullRuleNameToShort[t.name],n,e);c.setLaFuncCache(u,s)})},t.prototype.lookAheadBuilderForOptional=function(t,e,n){return r.buildSingleAlternativeLookaheadFunction(t,e,n)},t.prototype.lookAheadBuilderForAlternatives=function(t,e,n,i){return r.buildAlternativesLookAheadFunc(t,e,n,i)},t.prototype.getKeyForAutomaticLookahead=function(t,e){var n=this.getLastExplicitRuleShortName();return a.getKeyForAutomaticLookahead(n,t,e)},t.prototype.getLaFuncFromCache=function(t){},t.prototype.getLaFuncFromMap=function(t){return this.lookAheadFuncsCache.get(t)},t.prototype.getLaFuncFromObj=function(t){return this.lookAheadFuncsCache[t]},t.prototype.setLaFuncCache=function(t,e){},t.prototype.setLaFuncCacheUsingMap=function(t,e){this.lookAheadFuncsCache.set(t,e)},t.prototype.setLaFuncUsingObj=function(t,e){this.lookAheadFuncsCache[t]=e},t}();e.LooksAhead=c},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(17),i=n(0),o=n(32),a=n(7),s=n(2),c=function(){function t(){}return t.prototype.initTreeBuilder=function(t){if(this.LAST_EXPLICIT_RULE_STACK=[],this.CST_STACK=[],this.outputCst=i.has(t,"outputCst")?t.outputCst:s.DEFAULT_PARSER_CONFIG.outputCst,this.nodeLocationTracking=i.has(t,"nodeLocationTracking")?t.nodeLocationTracking:s.DEFAULT_PARSER_CONFIG.nodeLocationTracking,this.outputCst)if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=r.setNodeLocationFull,this.setNodeLocationFromNode=r.setNodeLocationFull,this.cstPostRule=i.NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=i.NOOP,this.setNodeLocationFromNode=i.NOOP,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=r.setNodeLocationOnlyOffset,this.setNodeLocationFromNode=r.setNodeLocationOnlyOffset,this.cstPostRule=i.NOOP,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=i.NOOP,this.setNodeLocationFromNode=i.NOOP,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.NOOP,this.setNodeLocationFromNode=i.NOOP,this.cstPostRule=i.NOOP,this.setInitialNodeLocation=i.NOOP}else this.cstInvocationStateUpdate=i.NOOP,this.cstFinallyStateUpdate=i.NOOP,this.cstPostTerminal=i.NOOP,this.cstPostNonTerminal=i.NOOP,this.cstPostRule=i.NOOP,this.getLastExplicitRuleShortName=this.getLastExplicitRuleShortNameNoCst,this.getPreviousExplicitRuleShortName=this.getPreviousExplicitRuleShortNameNoCst,this.getLastExplicitRuleOccurrenceIndex=this.getLastExplicitRuleOccurrenceIndexNoCst,this.manyInternal=this.manyInternalNoCst,this.orInternal=this.orInternalNoCst,this.optionInternal=this.optionInternalNoCst,this.atLeastOneInternal=this.atLeastOneInternalNoCst,this.manySepFirstInternal=this.manySepFirstInternalNoCst,this.atLeastOneSepFirstInternal=this.atLeastOneSepFirstInternalNoCst},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.cstNestedInvocationStateUpdate=function(t,e){var n={name:t,fullName:this.shortRuleNameToFull[this.getLastExplicitRuleShortName()]+t,children:{}};this.setInitialNodeLocation(n),this.CST_STACK.push(n)},t.prototype.cstInvocationStateUpdate=function(t,e){this.LAST_EXPLICIT_RULE_STACK.push(this.RULE_STACK.length-1);var n={name:t,children:{}};this.setInitialNodeLocation(n),this.CST_STACK.push(n)},t.prototype.cstFinallyStateUpdate=function(){this.LAST_EXPLICIT_RULE_STACK.pop(),this.CST_STACK.pop()},t.prototype.cstNestedFinallyStateUpdate=function(){var t=this.CST_STACK.pop();this.cstPostRule(t)},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=this.CST_STACK[this.CST_STACK.length-1];r.addTerminalToCst(n,e,t),this.setNodeLocationFromToken(n.location,e)},t.prototype.cstPostNonTerminal=function(t,e){if(!0!==this.isBackTracking()){var n=this.CST_STACK[this.CST_STACK.length-1];r.addNoneTerminalToCst(n,e,t),this.setNodeLocationFromNode(n.location,t.location)}},t.prototype.getBaseCstVisitorConstructor=function(){if(i.isUndefined(this.baseCstVisitorConstructor)){var t=o.createBaseSemanticVisitorConstructor(this.className,this.allRuleNames);return this.baseCstVisitorConstructor=t,t}return this.baseCstVisitorConstructor},t.prototype.getBaseCstVisitorConstructorWithDefaults=function(){if(i.isUndefined(this.baseCstVisitorWithDefaultsConstructor)){var t=o.createBaseVisitorConstructorWithDefaults(this.className,this.allRuleNames,this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=t,t}return this.baseCstVisitorWithDefaultsConstructor},t.prototype.nestedRuleBeforeClause=function(t,e){var n;return void 0!==t.NAME?(n=t.NAME,this.nestedRuleInvocationStateUpdate(n,e),n):void 0},t.prototype.nestedAltBeforeClause=function(t,e,n,r){var i,o=this.getLastExplicitRuleShortName(),s=a.getKeyForAltIndex(o,n,e,r);return void 0!==t.NAME?(i=t.NAME,this.nestedRuleInvocationStateUpdate(i,s),{shortName:s,nestedName:i}):void 0},t.prototype.nestedRuleFinallyClause=function(t,e){var n=this.CST_STACK,i=n[n.length-1];this.nestedRuleFinallyStateUpdate();var o=n[n.length-1];r.addNoneTerminalToCst(o,e,i),this.setNodeLocationFromNode(o.location,i.location)},t.prototype.getLastExplicitRuleShortName=function(){var t=this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length-1];return this.RULE_STACK[t]},t.prototype.getLastExplicitRuleShortNameNoCst=function(){var t=this.RULE_STACK;return t[t.length-1]},t.prototype.getPreviousExplicitRuleShortName=function(){var t=this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length-2];return this.RULE_STACK[t]},t.prototype.getPreviousExplicitRuleShortNameNoCst=function(){var t=this.RULE_STACK;return t[t.length-2]},t.prototype.getLastExplicitRuleOccurrenceIndex=function(){var t=this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length-1];return this.RULE_OCCURRENCE_STACK[t]},t.prototype.getLastExplicitRuleOccurrenceIndexNoCst=function(){var t=this.RULE_OCCURRENCE_STACK;return t[t.length-1]},t.prototype.nestedRuleInvocationStateUpdate=function(t,e){this.RULE_OCCURRENCE_STACK.push(1),this.RULE_STACK.push(e),this.cstNestedInvocationStateUpdate(t,e)},t.prototype.nestedRuleFinallyStateUpdate=function(){this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstNestedFinallyStateUpdate()},t}();e.TreeBuilder=c},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r,i=n(0),o=n(26),a=n(11);function s(t,e){for(var n=i.keys(t),r=n.length,o=0;o on "+o.functionName(t.constructor)+" CST Visitor.",type:r.MISSING_METHOD,methodName:e}});return i.compact(n)}e.defaultVisit=s,e.createBaseSemanticVisitorConstructor=function(t,e){var n=function(){};return o.defineNameProp(n,t+"BaseSemantics"),(n.prototype={visit:function(t,e){if(i.isArray(t)&&(t=t[0]),!i.isUndefined(t))return void 0!==t.fullName?this[t.fullName](t.children,e):this[t.name](t.children,e)},validateVisitor:function(){var t=c(this,e);if(!i.isEmpty(t)){var n=i.map(t,function(t){return t.msg});throw Error("Errors Detected in CST Visitor <"+o.functionName(this.constructor)+">:\n\t"+n.join("\n\n").replace(/\n/g,"\n\t"))}}}).constructor=n,n._RULE_NAMES=e,n},e.createBaseVisitorConstructorWithDefaults=function(t,e,n){var r=function(){};o.defineNameProp(r,t+"BaseSemanticsWithDefaults");var a=Object.create(n.prototype);return i.forEach(e,function(t){a[t]=s}),(r.prototype=a).constructor=r,r},function(t){t[t.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",t[t.MISSING_METHOD=1]="MISSING_METHOD"}(r=e.CstVisitorDefinitionError||(e.CstVisitorDefinitionError={})),e.validateVisitor=c,e.validateMissingCstMethods=u;var l=["constructor","visit","validateVisitor"];function p(t,e){var n=[];for(var s in t)a.validTermsPattern.test(s)&&i.isFunction(t[s])&&!i.contains(l,s)&&!i.contains(e,s)&&n.push({msg:"Redundant visitor method: <"+s+"> on "+o.functionName(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 /"+a.validTermsPattern.source+"/.",type:r.REDUNDANT_METHOD,methodName:s});return n}e.validateRedundantMethods=p},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(2),i=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:!0,configurable:!0}),t.prototype.SKIP_TOKEN=function(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):r.END_OF_FILE},t.prototype.LA=function(t){var e=this.currIdx+t;return e<0||this.tokVectorLength<=e?r.END_OF_FILE: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}();e.LexerAdapter=i},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(0),i=n(8),o=n(2),a=n(10),s=n(11),c=n(1),u=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=o.DEFAULT_RULE_CONFIG),r.contains(this.definedRulesNames,t)){var i={message:a.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({topLevelRule:t,grammarName:this.className}),type:o.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,ruleName:t};this.definitionErrors.push(i)}this.definedRulesNames.push(t);var s=this.defineRule(t,e,n);return this[t]=s,s},t.prototype.OVERRIDE_RULE=function(t,e,n){void 0===n&&(n=o.DEFAULT_RULE_CONFIG);var r=[];r=r.concat(s.validateRuleIsOverridden(t,this.definedRulesNames,this.className)),this.definitionErrors.push.apply(this.definitionErrors,r);var i=this.defineRule(t,e,n);return this[t]=i,i},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(i.isRecognitionException(t))return!1;throw t}finally{this.reloadRecogState(n),this.isBackTrackingStack.pop()}}},t.prototype.getGAstProductions=function(){return this.gastProductionsCache},t.prototype.getSerializedGastProductions=function(){return c.serializeGrammar(r.values(this.gastProductionsCache))},t}();e.RecognizerApi=u},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(0),i=n(7),o=n(8),a=n(12),s=n(13),c=n(2),u=n(25),l=n(3),p=n(5),h=n(26),f=function(){function t(){}return t.prototype.initRecognizerEngine=function(t,e){if(this.className=h.classNameFromInstance(this),this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=p.tokenStructuredMatcherNoCategories,this.definedRulesNames=[],this.tokensMap={},this.allRuleNames=[],this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},r.has(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(r.isArray(t)){if(r.isEmpty(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(r.isArray(t))this.tokensMap=r.reduce(t,function(t,e){return t[e.name]=e,t},{});else if(r.has(t,"modes")&&r.every(r.flatten(r.values(t.modes)),p.isTokenType)){var n=r.flatten(r.values(t.modes)),i=r.uniq(n);this.tokensMap=r.reduce(i,function(t,e){return t[e.name]=e,t},{})}else{if(!r.isObject(t))throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap=r.cloneObj(t)}this.tokensMap.EOF=l.EOF;var o=r.every(r.values(t),function(t){return r.isEmpty(t.categoryMatches)});this.tokenMatcher=o?p.tokenStructuredMatcherNoCategories:p.tokenStructuredMatcher,p.augmentTokenTypes(r.values(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 o,a=r.has(n,"resyncEnabled")?n.resyncEnabled:c.DEFAULT_RULE_CONFIG.resyncEnabled,s=r.has(n,"recoveryValueFunc")?n.recoveryValueFunc:c.DEFAULT_RULE_CONFIG.recoveryValueFunc,u=this.ruleShortNameIdx<e},t.prototype.orInternalNoCst=function(t,e){var n=r.isArray(t)?t:t.DEF,o=this.getKeyForAutomaticLookahead(i.OR_IDX,e),a=this.getLaFuncFromCache(o).call(this,n);if(void 0!==a)return n[a].ALT.call(this);this.raiseNoAltException(e,t.ERR_MSG)},t.prototype.orInternal=function(t,e){var n=this.getKeyForAutomaticLookahead(i.OR_IDX,e),o=this.nestedRuleBeforeClause(t,n);try{var a=r.isArray(t)?t:t.DEF,s=this.getLaFuncFromCache(n).call(this,a);if(void 0!==s){var c=a[s],u=this.nestedAltBeforeClause(c,e,i.OR_IDX,s);try{return c.ALT.call(this)}finally{void 0!==u&&this.nestedRuleFinallyClause(u.shortName,u.nestedName)}}this.raiseNoAltException(e,t.ERR_MSG)}finally{void 0!==o&&this.nestedRuleFinallyClause(n,o)}},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 o.NotAllInputParsedException(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 o.isRecognitionException(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 o.MismatchedTokenException(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 t.name===u.IN_RULE_RECOVERY_EXCEPTION?n:t}},t.prototype.saveRecogState=function(){var t=this.errors,e=r.cloneArr(this.RULE_STACK);return{errors:t,lexerState:this.exportLexerState(),RULE_STACK:e,CST_STACK:this.CST_STACK,LAST_EXPLICIT_RULE_STACK:this.LAST_EXPLICIT_RULE_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),l.EOF)},t.prototype.reset=function(){this.resetLexerState(),this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.LAST_EXPLICIT_RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]},t}();e.RecognizerEngine=f},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(8),i=n(0),o=n(12),a=n(2),s=function(){function t(){}return t.prototype.initErrorHandler=function(t){this._errors=[],this.errorMessageProvider=i.defaults(t.errorMessageProvider,a.DEFAULT_PARSER_CONFIG.errorMessageProvider)},t.prototype.SAVE_ERROR=function(t){if(r.isRecognitionException(t))return t.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:i.cloneArr(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 i.cloneArr(this._errors)},set:function(t){this._errors=t},enumerable:!0,configurable:!0}),t.prototype.raiseEarlyExitException=function(t,e,n){for(var i=this.getCurrRuleFullName(),a=this.getGAstProductions()[i],s=o.getLookaheadPathsForOptionalProd(t,a,e,this.maxLookahead)[0],c=[],u=1;u<=this.maxLookahead;u++)c.push(this.LA(u));var l=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:s,actual:c,previous:this.LA(0),customUserDescription:n,ruleName:i});throw this.SAVE_ERROR(new r.EarlyExitException(l,this.LA(1),this.LA(0)))},t.prototype.raiseNoAltException=function(t,e){for(var n=this.getCurrRuleFullName(),i=this.getGAstProductions()[n],a=o.getLookaheadPathsForOr(t,i,this.maxLookahead),s=[],c=1;c<=this.maxLookahead;c++)s.push(this.LA(c));var u=this.LA(0),l=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:a,actual:s,previous:u,customUserDescription:e,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new r.NoViableAltException(l,this.LA(1),u))},t}();e.ErrorHandler=s},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(13),i=n(0),o=function(){function t(){}return t.prototype.initContentAssist=function(){},t.prototype.computeContentAssist=function(t,e){var n=this.gastProductionsCache[t];if(i.isUndefined(n))throw Error("Rule ->"+t+"<- does not exist in this grammar.");return r.nextPossibleTokensAfter([n],e,this.tokenMatcher,this.maxLookahead)},t.prototype.getNextPossibleTokenTypes=function(t){var e=i.first(t.ruleStack),n=this.getGAstProductions()[e];return new r.NextAfterTokenWalker(n,t).startWalking()},t}();e.ContentAssist=o},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(0),i=n(1),o=n(9),a=n(5),s=n(3),c=n(2),u=n(7),l={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(l);var p=Math.pow(2,u.BITS_FOR_OCCURRENCE_IDX)-1,h=s.createToken({name:"RECORDING_PHASE_TOKEN",pattern:o.Lexer.NA});a.augmentTokenTypes([h]);var f=s.createTokenInstance(h,"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(f);var d={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:{}},m=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 c.END_OF_FILE},t.prototype.topLevelRuleRecord=function(t,e){try{var n=new i.Rule({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 E.call(this,i.Option,t,e)},t.prototype.atLeastOneInternalRecord=function(t,e){E.call(this,i.RepetitionMandatory,e,t)},t.prototype.atLeastOneSepFirstInternalRecord=function(t,e){E.call(this,i.RepetitionMandatoryWithSeparator,e,t,!0)},t.prototype.manyInternalRecord=function(t,e){E.call(this,i.Repetition,e,t)},t.prototype.manySepFirstInternalRecord=function(t,e){E.call(this,i.RepetitionWithSeparator,e,t,!0)},t.prototype.orInternalRecord=function(t,e){return function(t,e){var n=this;y(e);var o=r.peek(this.recordingProdStack),a=!1===r.isArray(t),s=!1===a?t:t.DEF,c=new i.Alternation({definition:[],idx:e,ignoreAmbiguities:a&&!0===t.IGNORE_AMBIGUITIES});r.has(t,"NAME")&&(c.name=t.NAME);r.has(t,"MAX_LOOKAHEAD")&&(c.maxLookahead=t.MAX_LOOKAHEAD);var u=r.some(s,function(t){return r.isFunction(t.GATE)});return c.hasPredicates=u,o.definition.push(c),r.forEach(s,function(t){var e=new i.Flat({definition:[]});c.definition.push(e),r.has(t,"NAME")&&(e.name=t.NAME),r.has(t,"IGNORE_AMBIGUITIES")?e.ignoreAmbiguities=t.IGNORE_AMBIGUITIES:r.has(t,"GATE")&&(e.ignoreAmbiguities=!0),n.recordingProdStack.push(e),t.ALT.call(n),n.recordingProdStack.pop()}),l}.call(this,t,e)},t.prototype.subruleInternalRecord=function(t,e,n){if(y(e),!t||!1===r.has(t,"ruleName")){var o=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 o.KNOWN_RECORDER_ERROR=!0,o}var a=r.peek(this.recordingProdStack),s=t.ruleName,c=new i.NonTerminal({idx:e,nonTerminalName:s,referencedRule:void 0});return a.definition.push(c),this.outputCst?d:l},t.prototype.consumeInternalRecord=function(t,e,n){if(y(e),!a.hasShortKeyProperty(t)){var o=new Error(" argument is invalid expecting a TokenType reference but got: <"+JSON.stringify(t)+">\n inside top level rule: <"+this.recordingProdStack[0].name+">");throw o.KNOWN_RECORDER_ERROR=!0,o}var s=r.peek(this.recordingProdStack),c=new i.Terminal({idx:e,terminalType:t});return s.definition.push(c),f},t}();function E(t,e,n,i){void 0===i&&(i=!1),y(n);var o=r.peek(this.recordingProdStack),a=r.isFunction(e)?e:e.DEF,s=new t({definition:[],idx:n});return r.has(e,"NAME")&&(s.name=e.NAME),i&&(s.separator=e.SEP),r.has(e,"MAX_LOOKAHEAD")&&(s.maxLookahead=e.MAX_LOOKAHEAD),this.recordingProdStack.push(s),a.call(this),o.definition.push(s),this.recordingProdStack.pop(),l}function T(t){return 0===t?"":""+t}function y(t){if(t<0||t>p){var e=new Error("Invalid DSL Method idx value: <"+t+">\n\tIdx value must be a none negative value smaller than "+(p+1));throw e.KNOWN_RECORDER_ERROR=!0,e}}e.GastRecorder=m},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(0),i=n(2),o=function(){function t(){}return t.prototype.initPerformanceTracer=function(t){if(r.has(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=i.DEFAULT_PARSER_CONFIG.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 i=r.timer(e),o=i.time,a=i.value,s=o>10?console.warn:console.log;return this.traceInitIndent time: "+o+"ms"),this.traceInitIndent--,a}return e()},t}();e.PerformanceTracer=o},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(19);e.createSyntaxDiagramsCode=function(t,e){var n=void 0===e?{}:e,i=n.resourceBase,o=void 0===i?"https://unpkg.com/chevrotain@"+r.VERSION+"/diagrams/":i,a=n.css;return"\n\x3c!-- This is a generated file --\x3e\n\n\n\n\n\n\n\n\n\n\n\n";
+ var diagramsDiv = "\n \n";
+ var serializedGrammar = "\n\n";
+ var initLogic = "\n\n";
+ return (header + cssHtml + scripts + diagramsDiv + serializedGrammar + initLogic);
+}
+exports.createSyntaxDiagramsCode = createSyntaxDiagramsCode;
+//# sourceMappingURL=render_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/generate/generate.js b/node_modules/chevrotain/lib/src/generate/generate.js
new file mode 100644
index 0000000..4037963
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/generate/generate.js
@@ -0,0 +1,142 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../utils/utils");
+var gast_public_1 = require("../parse/grammar/gast/gast_public");
+/**
+ * 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";
+}
+exports.genUmdModule = genUmdModule;
+function genWrapperFunction(options) {
+ return " \n" + genClass(options) + "\nreturn new " + options.name + "(tokenVocabulary, config) \n";
+}
+exports.genWrapperFunction = genWrapperFunction;
+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;
+}
+exports.genClass = genClass;
+function genAllRules(rules) {
+ var rulesText = utils_1.map(rules, function (currRule) {
+ return genRule(currRule, 1);
+ });
+ return rulesText.join("\n");
+}
+exports.genAllRules = genAllRules;
+function genRule(prod, n) {
+ var result = indent(n, "$.RULE(\"" + prod.name + "\", function() {") + NL;
+ result += genDefinition(prod.definition, n + 1);
+ result += indent(n + 1, "})") + NL;
+ return result;
+}
+exports.genRule = genRule;
+function genTerminal(prod, n) {
+ var name = prod.terminalType.name;
+ // TODO: potential performance optimization, avoid tokenMap Dictionary access
+ return indent(n, "$.CONSUME" + prod.idx + "(this.tokensMap." + name + ")" + NL);
+}
+exports.genTerminal = genTerminal;
+function genNonTerminal(prod, n) {
+ return indent(n, "$.SUBRULE" + prod.idx + "($." + prod.nonTerminalName + ")" + NL);
+}
+exports.genNonTerminal = genNonTerminal;
+function genAlternation(prod, n) {
+ var result = indent(n, "$.OR" + prod.idx + "([") + NL;
+ var alts = utils_1.map(prod.definition, function (altDef) { return genSingleAlt(altDef, n + 1); });
+ result += alts.join("," + NL);
+ result += NL + indent(n, "])" + NL);
+ return result;
+}
+exports.genAlternation = genAlternation;
+function genSingleAlt(prod, n) {
+ var result = indent(n, "{") + NL;
+ if (prod.name) {
+ result += indent(n + 1, "NAME: \"" + prod.name + "\",") + NL;
+ }
+ result += indent(n + 1, "ALT: function() {") + NL;
+ result += genDefinition(prod.definition, n + 1);
+ result += indent(n + 1, "}") + NL;
+ result += indent(n, "}");
+ return result;
+}
+exports.genSingleAlt = genSingleAlt;
+function genProd(prod, n) {
+ /* istanbul ignore else */
+ if (prod instanceof gast_public_1.NonTerminal) {
+ return genNonTerminal(prod, n);
+ }
+ else if (prod instanceof gast_public_1.Option) {
+ return genDSLRule("OPTION", prod, n);
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatory) {
+ return genDSLRule("AT_LEAST_ONE", prod, n);
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatoryWithSeparator) {
+ return genDSLRule("AT_LEAST_ONE_SEP", prod, n);
+ }
+ else if (prod instanceof gast_public_1.RepetitionWithSeparator) {
+ return genDSLRule("MANY_SEP", prod, n);
+ }
+ else if (prod instanceof gast_public_1.Repetition) {
+ return genDSLRule("MANY", prod, n);
+ }
+ else if (prod instanceof gast_public_1.Alternation) {
+ return genAlternation(prod, n);
+ }
+ else if (prod instanceof gast_public_1.Terminal) {
+ return genTerminal(prod, n);
+ }
+ else if (prod instanceof gast_public_1.Flat) {
+ return genDefinition(prod.definition, n);
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+function genDSLRule(dslName, prod, n) {
+ var result = indent(n, "$." + (dslName + prod.idx) + "(");
+ if (prod.name || prod.separator) {
+ result += "{" + NL;
+ if (prod.name) {
+ result += indent(n + 1, "NAME: \"" + prod.name + "\"") + "," + NL;
+ }
+ if (prod.separator) {
+ result +=
+ indent(n + 1, "SEP: this.tokensMap." + prod.separator.name) +
+ "," +
+ NL;
+ }
+ result += "DEF: " + genDefFunction(prod.definition, n + 2) + NL;
+ result += indent(n, "}") + NL;
+ }
+ else {
+ result += genDefFunction(prod.definition, n + 1);
+ }
+ result += indent(n, ")") + NL;
+ return result;
+}
+function genDefFunction(definition, n) {
+ var def = "function() {" + NL;
+ def += genDefinition(definition, n);
+ def += indent(n, "}") + NL;
+ return def;
+}
+function genDefinition(def, n) {
+ var result = "";
+ utils_1.forEach(def, function (prod) {
+ result += genProd(prod, n + 1);
+ });
+ return result;
+}
+function indent(howMuch, text) {
+ var spaces = Array(howMuch * 4 + 1).join(" ");
+ return spaces + text;
+}
+//# sourceMappingURL=generate.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/generate/generate_public.js b/node_modules/chevrotain/lib/src/generate/generate_public.js
new file mode 100644
index 0000000..ee61459
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/generate/generate_public.js
@@ -0,0 +1,21 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var generate_1 = require("./generate");
+function generateParserFactory(options) {
+ var wrapperText = generate_1.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
+ require("../api"));
+ };
+}
+exports.generateParserFactory = generateParserFactory;
+function generateParserModule(options) {
+ return generate_1.genUmdModule({ name: options.name, rules: options.rules });
+}
+exports.generateParserModule = generateParserModule;
+//# sourceMappingURL=generate_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/lang/lang_extensions.js b/node_modules/chevrotain/lib/src/lang/lang_extensions.js
new file mode 100644
index 0000000..d233d74
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/lang/lang_extensions.js
@@ -0,0 +1,42 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../utils/utils");
+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;
+//# sourceMappingURL=lang_extensions.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/constants.js b/node_modules/chevrotain/lib/src/parse/constants.js
new file mode 100644
index 0000000..ba03ed9
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/constants.js
@@ -0,0 +1,5 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+// TODO: can this be removed? where is it used?
+exports.IN = "_~IN~_";
+//# sourceMappingURL=constants.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/cst/cst.js b/node_modules/chevrotain/lib/src/parse/cst/cst.js
new file mode 100644
index 0000000..f872cd6
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/cst/cst.js
@@ -0,0 +1,194 @@
+"use strict";
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../../utils/utils");
+var keys_1 = require("../grammar/keys");
+var gast_public_1 = require("../grammar/gast/gast_public");
+var gast_visitor_public_1 = require("../grammar/gast/gast_visitor_public");
+/**
+ * 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;
+ }
+}
+exports.setNodeLocationOnlyOffset = setNodeLocationOnlyOffset;
+/**
+ * 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;
+ }
+}
+exports.setNodeLocationFull = setNodeLocationFull;
+function addTerminalToCst(node, token, tokenTypeName) {
+ if (node.children[tokenTypeName] === undefined) {
+ node.children[tokenTypeName] = [token];
+ }
+ else {
+ node.children[tokenTypeName].push(token);
+ }
+}
+exports.addTerminalToCst = addTerminalToCst;
+function addNoneTerminalToCst(node, ruleName, ruleResult) {
+ if (node.children[ruleName] === undefined) {
+ node.children[ruleName] = [ruleResult];
+ }
+ else {
+ node.children[ruleName].push(ruleResult);
+ }
+}
+exports.addNoneTerminalToCst = addNoneTerminalToCst;
+var NamedDSLMethodsCollectorVisitor = /** @class */ (function (_super) {
+ __extends(NamedDSLMethodsCollectorVisitor, _super);
+ function NamedDSLMethodsCollectorVisitor(ruleIdx) {
+ var _this = _super.call(this) || this;
+ _this.result = [];
+ _this.ruleIdx = ruleIdx;
+ return _this;
+ }
+ NamedDSLMethodsCollectorVisitor.prototype.collectNamedDSLMethod = function (node, newNodeConstructor, methodIdx) {
+ // TODO: better hack to copy what we need here...
+ if (!utils_1.isUndefined(node.name)) {
+ // copy without name so this will indeed be processed later.
+ var nameLessNode
+ /* istanbul ignore else */
+ = void 0;
+ /* istanbul ignore else */
+ if (node instanceof gast_public_1.Option ||
+ node instanceof gast_public_1.Repetition ||
+ node instanceof gast_public_1.RepetitionMandatory ||
+ node instanceof gast_public_1.Alternation) {
+ nameLessNode = new newNodeConstructor({
+ definition: node.definition,
+ idx: node.idx
+ });
+ }
+ else if (node instanceof gast_public_1.RepetitionMandatoryWithSeparator ||
+ node instanceof gast_public_1.RepetitionWithSeparator) {
+ nameLessNode = new newNodeConstructor({
+ definition: node.definition,
+ idx: node.idx,
+ separator: node.separator
+ });
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ var def = [nameLessNode];
+ var key = keys_1.getKeyForAutomaticLookahead(this.ruleIdx, methodIdx, node.idx);
+ this.result.push({ def: def, key: key, name: node.name, orgProd: node });
+ }
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitOption = function (node) {
+ this.collectNamedDSLMethod(node, gast_public_1.Option, keys_1.OPTION_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitRepetition = function (node) {
+ this.collectNamedDSLMethod(node, gast_public_1.Repetition, keys_1.MANY_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionMandatory = function (node) {
+ this.collectNamedDSLMethod(node, gast_public_1.RepetitionMandatory, keys_1.AT_LEAST_ONE_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) {
+ this.collectNamedDSLMethod(node, gast_public_1.RepetitionMandatoryWithSeparator, keys_1.AT_LEAST_ONE_SEP_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionWithSeparator = function (node) {
+ this.collectNamedDSLMethod(node, gast_public_1.RepetitionWithSeparator, keys_1.MANY_SEP_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitAlternation = function (node) {
+ var _this = this;
+ this.collectNamedDSLMethod(node, gast_public_1.Alternation, keys_1.OR_IDX);
+ var hasMoreThanOneAlternative = node.definition.length > 1;
+ utils_1.forEach(node.definition, function (currFlatAlt, altIdx) {
+ if (!utils_1.isUndefined(currFlatAlt.name)) {
+ var def = currFlatAlt.definition;
+ if (hasMoreThanOneAlternative) {
+ def = [new gast_public_1.Option({ definition: currFlatAlt.definition })];
+ }
+ else {
+ // mandatory
+ def = currFlatAlt.definition;
+ }
+ var key = keys_1.getKeyForAltIndex(_this.ruleIdx, keys_1.OR_IDX, node.idx, altIdx);
+ _this.result.push({
+ def: def,
+ key: key,
+ name: currFlatAlt.name,
+ orgProd: currFlatAlt
+ });
+ }
+ });
+ };
+ return NamedDSLMethodsCollectorVisitor;
+}(gast_visitor_public_1.GAstVisitor));
+exports.NamedDSLMethodsCollectorVisitor = NamedDSLMethodsCollectorVisitor;
+function expandAllNestedRuleNames(topRules, fullToShortName) {
+ var result = {
+ allRuleNames: []
+ };
+ utils_1.forEach(topRules, function (currTopRule) {
+ var currTopRuleShortName = fullToShortName[currTopRule.name];
+ result.allRuleNames.push(currTopRule.name);
+ var namedCollectorVisitor = new NamedDSLMethodsCollectorVisitor(currTopRuleShortName);
+ currTopRule.accept(namedCollectorVisitor);
+ utils_1.forEach(namedCollectorVisitor.result, function (_a) {
+ var def = _a.def, key = _a.key, name = _a.name;
+ result.allRuleNames.push(currTopRule.name + name);
+ });
+ });
+ return result;
+}
+exports.expandAllNestedRuleNames = expandAllNestedRuleNames;
+//# sourceMappingURL=cst.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/cst/cst_visitor.js b/node_modules/chevrotain/lib/src/parse/cst/cst_visitor.js
new file mode 100644
index 0000000..46e3015
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/cst/cst_visitor.js
@@ -0,0 +1,129 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../../utils/utils");
+var lang_extensions_1 = require("../../lang/lang_extensions");
+var checks_1 = require("../grammar/checks");
+function defaultVisit(ctx, param) {
+ var childrenNames = utils_1.keys(ctx);
+ var childrenNamesLength = childrenNames.length;
+ for (var i = 0; i < childrenNamesLength; i++) {
+ var currChildName = childrenNames[i];
+ var currChildArray = ctx[currChildName];
+ var currChildArrayLength = currChildArray.length;
+ for (var j = 0; j < currChildArrayLength; j++) {
+ var currChild = currChildArray[j];
+ // distinction between Tokens Children and CstNode children
+ if (currChild.tokenTypeIdx === undefined) {
+ if (currChild.fullName !== undefined) {
+ this[currChild.fullName](currChild.children, param);
+ }
+ else {
+ this[currChild.name](currChild.children, param);
+ }
+ }
+ }
+ }
+ // defaultVisit does not support generic out param
+ return undefined;
+}
+exports.defaultVisit = defaultVisit;
+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
+ lang_extensions_1.defineNameProp(derivedConstructor, grammarName + "BaseSemantics");
+ var semanticProto = {
+ visit: function (cstNode, param) {
+ // enables writing more concise visitor methods when CstNode has only a single child
+ if (utils_1.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 (utils_1.isUndefined(cstNode)) {
+ return undefined;
+ }
+ if (cstNode.fullName !== undefined) {
+ return this[cstNode.fullName](cstNode.children, param);
+ }
+ else {
+ return this[cstNode.name](cstNode.children, param);
+ }
+ },
+ validateVisitor: function () {
+ var semanticDefinitionErrors = validateVisitor(this, ruleNames);
+ if (!utils_1.isEmpty(semanticDefinitionErrors)) {
+ var errorMessages = utils_1.map(semanticDefinitionErrors, function (currDefError) { return currDefError.msg; });
+ throw Error("Errors Detected in CST Visitor <" + lang_extensions_1.functionName(this.constructor) + ">:\n\t" +
+ ("" + errorMessages.join("\n\n").replace(/\n/g, "\n\t")));
+ }
+ }
+ };
+ derivedConstructor.prototype = semanticProto;
+ derivedConstructor.prototype.constructor = derivedConstructor;
+ derivedConstructor._RULE_NAMES = ruleNames;
+ return derivedConstructor;
+}
+exports.createBaseSemanticVisitorConstructor = createBaseSemanticVisitorConstructor;
+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
+ lang_extensions_1.defineNameProp(derivedConstructor, grammarName + "BaseSemanticsWithDefaults");
+ var withDefaultsProto = Object.create(baseConstructor.prototype);
+ utils_1.forEach(ruleNames, function (ruleName) {
+ withDefaultsProto[ruleName] = defaultVisit;
+ });
+ derivedConstructor.prototype = withDefaultsProto;
+ derivedConstructor.prototype.constructor = derivedConstructor;
+ return derivedConstructor;
+}
+exports.createBaseVisitorConstructorWithDefaults = createBaseVisitorConstructorWithDefaults;
+var CstVisitorDefinitionError;
+(function (CstVisitorDefinitionError) {
+ CstVisitorDefinitionError[CstVisitorDefinitionError["REDUNDANT_METHOD"] = 0] = "REDUNDANT_METHOD";
+ CstVisitorDefinitionError[CstVisitorDefinitionError["MISSING_METHOD"] = 1] = "MISSING_METHOD";
+})(CstVisitorDefinitionError = exports.CstVisitorDefinitionError || (exports.CstVisitorDefinitionError = {}));
+function validateVisitor(visitorInstance, ruleNames) {
+ var missingErrors = validateMissingCstMethods(visitorInstance, ruleNames);
+ var redundantErrors = validateRedundantMethods(visitorInstance, ruleNames);
+ return missingErrors.concat(redundantErrors);
+}
+exports.validateVisitor = validateVisitor;
+function validateMissingCstMethods(visitorInstance, ruleNames) {
+ var errors = utils_1.map(ruleNames, function (currRuleName) {
+ if (!utils_1.isFunction(visitorInstance[currRuleName])) {
+ return {
+ msg: "Missing visitor method: <" + currRuleName + "> on " + lang_extensions_1.functionName(visitorInstance.constructor) + " CST Visitor.",
+ type: CstVisitorDefinitionError.MISSING_METHOD,
+ methodName: currRuleName
+ };
+ }
+ });
+ return utils_1.compact(errors);
+}
+exports.validateMissingCstMethods = validateMissingCstMethods;
+var VALID_PROP_NAMES = ["constructor", "visit", "validateVisitor"];
+function validateRedundantMethods(visitorInstance, ruleNames) {
+ var errors = [];
+ for (var prop in visitorInstance) {
+ if (checks_1.validTermsPattern.test(prop) &&
+ utils_1.isFunction(visitorInstance[prop]) &&
+ !utils_1.contains(VALID_PROP_NAMES, prop) &&
+ !utils_1.contains(ruleNames, prop)) {
+ errors.push({
+ msg: "Redundant visitor method: <" + prop + "> on " + lang_extensions_1.functionName(visitorInstance.constructor) + " CST Visitor\n" +
+ "There is no Grammar Rule corresponding to this method's name.\n" +
+ ("For utility methods on visitor classes use methods names that do not match /" + checks_1.validTermsPattern.source + "/."),
+ type: CstVisitorDefinitionError.REDUNDANT_METHOD,
+ methodName: prop
+ });
+ }
+ }
+ return errors;
+}
+exports.validateRedundantMethods = validateRedundantMethods;
+//# sourceMappingURL=cst_visitor.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/errors_public.js b/node_modules/chevrotain/lib/src/parse/errors_public.js
new file mode 100644
index 0000000..539a246
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/errors_public.js
@@ -0,0 +1,205 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var tokens_public_1 = require("../scan/tokens_public");
+var utils = require("../utils/utils");
+var utils_1 = require("../utils/utils");
+var gast_public_1 = require("./grammar/gast/gast_public");
+var gast_1 = require("./grammar/gast/gast");
+var checks_1 = require("./grammar/checks");
+exports.defaultParserErrorProvider = {
+ buildMismatchTokenMessage: function (_a) {
+ var expected = _a.expected, actual = _a.actual, previous = _a.previous, ruleName = _a.ruleName;
+ var hasLabel = tokens_public_1.hasTokenLabel(expected);
+ var expectedMsg = hasLabel
+ ? "--> " + tokens_public_1.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 = 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 prod.terminalType.name;
+ }
+ 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 hasExplicitIndex = index > 0;
+ var msg = "->" + dslName + (hasExplicitIndex ? index : "") + "<- " + (extraArgument ? "with argument: ->" + extraArgument + "<-" : "") + "\n appears more than once (" + duplicateProds.length + " times) in the top level rule: ->" + topLevelName + "<-. \n For further details see: https://sap.github.io/chevrotain/docs/FAQ.html#NUMERICAL_SUFFIXES \n ";
+ // white space trimming time! better to trim afterwards as it allows to use WELL formatted multi line template strings...
+ msg = msg.replace(/[ \t]+/g, " ");
+ msg = msg.replace(/\s\s+/g, "\n");
+ return msg;
+ },
+ buildInvalidNestedRuleNameError: function (topLevelRule, nestedProd) {
+ var msg = "Invalid nested rule name: ->" + nestedProd.name + "<- inside rule: ->" + topLevelRule.name + "<-\n" +
+ ("it must match the pattern: ->" + 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: 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 = utils_1.map(options.prefixPath, function (currTok) {
+ return tokens_public_1.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 = utils_1.map(options.prefixPath, function (currtok) {
+ return tokens_public_1.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 = gast_1.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.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_1.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
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/exceptions_public.js b/node_modules/chevrotain/lib/src/parse/exceptions_public.js
new file mode 100644
index 0000000..1f4cf50
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/exceptions_public.js
@@ -0,0 +1,58 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../utils/utils");
+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 utils_1.contains(RECOGNITION_EXCEPTION_NAMES, error.name);
+}
+exports.isRecognitionException = isRecognitionException;
+function MismatchedTokenException(message, token, previousToken) {
+ this.name = MISMATCHED_TOKEN_EXCEPTION;
+ this.message = message;
+ this.token = token;
+ this.previousToken = previousToken;
+ this.resyncedTokens = [];
+}
+exports.MismatchedTokenException = MismatchedTokenException;
+// 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 = [];
+}
+exports.NoViableAltException = NoViableAltException;
+NoViableAltException.prototype = Error.prototype;
+function NotAllInputParsedException(message, token) {
+ this.name = NOT_ALL_INPUT_PARSED_EXCEPTION;
+ this.message = message;
+ this.token = token;
+ this.resyncedTokens = [];
+}
+exports.NotAllInputParsedException = NotAllInputParsedException;
+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 = [];
+}
+exports.EarlyExitException = EarlyExitException;
+EarlyExitException.prototype = Error.prototype;
+//# sourceMappingURL=exceptions_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/grammar/checks.js b/node_modules/chevrotain/lib/src/parse/grammar/checks.js
new file mode 100644
index 0000000..8ec714c
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/grammar/checks.js
@@ -0,0 +1,590 @@
+"use strict";
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils = require("../../utils/utils");
+var utils_1 = require("../../utils/utils");
+var parser_1 = require("../parser/parser");
+var gast_1 = require("./gast/gast");
+var lookahead_1 = require("./lookahead");
+var cst_1 = require("../cst/cst");
+var interpreter_1 = require("./interpreter");
+var gast_public_1 = require("./gast/gast_public");
+var gast_visitor_public_1 = require("./gast/gast_visitor_public");
+function validateGrammar(topLevels, globalMaxLookahead, tokenTypes, ignoredIssues, errMsgProvider, grammarName) {
+ var duplicateErrors = utils.map(topLevels, function (currTopLevel) {
+ return validateDuplicateProductions(currTopLevel, errMsgProvider);
+ });
+ var leftRecursionErrors = utils.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 (utils_1.every(leftRecursionErrors, utils_1.isEmpty)) {
+ emptyAltErrors = utils_1.map(topLevels, function (currTopRule) {
+ return validateEmptyOrAlternative(currTopRule, errMsgProvider);
+ });
+ ambiguousAltsErrors = utils_1.map(topLevels, function (currTopRule) {
+ return validateAmbiguousAlternationAlternatives(currTopRule, globalMaxLookahead, ignoredIssues, errMsgProvider);
+ });
+ emptyRepetitionErrors = validateSomeNonEmptyLookaheadPath(topLevels, globalMaxLookahead, errMsgProvider);
+ }
+ var termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider);
+ var tokenNameErrors = utils.map(tokenTypes, function (currTokType) {
+ return validateTokenName(currTokType, errMsgProvider);
+ });
+ var nestedRulesNameErrors = validateNestedRulesNames(topLevels, errMsgProvider);
+ var nestedRulesDuplicateErrors = validateDuplicateNestedRules(topLevels, errMsgProvider);
+ var tooManyAltsErrors = utils_1.map(topLevels, function (curRule) {
+ return validateTooManyAlts(curRule, errMsgProvider);
+ });
+ var ruleNameErrors = utils_1.map(topLevels, function (curRule) {
+ return validateRuleName(curRule, errMsgProvider);
+ });
+ var duplicateRulesError = utils_1.map(topLevels, function (curRule) {
+ return validateRuleDoesNotAlreadyExist(curRule, topLevels, grammarName, errMsgProvider);
+ });
+ return (utils.flatten(duplicateErrors.concat(tokenNameErrors, nestedRulesNameErrors, nestedRulesDuplicateErrors, emptyRepetitionErrors, leftRecursionErrors, emptyAltErrors, ambiguousAltsErrors, termsNamespaceConflictErrors, tooManyAltsErrors, ruleNameErrors, duplicateRulesError)));
+}
+exports.validateGrammar = validateGrammar;
+function validateNestedRulesNames(topLevels, errMsgProvider) {
+ var result = [];
+ utils_1.forEach(topLevels, function (curTopLevel) {
+ var namedCollectorVisitor = new cst_1.NamedDSLMethodsCollectorVisitor("");
+ curTopLevel.accept(namedCollectorVisitor);
+ var nestedProds = utils_1.map(namedCollectorVisitor.result, function (currItem) { return currItem.orgProd; });
+ result.push(utils_1.map(nestedProds, function (currNestedProd) {
+ return validateNestedRuleName(curTopLevel, currNestedProd, errMsgProvider);
+ }));
+ });
+ return utils_1.flatten(result);
+}
+function validateDuplicateProductions(topLevelRule, errMsgProvider) {
+ var collectorVisitor = new OccurrenceValidationCollector();
+ topLevelRule.accept(collectorVisitor);
+ var allRuleProductions = collectorVisitor.allProductions;
+ var productionGroups = utils.groupBy(allRuleProductions, identifyProductionForDuplicates);
+ var duplicates = utils.pick(productionGroups, function (currGroup) {
+ return currGroup.length > 1;
+ });
+ var errors = utils.map(utils.values(duplicates), function (currDuplicates) {
+ var firstProd = utils.first(currDuplicates);
+ var msg = errMsgProvider.buildDuplicateFoundError(topLevelRule, currDuplicates);
+ var dslName = gast_1.getProductionDslName(firstProd);
+ var defError = {
+ message: msg,
+ type: parser_1.ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,
+ ruleName: topLevelRule.name,
+ dslName: dslName,
+ occurrence: firstProd.idx
+ };
+ var param = getExtraProductionArgument(firstProd);
+ if (param) {
+ defError.parameter = param;
+ }
+ return defError;
+ });
+ return errors;
+}
+function identifyProductionForDuplicates(prod) {
+ return gast_1.getProductionDslName(prod) + "_#_" + prod.idx + "_#_" + getExtraProductionArgument(prod);
+}
+exports.identifyProductionForDuplicates = identifyProductionForDuplicates;
+function getExtraProductionArgument(prod) {
+ if (prod instanceof gast_public_1.Terminal) {
+ return prod.terminalType.name;
+ }
+ else if (prod instanceof gast_public_1.NonTerminal) {
+ return prod.nonTerminalName;
+ }
+ else {
+ return "";
+ }
+}
+var OccurrenceValidationCollector = /** @class */ (function (_super) {
+ __extends(OccurrenceValidationCollector, _super);
+ function OccurrenceValidationCollector() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.allProductions = [];
+ return _this;
+ }
+ OccurrenceValidationCollector.prototype.visitNonTerminal = function (subrule) {
+ this.allProductions.push(subrule);
+ };
+ OccurrenceValidationCollector.prototype.visitOption = function (option) {
+ this.allProductions.push(option);
+ };
+ OccurrenceValidationCollector.prototype.visitRepetitionWithSeparator = function (manySep) {
+ this.allProductions.push(manySep);
+ };
+ OccurrenceValidationCollector.prototype.visitRepetitionMandatory = function (atLeastOne) {
+ this.allProductions.push(atLeastOne);
+ };
+ OccurrenceValidationCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) {
+ this.allProductions.push(atLeastOneSep);
+ };
+ OccurrenceValidationCollector.prototype.visitRepetition = function (many) {
+ this.allProductions.push(many);
+ };
+ OccurrenceValidationCollector.prototype.visitAlternation = function (or) {
+ this.allProductions.push(or);
+ };
+ OccurrenceValidationCollector.prototype.visitTerminal = function (terminal) {
+ this.allProductions.push(terminal);
+ };
+ return OccurrenceValidationCollector;
+}(gast_visitor_public_1.GAstVisitor));
+exports.OccurrenceValidationCollector = OccurrenceValidationCollector;
+exports.validTermsPattern = /^[a-zA-Z_]\w*$/;
+exports.validNestedRuleName = new RegExp(exports.validTermsPattern.source.replace("^", "^\\$"));
+// TODO: remove this limitation now that we use recorders
+function validateRuleName(rule, errMsgProvider) {
+ var errors = [];
+ var ruleName = rule.name;
+ if (!ruleName.match(exports.validTermsPattern)) {
+ errors.push({
+ message: errMsgProvider.buildInvalidRuleNameError({
+ topLevelRule: rule,
+ expectedPattern: exports.validTermsPattern
+ }),
+ type: parser_1.ParserDefinitionErrorType.INVALID_RULE_NAME,
+ ruleName: ruleName
+ });
+ }
+ return errors;
+}
+exports.validateRuleName = validateRuleName;
+// TODO: did the nested rule name regExp now change?
+function validateNestedRuleName(topLevel, nestedProd, errMsgProvider) {
+ var errors = [];
+ var errMsg;
+ if (!nestedProd.name.match(exports.validNestedRuleName)) {
+ errMsg = errMsgProvider.buildInvalidNestedRuleNameError(topLevel, nestedProd);
+ errors.push({
+ message: errMsg,
+ type: parser_1.ParserDefinitionErrorType.INVALID_NESTED_RULE_NAME,
+ ruleName: topLevel.name
+ });
+ }
+ return errors;
+}
+exports.validateNestedRuleName = validateNestedRuleName;
+// TODO: remove this limitation now that we use recorders
+function validateTokenName(tokenType, errMsgProvider) {
+ var errors = [];
+ var tokTypeName = tokenType.name;
+ if (!tokTypeName.match(exports.validTermsPattern)) {
+ errors.push({
+ message: errMsgProvider.buildTokenNameError({
+ tokenType: tokenType,
+ expectedPattern: exports.validTermsPattern
+ }),
+ type: parser_1.ParserDefinitionErrorType.INVALID_TOKEN_NAME
+ });
+ }
+ return errors;
+}
+exports.validateTokenName = validateTokenName;
+function validateRuleDoesNotAlreadyExist(rule, allRules, className, errMsgProvider) {
+ var errors = [];
+ var occurrences = utils_1.reduce(allRules, function (result, curRule) {
+ if (curRule.name === rule.name) {
+ return result + 1;
+ }
+ return result;
+ }, 0);
+ if (occurrences > 1) {
+ var errMsg = errMsgProvider.buildDuplicateRuleNameError({
+ topLevelRule: rule,
+ grammarName: className
+ });
+ errors.push({
+ message: errMsg,
+ type: parser_1.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,
+ ruleName: rule.name
+ });
+ }
+ return errors;
+}
+exports.validateRuleDoesNotAlreadyExist = validateRuleDoesNotAlreadyExist;
+// 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.contains(definedRulesNames, ruleName)) {
+ errMsg =
+ "Invalid rule override, rule: ->" + ruleName + "<- cannot be overridden in the grammar: ->" + className + "<-" +
+ "as it is not defined in any of the super grammars ";
+ errors.push({
+ message: errMsg,
+ type: parser_1.ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,
+ ruleName: ruleName
+ });
+ }
+ return errors;
+}
+exports.validateRuleIsOverridden = validateRuleIsOverridden;
+function validateNoLeftRecursion(topRule, currRule, errMsgProvider, path) {
+ if (path === void 0) { path = []; }
+ var errors = [];
+ var nextNonTerminals = getFirstNoneTerminal(currRule.definition);
+ if (utils.isEmpty(nextNonTerminals)) {
+ return [];
+ }
+ else {
+ var ruleName = topRule.name;
+ var foundLeftRecursion = utils.contains(nextNonTerminals, topRule);
+ if (foundLeftRecursion) {
+ errors.push({
+ message: errMsgProvider.buildLeftRecursionError({
+ topLevelRule: topRule,
+ leftRecursionPath: path
+ }),
+ type: parser_1.ParserDefinitionErrorType.LEFT_RECURSION,
+ ruleName: ruleName
+ });
+ }
+ // we are only looking for cyclic paths leading back to the specific topRule
+ // other cyclic paths are ignored, we still need this difference to avoid infinite loops...
+ var validNextSteps = utils.difference(nextNonTerminals, path.concat([topRule]));
+ var errorsFromNextSteps = utils.map(validNextSteps, function (currRefRule) {
+ var newPath = utils.cloneArr(path);
+ newPath.push(currRefRule);
+ return validateNoLeftRecursion(topRule, currRefRule, errMsgProvider, newPath);
+ });
+ return errors.concat(utils.flatten(errorsFromNextSteps));
+ }
+}
+exports.validateNoLeftRecursion = validateNoLeftRecursion;
+function getFirstNoneTerminal(definition) {
+ var result = [];
+ if (utils.isEmpty(definition)) {
+ return result;
+ }
+ var firstProd = utils.first(definition);
+ /* istanbul ignore else */
+ if (firstProd instanceof gast_public_1.NonTerminal) {
+ result.push(firstProd.referencedRule);
+ }
+ else if (firstProd instanceof gast_public_1.Flat ||
+ firstProd instanceof gast_public_1.Option ||
+ firstProd instanceof gast_public_1.RepetitionMandatory ||
+ firstProd instanceof gast_public_1.RepetitionMandatoryWithSeparator ||
+ firstProd instanceof gast_public_1.RepetitionWithSeparator ||
+ firstProd instanceof gast_public_1.Repetition) {
+ result = result.concat(getFirstNoneTerminal(firstProd.definition));
+ }
+ else if (firstProd instanceof gast_public_1.Alternation) {
+ // each sub definition in alternation is a FLAT
+ result = utils.flatten(utils.map(firstProd.definition, function (currSubDef) {
+ return getFirstNoneTerminal(currSubDef.definition);
+ }));
+ }
+ else if (firstProd instanceof gast_public_1.Terminal) {
+ // nothing to see, move along
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ var isFirstOptional = gast_1.isOptionalProd(firstProd);
+ var hasMore = definition.length > 1;
+ if (isFirstOptional && hasMore) {
+ var rest = utils.drop(definition);
+ return result.concat(getFirstNoneTerminal(rest));
+ }
+ else {
+ return result;
+ }
+}
+exports.getFirstNoneTerminal = getFirstNoneTerminal;
+var OrCollector = /** @class */ (function (_super) {
+ __extends(OrCollector, _super);
+ function OrCollector() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.alternations = [];
+ return _this;
+ }
+ OrCollector.prototype.visitAlternation = function (node) {
+ this.alternations.push(node);
+ };
+ return OrCollector;
+}(gast_visitor_public_1.GAstVisitor));
+function validateEmptyOrAlternative(topLevelRule, errMsgProvider) {
+ var orCollector = new OrCollector();
+ topLevelRule.accept(orCollector);
+ var ors = orCollector.alternations;
+ var errors = utils.reduce(ors, function (errors, currOr) {
+ var exceptLast = utils.dropRight(currOr.definition);
+ var currErrors = utils.map(exceptLast, function (currAlternative, currAltIdx) {
+ var possibleFirstInAlt = interpreter_1.nextPossibleTokensAfter([currAlternative], [], null, 1);
+ if (utils.isEmpty(possibleFirstInAlt)) {
+ return {
+ message: errMsgProvider.buildEmptyAlternationError({
+ topLevelRule: topLevelRule,
+ alternation: currOr,
+ emptyChoiceIdx: currAltIdx
+ }),
+ type: parser_1.ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,
+ ruleName: topLevelRule.name,
+ occurrence: currOr.idx,
+ alternative: currAltIdx + 1
+ };
+ }
+ else {
+ return null;
+ }
+ });
+ return errors.concat(utils.compact(currErrors));
+ }, []);
+ return errors;
+}
+exports.validateEmptyOrAlternative = validateEmptyOrAlternative;
+function validateAmbiguousAlternationAlternatives(topLevelRule, globalMaxLookahead, ignoredIssues, errMsgProvider) {
+ var orCollector = new OrCollector();
+ topLevelRule.accept(orCollector);
+ var ors = orCollector.alternations;
+ // TODO: this filtering should be deprecated once we remove the ignoredIssues
+ // IParserConfig property
+ var ignoredIssuesForCurrentRule = ignoredIssues[topLevelRule.name];
+ if (ignoredIssuesForCurrentRule) {
+ ors = utils_1.reject(ors, function (currOr) {
+ return ignoredIssuesForCurrentRule[gast_1.getProductionDslName(currOr) +
+ (currOr.idx === 0 ? "" : currOr.idx)];
+ });
+ }
+ // New Handling of ignoring ambiguities
+ // - https://github.com/SAP/chevrotain/issues/869
+ ors = utils_1.reject(ors, function (currOr) { return currOr.ignoreAmbiguities === true; });
+ var errors = utils.reduce(ors, function (result, currOr) {
+ var currOccurrence = currOr.idx;
+ var actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead;
+ var alternatives = lookahead_1.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;
+}
+exports.validateAmbiguousAlternationAlternatives = validateAmbiguousAlternationAlternatives;
+var RepetionCollector = /** @class */ (function (_super) {
+ __extends(RepetionCollector, _super);
+ function RepetionCollector() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.allProductions = [];
+ return _this;
+ }
+ RepetionCollector.prototype.visitRepetitionWithSeparator = function (manySep) {
+ this.allProductions.push(manySep);
+ };
+ RepetionCollector.prototype.visitRepetitionMandatory = function (atLeastOne) {
+ this.allProductions.push(atLeastOne);
+ };
+ RepetionCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) {
+ this.allProductions.push(atLeastOneSep);
+ };
+ RepetionCollector.prototype.visitRepetition = function (many) {
+ this.allProductions.push(many);
+ };
+ return RepetionCollector;
+}(gast_visitor_public_1.GAstVisitor));
+exports.RepetionCollector = RepetionCollector;
+function validateTooManyAlts(topLevelRule, errMsgProvider) {
+ var orCollector = new OrCollector();
+ topLevelRule.accept(orCollector);
+ var ors = orCollector.alternations;
+ var errors = utils.reduce(ors, function (errors, currOr) {
+ if (currOr.definition.length > 255) {
+ errors.push({
+ message: errMsgProvider.buildTooManyAlternativesError({
+ topLevelRule: topLevelRule,
+ alternation: currOr
+ }),
+ type: parser_1.ParserDefinitionErrorType.TOO_MANY_ALTS,
+ ruleName: topLevelRule.name,
+ occurrence: currOr.idx
+ });
+ }
+ return errors;
+ }, []);
+ return errors;
+}
+exports.validateTooManyAlts = validateTooManyAlts;
+function validateSomeNonEmptyLookaheadPath(topLevelRules, maxLookahead, errMsgProvider) {
+ var errors = [];
+ utils_1.forEach(topLevelRules, function (currTopRule) {
+ var collectorVisitor = new RepetionCollector();
+ currTopRule.accept(collectorVisitor);
+ var allRuleProductions = collectorVisitor.allProductions;
+ utils_1.forEach(allRuleProductions, function (currProd) {
+ var prodType = lookahead_1.getProdType(currProd);
+ var actualMaxLookahead = currProd.maxLookahead || maxLookahead;
+ var currOccurrence = currProd.idx;
+ var paths = lookahead_1.getLookaheadPathsForOptionalProd(currOccurrence, currTopRule, prodType, actualMaxLookahead);
+ var pathsInsideProduction = paths[0];
+ if (utils_1.isEmpty(utils_1.flatten(pathsInsideProduction))) {
+ var errMsg = errMsgProvider.buildEmptyRepetitionError({
+ topLevelRule: currTopRule,
+ repetition: currProd
+ });
+ errors.push({
+ message: errMsg,
+ type: parser_1.ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,
+ ruleName: currTopRule.name
+ });
+ }
+ });
+ });
+ return errors;
+}
+exports.validateSomeNonEmptyLookaheadPath = validateSomeNonEmptyLookaheadPath;
+function checkAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) {
+ var foundAmbiguousPaths = [];
+ var identicalAmbiguities = utils_1.reduce(alternatives, function (result, currAlt, currAltIdx) {
+ // ignore (skip) ambiguities with this alternative
+ if (alternation.definition[currAltIdx].ignoreAmbiguities === true) {
+ return result;
+ }
+ utils_1.forEach(currAlt, function (currPath) {
+ var altsCurrPathAppearsIn = [currAltIdx];
+ utils_1.forEach(alternatives, function (currOtherAlt, currOtherAltIdx) {
+ if (currAltIdx !== currOtherAltIdx &&
+ lookahead_1.containsPath(currOtherAlt, currPath) &&
+ // ignore (skip) ambiguities with this "other" alternative
+ alternation.definition[currOtherAltIdx]
+ .ignoreAmbiguities !== true) {
+ altsCurrPathAppearsIn.push(currOtherAltIdx);
+ }
+ });
+ if (altsCurrPathAppearsIn.length > 1 &&
+ !lookahead_1.containsPath(foundAmbiguousPaths, currPath)) {
+ foundAmbiguousPaths.push(currPath);
+ result.push({
+ alts: altsCurrPathAppearsIn,
+ path: currPath
+ });
+ }
+ });
+ return result;
+ }, []);
+ var currErrors = utils.map(identicalAmbiguities, function (currAmbDescriptor) {
+ var ambgIndices = utils_1.map(currAmbDescriptor.alts, function (currAltIdx) { return currAltIdx + 1; });
+ var currMessage = errMsgProvider.buildAlternationAmbiguityError({
+ topLevelRule: rule,
+ alternation: alternation,
+ ambiguityIndices: ambgIndices,
+ prefixPath: currAmbDescriptor.path
+ });
+ return {
+ message: currMessage,
+ type: parser_1.ParserDefinitionErrorType.AMBIGUOUS_ALTS,
+ ruleName: rule.name,
+ occurrence: alternation.idx,
+ alternatives: [currAmbDescriptor.alts]
+ };
+ });
+ return currErrors;
+}
+function checkPrefixAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) {
+ var errors = [];
+ // flatten
+ var pathsAndIndices = utils_1.reduce(alternatives, function (result, currAlt, idx) {
+ var currPathsAndIdx = utils_1.map(currAlt, function (currPath) {
+ return { idx: idx, path: currPath };
+ });
+ return result.concat(currPathsAndIdx);
+ }, []);
+ utils_1.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 = utils_1.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.
+ lookahead_1.isStrictPrefixOfPath(searchPathAndIdx.path, targetPath));
+ });
+ var currPathPrefixErrors = utils_1.map(prefixAmbiguitiesPathsAndIndices, function (currAmbPathAndIdx) {
+ var ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1];
+ var occurrence = alternation.idx === 0 ? "" : alternation.idx;
+ var message = errMsgProvider.buildAlternationPrefixAmbiguityError({
+ topLevelRule: rule,
+ alternation: alternation,
+ ambiguityIndices: ambgIndices,
+ prefixPath: currAmbPathAndIdx.path
+ });
+ return {
+ message: message,
+ type: parser_1.ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS,
+ ruleName: rule.name,
+ occurrence: occurrence,
+ alternatives: ambgIndices
+ };
+ });
+ errors = errors.concat(currPathPrefixErrors);
+ });
+ return errors;
+}
+exports.checkPrefixAlternativesAmbiguities = checkPrefixAlternativesAmbiguities;
+function checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider) {
+ var errors = [];
+ var tokenNames = utils_1.map(tokenTypes, function (currToken) { return currToken.name; });
+ utils_1.forEach(topLevels, function (currRule) {
+ var currRuleName = currRule.name;
+ if (utils_1.contains(tokenNames, currRuleName)) {
+ var errMsg = errMsgProvider.buildNamespaceConflictError(currRule);
+ errors.push({
+ message: errMsg,
+ type: parser_1.ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,
+ ruleName: currRuleName
+ });
+ }
+ });
+ return errors;
+}
+function validateDuplicateNestedRules(topLevelRules, errMsgProvider) {
+ var errors = [];
+ utils_1.forEach(topLevelRules, function (currTopRule) {
+ var namedCollectorVisitor = new cst_1.NamedDSLMethodsCollectorVisitor("");
+ currTopRule.accept(namedCollectorVisitor);
+ var prodsByGroup = utils_1.groupBy(namedCollectorVisitor.result, function (item) { return item.name; });
+ var duplicates = utils_1.pick(prodsByGroup, function (currGroup) {
+ return currGroup.length > 1;
+ });
+ utils_1.forEach(utils_1.values(duplicates), function (currDupGroup) {
+ var currDupProds = utils_1.map(currDupGroup, function (dupGroup) { return dupGroup.orgProd; });
+ var errMsg = errMsgProvider.buildDuplicateNestedRuleNameError(currTopRule, currDupProds);
+ errors.push({
+ message: errMsg,
+ type: parser_1.ParserDefinitionErrorType.DUPLICATE_NESTED_NAME,
+ ruleName: currTopRule.name
+ });
+ });
+ });
+ return errors;
+}
+//# sourceMappingURL=checks.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/grammar/first.js b/node_modules/chevrotain/lib/src/parse/grammar/first.js
new file mode 100644
index 0000000..0cc4def
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/grammar/first.js
@@ -0,0 +1,63 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../../utils/utils");
+var gast_public_1 = require("./gast/gast_public");
+var gast_1 = require("./gast/gast");
+function first(prod) {
+ /* istanbul ignore else */
+ if (prod instanceof gast_public_1.NonTerminal) {
+ // this could in theory cause infinite loops if
+ // (1) prod A refs prod B.
+ // (2) prod B refs prod A
+ // (3) AB can match the empty set
+ // in other words a cycle where everything is optional so the first will keep
+ // looking ahead for the next optional part and will never exit
+ // currently there is no safeguard for this unique edge case because
+ // (1) not sure a grammar in which this can happen is useful for anything (productive)
+ return first(prod.referencedRule);
+ }
+ else if (prod instanceof gast_public_1.Terminal) {
+ return firstForTerminal(prod);
+ }
+ else if (gast_1.isSequenceProd(prod)) {
+ return firstForSequence(prod);
+ }
+ else if (gast_1.isBranchingProd(prod)) {
+ return firstForBranching(prod);
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+exports.first = first;
+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 = gast_1.isOptionalProd(currSubProd);
+ firstSet = firstSet.concat(first(currSubProd));
+ nextSubProdIdx = nextSubProdIdx + 1;
+ hasInnerProdsRemaining = seq.length > nextSubProdIdx;
+ }
+ return utils_1.uniq(firstSet);
+}
+exports.firstForSequence = firstForSequence;
+function firstForBranching(prod) {
+ var allAlternativesFirsts = utils_1.map(prod.definition, function (innerProd) {
+ return first(innerProd);
+ });
+ return utils_1.uniq(utils_1.flatten(allAlternativesFirsts));
+}
+exports.firstForBranching = firstForBranching;
+function firstForTerminal(terminal) {
+ return [terminal.terminalType];
+}
+exports.firstForTerminal = firstForTerminal;
+//# sourceMappingURL=first.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/grammar/follow.js b/node_modules/chevrotain/lib/src/parse/grammar/follow.js
new file mode 100644
index 0000000..e8106a0
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/grammar/follow.js
@@ -0,0 +1,67 @@
+"use strict";
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var rest_1 = require("./rest");
+var first_1 = require("./first");
+var utils_1 = require("../../utils/utils");
+var constants_1 = require("../constants");
+var gast_public_1 = require("./gast/gast_public");
+// This ResyncFollowsWalker computes all of the follows required for RESYNC
+// (skipping reference production).
+var ResyncFollowsWalker = /** @class */ (function (_super) {
+ __extends(ResyncFollowsWalker, _super);
+ function ResyncFollowsWalker(topProd) {
+ var _this = _super.call(this) || this;
+ _this.topProd = topProd;
+ _this.follows = {};
+ return _this;
+ }
+ ResyncFollowsWalker.prototype.startWalking = function () {
+ this.walk(this.topProd);
+ return this.follows;
+ };
+ ResyncFollowsWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) {
+ // do nothing! just like in the public sector after 13:00
+ };
+ ResyncFollowsWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) {
+ var followName = buildBetweenProdsFollowPrefix(refProd.referencedRule, refProd.idx) +
+ this.topProd.name;
+ var fullRest = currRest.concat(prevRest);
+ var restProd = new gast_public_1.Flat({ definition: fullRest });
+ var t_in_topProd_follows = first_1.first(restProd);
+ this.follows[followName] = t_in_topProd_follows;
+ };
+ return ResyncFollowsWalker;
+}(rest_1.RestWalker));
+exports.ResyncFollowsWalker = ResyncFollowsWalker;
+function computeAllProdsFollows(topProductions) {
+ var reSyncFollows = {};
+ utils_1.forEach(topProductions, function (topProd) {
+ var currRefsFollow = new ResyncFollowsWalker(topProd).startWalking();
+ utils_1.assign(reSyncFollows, currRefsFollow);
+ });
+ return reSyncFollows;
+}
+exports.computeAllProdsFollows = computeAllProdsFollows;
+function buildBetweenProdsFollowPrefix(inner, occurenceInParent) {
+ return inner.name + occurenceInParent + constants_1.IN;
+}
+exports.buildBetweenProdsFollowPrefix = buildBetweenProdsFollowPrefix;
+function buildInProdFollowPrefix(terminal) {
+ var terminalName = terminal.terminalType.name;
+ return terminalName + terminal.idx + constants_1.IN;
+}
+exports.buildInProdFollowPrefix = buildInProdFollowPrefix;
+//# sourceMappingURL=follow.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/grammar/gast/gast.js b/node_modules/chevrotain/lib/src/parse/grammar/gast/gast.js
new file mode 100644
index 0000000..c202b58
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/grammar/gast/gast.js
@@ -0,0 +1,170 @@
+"use strict";
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../../../utils/utils");
+var gast_public_1 = require("./gast_public");
+var gast_visitor_public_1 = require("./gast_visitor_public");
+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) {
+ /* istanbul ignore else */
+ 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 {
+ throw Error("non exhaustive match");
+ }
+}
+exports.getProductionDslName = getProductionDslName;
+var DslMethodsCollectorVisitor = /** @class */ (function (_super) {
+ __extends(DslMethodsCollectorVisitor, _super);
+ function DslMethodsCollectorVisitor() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ // A minus is never valid in an identifier name
+ _this.separator = "-";
+ _this.dslMethods = {
+ option: [],
+ alternation: [],
+ repetition: [],
+ repetitionWithSeparator: [],
+ repetitionMandatory: [],
+ repetitionMandatoryWithSeparator: []
+ };
+ return _this;
+ }
+ DslMethodsCollectorVisitor.prototype.reset = function () {
+ this.dslMethods = {
+ option: [],
+ alternation: [],
+ repetition: [],
+ repetitionWithSeparator: [],
+ repetitionMandatory: [],
+ repetitionMandatoryWithSeparator: []
+ };
+ };
+ DslMethodsCollectorVisitor.prototype.visitTerminal = function (terminal) {
+ var key = terminal.terminalType.name + this.separator + "Terminal";
+ if (!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;
+var collectorVisitor = new DslMethodsCollectorVisitor();
+function collectMethods(rule) {
+ collectorVisitor.reset();
+ rule.accept(collectorVisitor);
+ var dslMethods = collectorVisitor.dslMethods;
+ // avoid uncleaned references
+ collectorVisitor.reset();
+ return dslMethods;
+}
+exports.collectMethods = collectMethods;
+//# sourceMappingURL=gast.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/grammar/gast/gast_public.js b/node_modules/chevrotain/lib/src/parse/grammar/gast/gast_public.js
new file mode 100644
index 0000000..8b0ceb5
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/grammar/gast/gast_public.js
@@ -0,0 +1,262 @@
+"use strict";
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../../../utils/utils");
+var tokens_public_1 = require("../../../scan/tokens_public");
+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, utils_1.pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ Object.defineProperty(NonTerminal.prototype, "definition", {
+ get: function () {
+ if (this.referencedRule !== undefined) {
+ return this.referencedRule.definition;
+ }
+ return [];
+ },
+ set: function (definition) {
+ // immutable
+ },
+ enumerable: true,
+ configurable: true
+ });
+ NonTerminal.prototype.accept = function (visitor) {
+ visitor.visit(this);
+ // don't visit children of a reference, we will get cyclic infinite loops if we do so
+ };
+ return NonTerminal;
+}(AbstractProduction));
+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, utils_1.pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ return Rule;
+}(AbstractProduction));
+exports.Rule = Rule;
+// TODO: is this only used in an Alternation?
+// Perhaps `Flat` should be renamed to `Alternative`?
+var Flat = /** @class */ (function (_super) {
+ __extends(Flat, _super);
+ // A named Flat production is used to indicate a Nested Rule in an alternation
+ function Flat(options) {
+ var _this = _super.call(this, options.definition) || this;
+ _this.ignoreAmbiguities = false;
+ utils_1.assign(_this, utils_1.pick(options, function (v) { return v !== undefined; }));
+ 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, utils_1.pick(options, function (v) { return v !== undefined; }));
+ 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, utils_1.pick(options, function (v) { return v !== undefined; }));
+ 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, utils_1.pick(options, function (v) { return v !== undefined; }));
+ 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, utils_1.pick(options, function (v) { return v !== undefined; }));
+ 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, utils_1.pick(options, function (v) { return v !== undefined; }));
+ 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;
+ _this.ignoreAmbiguities = false;
+ _this.hasPredicates = false;
+ utils_1.assign(_this, utils_1.pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ return Alternation;
+}(AbstractProduction));
+exports.Alternation = Alternation;
+var Terminal = /** @class */ (function () {
+ function Terminal(options) {
+ this.idx = 1;
+ utils_1.assign(this, utils_1.pick(options, function (v) { return v !== undefined; }));
+ }
+ 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);
+ }
+ /* istanbul ignore else */
+ if (node instanceof NonTerminal) {
+ return {
+ type: "NonTerminal",
+ name: node.nonTerminalName,
+ idx: node.idx
+ };
+ }
+ else if (node instanceof Flat) {
+ return {
+ type: "Flat",
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof Option) {
+ return {
+ type: "Option",
+ idx: node.idx,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof RepetitionMandatory) {
+ return {
+ type: "RepetitionMandatory",
+ name: node.name,
+ idx: node.idx,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof RepetitionMandatoryWithSeparator) {
+ return {
+ type: "RepetitionMandatoryWithSeparator",
+ name: node.name,
+ idx: node.idx,
+ separator: (serializeProduction(new Terminal({ terminalType: node.separator }))),
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof RepetitionWithSeparator) {
+ return {
+ type: "RepetitionWithSeparator",
+ name: node.name,
+ idx: node.idx,
+ separator: (serializeProduction(new Terminal({ terminalType: node.separator }))),
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof Repetition) {
+ return {
+ type: "Repetition",
+ name: node.name,
+ idx: node.idx,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof Alternation) {
+ return {
+ type: "Alternation",
+ name: node.name,
+ idx: node.idx,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof Terminal) {
+ var serializedTerminal = {
+ type: "Terminal",
+ name: node.terminalType.name,
+ label: 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) {
+ return {
+ type: "Rule",
+ name: node.name,
+ orgText: node.orgText,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+exports.serializeProduction = serializeProduction;
+//# sourceMappingURL=gast_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/grammar/gast/gast_resolver_public.js b/node_modules/chevrotain/lib/src/parse/grammar/gast/gast_resolver_public.js
new file mode 100644
index 0000000..f47165b
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/grammar/gast/gast_resolver_public.js
@@ -0,0 +1,39 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../../../utils/utils");
+var resolver_1 = require("../resolver");
+var checks_1 = require("../checks");
+var errors_public_1 = require("../../errors_public");
+var gast_1 = require("./gast");
+function resolveGrammar(options) {
+ options = utils_1.defaults(options, {
+ errMsgProvider: errors_public_1.defaultGrammarResolverErrorProvider
+ });
+ var topRulesTable = {};
+ utils_1.forEach(options.rules, function (rule) {
+ topRulesTable[rule.name] = rule;
+ });
+ return resolver_1.resolveGrammar(topRulesTable, options.errMsgProvider);
+}
+exports.resolveGrammar = resolveGrammar;
+function validateGrammar(options) {
+ options = utils_1.defaults(options, {
+ errMsgProvider: errors_public_1.defaultGrammarValidatorErrorProvider,
+ ignoredIssues: {}
+ });
+ return checks_1.validateGrammar(options.rules, options.maxLookahead, options.tokenTypes, options.ignoredIssues, options.errMsgProvider, options.grammarName);
+}
+exports.validateGrammar = validateGrammar;
+function assignOccurrenceIndices(options) {
+ utils_1.forEach(options.rules, function (currRule) {
+ var methodsCollector = new gast_1.DslMethodsCollectorVisitor();
+ currRule.accept(methodsCollector);
+ utils_1.forEach(methodsCollector.dslMethods, function (methods) {
+ utils_1.forEach(methods, function (currMethod, arrIdx) {
+ currMethod.idx = arrIdx + 1;
+ });
+ });
+ });
+}
+exports.assignOccurrenceIndices = assignOccurrenceIndices;
+//# sourceMappingURL=gast_resolver_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/grammar/gast/gast_visitor_public.js b/node_modules/chevrotain/lib/src/parse/grammar/gast/gast_visitor_public.js
new file mode 100644
index 0000000..baf298d
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/grammar/gast/gast_visitor_public.js
@@ -0,0 +1,48 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var gast_public_1 = require("./gast_public");
+var GAstVisitor = /** @class */ (function () {
+ function GAstVisitor() {
+ }
+ GAstVisitor.prototype.visit = function (node) {
+ var nodeAny = node;
+ switch (nodeAny.constructor) {
+ case gast_public_1.NonTerminal:
+ return this.visitNonTerminal(nodeAny);
+ case gast_public_1.Flat:
+ return this.visitFlat(nodeAny);
+ case gast_public_1.Option:
+ return this.visitOption(nodeAny);
+ case gast_public_1.RepetitionMandatory:
+ return this.visitRepetitionMandatory(nodeAny);
+ case gast_public_1.RepetitionMandatoryWithSeparator:
+ return this.visitRepetitionMandatoryWithSeparator(nodeAny);
+ case gast_public_1.RepetitionWithSeparator:
+ return this.visitRepetitionWithSeparator(nodeAny);
+ case gast_public_1.Repetition:
+ return this.visitRepetition(nodeAny);
+ case gast_public_1.Alternation:
+ return this.visitAlternation(nodeAny);
+ case gast_public_1.Terminal:
+ return this.visitTerminal(nodeAny);
+ case gast_public_1.Rule:
+ return this.visitRule(nodeAny);
+ /* istanbul ignore next */
+ default:
+ throw Error("non exhaustive match");
+ }
+ };
+ GAstVisitor.prototype.visitNonTerminal = function (node) { };
+ GAstVisitor.prototype.visitFlat = function (node) { };
+ GAstVisitor.prototype.visitOption = function (node) { };
+ GAstVisitor.prototype.visitRepetition = function (node) { };
+ GAstVisitor.prototype.visitRepetitionMandatory = function (node) { };
+ GAstVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { };
+ GAstVisitor.prototype.visitRepetitionWithSeparator = function (node) { };
+ GAstVisitor.prototype.visitAlternation = function (node) { };
+ GAstVisitor.prototype.visitTerminal = function (node) { };
+ GAstVisitor.prototype.visitRule = function (node) { };
+ return GAstVisitor;
+}());
+exports.GAstVisitor = GAstVisitor;
+//# sourceMappingURL=gast_visitor_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/grammar/interpreter.js b/node_modules/chevrotain/lib/src/parse/grammar/interpreter.js
new file mode 100644
index 0000000..5682c6d
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/grammar/interpreter.js
@@ -0,0 +1,548 @@
+"use strict";
+/* istanbul ignore next */ var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var rest_1 = require("./rest");
+var utils_1 = require("../../utils/utils");
+var first_1 = require("./first");
+var gast_public_1 = require("./gast/gast_public");
+var AbstractNextPossibleTokensWalker = /** @class */ (function (_super) {
+ __extends(AbstractNextPossibleTokensWalker, _super);
+ function AbstractNextPossibleTokensWalker(topProd, path) {
+ var _this = _super.call(this) /* istanbul ignore next */ || 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 = utils_1.cloneArr(this.path.ruleStack).reverse(); // intelij bug requires assertion
+ this.occurrenceStack = utils_1.cloneArr(this.path.occurrenceStack).reverse(); // intelij bug requires assertion
+ // already verified that the first production is valid, we now seek the 2nd production
+ this.ruleStack.pop();
+ this.occurrenceStack.pop();
+ this.updateExpectedNext();
+ this.walk(this.topProd);
+ return this.possibleTokTypes;
+ };
+ AbstractNextPossibleTokensWalker.prototype.walk = function (prod, prevRest) {
+ if (prevRest === void 0) { prevRest = []; }
+ // stop scanning once we found the path
+ if (!this.found) {
+ _super.prototype.walk.call(this, prod, prevRest);
+ }
+ };
+ AbstractNextPossibleTokensWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) {
+ // found the next production, need to keep walking in it
+ if (refProd.referencedRule.name === this.nextProductionName &&
+ refProd.idx === this.nextProductionOccurrence) {
+ var fullRest = currRest.concat(prevRest);
+ this.updateExpectedNext();
+ this.walk(refProd.referencedRule, fullRest);
+ }
+ };
+ AbstractNextPossibleTokensWalker.prototype.updateExpectedNext = function () {
+ // need to consume the Terminal
+ if (utils_1.isEmpty(this.ruleStack)) {
+ // must reset nextProductionXXX to avoid walking down another Top Level production while what we are
+ // really seeking is the last Terminal...
+ this.nextProductionName = "";
+ this.nextProductionOccurrence = 0;
+ this.isAtEndOfPath = true;
+ }
+ else {
+ this.nextProductionName = this.ruleStack.pop();
+ this.nextProductionOccurrence = this.occurrenceStack.pop();
+ }
+ };
+ return AbstractNextPossibleTokensWalker;
+}(rest_1.RestWalker));
+exports.AbstractNextPossibleTokensWalker = AbstractNextPossibleTokensWalker;
+var NextAfterTokenWalker = /** @class */ (function (_super) {
+ __extends(NextAfterTokenWalker, _super);
+ function NextAfterTokenWalker(topProd, path) {
+ var _this = _super.call(this, topProd, path) /* istanbul ignore next */ || 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_1.Flat({ definition: fullRest });
+ this.possibleTokTypes = first_1.first(restProd);
+ this.found = true;
+ }
+ };
+ return NextAfterTokenWalker;
+}(AbstractNextPossibleTokensWalker));
+exports.NextAfterTokenWalker = NextAfterTokenWalker;
+/**
+ * This walker only "walks" a single "TOP" level in the Grammar Ast, this means
+ * it never "follows" production refs
+ */
+var AbstractNextTerminalAfterProductionWalker = /** @class */ (function (_super) {
+ __extends(AbstractNextTerminalAfterProductionWalker, _super);
+ function AbstractNextTerminalAfterProductionWalker(topRule, occurrence) {
+ var _this = _super.call(this) /* istanbul ignore next */ || 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_1.RestWalker));
+exports.AbstractNextTerminalAfterProductionWalker = AbstractNextTerminalAfterProductionWalker;
+var NextTerminalAfterManyWalker = /** @class */ (function (_super) {
+ __extends(NextTerminalAfterManyWalker, _super);
+ function NextTerminalAfterManyWalker() {
+ return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this;
+ }
+ NextTerminalAfterManyWalker.prototype.walkMany = function (manyProd, currRest, prevRest) {
+ if (manyProd.idx === this.occurrence) {
+ var firstAfterMany = utils_1.first(currRest.concat(prevRest));
+ this.result.isEndOfRule = firstAfterMany === undefined;
+ if (firstAfterMany instanceof gast_public_1.Terminal) {
+ this.result.token = firstAfterMany.terminalType;
+ this.result.occurrence = firstAfterMany.idx;
+ }
+ }
+ else {
+ _super.prototype.walkMany.call(this, manyProd, currRest, prevRest);
+ }
+ };
+ return NextTerminalAfterManyWalker;
+}(AbstractNextTerminalAfterProductionWalker));
+exports.NextTerminalAfterManyWalker = NextTerminalAfterManyWalker;
+var NextTerminalAfterManySepWalker = /** @class */ (function (_super) {
+ __extends(NextTerminalAfterManySepWalker, _super);
+ function NextTerminalAfterManySepWalker() {
+ return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this;
+ }
+ NextTerminalAfterManySepWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) {
+ if (manySepProd.idx === this.occurrence) {
+ var firstAfterManySep = utils_1.first(currRest.concat(prevRest));
+ this.result.isEndOfRule = firstAfterManySep === undefined;
+ if (firstAfterManySep instanceof gast_public_1.Terminal) {
+ this.result.token = firstAfterManySep.terminalType;
+ this.result.occurrence = firstAfterManySep.idx;
+ }
+ }
+ else {
+ _super.prototype.walkManySep.call(this, manySepProd, currRest, prevRest);
+ }
+ };
+ return NextTerminalAfterManySepWalker;
+}(AbstractNextTerminalAfterProductionWalker));
+exports.NextTerminalAfterManySepWalker = NextTerminalAfterManySepWalker;
+var NextTerminalAfterAtLeastOneWalker = /** @class */ (function (_super) {
+ __extends(NextTerminalAfterAtLeastOneWalker, _super);
+ function NextTerminalAfterAtLeastOneWalker() {
+ return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this;
+ }
+ NextTerminalAfterAtLeastOneWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) {
+ if (atLeastOneProd.idx === this.occurrence) {
+ var firstAfterAtLeastOne = utils_1.first(currRest.concat(prevRest));
+ this.result.isEndOfRule = firstAfterAtLeastOne === undefined;
+ if (firstAfterAtLeastOne instanceof gast_public_1.Terminal) {
+ this.result.token = firstAfterAtLeastOne.terminalType;
+ this.result.occurrence = firstAfterAtLeastOne.idx;
+ }
+ }
+ else {
+ _super.prototype.walkAtLeastOne.call(this, atLeastOneProd, currRest, prevRest);
+ }
+ };
+ return NextTerminalAfterAtLeastOneWalker;
+}(AbstractNextTerminalAfterProductionWalker));
+exports.NextTerminalAfterAtLeastOneWalker = NextTerminalAfterAtLeastOneWalker;
+// TODO: reduce code duplication in the AfterWalkers
+var NextTerminalAfterAtLeastOneSepWalker = /** @class */ (function (_super) {
+ __extends(NextTerminalAfterAtLeastOneSepWalker, _super);
+ function NextTerminalAfterAtLeastOneSepWalker() {
+ return _super !== null && _super.apply(this, arguments) /* istanbul ignore next */ || this;
+ }
+ NextTerminalAfterAtLeastOneSepWalker.prototype.walkAtLeastOneSep = function (atleastOneSepProd, currRest, prevRest) {
+ if (atleastOneSepProd.idx === this.occurrence) {
+ var firstAfterfirstAfterAtLeastOneSep = utils_1.first(currRest.concat(prevRest));
+ this.result.isEndOfRule =
+ firstAfterfirstAfterAtLeastOneSep === undefined;
+ if (firstAfterfirstAfterAtLeastOneSep instanceof gast_public_1.Terminal) {
+ this.result.token =
+ firstAfterfirstAfterAtLeastOneSep.terminalType;
+ this.result.occurrence = firstAfterfirstAfterAtLeastOneSep.idx;
+ }
+ }
+ else {
+ _super.prototype.walkAtLeastOneSep.call(this, atleastOneSepProd, currRest, prevRest);
+ }
+ };
+ return NextTerminalAfterAtLeastOneSepWalker;
+}(AbstractNextTerminalAfterProductionWalker));
+exports.NextTerminalAfterAtLeastOneSepWalker = NextTerminalAfterAtLeastOneSepWalker;
+function possiblePathsFrom(targetDef, maxLength, currPath) {
+ if (currPath === void 0) { currPath = []; }
+ // avoid side effects
+ currPath = utils_1.cloneArr(currPath);
+ var result = [];
+ var i = 0;
+ // TODO: avoid inner funcs
+ function remainingPathWith(nextDef) {
+ return nextDef.concat(utils_1.drop(targetDef, i + 1));
+ }
+ // TODO: avoid inner funcs
+ function getAlternativesForProd(definition) {
+ var alternatives = possiblePathsFrom(remainingPathWith(definition), maxLength, currPath);
+ return result.concat(alternatives);
+ }
+ /**
+ * Mandatory productions will halt the loop as the paths computed from their recursive calls will already contain the
+ * following (rest) of the targetDef.
+ *
+ * For optional productions (Option/Repetition/...) the loop will continue to represent the paths that do not include the
+ * the optional production.
+ */
+ while (currPath.length < maxLength && i < targetDef.length) {
+ var prod = targetDef[i];
+ /* istanbul ignore else */
+ if (prod instanceof gast_public_1.Flat) {
+ return getAlternativesForProd(prod.definition);
+ }
+ else if (prod instanceof gast_public_1.NonTerminal) {
+ return getAlternativesForProd(prod.definition);
+ }
+ else if (prod instanceof gast_public_1.Option) {
+ result = getAlternativesForProd(prod.definition);
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatory) {
+ var newDef = prod.definition.concat([
+ new gast_public_1.Repetition({
+ definition: prod.definition
+ })
+ ]);
+ return getAlternativesForProd(newDef);
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatoryWithSeparator) {
+ var newDef = [
+ new gast_public_1.Flat({ definition: prod.definition }),
+ new gast_public_1.Repetition({
+ definition: [
+ new gast_public_1.Terminal({ terminalType: prod.separator })
+ ].concat(prod.definition)
+ })
+ ];
+ return getAlternativesForProd(newDef);
+ }
+ else if (prod instanceof gast_public_1.RepetitionWithSeparator) {
+ var newDef = prod.definition.concat([
+ new gast_public_1.Repetition({
+ definition: [
+ new gast_public_1.Terminal({ terminalType: prod.separator })
+ ].concat(prod.definition)
+ })
+ ]);
+ result = getAlternativesForProd(newDef);
+ }
+ else if (prod instanceof gast_public_1.Repetition) {
+ var newDef = prod.definition.concat([
+ new gast_public_1.Repetition({
+ definition: prod.definition
+ })
+ ]);
+ result = getAlternativesForProd(newDef);
+ }
+ else if (prod instanceof gast_public_1.Alternation) {
+ utils_1.forEach(prod.definition, function (currAlt) {
+ result = getAlternativesForProd(currAlt.definition);
+ });
+ return result;
+ }
+ else if (prod instanceof gast_public_1.Terminal) {
+ currPath.push(prod.terminalType);
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ i++;
+ }
+ result.push({
+ partialPath: currPath,
+ suffixDef: utils_1.drop(targetDef, i)
+ });
+ return result;
+}
+exports.possiblePathsFrom = possiblePathsFrom;
+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 (!utils_1.isEmpty(possiblePaths)) {
+ var currPath = possiblePaths.pop();
+ // skip alternatives if no more results can be found (assuming deterministic grammar with fixed lookahead)
+ if (currPath === EXIT_ALTERNATIVE) {
+ if (foundCompletePath &&
+ utils_1.last(possiblePaths).idx <= minimalAlternativesIndex) {
+ // remove irrelevant alternative
+ possiblePaths.pop();
+ }
+ continue;
+ }
+ var currDef = currPath.def;
+ var currIdx = currPath.idx;
+ var currRuleStack = currPath.ruleStack;
+ var currOccurrenceStack = currPath.occurrenceStack;
+ // For Example: an empty path could exist in a valid grammar in the case of an EMPTY_ALT
+ if (utils_1.isEmpty(currDef)) {
+ continue;
+ }
+ var prod = currDef[0];
+ /* istanbul ignore else */
+ if (prod === EXIT_NON_TERMINAL) {
+ var nextPath = {
+ idx: currIdx,
+ def: utils_1.drop(currDef),
+ ruleStack: utils_1.dropRight(currRuleStack),
+ occurrenceStack: utils_1.dropRight(currOccurrenceStack)
+ };
+ possiblePaths.push(nextPath);
+ }
+ else if (prod instanceof gast_public_1.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: utils_1.drop(currDef),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPath);
+ }
+ // end of the line
+ }
+ else if (currIdx === tokenVectorLength - 1) {
+ // IGNORE ABOVE ELSE
+ result.push({
+ nextTokenType: prod.terminalType,
+ nextTokenOccurrence: prod.idx,
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ });
+ foundCompletePath = true;
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ }
+ else if (prod instanceof gast_public_1.NonTerminal) {
+ var newRuleStack = utils_1.cloneArr(currRuleStack);
+ newRuleStack.push(prod.nonTerminalName);
+ var newOccurrenceStack = utils_1.cloneArr(currOccurrenceStack);
+ newOccurrenceStack.push(prod.idx);
+ var nextPath = {
+ idx: currIdx,
+ def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, utils_1.drop(currDef)),
+ ruleStack: newRuleStack,
+ occurrenceStack: newOccurrenceStack
+ };
+ possiblePaths.push(nextPath);
+ }
+ else if (prod instanceof gast_public_1.Option) {
+ // the order of alternatives is meaningful, FILO (Last path will be traversed first).
+ var nextPathWithout = {
+ idx: currIdx,
+ def: utils_1.drop(currDef),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWithout);
+ // required marker to avoid backtracking paths whose higher priority alternatives already matched
+ possiblePaths.push(EXIT_ALTERNATIVE);
+ var nextPathWith = {
+ idx: currIdx,
+ def: prod.definition.concat(utils_1.drop(currDef)),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWith);
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatory) {
+ // TODO:(THE NEW operators here take a while...) (convert once?)
+ var secondIteration = new gast_public_1.Repetition({
+ definition: prod.definition,
+ idx: prod.idx
+ });
+ var nextDef = prod.definition.concat([secondIteration], utils_1.drop(currDef));
+ var nextPath = {
+ idx: currIdx,
+ def: nextDef,
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPath);
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatoryWithSeparator) {
+ // TODO:(THE NEW operators here take a while...) (convert once?)
+ var separatorGast = new gast_public_1.Terminal({
+ terminalType: prod.separator
+ });
+ var secondIteration = new gast_public_1.Repetition({
+ definition: [separatorGast].concat(prod.definition),
+ idx: prod.idx
+ });
+ var nextDef = prod.definition.concat([secondIteration], utils_1.drop(currDef));
+ var nextPath = {
+ idx: currIdx,
+ def: nextDef,
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPath);
+ }
+ else if (prod instanceof gast_public_1.RepetitionWithSeparator) {
+ // the order of alternatives is meaningful, FILO (Last path will be traversed first).
+ var nextPathWithout = {
+ idx: currIdx,
+ def: utils_1.drop(currDef),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWithout);
+ // required marker to avoid backtracking paths whose higher priority alternatives already matched
+ possiblePaths.push(EXIT_ALTERNATIVE);
+ var separatorGast = new gast_public_1.Terminal({
+ terminalType: prod.separator
+ });
+ var nthRepetition = new gast_public_1.Repetition({
+ definition: [separatorGast].concat(prod.definition),
+ idx: prod.idx
+ });
+ var nextDef = prod.definition.concat([nthRepetition], utils_1.drop(currDef));
+ var nextPathWith = {
+ idx: currIdx,
+ def: nextDef,
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWith);
+ }
+ else if (prod instanceof gast_public_1.Repetition) {
+ // the order of alternatives is meaningful, FILO (Last path will be traversed first).
+ var nextPathWithout = {
+ idx: currIdx,
+ def: utils_1.drop(currDef),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWithout);
+ // required marker to avoid backtracking paths whose higher priority alternatives already matched
+ possiblePaths.push(EXIT_ALTERNATIVE);
+ // TODO: an empty repetition will cause infinite loops here, will the parser detect this in selfAnalysis?
+ var nthRepetition = new gast_public_1.Repetition({
+ definition: prod.definition,
+ idx: prod.idx
+ });
+ var nextDef = prod.definition.concat([nthRepetition], utils_1.drop(currDef));
+ var nextPathWith = {
+ idx: currIdx,
+ def: nextDef,
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWith);
+ }
+ else if (prod instanceof gast_public_1.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(utils_1.drop(currDef)),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(currAltPath);
+ possiblePaths.push(EXIT_ALTERNATIVE);
+ }
+ }
+ else if (prod instanceof gast_public_1.Flat) {
+ possiblePaths.push({
+ idx: currIdx,
+ def: prod.definition.concat(utils_1.drop(currDef)),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ });
+ }
+ else if (prod instanceof gast_public_1.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;
+}
+exports.nextPossibleTokensAfter = nextPossibleTokensAfter;
+function expandTopLevelRule(topRule, currIdx, currRuleStack, currOccurrenceStack) {
+ var newRuleStack = utils_1.cloneArr(currRuleStack);
+ newRuleStack.push(topRule.name);
+ var newCurrOccurrenceStack = utils_1.cloneArr(currOccurrenceStack);
+ // top rule is always assumed to have been called with occurrence index 1
+ newCurrOccurrenceStack.push(1);
+ return {
+ idx: currIdx,
+ def: topRule.definition,
+ ruleStack: newRuleStack,
+ occurrenceStack: newCurrOccurrenceStack
+ };
+}
+//# sourceMappingURL=interpreter.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/grammar/keys.js b/node_modules/chevrotain/lib/src/parse/grammar/keys.js
new file mode 100644
index 0000000..8539110
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/grammar/keys.js
@@ -0,0 +1,42 @@
+"use strict";
+// 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
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.BITS_FOR_METHOD_TYPE = 4;
+exports.BITS_FOR_OCCURRENCE_IDX = 8;
+exports.BITS_FOR_RULE_IDX = 12;
+// TODO: validation, this means that there may at most 2^8 --> 256 alternatives for an alternation.
+exports.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 */
+exports.OR_IDX = 1 << exports.BITS_FOR_OCCURRENCE_IDX;
+exports.OPTION_IDX = 2 << exports.BITS_FOR_OCCURRENCE_IDX;
+exports.MANY_IDX = 3 << exports.BITS_FOR_OCCURRENCE_IDX;
+exports.AT_LEAST_ONE_IDX = 4 << exports.BITS_FOR_OCCURRENCE_IDX;
+exports.MANY_SEP_IDX = 5 << exports.BITS_FOR_OCCURRENCE_IDX;
+exports.AT_LEAST_ONE_SEP_IDX = 6 << exports.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 */
+}
+exports.getKeyForAutomaticLookahead = getKeyForAutomaticLookahead;
+var BITS_START_FOR_ALT_IDX = 32 - exports.BITS_FOR_ALT_IDX;
+function getKeyForAltIndex(ruleIdx, dslMethodIdx, occurrence, altIdx) {
+ /* tslint:disable */
+ // alternative indices are zero based, thus must always add one (turn on one bit) to guarantee uniqueness.
+ var altIdxBitMap = (altIdx + 1) << BITS_START_FOR_ALT_IDX;
+ return (getKeyForAutomaticLookahead(ruleIdx, dslMethodIdx, occurrence) |
+ altIdxBitMap);
+ /* tslint:enable */
+}
+exports.getKeyForAltIndex = getKeyForAltIndex;
+//# sourceMappingURL=keys.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/grammar/lookahead.js b/node_modules/chevrotain/lib/src/parse/grammar/lookahead.js
new file mode 100644
index 0000000..e7bb42b
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/grammar/lookahead.js
@@ -0,0 +1,502 @@
+"use strict";
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../../utils/utils");
+var interpreter_1 = require("./interpreter");
+var rest_1 = require("./rest");
+var tokens_1 = require("../../scan/tokens");
+var gast_public_1 = require("./gast/gast_public");
+var gast_visitor_public_1 = require("./gast/gast_visitor_public");
+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 = exports.PROD_TYPE || (exports.PROD_TYPE = {}));
+function getProdType(prod) {
+ /* istanbul ignore else */
+ if (prod instanceof gast_public_1.Option) {
+ return PROD_TYPE.OPTION;
+ }
+ else if (prod instanceof gast_public_1.Repetition) {
+ return PROD_TYPE.REPETITION;
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatory) {
+ return PROD_TYPE.REPETITION_MANDATORY;
+ }
+ else if (prod instanceof gast_public_1.RepetitionMandatoryWithSeparator) {
+ return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR;
+ }
+ else if (prod instanceof gast_public_1.RepetitionWithSeparator) {
+ return PROD_TYPE.REPETITION_WITH_SEPARATOR;
+ }
+ else if (prod instanceof gast_public_1.Alternation) {
+ return PROD_TYPE.ALTERNATION;
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+exports.getProdType = getProdType;
+function buildLookaheadFuncForOr(occurrence, ruleGrammar, maxLookahead, hasPredicates, dynamicTokensEnabled, laFuncBuilder) {
+ var lookAheadPaths = getLookaheadPathsForOr(occurrence, ruleGrammar, maxLookahead);
+ var tokenMatcher = areTokenCategoriesNotUsed(lookAheadPaths)
+ ? tokens_1.tokenStructuredMatcherNoCategories
+ : tokens_1.tokenStructuredMatcher;
+ return laFuncBuilder(lookAheadPaths, hasPredicates, tokenMatcher, dynamicTokensEnabled);
+}
+exports.buildLookaheadFuncForOr = buildLookaheadFuncForOr;
+/**
+ * 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)
+ ? tokens_1.tokenStructuredMatcherNoCategories
+ : tokens_1.tokenStructuredMatcher;
+ return lookaheadBuilder(lookAheadPaths[0], tokenMatcher, dynamicTokensEnabled);
+}
+exports.buildLookaheadFuncForOptionalProd = buildLookaheadFuncForOptionalProd;
+function buildAlternativesLookAheadFunc(alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) {
+ var numOfAlts = alts.length;
+ var areAllOneTokenLookahead = utils_1.every(alts, function (currAlt) {
+ return utils_1.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 = utils_1.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 = utils_1.map(alts, function (currAlt) {
+ return utils_1.flatten(currAlt);
+ });
+ var choiceToAlt_1 = utils_1.reduce(singleTokenAlts, function (result, currAlt, idx) {
+ utils_1.forEach(currAlt, function (currTokType) {
+ if (!utils_1.has(result, currTokType.tokenTypeIdx)) {
+ result[currTokType.tokenTypeIdx] = idx;
+ }
+ utils_1.forEach(currTokType.categoryMatches, function (currExtendingType) {
+ if (!utils_1.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;
+ };
+ }
+}
+exports.buildAlternativesLookAheadFunc = buildAlternativesLookAheadFunc;
+function buildSingleAlternativeLookaheadFunction(alt, tokenMatcher, dynamicTokensEnabled) {
+ var areAllOneTokenLookahead = utils_1.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 = utils_1.flatten(alt);
+ if (singleTokensTypes.length === 1 &&
+ utils_1.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 = utils_1.reduce(singleTokensTypes, function (result, currTokType, idx) {
+ result[currTokType.tokenTypeIdx] = true;
+ utils_1.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;
+ };
+ }
+}
+exports.buildSingleAlternativeLookaheadFunction = buildSingleAlternativeLookaheadFunction;
+var RestDefinitionFinderWalker = /** @class */ (function (_super) {
+ __extends(RestDefinitionFinderWalker, _super);
+ function RestDefinitionFinderWalker(topProd, targetOccurrence, targetProdType) {
+ var _this = _super.call(this) || this;
+ _this.topProd = topProd;
+ _this.targetOccurrence = targetOccurrence;
+ _this.targetProdType = targetProdType;
+ return _this;
+ }
+ RestDefinitionFinderWalker.prototype.startWalking = function () {
+ this.walk(this.topProd);
+ return this.restDef;
+ };
+ RestDefinitionFinderWalker.prototype.checkIsTarget = function (node, expectedProdType, currRest, prevRest) {
+ if (node.idx === this.targetOccurrence &&
+ this.targetProdType === expectedProdType) {
+ this.restDef = currRest.concat(prevRest);
+ return true;
+ }
+ // performance optimization, do not iterate over the entire Grammar ast after we have found the target
+ return false;
+ };
+ RestDefinitionFinderWalker.prototype.walkOption = function (optionProd, currRest, prevRest) {
+ if (!this.checkIsTarget(optionProd, PROD_TYPE.OPTION, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, optionProd, currRest, prevRest);
+ }
+ };
+ RestDefinitionFinderWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) {
+ if (!this.checkIsTarget(atLeastOneProd, PROD_TYPE.REPETITION_MANDATORY, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, atLeastOneProd, currRest, prevRest);
+ }
+ };
+ RestDefinitionFinderWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) {
+ if (!this.checkIsTarget(atLeastOneSepProd, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, atLeastOneSepProd, currRest, prevRest);
+ }
+ };
+ RestDefinitionFinderWalker.prototype.walkMany = function (manyProd, currRest, prevRest) {
+ if (!this.checkIsTarget(manyProd, PROD_TYPE.REPETITION, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, manyProd, currRest, prevRest);
+ }
+ };
+ RestDefinitionFinderWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) {
+ if (!this.checkIsTarget(manySepProd, PROD_TYPE.REPETITION_WITH_SEPARATOR, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, manySepProd, currRest, prevRest);
+ }
+ };
+ return RestDefinitionFinderWalker;
+}(rest_1.RestWalker));
+/**
+ * Returns the definition of a target production in a top level level rule.
+ */
+var InsideDefinitionFinderVisitor = /** @class */ (function (_super) {
+ __extends(InsideDefinitionFinderVisitor, _super);
+ function InsideDefinitionFinderVisitor(targetOccurrence, targetProdType, targetRef) {
+ var _this = _super.call(this) || this;
+ _this.targetOccurrence = targetOccurrence;
+ _this.targetProdType = targetProdType;
+ _this.targetRef = targetRef;
+ _this.result = [];
+ return _this;
+ }
+ InsideDefinitionFinderVisitor.prototype.checkIsTarget = function (node, expectedProdName) {
+ if (node.idx === this.targetOccurrence &&
+ this.targetProdType === expectedProdName &&
+ (this.targetRef === undefined || node === this.targetRef)) {
+ this.result = node.definition;
+ }
+ };
+ InsideDefinitionFinderVisitor.prototype.visitOption = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.OPTION);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitRepetition = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.REPETITION);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatory = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitRepetitionWithSeparator = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.REPETITION_WITH_SEPARATOR);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitAlternation = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.ALTERNATION);
+ };
+ return InsideDefinitionFinderVisitor;
+}(gast_visitor_public_1.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 = utils_1.map(altsDefs, function (currAlt) { return interpreter_1.possiblePathsFrom([currAlt], 1); });
+ var finalResult = initializeArrayOfArrays(partialAlts.length);
+ var altsHashes = utils_1.map(partialAlts, function (currAltPaths) {
+ var dict = {};
+ utils_1.forEach(currAltPaths, function (item) {
+ var keys = pathToHashKeys(item.partialPath);
+ utils_1.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 ||
+ utils_1.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 = interpreter_1.possiblePathsFrom(suffixDef, pathLength + 1, currPathPrefix);
+ newData[altIdx] = newData[altIdx].concat(newPartialPathsAndSuffixes);
+ // Update keys for new known paths
+ utils_1.forEach(newPartialPathsAndSuffixes, function (item) {
+ var prefixKeys = pathToHashKeys(item.partialPath);
+ utils_1.forEach(prefixKeys, function (key) {
+ altsHashes[altIdx][key] = true;
+ });
+ });
+ }
+ }
+ };
+ // alternatives loop
+ for (var altIdx = 0; altIdx < currDataset.length; altIdx++) {
+ _loop_1(altIdx);
+ }
+ }
+ return finalResult;
+}
+exports.lookAheadSequenceFromAlternatives = lookAheadSequenceFromAlternatives;
+function getLookaheadPathsForOr(occurrence, ruleGrammar, k, orProd) {
+ var visitor = new InsideDefinitionFinderVisitor(occurrence, PROD_TYPE.ALTERNATION, orProd);
+ ruleGrammar.accept(visitor);
+ return lookAheadSequenceFromAlternatives(visitor.result, k);
+}
+exports.getLookaheadPathsForOr = getLookaheadPathsForOr;
+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_1.Flat({ definition: insideDef });
+ var afterFlat = new gast_public_1.Flat({ definition: afterDef });
+ return lookAheadSequenceFromAlternatives([insideFlat, afterFlat], k);
+}
+exports.getLookaheadPathsForOptionalProd = getLookaheadPathsForOptionalProd;
+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;
+}
+exports.containsPath = containsPath;
+function isStrictPrefixOfPath(prefix, other) {
+ return (prefix.length < other.length &&
+ utils_1.every(prefix, function (tokType, idx) {
+ var otherTokType = other[idx];
+ return (tokType === otherTokType ||
+ otherTokType.categoryMatchesMap[tokType.tokenTypeIdx]);
+ }));
+}
+exports.isStrictPrefixOfPath = isStrictPrefixOfPath;
+function areTokenCategoriesNotUsed(lookAheadPaths) {
+ return utils_1.every(lookAheadPaths, function (singleAltPaths) {
+ return utils_1.every(singleAltPaths, function (singlePath) {
+ return utils_1.every(singlePath, function (token) { return utils_1.isEmpty(token.categoryMatches); });
+ });
+ });
+}
+exports.areTokenCategoriesNotUsed = areTokenCategoriesNotUsed;
+//# sourceMappingURL=lookahead.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/grammar/resolver.js b/node_modules/chevrotain/lib/src/parse/grammar/resolver.js
new file mode 100644
index 0000000..12109b7
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/grammar/resolver.js
@@ -0,0 +1,59 @@
+"use strict";
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var parser_1 = require("../parser/parser");
+var utils_1 = require("../../utils/utils");
+var gast_visitor_public_1 = require("./gast/gast_visitor_public");
+function resolveGrammar(topLevels, errMsgProvider) {
+ var refResolver = new GastRefResolverVisitor(topLevels, errMsgProvider);
+ refResolver.resolveRefs();
+ return refResolver.errors;
+}
+exports.resolveGrammar = resolveGrammar;
+var GastRefResolverVisitor = /** @class */ (function (_super) {
+ __extends(GastRefResolverVisitor, _super);
+ function GastRefResolverVisitor(nameToTopRule, errMsgProvider) {
+ var _this = _super.call(this) || this;
+ _this.nameToTopRule = nameToTopRule;
+ _this.errMsgProvider = errMsgProvider;
+ _this.errors = [];
+ return _this;
+ }
+ GastRefResolverVisitor.prototype.resolveRefs = function () {
+ var _this = this;
+ utils_1.forEach(utils_1.values(this.nameToTopRule), function (prod) {
+ _this.currTopLevel = prod;
+ prod.accept(_this);
+ });
+ };
+ GastRefResolverVisitor.prototype.visitNonTerminal = function (node) {
+ var ref = this.nameToTopRule[node.nonTerminalName];
+ if (!ref) {
+ var msg = this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel, node);
+ this.errors.push({
+ message: msg,
+ type: parser_1.ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,
+ ruleName: this.currTopLevel.name,
+ unresolvedRefName: node.nonTerminalName
+ });
+ }
+ else {
+ node.referencedRule = ref;
+ }
+ };
+ return GastRefResolverVisitor;
+}(gast_visitor_public_1.GAstVisitor));
+exports.GastRefResolverVisitor = GastRefResolverVisitor;
+//# sourceMappingURL=resolver.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/grammar/rest.js b/node_modules/chevrotain/lib/src/parse/grammar/rest.js
new file mode 100644
index 0000000..9a79459
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/grammar/rest.js
@@ -0,0 +1,112 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../../utils/utils");
+var gast_public_1 = require("./gast/gast_public");
+/**
+ * A Grammar Walker that computes the "remaining" grammar "after" a productions in the grammar.
+ */
+var RestWalker = /** @class */ (function () {
+ function RestWalker() {
+ }
+ RestWalker.prototype.walk = function (prod, prevRest) {
+ var _this = this;
+ if (prevRest === void 0) { prevRest = []; }
+ utils_1.forEach(prod.definition, function (subProd, index) {
+ var currRest = utils_1.drop(prod.definition, index + 1);
+ /* istanbul ignore else */
+ if (subProd instanceof gast_public_1.NonTerminal) {
+ _this.walkProdRef(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.Terminal) {
+ _this.walkTerminal(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.Flat) {
+ _this.walkFlat(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.Option) {
+ _this.walkOption(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.RepetitionMandatory) {
+ _this.walkAtLeastOne(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.RepetitionMandatoryWithSeparator) {
+ _this.walkAtLeastOneSep(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.RepetitionWithSeparator) {
+ _this.walkManySep(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.Repetition) {
+ _this.walkMany(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof gast_public_1.Alternation) {
+ _this.walkOr(subProd, currRest, prevRest);
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ });
+ };
+ RestWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) { };
+ RestWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) { };
+ RestWalker.prototype.walkFlat = function (flatProd, currRest, prevRest) {
+ // ABCDEF => after the D the rest is EF
+ var fullOrRest = currRest.concat(prevRest);
+ this.walk(flatProd, fullOrRest);
+ };
+ RestWalker.prototype.walkOption = function (optionProd, currRest, prevRest) {
+ // ABC(DE)?F => after the (DE)? the rest is F
+ var fullOrRest = currRest.concat(prevRest);
+ this.walk(optionProd, fullOrRest);
+ };
+ RestWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) {
+ // ABC(DE)+F => after the (DE)+ the rest is (DE)?F
+ var fullAtLeastOneRest = [
+ new gast_public_1.Option({ definition: atLeastOneProd.definition })
+ ].concat(currRest, prevRest);
+ this.walk(atLeastOneProd, fullAtLeastOneRest);
+ };
+ RestWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) {
+ // ABC DE(,DE)* F => after the (,DE)+ the rest is (,DE)?F
+ var fullAtLeastOneSepRest = restForRepetitionWithSeparator(atLeastOneSepProd, currRest, prevRest);
+ this.walk(atLeastOneSepProd, fullAtLeastOneSepRest);
+ };
+ RestWalker.prototype.walkMany = function (manyProd, currRest, prevRest) {
+ // ABC(DE)*F => after the (DE)* the rest is (DE)?F
+ var fullManyRest = [
+ new gast_public_1.Option({ definition: manyProd.definition })
+ ].concat(currRest, prevRest);
+ this.walk(manyProd, fullManyRest);
+ };
+ RestWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) {
+ // ABC (DE(,DE)*)? F => after the (,DE)* the rest is (,DE)?F
+ var fullManySepRest = restForRepetitionWithSeparator(manySepProd, currRest, prevRest);
+ this.walk(manySepProd, fullManySepRest);
+ };
+ RestWalker.prototype.walkOr = function (orProd, currRest, prevRest) {
+ var _this = this;
+ // ABC(D|E|F)G => when finding the (D|E|F) the rest is G
+ var fullOrRest = currRest.concat(prevRest);
+ // walk all different alternatives
+ utils_1.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_1.Flat({ definition: [alt] });
+ _this.walk(prodWrapper, fullOrRest);
+ });
+ };
+ return RestWalker;
+}());
+exports.RestWalker = RestWalker;
+function restForRepetitionWithSeparator(repSepProd, currRest, prevRest) {
+ var repSepRest = [
+ new gast_public_1.Option({
+ definition: [
+ new gast_public_1.Terminal({ terminalType: repSepProd.separator })
+ ].concat(repSepProd.definition)
+ })
+ ];
+ var fullRepSepRest = repSepRest.concat(currRest, prevRest);
+ return fullRepSepRest;
+}
+//# sourceMappingURL=rest.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/parser/parser.js b/node_modules/chevrotain/lib/src/parse/parser/parser.js
new file mode 100644
index 0000000..3d94fd3
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/parser/parser.js
@@ -0,0 +1,235 @@
+"use strict";
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../../utils/utils");
+var follow_1 = require("../grammar/follow");
+var tokens_public_1 = require("../../scan/tokens_public");
+var cst_1 = require("../cst/cst");
+var errors_public_1 = require("../errors_public");
+var gast_resolver_public_1 = require("../grammar/gast/gast_resolver_public");
+var recoverable_1 = require("./traits/recoverable");
+var looksahead_1 = require("./traits/looksahead");
+var tree_builder_1 = require("./traits/tree_builder");
+var lexer_adapter_1 = require("./traits/lexer_adapter");
+var recognizer_api_1 = require("./traits/recognizer_api");
+var recognizer_engine_1 = require("./traits/recognizer_engine");
+var error_handler_1 = require("./traits/error_handler");
+var context_assist_1 = require("./traits/context_assist");
+var gast_recorder_1 = require("./traits/gast_recorder");
+var perf_tracer_1 = require("./traits/perf_tracer");
+exports.END_OF_FILE = tokens_public_1.createTokenInstance(tokens_public_1.EOF, "", NaN, NaN, NaN, NaN, NaN, NaN);
+Object.freeze(exports.END_OF_FILE);
+exports.DEFAULT_PARSER_CONFIG = Object.freeze({
+ recoveryEnabled: false,
+ maxLookahead: 4,
+ ignoredIssues: {},
+ dynamicTokensEnabled: false,
+ outputCst: true,
+ errorMessageProvider: errors_public_1.defaultParserErrorProvider,
+ nodeLocationTracking: "none",
+ traceInitPerf: false,
+ skipValidations: false
+});
+exports.DEFAULT_RULE_CONFIG = Object.freeze({
+ recoveryValueFunc: function () { return undefined; },
+ resyncEnabled: true
+});
+var ParserDefinitionErrorType;
+(function (ParserDefinitionErrorType) {
+ ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_NAME"] = 0] = "INVALID_RULE_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_RULE_NAME"] = 1] = "DUPLICATE_RULE_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_OVERRIDE"] = 2] = "INVALID_RULE_OVERRIDE";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_PRODUCTIONS"] = 3] = "DUPLICATE_PRODUCTIONS";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["UNRESOLVED_SUBRULE_REF"] = 4] = "UNRESOLVED_SUBRULE_REF";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["LEFT_RECURSION"] = 5] = "LEFT_RECURSION";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["NONE_LAST_EMPTY_ALT"] = 6] = "NONE_LAST_EMPTY_ALT";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_ALTS"] = 7] = "AMBIGUOUS_ALTS";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["CONFLICT_TOKENS_RULES_NAMESPACE"] = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_TOKEN_NAME"] = 9] = "INVALID_TOKEN_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_NESTED_RULE_NAME"] = 10] = "INVALID_NESTED_RULE_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_NESTED_NAME"] = 11] = "DUPLICATE_NESTED_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["NO_NON_EMPTY_LOOKAHEAD"] = 12] = "NO_NON_EMPTY_LOOKAHEAD";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_PREFIX_ALTS"] = 13] = "AMBIGUOUS_PREFIX_ALTS";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["TOO_MANY_ALTS"] = 14] = "TOO_MANY_ALTS";
+})(ParserDefinitionErrorType = exports.ParserDefinitionErrorType || (exports.ParserDefinitionErrorType = {}));
+function EMPTY_ALT(value) {
+ if (value === void 0) { value = undefined; }
+ return function () {
+ return value;
+ };
+}
+exports.EMPTY_ALT = EMPTY_ALT;
+var Parser = /** @class */ (function () {
+ function Parser(tokenVocabulary, config) {
+ if (config === void 0) { config = exports.DEFAULT_PARSER_CONFIG; }
+ this.ignoredIssues = exports.DEFAULT_PARSER_CONFIG.ignoredIssues;
+ this.definitionErrors = [];
+ this.selfAnalysisDone = false;
+ var that = this;
+ that.initErrorHandler(config);
+ that.initLexerAdapter();
+ that.initLooksAhead(config);
+ that.initRecognizerEngine(tokenVocabulary, config);
+ that.initRecoverable(config);
+ that.initTreeBuilder(config);
+ that.initContentAssist();
+ that.initGastRecorder(config);
+ that.initPerformanceTracer(config);
+ /* istanbul ignore if - complete over-kill to test this, we should only add a test when we actually hard deprecate it and throw an error... */
+ if (utils_1.has(config, "ignoredIssues") &&
+ config.ignoredIssues !== exports.DEFAULT_PARSER_CONFIG.ignoredIssues) {
+ utils_1.PRINT_WARNING("The IParserConfig property is soft-deprecated and will be removed in future versions.\n\t" +
+ "Please use the flag on the relevant DSL method instead.");
+ }
+ this.ignoredIssues = utils_1.has(config, "ignoredIssues")
+ ? config.ignoredIssues
+ : exports.DEFAULT_PARSER_CONFIG.ignoredIssues;
+ this.skipValidations = utils_1.has(config, "skipValidations")
+ ? config.skipValidations
+ : exports.DEFAULT_PARSER_CONFIG.skipValidations;
+ }
+ /**
+ * @deprecated use the **instance** method with the same name instead
+ */
+ Parser.performSelfAnalysis = function (parserInstance) {
+ ;
+ parserInstance.performSelfAnalysis();
+ };
+ Parser.prototype.performSelfAnalysis = function () {
+ var _this = this;
+ this.TRACE_INIT("performSelfAnalysis", function () {
+ var defErrorsMsgs;
+ _this.selfAnalysisDone = true;
+ var className = _this.className;
+ _this.TRACE_INIT("toFastProps", function () {
+ // Without this voodoo magic the parser would be x3-x4 slower
+ // It seems it is better to invoke `toFastProperties` **before**
+ // Any manipulations of the `this` object done during the recording phase.
+ utils_1.toFastProperties(_this);
+ });
+ _this.TRACE_INIT("Grammar Recording", function () {
+ try {
+ _this.enableRecording();
+ // Building the GAST
+ utils_1.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_1.resolveGrammar({
+ rules: utils_1.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 (utils_1.isEmpty(resolverErrors) && _this.skipValidations === false) {
+ var validationErrors = gast_resolver_public_1.validateGrammar({
+ rules: utils_1.values(_this.gastProductionsCache),
+ maxLookahead: _this.maxLookahead,
+ tokenTypes: utils_1.values(_this.tokensMap),
+ ignoredIssues: _this.ignoredIssues,
+ errMsgProvider: errors_public_1.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 (utils_1.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 = follow_1.computeAllProdsFollows(utils_1.values(_this.gastProductionsCache));
+ _this.resyncFollows = allFollows;
+ });
+ }
+ _this.TRACE_INIT("ComputeLookaheadFunctions", function () {
+ _this.preComputeLookaheadFunctions(utils_1.values(_this.gastProductionsCache));
+ });
+ }
+ _this.TRACE_INIT("expandAllNestedRuleNames", function () {
+ // TODO: is this needed for EmbeddedActionsParser?
+ var cstAnalysisResult = cst_1.expandAllNestedRuleNames(utils_1.values(_this.gastProductionsCache), _this.fullRuleNameToShort);
+ _this.allRuleNames = cstAnalysisResult.allRuleNames;
+ });
+ if (!Parser.DEFER_DEFINITION_ERRORS_HANDLING &&
+ !utils_1.isEmpty(_this.definitionErrors)) {
+ defErrorsMsgs = utils_1.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;
+}());
+exports.Parser = Parser;
+utils_1.applyMixins(Parser, [
+ recoverable_1.Recoverable,
+ looksahead_1.LooksAhead,
+ tree_builder_1.TreeBuilder,
+ lexer_adapter_1.LexerAdapter,
+ recognizer_engine_1.RecognizerEngine,
+ recognizer_api_1.RecognizerApi,
+ error_handler_1.ErrorHandler,
+ context_assist_1.ContentAssist,
+ gast_recorder_1.GastRecorder,
+ perf_tracer_1.PerformanceTracer
+]);
+var CstParser = /** @class */ (function (_super) {
+ __extends(CstParser, _super);
+ function CstParser(tokenVocabulary, config) {
+ if (config === void 0) { config = exports.DEFAULT_PARSER_CONFIG; }
+ var _this = this;
+ var configClone = utils_1.cloneObj(config);
+ configClone.outputCst = true;
+ _this = _super.call(this, tokenVocabulary, configClone) || this;
+ return _this;
+ }
+ return CstParser;
+}(Parser));
+exports.CstParser = CstParser;
+var EmbeddedActionsParser = /** @class */ (function (_super) {
+ __extends(EmbeddedActionsParser, _super);
+ function EmbeddedActionsParser(tokenVocabulary, config) {
+ if (config === void 0) { config = exports.DEFAULT_PARSER_CONFIG; }
+ var _this = this;
+ var configClone = utils_1.cloneObj(config);
+ configClone.outputCst = false;
+ _this = _super.call(this, tokenVocabulary, configClone) || this;
+ return _this;
+ }
+ return EmbeddedActionsParser;
+}(Parser));
+exports.EmbeddedActionsParser = EmbeddedActionsParser;
+//# sourceMappingURL=parser.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/parser/traits/context_assist.js b/node_modules/chevrotain/lib/src/parse/parser/traits/context_assist.js
new file mode 100644
index 0000000..87f4ef1
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/parser/traits/context_assist.js
@@ -0,0 +1,28 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var interpreter_1 = require("../../grammar/interpreter");
+var utils_1 = require("../../../utils/utils");
+var ContentAssist = /** @class */ (function () {
+ function ContentAssist() {
+ }
+ ContentAssist.prototype.initContentAssist = function () { };
+ ContentAssist.prototype.computeContentAssist = function (startRuleName, precedingInput) {
+ var startRuleGast = this.gastProductionsCache[startRuleName];
+ if (utils_1.isUndefined(startRuleGast)) {
+ throw Error("Rule ->" + startRuleName + "<- does not exist in this grammar.");
+ }
+ return interpreter_1.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 = utils_1.first(grammarPath.ruleStack);
+ var gastProductions = this.getGAstProductions();
+ var topProduction = gastProductions[topRuleName];
+ var nextPossibleTokenTypes = new interpreter_1.NextAfterTokenWalker(topProduction, grammarPath).startWalking();
+ return nextPossibleTokenTypes;
+ };
+ return ContentAssist;
+}());
+exports.ContentAssist = ContentAssist;
+//# sourceMappingURL=context_assist.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/parser/traits/error_handler.js b/node_modules/chevrotain/lib/src/parse/parser/traits/error_handler.js
new file mode 100644
index 0000000..274bc87
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/parser/traits/error_handler.js
@@ -0,0 +1,83 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var exceptions_public_1 = require("../../exceptions_public");
+var utils_1 = require("../../../utils/utils");
+var lookahead_1 = require("../../grammar/lookahead");
+var parser_1 = require("../parser");
+/**
+ * Trait responsible for runtime parsing errors.
+ */
+var ErrorHandler = /** @class */ (function () {
+ function ErrorHandler() {
+ }
+ ErrorHandler.prototype.initErrorHandler = function (config) {
+ this._errors = [];
+ this.errorMessageProvider = utils_1.defaults(config.errorMessageProvider, parser_1.DEFAULT_PARSER_CONFIG.errorMessageProvider);
+ };
+ ErrorHandler.prototype.SAVE_ERROR = function (error) {
+ if (exceptions_public_1.isRecognitionException(error)) {
+ error.context = {
+ ruleStack: this.getHumanReadableRuleStack(),
+ ruleOccurrenceStack: utils_1.cloneArr(this.RULE_OCCURRENCE_STACK)
+ };
+ this._errors.push(error);
+ return error;
+ }
+ else {
+ throw Error("Trying to save an Error which is not a RecognitionException");
+ }
+ };
+ Object.defineProperty(ErrorHandler.prototype, "errors", {
+ // TODO: extract these methods to ErrorHandler Trait?
+ get: function () {
+ return utils_1.cloneArr(this._errors);
+ },
+ set: function (newErrors) {
+ this._errors = newErrors;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ // TODO: consider caching the error message computed information
+ ErrorHandler.prototype.raiseEarlyExitException = function (occurrence, prodType, userDefinedErrMsg) {
+ var ruleName = this.getCurrRuleFullName();
+ var ruleGrammar = this.getGAstProductions()[ruleName];
+ var lookAheadPathsPerAlternative = lookahead_1.getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, this.maxLookahead);
+ var insideProdPaths = lookAheadPathsPerAlternative[0];
+ var actualTokens = [];
+ for (var i = 1; i <= this.maxLookahead; i++) {
+ actualTokens.push(this.LA(i));
+ }
+ var msg = this.errorMessageProvider.buildEarlyExitMessage({
+ expectedIterationPaths: insideProdPaths,
+ actual: actualTokens,
+ previous: this.LA(0),
+ customUserDescription: userDefinedErrMsg,
+ ruleName: ruleName
+ });
+ throw this.SAVE_ERROR(new exceptions_public_1.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 = lookahead_1.getLookaheadPathsForOr(occurrence, ruleGrammar, this.maxLookahead);
+ var actualTokens = [];
+ for (var i = 1; i <= this.maxLookahead; i++) {
+ actualTokens.push(this.LA(i));
+ }
+ var previousToken = this.LA(0);
+ var errMsg = this.errorMessageProvider.buildNoViableAltMessage({
+ expectedPathsPerAlt: lookAheadPathsPerAlternative,
+ actual: actualTokens,
+ previous: previousToken,
+ customUserDescription: errMsgTypes,
+ ruleName: this.getCurrRuleFullName()
+ });
+ throw this.SAVE_ERROR(new exceptions_public_1.NoViableAltException(errMsg, this.LA(1), previousToken));
+ };
+ return ErrorHandler;
+}());
+exports.ErrorHandler = ErrorHandler;
+//# sourceMappingURL=error_handler.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/parser/traits/gast_recorder.js b/node_modules/chevrotain/lib/src/parse/parser/traits/gast_recorder.js
new file mode 100644
index 0000000..0a3bcba
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/parser/traits/gast_recorder.js
@@ -0,0 +1,318 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../../../utils/utils");
+var gast_public_1 = require("../../grammar/gast/gast_public");
+var lexer_public_1 = require("../../../scan/lexer_public");
+var tokens_1 = require("../../../scan/tokens");
+var tokens_public_1 = require("../../../scan/tokens_public");
+var parser_1 = require("../parser");
+var keys_1 = require("../../grammar/keys");
+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, keys_1.BITS_FOR_OCCURRENCE_IDX) - 1;
+var RFT = tokens_public_1.createToken({ name: "RECORDING_PHASE_TOKEN", pattern: lexer_public_1.Lexer.NA });
+tokens_1.augmentTokenTypes([RFT]);
+var RECORDING_PHASE_TOKEN = tokens_public_1.createTokenInstance(RFT, "This IToken indicates the Parser is in Recording Phase\n\t" +
+ "" +
+ "See: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details",
+// Using "-1" instead of NaN (as in EOF) because an actual number is less likely to
+// cause errors if the output of LA or CONSUME would be (incorrectly) used during the recording phase.
+-1, -1, -1, -1, -1, -1);
+Object.freeze(RECORDING_PHASE_TOKEN);
+var RECORDING_PHASE_CSTNODE = {
+ name: "This CSTNode indicates the Parser is in Recording Phase\n\t" +
+ "See: https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording for details",
+ children: {}
+};
+/**
+ * This trait handles the creation of the GAST structure for Chevrotain Grammars
+ */
+var GastRecorder = /** @class */ (function () {
+ function GastRecorder() {
+ }
+ GastRecorder.prototype.initGastRecorder = function (config) {
+ this.recordingProdStack = [];
+ this.RECORDING_PHASE = false;
+ };
+ GastRecorder.prototype.enableRecording = function () {
+ var _this = this;
+ this.RECORDING_PHASE = true;
+ this.TRACE_INIT("Enable Recording", function () {
+ var _loop_1 = function (i) {
+ var idx = i > 0 ? i : "";
+ _this["CONSUME" + idx] = function (arg1, arg2) {
+ return this.consumeInternalRecord(arg1, i, arg2);
+ };
+ _this["SUBRULE" + idx] = function (arg1, arg2) {
+ return this.subruleInternalRecord(arg1, i, arg2);
+ };
+ _this["OPTION" + idx] = function (arg1) {
+ return this.optionInternalRecord(arg1, i);
+ };
+ _this["OR" + idx] = function (arg1) {
+ return this.orInternalRecord(arg1, i);
+ };
+ _this["MANY" + idx] = function (arg1) {
+ this.manyInternalRecord(i, arg1);
+ };
+ _this["MANY_SEP" + idx] = function (arg1) {
+ this.manySepFirstInternalRecord(i, arg1);
+ };
+ _this["AT_LEAST_ONE" + idx] = function (arg1) {
+ this.atLeastOneInternalRecord(i, arg1);
+ };
+ _this["AT_LEAST_ONE_SEP" + idx] = function (arg1) {
+ this.atLeastOneSepFirstInternalRecord(i, arg1);
+ };
+ };
+ /**
+ * Warning Dark Voodoo Magic upcoming!
+ * We are "replacing" the public parsing DSL methods API
+ * With **new** alternative implementations on the Parser **instance**
+ *
+ * So far this is the only way I've found to avoid performance regressions during parsing time.
+ * - Approx 30% performance regression was measured on Chrome 75 Canary when attempting to replace the "internal"
+ * implementations directly instead.
+ */
+ for (var i = 0; i < 10; i++) {
+ _loop_1(i);
+ }
+ // DSL methods with the idx(suffix) as an argument
+ _this["consume"] = function (idx, arg1, arg2) {
+ return this.consumeInternalRecord(arg1, idx, arg2);
+ };
+ _this["subrule"] = function (idx, arg1, arg2) {
+ return this.subruleInternalRecord(arg1, idx, arg2);
+ };
+ _this["option"] = function (idx, arg1) {
+ return this.optionInternalRecord(arg1, idx);
+ };
+ _this["or"] = function (idx, arg1) {
+ return this.orInternalRecord(arg1, idx);
+ };
+ _this["many"] = function (idx, arg1) {
+ this.manyInternalRecord(idx, arg1);
+ };
+ _this["atLeastOne"] = function (idx, arg1) {
+ this.atLeastOneInternalRecord(idx, arg1);
+ };
+ _this.ACTION = _this.ACTION_RECORD;
+ _this.BACKTRACK = _this.BACKTRACK_RECORD;
+ _this.LA = _this.LA_RECORD;
+ });
+ };
+ GastRecorder.prototype.disableRecording = function () {
+ var _this = this;
+ this.RECORDING_PHASE = false;
+ // By deleting these **instance** properties, any future invocation
+ // will be deferred to the original methods on the **prototype** object
+ // This seems to get rid of any incorrect optimizations that V8 may
+ // do during the recording phase.
+ this.TRACE_INIT("Deleting Recording methods", function () {
+ for (var i = 0; i < 10; i++) {
+ var idx = i > 0 ? i : "";
+ delete _this["CONSUME" + idx];
+ delete _this["SUBRULE" + idx];
+ delete _this["OPTION" + idx];
+ delete _this["OR" + idx];
+ delete _this["MANY" + idx];
+ delete _this["MANY_SEP" + idx];
+ delete _this["AT_LEAST_ONE" + idx];
+ delete _this["AT_LEAST_ONE_SEP" + idx];
+ }
+ delete _this["consume"];
+ delete _this["subrule"];
+ delete _this["option"];
+ delete _this["or"];
+ delete _this["many"];
+ delete _this["atLeastOne"];
+ delete _this.ACTION;
+ delete _this.BACKTRACK;
+ delete _this.LA;
+ });
+ };
+ // TODO: is there any way to use this method to check no
+ // Parser methods are called inside an ACTION?
+ // Maybe try/catch/finally on ACTIONS while disabling the recorders state changes?
+ GastRecorder.prototype.ACTION_RECORD = function (impl) {
+ // NO-OP during recording
+ return;
+ };
+ // Executing backtracking logic will break our recording logic assumptions
+ GastRecorder.prototype.BACKTRACK_RECORD = function (grammarRule, args) {
+ return function () { return true; };
+ };
+ // LA is part of the official API and may be used for custom lookahead logic
+ // by end users who may forget to wrap it in ACTION or inside a GATE
+ GastRecorder.prototype.LA_RECORD = function (howMuch) {
+ // We cannot use the RECORD_PHASE_TOKEN here because someone may depend
+ // On LA return EOF at the end of the input so an infinite loop may occur.
+ return parser_1.END_OF_FILE;
+ };
+ GastRecorder.prototype.topLevelRuleRecord = function (name, def) {
+ try {
+ var newTopLevelRule = new gast_public_1.Rule({ definition: [], name: name });
+ newTopLevelRule.name = name;
+ this.recordingProdStack.push(newTopLevelRule);
+ def.call(this);
+ this.recordingProdStack.pop();
+ return newTopLevelRule;
+ }
+ catch (originalError) {
+ if (originalError.KNOWN_RECORDER_ERROR !== true) {
+ try {
+ originalError.message =
+ originalError.message +
+ '\n\t This error was thrown during the "grammar recording phase" For more info see:\n\t' +
+ "https://sap.github.io/chevrotain/docs/guide/internals.html#grammar-recording";
+ }
+ catch (mutabilityError) {
+ // We may not be able to modify the original error object
+ throw originalError;
+ }
+ }
+ throw originalError;
+ }
+ };
+ // Implementation of parsing DSL
+ GastRecorder.prototype.optionInternalRecord = function (actionORMethodDef, occurrence) {
+ return recordProd.call(this, gast_public_1.Option, actionORMethodDef, occurrence);
+ };
+ GastRecorder.prototype.atLeastOneInternalRecord = function (occurrence, actionORMethodDef) {
+ recordProd.call(this, gast_public_1.RepetitionMandatory, actionORMethodDef, occurrence);
+ };
+ GastRecorder.prototype.atLeastOneSepFirstInternalRecord = function (occurrence, options) {
+ recordProd.call(this, gast_public_1.RepetitionMandatoryWithSeparator, options, occurrence, HANDLE_SEPARATOR);
+ };
+ GastRecorder.prototype.manyInternalRecord = function (occurrence, actionORMethodDef) {
+ recordProd.call(this, gast_public_1.Repetition, actionORMethodDef, occurrence);
+ };
+ GastRecorder.prototype.manySepFirstInternalRecord = function (occurrence, options) {
+ recordProd.call(this, gast_public_1.RepetitionWithSeparator, options, occurrence, HANDLE_SEPARATOR);
+ };
+ GastRecorder.prototype.orInternalRecord = function (altsOrOpts, occurrence) {
+ return recordOrProd.call(this, altsOrOpts, occurrence);
+ };
+ GastRecorder.prototype.subruleInternalRecord = function (ruleToCall, occurrence, options) {
+ assertMethodIdxIsValid(occurrence);
+ if (!ruleToCall || utils_1.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 = utils_1.peek(this.recordingProdStack);
+ var ruleName = ruleToCall["ruleName"];
+ var newNoneTerminal = new gast_public_1.NonTerminal({
+ idx: occurrence,
+ nonTerminalName: ruleName,
+ // The resolving of the `referencedRule` property will be done once all the Rule's GASTs have been created
+ referencedRule: undefined
+ });
+ prevProd.definition.push(newNoneTerminal);
+ return this.outputCst
+ ? RECORDING_PHASE_CSTNODE
+ : RECORDING_NULL_OBJECT;
+ };
+ GastRecorder.prototype.consumeInternalRecord = function (tokType, occurrence, options) {
+ assertMethodIdxIsValid(occurrence);
+ if (!tokens_1.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 = utils_1.peek(this.recordingProdStack);
+ var newNoneTerminal = new gast_public_1.Terminal({
+ idx: occurrence,
+ terminalType: tokType
+ });
+ prevProd.definition.push(newNoneTerminal);
+ return RECORDING_PHASE_TOKEN;
+ };
+ return GastRecorder;
+}());
+exports.GastRecorder = GastRecorder;
+function recordProd(prodConstructor, mainProdArg, occurrence, handleSep) {
+ if (handleSep === void 0) { handleSep = false; }
+ assertMethodIdxIsValid(occurrence);
+ var prevProd = utils_1.peek(this.recordingProdStack);
+ var grammarAction = utils_1.isFunction(mainProdArg)
+ ? mainProdArg
+ : mainProdArg.DEF;
+ var newProd = new prodConstructor({ definition: [], idx: occurrence });
+ if (utils_1.has(mainProdArg, "NAME")) {
+ newProd.name = mainProdArg.NAME;
+ }
+ if (handleSep) {
+ newProd.separator = mainProdArg.SEP;
+ }
+ if (utils_1.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 = utils_1.peek(this.recordingProdStack);
+ // Only an array of alternatives
+ var hasOptions = utils_1.isArray(mainProdArg) === false;
+ var alts = hasOptions === false ? mainProdArg : mainProdArg.DEF;
+ var newOrProd = new gast_public_1.Alternation({
+ definition: [],
+ idx: occurrence,
+ ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true
+ });
+ if (utils_1.has(mainProdArg, "NAME")) {
+ newOrProd.name = mainProdArg.NAME;
+ }
+ if (utils_1.has(mainProdArg, "MAX_LOOKAHEAD")) {
+ newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;
+ }
+ var hasPredicates = utils_1.some(alts, function (currAlt) { return utils_1.isFunction(currAlt.GATE); });
+ newOrProd.hasPredicates = hasPredicates;
+ prevProd.definition.push(newOrProd);
+ utils_1.forEach(alts, function (currAlt) {
+ var currAltFlat = new gast_public_1.Flat({ definition: [] });
+ newOrProd.definition.push(currAltFlat);
+ if (utils_1.has(currAlt, "NAME")) {
+ currAltFlat.name = currAlt.NAME;
+ }
+ if (utils_1.has(currAlt, "IGNORE_AMBIGUITIES")) {
+ currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES;
+ }
+ // **implicit** ignoreAmbiguities due to usage of gate
+ else if (utils_1.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
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/parser/traits/lexer_adapter.js b/node_modules/chevrotain/lib/src/parse/parser/traits/lexer_adapter.js
new file mode 100644
index 0000000..4b3f2a3
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/parser/traits/lexer_adapter.js
@@ -0,0 +1,76 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var parser_1 = require("../parser");
+/**
+ * Trait responsible abstracting over the interaction with Lexer output (Token vector).
+ *
+ * This could be generalized to support other kinds of lexers, e.g.
+ * - Just in Time Lexing / Lexer-Less parsing.
+ * - Streaming Lexer.
+ */
+var LexerAdapter = /** @class */ (function () {
+ function LexerAdapter() {
+ }
+ LexerAdapter.prototype.initLexerAdapter = function () {
+ this.tokVector = [];
+ this.tokVectorLength = 0;
+ this.currIdx = -1;
+ };
+ Object.defineProperty(LexerAdapter.prototype, "input", {
+ get: function () {
+ return this.tokVector;
+ },
+ set: function (newInput) {
+ if (this.selfAnalysisDone !== true) {
+ throw Error("Missing invocation at the end of the Parser's constructor.");
+ }
+ this.reset();
+ this.tokVector = newInput;
+ this.tokVectorLength = newInput.length;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ // skips a token and returns the next token
+ LexerAdapter.prototype.SKIP_TOKEN = function () {
+ if (this.currIdx <= this.tokVector.length - 2) {
+ this.consumeToken();
+ return this.LA(1);
+ }
+ else {
+ return parser_1.END_OF_FILE;
+ }
+ };
+ // Lexer (accessing Token vector) related methods which can be overridden to implement lazy lexers
+ // or lexers dependent on parser context.
+ LexerAdapter.prototype.LA = function (howMuch) {
+ var soughtIdx = this.currIdx + howMuch;
+ if (soughtIdx < 0 || this.tokVectorLength <= soughtIdx) {
+ return parser_1.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;
+}());
+exports.LexerAdapter = LexerAdapter;
+//# sourceMappingURL=lexer_adapter.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/parser/traits/looksahead.js b/node_modules/chevrotain/lib/src/parse/parser/traits/looksahead.js
new file mode 100644
index 0000000..95695a7
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/parser/traits/looksahead.js
@@ -0,0 +1,108 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var lookahead_1 = require("../../grammar/lookahead");
+var utils_1 = require("../../../utils/utils");
+var parser_1 = require("../parser");
+var keys_1 = require("../../grammar/keys");
+var gast_1 = require("../../grammar/gast/gast");
+/**
+ * Trait responsible for the lookahead related utilities and optimizations.
+ */
+var LooksAhead = /** @class */ (function () {
+ function LooksAhead() {
+ }
+ LooksAhead.prototype.initLooksAhead = function (config) {
+ this.dynamicTokensEnabled = utils_1.has(config, "dynamicTokensEnabled")
+ ? config.dynamicTokensEnabled
+ : parser_1.DEFAULT_PARSER_CONFIG.dynamicTokensEnabled;
+ this.maxLookahead = utils_1.has(config, "maxLookahead")
+ ? config.maxLookahead
+ : parser_1.DEFAULT_PARSER_CONFIG.maxLookahead;
+ /* istanbul ignore next - Using plain array as dictionary will be tested on older node.js versions and IE11 */
+ this.lookAheadFuncsCache = utils_1.isES2015MapSupported() ? new Map() : [];
+ // Performance optimization on newer engines that support ES6 Map
+ // For larger Maps this is slightly faster than using a plain object (array in our case).
+ /* istanbul ignore else - The else branch will be tested on older node.js versions and IE11 */
+ if (utils_1.isES2015MapSupported()) {
+ this.getLaFuncFromCache = this.getLaFuncFromMap;
+ this.setLaFuncCache = this.setLaFuncCacheUsingMap;
+ }
+ else {
+ this.getLaFuncFromCache = this.getLaFuncFromObj;
+ this.setLaFuncCache = this.setLaFuncUsingObj;
+ }
+ };
+ LooksAhead.prototype.preComputeLookaheadFunctions = function (rules) {
+ var _this = this;
+ utils_1.forEach(rules, function (currRule) {
+ _this.TRACE_INIT(currRule.name + " Rule Lookahead", function () {
+ var _a = gast_1.collectMethods(currRule), alternation = _a.alternation, repetition = _a.repetition, option = _a.option, repetitionMandatory = _a.repetitionMandatory, repetitionMandatoryWithSeparator = _a.repetitionMandatoryWithSeparator, repetitionWithSeparator = _a.repetitionWithSeparator;
+ utils_1.forEach(alternation, function (currProd) {
+ var prodIdx = currProd.idx === 0 ? "" : currProd.idx;
+ _this.TRACE_INIT("" + gast_1.getProductionDslName(currProd) + prodIdx, function () {
+ var laFunc = lookahead_1.buildLookaheadFuncForOr(currProd.idx, currRule, currProd.maxLookahead || _this.maxLookahead, currProd.hasPredicates, _this.dynamicTokensEnabled, _this.lookAheadBuilderForAlternatives);
+ var key = keys_1.getKeyForAutomaticLookahead(_this.fullRuleNameToShort[currRule.name], keys_1.OR_IDX, currProd.idx);
+ _this.setLaFuncCache(key, laFunc);
+ });
+ });
+ utils_1.forEach(repetition, function (currProd) {
+ _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.MANY_IDX, lookahead_1.PROD_TYPE.REPETITION, currProd.maxLookahead, gast_1.getProductionDslName(currProd));
+ });
+ utils_1.forEach(option, function (currProd) {
+ _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.OPTION_IDX, lookahead_1.PROD_TYPE.OPTION, currProd.maxLookahead, gast_1.getProductionDslName(currProd));
+ });
+ utils_1.forEach(repetitionMandatory, function (currProd) {
+ _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.AT_LEAST_ONE_IDX, lookahead_1.PROD_TYPE.REPETITION_MANDATORY, currProd.maxLookahead, gast_1.getProductionDslName(currProd));
+ });
+ utils_1.forEach(repetitionMandatoryWithSeparator, function (currProd) {
+ _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.AT_LEAST_ONE_SEP_IDX, lookahead_1.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currProd.maxLookahead, gast_1.getProductionDslName(currProd));
+ });
+ utils_1.forEach(repetitionWithSeparator, function (currProd) {
+ _this.computeLookaheadFunc(currRule, currProd.idx, keys_1.MANY_SEP_IDX, lookahead_1.PROD_TYPE.REPETITION_WITH_SEPARATOR, currProd.maxLookahead, gast_1.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 = lookahead_1.buildLookaheadFuncForOptionalProd(prodOccurrence, rule, prodMaxLookahead || _this.maxLookahead, _this.dynamicTokensEnabled, prodType, _this.lookAheadBuilderForOptional);
+ var key = keys_1.getKeyForAutomaticLookahead(_this.fullRuleNameToShort[rule.name], prodKey, prodOccurrence);
+ _this.setLaFuncCache(key, laFunc);
+ });
+ };
+ LooksAhead.prototype.lookAheadBuilderForOptional = function (alt, tokenMatcher, dynamicTokensEnabled) {
+ return lookahead_1.buildSingleAlternativeLookaheadFunction(alt, tokenMatcher, dynamicTokensEnabled);
+ };
+ LooksAhead.prototype.lookAheadBuilderForAlternatives = function (alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) {
+ return lookahead_1.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 keys_1.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;
+}());
+exports.LooksAhead = LooksAhead;
+//# sourceMappingURL=looksahead.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/parser/traits/parser_traits.js b/node_modules/chevrotain/lib/src/parse/parser/traits/parser_traits.js
new file mode 100644
index 0000000..2b78198
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/parser/traits/parser_traits.js
@@ -0,0 +1,7 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var parser_1 = require("../parser");
+exports.Parser = parser_1.Parser;
+exports.CstParser = (parser_1.CstParser);
+exports.EmbeddedActionsParser = parser_1.EmbeddedActionsParser;
+//# sourceMappingURL=parser_traits.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/parser/traits/perf_tracer.js b/node_modules/chevrotain/lib/src/parse/parser/traits/perf_tracer.js
new file mode 100644
index 0000000..6b98356
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/parser/traits/perf_tracer.js
@@ -0,0 +1,53 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../../../utils/utils");
+var parser_1 = require("../parser");
+/**
+ * Trait responsible for runtime parsing errors.
+ */
+var PerformanceTracer = /** @class */ (function () {
+ function PerformanceTracer() {
+ }
+ PerformanceTracer.prototype.initPerformanceTracer = function (config) {
+ if (utils_1.has(config, "traceInitPerf")) {
+ var userTraceInitPerf = config.traceInitPerf;
+ var traceIsNumber = typeof userTraceInitPerf === "number";
+ this.traceInitMaxIdent = traceIsNumber
+ ? userTraceInitPerf
+ : Infinity;
+ this.traceInitPerf = traceIsNumber
+ ? userTraceInitPerf > 0
+ : userTraceInitPerf;
+ }
+ else {
+ this.traceInitMaxIdent = 0;
+ this.traceInitPerf = parser_1.DEFAULT_PARSER_CONFIG.traceInitPerf;
+ }
+ this.traceInitIndent = -1;
+ };
+ PerformanceTracer.prototype.TRACE_INIT = function (phaseDesc, phaseImpl) {
+ // No need to optimize this using NOOP pattern because
+ // It is not called in a hot spot...
+ if (this.traceInitPerf === true) {
+ this.traceInitIndent++;
+ var indent = new Array(this.traceInitIndent + 1).join("\t");
+ if (this.traceInitIndent < this.traceInitMaxIdent) {
+ console.log(indent + "--> <" + phaseDesc + ">");
+ }
+ var _a = utils_1.timer(phaseImpl), time = _a.time, value = _a.value;
+ /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */
+ var traceMethod = time > 10 ? console.warn : console.log;
+ if (this.traceInitIndent < this.traceInitMaxIdent) {
+ traceMethod(indent + "<-- <" + phaseDesc + "> time: " + time + "ms");
+ }
+ this.traceInitIndent--;
+ return value;
+ }
+ else {
+ return phaseImpl();
+ }
+ };
+ return PerformanceTracer;
+}());
+exports.PerformanceTracer = PerformanceTracer;
+//# sourceMappingURL=perf_tracer.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/parser/traits/recognizer_api.js b/node_modules/chevrotain/lib/src/parse/parser/traits/recognizer_api.js
new file mode 100644
index 0000000..da47b49
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/parser/traits/recognizer_api.js
@@ -0,0 +1,343 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../../../utils/utils");
+var exceptions_public_1 = require("../../exceptions_public");
+var parser_1 = require("../parser");
+var errors_public_1 = require("../../errors_public");
+var checks_1 = require("../../grammar/checks");
+var gast_public_1 = require("../../grammar/gast/gast_public");
+/**
+ * This trait is responsible for implementing the public API
+ * for defining Chevrotain parsers, i.e:
+ * - CONSUME
+ * - RULE
+ * - OPTION
+ * - ...
+ */
+var RecognizerApi = /** @class */ (function () {
+ function RecognizerApi() {
+ }
+ RecognizerApi.prototype.ACTION = function (impl) {
+ return impl.call(this);
+ };
+ RecognizerApi.prototype.consume = function (idx, tokType, options) {
+ return this.consumeInternal(tokType, idx, options);
+ };
+ RecognizerApi.prototype.subrule = function (idx, ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, idx, options);
+ };
+ RecognizerApi.prototype.option = function (idx, actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, idx);
+ };
+ RecognizerApi.prototype.or = function (idx, altsOrOpts) {
+ return this.orInternal(altsOrOpts, idx);
+ };
+ RecognizerApi.prototype.many = function (idx, actionORMethodDef) {
+ return this.manyInternal(idx, actionORMethodDef);
+ };
+ RecognizerApi.prototype.atLeastOne = function (idx, actionORMethodDef) {
+ return this.atLeastOneInternal(idx, actionORMethodDef);
+ };
+ RecognizerApi.prototype.CONSUME = function (tokType, options) {
+ return this.consumeInternal(tokType, 0, options);
+ };
+ RecognizerApi.prototype.CONSUME1 = function (tokType, options) {
+ return this.consumeInternal(tokType, 1, options);
+ };
+ RecognizerApi.prototype.CONSUME2 = function (tokType, options) {
+ return this.consumeInternal(tokType, 2, options);
+ };
+ RecognizerApi.prototype.CONSUME3 = function (tokType, options) {
+ return this.consumeInternal(tokType, 3, options);
+ };
+ RecognizerApi.prototype.CONSUME4 = function (tokType, options) {
+ return this.consumeInternal(tokType, 4, options);
+ };
+ RecognizerApi.prototype.CONSUME5 = function (tokType, options) {
+ return this.consumeInternal(tokType, 5, options);
+ };
+ RecognizerApi.prototype.CONSUME6 = function (tokType, options) {
+ return this.consumeInternal(tokType, 6, options);
+ };
+ RecognizerApi.prototype.CONSUME7 = function (tokType, options) {
+ return this.consumeInternal(tokType, 7, options);
+ };
+ RecognizerApi.prototype.CONSUME8 = function (tokType, options) {
+ return this.consumeInternal(tokType, 8, options);
+ };
+ RecognizerApi.prototype.CONSUME9 = function (tokType, options) {
+ return this.consumeInternal(tokType, 9, options);
+ };
+ RecognizerApi.prototype.SUBRULE = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 0, options);
+ };
+ RecognizerApi.prototype.SUBRULE1 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 1, options);
+ };
+ RecognizerApi.prototype.SUBRULE2 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 2, options);
+ };
+ RecognizerApi.prototype.SUBRULE3 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 3, options);
+ };
+ RecognizerApi.prototype.SUBRULE4 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 4, options);
+ };
+ RecognizerApi.prototype.SUBRULE5 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 5, options);
+ };
+ RecognizerApi.prototype.SUBRULE6 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 6, options);
+ };
+ RecognizerApi.prototype.SUBRULE7 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 7, options);
+ };
+ RecognizerApi.prototype.SUBRULE8 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 8, options);
+ };
+ RecognizerApi.prototype.SUBRULE9 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 9, options);
+ };
+ RecognizerApi.prototype.OPTION = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 0);
+ };
+ RecognizerApi.prototype.OPTION1 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 1);
+ };
+ RecognizerApi.prototype.OPTION2 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 2);
+ };
+ RecognizerApi.prototype.OPTION3 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 3);
+ };
+ RecognizerApi.prototype.OPTION4 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 4);
+ };
+ RecognizerApi.prototype.OPTION5 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 5);
+ };
+ RecognizerApi.prototype.OPTION6 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 6);
+ };
+ RecognizerApi.prototype.OPTION7 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 7);
+ };
+ RecognizerApi.prototype.OPTION8 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 8);
+ };
+ RecognizerApi.prototype.OPTION9 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 9);
+ };
+ RecognizerApi.prototype.OR = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 0);
+ };
+ RecognizerApi.prototype.OR1 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 1);
+ };
+ RecognizerApi.prototype.OR2 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 2);
+ };
+ RecognizerApi.prototype.OR3 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 3);
+ };
+ RecognizerApi.prototype.OR4 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 4);
+ };
+ RecognizerApi.prototype.OR5 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 5);
+ };
+ RecognizerApi.prototype.OR6 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 6);
+ };
+ RecognizerApi.prototype.OR7 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 7);
+ };
+ RecognizerApi.prototype.OR8 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 8);
+ };
+ RecognizerApi.prototype.OR9 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 9);
+ };
+ RecognizerApi.prototype.MANY = function (actionORMethodDef) {
+ this.manyInternal(0, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY1 = function (actionORMethodDef) {
+ this.manyInternal(1, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY2 = function (actionORMethodDef) {
+ this.manyInternal(2, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY3 = function (actionORMethodDef) {
+ this.manyInternal(3, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY4 = function (actionORMethodDef) {
+ this.manyInternal(4, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY5 = function (actionORMethodDef) {
+ this.manyInternal(5, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY6 = function (actionORMethodDef) {
+ this.manyInternal(6, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY7 = function (actionORMethodDef) {
+ this.manyInternal(7, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY8 = function (actionORMethodDef) {
+ this.manyInternal(8, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY9 = function (actionORMethodDef) {
+ this.manyInternal(9, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY_SEP = function (options) {
+ this.manySepFirstInternal(0, options);
+ };
+ RecognizerApi.prototype.MANY_SEP1 = function (options) {
+ this.manySepFirstInternal(1, options);
+ };
+ RecognizerApi.prototype.MANY_SEP2 = function (options) {
+ this.manySepFirstInternal(2, options);
+ };
+ RecognizerApi.prototype.MANY_SEP3 = function (options) {
+ this.manySepFirstInternal(3, options);
+ };
+ RecognizerApi.prototype.MANY_SEP4 = function (options) {
+ this.manySepFirstInternal(4, options);
+ };
+ RecognizerApi.prototype.MANY_SEP5 = function (options) {
+ this.manySepFirstInternal(5, options);
+ };
+ RecognizerApi.prototype.MANY_SEP6 = function (options) {
+ this.manySepFirstInternal(6, options);
+ };
+ RecognizerApi.prototype.MANY_SEP7 = function (options) {
+ this.manySepFirstInternal(7, options);
+ };
+ RecognizerApi.prototype.MANY_SEP8 = function (options) {
+ this.manySepFirstInternal(8, options);
+ };
+ RecognizerApi.prototype.MANY_SEP9 = function (options) {
+ this.manySepFirstInternal(9, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE = function (actionORMethodDef) {
+ this.atLeastOneInternal(0, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE1 = function (actionORMethodDef) {
+ return this.atLeastOneInternal(1, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE2 = function (actionORMethodDef) {
+ this.atLeastOneInternal(2, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE3 = function (actionORMethodDef) {
+ this.atLeastOneInternal(3, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE4 = function (actionORMethodDef) {
+ this.atLeastOneInternal(4, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE5 = function (actionORMethodDef) {
+ this.atLeastOneInternal(5, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE6 = function (actionORMethodDef) {
+ this.atLeastOneInternal(6, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE7 = function (actionORMethodDef) {
+ this.atLeastOneInternal(7, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE8 = function (actionORMethodDef) {
+ this.atLeastOneInternal(8, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE9 = function (actionORMethodDef) {
+ this.atLeastOneInternal(9, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP = function (options) {
+ this.atLeastOneSepFirstInternal(0, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP1 = function (options) {
+ this.atLeastOneSepFirstInternal(1, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP2 = function (options) {
+ this.atLeastOneSepFirstInternal(2, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP3 = function (options) {
+ this.atLeastOneSepFirstInternal(3, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP4 = function (options) {
+ this.atLeastOneSepFirstInternal(4, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP5 = function (options) {
+ this.atLeastOneSepFirstInternal(5, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP6 = function (options) {
+ this.atLeastOneSepFirstInternal(6, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP7 = function (options) {
+ this.atLeastOneSepFirstInternal(7, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP8 = function (options) {
+ this.atLeastOneSepFirstInternal(8, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP9 = function (options) {
+ this.atLeastOneSepFirstInternal(9, options);
+ };
+ RecognizerApi.prototype.RULE = function (name, implementation, config) {
+ if (config === void 0) { config = parser_1.DEFAULT_RULE_CONFIG; }
+ if (utils_1.contains(this.definedRulesNames, name)) {
+ var errMsg = errors_public_1.defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({
+ topLevelRule: name,
+ grammarName: this.className
+ });
+ var error = {
+ message: errMsg,
+ type: parser_1.ParserDefinitionErrorType.DUPLICATE_RULE_NAME,
+ ruleName: name
+ };
+ this.definitionErrors.push(error);
+ }
+ this.definedRulesNames.push(name);
+ var ruleImplementation = this.defineRule(name, implementation, config);
+ this[name] = ruleImplementation;
+ return ruleImplementation;
+ };
+ RecognizerApi.prototype.OVERRIDE_RULE = function (name, impl, config) {
+ if (config === void 0) { config = parser_1.DEFAULT_RULE_CONFIG; }
+ var ruleErrors = [];
+ ruleErrors = ruleErrors.concat(checks_1.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 (exceptions_public_1.isRecognitionException(e)) {
+ return false;
+ }
+ else {
+ throw e;
+ }
+ }
+ finally {
+ this.reloadRecogState(orgState);
+ this.isBackTrackingStack.pop();
+ }
+ };
+ };
+ // GAST export APIs
+ RecognizerApi.prototype.getGAstProductions = function () {
+ return this.gastProductionsCache;
+ };
+ RecognizerApi.prototype.getSerializedGastProductions = function () {
+ return gast_public_1.serializeGrammar(utils_1.values(this.gastProductionsCache));
+ };
+ return RecognizerApi;
+}());
+exports.RecognizerApi = RecognizerApi;
+//# sourceMappingURL=recognizer_api.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/parser/traits/recognizer_engine.js b/node_modules/chevrotain/lib/src/parse/parser/traits/recognizer_engine.js
new file mode 100644
index 0000000..e488c86
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/parser/traits/recognizer_engine.js
@@ -0,0 +1,645 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../../../utils/utils");
+var keys_1 = require("../../grammar/keys");
+var exceptions_public_1 = require("../../exceptions_public");
+var lookahead_1 = require("../../grammar/lookahead");
+var interpreter_1 = require("../../grammar/interpreter");
+var parser_1 = require("../parser");
+var recoverable_1 = require("./recoverable");
+var tokens_public_1 = require("../../../scan/tokens_public");
+var tokens_1 = require("../../../scan/tokens");
+var lang_extensions_1 = require("../../../lang/lang_extensions");
+/**
+ * This trait is responsible for the runtime parsing engine
+ * Used by the official API (recognizer_api.ts)
+ */
+var RecognizerEngine = /** @class */ (function () {
+ function RecognizerEngine() {
+ }
+ RecognizerEngine.prototype.initRecognizerEngine = function (tokenVocabulary, config) {
+ this.className = lang_extensions_1.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 = tokens_1.tokenStructuredMatcherNoCategories;
+ this.definedRulesNames = [];
+ this.tokensMap = {};
+ this.allRuleNames = [];
+ this.isBackTrackingStack = [];
+ this.RULE_STACK = [];
+ this.RULE_OCCURRENCE_STACK = [];
+ this.gastProductionsCache = {};
+ if (utils_1.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 (utils_1.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 (utils_1.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 (utils_1.isArray(tokenVocabulary)) {
+ this.tokensMap = utils_1.reduce(tokenVocabulary, function (acc, tokType) {
+ acc[tokType.name] = tokType;
+ return acc;
+ }, {});
+ }
+ else if (utils_1.has(tokenVocabulary, "modes") &&
+ utils_1.every(utils_1.flatten(utils_1.values(tokenVocabulary.modes)), tokens_1.isTokenType)) {
+ var allTokenTypes = utils_1.flatten(utils_1.values(tokenVocabulary.modes));
+ var uniqueTokens = utils_1.uniq(allTokenTypes);
+ this.tokensMap = utils_1.reduce(uniqueTokens, function (acc, tokType) {
+ acc[tokType.name] = tokType;
+ return acc;
+ }, {});
+ }
+ else if (utils_1.isObject(tokenVocabulary)) {
+ this.tokensMap = utils_1.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"] = tokens_public_1.EOF;
+ // TODO: This check may not be accurate for multi mode lexers
+ var noTokenCategoriesUsed = utils_1.every(utils_1.values(tokenVocabulary), function (tokenConstructor) { return utils_1.isEmpty(tokenConstructor.categoryMatches); });
+ this.tokenMatcher = noTokenCategoriesUsed
+ ? tokens_1.tokenStructuredMatcherNoCategories
+ : tokens_1.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
+ tokens_1.augmentTokenTypes(utils_1.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 = utils_1.has(config, "resyncEnabled")
+ ? config.resyncEnabled
+ : parser_1.DEFAULT_RULE_CONFIG.resyncEnabled;
+ var recoveryValueFunc = utils_1.has(config, "recoveryValueFunc")
+ ? config.recoveryValueFunc
+ : parser_1.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 <<
+ (keys_1.BITS_FOR_METHOD_TYPE + keys_1.BITS_FOR_OCCURRENCE_IDX);
+ /* tslint:enable */
+ this.ruleShortNameIdx++;
+ this.shortRuleNameToFull[shortName] = ruleName;
+ this.fullRuleNameToShort[ruleName] = shortName;
+ function invokeRuleWithTry(args) {
+ try {
+ if (this.outputCst === true) {
+ impl.apply(this, args);
+ var cst = this.CST_STACK[this.CST_STACK.length - 1];
+ this.cstPostRule(cst);
+ return cst;
+ }
+ else {
+ return impl.apply(this, args);
+ }
+ }
+ catch (e) {
+ return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc);
+ }
+ finally {
+ this.ruleFinallyStateUpdate();
+ }
+ }
+ var wrappedGrammarRule;
+ wrappedGrammarRule = function (idxInCallingRule, args) {
+ if (idxInCallingRule === void 0) { idxInCallingRule = 0; }
+ this.ruleInvocationStateUpdate(shortName, ruleName, idxInCallingRule);
+ return invokeRuleWithTry.call(this, args);
+ };
+ var ruleNamePropName = "ruleName";
+ wrappedGrammarRule[ruleNamePropName] = ruleName;
+ wrappedGrammarRule["originalGrammarAction"] = impl;
+ return wrappedGrammarRule;
+ };
+ RecognizerEngine.prototype.invokeRuleCatch = function (e, resyncEnabledConfig, recoveryValueFunc) {
+ var isFirstInvokedRule = this.RULE_STACK.length === 1;
+ // note the reSync is always enabled for the first rule invocation, because we must always be able to
+ // reSync with EOF and just output some INVALID ParseTree
+ // during backtracking reSync recovery is disabled, otherwise we can't be certain the backtracking
+ // path is really the most valid one
+ var reSyncEnabled = resyncEnabledConfig &&
+ !this.isBackTracking() &&
+ this.recoveryEnabled;
+ if (exceptions_public_1.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(keys_1.OPTION_IDX, occurrence);
+ var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, key);
+ try {
+ return this.optionInternalLogic(actionORMethodDef, occurrence, key);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(key, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.optionInternalNoCst = function (actionORMethodDef, occurrence) {
+ var key = this.getKeyForAutomaticLookahead(keys_1.OPTION_IDX, occurrence);
+ return this.optionInternalLogic(actionORMethodDef, occurrence, key);
+ };
+ RecognizerEngine.prototype.optionInternalLogic = function (actionORMethodDef, occurrence, key) {
+ var _this = this;
+ var lookAheadFunc = this.getLaFuncFromCache(key);
+ var action;
+ var predicate;
+ if (actionORMethodDef.DEF !== undefined) {
+ action = actionORMethodDef.DEF;
+ predicate = actionORMethodDef.GATE;
+ // predicate present
+ if (predicate !== undefined) {
+ var orgLookaheadFunction_1 = lookAheadFunc;
+ lookAheadFunc = function () {
+ return (predicate.call(_this) && orgLookaheadFunction_1.call(_this));
+ };
+ }
+ }
+ else {
+ action = actionORMethodDef;
+ }
+ if (lookAheadFunc.call(this) === true) {
+ return action.call(this);
+ }
+ return undefined;
+ };
+ RecognizerEngine.prototype.atLeastOneInternal = function (prodOccurrence, actionORMethodDef) {
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.AT_LEAST_ONE_IDX, prodOccurrence);
+ var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, laKey);
+ try {
+ return this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, laKey);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.atLeastOneInternalNoCst = function (prodOccurrence, actionORMethodDef) {
+ var key = this.getKeyForAutomaticLookahead(keys_1.AT_LEAST_ONE_IDX, prodOccurrence);
+ this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, key);
+ };
+ RecognizerEngine.prototype.atLeastOneInternalLogic = function (prodOccurrence, actionORMethodDef, key) {
+ var _this = this;
+ var lookAheadFunc = this.getLaFuncFromCache(key);
+ var action;
+ var predicate;
+ if (actionORMethodDef.DEF !== undefined) {
+ action = actionORMethodDef.DEF;
+ predicate = actionORMethodDef.GATE;
+ // predicate present
+ if (predicate !== undefined) {
+ var orgLookaheadFunction_2 = lookAheadFunc;
+ lookAheadFunc = function () {
+ return (predicate.call(_this) && orgLookaheadFunction_2.call(_this));
+ };
+ }
+ }
+ else {
+ action = actionORMethodDef;
+ }
+ if (lookAheadFunc.call(this) === true) {
+ var notStuck = this.doSingleRepetition(action);
+ while (lookAheadFunc.call(this) === true &&
+ notStuck === true) {
+ notStuck = this.doSingleRepetition(action);
+ }
+ }
+ else {
+ throw this.raiseEarlyExitException(prodOccurrence, lookahead_1.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, keys_1.AT_LEAST_ONE_IDX, prodOccurrence, interpreter_1.NextTerminalAfterAtLeastOneWalker);
+ };
+ RecognizerEngine.prototype.atLeastOneSepFirstInternal = function (prodOccurrence, options) {
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.AT_LEAST_ONE_SEP_IDX, prodOccurrence);
+ var nestedName = this.nestedRuleBeforeClause(options, laKey);
+ try {
+ this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.atLeastOneSepFirstInternalNoCst = function (prodOccurrence, options) {
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.AT_LEAST_ONE_SEP_IDX, prodOccurrence);
+ this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey);
+ };
+ RecognizerEngine.prototype.atLeastOneSepFirstInternalLogic = function (prodOccurrence, options, key) {
+ var _this = this;
+ var action = options.DEF;
+ var separator = options.SEP;
+ var firstIterationLookaheadFunc = this.getLaFuncFromCache(key);
+ // 1st iteration
+ if (firstIterationLookaheadFunc.call(this) === true) {
+ ;
+ action.call(this);
+ // TODO: Optimization can move this function construction into "attemptInRepetitionRecovery"
+ // because it is only needed in error recovery scenarios.
+ var separatorLookAheadFunc = function () {
+ return _this.tokenMatcher(_this.LA(1), separator);
+ };
+ // 2nd..nth iterations
+ while (this.tokenMatcher(this.LA(1), separator) === true) {
+ // note that this CONSUME will never enter recovery because
+ // the separatorLookAheadFunc checks that the separator really does exist.
+ this.CONSUME(separator);
+ action.call(this);
+ }
+ // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled
+ this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [
+ prodOccurrence,
+ separator,
+ separatorLookAheadFunc,
+ action,
+ interpreter_1.NextTerminalAfterAtLeastOneSepWalker
+ ], separatorLookAheadFunc, keys_1.AT_LEAST_ONE_SEP_IDX, prodOccurrence, interpreter_1.NextTerminalAfterAtLeastOneSepWalker);
+ }
+ else {
+ throw this.raiseEarlyExitException(prodOccurrence, lookahead_1.PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, options.ERR_MSG);
+ }
+ };
+ RecognizerEngine.prototype.manyInternal = function (prodOccurrence, actionORMethodDef) {
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.MANY_IDX, prodOccurrence);
+ var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, laKey);
+ try {
+ return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.manyInternalNoCst = function (prodOccurrence, actionORMethodDef) {
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.MANY_IDX, prodOccurrence);
+ return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey);
+ };
+ RecognizerEngine.prototype.manyInternalLogic = function (prodOccurrence, actionORMethodDef, key) {
+ var _this = this;
+ var lookaheadFunction = this.getLaFuncFromCache(key);
+ var action;
+ var predicate;
+ if (actionORMethodDef.DEF !== undefined) {
+ action = actionORMethodDef.DEF;
+ predicate = actionORMethodDef.GATE;
+ // predicate present
+ if (predicate !== undefined) {
+ var orgLookaheadFunction_3 = lookaheadFunction;
+ lookaheadFunction = function () {
+ return (predicate.call(_this) && orgLookaheadFunction_3.call(_this));
+ };
+ }
+ }
+ else {
+ action = actionORMethodDef;
+ }
+ var notStuck = true;
+ while (lookaheadFunction.call(this) === true && notStuck === true) {
+ notStuck = this.doSingleRepetition(action);
+ }
+ // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled
+ this.attemptInRepetitionRecovery(this.manyInternal, [prodOccurrence, actionORMethodDef], lookaheadFunction, keys_1.MANY_IDX, prodOccurrence, interpreter_1.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(keys_1.MANY_SEP_IDX, prodOccurrence);
+ var nestedName = this.nestedRuleBeforeClause(options, laKey);
+ try {
+ this.manySepFirstInternalLogic(prodOccurrence, options, laKey);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.manySepFirstInternalNoCst = function (prodOccurrence, options) {
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.MANY_SEP_IDX, prodOccurrence);
+ this.manySepFirstInternalLogic(prodOccurrence, options, laKey);
+ };
+ RecognizerEngine.prototype.manySepFirstInternalLogic = function (prodOccurrence, options, key) {
+ var _this = this;
+ var action = options.DEF;
+ var separator = options.SEP;
+ var firstIterationLaFunc = this.getLaFuncFromCache(key);
+ // 1st iteration
+ if (firstIterationLaFunc.call(this) === true) {
+ action.call(this);
+ var separatorLookAheadFunc = function () {
+ return _this.tokenMatcher(_this.LA(1), separator);
+ };
+ // 2nd..nth iterations
+ while (this.tokenMatcher(this.LA(1), separator) === true) {
+ // note that this CONSUME will never enter recovery because
+ // the separatorLookAheadFunc checks that the separator really does exist.
+ this.CONSUME(separator);
+ // No need for checking infinite loop here due to consuming the separator.
+ action.call(this);
+ }
+ // Performance optimization: "attemptInRepetitionRecovery" will be defined as NOOP unless recovery is enabled
+ this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [
+ prodOccurrence,
+ separator,
+ separatorLookAheadFunc,
+ action,
+ interpreter_1.NextTerminalAfterManySepWalker
+ ], separatorLookAheadFunc, keys_1.MANY_SEP_IDX, prodOccurrence, interpreter_1.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, keys_1.AT_LEAST_ONE_SEP_IDX, prodOccurrence, nextTerminalAfterWalker);
+ };
+ RecognizerEngine.prototype.doSingleRepetition = function (action) {
+ var beforeIteration = this.getLexerPosition();
+ action.call(this);
+ var afterIteration = this.getLexerPosition();
+ // This boolean will indicate if this repetition progressed
+ // or if we are "stuck" (potential infinite loop in the repetition).
+ return afterIteration > beforeIteration;
+ };
+ RecognizerEngine.prototype.orInternalNoCst = function (altsOrOpts, occurrence) {
+ var alts = utils_1.isArray(altsOrOpts)
+ ? altsOrOpts
+ : altsOrOpts.DEF;
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.OR_IDX, occurrence);
+ var laFunc = this.getLaFuncFromCache(laKey);
+ var altIdxToTake = laFunc.call(this, alts);
+ if (altIdxToTake !== undefined) {
+ var chosenAlternative = alts[altIdxToTake];
+ return chosenAlternative.ALT.call(this);
+ }
+ this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG);
+ };
+ RecognizerEngine.prototype.orInternal = function (altsOrOpts, occurrence) {
+ var laKey = this.getKeyForAutomaticLookahead(keys_1.OR_IDX, occurrence);
+ var nestedName = this.nestedRuleBeforeClause(altsOrOpts, laKey);
+ try {
+ var alts = utils_1.isArray(altsOrOpts)
+ ? altsOrOpts
+ : altsOrOpts.DEF;
+ var laFunc = this.getLaFuncFromCache(laKey);
+ var altIdxToTake = laFunc.call(this, alts);
+ if (altIdxToTake !== undefined) {
+ var chosenAlternative = alts[altIdxToTake];
+ var nestedAltBeforeClauseResult = this.nestedAltBeforeClause(chosenAlternative, occurrence, keys_1.OR_IDX, altIdxToTake);
+ try {
+ return chosenAlternative.ALT.call(this);
+ }
+ finally {
+ if (nestedAltBeforeClauseResult !== undefined) {
+ this.nestedRuleFinallyClause(nestedAltBeforeClauseResult.shortName, nestedAltBeforeClauseResult.nestedName);
+ }
+ }
+ }
+ this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.ruleFinallyStateUpdate = function () {
+ this.RULE_STACK.pop();
+ this.RULE_OCCURRENCE_STACK.pop();
+ // NOOP when cst is disabled
+ this.cstFinallyStateUpdate();
+ if (this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) {
+ var firstRedundantTok = this.LA(1);
+ var errMsg = this.errorMessageProvider.buildNotAllInputParsedMessage({
+ firstRedundant: firstRedundantTok,
+ ruleName: this.getCurrRuleFullName()
+ });
+ this.SAVE_ERROR(new exceptions_public_1.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 (exceptions_public_1.isRecognitionException(e) && e.partialCstResult !== undefined) {
+ this.cstPostNonTerminal(e.partialCstResult, options !== undefined && options.LABEL !== undefined
+ ? options.LABEL
+ : ruleName);
+ delete e.partialCstResult;
+ }
+ throw e;
+ };
+ RecognizerEngine.prototype.consumeInternal = function (tokType, idx, options) {
+ var consumedToken;
+ try {
+ var nextToken = this.LA(1);
+ if (this.tokenMatcher(nextToken, tokType) === true) {
+ this.consumeToken();
+ consumedToken = nextToken;
+ }
+ else {
+ this.consumeInternalError(tokType, nextToken, options);
+ }
+ }
+ catch (eFromConsumption) {
+ consumedToken = this.consumeInternalRecovery(tokType, idx, eFromConsumption);
+ }
+ this.cstPostTerminal(options !== undefined && options.LABEL !== undefined
+ ? options.LABEL
+ : tokType.name, consumedToken);
+ return consumedToken;
+ };
+ RecognizerEngine.prototype.consumeInternalError = function (tokType, nextToken, options) {
+ var msg;
+ var previousToken = this.LA(0);
+ if (options !== undefined && options.ERR_MSG) {
+ msg = options.ERR_MSG;
+ }
+ else {
+ msg = this.errorMessageProvider.buildMismatchTokenMessage({
+ expected: tokType,
+ actual: nextToken,
+ previous: previousToken,
+ ruleName: this.getCurrRuleFullName()
+ });
+ }
+ throw this.SAVE_ERROR(new exceptions_public_1.MismatchedTokenException(msg, nextToken, previousToken));
+ };
+ RecognizerEngine.prototype.consumeInternalRecovery = function (tokType, idx, eFromConsumption) {
+ // no recovery allowed during backtracking, otherwise backtracking may recover invalid syntax and accept it
+ // but the original syntax could have been parsed successfully without any backtracking + recovery
+ if (this.recoveryEnabled &&
+ // TODO: more robust checking of the exception type. Perhaps Typescript extending expressions?
+ eFromConsumption.name === "MismatchedTokenException" &&
+ !this.isBackTracking()) {
+ var follows = this.getFollowsForInRuleRecovery(tokType, idx);
+ try {
+ return this.tryInRuleRecovery(tokType, follows);
+ }
+ catch (eFromInRuleRecovery) {
+ if (eFromInRuleRecovery.name === recoverable_1.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 = utils_1.cloneArr(this.RULE_STACK);
+ return {
+ errors: savedErrors,
+ lexerState: this.exportLexerState(),
+ RULE_STACK: savedRuleStack,
+ CST_STACK: this.CST_STACK,
+ LAST_EXPLICIT_RULE_STACK: this.LAST_EXPLICIT_RULE_STACK
+ };
+ };
+ RecognizerEngine.prototype.reloadRecogState = function (newState) {
+ this.errors = newState.errors;
+ this.importLexerState(newState.lexerState);
+ this.RULE_STACK = newState.RULE_STACK;
+ };
+ RecognizerEngine.prototype.ruleInvocationStateUpdate = function (shortName, fullName, idxInCallingRule) {
+ this.RULE_OCCURRENCE_STACK.push(idxInCallingRule);
+ this.RULE_STACK.push(shortName);
+ // NOOP when cst is disabled
+ this.cstInvocationStateUpdate(fullName, shortName);
+ };
+ RecognizerEngine.prototype.isBackTracking = function () {
+ return this.isBackTrackingStack.length !== 0;
+ };
+ RecognizerEngine.prototype.getCurrRuleFullName = function () {
+ var shortName = this.getLastExplicitRuleShortName();
+ return this.shortRuleNameToFull[shortName];
+ };
+ RecognizerEngine.prototype.shortRuleNameToFullName = function (shortName) {
+ return this.shortRuleNameToFull[shortName];
+ };
+ RecognizerEngine.prototype.isAtEndOfInput = function () {
+ return this.tokenMatcher(this.LA(1), tokens_public_1.EOF);
+ };
+ RecognizerEngine.prototype.reset = function () {
+ this.resetLexerState();
+ this.isBackTrackingStack = [];
+ this.errors = [];
+ this.RULE_STACK = [];
+ this.LAST_EXPLICIT_RULE_STACK = [];
+ // TODO: extract a specific rest for TreeBuilder trait
+ this.CST_STACK = [];
+ this.RULE_OCCURRENCE_STACK = [];
+ };
+ return RecognizerEngine;
+}());
+exports.RecognizerEngine = RecognizerEngine;
+//# sourceMappingURL=recognizer_engine.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/parser/traits/recoverable.js b/node_modules/chevrotain/lib/src/parse/parser/traits/recoverable.js
new file mode 100644
index 0000000..692d5fd
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/parser/traits/recoverable.js
@@ -0,0 +1,309 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var tokens_public_1 = require("../../../scan/tokens_public");
+var utils_1 = require("../../../utils/utils");
+var exceptions_public_1 = require("../../exceptions_public");
+var constants_1 = require("../../constants");
+var parser_1 = require("../parser");
+exports.EOF_FOLLOW_KEY = {};
+exports.IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException";
+function InRuleRecoveryException(message) {
+ this.name = exports.IN_RULE_RECOVERY_EXCEPTION;
+ this.message = message;
+}
+exports.InRuleRecoveryException = InRuleRecoveryException;
+InRuleRecoveryException.prototype = Error.prototype;
+/**
+ * This trait is responsible for the error recovery and fault tolerant logic
+ */
+var Recoverable = /** @class */ (function () {
+ function Recoverable() {
+ }
+ Recoverable.prototype.initRecoverable = function (config) {
+ this.firstAfterRepMap = {};
+ this.resyncFollows = {};
+ this.recoveryEnabled = utils_1.has(config, "recoveryEnabled")
+ ? config.recoveryEnabled
+ : parser_1.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 = tokens_public_1.createTokenInstance(tokType, "", NaN, NaN, NaN, NaN, NaN, NaN);
+ tokToInsert.isInsertedInRecovery = true;
+ return tokToInsert;
+ };
+ Recoverable.prototype.canTokenTypeBeInsertedInRecovery = function (tokType) {
+ return true;
+ };
+ Recoverable.prototype.tryInRepetitionRecovery = function (grammarRule, grammarRuleArgs, lookAheadFunc, expectedTokType) {
+ var _this = this;
+ // TODO: can the resyncTokenType be cached?
+ var reSyncTokType = this.findReSyncTokenType();
+ var savedLexerState = this.exportLexerState();
+ var resyncedTokens = [];
+ var passedResyncPoint = false;
+ var nextTokenWithoutResync = this.LA(1);
+ var currToken = this.LA(1);
+ var generateErrorMessage = function () {
+ var previousToken = _this.LA(0);
+ // we are preemptively re-syncing before an error has been detected, therefor we must reproduce
+ // the error that would have been thrown
+ var msg = _this.errorMessageProvider.buildMismatchTokenMessage({
+ expected: expectedTokType,
+ actual: nextTokenWithoutResync,
+ previous: previousToken,
+ ruleName: _this.getCurrRuleFullName()
+ });
+ var error = new exceptions_public_1.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 = utils_1.dropRight(resyncedTokens);
+ _this.SAVE_ERROR(error);
+ };
+ while (!passedResyncPoint) {
+ // re-synced to a point where we can safely exit the repetition/
+ if (this.tokenMatcher(currToken, expectedTokType)) {
+ generateErrorMessage();
+ return; // must return here to avoid reverting the inputIdx
+ }
+ else if (lookAheadFunc.call(this)) {
+ // we skipped enough tokens so we can resync right back into another iteration of the repetition grammar rule
+ generateErrorMessage();
+ // recursive invocation in other to support multiple re-syncs in the same top level repetition grammar rule
+ grammarRule.apply(this, grammarRuleArgs);
+ return; // must return here to avoid reverting the inputIdx
+ }
+ else if (this.tokenMatcher(currToken, reSyncTokType)) {
+ passedResyncPoint = true;
+ }
+ else {
+ currToken = this.SKIP_TOKEN();
+ this.addToResyncTokens(currToken, resyncedTokens);
+ }
+ }
+ // we were unable to find a CLOSER point to resync inside the Repetition, reset the state.
+ // The parsing exception we were trying to prevent will happen in the NEXT parsing step. it may be handled by
+ // "between rules" resync recovery later in the flow.
+ this.importLexerState(savedLexerState);
+ };
+ Recoverable.prototype.shouldInRepetitionRecoveryBeTried = function (expectTokAfterLastMatch, nextTokIdx, notStuck) {
+ // Edge case of arriving from a MANY repetition which is stuck
+ // Attempting recovery in this case could cause an infinite loop
+ if (notStuck === false) {
+ return false;
+ }
+ // arguments to try and perform resync into the next iteration of the many are missing
+ if (expectTokAfterLastMatch === undefined || nextTokIdx === undefined) {
+ return false;
+ }
+ // no need to recover, next token is what we expect...
+ if (this.tokenMatcher(this.LA(1), expectTokAfterLastMatch)) {
+ return false;
+ }
+ // error recovery is disabled during backtracking as it can make the parser ignore a valid grammar path
+ // and prefer some backtracking path that includes recovered errors.
+ if (this.isBackTracking()) {
+ return false;
+ }
+ // if we can perform inRule recovery (single token insertion or deletion) we always prefer that recovery algorithm
+ // because if it works, it makes the least amount of changes to the input stream (greedy algorithm)
+ //noinspection RedundantIfStatementJS
+ if (this.canPerformInRuleRecovery(expectTokAfterLastMatch, this.getFollowsForInRuleRecovery(expectTokAfterLastMatch, nextTokIdx))) {
+ return false;
+ }
+ return true;
+ };
+ // Error Recovery functionality
+ Recoverable.prototype.getFollowsForInRuleRecovery = function (tokType, tokIdxInRule) {
+ var grammarPath = this.getCurrentGrammarPath(tokType, tokIdxInRule);
+ var follows = this.getNextPossibleTokenTypes(grammarPath);
+ return follows;
+ };
+ Recoverable.prototype.tryInRuleRecovery = function (expectedTokType, follows) {
+ if (this.canRecoverWithSingleTokenInsertion(expectedTokType, follows)) {
+ var tokToInsert = this.getTokenToInsert(expectedTokType);
+ return tokToInsert;
+ }
+ if (this.canRecoverWithSingleTokenDeletion(expectedTokType)) {
+ var nextTok = this.SKIP_TOKEN();
+ this.consumeToken();
+ return nextTok;
+ }
+ throw new InRuleRecoveryException("sad sad panda");
+ };
+ Recoverable.prototype.canPerformInRuleRecovery = function (expectedToken, follows) {
+ return (this.canRecoverWithSingleTokenInsertion(expectedToken, follows) ||
+ this.canRecoverWithSingleTokenDeletion(expectedToken));
+ };
+ Recoverable.prototype.canRecoverWithSingleTokenInsertion = function (expectedTokType, follows) {
+ var _this = this;
+ if (!this.canTokenTypeBeInsertedInRecovery(expectedTokType)) {
+ return false;
+ }
+ // must know the possible following tokens to perform single token insertion
+ if (utils_1.isEmpty(follows)) {
+ return false;
+ }
+ var mismatchedTok = this.LA(1);
+ var isMisMatchedTokInFollows = utils_1.find(follows, function (possibleFollowsTokType) {
+ return _this.tokenMatcher(mismatchedTok, possibleFollowsTokType);
+ }) !== undefined;
+ return isMisMatchedTokInFollows;
+ };
+ Recoverable.prototype.canRecoverWithSingleTokenDeletion = function (expectedTokType) {
+ var isNextTokenWhatIsExpected = this.tokenMatcher(this.LA(2), expectedTokType);
+ return isNextTokenWhatIsExpected;
+ };
+ Recoverable.prototype.isInCurrentRuleReSyncSet = function (tokenTypeIdx) {
+ var followKey = this.getCurrFollowKey();
+ var currentRuleReSyncSet = this.getFollowSetFromFollowKey(followKey);
+ return utils_1.contains(currentRuleReSyncSet, tokenTypeIdx);
+ };
+ Recoverable.prototype.findReSyncTokenType = function () {
+ var allPossibleReSyncTokTypes = this.flattenFollowSet();
+ // this loop will always terminate as EOF is always in the follow stack and also always (virtually) in the input
+ var nextToken = this.LA(1);
+ var k = 2;
+ while (true) {
+ var nextTokenType = nextToken.tokenType;
+ if (utils_1.contains(allPossibleReSyncTokTypes, nextTokenType)) {
+ return nextTokenType;
+ }
+ nextToken = this.LA(k);
+ k++;
+ }
+ };
+ Recoverable.prototype.getCurrFollowKey = function () {
+ // the length is at least one as we always add the ruleName to the stack before invoking the rule.
+ if (this.RULE_STACK.length === 1) {
+ return exports.EOF_FOLLOW_KEY;
+ }
+ var currRuleShortName = this.getLastExplicitRuleShortName();
+ var currRuleIdx = this.getLastExplicitRuleOccurrenceIndex();
+ var prevRuleShortName = this.getPreviousExplicitRuleShortName();
+ return {
+ ruleName: this.shortRuleNameToFullName(currRuleShortName),
+ idxInCallingRule: currRuleIdx,
+ inRule: this.shortRuleNameToFullName(prevRuleShortName)
+ };
+ };
+ Recoverable.prototype.buildFullFollowKeyStack = function () {
+ var _this = this;
+ var explicitRuleStack = this.RULE_STACK;
+ var explicitOccurrenceStack = this.RULE_OCCURRENCE_STACK;
+ if (!utils_1.isEmpty(this.LAST_EXPLICIT_RULE_STACK)) {
+ explicitRuleStack = utils_1.map(this.LAST_EXPLICIT_RULE_STACK, function (idx) { return _this.RULE_STACK[idx]; });
+ explicitOccurrenceStack = utils_1.map(this.LAST_EXPLICIT_RULE_STACK, function (idx) { return _this.RULE_OCCURRENCE_STACK[idx]; });
+ }
+ // TODO: only iterate over explicit rules here
+ return utils_1.map(explicitRuleStack, function (ruleName, idx) {
+ if (idx === 0) {
+ return exports.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 = utils_1.map(this.buildFullFollowKeyStack(), function (currKey) {
+ return _this.getFollowSetFromFollowKey(currKey);
+ });
+ return utils_1.flatten(followStack);
+ };
+ Recoverable.prototype.getFollowSetFromFollowKey = function (followKey) {
+ if (followKey === exports.EOF_FOLLOW_KEY) {
+ return [tokens_public_1.EOF];
+ }
+ var followName = followKey.ruleName +
+ followKey.idxInCallingRule +
+ constants_1.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, tokens_public_1.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 utils_1.dropRight(resyncedTokens);
+ };
+ Recoverable.prototype.attemptInRepetitionRecovery = function (prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) {
+ // by default this is a NO-OP
+ // The actual implementation is with the function(not method) below
+ };
+ Recoverable.prototype.getCurrentGrammarPath = function (tokType, tokIdxInRule) {
+ var pathRuleStack = this.getHumanReadableRuleStack();
+ var pathOccurrenceStack = utils_1.cloneArr(this.RULE_OCCURRENCE_STACK);
+ var grammarPath = {
+ ruleStack: pathRuleStack,
+ occurrenceStack: pathOccurrenceStack,
+ lastTok: tokType,
+ lastTokOccurrence: tokIdxInRule
+ };
+ return grammarPath;
+ };
+ Recoverable.prototype.getHumanReadableRuleStack = function () {
+ var _this = this;
+ if (!utils_1.isEmpty(this.LAST_EXPLICIT_RULE_STACK)) {
+ return utils_1.map(this.LAST_EXPLICIT_RULE_STACK, function (currIdx) {
+ return _this.shortRuleNameToFullName(_this.RULE_STACK[currIdx]);
+ });
+ }
+ else {
+ return utils_1.map(this.RULE_STACK, function (currShortName) {
+ return _this.shortRuleNameToFullName(currShortName);
+ });
+ }
+ };
+ return Recoverable;
+}());
+exports.Recoverable = 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 = tokens_public_1.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);
+ }
+}
+exports.attemptInRepetitionRecovery = attemptInRepetitionRecovery;
+//# sourceMappingURL=recoverable.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/parse/parser/traits/tree_builder.js b/node_modules/chevrotain/lib/src/parse/parser/traits/tree_builder.js
new file mode 100644
index 0000000..9d9fe7b
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/parse/parser/traits/tree_builder.js
@@ -0,0 +1,290 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var cst_1 = require("../../cst/cst");
+var utils_1 = require("../../../utils/utils");
+var cst_visitor_1 = require("../../cst/cst_visitor");
+var keys_1 = require("../../grammar/keys");
+var parser_1 = require("../parser");
+/**
+ * This trait is responsible for the CST building logic.
+ */
+var TreeBuilder = /** @class */ (function () {
+ function TreeBuilder() {
+ }
+ TreeBuilder.prototype.initTreeBuilder = function (config) {
+ this.LAST_EXPLICIT_RULE_STACK = [];
+ this.CST_STACK = [];
+ this.outputCst = utils_1.has(config, "outputCst")
+ ? config.outputCst
+ : parser_1.DEFAULT_PARSER_CONFIG.outputCst;
+ this.nodeLocationTracking = utils_1.has(config, "nodeLocationTracking")
+ ? config.nodeLocationTracking
+ : parser_1.DEFAULT_PARSER_CONFIG.nodeLocationTracking;
+ if (!this.outputCst) {
+ this.cstInvocationStateUpdate = utils_1.NOOP;
+ this.cstFinallyStateUpdate = utils_1.NOOP;
+ this.cstPostTerminal = utils_1.NOOP;
+ this.cstPostNonTerminal = utils_1.NOOP;
+ this.cstPostRule = utils_1.NOOP;
+ this.getLastExplicitRuleShortName = this.getLastExplicitRuleShortNameNoCst;
+ this.getPreviousExplicitRuleShortName = this.getPreviousExplicitRuleShortNameNoCst;
+ this.getLastExplicitRuleOccurrenceIndex = this.getLastExplicitRuleOccurrenceIndexNoCst;
+ this.manyInternal = this.manyInternalNoCst;
+ this.orInternal = this.orInternalNoCst;
+ this.optionInternal = this.optionInternalNoCst;
+ this.atLeastOneInternal = this.atLeastOneInternalNoCst;
+ this.manySepFirstInternal = this.manySepFirstInternalNoCst;
+ this.atLeastOneSepFirstInternal = this.atLeastOneSepFirstInternalNoCst;
+ }
+ else {
+ if (/full/i.test(this.nodeLocationTracking)) {
+ if (this.recoveryEnabled) {
+ this.setNodeLocationFromToken = cst_1.setNodeLocationFull;
+ this.setNodeLocationFromNode = cst_1.setNodeLocationFull;
+ this.cstPostRule = utils_1.NOOP;
+ this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery;
+ }
+ else {
+ this.setNodeLocationFromToken = utils_1.NOOP;
+ this.setNodeLocationFromNode = utils_1.NOOP;
+ this.cstPostRule = this.cstPostRuleFull;
+ this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular;
+ }
+ }
+ else if (/onlyOffset/i.test(this.nodeLocationTracking)) {
+ if (this.recoveryEnabled) {
+ this.setNodeLocationFromToken = (cst_1.setNodeLocationOnlyOffset);
+ this.setNodeLocationFromNode = (cst_1.setNodeLocationOnlyOffset);
+ this.cstPostRule = utils_1.NOOP;
+ this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery;
+ }
+ else {
+ this.setNodeLocationFromToken = utils_1.NOOP;
+ this.setNodeLocationFromNode = utils_1.NOOP;
+ this.cstPostRule = this.cstPostRuleOnlyOffset;
+ this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular;
+ }
+ }
+ else if (/none/i.test(this.nodeLocationTracking)) {
+ this.setNodeLocationFromToken = utils_1.NOOP;
+ this.setNodeLocationFromNode = utils_1.NOOP;
+ this.cstPostRule = utils_1.NOOP;
+ this.setInitialNodeLocation = utils_1.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
+ };
+ };
+ // CST
+ TreeBuilder.prototype.cstNestedInvocationStateUpdate = function (nestedName, shortName) {
+ var cstNode = {
+ name: nestedName,
+ fullName: this.shortRuleNameToFull[this.getLastExplicitRuleShortName()] +
+ nestedName,
+ children: {}
+ };
+ this.setInitialNodeLocation(cstNode);
+ this.CST_STACK.push(cstNode);
+ };
+ TreeBuilder.prototype.cstInvocationStateUpdate = function (fullRuleName, shortName) {
+ this.LAST_EXPLICIT_RULE_STACK.push(this.RULE_STACK.length - 1);
+ var cstNode = {
+ name: fullRuleName,
+ children: {}
+ };
+ this.setInitialNodeLocation(cstNode);
+ this.CST_STACK.push(cstNode);
+ };
+ TreeBuilder.prototype.cstFinallyStateUpdate = function () {
+ this.LAST_EXPLICIT_RULE_STACK.pop();
+ this.CST_STACK.pop();
+ };
+ TreeBuilder.prototype.cstNestedFinallyStateUpdate = function () {
+ var lastCstNode = this.CST_STACK.pop();
+ // TODO: the naming is bad, this should go directly to the
+ // (correct) cstLocation update method
+ // e.g if we put other logic in postRule...
+ this.cstPostRule(lastCstNode);
+ };
+ TreeBuilder.prototype.cstPostRuleFull = function (ruleCstNode) {
+ var prevToken = this.LA(0);
+ var loc = ruleCstNode.location;
+ // If this condition is true it means we consumed at least one Token
+ // In this CstNode or its nested children.
+ if (loc.startOffset <= prevToken.startOffset === true) {
+ loc.endOffset = prevToken.endOffset;
+ loc.endLine = prevToken.endLine;
+ loc.endColumn = prevToken.endColumn;
+ }
+ // "empty" CstNode edge case
+ else {
+ loc.startOffset = NaN;
+ loc.startLine = NaN;
+ loc.startColumn = NaN;
+ }
+ };
+ TreeBuilder.prototype.cstPostRuleOnlyOffset = function (ruleCstNode) {
+ var prevToken = this.LA(0);
+ var loc = ruleCstNode.location;
+ // If this condition is true it means we consumed at least one Token
+ // In this CstNode or its nested children.
+ if (loc.startOffset <= prevToken.startOffset === true) {
+ loc.endOffset = prevToken.endOffset;
+ }
+ // "empty" CstNode edge case
+ else {
+ loc.startOffset = NaN;
+ }
+ };
+ TreeBuilder.prototype.cstPostTerminal = function (key, consumedToken) {
+ var rootCst = this.CST_STACK[this.CST_STACK.length - 1];
+ cst_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) {
+ // Avoid side effects due to back tracking
+ // TODO: This costs a 2-3% in performance, A flag on IParserConfig
+ // could be used to get rid of this conditional, but not sure its worth the effort
+ // and API complexity.
+ if (this.isBackTracking() !== true) {
+ var preCstNode = this.CST_STACK[this.CST_STACK.length - 1];
+ cst_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 (utils_1.isUndefined(this.baseCstVisitorConstructor)) {
+ var newBaseCstVisitorConstructor = cst_visitor_1.createBaseSemanticVisitorConstructor(this.className, this.allRuleNames);
+ this.baseCstVisitorConstructor = newBaseCstVisitorConstructor;
+ return newBaseCstVisitorConstructor;
+ }
+ return this.baseCstVisitorConstructor;
+ };
+ TreeBuilder.prototype.getBaseCstVisitorConstructorWithDefaults = function () {
+ if (utils_1.isUndefined(this.baseCstVisitorWithDefaultsConstructor)) {
+ var newConstructor = cst_visitor_1.createBaseVisitorConstructorWithDefaults(this.className, this.allRuleNames, this.getBaseCstVisitorConstructor());
+ this.baseCstVisitorWithDefaultsConstructor = newConstructor;
+ return newConstructor;
+ }
+ return this.baseCstVisitorWithDefaultsConstructor;
+ };
+ TreeBuilder.prototype.nestedRuleBeforeClause = function (methodOpts, laKey) {
+ var nestedName;
+ if (methodOpts.NAME !== undefined) {
+ nestedName = methodOpts.NAME;
+ this.nestedRuleInvocationStateUpdate(nestedName, laKey);
+ return nestedName;
+ }
+ else {
+ return undefined;
+ }
+ };
+ TreeBuilder.prototype.nestedAltBeforeClause = function (methodOpts, occurrence, methodKeyIdx, altIdx) {
+ var ruleIdx = this.getLastExplicitRuleShortName();
+ var shortName = keys_1.getKeyForAltIndex(ruleIdx, methodKeyIdx, occurrence, altIdx);
+ var nestedName;
+ if (methodOpts.NAME !== undefined) {
+ nestedName = methodOpts.NAME;
+ this.nestedRuleInvocationStateUpdate(nestedName, shortName);
+ return {
+ shortName: shortName,
+ nestedName: nestedName
+ };
+ }
+ else {
+ return undefined;
+ }
+ };
+ TreeBuilder.prototype.nestedRuleFinallyClause = function (laKey, nestedName) {
+ var cstStack = this.CST_STACK;
+ var nestedRuleCst = cstStack[cstStack.length - 1];
+ this.nestedRuleFinallyStateUpdate();
+ // this return a different result than the previous invocation because "nestedRuleFinallyStateUpdate" pops the cst stack
+ var parentCstNode = cstStack[cstStack.length - 1];
+ cst_1.addNoneTerminalToCst(parentCstNode, nestedName, nestedRuleCst);
+ this.setNodeLocationFromNode(parentCstNode.location, nestedRuleCst.location);
+ };
+ TreeBuilder.prototype.getLastExplicitRuleShortName = function () {
+ var lastExplictIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 1];
+ return this.RULE_STACK[lastExplictIndex];
+ };
+ TreeBuilder.prototype.getLastExplicitRuleShortNameNoCst = function () {
+ var ruleStack = this.RULE_STACK;
+ return ruleStack[ruleStack.length - 1];
+ };
+ TreeBuilder.prototype.getPreviousExplicitRuleShortName = function () {
+ var lastExplicitIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 2];
+ return this.RULE_STACK[lastExplicitIndex];
+ };
+ TreeBuilder.prototype.getPreviousExplicitRuleShortNameNoCst = function () {
+ var ruleStack = this.RULE_STACK;
+ return ruleStack[ruleStack.length - 2];
+ };
+ TreeBuilder.prototype.getLastExplicitRuleOccurrenceIndex = function () {
+ var lastExplicitIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 1];
+ return this.RULE_OCCURRENCE_STACK[lastExplicitIndex];
+ };
+ TreeBuilder.prototype.getLastExplicitRuleOccurrenceIndexNoCst = function () {
+ var occurrenceStack = this.RULE_OCCURRENCE_STACK;
+ return occurrenceStack[occurrenceStack.length - 1];
+ };
+ TreeBuilder.prototype.nestedRuleInvocationStateUpdate = function (nestedRuleName, shortNameKey) {
+ this.RULE_OCCURRENCE_STACK.push(1);
+ this.RULE_STACK.push(shortNameKey);
+ this.cstNestedInvocationStateUpdate(nestedRuleName, shortNameKey);
+ };
+ TreeBuilder.prototype.nestedRuleFinallyStateUpdate = function () {
+ this.RULE_STACK.pop();
+ this.RULE_OCCURRENCE_STACK.pop();
+ // NOOP when cst is disabled
+ this.cstNestedFinallyStateUpdate();
+ };
+ return TreeBuilder;
+}());
+exports.TreeBuilder = TreeBuilder;
+//# sourceMappingURL=tree_builder.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/scan/lexer.js b/node_modules/chevrotain/lib/src/scan/lexer.js
new file mode 100644
index 0000000..414d899
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/scan/lexer.js
@@ -0,0 +1,910 @@
+"use strict";
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var regexp_to_ast_1 = require("regexp-to-ast");
+var lexer_public_1 = require("./lexer_public");
+var utils_1 = require("../utils/utils");
+var reg_exp_1 = require("./reg_exp");
+var reg_exp_parser_1 = require("./reg_exp_parser");
+var PATTERN = "PATTERN";
+exports.DEFAULT_MODE = "defaultMode";
+exports.MODES = "modes";
+exports.SUPPORT_STICKY = typeof new RegExp("(?:)").sticky === "boolean";
+function disableSticky() {
+ exports.SUPPORT_STICKY = false;
+}
+exports.disableSticky = disableSticky;
+function enableSticky() {
+ exports.SUPPORT_STICKY = true;
+}
+exports.enableSticky = enableSticky;
+function analyzeTokenTypes(tokenTypes, options) {
+ options = utils_1.defaults(options, {
+ useSticky: exports.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 = utils_1.reject(tokenTypes, function (currType) {
+ return currType[PATTERN] === lexer_public_1.Lexer.NA;
+ });
+ });
+ var hasCustom = false;
+ var allTransformedPatterns;
+ tracer("Transform Patterns", function () {
+ hasCustom = false;
+ allTransformedPatterns = utils_1.map(onlyRelevantTypes, function (currType) {
+ var currPattern = currType[PATTERN];
+ /* istanbul ignore else */
+ if (utils_1.isRegExp(currPattern)) {
+ var regExpSource = currPattern.source;
+ if (regExpSource.length === 1 &&
+ // only these regExp meta characters which can appear in a length one regExp
+ regExpSource !== "^" &&
+ regExpSource !== "$" &&
+ regExpSource !== ".") {
+ return regExpSource;
+ }
+ else if (regExpSource.length === 2 &&
+ regExpSource[0] === "\\" &&
+ // not a meta character
+ !utils_1.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 (utils_1.isFunction(currPattern)) {
+ hasCustom = true;
+ // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object
+ return { exec: currPattern };
+ }
+ else if (utils_1.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 = utils_1.map(onlyRelevantTypes, function (currType) { return currType.tokenTypeIdx; });
+ patternIdxToGroup = utils_1.map(onlyRelevantTypes, function (clazz) {
+ var groupName = clazz.GROUP;
+ /* istanbul ignore next */
+ if (groupName === lexer_public_1.Lexer.SKIPPED) {
+ return undefined;
+ }
+ else if (utils_1.isString(groupName)) {
+ return groupName;
+ }
+ else if (utils_1.isUndefined(groupName)) {
+ return false;
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ });
+ patternIdxToLongerAltIdx = utils_1.map(onlyRelevantTypes, function (clazz) {
+ var longerAltType = clazz.LONGER_ALT;
+ if (longerAltType) {
+ var longerAltIdx = utils_1.indexOf(onlyRelevantTypes, longerAltType);
+ return longerAltIdx;
+ }
+ });
+ patternIdxToPushMode = utils_1.map(onlyRelevantTypes, function (clazz) { return clazz.PUSH_MODE; });
+ patternIdxToPopMode = utils_1.map(onlyRelevantTypes, function (clazz) {
+ return utils_1.has(clazz, "POP_MODE");
+ });
+ });
+ var patternIdxToCanLineTerminator;
+ tracer("Line Terminator Handling", function () {
+ var lineTerminatorCharCodes = getCharCodes(options.lineTerminatorCharacters);
+ patternIdxToCanLineTerminator = utils_1.map(onlyRelevantTypes, function (tokType) { return false; });
+ if (options.positionTracking !== "onlyOffset") {
+ patternIdxToCanLineTerminator = utils_1.map(onlyRelevantTypes, function (tokType) {
+ if (utils_1.has(tokType, "LINE_BREAKS")) {
+ return tokType.LINE_BREAKS;
+ }
+ else {
+ if (checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false) {
+ return reg_exp_1.canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN);
+ }
+ }
+ });
+ }
+ });
+ var patternIdxToIsCustom;
+ var patternIdxToShort;
+ var emptyGroups;
+ var patternIdxToConfig;
+ tracer("Misc Mapping #2", function () {
+ patternIdxToIsCustom = utils_1.map(onlyRelevantTypes, isCustomPattern);
+ patternIdxToShort = utils_1.map(allTransformedPatterns, isShortPattern);
+ emptyGroups = utils_1.reduce(onlyRelevantTypes, function (acc, clazz) {
+ var groupName = clazz.GROUP;
+ if (utils_1.isString(groupName) && !(groupName === lexer_public_1.Lexer.SKIPPED)) {
+ acc[groupName] = [];
+ }
+ return acc;
+ }, {});
+ patternIdxToConfig = utils_1.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 = utils_1.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 (utils_1.isArray(currTokType.START_CHARS_HINT)) {
+ var lastOptimizedIdx_1;
+ utils_1.forEach(currTokType.START_CHARS_HINT, function (charOrInt) {
+ var charCode = typeof charOrInt === "string"
+ ? charOrInt.charCodeAt(0)
+ : charOrInt;
+ var currOptimizedIdx = charCodeToOptimizedIndex(charCode);
+ // Avoid adding the config multiple times
+ if (lastOptimizedIdx_1 !== currOptimizedIdx) {
+ lastOptimizedIdx_1 = currOptimizedIdx;
+ addToMapOfArrays(result, currOptimizedIdx, patternIdxToConfig[idx]);
+ }
+ });
+ }
+ else if (utils_1.isRegExp(currTokType.PATTERN)) {
+ if (currTokType.PATTERN.unicode) {
+ canBeOptimized = false;
+ if (options.ensureOptimizations) {
+ utils_1.PRINT_ERROR("" + reg_exp_1.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 = reg_exp_1.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 (utils_1.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;
+ }
+ utils_1.forEach(optimizedCodes, function (code) {
+ addToMapOfArrays(result, code, patternIdxToConfig[idx]);
+ });
+ }
+ }
+ else {
+ if (options.ensureOptimizations) {
+ utils_1.PRINT_ERROR("" + reg_exp_1.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 = utils_1.packArray(charCodeToPatternIdxToConfig);
+ });
+ return {
+ emptyGroups: emptyGroups,
+ patternIdxToConfig: patternIdxToConfig,
+ charCodeToPatternIdxToConfig: charCodeToPatternIdxToConfig,
+ hasCustom: hasCustom,
+ canBeOptimized: canBeOptimized
+ };
+}
+exports.analyzeTokenTypes = analyzeTokenTypes;
+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;
+}
+exports.validatePatterns = validatePatterns;
+function validateRegExpPattern(tokenTypes) {
+ var errors = [];
+ var withRegExpPatterns = utils_1.filter(tokenTypes, function (currTokType) {
+ return utils_1.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 = utils_1.filter(tokenTypes, function (currType) {
+ return !utils_1.has(currType, PATTERN);
+ });
+ var errors = utils_1.map(tokenTypesWithMissingPattern, function (currType) {
+ return {
+ message: "Token Type: ->" +
+ currType.name +
+ "<- missing static 'PATTERN' property",
+ type: lexer_public_1.LexerDefinitionErrorType.MISSING_PATTERN,
+ tokenTypes: [currType]
+ };
+ });
+ var valid = utils_1.difference(tokenTypes, tokenTypesWithMissingPattern);
+ return { errors: errors, valid: valid };
+}
+exports.findMissingPatterns = findMissingPatterns;
+function findInvalidPatterns(tokenTypes) {
+ var tokenTypesWithInvalidPattern = utils_1.filter(tokenTypes, function (currType) {
+ var pattern = currType[PATTERN];
+ return (!utils_1.isRegExp(pattern) &&
+ !utils_1.isFunction(pattern) &&
+ !utils_1.has(pattern, "exec") &&
+ !utils_1.isString(pattern));
+ });
+ var errors = utils_1.map(tokenTypesWithInvalidPattern, function (currType) {
+ return {
+ message: "Token Type: ->" +
+ currType.name +
+ "<- static 'PATTERN' can only be a RegExp, a" +
+ " Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",
+ type: lexer_public_1.LexerDefinitionErrorType.INVALID_PATTERN,
+ tokenTypes: [currType]
+ };
+ });
+ var valid = utils_1.difference(tokenTypes, tokenTypesWithInvalidPattern);
+ return { errors: errors, valid: valid };
+}
+exports.findInvalidPatterns = findInvalidPatterns;
+var end_of_input = /[^\\][\$]/;
+function findEndOfInputAnchor(tokenTypes) {
+ var EndAnchorFinder = /** @class */ (function (_super) {
+ __extends(EndAnchorFinder, _super);
+ function EndAnchorFinder() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.found = false;
+ return _this;
+ }
+ EndAnchorFinder.prototype.visitEndAnchor = function (node) {
+ this.found = true;
+ };
+ return EndAnchorFinder;
+ }(regexp_to_ast_1.BaseRegExpVisitor));
+ var invalidRegex = utils_1.filter(tokenTypes, function (currType) {
+ var pattern = currType[PATTERN];
+ try {
+ var regexpAst = reg_exp_parser_1.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 = utils_1.map(invalidRegex, function (currType) {
+ return {
+ message: "Unexpected RegExp Anchor Error:\n" +
+ "\tToken Type: ->" +
+ currType.name +
+ "<- static 'PATTERN' cannot contain end of input anchor '$'\n" +
+ "\tSee sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#ANCHORS" +
+ "\tfor details.",
+ type: lexer_public_1.LexerDefinitionErrorType.EOI_ANCHOR_FOUND,
+ tokenTypes: [currType]
+ };
+ });
+ return errors;
+}
+exports.findEndOfInputAnchor = findEndOfInputAnchor;
+function findEmptyMatchRegExps(tokenTypes) {
+ var matchesEmptyString = utils_1.filter(tokenTypes, function (currType) {
+ var pattern = currType[PATTERN];
+ return pattern.test("");
+ });
+ var errors = utils_1.map(matchesEmptyString, function (currType) {
+ return {
+ message: "Token Type: ->" +
+ currType.name +
+ "<- static 'PATTERN' must not match an empty string",
+ type: lexer_public_1.LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,
+ tokenTypes: [currType]
+ };
+ });
+ return errors;
+}
+exports.findEmptyMatchRegExps = findEmptyMatchRegExps;
+var start_of_input = /[^\\[][\^]|^\^/;
+function findStartOfInputAnchor(tokenTypes) {
+ var StartAnchorFinder = /** @class */ (function (_super) {
+ __extends(StartAnchorFinder, _super);
+ function StartAnchorFinder() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.found = false;
+ return _this;
+ }
+ StartAnchorFinder.prototype.visitStartAnchor = function (node) {
+ this.found = true;
+ };
+ return StartAnchorFinder;
+ }(regexp_to_ast_1.BaseRegExpVisitor));
+ var invalidRegex = utils_1.filter(tokenTypes, function (currType) {
+ var pattern = currType[PATTERN];
+ try {
+ var regexpAst = reg_exp_parser_1.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 = utils_1.map(invalidRegex, function (currType) {
+ return {
+ message: "Unexpected RegExp Anchor Error:\n" +
+ "\tToken Type: ->" +
+ currType.name +
+ "<- static 'PATTERN' cannot contain start of input anchor '^'\n" +
+ "\tSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#ANCHORS" +
+ "\tfor details.",
+ type: lexer_public_1.LexerDefinitionErrorType.SOI_ANCHOR_FOUND,
+ tokenTypes: [currType]
+ };
+ });
+ return errors;
+}
+exports.findStartOfInputAnchor = findStartOfInputAnchor;
+function findUnsupportedFlags(tokenTypes) {
+ var invalidFlags = utils_1.filter(tokenTypes, function (currType) {
+ var pattern = currType[PATTERN];
+ return (pattern instanceof RegExp && (pattern.multiline || pattern.global));
+ });
+ var errors = utils_1.map(invalidFlags, function (currType) {
+ return {
+ message: "Token Type: ->" +
+ currType.name +
+ "<- static 'PATTERN' may NOT contain global('g') or multiline('m')",
+ type: lexer_public_1.LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,
+ tokenTypes: [currType]
+ };
+ });
+ return errors;
+}
+exports.findUnsupportedFlags = findUnsupportedFlags;
+// This can only test for identical duplicate RegExps, not semantically equivalent ones.
+function findDuplicatePatterns(tokenTypes) {
+ var found = [];
+ var identicalPatterns = utils_1.map(tokenTypes, function (outerType) {
+ return utils_1.reduce(tokenTypes, function (result, innerType) {
+ if (outerType.PATTERN.source === innerType.PATTERN.source &&
+ !utils_1.contains(found, innerType) &&
+ innerType.PATTERN !== lexer_public_1.Lexer.NA) {
+ // this avoids duplicates in the result, each Token Type may only appear in one "set"
+ // in essence we are creating Equivalence classes on equality relation.
+ found.push(innerType);
+ result.push(innerType);
+ return result;
+ }
+ return result;
+ }, []);
+ });
+ identicalPatterns = utils_1.compact(identicalPatterns);
+ var duplicatePatterns = utils_1.filter(identicalPatterns, function (currIdenticalSet) {
+ return currIdenticalSet.length > 1;
+ });
+ var errors = utils_1.map(duplicatePatterns, function (setOfIdentical) {
+ var tokenTypeNames = utils_1.map(setOfIdentical, function (currType) {
+ return currType.name;
+ });
+ var dupPatternSrc = utils_1.first(setOfIdentical).PATTERN;
+ return {
+ message: "The same RegExp pattern ->" + dupPatternSrc + "<-" +
+ ("has been used in all of the following Token Types: " + tokenTypeNames.join(", ") + " <-"),
+ type: lexer_public_1.LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,
+ tokenTypes: setOfIdentical
+ };
+ });
+ return errors;
+}
+exports.findDuplicatePatterns = findDuplicatePatterns;
+function findInvalidGroupType(tokenTypes) {
+ var invalidTypes = utils_1.filter(tokenTypes, function (clazz) {
+ if (!utils_1.has(clazz, "GROUP")) {
+ return false;
+ }
+ var group = clazz.GROUP;
+ return group !== lexer_public_1.Lexer.SKIPPED && group !== lexer_public_1.Lexer.NA && !utils_1.isString(group);
+ });
+ var errors = utils_1.map(invalidTypes, function (currType) {
+ return {
+ message: "Token Type: ->" +
+ currType.name +
+ "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",
+ type: lexer_public_1.LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,
+ tokenTypes: [currType]
+ };
+ });
+ return errors;
+}
+exports.findInvalidGroupType = findInvalidGroupType;
+function findModesThatDoNotExist(tokenTypes, validModes) {
+ var invalidModes = utils_1.filter(tokenTypes, function (clazz) {
+ return (clazz.PUSH_MODE !== undefined &&
+ !utils_1.contains(validModes, clazz.PUSH_MODE));
+ });
+ var errors = utils_1.map(invalidModes, function (tokType) {
+ var msg = "Token Type: ->" + tokType.name + "<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->" + tokType.PUSH_MODE + "<-" +
+ "which does not exist";
+ return {
+ message: msg,
+ type: lexer_public_1.LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,
+ tokenTypes: [tokType]
+ };
+ });
+ return errors;
+}
+exports.findModesThatDoNotExist = findModesThatDoNotExist;
+function findUnreachablePatterns(tokenTypes) {
+ var errors = [];
+ var canBeTested = utils_1.reduce(tokenTypes, function (result, tokType, idx) {
+ var pattern = tokType.PATTERN;
+ if (pattern === lexer_public_1.Lexer.NA) {
+ return result;
+ }
+ // a more comprehensive validation for all forms of regExps would require
+ // deeper regExp analysis capabilities
+ if (utils_1.isString(pattern)) {
+ result.push({ str: pattern, idx: idx, tokenType: tokType });
+ }
+ else if (utils_1.isRegExp(pattern) && noMetaChar(pattern)) {
+ result.push({ str: pattern.source, idx: idx, tokenType: tokType });
+ }
+ return result;
+ }, []);
+ utils_1.forEach(tokenTypes, function (tokType, testIdx) {
+ utils_1.forEach(canBeTested, function (_a) {
+ var str = _a.str, idx = _a.idx, tokenType = _a.tokenType;
+ if (testIdx < idx && testTokenType(str, tokType.PATTERN)) {
+ var msg = "Token: ->" + tokenType.name + "<- can never be matched.\n" +
+ ("Because it appears AFTER the Token Type ->" + tokType.name + "<-") +
+ "in the lexer's definition.\n" +
+ "See https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#UNREACHABLE";
+ errors.push({
+ message: msg,
+ type: lexer_public_1.LexerDefinitionErrorType.UNREACHABLE_PATTERN,
+ tokenTypes: [tokType, tokenType]
+ });
+ }
+ });
+ });
+ return errors;
+}
+exports.findUnreachablePatterns = findUnreachablePatterns;
+function testTokenType(str, pattern) {
+ /* istanbul ignore else */
+ if (utils_1.isRegExp(pattern)) {
+ var regExpArray = pattern.exec(str);
+ return regExpArray !== null && regExpArray.index === 0;
+ }
+ else if (utils_1.isFunction(pattern)) {
+ // maintain the API of custom patterns
+ return pattern(str, 0, [], {});
+ }
+ else if (utils_1.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 (utils_1.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);
+}
+exports.addStartOfInput = addStartOfInput;
+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);
+}
+exports.addStickyFlag = addStickyFlag;
+function performRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) {
+ var errors = [];
+ // some run time checks to help the end users.
+ if (!utils_1.has(lexerDefinition, exports.DEFAULT_MODE)) {
+ errors.push({
+ message: "A MultiMode Lexer cannot be initialized without a <" +
+ exports.DEFAULT_MODE +
+ "> property in its definition\n",
+ type: lexer_public_1.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE
+ });
+ }
+ if (!utils_1.has(lexerDefinition, exports.MODES)) {
+ errors.push({
+ message: "A MultiMode Lexer cannot be initialized without a <" +
+ exports.MODES +
+ "> property in its definition\n",
+ type: lexer_public_1.LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY
+ });
+ }
+ if (utils_1.has(lexerDefinition, exports.MODES) &&
+ utils_1.has(lexerDefinition, exports.DEFAULT_MODE) &&
+ !utils_1.has(lexerDefinition.modes, lexerDefinition.defaultMode)) {
+ errors.push({
+ message: "A MultiMode Lexer cannot be initialized with a " + exports.DEFAULT_MODE + ": <" + lexerDefinition.defaultMode + ">" +
+ "which does not exist\n",
+ type: lexer_public_1.LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST
+ });
+ }
+ if (utils_1.has(lexerDefinition, exports.MODES)) {
+ utils_1.forEach(lexerDefinition.modes, function (currModeValue, currModeName) {
+ utils_1.forEach(currModeValue, function (currTokType, currIdx) {
+ if (utils_1.isUndefined(currTokType)) {
+ errors.push({
+ message: "A Lexer cannot be initialized using an undefined Token Type. Mode:" +
+ ("<" + currModeName + "> at index: <" + currIdx + ">\n"),
+ type: lexer_public_1.LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED
+ });
+ }
+ });
+ });
+ }
+ return errors;
+}
+exports.performRuntimeChecks = performRuntimeChecks;
+function performWarningRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) {
+ var warnings = [];
+ var hasAnyLineBreak = false;
+ var allTokenTypes = utils_1.compact(utils_1.flatten(utils_1.mapValues(lexerDefinition.modes, function (tokTypes) { return tokTypes; })));
+ var concreteTokenTypes = utils_1.reject(allTokenTypes, function (currType) { return currType[PATTERN] === lexer_public_1.Lexer.NA; });
+ var terminatorCharCodes = getCharCodes(lineTerminatorCharacters);
+ if (trackLines) {
+ utils_1.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 (utils_1.has(tokType, "LINE_BREAKS")) {
+ if (tokType.LINE_BREAKS === true) {
+ hasAnyLineBreak = true;
+ }
+ }
+ else {
+ if (reg_exp_1.canMatchCharCode(terminatorCharCodes, tokType.PATTERN)) {
+ hasAnyLineBreak = true;
+ }
+ }
+ }
+ });
+ }
+ if (trackLines && !hasAnyLineBreak) {
+ warnings.push({
+ message: "Warning: No LINE_BREAKS Found.\n" +
+ "\tThis Lexer has been defined to track line and column information,\n" +
+ "\tBut none of the Token Types can be identified as matching a line terminator.\n" +
+ "\tSee https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n" +
+ "\tfor details.",
+ type: lexer_public_1.LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS
+ });
+ }
+ return warnings;
+}
+exports.performWarningRuntimeChecks = performWarningRuntimeChecks;
+function cloneEmptyGroups(emptyGroups) {
+ var clonedResult = {};
+ var groupKeys = utils_1.keys(emptyGroups);
+ utils_1.forEach(groupKeys, function (currKey) {
+ var currGroupValue = emptyGroups[currKey];
+ /* istanbul ignore else */
+ if (utils_1.isArray(currGroupValue)) {
+ clonedResult[currKey] = [];
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ });
+ return clonedResult;
+}
+exports.cloneEmptyGroups = cloneEmptyGroups;
+// TODO: refactor to avoid duplication
+function isCustomPattern(tokenType) {
+ var pattern = tokenType.PATTERN;
+ /* istanbul ignore else */
+ if (utils_1.isRegExp(pattern)) {
+ return false;
+ }
+ else if (utils_1.isFunction(pattern)) {
+ // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object
+ return true;
+ }
+ else if (utils_1.has(pattern, "exec")) {
+ // ICustomPattern
+ return true;
+ }
+ else if (utils_1.isString(pattern)) {
+ return false;
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+exports.isCustomPattern = isCustomPattern;
+function isShortPattern(pattern) {
+ if (utils_1.isString(pattern) && pattern.length === 1) {
+ return pattern.charCodeAt(0);
+ }
+ else {
+ return false;
+ }
+}
+exports.isShortPattern = isShortPattern;
+/**
+ * Faster than using a RegExp for default newline detection during lexing.
+ */
+exports.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 (utils_1.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 (utils_1.isRegExp(tokType.PATTERN)) {
+ try {
+ reg_exp_1.canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN);
+ }
+ catch (e) {
+ /* istanbul ignore next - to test this we would have to mock to throw an error */
+ return {
+ issue: lexer_public_1.LexerDefinitionErrorType.IDENTIFY_TERMINATOR,
+ errMsg: e.message
+ };
+ }
+ return false;
+ }
+ else if (utils_1.isString(tokType.PATTERN)) {
+ // string literal patterns can always be analyzed to detect line terminator usage
+ return false;
+ }
+ else if (isCustomPattern(tokType)) {
+ // custom token types
+ return { issue: lexer_public_1.LexerDefinitionErrorType.CUSTOM_LINE_BREAK };
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ }
+}
+function buildLineBreakIssueMessage(tokType, details) {
+ /* istanbul ignore else */
+ if (details.issue === lexer_public_1.LexerDefinitionErrorType.IDENTIFY_TERMINATOR) {
+ return ("Warning: unable to identify line terminator usage in pattern.\n" +
+ ("\tThe problem is in the <" + tokType.name + "> Token Type\n") +
+ ("\t Root cause: " + details.errMsg + ".\n") +
+ "\tFor details See: https://sap.github.io/chevrotain/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR");
+ }
+ else if (details.issue === lexer_public_1.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");
+ }
+}
+exports.buildLineBreakIssueMessage = buildLineBreakIssueMessage;
+function getCharCodes(charsOrCodes) {
+ var charCodes = utils_1.map(charsOrCodes, function (numOrString) {
+ if (utils_1.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);
+ }
+}
+exports.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 < exports.minOptimizationVal
+ ? charCode
+ : charCodeToOptimizedIdxMap[charCode];
+}
+exports.charCodeToOptimizedIndex = charCodeToOptimizedIndex;
+/**
+ * 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 (utils_1.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
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/scan/lexer_errors_public.js b/node_modules/chevrotain/lib/src/scan/lexer_errors_public.js
new file mode 100644
index 0000000..f3d4e16
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/scan/lexer_errors_public.js
@@ -0,0 +1,11 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.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
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/scan/lexer_public.js b/node_modules/chevrotain/lib/src/scan/lexer_public.js
new file mode 100644
index 0000000..c208566
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/scan/lexer_public.js
@@ -0,0 +1,674 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var lexer_1 = require("./lexer");
+var utils_1 = require("../utils/utils");
+var tokens_1 = require("./tokens");
+var lexer_errors_public_1 = require("../scan/lexer_errors_public");
+var reg_exp_parser_1 = require("./reg_exp_parser");
+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 = exports.LexerDefinitionErrorType || (exports.LexerDefinitionErrorType = {}));
+var DEFAULT_LEXER_CONFIG = {
+ deferDefinitionErrorsHandling: false,
+ positionTracking: "full",
+ lineTerminatorsPattern: /\n|\r\n?/g,
+ lineTerminatorCharacters: ["\n", "\r"],
+ ensureOptimizations: false,
+ safeMode: false,
+ errorMessageProvider: lexer_errors_public_1.defaultLexerErrorProvider,
+ traceInitPerf: false,
+ skipValidations: false
+};
+Object.freeze(DEFAULT_LEXER_CONFIG);
+var Lexer = /** @class */ (function () {
+ function Lexer(lexerDefinition, config) {
+ var _this = this;
+ if (config === void 0) { config = DEFAULT_LEXER_CONFIG; }
+ this.lexerDefinition = lexerDefinition;
+ this.lexerDefinitionErrors = [];
+ this.lexerDefinitionWarning = [];
+ this.patternIdxToConfig = {};
+ this.charCodeToPatternIdxToConfig = {};
+ this.modes = [];
+ this.emptyGroups = {};
+ this.config = undefined;
+ this.trackStartLines = true;
+ this.trackEndLines = true;
+ this.hasCustom = false;
+ this.canModeBeOptimized = {};
+ if (typeof config === "boolean") {
+ throw Error("The second argument to the Lexer constructor is now an ILexerConfig Object.\n" +
+ "a boolean 2nd argument is no longer supported");
+ }
+ // todo: defaults func?
+ this.config = utils_1.merge(DEFAULT_LEXER_CONFIG, config);
+ var traceInitVal = this.config.traceInitPerf;
+ if (traceInitVal === true) {
+ this.traceInitMaxIdent = Infinity;
+ this.traceInitPerf = true;
+ }
+ else if (typeof traceInitVal === "number") {
+ this.traceInitMaxIdent = traceInitVal;
+ this.traceInitPerf = true;
+ }
+ this.traceInitIndent = -1;
+ this.TRACE_INIT("Lexer Constructor", function () {
+ var actualDefinition;
+ var hasOnlySingleMode = true;
+ _this.TRACE_INIT("Lexer Config handling", function () {
+ if (_this.config.lineTerminatorsPattern ===
+ DEFAULT_LEXER_CONFIG.lineTerminatorsPattern) {
+ // optimized built-in implementation for the defaults definition of lineTerminators
+ _this.config.lineTerminatorsPattern = lexer_1.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 (utils_1.isArray(lexerDefinition)) {
+ actualDefinition = { modes: {} };
+ actualDefinition.modes[lexer_1.DEFAULT_MODE] = utils_1.cloneArr(lexerDefinition);
+ actualDefinition[lexer_1.DEFAULT_MODE] = lexer_1.DEFAULT_MODE;
+ }
+ else {
+ // no conversion needed, input should already be a IMultiModeLexerDefinition
+ hasOnlySingleMode = false;
+ actualDefinition = utils_1.cloneObj((lexerDefinition));
+ }
+ });
+ if (_this.config.skipValidations === false) {
+ _this.TRACE_INIT("performRuntimeChecks", function () {
+ _this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat(lexer_1.performRuntimeChecks(actualDefinition, _this.trackStartLines, _this.config.lineTerminatorCharacters));
+ });
+ _this.TRACE_INIT("performWarningRuntimeChecks", function () {
+ _this.lexerDefinitionWarning = _this.lexerDefinitionWarning.concat(lexer_1.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.
+ utils_1.forEach(actualDefinition.modes, function (currModeValue, currModeName) {
+ actualDefinition.modes[currModeName] = utils_1.reject(currModeValue, function (currTokType) { return utils_1.isUndefined(currTokType); });
+ });
+ var allModeNames = utils_1.keys(actualDefinition.modes);
+ utils_1.forEach(actualDefinition.modes, function (currModDef, currModName) {
+ _this.TRACE_INIT("Mode: <" + currModName + "> processing", function () {
+ _this.modes.push(currModName);
+ if (_this.config.skipValidations === false) {
+ _this.TRACE_INIT("validatePatterns", function () {
+ _this.lexerDefinitionErrors = _this.lexerDefinitionErrors.concat(lexer_1.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 (utils_1.isEmpty(_this.lexerDefinitionErrors)) {
+ tokens_1.augmentTokenTypes(currModDef);
+ var currAnalyzeResult_1;
+ _this.TRACE_INIT("analyzeTokenTypes", function () {
+ currAnalyzeResult_1 = lexer_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 = utils_1.merge(_this.emptyGroups, currAnalyzeResult_1.emptyGroups);
+ _this.hasCustom =
+ currAnalyzeResult_1.hasCustom || _this.hasCustom;
+ _this.canModeBeOptimized[currModName] =
+ currAnalyzeResult_1.canBeOptimized;
+ }
+ });
+ });
+ _this.defaultMode = actualDefinition.defaultMode;
+ if (!utils_1.isEmpty(_this.lexerDefinitionErrors) &&
+ !_this.config.deferDefinitionErrorsHandling) {
+ var allErrMessages = utils_1.map(_this.lexerDefinitionErrors, function (error) {
+ return error.message;
+ });
+ var allErrMessagesString = allErrMessages.join("-----------------------\n");
+ throw new Error("Errors detected in definition of Lexer:\n" +
+ allErrMessagesString);
+ }
+ // Only print warning if there are no errors, This will avoid pl
+ utils_1.forEach(_this.lexerDefinitionWarning, function (warningDescriptor) {
+ utils_1.PRINT_WARNING(warningDescriptor.message);
+ });
+ _this.TRACE_INIT("Choosing sub-methods implementations", function () {
+ // Choose the relevant internal implementations for this specific parser.
+ // These implementations should be in-lined by the JavaScript engine
+ // to provide optimal performance in each scenario.
+ if (lexer_1.SUPPORT_STICKY) {
+ _this.chopInput = utils_1.IDENTITY;
+ _this.match = _this.matchWithTest;
+ }
+ else {
+ _this.updateLastIndex = utils_1.NOOP;
+ _this.match = _this.matchWithExec;
+ }
+ if (hasOnlySingleMode) {
+ _this.handleModes = utils_1.NOOP;
+ }
+ if (_this.trackStartLines === false) {
+ _this.computeNewColumn = utils_1.IDENTITY;
+ }
+ if (_this.trackEndLines === false) {
+ _this.updateTokenEndLineColumnLocation = utils_1.NOOP;
+ }
+ if (/full/i.test(_this.config.positionTracking)) {
+ _this.createTokenInstance = _this.createFullToken;
+ }
+ else if (/onlyStart/i.test(_this.config.positionTracking)) {
+ _this.createTokenInstance = _this.createStartOnlyToken;
+ }
+ else if (/onlyOffset/i.test(_this.config.positionTracking)) {
+ _this.createTokenInstance = _this.createOffsetOnlyToken;
+ }
+ else {
+ throw Error("Invalid 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 = utils_1.reduce(_this.canModeBeOptimized, function (cannotBeOptimized, canBeOptimized, modeName) {
+ if (canBeOptimized === false) {
+ cannotBeOptimized.push(modeName);
+ }
+ return cannotBeOptimized;
+ }, []);
+ if (config.ensureOptimizations && !utils_1.isEmpty(unOptimizedModes)) {
+ throw Error("Lexer Modes: < " + unOptimizedModes.join(", ") + " > cannot be optimized.\n" +
+ '\t Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.\n' +
+ "\t Or inspect the console log for details on how to resolve these issues.");
+ }
+ });
+ _this.TRACE_INIT("clearRegExpParserCache", function () {
+ reg_exp_parser_1.clearRegExpParserCache();
+ });
+ _this.TRACE_INIT("toFastProperties", function () {
+ utils_1.toFastProperties(_this);
+ });
+ });
+ }
+ Lexer.prototype.tokenize = function (text, initialMode) {
+ if (initialMode === void 0) { initialMode = this.defaultMode; }
+ if (!utils_1.isEmpty(this.lexerDefinitionErrors)) {
+ var allErrMessages = utils_1.map(this.lexerDefinitionErrors, function (error) {
+ return error.message;
+ });
+ var allErrMessagesString = allErrMessages.join("-----------------------\n");
+ throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n" +
+ allErrMessagesString);
+ }
+ var lexResult = this.tokenizeInternal(text, initialMode);
+ return lexResult;
+ };
+ // There is quite a bit of duplication between this and "tokenizeInternalLazy"
+ // This is intentional due to performance considerations.
+ Lexer.prototype.tokenizeInternal = function (text, initialMode) {
+ var _this = this;
+ var i, j, matchAltImage, longerAltIdx, matchedImage, payload, altPayload, imageLength, group, tokType, newToken, errLength, droppedChar, msg, match;
+ var orgText = text;
+ var orgLength = orgText.length;
+ var offset = 0;
+ var matchedTokensIndex = 0;
+ // initializing the tokensArray to the "guessed" size.
+ // guessing too little will still reduce the number of array re-sizes on pushes.
+ // guessing too large (Tested by guessing x4 too large) may cost a bit more of memory
+ // but would still have a faster runtime by avoiding (All but one) array resizing.
+ var guessedNumberOfTokens = this.hasCustom
+ ? 0 // will break custom token pattern APIs the matchedTokens array will contain undefined elements.
+ : Math.floor(text.length / 10);
+ var matchedTokens = new Array(guessedNumberOfTokens);
+ var errors = [];
+ var line = this.trackStartLines ? 1 : undefined;
+ var column = this.trackStartLines ? 1 : undefined;
+ var groups = lexer_1.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 = lexer_1.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 = utils_1.last(modeStack);
+ patternIdxToConfig = _this.patternIdxToConfig[newMode];
+ currCharCodeToPatternIdxToConfig = _this
+ .charCodeToPatternIdxToConfig[newMode];
+ currModePatternsLength = patternIdxToConfig.length;
+ var modeCanBeOptimized = _this.canModeBeOptimized[newMode] &&
+ _this.config.safeMode === false;
+ if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {
+ getPossiblePatterns = getPossiblePatternsOptimized;
+ }
+ else {
+ getPossiblePatterns = getPossiblePatternsSlow;
+ }
+ }
+ };
+ function push_mode(newMode) {
+ modeStack.push(newMode);
+ currCharCodeToPatternIdxToConfig = this
+ .charCodeToPatternIdxToConfig[newMode];
+ patternIdxToConfig = this.patternIdxToConfig[newMode];
+ currModePatternsLength = patternIdxToConfig.length;
+ currModePatternsLength = patternIdxToConfig.length;
+ var modeCanBeOptimized = this.canModeBeOptimized[newMode] &&
+ this.config.safeMode === false;
+ if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {
+ getPossiblePatterns = getPossiblePatternsOptimized;
+ }
+ else {
+ getPossiblePatterns = getPossiblePatternsSlow;
+ }
+ }
+ // this pattern seems to avoid a V8 de-optimization, although that de-optimization does not
+ // seem to matter performance wise.
+ push_mode.call(this, initialMode);
+ var currConfig;
+ while (offset < orgLength) {
+ matchedImage = null;
+ var nextCharCode = orgText.charCodeAt(offset);
+ var chosenPatternIdxToConfig = getPossiblePatterns(nextCharCode);
+ var chosenPatternsLength = chosenPatternIdxToConfig.length;
+ for (i = 0; i < chosenPatternsLength; i++) {
+ currConfig = chosenPatternIdxToConfig[i];
+ var currPattern = currConfig.pattern;
+ payload = null;
+ // manually in-lined because > 600 chars won't be in-lined in V8
+ var singleCharCode = currConfig.short;
+ if (singleCharCode !== false) {
+ if (nextCharCode === singleCharCode) {
+ // single character string
+ matchedImage = currPattern;
+ }
+ }
+ else if (currConfig.isCustom === true) {
+ match = currPattern.exec(orgText, offset, matchedTokens, groups);
+ if (match !== null) {
+ matchedImage = match[0];
+ if (match.payload !== undefined) {
+ payload = match.payload;
+ }
+ }
+ else {
+ matchedImage = null;
+ }
+ }
+ else {
+ this.updateLastIndex(currPattern, offset);
+ matchedImage = this.match(currPattern, text, offset);
+ }
+ if (matchedImage !== null) {
+ // even though this pattern matched we must try a another longer alternative.
+ // this can be used to prioritize keywords over identifiers
+ longerAltIdx = currConfig.longerAlt;
+ if (longerAltIdx !== undefined) {
+ // TODO: micro optimize, avoid extra prop access
+ // by saving/linking longerAlt on the original config?
+ var longerAltConfig = patternIdxToConfig[longerAltIdx];
+ var longerAltPattern = longerAltConfig.pattern;
+ altPayload = null;
+ // single Char can never be a longer alt so no need to test it.
+ // manually in-lined because > 600 chars won't be in-lined in V8
+ if (longerAltConfig.isCustom === true) {
+ match = longerAltPattern.exec(orgText, offset, matchedTokens, groups);
+ if (match !== null) {
+ matchAltImage = match[0];
+ if (match.payload !== undefined) {
+ altPayload = match.payload;
+ }
+ }
+ else {
+ matchAltImage = null;
+ }
+ }
+ else {
+ this.updateLastIndex(longerAltPattern, offset);
+ matchAltImage = this.match(longerAltPattern, text, offset);
+ }
+ if (matchAltImage &&
+ matchAltImage.length > matchedImage.length) {
+ matchedImage = matchAltImage;
+ payload = altPayload;
+ currConfig = longerAltConfig;
+ }
+ }
+ break;
+ }
+ }
+ // successful match
+ if (matchedImage !== null) {
+ imageLength = matchedImage.length;
+ group = currConfig.group;
+ if (group !== undefined) {
+ tokType = currConfig.tokenTypeIdx;
+ // TODO: "offset + imageLength" and the new column may be computed twice in case of "full" location information inside
+ // createFullToken method
+ newToken = this.createTokenInstance(matchedImage, offset, tokType, currConfig.tokenType, line, column, imageLength);
+ this.handlePayload(newToken, payload);
+ // TODO: optimize NOOP in case there are no special groups?
+ if (group === false) {
+ matchedTokensIndex = this.addToken(matchedTokens, matchedTokensIndex, newToken);
+ }
+ else {
+ groups[group].push(newToken);
+ }
+ }
+ text = this.chopInput(text, imageLength);
+ offset = offset + imageLength;
+ // TODO: with newlines the column may be assigned twice
+ column = this.computeNewColumn(column, imageLength);
+ if (trackLines === true &&
+ currConfig.canLineTerminator === true) {
+ var numOfLTsInMatch = 0;
+ var foundTerminator = void 0;
+ var lastLTEndOffset = void 0;
+ lineTerminatorPattern.lastIndex = 0;
+ do {
+ foundTerminator = lineTerminatorPattern.test(matchedImage);
+ if (foundTerminator === true) {
+ lastLTEndOffset =
+ lineTerminatorPattern.lastIndex - 1;
+ numOfLTsInMatch++;
+ }
+ } while (foundTerminator === true);
+ if (numOfLTsInMatch !== 0) {
+ line = line + numOfLTsInMatch;
+ column = imageLength - lastLTEndOffset;
+ this.updateTokenEndLineColumnLocation(newToken, group, lastLTEndOffset, numOfLTsInMatch, line, column, imageLength);
+ }
+ }
+ // will be NOOP if no modes present
+ this.handleModes(currConfig, pop_mode, push_mode, newToken);
+ }
+ else {
+ // error recovery, drop characters until we identify a valid token's start point
+ var errorStartOffset = offset;
+ var errorLine = line;
+ var errorColumn = column;
+ var foundResyncPoint = false;
+ while (!foundResyncPoint && offset < orgLength) {
+ // drop chars until we succeed in matching something
+ droppedChar = orgText.charCodeAt(offset);
+ // Identity Func (when sticky flag is enabled)
+ text = this.chopInput(text, 1);
+ offset++;
+ for (j = 0; j < currModePatternsLength; j++) {
+ var currConfig_1 = patternIdxToConfig[j];
+ var currPattern = currConfig_1.pattern;
+ // manually in-lined because > 600 chars won't be in-lined in V8
+ var singleCharCode = currConfig_1.short;
+ if (singleCharCode !== false) {
+ if (orgText.charCodeAt(offset) === singleCharCode) {
+ // single character string
+ foundResyncPoint = true;
+ }
+ }
+ else if (currConfig_1.isCustom === true) {
+ foundResyncPoint =
+ currPattern.exec(orgText, offset, matchedTokens, groups) !== null;
+ }
+ else {
+ this.updateLastIndex(currPattern, offset);
+ foundResyncPoint = currPattern.exec(text) !== null;
+ }
+ if (foundResyncPoint === true) {
+ break;
+ }
+ }
+ }
+ errLength = offset - errorStartOffset;
+ // at this point we either re-synced or reached the end of the input text
+ msg = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(orgText, errorStartOffset, errLength, errorLine, errorColumn);
+ errors.push({
+ offset: errorStartOffset,
+ line: errorLine,
+ column: errorColumn,
+ length: errLength,
+ message: msg
+ });
+ }
+ }
+ // if we do have custom patterns which push directly into the
+ // TODO: custom tokens should not push directly??
+ if (!this.hasCustom) {
+ // if we guessed a too large size for the tokens array this will shrink it to the right size.
+ matchedTokens.length = matchedTokensIndex;
+ }
+ return {
+ tokens: matchedTokens,
+ groups: groups,
+ errors: errors
+ };
+ };
+ Lexer.prototype.handleModes = function (config, pop_mode, push_mode, newToken) {
+ if (config.pop === true) {
+ // need to save the PUSH_MODE property as if the mode is popped
+ // patternIdxToPopMode is updated to reflect the new mode after popping the stack
+ var pushMode = config.push;
+ pop_mode(newToken);
+ if (pushMode !== undefined) {
+ push_mode.call(this, pushMode);
+ }
+ }
+ else if (config.push !== undefined) {
+ push_mode.call(this, config.push);
+ }
+ };
+ Lexer.prototype.chopInput = function (text, length) {
+ return text.substring(length);
+ };
+ Lexer.prototype.updateLastIndex = function (regExp, newLastIndex) {
+ regExp.lastIndex = newLastIndex;
+ };
+ // TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler
+ Lexer.prototype.updateTokenEndLineColumnLocation = function (newToken, group, lastLTIdx, numOfLTsInMatch, line, column, imageLength) {
+ var lastCharIsLT, fixForEndingInLT;
+ if (group !== undefined) {
+ // a none skipped multi line Token, need to update endLine/endColumn
+ lastCharIsLT = lastLTIdx === imageLength - 1;
+ fixForEndingInLT = lastCharIsLT ? -1 : 0;
+ if (!(numOfLTsInMatch === 1 && lastCharIsLT === true)) {
+ // if a token ends in a LT that last LT only affects the line numbering of following Tokens
+ newToken.endLine = line + fixForEndingInLT;
+ // the last LT in a token does not affect the endColumn either as the [columnStart ... columnEnd)
+ // inclusive to exclusive range.
+ newToken.endColumn = column - 1 + -fixForEndingInLT;
+ }
+ // else single LT in the last character of a token, no need to modify the endLine/EndColumn
+ }
+ };
+ Lexer.prototype.computeNewColumn = function (oldColumn, imageLength) {
+ return oldColumn + imageLength;
+ };
+ // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime.
+ /* istanbul ignore next - place holder */
+ Lexer.prototype.createTokenInstance = function () {
+ var args = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ args[_i] = arguments[_i];
+ }
+ return null;
+ };
+ Lexer.prototype.createOffsetOnlyToken = function (image, startOffset, tokenTypeIdx, tokenType) {
+ return {
+ image: image,
+ startOffset: startOffset,
+ tokenTypeIdx: tokenTypeIdx,
+ tokenType: tokenType
+ };
+ };
+ Lexer.prototype.createStartOnlyToken = function (image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn) {
+ return {
+ image: image,
+ startOffset: startOffset,
+ startLine: startLine,
+ startColumn: startColumn,
+ tokenTypeIdx: tokenTypeIdx,
+ tokenType: tokenType
+ };
+ };
+ Lexer.prototype.createFullToken = function (image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn, imageLength) {
+ return {
+ image: image,
+ startOffset: startOffset,
+ endOffset: startOffset + imageLength - 1,
+ startLine: startLine,
+ endLine: startLine,
+ startColumn: startColumn,
+ endColumn: startColumn + imageLength - 1,
+ tokenTypeIdx: tokenTypeIdx,
+ tokenType: tokenType
+ };
+ };
+ // Place holder, will be replaced by the correct variant according to the locationTracking option at runtime.
+ /* istanbul ignore next - place holder */
+ Lexer.prototype.addToken = function (tokenVector, index, tokenToAdd) {
+ return 666;
+ };
+ Lexer.prototype.addTokenUsingPush = function (tokenVector, index, tokenToAdd) {
+ tokenVector.push(tokenToAdd);
+ return index;
+ };
+ Lexer.prototype.addTokenUsingMemberAccess = function (tokenVector, index, tokenToAdd) {
+ tokenVector[index] = tokenToAdd;
+ index++;
+ return index;
+ };
+ // Place holder, will be replaced by the correct variant according to the hasCustom flag option at runtime.
+ /* istanbul ignore next - place holder */
+ Lexer.prototype.handlePayload = function (token, payload) { };
+ Lexer.prototype.handlePayloadNoCustom = function (token, payload) { };
+ Lexer.prototype.handlePayloadWithCustom = function (token, payload) {
+ if (payload !== null) {
+ token.payload = payload;
+ }
+ };
+ /* istanbul ignore next - place holder to be replaced with chosen alternative at runtime */
+ Lexer.prototype.match = function (pattern, text, offset) {
+ return null;
+ };
+ Lexer.prototype.matchWithTest = function (pattern, text, offset) {
+ var found = pattern.test(text);
+ if (found === true) {
+ return text.substring(offset, pattern.lastIndex);
+ }
+ return null;
+ };
+ Lexer.prototype.matchWithExec = function (pattern, text) {
+ var regExpArray = pattern.exec(text);
+ return regExpArray !== null ? regExpArray[0] : regExpArray;
+ };
+ // Duplicated from the parser's perf trace trait to allow future extraction
+ // of the lexer to a separate package.
+ Lexer.prototype.TRACE_INIT = function (phaseDesc, phaseImpl) {
+ // No need to optimize this using NOOP pattern because
+ // It is not called in a hot spot...
+ if (this.traceInitPerf === true) {
+ this.traceInitIndent++;
+ var indent = new Array(this.traceInitIndent + 1).join("\t");
+ if (this.traceInitIndent < this.traceInitMaxIdent) {
+ console.log(indent + "--> <" + phaseDesc + ">");
+ }
+ var _a = utils_1.timer(phaseImpl), time = _a.time, value = _a.value;
+ /* istanbul ignore next - Difficult to reproduce specific performance behavior (>10ms) in tests */
+ var traceMethod = time > 10 ? console.warn : console.log;
+ if (this.traceInitIndent < this.traceInitMaxIdent) {
+ traceMethod(indent + "<-- <" + phaseDesc + "> time: " + time + "ms");
+ }
+ this.traceInitIndent--;
+ return value;
+ }
+ else {
+ return phaseImpl();
+ }
+ };
+ Lexer.SKIPPED = "This marks a skipped Token pattern, this means each token identified by it will" +
+ "be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.";
+ Lexer.NA = /NOT_APPLICABLE/;
+ return Lexer;
+}());
+exports.Lexer = Lexer;
+//# sourceMappingURL=lexer_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/scan/reg_exp.js b/node_modules/chevrotain/lib/src/scan/reg_exp.js
new file mode 100644
index 0000000..f50c0ed
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/scan/reg_exp.js
@@ -0,0 +1,265 @@
+"use strict";
+var __extends = (this && this.__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 __());
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+var regexp_to_ast_1 = require("regexp-to-ast");
+var utils_1 = require("../utils/utils");
+var reg_exp_parser_1 = require("./reg_exp_parser");
+var lexer_1 = require("./lexer");
+var complementErrorMessage = "Complement Sets are not supported for first char optimization";
+exports.failedOptimizationPrefixMsg = 'Unable to use "first char" lexer optimizations:\n';
+function getOptimizedStartCodesIndices(regExp, ensureOptimizations) {
+ if (ensureOptimizations === void 0) { ensureOptimizations = false; }
+ try {
+ var ast = reg_exp_parser_1.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) {
+ utils_1.PRINT_WARNING("" + exports.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.";
+ }
+ utils_1.PRINT_ERROR(exports.failedOptimizationPrefixMsg + "\n" +
+ ("\tFailed parsing: < " + regExp.toString() + " >\n") +
+ ("\tUsing the regexp-to-ast library version: " + regexp_to_ast_1.VERSION + "\n") +
+ "\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues" +
+ msgSuffix);
+ }
+ }
+ return [];
+}
+exports.getOptimizedStartCodesIndices = getOptimizedStartCodesIndices;
+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);
+ }
+ utils_1.forEach(atom.value, function (code) {
+ if (typeof code === "number") {
+ addOptimizedIdxToResult(code, result, ignoreCase);
+ }
+ else {
+ // range
+ var range = code;
+ // cannot optimize when ignoreCase is
+ if (ignoreCase === true) {
+ for (var rangeCode = range.from; rangeCode <= range.to; rangeCode++) {
+ addOptimizedIdxToResult(rangeCode, result, ignoreCase);
+ }
+ }
+ // Optimization (2 orders of magnitude less work for very large ranges)
+ else {
+ // handle unoptimized values
+ for (var rangeCode = range.from; rangeCode <= range.to &&
+ rangeCode < lexer_1.minOptimizationVal; rangeCode++) {
+ addOptimizedIdxToResult(rangeCode, result, ignoreCase);
+ }
+ // Less common charCode where we optimize for faster init time, by using larger "buckets"
+ if (range.to >= lexer_1.minOptimizationVal) {
+ var minUnOptVal = range.from >= lexer_1.minOptimizationVal
+ ? range.from
+ : lexer_1.minOptimizationVal;
+ var maxUnOptVal = range.to;
+ var minOptIdx = lexer_1.charCodeToOptimizedIndex(minUnOptVal);
+ var maxOptIdx = lexer_1.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 utils_1.values(result);
+}
+exports.firstCharOptimizedIndices = firstCharOptimizedIndices;
+function addOptimizedIdxToResult(code, result, ignoreCase) {
+ var optimizedCharIdx = lexer_1.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 = lexer_1.charCodeToOptimizedIndex(upperChar.charCodeAt(0));
+ result[optimizedCharIdx] = optimizedCharIdx;
+ }
+ else {
+ var lowerChar = char.toLowerCase();
+ if (lowerChar !== char) {
+ var optimizedCharIdx = lexer_1.charCodeToOptimizedIndex(lowerChar.charCodeAt(0));
+ result[optimizedCharIdx] = optimizedCharIdx;
+ }
+ }
+}
+function findCode(setNode, targetCharCodes) {
+ return utils_1.find(setNode.value, function (codeOrRange) {
+ if (typeof codeOrRange === "number") {
+ return utils_1.contains(targetCharCodes, codeOrRange);
+ }
+ else {
+ // range
+ var range_1 = codeOrRange;
+ return (utils_1.find(targetCharCodes, function (targetCode) {
+ return range_1.from <= targetCode && targetCode <= range_1.to;
+ }) !== undefined);
+ }
+ });
+}
+function isWholeOptional(ast) {
+ if (ast.quantifier && ast.quantifier.atLeast === 0) {
+ return true;
+ }
+ if (!ast.value) {
+ return false;
+ }
+ return utils_1.isArray(ast.value)
+ ? utils_1.every(ast.value, isWholeOptional)
+ : isWholeOptional(ast.value);
+}
+var CharCodeFinder = /** @class */ (function (_super) {
+ __extends(CharCodeFinder, _super);
+ function CharCodeFinder(targetCharCodes) {
+ var _this = _super.call(this) || this;
+ _this.targetCharCodes = targetCharCodes;
+ _this.found = false;
+ return _this;
+ }
+ CharCodeFinder.prototype.visitChildren = function (node) {
+ // No need to keep looking...
+ if (this.found === true) {
+ return;
+ }
+ // switch lookaheads as they do not actually consume any characters thus
+ // finding a charCode at lookahead context does not mean that regexp can actually contain it in a match.
+ switch (node.type) {
+ case "Lookahead":
+ this.visitLookahead(node);
+ return;
+ case "NegativeLookahead":
+ this.visitNegativeLookahead(node);
+ return;
+ }
+ _super.prototype.visitChildren.call(this, node);
+ };
+ CharCodeFinder.prototype.visitCharacter = function (node) {
+ if (utils_1.contains(this.targetCharCodes, node.value)) {
+ this.found = true;
+ }
+ };
+ CharCodeFinder.prototype.visitSet = function (node) {
+ if (node.complement) {
+ if (findCode(node, this.targetCharCodes) === undefined) {
+ this.found = true;
+ }
+ }
+ else {
+ if (findCode(node, this.targetCharCodes) !== undefined) {
+ this.found = true;
+ }
+ }
+ };
+ return CharCodeFinder;
+}(regexp_to_ast_1.BaseRegExpVisitor));
+function canMatchCharCode(charCodes, pattern) {
+ if (pattern instanceof RegExp) {
+ var ast = reg_exp_parser_1.getRegExpAst(pattern);
+ var charCodeFinder = new CharCodeFinder(charCodes);
+ charCodeFinder.visit(ast);
+ return charCodeFinder.found;
+ }
+ else {
+ return (utils_1.find(pattern, function (char) {
+ return utils_1.contains(charCodes, char.charCodeAt(0));
+ }) !== undefined);
+ }
+}
+exports.canMatchCharCode = canMatchCharCode;
+//# sourceMappingURL=reg_exp.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/scan/reg_exp_parser.js b/node_modules/chevrotain/lib/src/scan/reg_exp_parser.js
new file mode 100644
index 0000000..dfab4e8
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/scan/reg_exp_parser.js
@@ -0,0 +1,22 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var regexp_to_ast_1 = require("regexp-to-ast");
+var regExpAstCache = {};
+var regExpParser = new regexp_to_ast_1.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;
+ }
+}
+exports.getRegExpAst = getRegExpAst;
+function clearRegExpParserCache() {
+ regExpAstCache = {};
+}
+exports.clearRegExpParserCache = clearRegExpParserCache;
+//# sourceMappingURL=reg_exp_parser.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/scan/tokens.js b/node_modules/chevrotain/lib/src/scan/tokens.js
new file mode 100644
index 0000000..c6e4a20
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/scan/tokens.js
@@ -0,0 +1,129 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../utils/utils");
+function tokenStructuredMatcher(tokInstance, tokConstructor) {
+ var instanceType = tokInstance.tokenTypeIdx;
+ if (instanceType === tokConstructor.tokenTypeIdx) {
+ return true;
+ }
+ else {
+ return (tokConstructor.isParent === true &&
+ tokConstructor.categoryMatchesMap[instanceType] === true);
+ }
+}
+exports.tokenStructuredMatcher = tokenStructuredMatcher;
+// 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;
+}
+exports.tokenStructuredMatcherNoCategories = tokenStructuredMatcherNoCategories;
+exports.tokenShortNameIdx = 1;
+exports.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);
+ utils_1.forEach(tokenTypesAndParents, function (tokType) {
+ tokType.isParent = tokType.categoryMatches.length > 0;
+ });
+}
+exports.augmentTokenTypes = augmentTokenTypes;
+function expandCategories(tokenTypes) {
+ var result = utils_1.cloneArr(tokenTypes);
+ var categories = tokenTypes;
+ var searching = true;
+ while (searching) {
+ categories = utils_1.compact(utils_1.flatten(utils_1.map(categories, function (currTokType) { return currTokType.CATEGORIES; })));
+ var newCategories = utils_1.difference(categories, result);
+ result = result.concat(newCategories);
+ if (utils_1.isEmpty(newCategories)) {
+ searching = false;
+ }
+ else {
+ categories = newCategories;
+ }
+ }
+ return result;
+}
+exports.expandCategories = expandCategories;
+function assignTokenDefaultProps(tokenTypes) {
+ utils_1.forEach(tokenTypes, function (currTokType) {
+ if (!hasShortKeyProperty(currTokType)) {
+ exports.tokenIdxToClass[exports.tokenShortNameIdx] = currTokType;
+ currTokType.tokenTypeIdx = exports.tokenShortNameIdx++;
+ }
+ // CATEGORIES? : TokenType | TokenType[]
+ if (hasCategoriesProperty(currTokType) &&
+ !utils_1.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 = {};
+ }
+ });
+}
+exports.assignTokenDefaultProps = assignTokenDefaultProps;
+function assignCategoriesTokensProp(tokenTypes) {
+ utils_1.forEach(tokenTypes, function (currTokType) {
+ // avoid duplications
+ currTokType.categoryMatches = [];
+ utils_1.forEach(currTokType.categoryMatchesMap, function (val, key) {
+ currTokType.categoryMatches.push(exports.tokenIdxToClass[key].tokenTypeIdx);
+ });
+ });
+}
+exports.assignCategoriesTokensProp = assignCategoriesTokensProp;
+function assignCategoriesMapProp(tokenTypes) {
+ utils_1.forEach(tokenTypes, function (currTokType) {
+ singleAssignCategoriesToksMap([], currTokType);
+ });
+}
+exports.assignCategoriesMapProp = assignCategoriesMapProp;
+function singleAssignCategoriesToksMap(path, nextNode) {
+ utils_1.forEach(path, function (pathNode) {
+ nextNode.categoryMatchesMap[pathNode.tokenTypeIdx] = true;
+ });
+ utils_1.forEach(nextNode.CATEGORIES, function (nextCategory) {
+ var newPath = path.concat(nextNode);
+ // avoids infinite loops due to cyclic categories.
+ if (!utils_1.contains(newPath, nextCategory)) {
+ singleAssignCategoriesToksMap(newPath, nextCategory);
+ }
+ });
+}
+exports.singleAssignCategoriesToksMap = singleAssignCategoriesToksMap;
+function hasShortKeyProperty(tokType) {
+ return utils_1.has(tokType, "tokenTypeIdx");
+}
+exports.hasShortKeyProperty = hasShortKeyProperty;
+function hasCategoriesProperty(tokType) {
+ return utils_1.has(tokType, "CATEGORIES");
+}
+exports.hasCategoriesProperty = hasCategoriesProperty;
+function hasExtendingTokensTypesProperty(tokType) {
+ return utils_1.has(tokType, "categoryMatches");
+}
+exports.hasExtendingTokensTypesProperty = hasExtendingTokensTypesProperty;
+function hasExtendingTokensTypesMapProperty(tokType) {
+ return utils_1.has(tokType, "categoryMatchesMap");
+}
+exports.hasExtendingTokensTypesMapProperty = hasExtendingTokensTypesMapProperty;
+function isTokenType(tokType) {
+ return utils_1.has(tokType, "tokenTypeIdx");
+}
+exports.isTokenType = isTokenType;
+//# sourceMappingURL=tokens.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/scan/tokens_constants.js b/node_modules/chevrotain/lib/src/scan/tokens_constants.js
new file mode 100644
index 0000000..e718961
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/scan/tokens_constants.js
@@ -0,0 +1,4 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.EOF_TOKEN_TYPE = 1;
+//# sourceMappingURL=tokens_constants.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/scan/tokens_public.js b/node_modules/chevrotain/lib/src/scan/tokens_public.js
new file mode 100644
index 0000000..8485a88
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/scan/tokens_public.js
@@ -0,0 +1,95 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var utils_1 = require("../utils/utils");
+var lexer_public_1 = require("./lexer_public");
+var tokens_1 = require("./tokens");
+function tokenLabel(tokType) {
+ if (hasTokenLabel(tokType)) {
+ return tokType.LABEL;
+ }
+ else {
+ return tokType.name;
+ }
+}
+exports.tokenLabel = tokenLabel;
+function tokenName(tokType) {
+ return tokType.name;
+}
+exports.tokenName = tokenName;
+function hasTokenLabel(obj) {
+ return utils_1.isString(obj.LABEL) && obj.LABEL !== "";
+}
+exports.hasTokenLabel = hasTokenLabel;
+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);
+}
+exports.createToken = createToken;
+function createTokenInternal(config) {
+ var pattern = config.pattern;
+ var tokenType = {};
+ tokenType.name = config.name;
+ 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)) {
+ // casting to ANY as this will be fixed inside `augmentTokenTypes``
+ 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];
+ }
+ if (utils_1.has(config, START_CHARS_HINT)) {
+ tokenType.START_CHARS_HINT = config[START_CHARS_HINT];
+ }
+ return tokenType;
+}
+exports.EOF = createToken({ name: "EOF", pattern: lexer_public_1.Lexer.NA });
+tokens_1.augmentTokenTypes([exports.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
+ };
+}
+exports.createTokenInstance = createTokenInstance;
+function tokenMatcher(token, tokType) {
+ return tokens_1.tokenStructuredMatcher(token, tokType);
+}
+exports.tokenMatcher = tokenMatcher;
+//# sourceMappingURL=tokens_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/text/range.js b/node_modules/chevrotain/lib/src/text/range.js
new file mode 100644
index 0000000..5241f99
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/text/range.js
@@ -0,0 +1,33 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+var Range = /** @class */ (function () {
+ function Range(start, end) {
+ this.start = start;
+ this.end = end;
+ if (!isValidRange(start, end)) {
+ throw new Error("INVALID RANGE");
+ }
+ }
+ Range.prototype.contains = function (num) {
+ return this.start <= num && this.end >= num;
+ };
+ Range.prototype.containsRange = function (other) {
+ return this.start <= other.start && this.end >= other.end;
+ };
+ Range.prototype.isContainedInRange = function (other) {
+ return other.containsRange(this);
+ };
+ Range.prototype.strictlyContainsRange = function (other) {
+ return this.start < other.start && this.end > other.end;
+ };
+ Range.prototype.isStrictlyContainedInRange = function (other) {
+ return other.strictlyContainsRange(this);
+ };
+ return Range;
+}());
+exports.Range = Range;
+function isValidRange(start, end) {
+ return !(start < 0 || end < start);
+}
+exports.isValidRange = isValidRange;
+//# sourceMappingURL=range.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/utils/utils.js b/node_modules/chevrotain/lib/src/utils/utils.js
new file mode 100644
index 0000000..4aac63d
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/utils/utils.js
@@ -0,0 +1,473 @@
+"use strict";
+/*
+ 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...
+ */
+Object.defineProperty(exports, "__esModule", { value: true });
+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) {
+ /* 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");
+ }
+}
+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 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;
+}
+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;
+/**
+ * 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;
+}
+exports.packArray = packArray;
+function PRINT_ERROR(msg) {
+ /* istanbul ignore else - can't override global.console in node.js */
+ if (console && console.error) {
+ console.error("Error: " + msg);
+ }
+}
+exports.PRINT_ERROR = PRINT_ERROR;
+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);
+ }
+}
+exports.PRINT_WARNING = PRINT_WARNING;
+function isES2015MapSupported() {
+ return typeof Map === "function";
+}
+exports.isES2015MapSupported = isES2015MapSupported;
+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];
+ }
+ });
+ });
+}
+exports.applyMixins = applyMixins;
+// 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);
+}
+exports.toFastProperties = toFastProperties;
+function peek(arr) {
+ return arr[arr.length - 1];
+}
+exports.peek = peek;
+/* 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 };
+}
+exports.timer = timer;
+//# sourceMappingURL=utils.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib/src/version.js b/node_modules/chevrotain/lib/src/version.js
new file mode 100644
index 0000000..c6246c3
--- /dev/null
+++ b/node_modules/chevrotain/lib/src/version.js
@@ -0,0 +1,7 @@
+"use strict";
+Object.defineProperty(exports, "__esModule", { value: true });
+// 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.
+exports.VERSION = "6.5.0";
+//# sourceMappingURL=version.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/api.js b/node_modules/chevrotain/lib_esm/src/api.js
new file mode 100644
index 0000000..8deed3a
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/api.js
@@ -0,0 +1,25 @@
+// semantic version
+export { VERSION } from "./version";
+export { Parser, CstParser, EmbeddedActionsParser, ParserDefinitionErrorType, EMPTY_ALT } from "./parse/parser/parser";
+export { Lexer, LexerDefinitionErrorType } from "./scan/lexer_public";
+// Tokens utilities
+export { createToken, createTokenInstance, EOF, tokenLabel, tokenMatcher, tokenName } from "./scan/tokens_public";
+// Other Utilities
+export { defaultGrammarResolverErrorProvider, defaultGrammarValidatorErrorProvider, defaultParserErrorProvider } from "./parse/errors_public";
+export { EarlyExitException, isRecognitionException, MismatchedTokenException, NotAllInputParsedException, NoViableAltException } from "./parse/exceptions_public";
+export { defaultLexerErrorProvider } from "./scan/lexer_errors_public";
+// grammar reflection API
+export { Alternation, Flat, NonTerminal, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Rule, Terminal } from "./parse/grammar/gast/gast_public";
+// GAST Utilities
+export { serializeGrammar, serializeProduction } from "./parse/grammar/gast/gast_public";
+export { GAstVisitor } from "./parse/grammar/gast/gast_visitor_public";
+export { assignOccurrenceIndices, resolveGrammar, validateGrammar } from "./parse/grammar/gast/gast_resolver_public";
+/* istanbul ignore next */
+export 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");
+}
+export { createSyntaxDiagramsCode } from "./diagrams/render_public";
+export { generateParserFactory, generateParserModule } from "./generate/generate_public";
+//# sourceMappingURL=api.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/diagrams/render_public.js b/node_modules/chevrotain/lib_esm/src/diagrams/render_public.js
new file mode 100644
index 0000000..00a16ad
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/diagrams/render_public.js
@@ -0,0 +1,12 @@
+import { VERSION } from "../version";
+export 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
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/generate/generate.js b/node_modules/chevrotain/lib_esm/src/generate/generate.js
new file mode 100644
index 0000000..379eaf1
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/generate/generate.js
@@ -0,0 +1,131 @@
+import { forEach, map } from "../utils/utils";
+import { RepetitionMandatory, Option, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Terminal, NonTerminal, Alternation, Flat, Repetition } from "../parse/grammar/gast/gast_public";
+/**
+ * Missing features
+ * 1. Rule arguments
+ * 2. Gates
+ * 3. embedded actions
+ */
+var NL = "\n";
+export 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";
+}
+export function genWrapperFunction(options) {
+ return " \n" + genClass(options) + "\nreturn new " + options.name + "(tokenVocabulary, config) \n";
+}
+export 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;
+}
+export function genAllRules(rules) {
+ var rulesText = map(rules, function (currRule) {
+ return genRule(currRule, 1);
+ });
+ return rulesText.join("\n");
+}
+export function genRule(prod, n) {
+ var result = indent(n, "$.RULE(\"" + prod.name + "\", function() {") + NL;
+ result += genDefinition(prod.definition, n + 1);
+ result += indent(n + 1, "})") + NL;
+ return result;
+}
+export function genTerminal(prod, n) {
+ var name = prod.terminalType.name;
+ // TODO: potential performance optimization, avoid tokenMap Dictionary access
+ return indent(n, "$.CONSUME" + prod.idx + "(this.tokensMap." + name + ")" + NL);
+}
+export function genNonTerminal(prod, n) {
+ return indent(n, "$.SUBRULE" + prod.idx + "($." + prod.nonTerminalName + ")" + NL);
+}
+export function genAlternation(prod, n) {
+ var result = indent(n, "$.OR" + prod.idx + "([") + NL;
+ var alts = map(prod.definition, function (altDef) { return genSingleAlt(altDef, n + 1); });
+ result += alts.join("," + NL);
+ result += NL + indent(n, "])" + NL);
+ return result;
+}
+export function genSingleAlt(prod, n) {
+ var result = indent(n, "{") + NL;
+ if (prod.name) {
+ result += indent(n + 1, "NAME: \"" + prod.name + "\",") + NL;
+ }
+ result += indent(n + 1, "ALT: function() {") + NL;
+ result += genDefinition(prod.definition, n + 1);
+ result += indent(n + 1, "}") + NL;
+ result += indent(n, "}");
+ return result;
+}
+function genProd(prod, n) {
+ /* istanbul ignore else */
+ if (prod instanceof NonTerminal) {
+ return genNonTerminal(prod, n);
+ }
+ else if (prod instanceof Option) {
+ return genDSLRule("OPTION", prod, n);
+ }
+ else if (prod instanceof RepetitionMandatory) {
+ return genDSLRule("AT_LEAST_ONE", prod, n);
+ }
+ else if (prod instanceof RepetitionMandatoryWithSeparator) {
+ return genDSLRule("AT_LEAST_ONE_SEP", prod, n);
+ }
+ else if (prod instanceof RepetitionWithSeparator) {
+ return genDSLRule("MANY_SEP", prod, n);
+ }
+ else if (prod instanceof Repetition) {
+ return genDSLRule("MANY", prod, n);
+ }
+ else if (prod instanceof Alternation) {
+ return genAlternation(prod, n);
+ }
+ else if (prod instanceof Terminal) {
+ return genTerminal(prod, n);
+ }
+ else if (prod instanceof Flat) {
+ return genDefinition(prod.definition, n);
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+function genDSLRule(dslName, prod, n) {
+ var result = indent(n, "$." + (dslName + prod.idx) + "(");
+ if (prod.name || prod.separator) {
+ result += "{" + NL;
+ if (prod.name) {
+ result += indent(n + 1, "NAME: \"" + prod.name + "\"") + "," + NL;
+ }
+ if (prod.separator) {
+ result +=
+ indent(n + 1, "SEP: this.tokensMap." + prod.separator.name) +
+ "," +
+ NL;
+ }
+ result += "DEF: " + genDefFunction(prod.definition, n + 2) + NL;
+ result += indent(n, "}") + NL;
+ }
+ else {
+ result += genDefFunction(prod.definition, n + 1);
+ }
+ result += indent(n, ")") + NL;
+ return result;
+}
+function genDefFunction(definition, n) {
+ var def = "function() {" + NL;
+ def += genDefinition(definition, n);
+ def += indent(n, "}") + NL;
+ return def;
+}
+function genDefinition(def, n) {
+ var result = "";
+ forEach(def, function (prod) {
+ result += genProd(prod, n + 1);
+ });
+ return result;
+}
+function indent(howMuch, text) {
+ var spaces = Array(howMuch * 4 + 1).join(" ");
+ return spaces + text;
+}
+//# sourceMappingURL=generate.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/generate/generate_public.js b/node_modules/chevrotain/lib_esm/src/generate/generate_public.js
new file mode 100644
index 0000000..fc8d424
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/generate/generate_public.js
@@ -0,0 +1,17 @@
+import { genUmdModule, genWrapperFunction } from "./generate";
+export 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
+ require("../api"));
+ };
+}
+export function generateParserModule(options) {
+ return genUmdModule({ name: options.name, rules: options.rules });
+}
+//# sourceMappingURL=generate_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/lang/lang_extensions.js b/node_modules/chevrotain/lib_esm/src/lang/lang_extensions.js
new file mode 100644
index 0000000..4baa8e7
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/lang/lang_extensions.js
@@ -0,0 +1,37 @@
+import { isUndefined } from "../utils/utils";
+export 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*/
+export 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
+ */
+export function defineNameProp(obj, nameValue) {
+ var namePropDescriptor = Object.getOwnPropertyDescriptor(obj, NAME);
+ /* istanbul ignore else -> will only run in old versions of node.js */
+ if (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
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/constants.js b/node_modules/chevrotain/lib_esm/src/parse/constants.js
new file mode 100644
index 0000000..5e29b32
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/constants.js
@@ -0,0 +1,3 @@
+// TODO: can this be removed? where is it used?
+export var IN = "_~IN~_";
+//# sourceMappingURL=constants.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/cst/cst.js b/node_modules/chevrotain/lib_esm/src/parse/cst/cst.js
new file mode 100644
index 0000000..dd271b9
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/cst/cst.js
@@ -0,0 +1,187 @@
+var __extends = (this && this.__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 __());
+ };
+})();
+import { forEach, isUndefined } from "../../utils/utils";
+import { AT_LEAST_ONE_IDX, AT_LEAST_ONE_SEP_IDX, getKeyForAltIndex, getKeyForAutomaticLookahead, MANY_IDX, MANY_SEP_IDX, OPTION_IDX, OR_IDX } from "../grammar/keys";
+import { Alternation, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator } from "../grammar/gast/gast_public";
+import { GAstVisitor } from "../grammar/gast/gast_visitor_public";
+/**
+ * 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**
+ */
+export 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**
+ */
+export 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;
+ }
+}
+export function addTerminalToCst(node, token, tokenTypeName) {
+ if (node.children[tokenTypeName] === undefined) {
+ node.children[tokenTypeName] = [token];
+ }
+ else {
+ node.children[tokenTypeName].push(token);
+ }
+}
+export function addNoneTerminalToCst(node, ruleName, ruleResult) {
+ if (node.children[ruleName] === undefined) {
+ node.children[ruleName] = [ruleResult];
+ }
+ else {
+ node.children[ruleName].push(ruleResult);
+ }
+}
+var NamedDSLMethodsCollectorVisitor = /** @class */ (function (_super) {
+ __extends(NamedDSLMethodsCollectorVisitor, _super);
+ function NamedDSLMethodsCollectorVisitor(ruleIdx) {
+ var _this = _super.call(this) || this;
+ _this.result = [];
+ _this.ruleIdx = ruleIdx;
+ return _this;
+ }
+ NamedDSLMethodsCollectorVisitor.prototype.collectNamedDSLMethod = function (node, newNodeConstructor, methodIdx) {
+ // TODO: better hack to copy what we need here...
+ if (!isUndefined(node.name)) {
+ // copy without name so this will indeed be processed later.
+ var nameLessNode
+ /* istanbul ignore else */
+ = void 0;
+ /* istanbul ignore else */
+ if (node instanceof Option ||
+ node instanceof Repetition ||
+ node instanceof RepetitionMandatory ||
+ node instanceof Alternation) {
+ nameLessNode = new newNodeConstructor({
+ definition: node.definition,
+ idx: node.idx
+ });
+ }
+ else if (node instanceof RepetitionMandatoryWithSeparator ||
+ node instanceof RepetitionWithSeparator) {
+ nameLessNode = new newNodeConstructor({
+ definition: node.definition,
+ idx: node.idx,
+ separator: node.separator
+ });
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ var def = [nameLessNode];
+ var key = getKeyForAutomaticLookahead(this.ruleIdx, methodIdx, node.idx);
+ this.result.push({ def: def, key: key, name: node.name, orgProd: node });
+ }
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitOption = function (node) {
+ this.collectNamedDSLMethod(node, Option, OPTION_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitRepetition = function (node) {
+ this.collectNamedDSLMethod(node, Repetition, MANY_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionMandatory = function (node) {
+ this.collectNamedDSLMethod(node, RepetitionMandatory, AT_LEAST_ONE_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) {
+ this.collectNamedDSLMethod(node, RepetitionMandatoryWithSeparator, AT_LEAST_ONE_SEP_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitRepetitionWithSeparator = function (node) {
+ this.collectNamedDSLMethod(node, RepetitionWithSeparator, MANY_SEP_IDX);
+ };
+ NamedDSLMethodsCollectorVisitor.prototype.visitAlternation = function (node) {
+ var _this = this;
+ this.collectNamedDSLMethod(node, Alternation, OR_IDX);
+ var hasMoreThanOneAlternative = node.definition.length > 1;
+ forEach(node.definition, function (currFlatAlt, altIdx) {
+ if (!isUndefined(currFlatAlt.name)) {
+ var def = currFlatAlt.definition;
+ if (hasMoreThanOneAlternative) {
+ def = [new Option({ definition: currFlatAlt.definition })];
+ }
+ else {
+ // mandatory
+ def = currFlatAlt.definition;
+ }
+ var key = getKeyForAltIndex(_this.ruleIdx, OR_IDX, node.idx, altIdx);
+ _this.result.push({
+ def: def,
+ key: key,
+ name: currFlatAlt.name,
+ orgProd: currFlatAlt
+ });
+ }
+ });
+ };
+ return NamedDSLMethodsCollectorVisitor;
+}(GAstVisitor));
+export { NamedDSLMethodsCollectorVisitor };
+export function expandAllNestedRuleNames(topRules, fullToShortName) {
+ var result = {
+ allRuleNames: []
+ };
+ forEach(topRules, function (currTopRule) {
+ var currTopRuleShortName = fullToShortName[currTopRule.name];
+ result.allRuleNames.push(currTopRule.name);
+ var namedCollectorVisitor = new NamedDSLMethodsCollectorVisitor(currTopRuleShortName);
+ currTopRule.accept(namedCollectorVisitor);
+ forEach(namedCollectorVisitor.result, function (_a) {
+ var def = _a.def, key = _a.key, name = _a.name;
+ result.allRuleNames.push(currTopRule.name + name);
+ });
+ });
+ return result;
+}
+//# sourceMappingURL=cst.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/cst/cst_visitor.js b/node_modules/chevrotain/lib_esm/src/parse/cst/cst_visitor.js
new file mode 100644
index 0000000..54e6626
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/cst/cst_visitor.js
@@ -0,0 +1,121 @@
+import { compact, contains, forEach, isArray, isEmpty, isFunction, isUndefined, keys, map } from "../../utils/utils";
+import { defineNameProp, functionName } from "../../lang/lang_extensions";
+import { validTermsPattern } from "../grammar/checks";
+export function defaultVisit(ctx, param) {
+ var childrenNames = keys(ctx);
+ var childrenNamesLength = childrenNames.length;
+ for (var i = 0; i < childrenNamesLength; i++) {
+ var currChildName = childrenNames[i];
+ var currChildArray = ctx[currChildName];
+ var currChildArrayLength = currChildArray.length;
+ for (var j = 0; j < currChildArrayLength; j++) {
+ var currChild = currChildArray[j];
+ // distinction between Tokens Children and CstNode children
+ if (currChild.tokenTypeIdx === undefined) {
+ if (currChild.fullName !== undefined) {
+ this[currChild.fullName](currChild.children, param);
+ }
+ else {
+ this[currChild.name](currChild.children, param);
+ }
+ }
+ }
+ }
+ // defaultVisit does not support generic out param
+ return undefined;
+}
+export 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 (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 (isUndefined(cstNode)) {
+ return undefined;
+ }
+ if (cstNode.fullName !== undefined) {
+ return this[cstNode.fullName](cstNode.children, param);
+ }
+ else {
+ return this[cstNode.name](cstNode.children, param);
+ }
+ },
+ validateVisitor: function () {
+ var semanticDefinitionErrors = validateVisitor(this, ruleNames);
+ if (!isEmpty(semanticDefinitionErrors)) {
+ var errorMessages = 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;
+}
+export 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);
+ forEach(ruleNames, function (ruleName) {
+ withDefaultsProto[ruleName] = defaultVisit;
+ });
+ derivedConstructor.prototype = withDefaultsProto;
+ derivedConstructor.prototype.constructor = derivedConstructor;
+ return derivedConstructor;
+}
+export var CstVisitorDefinitionError;
+(function (CstVisitorDefinitionError) {
+ CstVisitorDefinitionError[CstVisitorDefinitionError["REDUNDANT_METHOD"] = 0] = "REDUNDANT_METHOD";
+ CstVisitorDefinitionError[CstVisitorDefinitionError["MISSING_METHOD"] = 1] = "MISSING_METHOD";
+})(CstVisitorDefinitionError || (CstVisitorDefinitionError = {}));
+export function validateVisitor(visitorInstance, ruleNames) {
+ var missingErrors = validateMissingCstMethods(visitorInstance, ruleNames);
+ var redundantErrors = validateRedundantMethods(visitorInstance, ruleNames);
+ return missingErrors.concat(redundantErrors);
+}
+export function validateMissingCstMethods(visitorInstance, ruleNames) {
+ var errors = map(ruleNames, function (currRuleName) {
+ if (!isFunction(visitorInstance[currRuleName])) {
+ return {
+ msg: "Missing visitor method: <" + currRuleName + "> on " + functionName(visitorInstance.constructor) + " CST Visitor.",
+ type: CstVisitorDefinitionError.MISSING_METHOD,
+ methodName: currRuleName
+ };
+ }
+ });
+ return compact(errors);
+}
+var VALID_PROP_NAMES = ["constructor", "visit", "validateVisitor"];
+export function validateRedundantMethods(visitorInstance, ruleNames) {
+ var errors = [];
+ for (var prop in visitorInstance) {
+ if (validTermsPattern.test(prop) &&
+ isFunction(visitorInstance[prop]) &&
+ !contains(VALID_PROP_NAMES, prop) &&
+ !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
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/errors_public.js b/node_modules/chevrotain/lib_esm/src/parse/errors_public.js
new file mode 100644
index 0000000..6c06038
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/errors_public.js
@@ -0,0 +1,203 @@
+import { hasTokenLabel, tokenLabel } from "../scan/tokens_public";
+import * as utils from "../utils/utils";
+import { first, map, reduce } from "../utils/utils";
+import { NonTerminal, Rule, Terminal } from "./grammar/gast/gast_public";
+import { getProductionDslName } from "./grammar/gast/gast";
+import { validNestedRuleName } from "./grammar/checks";
+export 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 = first(actual).image;
+ var errSuffix = "\nbut found: '" + actualText + "'";
+ if (customUserDescription) {
+ return errPrefix + customUserDescription + errSuffix;
+ }
+ else {
+ var allLookAheadPaths = reduce(expectedPathsPerAlt, function (result, currAltPaths) { return result.concat(currAltPaths); }, []);
+ var nextValidTokenSequences = map(allLookAheadPaths, function (currPath) {
+ return "[" + map(currPath, function (currTokenType) {
+ return tokenLabel(currTokenType);
+ }).join(", ") + "]";
+ });
+ var nextValidSequenceItems = 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 = first(actual).image;
+ var errSuffix = "\nbut found: '" + actualText + "'";
+ if (customUserDescription) {
+ return errPrefix + customUserDescription + errSuffix;
+ }
+ else {
+ var nextValidTokenSequences = map(expectedIterationPaths, function (currPath) {
+ return "[" + 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);
+export 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;
+ }
+};
+export var defaultGrammarValidatorErrorProvider = {
+ buildDuplicateFoundError: function (topLevelRule, duplicateProds) {
+ function getExtraProductionArgument(prod) {
+ if (prod instanceof Terminal) {
+ return prod.terminalType.name;
+ }
+ else if (prod instanceof NonTerminal) {
+ return prod.nonTerminalName;
+ }
+ else {
+ return "";
+ }
+ }
+ var topLevelName = topLevelRule.name;
+ var duplicateProd = 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;
+ },
+ buildInvalidNestedRuleNameError: function (topLevelRule, nestedProd) {
+ var msg = "Invalid nested rule name: ->" + nestedProd.name + "<- inside rule: ->" + topLevelRule.name + "<-\n" +
+ ("it must match the pattern: ->" + 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 = first(nestedProd).name;
+ var errMsg = "Duplicate nested rule name: ->" + duplicateName + "<- inside rule: ->" + topLevelRule.name + "<-\n" +
+ "A nested name must be unique in the scope of a top level grammar rule.";
+ return errMsg;
+ },
+ buildNamespaceConflictError: function (rule) {
+ var errMsg = "Namespace conflict found in grammar.\n" +
+ ("The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <" + rule.name + ">.\n") +
+ "To resolve this make sure each Terminal and Non-Terminal names are unique\n" +
+ "This is easy to accomplish by using the convention that Terminal names start with an uppercase letter\n" +
+ "and Non-Terminal names start with a lower case letter.";
+ return errMsg;
+ },
+ buildAlternationPrefixAmbiguityError: function (options) {
+ var pathMsg = 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 = 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.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 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
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/exceptions_public.js b/node_modules/chevrotain/lib_esm/src/parse/exceptions_public.js
new file mode 100644
index 0000000..dd1675b
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/exceptions_public.js
@@ -0,0 +1,51 @@
+import { contains } from "../utils/utils";
+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
+export function isRecognitionException(error) {
+ // can't do instanceof on hacked custom js exceptions
+ return contains(RECOGNITION_EXCEPTION_NAMES, error.name);
+}
+export 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;
+export 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;
+export function NotAllInputParsedException(message, token) {
+ this.name = NOT_ALL_INPUT_PARSED_EXCEPTION;
+ this.message = message;
+ this.token = token;
+ this.resyncedTokens = [];
+}
+NotAllInputParsedException.prototype = Error.prototype;
+export 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
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/grammar/checks.js b/node_modules/chevrotain/lib_esm/src/parse/grammar/checks.js
new file mode 100644
index 0000000..73ecc84
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/grammar/checks.js
@@ -0,0 +1,574 @@
+var __extends = (this && this.__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 __());
+ };
+})();
+import * as utils from "../../utils/utils";
+import { contains, every, findAll, flatten, forEach, groupBy, isEmpty, map, pick, reduce, reject, values } from "../../utils/utils";
+import { ParserDefinitionErrorType } from "../parser/parser";
+import { getProductionDslName, isOptionalProd } from "./gast/gast";
+import { containsPath, getLookaheadPathsForOptionalProd, getLookaheadPathsForOr, getProdType, isStrictPrefixOfPath } from "./lookahead";
+import { NamedDSLMethodsCollectorVisitor } from "../cst/cst";
+import { nextPossibleTokensAfter } from "./interpreter";
+import { Alternation, Flat, NonTerminal, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Terminal } from "./gast/gast_public";
+import { GAstVisitor } from "./gast/gast_visitor_public";
+export function validateGrammar(topLevels, globalMaxLookahead, tokenTypes, ignoredIssues, errMsgProvider, grammarName) {
+ var duplicateErrors = utils.map(topLevels, function (currTopLevel) {
+ return validateDuplicateProductions(currTopLevel, errMsgProvider);
+ });
+ var leftRecursionErrors = utils.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 (every(leftRecursionErrors, isEmpty)) {
+ emptyAltErrors = map(topLevels, function (currTopRule) {
+ return validateEmptyOrAlternative(currTopRule, errMsgProvider);
+ });
+ ambiguousAltsErrors = map(topLevels, function (currTopRule) {
+ return validateAmbiguousAlternationAlternatives(currTopRule, globalMaxLookahead, ignoredIssues, errMsgProvider);
+ });
+ emptyRepetitionErrors = validateSomeNonEmptyLookaheadPath(topLevels, globalMaxLookahead, errMsgProvider);
+ }
+ var termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider);
+ var tokenNameErrors = utils.map(tokenTypes, function (currTokType) {
+ return validateTokenName(currTokType, errMsgProvider);
+ });
+ var nestedRulesNameErrors = validateNestedRulesNames(topLevels, errMsgProvider);
+ var nestedRulesDuplicateErrors = validateDuplicateNestedRules(topLevels, errMsgProvider);
+ var tooManyAltsErrors = map(topLevels, function (curRule) {
+ return validateTooManyAlts(curRule, errMsgProvider);
+ });
+ var ruleNameErrors = map(topLevels, function (curRule) {
+ return validateRuleName(curRule, errMsgProvider);
+ });
+ var duplicateRulesError = map(topLevels, function (curRule) {
+ return validateRuleDoesNotAlreadyExist(curRule, topLevels, grammarName, errMsgProvider);
+ });
+ return (utils.flatten(duplicateErrors.concat(tokenNameErrors, nestedRulesNameErrors, nestedRulesDuplicateErrors, emptyRepetitionErrors, leftRecursionErrors, emptyAltErrors, ambiguousAltsErrors, termsNamespaceConflictErrors, tooManyAltsErrors, ruleNameErrors, duplicateRulesError)));
+}
+function validateNestedRulesNames(topLevels, errMsgProvider) {
+ var result = [];
+ forEach(topLevels, function (curTopLevel) {
+ var namedCollectorVisitor = new NamedDSLMethodsCollectorVisitor("");
+ curTopLevel.accept(namedCollectorVisitor);
+ var nestedProds = map(namedCollectorVisitor.result, function (currItem) { return currItem.orgProd; });
+ result.push(map(nestedProds, function (currNestedProd) {
+ return validateNestedRuleName(curTopLevel, currNestedProd, errMsgProvider);
+ }));
+ });
+ return flatten(result);
+}
+function validateDuplicateProductions(topLevelRule, errMsgProvider) {
+ var collectorVisitor = new OccurrenceValidationCollector();
+ topLevelRule.accept(collectorVisitor);
+ var allRuleProductions = collectorVisitor.allProductions;
+ var productionGroups = utils.groupBy(allRuleProductions, identifyProductionForDuplicates);
+ var duplicates = utils.pick(productionGroups, function (currGroup) {
+ return currGroup.length > 1;
+ });
+ var errors = utils.map(utils.values(duplicates), function (currDuplicates) {
+ var firstProd = utils.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 = getExtraProductionArgument(firstProd);
+ if (param) {
+ defError.parameter = param;
+ }
+ return defError;
+ });
+ return errors;
+}
+export function identifyProductionForDuplicates(prod) {
+ return getProductionDslName(prod) + "_#_" + prod.idx + "_#_" + getExtraProductionArgument(prod);
+}
+function getExtraProductionArgument(prod) {
+ if (prod instanceof Terminal) {
+ return prod.terminalType.name;
+ }
+ else if (prod instanceof NonTerminal) {
+ return prod.nonTerminalName;
+ }
+ else {
+ return "";
+ }
+}
+var OccurrenceValidationCollector = /** @class */ (function (_super) {
+ __extends(OccurrenceValidationCollector, _super);
+ function OccurrenceValidationCollector() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.allProductions = [];
+ return _this;
+ }
+ OccurrenceValidationCollector.prototype.visitNonTerminal = function (subrule) {
+ this.allProductions.push(subrule);
+ };
+ OccurrenceValidationCollector.prototype.visitOption = function (option) {
+ this.allProductions.push(option);
+ };
+ OccurrenceValidationCollector.prototype.visitRepetitionWithSeparator = function (manySep) {
+ this.allProductions.push(manySep);
+ };
+ OccurrenceValidationCollector.prototype.visitRepetitionMandatory = function (atLeastOne) {
+ this.allProductions.push(atLeastOne);
+ };
+ OccurrenceValidationCollector.prototype.visitRepetitionMandatoryWithSeparator = function (atLeastOneSep) {
+ this.allProductions.push(atLeastOneSep);
+ };
+ OccurrenceValidationCollector.prototype.visitRepetition = function (many) {
+ this.allProductions.push(many);
+ };
+ OccurrenceValidationCollector.prototype.visitAlternation = function (or) {
+ this.allProductions.push(or);
+ };
+ OccurrenceValidationCollector.prototype.visitTerminal = function (terminal) {
+ this.allProductions.push(terminal);
+ };
+ return OccurrenceValidationCollector;
+}(GAstVisitor));
+export { OccurrenceValidationCollector };
+export var validTermsPattern = /^[a-zA-Z_]\w*$/;
+export var validNestedRuleName = new RegExp(validTermsPattern.source.replace("^", "^\\$"));
+// TODO: remove this limitation now that we use recorders
+export 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: did the nested rule name regExp now change?
+export function validateNestedRuleName(topLevel, nestedProd, errMsgProvider) {
+ var errors = [];
+ var errMsg;
+ if (!nestedProd.name.match(validNestedRuleName)) {
+ errMsg = errMsgProvider.buildInvalidNestedRuleNameError(topLevel, nestedProd);
+ errors.push({
+ message: errMsg,
+ type: ParserDefinitionErrorType.INVALID_NESTED_RULE_NAME,
+ ruleName: topLevel.name
+ });
+ }
+ return errors;
+}
+// TODO: remove this limitation now that we use recorders
+export 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;
+}
+export function validateRuleDoesNotAlreadyExist(rule, allRules, className, errMsgProvider) {
+ var errors = [];
+ var occurrences = 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.
+export function validateRuleIsOverridden(ruleName, definedRulesNames, className) {
+ var errors = [];
+ var errMsg;
+ if (!utils.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;
+}
+export function validateNoLeftRecursion(topRule, currRule, errMsgProvider, path) {
+ if (path === void 0) { path = []; }
+ var errors = [];
+ var nextNonTerminals = getFirstNoneTerminal(currRule.definition);
+ if (utils.isEmpty(nextNonTerminals)) {
+ return [];
+ }
+ else {
+ var ruleName = topRule.name;
+ var foundLeftRecursion = utils.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.difference(nextNonTerminals, path.concat([topRule]));
+ var errorsFromNextSteps = utils.map(validNextSteps, function (currRefRule) {
+ var newPath = utils.cloneArr(path);
+ newPath.push(currRefRule);
+ return validateNoLeftRecursion(topRule, currRefRule, errMsgProvider, newPath);
+ });
+ return errors.concat(utils.flatten(errorsFromNextSteps));
+ }
+}
+export function getFirstNoneTerminal(definition) {
+ var result = [];
+ if (utils.isEmpty(definition)) {
+ return result;
+ }
+ var firstProd = utils.first(definition);
+ /* istanbul ignore else */
+ if (firstProd instanceof NonTerminal) {
+ result.push(firstProd.referencedRule);
+ }
+ else if (firstProd instanceof Flat ||
+ firstProd instanceof Option ||
+ firstProd instanceof RepetitionMandatory ||
+ firstProd instanceof RepetitionMandatoryWithSeparator ||
+ firstProd instanceof RepetitionWithSeparator ||
+ firstProd instanceof Repetition) {
+ result = result.concat(getFirstNoneTerminal(firstProd.definition));
+ }
+ else if (firstProd instanceof Alternation) {
+ // each sub definition in alternation is a FLAT
+ result = utils.flatten(utils.map(firstProd.definition, function (currSubDef) {
+ return getFirstNoneTerminal(currSubDef.definition);
+ }));
+ }
+ else if (firstProd instanceof 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.drop(definition);
+ return result.concat(getFirstNoneTerminal(rest));
+ }
+ else {
+ return result;
+ }
+}
+var OrCollector = /** @class */ (function (_super) {
+ __extends(OrCollector, _super);
+ function OrCollector() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.alternations = [];
+ return _this;
+ }
+ OrCollector.prototype.visitAlternation = function (node) {
+ this.alternations.push(node);
+ };
+ return OrCollector;
+}(GAstVisitor));
+export function validateEmptyOrAlternative(topLevelRule, errMsgProvider) {
+ var orCollector = new OrCollector();
+ topLevelRule.accept(orCollector);
+ var ors = orCollector.alternations;
+ var errors = utils.reduce(ors, function (errors, currOr) {
+ var exceptLast = utils.dropRight(currOr.definition);
+ var currErrors = utils.map(exceptLast, function (currAlternative, currAltIdx) {
+ var possibleFirstInAlt = nextPossibleTokensAfter([currAlternative], [], null, 1);
+ if (utils.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.compact(currErrors));
+ }, []);
+ return errors;
+}
+export function validateAmbiguousAlternationAlternatives(topLevelRule, globalMaxLookahead, ignoredIssues, errMsgProvider) {
+ var orCollector = new OrCollector();
+ topLevelRule.accept(orCollector);
+ var ors = orCollector.alternations;
+ // TODO: this filtering should be deprecated once we remove the ignoredIssues
+ // IParserConfig property
+ var ignoredIssuesForCurrentRule = ignoredIssues[topLevelRule.name];
+ if (ignoredIssuesForCurrentRule) {
+ ors = reject(ors, function (currOr) {
+ return ignoredIssuesForCurrentRule[getProductionDslName(currOr) +
+ (currOr.idx === 0 ? "" : currOr.idx)];
+ });
+ }
+ // New Handling of ignoring ambiguities
+ // - https://github.com/SAP/chevrotain/issues/869
+ ors = reject(ors, function (currOr) { return currOr.ignoreAmbiguities === true; });
+ var errors = utils.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) {
+ __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;
+}(GAstVisitor));
+export { RepetionCollector };
+export function validateTooManyAlts(topLevelRule, errMsgProvider) {
+ var orCollector = new OrCollector();
+ topLevelRule.accept(orCollector);
+ var ors = orCollector.alternations;
+ var errors = utils.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;
+}
+export function validateSomeNonEmptyLookaheadPath(topLevelRules, maxLookahead, errMsgProvider) {
+ var errors = [];
+ forEach(topLevelRules, function (currTopRule) {
+ var collectorVisitor = new RepetionCollector();
+ currTopRule.accept(collectorVisitor);
+ var allRuleProductions = collectorVisitor.allProductions;
+ 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 (isEmpty(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 = reduce(alternatives, function (result, currAlt, currAltIdx) {
+ // ignore (skip) ambiguities with this alternative
+ if (alternation.definition[currAltIdx].ignoreAmbiguities === true) {
+ return result;
+ }
+ forEach(currAlt, function (currPath) {
+ var altsCurrPathAppearsIn = [currAltIdx];
+ 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.map(identicalAmbiguities, function (currAmbDescriptor) {
+ var ambgIndices = 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;
+}
+export function checkPrefixAlternativesAmbiguities(alternatives, alternation, rule, errMsgProvider) {
+ var errors = [];
+ // flatten
+ var pathsAndIndices = reduce(alternatives, function (result, currAlt, idx) {
+ var currPathsAndIdx = map(currAlt, function (currPath) {
+ return { idx: idx, path: currPath };
+ });
+ return result.concat(currPathsAndIdx);
+ }, []);
+ 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 = 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 = 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 = map(tokenTypes, function (currToken) { return currToken.name; });
+ forEach(topLevels, function (currRule) {
+ var currRuleName = currRule.name;
+ if (contains(tokenNames, currRuleName)) {
+ var errMsg = errMsgProvider.buildNamespaceConflictError(currRule);
+ errors.push({
+ message: errMsg,
+ type: ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,
+ ruleName: currRuleName
+ });
+ }
+ });
+ return errors;
+}
+function validateDuplicateNestedRules(topLevelRules, errMsgProvider) {
+ var errors = [];
+ forEach(topLevelRules, function (currTopRule) {
+ var namedCollectorVisitor = new NamedDSLMethodsCollectorVisitor("");
+ currTopRule.accept(namedCollectorVisitor);
+ var prodsByGroup = groupBy(namedCollectorVisitor.result, function (item) { return item.name; });
+ var duplicates = pick(prodsByGroup, function (currGroup) {
+ return currGroup.length > 1;
+ });
+ forEach(values(duplicates), function (currDupGroup) {
+ var currDupProds = map(currDupGroup, function (dupGroup) { return dupGroup.orgProd; });
+ var errMsg = errMsgProvider.buildDuplicateNestedRuleNameError(currTopRule, currDupProds);
+ errors.push({
+ message: errMsg,
+ type: ParserDefinitionErrorType.DUPLICATE_NESTED_NAME,
+ ruleName: currTopRule.name
+ });
+ });
+ });
+ return errors;
+}
+//# sourceMappingURL=checks.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/grammar/first.js b/node_modules/chevrotain/lib_esm/src/parse/grammar/first.js
new file mode 100644
index 0000000..3d9b112
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/grammar/first.js
@@ -0,0 +1,57 @@
+import { uniq, map, flatten } from "../../utils/utils";
+import { NonTerminal, Terminal } from "./gast/gast_public";
+import { isBranchingProd, isOptionalProd, isSequenceProd } from "./gast/gast";
+export function first(prod) {
+ /* istanbul ignore else */
+ if (prod instanceof 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 Terminal) {
+ return firstForTerminal(prod);
+ }
+ else if (isSequenceProd(prod)) {
+ return firstForSequence(prod);
+ }
+ else if (isBranchingProd(prod)) {
+ return firstForBranching(prod);
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+export 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 uniq(firstSet);
+}
+export function firstForBranching(prod) {
+ var allAlternativesFirsts = map(prod.definition, function (innerProd) {
+ return first(innerProd);
+ });
+ return uniq(flatten(allAlternativesFirsts));
+}
+export function firstForTerminal(terminal) {
+ return [terminal.terminalType];
+}
+//# sourceMappingURL=first.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/grammar/follow.js b/node_modules/chevrotain/lib_esm/src/parse/grammar/follow.js
new file mode 100644
index 0000000..8bf490f
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/grammar/follow.js
@@ -0,0 +1,62 @@
+var __extends = (this && this.__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 __());
+ };
+})();
+import { RestWalker } from "./rest";
+import { first } from "./first";
+import { assign, forEach } from "../../utils/utils";
+import { IN } from "../constants";
+import { Flat } from "./gast/gast_public";
+// This ResyncFollowsWalker computes all of the follows required for RESYNC
+// (skipping reference production).
+var ResyncFollowsWalker = /** @class */ (function (_super) {
+ __extends(ResyncFollowsWalker, _super);
+ function ResyncFollowsWalker(topProd) {
+ var _this = _super.call(this) || this;
+ _this.topProd = topProd;
+ _this.follows = {};
+ return _this;
+ }
+ ResyncFollowsWalker.prototype.startWalking = function () {
+ this.walk(this.topProd);
+ return this.follows;
+ };
+ ResyncFollowsWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) {
+ // do nothing! just like in the public sector after 13:00
+ };
+ ResyncFollowsWalker.prototype.walkProdRef = function (refProd, currRest, prevRest) {
+ var followName = buildBetweenProdsFollowPrefix(refProd.referencedRule, refProd.idx) +
+ this.topProd.name;
+ var fullRest = currRest.concat(prevRest);
+ var restProd = new Flat({ definition: fullRest });
+ var t_in_topProd_follows = first(restProd);
+ this.follows[followName] = t_in_topProd_follows;
+ };
+ return ResyncFollowsWalker;
+}(RestWalker));
+export { ResyncFollowsWalker };
+export function computeAllProdsFollows(topProductions) {
+ var reSyncFollows = {};
+ forEach(topProductions, function (topProd) {
+ var currRefsFollow = new ResyncFollowsWalker(topProd).startWalking();
+ assign(reSyncFollows, currRefsFollow);
+ });
+ return reSyncFollows;
+}
+export function buildBetweenProdsFollowPrefix(inner, occurenceInParent) {
+ return inner.name + occurenceInParent + IN;
+}
+export function buildInProdFollowPrefix(terminal) {
+ var terminalName = terminal.terminalType.name;
+ return terminalName + terminal.idx + IN;
+}
+//# sourceMappingURL=follow.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast.js b/node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast.js
new file mode 100644
index 0000000..d797ee0
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast.js
@@ -0,0 +1,163 @@
+var __extends = (this && this.__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 __());
+ };
+})();
+import { contains, every, has, some } from "../../../utils/utils";
+import { AbstractProduction, Alternation, Flat, NonTerminal, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Rule, Terminal } from "./gast_public";
+import { GAstVisitor } from "./gast_visitor_public";
+export function isSequenceProd(prod) {
+ return (prod instanceof Flat ||
+ prod instanceof Option ||
+ prod instanceof Repetition ||
+ prod instanceof RepetitionMandatory ||
+ prod instanceof RepetitionMandatoryWithSeparator ||
+ prod instanceof RepetitionWithSeparator ||
+ prod instanceof Terminal ||
+ prod instanceof Rule);
+}
+export function isOptionalProd(prod, alreadyVisited) {
+ if (alreadyVisited === void 0) { alreadyVisited = []; }
+ var isDirectlyOptional = prod instanceof Option ||
+ prod instanceof Repetition ||
+ prod instanceof 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 Alternation) {
+ // for OR its enough for just one of the alternatives to be optional
+ return some(prod.definition, function (subProd) {
+ return isOptionalProd(subProd, alreadyVisited);
+ });
+ }
+ else if (prod instanceof NonTerminal && contains(alreadyVisited, prod)) {
+ // avoiding stack overflow due to infinite recursion
+ return false;
+ }
+ else if (prod instanceof AbstractProduction) {
+ if (prod instanceof NonTerminal) {
+ alreadyVisited.push(prod);
+ }
+ return every(prod.definition, function (subProd) {
+ return isOptionalProd(subProd, alreadyVisited);
+ });
+ }
+ else {
+ return false;
+ }
+}
+export function isBranchingProd(prod) {
+ return prod instanceof Alternation;
+}
+export function getProductionDslName(prod) {
+ /* istanbul ignore else */
+ if (prod instanceof NonTerminal) {
+ return "SUBRULE";
+ }
+ else if (prod instanceof Option) {
+ return "OPTION";
+ }
+ else if (prod instanceof Alternation) {
+ return "OR";
+ }
+ else if (prod instanceof RepetitionMandatory) {
+ return "AT_LEAST_ONE";
+ }
+ else if (prod instanceof RepetitionMandatoryWithSeparator) {
+ return "AT_LEAST_ONE_SEP";
+ }
+ else if (prod instanceof RepetitionWithSeparator) {
+ return "MANY_SEP";
+ }
+ else if (prod instanceof Repetition) {
+ return "MANY";
+ }
+ else if (prod instanceof Terminal) {
+ return "CONSUME";
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+var DslMethodsCollectorVisitor = /** @class */ (function (_super) {
+ __extends(DslMethodsCollectorVisitor, _super);
+ function DslMethodsCollectorVisitor() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ // A minus is never valid in an identifier name
+ _this.separator = "-";
+ _this.dslMethods = {
+ option: [],
+ alternation: [],
+ repetition: [],
+ repetitionWithSeparator: [],
+ repetitionMandatory: [],
+ repetitionMandatoryWithSeparator: []
+ };
+ return _this;
+ }
+ DslMethodsCollectorVisitor.prototype.reset = function () {
+ this.dslMethods = {
+ option: [],
+ alternation: [],
+ repetition: [],
+ repetitionWithSeparator: [],
+ repetitionMandatory: [],
+ repetitionMandatoryWithSeparator: []
+ };
+ };
+ DslMethodsCollectorVisitor.prototype.visitTerminal = function (terminal) {
+ var key = terminal.terminalType.name + this.separator + "Terminal";
+ if (!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 (!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;
+}(GAstVisitor));
+export { DslMethodsCollectorVisitor };
+var collectorVisitor = new DslMethodsCollectorVisitor();
+export function collectMethods(rule) {
+ collectorVisitor.reset();
+ rule.accept(collectorVisitor);
+ var dslMethods = collectorVisitor.dslMethods;
+ // avoid uncleaned references
+ collectorVisitor.reset();
+ return dslMethods;
+}
+//# sourceMappingURL=gast.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast_public.js b/node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast_public.js
new file mode 100644
index 0000000..1f0b549
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast_public.js
@@ -0,0 +1,258 @@
+var __extends = (this && this.__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 __());
+ };
+})();
+import { assign, forEach, isRegExp, map, pick } from "../../../utils/utils";
+import { tokenLabel } from "../../../scan/tokens_public";
+var AbstractProduction = /** @class */ (function () {
+ function AbstractProduction(definition) {
+ this.definition = definition;
+ }
+ AbstractProduction.prototype.accept = function (visitor) {
+ visitor.visit(this);
+ forEach(this.definition, function (prod) {
+ prod.accept(visitor);
+ });
+ };
+ return AbstractProduction;
+}());
+export { AbstractProduction };
+var NonTerminal = /** @class */ (function (_super) {
+ __extends(NonTerminal, _super);
+ function NonTerminal(options) {
+ var _this = _super.call(this, []) || this;
+ _this.idx = 1;
+ assign(_this, pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ Object.defineProperty(NonTerminal.prototype, "definition", {
+ get: function () {
+ if (this.referencedRule !== undefined) {
+ return this.referencedRule.definition;
+ }
+ return [];
+ },
+ set: function (definition) {
+ // immutable
+ },
+ enumerable: true,
+ configurable: true
+ });
+ NonTerminal.prototype.accept = function (visitor) {
+ visitor.visit(this);
+ // don't visit children of a reference, we will get cyclic infinite loops if we do so
+ };
+ return NonTerminal;
+}(AbstractProduction));
+export { NonTerminal };
+var Rule = /** @class */ (function (_super) {
+ __extends(Rule, _super);
+ function Rule(options) {
+ var _this = _super.call(this, options.definition) || this;
+ _this.orgText = "";
+ assign(_this, pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ return Rule;
+}(AbstractProduction));
+export { Rule };
+// TODO: is this only used in an Alternation?
+// Perhaps `Flat` should be renamed to `Alternative`?
+var Flat = /** @class */ (function (_super) {
+ __extends(Flat, _super);
+ // A named Flat production is used to indicate a Nested Rule in an alternation
+ function Flat(options) {
+ var _this = _super.call(this, options.definition) || this;
+ _this.ignoreAmbiguities = false;
+ assign(_this, pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ return Flat;
+}(AbstractProduction));
+export { Flat };
+var Option = /** @class */ (function (_super) {
+ __extends(Option, _super);
+ function Option(options) {
+ var _this = _super.call(this, options.definition) || this;
+ _this.idx = 1;
+ assign(_this, pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ return Option;
+}(AbstractProduction));
+export { Option };
+var RepetitionMandatory = /** @class */ (function (_super) {
+ __extends(RepetitionMandatory, _super);
+ function RepetitionMandatory(options) {
+ var _this = _super.call(this, options.definition) || this;
+ _this.idx = 1;
+ assign(_this, pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ return RepetitionMandatory;
+}(AbstractProduction));
+export { RepetitionMandatory };
+var RepetitionMandatoryWithSeparator = /** @class */ (function (_super) {
+ __extends(RepetitionMandatoryWithSeparator, _super);
+ function RepetitionMandatoryWithSeparator(options) {
+ var _this = _super.call(this, options.definition) || this;
+ _this.idx = 1;
+ assign(_this, pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ return RepetitionMandatoryWithSeparator;
+}(AbstractProduction));
+export { RepetitionMandatoryWithSeparator };
+var Repetition = /** @class */ (function (_super) {
+ __extends(Repetition, _super);
+ function Repetition(options) {
+ var _this = _super.call(this, options.definition) || this;
+ _this.idx = 1;
+ assign(_this, pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ return Repetition;
+}(AbstractProduction));
+export { Repetition };
+var RepetitionWithSeparator = /** @class */ (function (_super) {
+ __extends(RepetitionWithSeparator, _super);
+ function RepetitionWithSeparator(options) {
+ var _this = _super.call(this, options.definition) || this;
+ _this.idx = 1;
+ assign(_this, pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ return RepetitionWithSeparator;
+}(AbstractProduction));
+export { RepetitionWithSeparator };
+var Alternation = /** @class */ (function (_super) {
+ __extends(Alternation, _super);
+ function Alternation(options) {
+ var _this = _super.call(this, options.definition) || this;
+ _this.idx = 1;
+ _this.ignoreAmbiguities = false;
+ _this.hasPredicates = false;
+ assign(_this, pick(options, function (v) { return v !== undefined; }));
+ return _this;
+ }
+ return Alternation;
+}(AbstractProduction));
+export { Alternation };
+var Terminal = /** @class */ (function () {
+ function Terminal(options) {
+ this.idx = 1;
+ assign(this, pick(options, function (v) { return v !== undefined; }));
+ }
+ Terminal.prototype.accept = function (visitor) {
+ visitor.visit(this);
+ };
+ return Terminal;
+}());
+export { Terminal };
+export function serializeGrammar(topRules) {
+ return map(topRules, serializeProduction);
+}
+export function serializeProduction(node) {
+ function convertDefinition(definition) {
+ return map(definition, serializeProduction);
+ }
+ /* istanbul ignore else */
+ if (node instanceof NonTerminal) {
+ return {
+ type: "NonTerminal",
+ name: node.nonTerminalName,
+ idx: node.idx
+ };
+ }
+ else if (node instanceof Flat) {
+ return {
+ type: "Flat",
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof Option) {
+ return {
+ type: "Option",
+ idx: node.idx,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof RepetitionMandatory) {
+ return {
+ type: "RepetitionMandatory",
+ name: node.name,
+ idx: node.idx,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof RepetitionMandatoryWithSeparator) {
+ return {
+ type: "RepetitionMandatoryWithSeparator",
+ name: node.name,
+ idx: node.idx,
+ separator: (serializeProduction(new Terminal({ terminalType: node.separator }))),
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof RepetitionWithSeparator) {
+ return {
+ type: "RepetitionWithSeparator",
+ name: node.name,
+ idx: node.idx,
+ separator: (serializeProduction(new Terminal({ terminalType: node.separator }))),
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof Repetition) {
+ return {
+ type: "Repetition",
+ name: node.name,
+ idx: node.idx,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof Alternation) {
+ return {
+ type: "Alternation",
+ name: node.name,
+ idx: node.idx,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else if (node instanceof Terminal) {
+ var serializedTerminal = {
+ type: "Terminal",
+ name: node.terminalType.name,
+ label: tokenLabel(node.terminalType),
+ idx: node.idx
+ };
+ var pattern = node.terminalType.PATTERN;
+ if (node.terminalType.PATTERN) {
+ serializedTerminal.pattern = isRegExp(pattern)
+ ? pattern.source
+ : pattern;
+ }
+ return serializedTerminal;
+ }
+ else if (node instanceof Rule) {
+ return {
+ type: "Rule",
+ name: node.name,
+ orgText: node.orgText,
+ definition: convertDefinition(node.definition)
+ };
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+//# sourceMappingURL=gast_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast_resolver_public.js b/node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast_resolver_public.js
new file mode 100644
index 0000000..18afb54
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast_resolver_public.js
@@ -0,0 +1,34 @@
+import { defaults, forEach } from "../../../utils/utils";
+import { resolveGrammar as orgResolveGrammar } from "../resolver";
+import { validateGrammar as orgValidateGrammar } from "../checks";
+import { defaultGrammarResolverErrorProvider, defaultGrammarValidatorErrorProvider } from "../../errors_public";
+import { DslMethodsCollectorVisitor } from "./gast";
+export function resolveGrammar(options) {
+ options = defaults(options, {
+ errMsgProvider: defaultGrammarResolverErrorProvider
+ });
+ var topRulesTable = {};
+ forEach(options.rules, function (rule) {
+ topRulesTable[rule.name] = rule;
+ });
+ return orgResolveGrammar(topRulesTable, options.errMsgProvider);
+}
+export function validateGrammar(options) {
+ options = defaults(options, {
+ errMsgProvider: defaultGrammarValidatorErrorProvider,
+ ignoredIssues: {}
+ });
+ return orgValidateGrammar(options.rules, options.maxLookahead, options.tokenTypes, options.ignoredIssues, options.errMsgProvider, options.grammarName);
+}
+export function assignOccurrenceIndices(options) {
+ forEach(options.rules, function (currRule) {
+ var methodsCollector = new DslMethodsCollectorVisitor();
+ currRule.accept(methodsCollector);
+ forEach(methodsCollector.dslMethods, function (methods) {
+ forEach(methods, function (currMethod, arrIdx) {
+ currMethod.idx = arrIdx + 1;
+ });
+ });
+ });
+}
+//# sourceMappingURL=gast_resolver_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast_visitor_public.js b/node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast_visitor_public.js
new file mode 100644
index 0000000..e56beb2
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/grammar/gast/gast_visitor_public.js
@@ -0,0 +1,46 @@
+import { Alternation, Flat, NonTerminal, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Rule, Terminal } from "./gast_public";
+var GAstVisitor = /** @class */ (function () {
+ function GAstVisitor() {
+ }
+ GAstVisitor.prototype.visit = function (node) {
+ var nodeAny = node;
+ switch (nodeAny.constructor) {
+ case NonTerminal:
+ return this.visitNonTerminal(nodeAny);
+ case Flat:
+ return this.visitFlat(nodeAny);
+ case Option:
+ return this.visitOption(nodeAny);
+ case RepetitionMandatory:
+ return this.visitRepetitionMandatory(nodeAny);
+ case RepetitionMandatoryWithSeparator:
+ return this.visitRepetitionMandatoryWithSeparator(nodeAny);
+ case RepetitionWithSeparator:
+ return this.visitRepetitionWithSeparator(nodeAny);
+ case Repetition:
+ return this.visitRepetition(nodeAny);
+ case Alternation:
+ return this.visitAlternation(nodeAny);
+ case Terminal:
+ return this.visitTerminal(nodeAny);
+ case Rule:
+ return this.visitRule(nodeAny);
+ /* istanbul ignore next */
+ default:
+ throw Error("non exhaustive match");
+ }
+ };
+ GAstVisitor.prototype.visitNonTerminal = function (node) { };
+ GAstVisitor.prototype.visitFlat = function (node) { };
+ GAstVisitor.prototype.visitOption = function (node) { };
+ GAstVisitor.prototype.visitRepetition = function (node) { };
+ GAstVisitor.prototype.visitRepetitionMandatory = function (node) { };
+ GAstVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) { };
+ GAstVisitor.prototype.visitRepetitionWithSeparator = function (node) { };
+ GAstVisitor.prototype.visitAlternation = function (node) { };
+ GAstVisitor.prototype.visitTerminal = function (node) { };
+ GAstVisitor.prototype.visitRule = function (node) { };
+ return GAstVisitor;
+}());
+export { GAstVisitor };
+//# sourceMappingURL=gast_visitor_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/grammar/interpreter.js b/node_modules/chevrotain/lib_esm/src/parse/grammar/interpreter.js
new file mode 100644
index 0000000..9de0189
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/grammar/interpreter.js
@@ -0,0 +1,544 @@
+var __extends = (this && this.__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 __());
+ };
+})();
+import { RestWalker } from "./rest";
+import { cloneArr, drop, dropRight, first as _first, forEach, isEmpty, last } from "../../utils/utils";
+import { first } from "./first";
+import { Alternation, Flat, NonTerminal, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Rule, Terminal } from "./gast/gast_public";
+var AbstractNextPossibleTokensWalker = /** @class */ (function (_super) {
+ __extends(AbstractNextPossibleTokensWalker, _super);
+ function AbstractNextPossibleTokensWalker(topProd, path) {
+ var _this = _super.call(this) || this;
+ _this.topProd = topProd;
+ _this.path = path;
+ _this.possibleTokTypes = [];
+ _this.nextProductionName = "";
+ _this.nextProductionOccurrence = 0;
+ _this.found = false;
+ _this.isAtEndOfPath = false;
+ return _this;
+ }
+ AbstractNextPossibleTokensWalker.prototype.startWalking = function () {
+ this.found = false;
+ if (this.path.ruleStack[0] !== this.topProd.name) {
+ throw Error("The path does not start with the walker's top Rule!");
+ }
+ // immutable for the win
+ this.ruleStack = cloneArr(this.path.ruleStack).reverse(); // intelij bug requires assertion
+ this.occurrenceStack = 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 (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;
+}(RestWalker));
+export { AbstractNextPossibleTokensWalker };
+var NextAfterTokenWalker = /** @class */ (function (_super) {
+ __extends(NextAfterTokenWalker, _super);
+ function NextAfterTokenWalker(topProd, path) {
+ var _this = _super.call(this, topProd, path) || this;
+ _this.path = path;
+ _this.nextTerminalName = "";
+ _this.nextTerminalOccurrence = 0;
+ _this.nextTerminalName = _this.path.lastTok.name;
+ _this.nextTerminalOccurrence = _this.path.lastTokOccurrence;
+ return _this;
+ }
+ NextAfterTokenWalker.prototype.walkTerminal = function (terminal, currRest, prevRest) {
+ if (this.isAtEndOfPath &&
+ terminal.terminalType.name === this.nextTerminalName &&
+ terminal.idx === this.nextTerminalOccurrence &&
+ !this.found) {
+ var fullRest = currRest.concat(prevRest);
+ var restProd = new Flat({ definition: fullRest });
+ this.possibleTokTypes = first(restProd);
+ this.found = true;
+ }
+ };
+ return NextAfterTokenWalker;
+}(AbstractNextPossibleTokensWalker));
+export { NextAfterTokenWalker };
+/**
+ * This walker only "walks" a single "TOP" level in the Grammar Ast, this means
+ * it never "follows" production refs
+ */
+var AbstractNextTerminalAfterProductionWalker = /** @class */ (function (_super) {
+ __extends(AbstractNextTerminalAfterProductionWalker, _super);
+ function AbstractNextTerminalAfterProductionWalker(topRule, occurrence) {
+ var _this = _super.call(this) || this;
+ _this.topRule = topRule;
+ _this.occurrence = occurrence;
+ _this.result = {
+ token: undefined,
+ occurrence: undefined,
+ isEndOfRule: undefined
+ };
+ return _this;
+ }
+ AbstractNextTerminalAfterProductionWalker.prototype.startWalking = function () {
+ this.walk(this.topRule);
+ return this.result;
+ };
+ return AbstractNextTerminalAfterProductionWalker;
+}(RestWalker));
+export { AbstractNextTerminalAfterProductionWalker };
+var NextTerminalAfterManyWalker = /** @class */ (function (_super) {
+ __extends(NextTerminalAfterManyWalker, _super);
+ function NextTerminalAfterManyWalker() {
+ return _super !== null && _super.apply(this, arguments) || this;
+ }
+ NextTerminalAfterManyWalker.prototype.walkMany = function (manyProd, currRest, prevRest) {
+ if (manyProd.idx === this.occurrence) {
+ var firstAfterMany = _first(currRest.concat(prevRest));
+ this.result.isEndOfRule = firstAfterMany === undefined;
+ if (firstAfterMany instanceof Terminal) {
+ this.result.token = firstAfterMany.terminalType;
+ this.result.occurrence = firstAfterMany.idx;
+ }
+ }
+ else {
+ _super.prototype.walkMany.call(this, manyProd, currRest, prevRest);
+ }
+ };
+ return NextTerminalAfterManyWalker;
+}(AbstractNextTerminalAfterProductionWalker));
+export { NextTerminalAfterManyWalker };
+var NextTerminalAfterManySepWalker = /** @class */ (function (_super) {
+ __extends(NextTerminalAfterManySepWalker, _super);
+ function NextTerminalAfterManySepWalker() {
+ return _super !== null && _super.apply(this, arguments) || this;
+ }
+ NextTerminalAfterManySepWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) {
+ if (manySepProd.idx === this.occurrence) {
+ var firstAfterManySep = _first(currRest.concat(prevRest));
+ this.result.isEndOfRule = firstAfterManySep === undefined;
+ if (firstAfterManySep instanceof Terminal) {
+ this.result.token = firstAfterManySep.terminalType;
+ this.result.occurrence = firstAfterManySep.idx;
+ }
+ }
+ else {
+ _super.prototype.walkManySep.call(this, manySepProd, currRest, prevRest);
+ }
+ };
+ return NextTerminalAfterManySepWalker;
+}(AbstractNextTerminalAfterProductionWalker));
+export { NextTerminalAfterManySepWalker };
+var NextTerminalAfterAtLeastOneWalker = /** @class */ (function (_super) {
+ __extends(NextTerminalAfterAtLeastOneWalker, _super);
+ function NextTerminalAfterAtLeastOneWalker() {
+ return _super !== null && _super.apply(this, arguments) || this;
+ }
+ NextTerminalAfterAtLeastOneWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) {
+ if (atLeastOneProd.idx === this.occurrence) {
+ var firstAfterAtLeastOne = _first(currRest.concat(prevRest));
+ this.result.isEndOfRule = firstAfterAtLeastOne === undefined;
+ if (firstAfterAtLeastOne instanceof Terminal) {
+ this.result.token = firstAfterAtLeastOne.terminalType;
+ this.result.occurrence = firstAfterAtLeastOne.idx;
+ }
+ }
+ else {
+ _super.prototype.walkAtLeastOne.call(this, atLeastOneProd, currRest, prevRest);
+ }
+ };
+ return NextTerminalAfterAtLeastOneWalker;
+}(AbstractNextTerminalAfterProductionWalker));
+export { NextTerminalAfterAtLeastOneWalker };
+// TODO: reduce code duplication in the AfterWalkers
+var NextTerminalAfterAtLeastOneSepWalker = /** @class */ (function (_super) {
+ __extends(NextTerminalAfterAtLeastOneSepWalker, _super);
+ function NextTerminalAfterAtLeastOneSepWalker() {
+ return _super !== null && _super.apply(this, arguments) || this;
+ }
+ NextTerminalAfterAtLeastOneSepWalker.prototype.walkAtLeastOneSep = function (atleastOneSepProd, currRest, prevRest) {
+ if (atleastOneSepProd.idx === this.occurrence) {
+ var firstAfterfirstAfterAtLeastOneSep = _first(currRest.concat(prevRest));
+ this.result.isEndOfRule =
+ firstAfterfirstAfterAtLeastOneSep === undefined;
+ if (firstAfterfirstAfterAtLeastOneSep instanceof Terminal) {
+ this.result.token =
+ firstAfterfirstAfterAtLeastOneSep.terminalType;
+ this.result.occurrence = firstAfterfirstAfterAtLeastOneSep.idx;
+ }
+ }
+ else {
+ _super.prototype.walkAtLeastOneSep.call(this, atleastOneSepProd, currRest, prevRest);
+ }
+ };
+ return NextTerminalAfterAtLeastOneSepWalker;
+}(AbstractNextTerminalAfterProductionWalker));
+export { NextTerminalAfterAtLeastOneSepWalker };
+export function possiblePathsFrom(targetDef, maxLength, currPath) {
+ if (currPath === void 0) { currPath = []; }
+ // avoid side effects
+ currPath = cloneArr(currPath);
+ var result = [];
+ var i = 0;
+ // TODO: avoid inner funcs
+ function remainingPathWith(nextDef) {
+ return nextDef.concat(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 Flat) {
+ return getAlternativesForProd(prod.definition);
+ }
+ else if (prod instanceof NonTerminal) {
+ return getAlternativesForProd(prod.definition);
+ }
+ else if (prod instanceof Option) {
+ result = getAlternativesForProd(prod.definition);
+ }
+ else if (prod instanceof RepetitionMandatory) {
+ var newDef = prod.definition.concat([
+ new Repetition({
+ definition: prod.definition
+ })
+ ]);
+ return getAlternativesForProd(newDef);
+ }
+ else if (prod instanceof RepetitionMandatoryWithSeparator) {
+ var newDef = [
+ new Flat({ definition: prod.definition }),
+ new Repetition({
+ definition: [
+ new Terminal({ terminalType: prod.separator })
+ ].concat(prod.definition)
+ })
+ ];
+ return getAlternativesForProd(newDef);
+ }
+ else if (prod instanceof RepetitionWithSeparator) {
+ var newDef = prod.definition.concat([
+ new Repetition({
+ definition: [
+ new Terminal({ terminalType: prod.separator })
+ ].concat(prod.definition)
+ })
+ ]);
+ result = getAlternativesForProd(newDef);
+ }
+ else if (prod instanceof Repetition) {
+ var newDef = prod.definition.concat([
+ new Repetition({
+ definition: prod.definition
+ })
+ ]);
+ result = getAlternativesForProd(newDef);
+ }
+ else if (prod instanceof Alternation) {
+ forEach(prod.definition, function (currAlt) {
+ result = getAlternativesForProd(currAlt.definition);
+ });
+ return result;
+ }
+ else if (prod instanceof Terminal) {
+ currPath.push(prod.terminalType);
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ i++;
+ }
+ result.push({
+ partialPath: currPath,
+ suffixDef: drop(targetDef, i)
+ });
+ return result;
+}
+export 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 (!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 &&
+ 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 (isEmpty(currDef)) {
+ continue;
+ }
+ var prod = currDef[0];
+ /* istanbul ignore else */
+ if (prod === EXIT_NON_TERMINAL) {
+ var nextPath = {
+ idx: currIdx,
+ def: drop(currDef),
+ ruleStack: dropRight(currRuleStack),
+ occurrenceStack: dropRight(currOccurrenceStack)
+ };
+ possiblePaths.push(nextPath);
+ }
+ else if (prod instanceof 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: 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 NonTerminal) {
+ var newRuleStack = cloneArr(currRuleStack);
+ newRuleStack.push(prod.nonTerminalName);
+ var newOccurrenceStack = cloneArr(currOccurrenceStack);
+ newOccurrenceStack.push(prod.idx);
+ var nextPath = {
+ idx: currIdx,
+ def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, drop(currDef)),
+ ruleStack: newRuleStack,
+ occurrenceStack: newOccurrenceStack
+ };
+ possiblePaths.push(nextPath);
+ }
+ else if (prod instanceof Option) {
+ // the order of alternatives is meaningful, FILO (Last path will be traversed first).
+ var nextPathWithout = {
+ idx: currIdx,
+ def: 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(drop(currDef)),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWith);
+ }
+ else if (prod instanceof RepetitionMandatory) {
+ // TODO:(THE NEW operators here take a while...) (convert once?)
+ var secondIteration = new Repetition({
+ definition: prod.definition,
+ idx: prod.idx
+ });
+ var nextDef = prod.definition.concat([secondIteration], drop(currDef));
+ var nextPath = {
+ idx: currIdx,
+ def: nextDef,
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPath);
+ }
+ else if (prod instanceof RepetitionMandatoryWithSeparator) {
+ // TODO:(THE NEW operators here take a while...) (convert once?)
+ var separatorGast = new Terminal({
+ terminalType: prod.separator
+ });
+ var secondIteration = new Repetition({
+ definition: [separatorGast].concat(prod.definition),
+ idx: prod.idx
+ });
+ var nextDef = prod.definition.concat([secondIteration], drop(currDef));
+ var nextPath = {
+ idx: currIdx,
+ def: nextDef,
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPath);
+ }
+ else if (prod instanceof RepetitionWithSeparator) {
+ // the order of alternatives is meaningful, FILO (Last path will be traversed first).
+ var nextPathWithout = {
+ idx: currIdx,
+ def: 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 Terminal({
+ terminalType: prod.separator
+ });
+ var nthRepetition = new Repetition({
+ definition: [separatorGast].concat(prod.definition),
+ idx: prod.idx
+ });
+ var nextDef = prod.definition.concat([nthRepetition], drop(currDef));
+ var nextPathWith = {
+ idx: currIdx,
+ def: nextDef,
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWith);
+ }
+ else if (prod instanceof Repetition) {
+ // the order of alternatives is meaningful, FILO (Last path will be traversed first).
+ var nextPathWithout = {
+ idx: currIdx,
+ def: 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 Repetition({
+ definition: prod.definition,
+ idx: prod.idx
+ });
+ var nextDef = prod.definition.concat([nthRepetition], drop(currDef));
+ var nextPathWith = {
+ idx: currIdx,
+ def: nextDef,
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(nextPathWith);
+ }
+ else if (prod instanceof 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(drop(currDef)),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ };
+ possiblePaths.push(currAltPath);
+ possiblePaths.push(EXIT_ALTERNATIVE);
+ }
+ }
+ else if (prod instanceof Flat) {
+ possiblePaths.push({
+ idx: currIdx,
+ def: prod.definition.concat(drop(currDef)),
+ ruleStack: currRuleStack,
+ occurrenceStack: currOccurrenceStack
+ });
+ }
+ else if (prod instanceof 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 = cloneArr(currRuleStack);
+ newRuleStack.push(topRule.name);
+ var newCurrOccurrenceStack = 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
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/grammar/keys.js b/node_modules/chevrotain/lib_esm/src/parse/grammar/keys.js
new file mode 100644
index 0000000..dcd3d59
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/grammar/keys.js
@@ -0,0 +1,38 @@
+// 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
+export var BITS_FOR_METHOD_TYPE = 4;
+export var BITS_FOR_OCCURRENCE_IDX = 8;
+export var BITS_FOR_RULE_IDX = 12;
+// TODO: validation, this means that there may at most 2^8 --> 256 alternatives for an alternation.
+export 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 */
+export var OR_IDX = 1 << BITS_FOR_OCCURRENCE_IDX;
+export var OPTION_IDX = 2 << BITS_FOR_OCCURRENCE_IDX;
+export var MANY_IDX = 3 << BITS_FOR_OCCURRENCE_IDX;
+export var AT_LEAST_ONE_IDX = 4 << BITS_FOR_OCCURRENCE_IDX;
+export var MANY_SEP_IDX = 5 << BITS_FOR_OCCURRENCE_IDX;
+export 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)
+export function getKeyForAutomaticLookahead(ruleIdx, dslMethodIdx, occurrence) {
+ /* tslint:disable */
+ return occurrence | dslMethodIdx | ruleIdx;
+ /* tslint:enable */
+}
+var BITS_START_FOR_ALT_IDX = 32 - BITS_FOR_ALT_IDX;
+export function getKeyForAltIndex(ruleIdx, dslMethodIdx, occurrence, altIdx) {
+ /* tslint:disable */
+ // alternative indices are zero based, thus must always add one (turn on one bit) to guarantee uniqueness.
+ var altIdxBitMap = (altIdx + 1) << BITS_START_FOR_ALT_IDX;
+ return (getKeyForAutomaticLookahead(ruleIdx, dslMethodIdx, occurrence) |
+ altIdxBitMap);
+ /* tslint:enable */
+}
+//# sourceMappingURL=keys.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/grammar/lookahead.js b/node_modules/chevrotain/lib_esm/src/parse/grammar/lookahead.js
new file mode 100644
index 0000000..cecff31
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/grammar/lookahead.js
@@ -0,0 +1,489 @@
+var __extends = (this && this.__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 __());
+ };
+})();
+import { map, reduce, every, isEmpty, flatten, forEach, has } from "../../utils/utils";
+import { possiblePathsFrom } from "./interpreter";
+import { RestWalker } from "./rest";
+import { tokenStructuredMatcher, tokenStructuredMatcherNoCategories } from "../../scan/tokens";
+import { Alternation, Flat, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator } from "./gast/gast_public";
+import { GAstVisitor } from "./gast/gast_visitor_public";
+export 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 = {}));
+export function getProdType(prod) {
+ /* istanbul ignore else */
+ if (prod instanceof Option) {
+ return PROD_TYPE.OPTION;
+ }
+ else if (prod instanceof Repetition) {
+ return PROD_TYPE.REPETITION;
+ }
+ else if (prod instanceof RepetitionMandatory) {
+ return PROD_TYPE.REPETITION_MANDATORY;
+ }
+ else if (prod instanceof RepetitionMandatoryWithSeparator) {
+ return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR;
+ }
+ else if (prod instanceof RepetitionWithSeparator) {
+ return PROD_TYPE.REPETITION_WITH_SEPARATOR;
+ }
+ else if (prod instanceof Alternation) {
+ return PROD_TYPE.ALTERNATION;
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+export 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.
+ */
+export 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);
+}
+export function buildAlternativesLookAheadFunc(alts, hasPredicates, tokenMatcher, dynamicTokensEnabled) {
+ var numOfAlts = alts.length;
+ var areAllOneTokenLookahead = every(alts, function (currAlt) {
+ return 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 = 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 = map(alts, function (currAlt) {
+ return flatten(currAlt);
+ });
+ var choiceToAlt_1 = reduce(singleTokenAlts, function (result, currAlt, idx) {
+ forEach(currAlt, function (currTokType) {
+ if (!has(result, currTokType.tokenTypeIdx)) {
+ result[currTokType.tokenTypeIdx] = idx;
+ }
+ forEach(currTokType.categoryMatches, function (currExtendingType) {
+ if (!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;
+ };
+ }
+}
+export function buildSingleAlternativeLookaheadFunction(alt, tokenMatcher, dynamicTokensEnabled) {
+ var areAllOneTokenLookahead = 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 = flatten(alt);
+ if (singleTokensTypes.length === 1 &&
+ 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 = reduce(singleTokensTypes, function (result, currTokType, idx) {
+ result[currTokType.tokenTypeIdx] = true;
+ forEach(currTokType.categoryMatches, function (currExtendingType) {
+ result[currExtendingType] = true;
+ });
+ return result;
+ }, []);
+ return function () {
+ var nextToken = this.LA(1);
+ return choiceToAlt_2[nextToken.tokenTypeIdx] === true;
+ };
+ }
+ }
+ else {
+ return function () {
+ nextPath: for (var j = 0; j < numOfPaths; j++) {
+ var currPath = alt[j];
+ var currPathLength = currPath.length;
+ for (var i = 0; i < currPathLength; i++) {
+ var nextToken = this.LA(i + 1);
+ if (tokenMatcher(nextToken, currPath[i]) === false) {
+ // mismatch in current path
+ // try the next pth
+ continue nextPath;
+ }
+ }
+ // found a full path that matches.
+ return true;
+ }
+ // none of the paths matched
+ return false;
+ };
+ }
+}
+var RestDefinitionFinderWalker = /** @class */ (function (_super) {
+ __extends(RestDefinitionFinderWalker, _super);
+ function RestDefinitionFinderWalker(topProd, targetOccurrence, targetProdType) {
+ var _this = _super.call(this) || this;
+ _this.topProd = topProd;
+ _this.targetOccurrence = targetOccurrence;
+ _this.targetProdType = targetProdType;
+ return _this;
+ }
+ RestDefinitionFinderWalker.prototype.startWalking = function () {
+ this.walk(this.topProd);
+ return this.restDef;
+ };
+ RestDefinitionFinderWalker.prototype.checkIsTarget = function (node, expectedProdType, currRest, prevRest) {
+ if (node.idx === this.targetOccurrence &&
+ this.targetProdType === expectedProdType) {
+ this.restDef = currRest.concat(prevRest);
+ return true;
+ }
+ // performance optimization, do not iterate over the entire Grammar ast after we have found the target
+ return false;
+ };
+ RestDefinitionFinderWalker.prototype.walkOption = function (optionProd, currRest, prevRest) {
+ if (!this.checkIsTarget(optionProd, PROD_TYPE.OPTION, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, optionProd, currRest, prevRest);
+ }
+ };
+ RestDefinitionFinderWalker.prototype.walkAtLeastOne = function (atLeastOneProd, currRest, prevRest) {
+ if (!this.checkIsTarget(atLeastOneProd, PROD_TYPE.REPETITION_MANDATORY, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, atLeastOneProd, currRest, prevRest);
+ }
+ };
+ RestDefinitionFinderWalker.prototype.walkAtLeastOneSep = function (atLeastOneSepProd, currRest, prevRest) {
+ if (!this.checkIsTarget(atLeastOneSepProd, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, atLeastOneSepProd, currRest, prevRest);
+ }
+ };
+ RestDefinitionFinderWalker.prototype.walkMany = function (manyProd, currRest, prevRest) {
+ if (!this.checkIsTarget(manyProd, PROD_TYPE.REPETITION, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, manyProd, currRest, prevRest);
+ }
+ };
+ RestDefinitionFinderWalker.prototype.walkManySep = function (manySepProd, currRest, prevRest) {
+ if (!this.checkIsTarget(manySepProd, PROD_TYPE.REPETITION_WITH_SEPARATOR, currRest, prevRest)) {
+ _super.prototype.walkOption.call(this, manySepProd, currRest, prevRest);
+ }
+ };
+ return RestDefinitionFinderWalker;
+}(RestWalker));
+/**
+ * Returns the definition of a target production in a top level level rule.
+ */
+var InsideDefinitionFinderVisitor = /** @class */ (function (_super) {
+ __extends(InsideDefinitionFinderVisitor, _super);
+ function InsideDefinitionFinderVisitor(targetOccurrence, targetProdType, targetRef) {
+ var _this = _super.call(this) || this;
+ _this.targetOccurrence = targetOccurrence;
+ _this.targetProdType = targetProdType;
+ _this.targetRef = targetRef;
+ _this.result = [];
+ return _this;
+ }
+ InsideDefinitionFinderVisitor.prototype.checkIsTarget = function (node, expectedProdName) {
+ if (node.idx === this.targetOccurrence &&
+ this.targetProdType === expectedProdName &&
+ (this.targetRef === undefined || node === this.targetRef)) {
+ this.result = node.definition;
+ }
+ };
+ InsideDefinitionFinderVisitor.prototype.visitOption = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.OPTION);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitRepetition = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.REPETITION);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatory = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitRepetitionMandatoryWithSeparator = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitRepetitionWithSeparator = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.REPETITION_WITH_SEPARATOR);
+ };
+ InsideDefinitionFinderVisitor.prototype.visitAlternation = function (node) {
+ this.checkIsTarget(node, PROD_TYPE.ALTERNATION);
+ };
+ return InsideDefinitionFinderVisitor;
+}(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;
+}
+export function lookAheadSequenceFromAlternatives(altsDefs, k) {
+ var partialAlts = map(altsDefs, function (currAlt) { return possiblePathsFrom([currAlt], 1); });
+ var finalResult = initializeArrayOfArrays(partialAlts.length);
+ var altsHashes = map(partialAlts, function (currAltPaths) {
+ var dict = {};
+ forEach(currAltPaths, function (item) {
+ var keys = pathToHashKeys(item.partialPath);
+ 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 ||
+ 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
+ forEach(newPartialPathsAndSuffixes, function (item) {
+ var prefixKeys = pathToHashKeys(item.partialPath);
+ forEach(prefixKeys, function (key) {
+ altsHashes[altIdx][key] = true;
+ });
+ });
+ }
+ }
+ };
+ // alternatives loop
+ for (var altIdx = 0; altIdx < currDataset.length; altIdx++) {
+ _loop_1(altIdx);
+ }
+ }
+ return finalResult;
+}
+export function getLookaheadPathsForOr(occurrence, ruleGrammar, k, orProd) {
+ var visitor = new InsideDefinitionFinderVisitor(occurrence, PROD_TYPE.ALTERNATION, orProd);
+ ruleGrammar.accept(visitor);
+ return lookAheadSequenceFromAlternatives(visitor.result, k);
+}
+export 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 Flat({ definition: insideDef });
+ var afterFlat = new Flat({ definition: afterDef });
+ return lookAheadSequenceFromAlternatives([insideFlat, afterFlat], k);
+}
+export 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;
+}
+export function isStrictPrefixOfPath(prefix, other) {
+ return (prefix.length < other.length &&
+ every(prefix, function (tokType, idx) {
+ var otherTokType = other[idx];
+ return (tokType === otherTokType ||
+ otherTokType.categoryMatchesMap[tokType.tokenTypeIdx]);
+ }));
+}
+export function areTokenCategoriesNotUsed(lookAheadPaths) {
+ return every(lookAheadPaths, function (singleAltPaths) {
+ return every(singleAltPaths, function (singlePath) {
+ return every(singlePath, function (token) { return isEmpty(token.categoryMatches); });
+ });
+ });
+}
+//# sourceMappingURL=lookahead.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/grammar/resolver.js b/node_modules/chevrotain/lib_esm/src/parse/grammar/resolver.js
new file mode 100644
index 0000000..37dc6f8
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/grammar/resolver.js
@@ -0,0 +1,56 @@
+var __extends = (this && this.__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 __());
+ };
+})();
+import { ParserDefinitionErrorType } from "../parser/parser";
+import { forEach, values } from "../../utils/utils";
+import { GAstVisitor } from "./gast/gast_visitor_public";
+export function resolveGrammar(topLevels, errMsgProvider) {
+ var refResolver = new GastRefResolverVisitor(topLevels, errMsgProvider);
+ refResolver.resolveRefs();
+ return refResolver.errors;
+}
+var GastRefResolverVisitor = /** @class */ (function (_super) {
+ __extends(GastRefResolverVisitor, _super);
+ function GastRefResolverVisitor(nameToTopRule, errMsgProvider) {
+ var _this = _super.call(this) || this;
+ _this.nameToTopRule = nameToTopRule;
+ _this.errMsgProvider = errMsgProvider;
+ _this.errors = [];
+ return _this;
+ }
+ GastRefResolverVisitor.prototype.resolveRefs = function () {
+ var _this = this;
+ forEach(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;
+}(GAstVisitor));
+export { GastRefResolverVisitor };
+//# sourceMappingURL=resolver.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/grammar/rest.js b/node_modules/chevrotain/lib_esm/src/parse/grammar/rest.js
new file mode 100644
index 0000000..07b6297
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/grammar/rest.js
@@ -0,0 +1,110 @@
+import { drop, forEach } from "../../utils/utils";
+import { Alternation, Flat, NonTerminal, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Terminal } from "./gast/gast_public";
+/**
+ * A Grammar Walker that computes the "remaining" grammar "after" a productions in the grammar.
+ */
+var RestWalker = /** @class */ (function () {
+ function RestWalker() {
+ }
+ RestWalker.prototype.walk = function (prod, prevRest) {
+ var _this = this;
+ if (prevRest === void 0) { prevRest = []; }
+ forEach(prod.definition, function (subProd, index) {
+ var currRest = drop(prod.definition, index + 1);
+ /* istanbul ignore else */
+ if (subProd instanceof NonTerminal) {
+ _this.walkProdRef(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof Terminal) {
+ _this.walkTerminal(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof Flat) {
+ _this.walkFlat(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof Option) {
+ _this.walkOption(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof RepetitionMandatory) {
+ _this.walkAtLeastOne(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof RepetitionMandatoryWithSeparator) {
+ _this.walkAtLeastOneSep(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof RepetitionWithSeparator) {
+ _this.walkManySep(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof Repetition) {
+ _this.walkMany(subProd, currRest, prevRest);
+ }
+ else if (subProd instanceof 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 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 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
+ 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 Flat({ definition: [alt] });
+ _this.walk(prodWrapper, fullOrRest);
+ });
+ };
+ return RestWalker;
+}());
+export { RestWalker };
+function restForRepetitionWithSeparator(repSepProd, currRest, prevRest) {
+ var repSepRest = [
+ new Option({
+ definition: [
+ new Terminal({ terminalType: repSepProd.separator })
+ ].concat(repSepProd.definition)
+ })
+ ];
+ var fullRepSepRest = repSepRest.concat(currRest, prevRest);
+ return fullRepSepRest;
+}
+//# sourceMappingURL=rest.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/parser/parser.js b/node_modules/chevrotain/lib_esm/src/parse/parser/parser.js
new file mode 100644
index 0000000..24d9914
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/parser/parser.js
@@ -0,0 +1,232 @@
+var __extends = (this && this.__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 __());
+ };
+})();
+import { applyMixins, cloneObj, forEach, has, isEmpty, map, PRINT_WARNING, toFastProperties, values } from "../../utils/utils";
+import { computeAllProdsFollows } from "../grammar/follow";
+import { createTokenInstance, EOF } from "../../scan/tokens_public";
+import { expandAllNestedRuleNames } from "../cst/cst";
+import { defaultGrammarValidatorErrorProvider, defaultParserErrorProvider } from "../errors_public";
+import { resolveGrammar, validateGrammar } from "../grammar/gast/gast_resolver_public";
+import { Recoverable } from "./traits/recoverable";
+import { LooksAhead } from "./traits/looksahead";
+import { TreeBuilder } from "./traits/tree_builder";
+import { LexerAdapter } from "./traits/lexer_adapter";
+import { RecognizerApi } from "./traits/recognizer_api";
+import { RecognizerEngine } from "./traits/recognizer_engine";
+import { ErrorHandler } from "./traits/error_handler";
+import { ContentAssist } from "./traits/context_assist";
+import { GastRecorder } from "./traits/gast_recorder";
+import { PerformanceTracer } from "./traits/perf_tracer";
+export var END_OF_FILE = createTokenInstance(EOF, "", NaN, NaN, NaN, NaN, NaN, NaN);
+Object.freeze(END_OF_FILE);
+export var DEFAULT_PARSER_CONFIG = Object.freeze({
+ recoveryEnabled: false,
+ maxLookahead: 4,
+ ignoredIssues: {},
+ dynamicTokensEnabled: false,
+ outputCst: true,
+ errorMessageProvider: defaultParserErrorProvider,
+ nodeLocationTracking: "none",
+ traceInitPerf: false,
+ skipValidations: false
+});
+export var DEFAULT_RULE_CONFIG = Object.freeze({
+ recoveryValueFunc: function () { return undefined; },
+ resyncEnabled: true
+});
+export var ParserDefinitionErrorType;
+(function (ParserDefinitionErrorType) {
+ ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_NAME"] = 0] = "INVALID_RULE_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_RULE_NAME"] = 1] = "DUPLICATE_RULE_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_RULE_OVERRIDE"] = 2] = "INVALID_RULE_OVERRIDE";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_PRODUCTIONS"] = 3] = "DUPLICATE_PRODUCTIONS";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["UNRESOLVED_SUBRULE_REF"] = 4] = "UNRESOLVED_SUBRULE_REF";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["LEFT_RECURSION"] = 5] = "LEFT_RECURSION";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["NONE_LAST_EMPTY_ALT"] = 6] = "NONE_LAST_EMPTY_ALT";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_ALTS"] = 7] = "AMBIGUOUS_ALTS";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["CONFLICT_TOKENS_RULES_NAMESPACE"] = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_TOKEN_NAME"] = 9] = "INVALID_TOKEN_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["INVALID_NESTED_RULE_NAME"] = 10] = "INVALID_NESTED_RULE_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["DUPLICATE_NESTED_NAME"] = 11] = "DUPLICATE_NESTED_NAME";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["NO_NON_EMPTY_LOOKAHEAD"] = 12] = "NO_NON_EMPTY_LOOKAHEAD";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["AMBIGUOUS_PREFIX_ALTS"] = 13] = "AMBIGUOUS_PREFIX_ALTS";
+ ParserDefinitionErrorType[ParserDefinitionErrorType["TOO_MANY_ALTS"] = 14] = "TOO_MANY_ALTS";
+})(ParserDefinitionErrorType || (ParserDefinitionErrorType = {}));
+export function EMPTY_ALT(value) {
+ if (value === void 0) { value = undefined; }
+ return function () {
+ return value;
+ };
+}
+var Parser = /** @class */ (function () {
+ function Parser(tokenVocabulary, config) {
+ if (config === void 0) { config = DEFAULT_PARSER_CONFIG; }
+ this.ignoredIssues = DEFAULT_PARSER_CONFIG.ignoredIssues;
+ this.definitionErrors = [];
+ this.selfAnalysisDone = false;
+ var that = this;
+ that.initErrorHandler(config);
+ that.initLexerAdapter();
+ that.initLooksAhead(config);
+ that.initRecognizerEngine(tokenVocabulary, config);
+ that.initRecoverable(config);
+ that.initTreeBuilder(config);
+ that.initContentAssist();
+ that.initGastRecorder(config);
+ that.initPerformanceTracer(config);
+ /* istanbul ignore if - complete over-kill to test this, we should only add a test when we actually hard deprecate it and throw an error... */
+ if (has(config, "ignoredIssues") &&
+ config.ignoredIssues !== DEFAULT_PARSER_CONFIG.ignoredIssues) {
+ PRINT_WARNING("The IParserConfig property is soft-deprecated and will be removed in future versions.\n\t" +
+ "Please use the flag on the relevant DSL method instead.");
+ }
+ this.ignoredIssues = has(config, "ignoredIssues")
+ ? config.ignoredIssues
+ : DEFAULT_PARSER_CONFIG.ignoredIssues;
+ this.skipValidations = has(config, "skipValidations")
+ ? config.skipValidations
+ : DEFAULT_PARSER_CONFIG.skipValidations;
+ }
+ /**
+ * @deprecated use the **instance** method with the same name instead
+ */
+ Parser.performSelfAnalysis = function (parserInstance) {
+ ;
+ parserInstance.performSelfAnalysis();
+ };
+ Parser.prototype.performSelfAnalysis = function () {
+ var _this = this;
+ this.TRACE_INIT("performSelfAnalysis", function () {
+ var defErrorsMsgs;
+ _this.selfAnalysisDone = true;
+ var className = _this.className;
+ _this.TRACE_INIT("toFastProps", function () {
+ // Without this voodoo magic the parser would be x3-x4 slower
+ // It seems it is better to invoke `toFastProperties` **before**
+ // Any manipulations of the `this` object done during the recording phase.
+ toFastProperties(_this);
+ });
+ _this.TRACE_INIT("Grammar Recording", function () {
+ try {
+ _this.enableRecording();
+ // Building the GAST
+ 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 = resolveGrammar({
+ rules: 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 (isEmpty(resolverErrors) && _this.skipValidations === false) {
+ var validationErrors = validateGrammar({
+ rules: values(_this.gastProductionsCache),
+ maxLookahead: _this.maxLookahead,
+ tokenTypes: values(_this.tokensMap),
+ ignoredIssues: _this.ignoredIssues,
+ 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 (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(values(_this.gastProductionsCache));
+ _this.resyncFollows = allFollows;
+ });
+ }
+ _this.TRACE_INIT("ComputeLookaheadFunctions", function () {
+ _this.preComputeLookaheadFunctions(values(_this.gastProductionsCache));
+ });
+ }
+ _this.TRACE_INIT("expandAllNestedRuleNames", function () {
+ // TODO: is this needed for EmbeddedActionsParser?
+ var cstAnalysisResult = expandAllNestedRuleNames(values(_this.gastProductionsCache), _this.fullRuleNameToShort);
+ _this.allRuleNames = cstAnalysisResult.allRuleNames;
+ });
+ if (!Parser.DEFER_DEFINITION_ERRORS_HANDLING &&
+ !isEmpty(_this.definitionErrors)) {
+ defErrorsMsgs = 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;
+}());
+export { Parser };
+applyMixins(Parser, [
+ Recoverable,
+ LooksAhead,
+ TreeBuilder,
+ LexerAdapter,
+ RecognizerEngine,
+ RecognizerApi,
+ ErrorHandler,
+ ContentAssist,
+ GastRecorder,
+ PerformanceTracer
+]);
+var CstParser = /** @class */ (function (_super) {
+ __extends(CstParser, _super);
+ function CstParser(tokenVocabulary, config) {
+ if (config === void 0) { config = DEFAULT_PARSER_CONFIG; }
+ var _this = this;
+ var configClone = cloneObj(config);
+ configClone.outputCst = true;
+ _this = _super.call(this, tokenVocabulary, configClone) || this;
+ return _this;
+ }
+ return CstParser;
+}(Parser));
+export { CstParser };
+var EmbeddedActionsParser = /** @class */ (function (_super) {
+ __extends(EmbeddedActionsParser, _super);
+ function EmbeddedActionsParser(tokenVocabulary, config) {
+ if (config === void 0) { config = DEFAULT_PARSER_CONFIG; }
+ var _this = this;
+ var configClone = cloneObj(config);
+ configClone.outputCst = false;
+ _this = _super.call(this, tokenVocabulary, configClone) || this;
+ return _this;
+ }
+ return EmbeddedActionsParser;
+}(Parser));
+export { EmbeddedActionsParser };
+//# sourceMappingURL=parser.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/parser/traits/context_assist.js b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/context_assist.js
new file mode 100644
index 0000000..4d4fbc0
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/context_assist.js
@@ -0,0 +1,26 @@
+import { NextAfterTokenWalker, nextPossibleTokensAfter } from "../../grammar/interpreter";
+import { first, isUndefined } from "../../../utils/utils";
+var ContentAssist = /** @class */ (function () {
+ function ContentAssist() {
+ }
+ ContentAssist.prototype.initContentAssist = function () { };
+ ContentAssist.prototype.computeContentAssist = function (startRuleName, precedingInput) {
+ var startRuleGast = this.gastProductionsCache[startRuleName];
+ if (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 = first(grammarPath.ruleStack);
+ var gastProductions = this.getGAstProductions();
+ var topProduction = gastProductions[topRuleName];
+ var nextPossibleTokenTypes = new NextAfterTokenWalker(topProduction, grammarPath).startWalking();
+ return nextPossibleTokenTypes;
+ };
+ return ContentAssist;
+}());
+export { ContentAssist };
+//# sourceMappingURL=context_assist.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/parser/traits/error_handler.js b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/error_handler.js
new file mode 100644
index 0000000..15c6850
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/error_handler.js
@@ -0,0 +1,81 @@
+import { EarlyExitException, isRecognitionException, NoViableAltException } from "../../exceptions_public";
+import { cloneArr, defaults } from "../../../utils/utils";
+import { getLookaheadPathsForOptionalProd, getLookaheadPathsForOr } from "../../grammar/lookahead";
+import { DEFAULT_PARSER_CONFIG } from "../parser";
+/**
+ * Trait responsible for runtime parsing errors.
+ */
+var ErrorHandler = /** @class */ (function () {
+ function ErrorHandler() {
+ }
+ ErrorHandler.prototype.initErrorHandler = function (config) {
+ this._errors = [];
+ this.errorMessageProvider = defaults(config.errorMessageProvider, DEFAULT_PARSER_CONFIG.errorMessageProvider);
+ };
+ ErrorHandler.prototype.SAVE_ERROR = function (error) {
+ if (isRecognitionException(error)) {
+ error.context = {
+ ruleStack: this.getHumanReadableRuleStack(),
+ ruleOccurrenceStack: cloneArr(this.RULE_OCCURRENCE_STACK)
+ };
+ this._errors.push(error);
+ return error;
+ }
+ else {
+ throw Error("Trying to save an Error which is not a RecognitionException");
+ }
+ };
+ Object.defineProperty(ErrorHandler.prototype, "errors", {
+ // TODO: extract these methods to ErrorHandler Trait?
+ get: function () {
+ return cloneArr(this._errors);
+ },
+ set: function (newErrors) {
+ this._errors = newErrors;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ // TODO: consider caching the error message computed information
+ ErrorHandler.prototype.raiseEarlyExitException = function (occurrence, prodType, userDefinedErrMsg) {
+ var ruleName = this.getCurrRuleFullName();
+ var ruleGrammar = this.getGAstProductions()[ruleName];
+ var lookAheadPathsPerAlternative = 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;
+}());
+export { ErrorHandler };
+//# sourceMappingURL=error_handler.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/parser/traits/gast_recorder.js b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/gast_recorder.js
new file mode 100644
index 0000000..e47f312
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/gast_recorder.js
@@ -0,0 +1,316 @@
+import { forEach, has, isArray, isFunction, peek, some } from "../../../utils/utils";
+import { Alternation, Flat, NonTerminal, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Rule, Terminal } from "../../grammar/gast/gast_public";
+import { Lexer } from "../../../scan/lexer_public";
+import { augmentTokenTypes, hasShortKeyProperty } from "../../../scan/tokens";
+import { createToken, createTokenInstance } from "../../../scan/tokens_public";
+import { END_OF_FILE } from "../parser";
+import { BITS_FOR_OCCURRENCE_IDX } from "../../grammar/keys";
+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.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 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 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, Option, actionORMethodDef, occurrence);
+ };
+ GastRecorder.prototype.atLeastOneInternalRecord = function (occurrence, actionORMethodDef) {
+ recordProd.call(this, RepetitionMandatory, actionORMethodDef, occurrence);
+ };
+ GastRecorder.prototype.atLeastOneSepFirstInternalRecord = function (occurrence, options) {
+ recordProd.call(this, RepetitionMandatoryWithSeparator, options, occurrence, HANDLE_SEPARATOR);
+ };
+ GastRecorder.prototype.manyInternalRecord = function (occurrence, actionORMethodDef) {
+ recordProd.call(this, Repetition, actionORMethodDef, occurrence);
+ };
+ GastRecorder.prototype.manySepFirstInternalRecord = function (occurrence, options) {
+ recordProd.call(this, 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 || 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 = peek(this.recordingProdStack);
+ var ruleName = ruleToCall["ruleName"];
+ var newNoneTerminal = new 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 = peek(this.recordingProdStack);
+ var newNoneTerminal = new Terminal({
+ idx: occurrence,
+ terminalType: tokType
+ });
+ prevProd.definition.push(newNoneTerminal);
+ return RECORDING_PHASE_TOKEN;
+ };
+ return GastRecorder;
+}());
+export { GastRecorder };
+function recordProd(prodConstructor, mainProdArg, occurrence, handleSep) {
+ if (handleSep === void 0) { handleSep = false; }
+ assertMethodIdxIsValid(occurrence);
+ var prevProd = peek(this.recordingProdStack);
+ var grammarAction = isFunction(mainProdArg)
+ ? mainProdArg
+ : mainProdArg.DEF;
+ var newProd = new prodConstructor({ definition: [], idx: occurrence });
+ if (has(mainProdArg, "NAME")) {
+ newProd.name = mainProdArg.NAME;
+ }
+ if (handleSep) {
+ newProd.separator = mainProdArg.SEP;
+ }
+ if (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 = peek(this.recordingProdStack);
+ // Only an array of alternatives
+ var hasOptions = isArray(mainProdArg) === false;
+ var alts = hasOptions === false ? mainProdArg : mainProdArg.DEF;
+ var newOrProd = new Alternation({
+ definition: [],
+ idx: occurrence,
+ ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true
+ });
+ if (has(mainProdArg, "NAME")) {
+ newOrProd.name = mainProdArg.NAME;
+ }
+ if (has(mainProdArg, "MAX_LOOKAHEAD")) {
+ newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;
+ }
+ var hasPredicates = some(alts, function (currAlt) { return isFunction(currAlt.GATE); });
+ newOrProd.hasPredicates = hasPredicates;
+ prevProd.definition.push(newOrProd);
+ forEach(alts, function (currAlt) {
+ var currAltFlat = new Flat({ definition: [] });
+ newOrProd.definition.push(currAltFlat);
+ if (has(currAlt, "NAME")) {
+ currAltFlat.name = currAlt.NAME;
+ }
+ if (has(currAlt, "IGNORE_AMBIGUITIES")) {
+ currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES;
+ }
+ // **implicit** ignoreAmbiguities due to usage of gate
+ else if (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
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/parser/traits/lexer_adapter.js b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/lexer_adapter.js
new file mode 100644
index 0000000..7f84a7d
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/lexer_adapter.js
@@ -0,0 +1,74 @@
+import { END_OF_FILE } from "../parser";
+/**
+ * Trait responsible abstracting over the interaction with Lexer output (Token vector).
+ *
+ * This could be generalized to support other kinds of lexers, e.g.
+ * - Just in Time Lexing / Lexer-Less parsing.
+ * - Streaming Lexer.
+ */
+var LexerAdapter = /** @class */ (function () {
+ function LexerAdapter() {
+ }
+ LexerAdapter.prototype.initLexerAdapter = function () {
+ this.tokVector = [];
+ this.tokVectorLength = 0;
+ this.currIdx = -1;
+ };
+ Object.defineProperty(LexerAdapter.prototype, "input", {
+ get: function () {
+ return this.tokVector;
+ },
+ set: function (newInput) {
+ if (this.selfAnalysisDone !== true) {
+ throw Error("Missing invocation at the end of the Parser's constructor.");
+ }
+ this.reset();
+ this.tokVector = newInput;
+ this.tokVectorLength = newInput.length;
+ },
+ enumerable: true,
+ configurable: true
+ });
+ // skips a token and returns the next token
+ LexerAdapter.prototype.SKIP_TOKEN = function () {
+ if (this.currIdx <= this.tokVector.length - 2) {
+ this.consumeToken();
+ return this.LA(1);
+ }
+ else {
+ return 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;
+}());
+export { LexerAdapter };
+//# sourceMappingURL=lexer_adapter.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/parser/traits/looksahead.js b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/looksahead.js
new file mode 100644
index 0000000..9274a6f
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/looksahead.js
@@ -0,0 +1,106 @@
+import { buildAlternativesLookAheadFunc, buildLookaheadFuncForOptionalProd, buildLookaheadFuncForOr, buildSingleAlternativeLookaheadFunction, PROD_TYPE } from "../../grammar/lookahead";
+import { forEach, has, isES2015MapSupported } from "../../../utils/utils";
+import { DEFAULT_PARSER_CONFIG } from "../parser";
+import { AT_LEAST_ONE_IDX, AT_LEAST_ONE_SEP_IDX, getKeyForAutomaticLookahead, MANY_IDX, MANY_SEP_IDX, OPTION_IDX, OR_IDX } from "../../grammar/keys";
+import { collectMethods, getProductionDslName } from "../../grammar/gast/gast";
+/**
+ * Trait responsible for the lookahead related utilities and optimizations.
+ */
+var LooksAhead = /** @class */ (function () {
+ function LooksAhead() {
+ }
+ LooksAhead.prototype.initLooksAhead = function (config) {
+ this.dynamicTokensEnabled = has(config, "dynamicTokensEnabled")
+ ? config.dynamicTokensEnabled
+ : DEFAULT_PARSER_CONFIG.dynamicTokensEnabled;
+ this.maxLookahead = 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 = 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 (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;
+ 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;
+ 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);
+ });
+ });
+ forEach(repetition, function (currProd) {
+ _this.computeLookaheadFunc(currRule, currProd.idx, MANY_IDX, PROD_TYPE.REPETITION, currProd.maxLookahead, getProductionDslName(currProd));
+ });
+ forEach(option, function (currProd) {
+ _this.computeLookaheadFunc(currRule, currProd.idx, OPTION_IDX, PROD_TYPE.OPTION, currProd.maxLookahead, getProductionDslName(currProd));
+ });
+ forEach(repetitionMandatory, function (currProd) {
+ _this.computeLookaheadFunc(currRule, currProd.idx, AT_LEAST_ONE_IDX, PROD_TYPE.REPETITION_MANDATORY, currProd.maxLookahead, getProductionDslName(currProd));
+ });
+ forEach(repetitionMandatoryWithSeparator, function (currProd) {
+ _this.computeLookaheadFunc(currRule, currProd.idx, AT_LEAST_ONE_SEP_IDX, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currProd.maxLookahead, getProductionDslName(currProd));
+ });
+ 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;
+}());
+export { LooksAhead };
+//# sourceMappingURL=looksahead.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/parser/traits/parser_traits.js b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/parser_traits.js
new file mode 100644
index 0000000..82d5781
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/parser_traits.js
@@ -0,0 +1,5 @@
+import { Parser as ParserConstructorImpel, CstParser as CstParserConstructorImpel, EmbeddedActionsParser as EmbeddedActionsParserConstructorImpel } from "../parser";
+export var Parser = ParserConstructorImpel;
+export var CstParser = (CstParserConstructorImpel);
+export var EmbeddedActionsParser = EmbeddedActionsParserConstructorImpel;
+//# sourceMappingURL=parser_traits.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/parser/traits/perf_tracer.js b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/perf_tracer.js
new file mode 100644
index 0000000..552238a
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/perf_tracer.js
@@ -0,0 +1,51 @@
+import { has, timer } from "../../../utils/utils";
+import { DEFAULT_PARSER_CONFIG } from "../parser";
+/**
+ * Trait responsible for runtime parsing errors.
+ */
+var PerformanceTracer = /** @class */ (function () {
+ function PerformanceTracer() {
+ }
+ PerformanceTracer.prototype.initPerformanceTracer = function (config) {
+ if (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 = 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;
+}());
+export { PerformanceTracer };
+//# sourceMappingURL=perf_tracer.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/parser/traits/recognizer_api.js b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/recognizer_api.js
new file mode 100644
index 0000000..a491f53
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/recognizer_api.js
@@ -0,0 +1,341 @@
+import { contains, values } from "../../../utils/utils";
+import { isRecognitionException } from "../../exceptions_public";
+import { DEFAULT_RULE_CONFIG, ParserDefinitionErrorType } from "../parser";
+import { defaultGrammarValidatorErrorProvider } from "../../errors_public";
+import { validateRuleIsOverridden } from "../../grammar/checks";
+import { serializeGrammar } from "../../grammar/gast/gast_public";
+/**
+ * This trait is responsible for implementing the public API
+ * for defining Chevrotain parsers, i.e:
+ * - CONSUME
+ * - RULE
+ * - OPTION
+ * - ...
+ */
+var RecognizerApi = /** @class */ (function () {
+ function RecognizerApi() {
+ }
+ RecognizerApi.prototype.ACTION = function (impl) {
+ return impl.call(this);
+ };
+ RecognizerApi.prototype.consume = function (idx, tokType, options) {
+ return this.consumeInternal(tokType, idx, options);
+ };
+ RecognizerApi.prototype.subrule = function (idx, ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, idx, options);
+ };
+ RecognizerApi.prototype.option = function (idx, actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, idx);
+ };
+ RecognizerApi.prototype.or = function (idx, altsOrOpts) {
+ return this.orInternal(altsOrOpts, idx);
+ };
+ RecognizerApi.prototype.many = function (idx, actionORMethodDef) {
+ return this.manyInternal(idx, actionORMethodDef);
+ };
+ RecognizerApi.prototype.atLeastOne = function (idx, actionORMethodDef) {
+ return this.atLeastOneInternal(idx, actionORMethodDef);
+ };
+ RecognizerApi.prototype.CONSUME = function (tokType, options) {
+ return this.consumeInternal(tokType, 0, options);
+ };
+ RecognizerApi.prototype.CONSUME1 = function (tokType, options) {
+ return this.consumeInternal(tokType, 1, options);
+ };
+ RecognizerApi.prototype.CONSUME2 = function (tokType, options) {
+ return this.consumeInternal(tokType, 2, options);
+ };
+ RecognizerApi.prototype.CONSUME3 = function (tokType, options) {
+ return this.consumeInternal(tokType, 3, options);
+ };
+ RecognizerApi.prototype.CONSUME4 = function (tokType, options) {
+ return this.consumeInternal(tokType, 4, options);
+ };
+ RecognizerApi.prototype.CONSUME5 = function (tokType, options) {
+ return this.consumeInternal(tokType, 5, options);
+ };
+ RecognizerApi.prototype.CONSUME6 = function (tokType, options) {
+ return this.consumeInternal(tokType, 6, options);
+ };
+ RecognizerApi.prototype.CONSUME7 = function (tokType, options) {
+ return this.consumeInternal(tokType, 7, options);
+ };
+ RecognizerApi.prototype.CONSUME8 = function (tokType, options) {
+ return this.consumeInternal(tokType, 8, options);
+ };
+ RecognizerApi.prototype.CONSUME9 = function (tokType, options) {
+ return this.consumeInternal(tokType, 9, options);
+ };
+ RecognizerApi.prototype.SUBRULE = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 0, options);
+ };
+ RecognizerApi.prototype.SUBRULE1 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 1, options);
+ };
+ RecognizerApi.prototype.SUBRULE2 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 2, options);
+ };
+ RecognizerApi.prototype.SUBRULE3 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 3, options);
+ };
+ RecognizerApi.prototype.SUBRULE4 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 4, options);
+ };
+ RecognizerApi.prototype.SUBRULE5 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 5, options);
+ };
+ RecognizerApi.prototype.SUBRULE6 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 6, options);
+ };
+ RecognizerApi.prototype.SUBRULE7 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 7, options);
+ };
+ RecognizerApi.prototype.SUBRULE8 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 8, options);
+ };
+ RecognizerApi.prototype.SUBRULE9 = function (ruleToCall, options) {
+ return this.subruleInternal(ruleToCall, 9, options);
+ };
+ RecognizerApi.prototype.OPTION = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 0);
+ };
+ RecognizerApi.prototype.OPTION1 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 1);
+ };
+ RecognizerApi.prototype.OPTION2 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 2);
+ };
+ RecognizerApi.prototype.OPTION3 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 3);
+ };
+ RecognizerApi.prototype.OPTION4 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 4);
+ };
+ RecognizerApi.prototype.OPTION5 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 5);
+ };
+ RecognizerApi.prototype.OPTION6 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 6);
+ };
+ RecognizerApi.prototype.OPTION7 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 7);
+ };
+ RecognizerApi.prototype.OPTION8 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 8);
+ };
+ RecognizerApi.prototype.OPTION9 = function (actionORMethodDef) {
+ return this.optionInternal(actionORMethodDef, 9);
+ };
+ RecognizerApi.prototype.OR = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 0);
+ };
+ RecognizerApi.prototype.OR1 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 1);
+ };
+ RecognizerApi.prototype.OR2 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 2);
+ };
+ RecognizerApi.prototype.OR3 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 3);
+ };
+ RecognizerApi.prototype.OR4 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 4);
+ };
+ RecognizerApi.prototype.OR5 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 5);
+ };
+ RecognizerApi.prototype.OR6 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 6);
+ };
+ RecognizerApi.prototype.OR7 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 7);
+ };
+ RecognizerApi.prototype.OR8 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 8);
+ };
+ RecognizerApi.prototype.OR9 = function (altsOrOpts) {
+ return this.orInternal(altsOrOpts, 9);
+ };
+ RecognizerApi.prototype.MANY = function (actionORMethodDef) {
+ this.manyInternal(0, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY1 = function (actionORMethodDef) {
+ this.manyInternal(1, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY2 = function (actionORMethodDef) {
+ this.manyInternal(2, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY3 = function (actionORMethodDef) {
+ this.manyInternal(3, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY4 = function (actionORMethodDef) {
+ this.manyInternal(4, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY5 = function (actionORMethodDef) {
+ this.manyInternal(5, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY6 = function (actionORMethodDef) {
+ this.manyInternal(6, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY7 = function (actionORMethodDef) {
+ this.manyInternal(7, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY8 = function (actionORMethodDef) {
+ this.manyInternal(8, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY9 = function (actionORMethodDef) {
+ this.manyInternal(9, actionORMethodDef);
+ };
+ RecognizerApi.prototype.MANY_SEP = function (options) {
+ this.manySepFirstInternal(0, options);
+ };
+ RecognizerApi.prototype.MANY_SEP1 = function (options) {
+ this.manySepFirstInternal(1, options);
+ };
+ RecognizerApi.prototype.MANY_SEP2 = function (options) {
+ this.manySepFirstInternal(2, options);
+ };
+ RecognizerApi.prototype.MANY_SEP3 = function (options) {
+ this.manySepFirstInternal(3, options);
+ };
+ RecognizerApi.prototype.MANY_SEP4 = function (options) {
+ this.manySepFirstInternal(4, options);
+ };
+ RecognizerApi.prototype.MANY_SEP5 = function (options) {
+ this.manySepFirstInternal(5, options);
+ };
+ RecognizerApi.prototype.MANY_SEP6 = function (options) {
+ this.manySepFirstInternal(6, options);
+ };
+ RecognizerApi.prototype.MANY_SEP7 = function (options) {
+ this.manySepFirstInternal(7, options);
+ };
+ RecognizerApi.prototype.MANY_SEP8 = function (options) {
+ this.manySepFirstInternal(8, options);
+ };
+ RecognizerApi.prototype.MANY_SEP9 = function (options) {
+ this.manySepFirstInternal(9, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE = function (actionORMethodDef) {
+ this.atLeastOneInternal(0, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE1 = function (actionORMethodDef) {
+ return this.atLeastOneInternal(1, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE2 = function (actionORMethodDef) {
+ this.atLeastOneInternal(2, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE3 = function (actionORMethodDef) {
+ this.atLeastOneInternal(3, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE4 = function (actionORMethodDef) {
+ this.atLeastOneInternal(4, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE5 = function (actionORMethodDef) {
+ this.atLeastOneInternal(5, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE6 = function (actionORMethodDef) {
+ this.atLeastOneInternal(6, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE7 = function (actionORMethodDef) {
+ this.atLeastOneInternal(7, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE8 = function (actionORMethodDef) {
+ this.atLeastOneInternal(8, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE9 = function (actionORMethodDef) {
+ this.atLeastOneInternal(9, actionORMethodDef);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP = function (options) {
+ this.atLeastOneSepFirstInternal(0, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP1 = function (options) {
+ this.atLeastOneSepFirstInternal(1, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP2 = function (options) {
+ this.atLeastOneSepFirstInternal(2, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP3 = function (options) {
+ this.atLeastOneSepFirstInternal(3, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP4 = function (options) {
+ this.atLeastOneSepFirstInternal(4, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP5 = function (options) {
+ this.atLeastOneSepFirstInternal(5, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP6 = function (options) {
+ this.atLeastOneSepFirstInternal(6, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP7 = function (options) {
+ this.atLeastOneSepFirstInternal(7, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP8 = function (options) {
+ this.atLeastOneSepFirstInternal(8, options);
+ };
+ RecognizerApi.prototype.AT_LEAST_ONE_SEP9 = function (options) {
+ this.atLeastOneSepFirstInternal(9, options);
+ };
+ RecognizerApi.prototype.RULE = function (name, implementation, config) {
+ if (config === void 0) { config = DEFAULT_RULE_CONFIG; }
+ if (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(values(this.gastProductionsCache));
+ };
+ return RecognizerApi;
+}());
+export { RecognizerApi };
+//# sourceMappingURL=recognizer_api.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/parser/traits/recognizer_engine.js b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/recognizer_engine.js
new file mode 100644
index 0000000..d475e9d
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/recognizer_engine.js
@@ -0,0 +1,643 @@
+import { cloneArr, cloneObj, every, flatten, has, isArray, isEmpty, isObject, reduce, uniq, values } from "../../../utils/utils";
+import { AT_LEAST_ONE_IDX, AT_LEAST_ONE_SEP_IDX, BITS_FOR_METHOD_TYPE, BITS_FOR_OCCURRENCE_IDX, MANY_IDX, MANY_SEP_IDX, OPTION_IDX, OR_IDX } from "../../grammar/keys";
+import { isRecognitionException, MismatchedTokenException, NotAllInputParsedException } from "../../exceptions_public";
+import { PROD_TYPE } from "../../grammar/lookahead";
+import { NextTerminalAfterAtLeastOneSepWalker, NextTerminalAfterAtLeastOneWalker, NextTerminalAfterManySepWalker, NextTerminalAfterManyWalker } from "../../grammar/interpreter";
+import { DEFAULT_RULE_CONFIG } from "../parser";
+import { IN_RULE_RECOVERY_EXCEPTION } from "./recoverable";
+import { EOF } from "../../../scan/tokens_public";
+import { augmentTokenTypes, isTokenType, tokenStructuredMatcher, tokenStructuredMatcherNoCategories } from "../../../scan/tokens";
+import { classNameFromInstance } from "../../../lang/lang_extensions";
+/**
+ * This trait is responsible for the runtime parsing engine
+ * Used by the official API (recognizer_api.ts)
+ */
+var RecognizerEngine = /** @class */ (function () {
+ function RecognizerEngine() {
+ }
+ RecognizerEngine.prototype.initRecognizerEngine = function (tokenVocabulary, config) {
+ this.className = 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.allRuleNames = [];
+ this.isBackTrackingStack = [];
+ this.RULE_STACK = [];
+ this.RULE_OCCURRENCE_STACK = [];
+ this.gastProductionsCache = {};
+ if (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 (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 (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 (isArray(tokenVocabulary)) {
+ this.tokensMap = reduce(tokenVocabulary, function (acc, tokType) {
+ acc[tokType.name] = tokType;
+ return acc;
+ }, {});
+ }
+ else if (has(tokenVocabulary, "modes") &&
+ every(flatten(values(tokenVocabulary.modes)), isTokenType)) {
+ var allTokenTypes = flatten(values(tokenVocabulary.modes));
+ var uniqueTokens = uniq(allTokenTypes);
+ this.tokensMap = reduce(uniqueTokens, function (acc, tokType) {
+ acc[tokType.name] = tokType;
+ return acc;
+ }, {});
+ }
+ else if (isObject(tokenVocabulary)) {
+ this.tokensMap = 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 = every(values(tokenVocabulary), function (tokenConstructor) { return 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(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 = has(config, "resyncEnabled")
+ ? config.resyncEnabled
+ : DEFAULT_RULE_CONFIG.resyncEnabled;
+ var recoveryValueFunc = 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);
+ var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, key);
+ try {
+ return this.optionInternalLogic(actionORMethodDef, occurrence, key);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(key, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.optionInternalNoCst = function (actionORMethodDef, occurrence) {
+ var key = this.getKeyForAutomaticLookahead(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);
+ var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, laKey);
+ try {
+ return this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, laKey);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.atLeastOneInternalNoCst = function (prodOccurrence, actionORMethodDef) {
+ var key = this.getKeyForAutomaticLookahead(AT_LEAST_ONE_IDX, prodOccurrence);
+ this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, key);
+ };
+ RecognizerEngine.prototype.atLeastOneInternalLogic = function (prodOccurrence, actionORMethodDef, key) {
+ var _this = this;
+ var lookAheadFunc = this.getLaFuncFromCache(key);
+ var action;
+ var predicate;
+ if (actionORMethodDef.DEF !== undefined) {
+ action = actionORMethodDef.DEF;
+ predicate = actionORMethodDef.GATE;
+ // predicate present
+ if (predicate !== undefined) {
+ var orgLookaheadFunction_2 = lookAheadFunc;
+ lookAheadFunc = function () {
+ return (predicate.call(_this) && orgLookaheadFunction_2.call(_this));
+ };
+ }
+ }
+ else {
+ action = actionORMethodDef;
+ }
+ if (lookAheadFunc.call(this) === true) {
+ var notStuck = this.doSingleRepetition(action);
+ while (lookAheadFunc.call(this) === true &&
+ notStuck === true) {
+ notStuck = this.doSingleRepetition(action);
+ }
+ }
+ else {
+ throw this.raiseEarlyExitException(prodOccurrence, 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, NextTerminalAfterAtLeastOneWalker);
+ };
+ RecognizerEngine.prototype.atLeastOneSepFirstInternal = function (prodOccurrence, options) {
+ var laKey = this.getKeyForAutomaticLookahead(AT_LEAST_ONE_SEP_IDX, prodOccurrence);
+ var nestedName = this.nestedRuleBeforeClause(options, laKey);
+ try {
+ this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.atLeastOneSepFirstInternalNoCst = function (prodOccurrence, options) {
+ var laKey = this.getKeyForAutomaticLookahead(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,
+ NextTerminalAfterAtLeastOneSepWalker
+ ], separatorLookAheadFunc, AT_LEAST_ONE_SEP_IDX, prodOccurrence, 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);
+ var nestedName = this.nestedRuleBeforeClause(actionORMethodDef, laKey);
+ try {
+ return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.manyInternalNoCst = function (prodOccurrence, actionORMethodDef) {
+ var laKey = this.getKeyForAutomaticLookahead(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, 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);
+ var nestedName = this.nestedRuleBeforeClause(options, laKey);
+ try {
+ this.manySepFirstInternalLogic(prodOccurrence, options, laKey);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.manySepFirstInternalNoCst = function (prodOccurrence, options) {
+ var laKey = this.getKeyForAutomaticLookahead(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,
+ NextTerminalAfterManySepWalker
+ ], separatorLookAheadFunc, MANY_SEP_IDX, prodOccurrence, 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.orInternalNoCst = function (altsOrOpts, occurrence) {
+ var alts = isArray(altsOrOpts)
+ ? altsOrOpts
+ : altsOrOpts.DEF;
+ var laKey = this.getKeyForAutomaticLookahead(OR_IDX, occurrence);
+ var laFunc = this.getLaFuncFromCache(laKey);
+ var altIdxToTake = laFunc.call(this, alts);
+ if (altIdxToTake !== undefined) {
+ var chosenAlternative = alts[altIdxToTake];
+ return chosenAlternative.ALT.call(this);
+ }
+ this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG);
+ };
+ RecognizerEngine.prototype.orInternal = function (altsOrOpts, occurrence) {
+ var laKey = this.getKeyForAutomaticLookahead(OR_IDX, occurrence);
+ var nestedName = this.nestedRuleBeforeClause(altsOrOpts, laKey);
+ try {
+ var alts = isArray(altsOrOpts)
+ ? altsOrOpts
+ : altsOrOpts.DEF;
+ var laFunc = this.getLaFuncFromCache(laKey);
+ var altIdxToTake = laFunc.call(this, alts);
+ if (altIdxToTake !== undefined) {
+ var chosenAlternative = alts[altIdxToTake];
+ var nestedAltBeforeClauseResult = this.nestedAltBeforeClause(chosenAlternative, occurrence, OR_IDX, altIdxToTake);
+ try {
+ return chosenAlternative.ALT.call(this);
+ }
+ finally {
+ if (nestedAltBeforeClauseResult !== undefined) {
+ this.nestedRuleFinallyClause(nestedAltBeforeClauseResult.shortName, nestedAltBeforeClauseResult.nestedName);
+ }
+ }
+ }
+ this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG);
+ }
+ finally {
+ if (nestedName !== undefined) {
+ this.nestedRuleFinallyClause(laKey, nestedName);
+ }
+ }
+ };
+ RecognizerEngine.prototype.ruleFinallyStateUpdate = function () {
+ this.RULE_STACK.pop();
+ this.RULE_OCCURRENCE_STACK.pop();
+ // NOOP when cst is disabled
+ this.cstFinallyStateUpdate();
+ if (this.RULE_STACK.length === 0 && this.isAtEndOfInput() === false) {
+ var firstRedundantTok = this.LA(1);
+ var errMsg = this.errorMessageProvider.buildNotAllInputParsedMessage({
+ firstRedundant: firstRedundantTok,
+ ruleName: this.getCurrRuleFullName()
+ });
+ this.SAVE_ERROR(new 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 = cloneArr(this.RULE_STACK);
+ return {
+ errors: savedErrors,
+ lexerState: this.exportLexerState(),
+ RULE_STACK: savedRuleStack,
+ CST_STACK: this.CST_STACK,
+ LAST_EXPLICIT_RULE_STACK: this.LAST_EXPLICIT_RULE_STACK
+ };
+ };
+ RecognizerEngine.prototype.reloadRecogState = function (newState) {
+ this.errors = newState.errors;
+ this.importLexerState(newState.lexerState);
+ this.RULE_STACK = newState.RULE_STACK;
+ };
+ RecognizerEngine.prototype.ruleInvocationStateUpdate = function (shortName, fullName, idxInCallingRule) {
+ this.RULE_OCCURRENCE_STACK.push(idxInCallingRule);
+ this.RULE_STACK.push(shortName);
+ // NOOP when cst is disabled
+ this.cstInvocationStateUpdate(fullName, shortName);
+ };
+ RecognizerEngine.prototype.isBackTracking = function () {
+ return this.isBackTrackingStack.length !== 0;
+ };
+ RecognizerEngine.prototype.getCurrRuleFullName = function () {
+ var shortName = this.getLastExplicitRuleShortName();
+ return this.shortRuleNameToFull[shortName];
+ };
+ RecognizerEngine.prototype.shortRuleNameToFullName = function (shortName) {
+ return this.shortRuleNameToFull[shortName];
+ };
+ RecognizerEngine.prototype.isAtEndOfInput = function () {
+ return this.tokenMatcher(this.LA(1), EOF);
+ };
+ RecognizerEngine.prototype.reset = function () {
+ this.resetLexerState();
+ this.isBackTrackingStack = [];
+ this.errors = [];
+ this.RULE_STACK = [];
+ this.LAST_EXPLICIT_RULE_STACK = [];
+ // TODO: extract a specific rest for TreeBuilder trait
+ this.CST_STACK = [];
+ this.RULE_OCCURRENCE_STACK = [];
+ };
+ return RecognizerEngine;
+}());
+export { RecognizerEngine };
+//# sourceMappingURL=recognizer_engine.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/parser/traits/recoverable.js b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/recoverable.js
new file mode 100644
index 0000000..4af3546
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/recoverable.js
@@ -0,0 +1,305 @@
+import { createTokenInstance, EOF } from "../../../scan/tokens_public";
+import { cloneArr, contains, dropRight, find, flatten, has, isEmpty, map } from "../../../utils/utils";
+import { MismatchedTokenException } from "../../exceptions_public";
+import { IN } from "../../constants";
+import { DEFAULT_PARSER_CONFIG } from "../parser";
+export var EOF_FOLLOW_KEY = {};
+export var IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException";
+export function InRuleRecoveryException(message) {
+ this.name = IN_RULE_RECOVERY_EXCEPTION;
+ this.message = message;
+}
+InRuleRecoveryException.prototype = Error.prototype;
+/**
+ * This trait is responsible for the error recovery and fault tolerant logic
+ */
+var Recoverable = /** @class */ (function () {
+ function Recoverable() {
+ }
+ Recoverable.prototype.initRecoverable = function (config) {
+ this.firstAfterRepMap = {};
+ this.resyncFollows = {};
+ this.recoveryEnabled = 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 = 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 (isEmpty(follows)) {
+ return false;
+ }
+ var mismatchedTok = this.LA(1);
+ var isMisMatchedTokInFollows = 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 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 (contains(allPossibleReSyncTokTypes, nextTokenType)) {
+ return nextTokenType;
+ }
+ nextToken = this.LA(k);
+ k++;
+ }
+ };
+ Recoverable.prototype.getCurrFollowKey = function () {
+ // the length is at least one as we always add the ruleName to the stack before invoking the rule.
+ if (this.RULE_STACK.length === 1) {
+ return EOF_FOLLOW_KEY;
+ }
+ var currRuleShortName = this.getLastExplicitRuleShortName();
+ var currRuleIdx = this.getLastExplicitRuleOccurrenceIndex();
+ var prevRuleShortName = this.getPreviousExplicitRuleShortName();
+ return {
+ ruleName: this.shortRuleNameToFullName(currRuleShortName),
+ idxInCallingRule: currRuleIdx,
+ inRule: this.shortRuleNameToFullName(prevRuleShortName)
+ };
+ };
+ Recoverable.prototype.buildFullFollowKeyStack = function () {
+ var _this = this;
+ var explicitRuleStack = this.RULE_STACK;
+ var explicitOccurrenceStack = this.RULE_OCCURRENCE_STACK;
+ if (!isEmpty(this.LAST_EXPLICIT_RULE_STACK)) {
+ explicitRuleStack = map(this.LAST_EXPLICIT_RULE_STACK, function (idx) { return _this.RULE_STACK[idx]; });
+ explicitOccurrenceStack = map(this.LAST_EXPLICIT_RULE_STACK, function (idx) { return _this.RULE_OCCURRENCE_STACK[idx]; });
+ }
+ // TODO: only iterate over explicit rules here
+ return 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 = map(this.buildFullFollowKeyStack(), function (currKey) {
+ return _this.getFollowSetFromFollowKey(currKey);
+ });
+ return 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 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 = cloneArr(this.RULE_OCCURRENCE_STACK);
+ var grammarPath = {
+ ruleStack: pathRuleStack,
+ occurrenceStack: pathOccurrenceStack,
+ lastTok: tokType,
+ lastTokOccurrence: tokIdxInRule
+ };
+ return grammarPath;
+ };
+ Recoverable.prototype.getHumanReadableRuleStack = function () {
+ var _this = this;
+ if (!isEmpty(this.LAST_EXPLICIT_RULE_STACK)) {
+ return map(this.LAST_EXPLICIT_RULE_STACK, function (currIdx) {
+ return _this.shortRuleNameToFullName(_this.RULE_STACK[currIdx]);
+ });
+ }
+ else {
+ return map(this.RULE_STACK, function (currShortName) {
+ return _this.shortRuleNameToFullName(currShortName);
+ });
+ }
+ };
+ return Recoverable;
+}());
+export { Recoverable };
+export 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
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/parse/parser/traits/tree_builder.js b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/tree_builder.js
new file mode 100644
index 0000000..fd76b69
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/parse/parser/traits/tree_builder.js
@@ -0,0 +1,288 @@
+import { addNoneTerminalToCst, addTerminalToCst, setNodeLocationFull, setNodeLocationOnlyOffset } from "../../cst/cst";
+import { has, isUndefined, NOOP } from "../../../utils/utils";
+import { createBaseSemanticVisitorConstructor, createBaseVisitorConstructorWithDefaults } from "../../cst/cst_visitor";
+import { getKeyForAltIndex } from "../../grammar/keys";
+import { DEFAULT_PARSER_CONFIG } from "../parser";
+/**
+ * This trait is responsible for the CST building logic.
+ */
+var TreeBuilder = /** @class */ (function () {
+ function TreeBuilder() {
+ }
+ TreeBuilder.prototype.initTreeBuilder = function (config) {
+ this.LAST_EXPLICIT_RULE_STACK = [];
+ this.CST_STACK = [];
+ this.outputCst = has(config, "outputCst")
+ ? config.outputCst
+ : DEFAULT_PARSER_CONFIG.outputCst;
+ this.nodeLocationTracking = has(config, "nodeLocationTracking")
+ ? config.nodeLocationTracking
+ : DEFAULT_PARSER_CONFIG.nodeLocationTracking;
+ if (!this.outputCst) {
+ this.cstInvocationStateUpdate = NOOP;
+ this.cstFinallyStateUpdate = NOOP;
+ this.cstPostTerminal = NOOP;
+ this.cstPostNonTerminal = NOOP;
+ this.cstPostRule = NOOP;
+ this.getLastExplicitRuleShortName = this.getLastExplicitRuleShortNameNoCst;
+ this.getPreviousExplicitRuleShortName = this.getPreviousExplicitRuleShortNameNoCst;
+ this.getLastExplicitRuleOccurrenceIndex = this.getLastExplicitRuleOccurrenceIndexNoCst;
+ this.manyInternal = this.manyInternalNoCst;
+ this.orInternal = this.orInternalNoCst;
+ this.optionInternal = this.optionInternalNoCst;
+ this.atLeastOneInternal = this.atLeastOneInternalNoCst;
+ this.manySepFirstInternal = this.manySepFirstInternalNoCst;
+ this.atLeastOneSepFirstInternal = this.atLeastOneSepFirstInternalNoCst;
+ }
+ else {
+ if (/full/i.test(this.nodeLocationTracking)) {
+ if (this.recoveryEnabled) {
+ this.setNodeLocationFromToken = setNodeLocationFull;
+ this.setNodeLocationFromNode = setNodeLocationFull;
+ this.cstPostRule = NOOP;
+ this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery;
+ }
+ else {
+ this.setNodeLocationFromToken = NOOP;
+ this.setNodeLocationFromNode = 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 = NOOP;
+ this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery;
+ }
+ else {
+ this.setNodeLocationFromToken = NOOP;
+ this.setNodeLocationFromNode = NOOP;
+ this.cstPostRule = this.cstPostRuleOnlyOffset;
+ this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular;
+ }
+ }
+ else if (/none/i.test(this.nodeLocationTracking)) {
+ this.setNodeLocationFromToken = NOOP;
+ this.setNodeLocationFromNode = NOOP;
+ this.cstPostRule = NOOP;
+ this.setInitialNodeLocation = 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
+ };
+ };
+ // CST
+ TreeBuilder.prototype.cstNestedInvocationStateUpdate = function (nestedName, shortName) {
+ var cstNode = {
+ name: nestedName,
+ fullName: this.shortRuleNameToFull[this.getLastExplicitRuleShortName()] +
+ nestedName,
+ children: {}
+ };
+ this.setInitialNodeLocation(cstNode);
+ this.CST_STACK.push(cstNode);
+ };
+ TreeBuilder.prototype.cstInvocationStateUpdate = function (fullRuleName, shortName) {
+ this.LAST_EXPLICIT_RULE_STACK.push(this.RULE_STACK.length - 1);
+ var cstNode = {
+ name: fullRuleName,
+ children: {}
+ };
+ this.setInitialNodeLocation(cstNode);
+ this.CST_STACK.push(cstNode);
+ };
+ TreeBuilder.prototype.cstFinallyStateUpdate = function () {
+ this.LAST_EXPLICIT_RULE_STACK.pop();
+ this.CST_STACK.pop();
+ };
+ TreeBuilder.prototype.cstNestedFinallyStateUpdate = function () {
+ var lastCstNode = this.CST_STACK.pop();
+ // TODO: the naming is bad, this should go directly to the
+ // (correct) cstLocation update method
+ // e.g if we put other logic in postRule...
+ this.cstPostRule(lastCstNode);
+ };
+ TreeBuilder.prototype.cstPostRuleFull = function (ruleCstNode) {
+ var prevToken = this.LA(0);
+ var loc = ruleCstNode.location;
+ // If this condition is true it means we consumed at least one Token
+ // In this CstNode or its nested children.
+ if (loc.startOffset <= prevToken.startOffset === true) {
+ loc.endOffset = prevToken.endOffset;
+ loc.endLine = prevToken.endLine;
+ loc.endColumn = prevToken.endColumn;
+ }
+ // "empty" CstNode edge case
+ else {
+ loc.startOffset = NaN;
+ loc.startLine = NaN;
+ loc.startColumn = NaN;
+ }
+ };
+ TreeBuilder.prototype.cstPostRuleOnlyOffset = function (ruleCstNode) {
+ var prevToken = this.LA(0);
+ var loc = ruleCstNode.location;
+ // If this condition is true it means we consumed at least one Token
+ // In this CstNode or its nested children.
+ if (loc.startOffset <= prevToken.startOffset === true) {
+ loc.endOffset = prevToken.endOffset;
+ }
+ // "empty" CstNode edge case
+ else {
+ loc.startOffset = NaN;
+ }
+ };
+ TreeBuilder.prototype.cstPostTerminal = function (key, consumedToken) {
+ var rootCst = this.CST_STACK[this.CST_STACK.length - 1];
+ addTerminalToCst(rootCst, consumedToken, key);
+ // This is only used when **both** error recovery and CST Output are enabled.
+ this.setNodeLocationFromToken(rootCst.location, consumedToken);
+ };
+ TreeBuilder.prototype.cstPostNonTerminal = function (ruleCstResult, ruleName) {
+ // Avoid side effects due to back tracking
+ // TODO: This costs a 2-3% in performance, A flag on IParserConfig
+ // could be used to get rid of this conditional, but not sure its worth the effort
+ // and API complexity.
+ if (this.isBackTracking() !== true) {
+ var preCstNode = this.CST_STACK[this.CST_STACK.length - 1];
+ 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 (isUndefined(this.baseCstVisitorConstructor)) {
+ var newBaseCstVisitorConstructor = createBaseSemanticVisitorConstructor(this.className, this.allRuleNames);
+ this.baseCstVisitorConstructor = newBaseCstVisitorConstructor;
+ return newBaseCstVisitorConstructor;
+ }
+ return this.baseCstVisitorConstructor;
+ };
+ TreeBuilder.prototype.getBaseCstVisitorConstructorWithDefaults = function () {
+ if (isUndefined(this.baseCstVisitorWithDefaultsConstructor)) {
+ var newConstructor = createBaseVisitorConstructorWithDefaults(this.className, this.allRuleNames, this.getBaseCstVisitorConstructor());
+ this.baseCstVisitorWithDefaultsConstructor = newConstructor;
+ return newConstructor;
+ }
+ return this.baseCstVisitorWithDefaultsConstructor;
+ };
+ TreeBuilder.prototype.nestedRuleBeforeClause = function (methodOpts, laKey) {
+ var nestedName;
+ if (methodOpts.NAME !== undefined) {
+ nestedName = methodOpts.NAME;
+ this.nestedRuleInvocationStateUpdate(nestedName, laKey);
+ return nestedName;
+ }
+ else {
+ return undefined;
+ }
+ };
+ TreeBuilder.prototype.nestedAltBeforeClause = function (methodOpts, occurrence, methodKeyIdx, altIdx) {
+ var ruleIdx = this.getLastExplicitRuleShortName();
+ var shortName = getKeyForAltIndex(ruleIdx, methodKeyIdx, occurrence, altIdx);
+ var nestedName;
+ if (methodOpts.NAME !== undefined) {
+ nestedName = methodOpts.NAME;
+ this.nestedRuleInvocationStateUpdate(nestedName, shortName);
+ return {
+ shortName: shortName,
+ nestedName: nestedName
+ };
+ }
+ else {
+ return undefined;
+ }
+ };
+ TreeBuilder.prototype.nestedRuleFinallyClause = function (laKey, nestedName) {
+ var cstStack = this.CST_STACK;
+ var nestedRuleCst = cstStack[cstStack.length - 1];
+ this.nestedRuleFinallyStateUpdate();
+ // this return a different result than the previous invocation because "nestedRuleFinallyStateUpdate" pops the cst stack
+ var parentCstNode = cstStack[cstStack.length - 1];
+ addNoneTerminalToCst(parentCstNode, nestedName, nestedRuleCst);
+ this.setNodeLocationFromNode(parentCstNode.location, nestedRuleCst.location);
+ };
+ TreeBuilder.prototype.getLastExplicitRuleShortName = function () {
+ var lastExplictIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 1];
+ return this.RULE_STACK[lastExplictIndex];
+ };
+ TreeBuilder.prototype.getLastExplicitRuleShortNameNoCst = function () {
+ var ruleStack = this.RULE_STACK;
+ return ruleStack[ruleStack.length - 1];
+ };
+ TreeBuilder.prototype.getPreviousExplicitRuleShortName = function () {
+ var lastExplicitIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 2];
+ return this.RULE_STACK[lastExplicitIndex];
+ };
+ TreeBuilder.prototype.getPreviousExplicitRuleShortNameNoCst = function () {
+ var ruleStack = this.RULE_STACK;
+ return ruleStack[ruleStack.length - 2];
+ };
+ TreeBuilder.prototype.getLastExplicitRuleOccurrenceIndex = function () {
+ var lastExplicitIndex = this.LAST_EXPLICIT_RULE_STACK[this.LAST_EXPLICIT_RULE_STACK.length - 1];
+ return this.RULE_OCCURRENCE_STACK[lastExplicitIndex];
+ };
+ TreeBuilder.prototype.getLastExplicitRuleOccurrenceIndexNoCst = function () {
+ var occurrenceStack = this.RULE_OCCURRENCE_STACK;
+ return occurrenceStack[occurrenceStack.length - 1];
+ };
+ TreeBuilder.prototype.nestedRuleInvocationStateUpdate = function (nestedRuleName, shortNameKey) {
+ this.RULE_OCCURRENCE_STACK.push(1);
+ this.RULE_STACK.push(shortNameKey);
+ this.cstNestedInvocationStateUpdate(nestedRuleName, shortNameKey);
+ };
+ TreeBuilder.prototype.nestedRuleFinallyStateUpdate = function () {
+ this.RULE_STACK.pop();
+ this.RULE_OCCURRENCE_STACK.pop();
+ // NOOP when cst is disabled
+ this.cstNestedFinallyStateUpdate();
+ };
+ return TreeBuilder;
+}());
+export { TreeBuilder };
+//# sourceMappingURL=tree_builder.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/scan/lexer.js b/node_modules/chevrotain/lib_esm/src/scan/lexer.js
new file mode 100644
index 0000000..9cf651a
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/scan/lexer.js
@@ -0,0 +1,885 @@
+var __extends = (this && this.__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 __());
+ };
+})();
+import { BaseRegExpVisitor } from "regexp-to-ast";
+import { Lexer, LexerDefinitionErrorType } from "./lexer_public";
+import { compact, contains, defaults, difference, filter, find, first, flatten, forEach, has, indexOf, isArray, isEmpty, isFunction, isRegExp, isString, isUndefined, keys, map, mapValues, packArray, PRINT_ERROR, reduce, reject } from "../utils/utils";
+import { canMatchCharCode, failedOptimizationPrefixMsg, getOptimizedStartCodesIndices } from "./reg_exp";
+import { getRegExpAst } from "./reg_exp_parser";
+var PATTERN = "PATTERN";
+export var DEFAULT_MODE = "defaultMode";
+export var MODES = "modes";
+export var SUPPORT_STICKY = typeof new RegExp("(?:)").sticky === "boolean";
+export function disableSticky() {
+ SUPPORT_STICKY = false;
+}
+export function enableSticky() {
+ SUPPORT_STICKY = true;
+}
+export function analyzeTokenTypes(tokenTypes, options) {
+ options = 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 = reject(tokenTypes, function (currType) {
+ return currType[PATTERN] === Lexer.NA;
+ });
+ });
+ var hasCustom = false;
+ var allTransformedPatterns;
+ tracer("Transform Patterns", function () {
+ hasCustom = false;
+ allTransformedPatterns = map(onlyRelevantTypes, function (currType) {
+ var currPattern = currType[PATTERN];
+ /* istanbul ignore else */
+ if (isRegExp(currPattern)) {
+ var regExpSource = currPattern.source;
+ if (regExpSource.length === 1 &&
+ // only these regExp meta characters which can appear in a length one regExp
+ regExpSource !== "^" &&
+ regExpSource !== "$" &&
+ regExpSource !== ".") {
+ return regExpSource;
+ }
+ else if (regExpSource.length === 2 &&
+ regExpSource[0] === "\\" &&
+ // not a meta character
+ !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 (isFunction(currPattern)) {
+ hasCustom = true;
+ // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object
+ return { exec: currPattern };
+ }
+ else if (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 = map(onlyRelevantTypes, function (currType) { return currType.tokenTypeIdx; });
+ patternIdxToGroup = map(onlyRelevantTypes, function (clazz) {
+ var groupName = clazz.GROUP;
+ /* istanbul ignore next */
+ if (groupName === Lexer.SKIPPED) {
+ return undefined;
+ }
+ else if (isString(groupName)) {
+ return groupName;
+ }
+ else if (isUndefined(groupName)) {
+ return false;
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ });
+ patternIdxToLongerAltIdx = map(onlyRelevantTypes, function (clazz) {
+ var longerAltType = clazz.LONGER_ALT;
+ if (longerAltType) {
+ var longerAltIdx = indexOf(onlyRelevantTypes, longerAltType);
+ return longerAltIdx;
+ }
+ });
+ patternIdxToPushMode = map(onlyRelevantTypes, function (clazz) { return clazz.PUSH_MODE; });
+ patternIdxToPopMode = map(onlyRelevantTypes, function (clazz) {
+ return has(clazz, "POP_MODE");
+ });
+ });
+ var patternIdxToCanLineTerminator;
+ tracer("Line Terminator Handling", function () {
+ var lineTerminatorCharCodes = getCharCodes(options.lineTerminatorCharacters);
+ patternIdxToCanLineTerminator = map(onlyRelevantTypes, function (tokType) { return false; });
+ if (options.positionTracking !== "onlyOffset") {
+ patternIdxToCanLineTerminator = map(onlyRelevantTypes, function (tokType) {
+ if (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 = map(onlyRelevantTypes, isCustomPattern);
+ patternIdxToShort = map(allTransformedPatterns, isShortPattern);
+ emptyGroups = reduce(onlyRelevantTypes, function (acc, clazz) {
+ var groupName = clazz.GROUP;
+ if (isString(groupName) && !(groupName === Lexer.SKIPPED)) {
+ acc[groupName] = [];
+ }
+ return acc;
+ }, {});
+ patternIdxToConfig = 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 = 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 (isArray(currTokType.START_CHARS_HINT)) {
+ var lastOptimizedIdx_1;
+ forEach(currTokType.START_CHARS_HINT, function (charOrInt) {
+ var charCode = typeof charOrInt === "string"
+ ? charOrInt.charCodeAt(0)
+ : charOrInt;
+ var currOptimizedIdx = charCodeToOptimizedIndex(charCode);
+ // Avoid adding the config multiple times
+ if (lastOptimizedIdx_1 !== currOptimizedIdx) {
+ lastOptimizedIdx_1 = currOptimizedIdx;
+ addToMapOfArrays(result, currOptimizedIdx, patternIdxToConfig[idx]);
+ }
+ });
+ }
+ else if (isRegExp(currTokType.PATTERN)) {
+ if (currTokType.PATTERN.unicode) {
+ canBeOptimized = false;
+ if (options.ensureOptimizations) {
+ 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 (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;
+ }
+ forEach(optimizedCodes, function (code) {
+ addToMapOfArrays(result, code, patternIdxToConfig[idx]);
+ });
+ }
+ }
+ else {
+ if (options.ensureOptimizations) {
+ 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 = packArray(charCodeToPatternIdxToConfig);
+ });
+ return {
+ emptyGroups: emptyGroups,
+ patternIdxToConfig: patternIdxToConfig,
+ charCodeToPatternIdxToConfig: charCodeToPatternIdxToConfig,
+ hasCustom: hasCustom,
+ canBeOptimized: canBeOptimized
+ };
+}
+export 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 = filter(tokenTypes, function (currTokType) {
+ return 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;
+}
+export function findMissingPatterns(tokenTypes) {
+ var tokenTypesWithMissingPattern = filter(tokenTypes, function (currType) {
+ return !has(currType, PATTERN);
+ });
+ var errors = map(tokenTypesWithMissingPattern, function (currType) {
+ return {
+ message: "Token Type: ->" +
+ currType.name +
+ "<- missing static 'PATTERN' property",
+ type: LexerDefinitionErrorType.MISSING_PATTERN,
+ tokenTypes: [currType]
+ };
+ });
+ var valid = difference(tokenTypes, tokenTypesWithMissingPattern);
+ return { errors: errors, valid: valid };
+}
+export function findInvalidPatterns(tokenTypes) {
+ var tokenTypesWithInvalidPattern = filter(tokenTypes, function (currType) {
+ var pattern = currType[PATTERN];
+ return (!isRegExp(pattern) &&
+ !isFunction(pattern) &&
+ !has(pattern, "exec") &&
+ !isString(pattern));
+ });
+ var errors = 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 = difference(tokenTypes, tokenTypesWithInvalidPattern);
+ return { errors: errors, valid: valid };
+}
+var end_of_input = /[^\\][\$]/;
+export function findEndOfInputAnchor(tokenTypes) {
+ var EndAnchorFinder = /** @class */ (function (_super) {
+ __extends(EndAnchorFinder, _super);
+ function EndAnchorFinder() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.found = false;
+ return _this;
+ }
+ EndAnchorFinder.prototype.visitEndAnchor = function (node) {
+ this.found = true;
+ };
+ return EndAnchorFinder;
+ }(BaseRegExpVisitor));
+ var invalidRegex = 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 = 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;
+}
+export function findEmptyMatchRegExps(tokenTypes) {
+ var matchesEmptyString = filter(tokenTypes, function (currType) {
+ var pattern = currType[PATTERN];
+ return pattern.test("");
+ });
+ var errors = 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 = /[^\\[][\^]|^\^/;
+export function findStartOfInputAnchor(tokenTypes) {
+ var StartAnchorFinder = /** @class */ (function (_super) {
+ __extends(StartAnchorFinder, _super);
+ function StartAnchorFinder() {
+ var _this = _super !== null && _super.apply(this, arguments) || this;
+ _this.found = false;
+ return _this;
+ }
+ StartAnchorFinder.prototype.visitStartAnchor = function (node) {
+ this.found = true;
+ };
+ return StartAnchorFinder;
+ }(BaseRegExpVisitor));
+ var invalidRegex = 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 = 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;
+}
+export function findUnsupportedFlags(tokenTypes) {
+ var invalidFlags = filter(tokenTypes, function (currType) {
+ var pattern = currType[PATTERN];
+ return (pattern instanceof RegExp && (pattern.multiline || pattern.global));
+ });
+ var errors = 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.
+export function findDuplicatePatterns(tokenTypes) {
+ var found = [];
+ var identicalPatterns = map(tokenTypes, function (outerType) {
+ return reduce(tokenTypes, function (result, innerType) {
+ if (outerType.PATTERN.source === innerType.PATTERN.source &&
+ !contains(found, innerType) &&
+ innerType.PATTERN !== 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 = compact(identicalPatterns);
+ var duplicatePatterns = filter(identicalPatterns, function (currIdenticalSet) {
+ return currIdenticalSet.length > 1;
+ });
+ var errors = map(duplicatePatterns, function (setOfIdentical) {
+ var tokenTypeNames = map(setOfIdentical, function (currType) {
+ return currType.name;
+ });
+ var dupPatternSrc = 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;
+}
+export function findInvalidGroupType(tokenTypes) {
+ var invalidTypes = filter(tokenTypes, function (clazz) {
+ if (!has(clazz, "GROUP")) {
+ return false;
+ }
+ var group = clazz.GROUP;
+ return group !== Lexer.SKIPPED && group !== Lexer.NA && !isString(group);
+ });
+ var errors = 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;
+}
+export function findModesThatDoNotExist(tokenTypes, validModes) {
+ var invalidModes = filter(tokenTypes, function (clazz) {
+ return (clazz.PUSH_MODE !== undefined &&
+ !contains(validModes, clazz.PUSH_MODE));
+ });
+ var errors = 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;
+}
+export function findUnreachablePatterns(tokenTypes) {
+ var errors = [];
+ var canBeTested = reduce(tokenTypes, function (result, tokType, idx) {
+ var pattern = tokType.PATTERN;
+ if (pattern === Lexer.NA) {
+ return result;
+ }
+ // a more comprehensive validation for all forms of regExps would require
+ // deeper regExp analysis capabilities
+ if (isString(pattern)) {
+ result.push({ str: pattern, idx: idx, tokenType: tokType });
+ }
+ else if (isRegExp(pattern) && noMetaChar(pattern)) {
+ result.push({ str: pattern.source, idx: idx, tokenType: tokType });
+ }
+ return result;
+ }, []);
+ forEach(tokenTypes, function (tokType, testIdx) {
+ 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 (isRegExp(pattern)) {
+ var regExpArray = pattern.exec(str);
+ return regExpArray !== null && regExpArray.index === 0;
+ }
+ else if (isFunction(pattern)) {
+ // maintain the API of custom patterns
+ return pattern(str, 0, [], {});
+ }
+ else if (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 (find(metaChars, function (char) { return regExp.source.indexOf(char) !== -1; }) ===
+ undefined);
+}
+export 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);
+}
+export 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);
+}
+export function performRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) {
+ var errors = [];
+ // some run time checks to help the end users.
+ if (!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 (!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 (has(lexerDefinition, MODES) &&
+ has(lexerDefinition, DEFAULT_MODE) &&
+ !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 (has(lexerDefinition, MODES)) {
+ forEach(lexerDefinition.modes, function (currModeValue, currModeName) {
+ forEach(currModeValue, function (currTokType, currIdx) {
+ if (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;
+}
+export function performWarningRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) {
+ var warnings = [];
+ var hasAnyLineBreak = false;
+ var allTokenTypes = compact(flatten(mapValues(lexerDefinition.modes, function (tokTypes) { return tokTypes; })));
+ var concreteTokenTypes = reject(allTokenTypes, function (currType) { return currType[PATTERN] === Lexer.NA; });
+ var terminatorCharCodes = getCharCodes(lineTerminatorCharacters);
+ if (trackLines) {
+ 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 (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;
+}
+export function cloneEmptyGroups(emptyGroups) {
+ var clonedResult = {};
+ var groupKeys = keys(emptyGroups);
+ forEach(groupKeys, function (currKey) {
+ var currGroupValue = emptyGroups[currKey];
+ /* istanbul ignore else */
+ if (isArray(currGroupValue)) {
+ clonedResult[currKey] = [];
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+ });
+ return clonedResult;
+}
+// TODO: refactor to avoid duplication
+export function isCustomPattern(tokenType) {
+ var pattern = tokenType.PATTERN;
+ /* istanbul ignore else */
+ if (isRegExp(pattern)) {
+ return false;
+ }
+ else if (isFunction(pattern)) {
+ // CustomPatternMatcherFunc - custom patterns do not require any transformations, only wrapping in a RegExp Like object
+ return true;
+ }
+ else if (has(pattern, "exec")) {
+ // ICustomPattern
+ return true;
+ }
+ else if (isString(pattern)) {
+ return false;
+ }
+ else {
+ throw Error("non exhaustive match");
+ }
+}
+export function isShortPattern(pattern) {
+ if (isString(pattern) && pattern.length === 1) {
+ return pattern.charCodeAt(0);
+ }
+ else {
+ return false;
+ }
+}
+/**
+ * Faster than using a RegExp for default newline detection during lexing.
+ */
+export 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 (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 (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 (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");
+ }
+ }
+}
+export 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 = map(charsOrCodes, function (numOrString) {
+ if (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);
+ }
+}
+export 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
+ */
+export 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 (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
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/scan/lexer_errors_public.js b/node_modules/chevrotain/lib_esm/src/scan/lexer_errors_public.js
new file mode 100644
index 0000000..ae9d6c4
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/scan/lexer_errors_public.js
@@ -0,0 +1,9 @@
+export var defaultLexerErrorProvider = {
+ buildUnableToPopLexerModeMessage: function (token) {
+ return "Unable to pop Lexer Mode after encountering Token ->" + token.image + "<- The Mode Stack is empty";
+ },
+ buildUnexpectedCharactersMessage: function (fullText, startOffset, length, line, column) {
+ return ("unexpected character: ->" + fullText.charAt(startOffset) + "<- at offset: " + startOffset + "," + (" skipped " + length + " characters."));
+ }
+};
+//# sourceMappingURL=lexer_errors_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/scan/lexer_public.js b/node_modules/chevrotain/lib_esm/src/scan/lexer_public.js
new file mode 100644
index 0000000..9090413
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/scan/lexer_public.js
@@ -0,0 +1,672 @@
+import { analyzeTokenTypes, charCodeToOptimizedIndex, cloneEmptyGroups, DEFAULT_MODE, LineTerminatorOptimizedTester, performRuntimeChecks, performWarningRuntimeChecks, SUPPORT_STICKY, validatePatterns } from "./lexer";
+import { cloneArr, cloneObj, forEach, IDENTITY, isArray, isEmpty, isUndefined, keys, last, map, merge, NOOP, PRINT_WARNING, reduce, reject, timer, toFastProperties } from "../utils/utils";
+import { augmentTokenTypes } from "./tokens";
+import { defaultLexerErrorProvider } from "../scan/lexer_errors_public";
+import { clearRegExpParserCache } from "./reg_exp_parser";
+export 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 = /** @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 = 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 (isArray(lexerDefinition)) {
+ actualDefinition = { modes: {} };
+ actualDefinition.modes[DEFAULT_MODE] = cloneArr(lexerDefinition);
+ actualDefinition[DEFAULT_MODE] = DEFAULT_MODE;
+ }
+ else {
+ // no conversion needed, input should already be a IMultiModeLexerDefinition
+ hasOnlySingleMode = false;
+ actualDefinition = 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.
+ forEach(actualDefinition.modes, function (currModeValue, currModeName) {
+ actualDefinition.modes[currModeName] = reject(currModeValue, function (currTokType) { return isUndefined(currTokType); });
+ });
+ var allModeNames = keys(actualDefinition.modes);
+ 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 (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 = merge(_this.emptyGroups, currAnalyzeResult_1.emptyGroups);
+ _this.hasCustom =
+ currAnalyzeResult_1.hasCustom || _this.hasCustom;
+ _this.canModeBeOptimized[currModName] =
+ currAnalyzeResult_1.canBeOptimized;
+ }
+ });
+ });
+ _this.defaultMode = actualDefinition.defaultMode;
+ if (!isEmpty(_this.lexerDefinitionErrors) &&
+ !_this.config.deferDefinitionErrorsHandling) {
+ var allErrMessages = 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
+ forEach(_this.lexerDefinitionWarning, function (warningDescriptor) {
+ 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 = IDENTITY;
+ _this.match = _this.matchWithTest;
+ }
+ else {
+ _this.updateLastIndex = NOOP;
+ _this.match = _this.matchWithExec;
+ }
+ if (hasOnlySingleMode) {
+ _this.handleModes = NOOP;
+ }
+ if (_this.trackStartLines === false) {
+ _this.computeNewColumn = IDENTITY;
+ }
+ if (_this.trackEndLines === false) {
+ _this.updateTokenEndLineColumnLocation = 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 = reduce(_this.canModeBeOptimized, function (cannotBeOptimized, canBeOptimized, modeName) {
+ if (canBeOptimized === false) {
+ cannotBeOptimized.push(modeName);
+ }
+ return cannotBeOptimized;
+ }, []);
+ if (config.ensureOptimizations && !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 () {
+ toFastProperties(_this);
+ });
+ });
+ }
+ Lexer.prototype.tokenize = function (text, initialMode) {
+ if (initialMode === void 0) { initialMode = this.defaultMode; }
+ if (!isEmpty(this.lexerDefinitionErrors)) {
+ var allErrMessages = 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 = 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 = 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;
+}());
+export { Lexer };
+//# sourceMappingURL=lexer_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/scan/reg_exp.js b/node_modules/chevrotain/lib_esm/src/scan/reg_exp.js
new file mode 100644
index 0000000..e4a062a
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/scan/reg_exp.js
@@ -0,0 +1,260 @@
+var __extends = (this && this.__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 __());
+ };
+})();
+import { VERSION, BaseRegExpVisitor } from "regexp-to-ast";
+import { forEach, contains, PRINT_ERROR, PRINT_WARNING, find, isArray, every, values } from "../utils/utils";
+import { getRegExpAst } from "./reg_exp_parser";
+import { charCodeToOptimizedIndex, minOptimizationVal } from "./lexer";
+var complementErrorMessage = "Complement Sets are not supported for first char optimization";
+export var failedOptimizationPrefixMsg = 'Unable to use "first char" lexer optimizations:\n';
+export 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) {
+ 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.";
+ }
+ PRINT_ERROR(failedOptimizationPrefixMsg + "\n" +
+ ("\tFailed parsing: < " + regExp.toString() + " >\n") +
+ ("\tUsing the regexp-to-ast library version: " + VERSION + "\n") +
+ "\tPlease open an issue at: https://github.com/bd82/regexp-to-ast/issues" +
+ msgSuffix);
+ }
+ }
+ return [];
+}
+export 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);
+ }
+ 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 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 find(setNode.value, function (codeOrRange) {
+ if (typeof codeOrRange === "number") {
+ return contains(targetCharCodes, codeOrRange);
+ }
+ else {
+ // range
+ var range_1 = codeOrRange;
+ return (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 isArray(ast.value)
+ ? every(ast.value, isWholeOptional)
+ : isWholeOptional(ast.value);
+}
+var CharCodeFinder = /** @class */ (function (_super) {
+ __extends(CharCodeFinder, _super);
+ function CharCodeFinder(targetCharCodes) {
+ var _this = _super.call(this) || this;
+ _this.targetCharCodes = targetCharCodes;
+ _this.found = false;
+ return _this;
+ }
+ CharCodeFinder.prototype.visitChildren = function (node) {
+ // No need to keep looking...
+ if (this.found === true) {
+ return;
+ }
+ // switch lookaheads as they do not actually consume any characters thus
+ // finding a charCode at lookahead context does not mean that regexp can actually contain it in a match.
+ switch (node.type) {
+ case "Lookahead":
+ this.visitLookahead(node);
+ return;
+ case "NegativeLookahead":
+ this.visitNegativeLookahead(node);
+ return;
+ }
+ _super.prototype.visitChildren.call(this, node);
+ };
+ CharCodeFinder.prototype.visitCharacter = function (node) {
+ if (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;
+}(BaseRegExpVisitor));
+export function canMatchCharCode(charCodes, pattern) {
+ if (pattern instanceof RegExp) {
+ var ast = getRegExpAst(pattern);
+ var charCodeFinder = new CharCodeFinder(charCodes);
+ charCodeFinder.visit(ast);
+ return charCodeFinder.found;
+ }
+ else {
+ return (find(pattern, function (char) {
+ return contains(charCodes, char.charCodeAt(0));
+ }) !== undefined);
+ }
+}
+//# sourceMappingURL=reg_exp.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/scan/reg_exp_parser.js b/node_modules/chevrotain/lib_esm/src/scan/reg_exp_parser.js
new file mode 100644
index 0000000..455eb59
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/scan/reg_exp_parser.js
@@ -0,0 +1,18 @@
+import { RegExpParser } from "regexp-to-ast";
+var regExpAstCache = {};
+var regExpParser = new RegExpParser();
+export 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;
+ }
+}
+export function clearRegExpParserCache() {
+ regExpAstCache = {};
+}
+//# sourceMappingURL=reg_exp_parser.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/scan/tokens.js b/node_modules/chevrotain/lib_esm/src/scan/tokens.js
new file mode 100644
index 0000000..d5a9d6c
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/scan/tokens.js
@@ -0,0 +1,114 @@
+import { cloneArr, compact, contains, difference, flatten, forEach, has, isArray, isEmpty, map } from "../utils/utils";
+export 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
+export function tokenStructuredMatcherNoCategories(token, tokType) {
+ return token.tokenTypeIdx === tokType.tokenTypeIdx;
+}
+export var tokenShortNameIdx = 1;
+export var tokenIdxToClass = {};
+export 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);
+ forEach(tokenTypesAndParents, function (tokType) {
+ tokType.isParent = tokType.categoryMatches.length > 0;
+ });
+}
+export function expandCategories(tokenTypes) {
+ var result = cloneArr(tokenTypes);
+ var categories = tokenTypes;
+ var searching = true;
+ while (searching) {
+ categories = compact(flatten(map(categories, function (currTokType) { return currTokType.CATEGORIES; })));
+ var newCategories = difference(categories, result);
+ result = result.concat(newCategories);
+ if (isEmpty(newCategories)) {
+ searching = false;
+ }
+ else {
+ categories = newCategories;
+ }
+ }
+ return result;
+}
+export function assignTokenDefaultProps(tokenTypes) {
+ forEach(tokenTypes, function (currTokType) {
+ if (!hasShortKeyProperty(currTokType)) {
+ tokenIdxToClass[tokenShortNameIdx] = currTokType;
+ currTokType.tokenTypeIdx = tokenShortNameIdx++;
+ }
+ // CATEGORIES? : TokenType | TokenType[]
+ if (hasCategoriesProperty(currTokType) &&
+ !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 = {};
+ }
+ });
+}
+export function assignCategoriesTokensProp(tokenTypes) {
+ forEach(tokenTypes, function (currTokType) {
+ // avoid duplications
+ currTokType.categoryMatches = [];
+ forEach(currTokType.categoryMatchesMap, function (val, key) {
+ currTokType.categoryMatches.push(tokenIdxToClass[key].tokenTypeIdx);
+ });
+ });
+}
+export function assignCategoriesMapProp(tokenTypes) {
+ forEach(tokenTypes, function (currTokType) {
+ singleAssignCategoriesToksMap([], currTokType);
+ });
+}
+export function singleAssignCategoriesToksMap(path, nextNode) {
+ forEach(path, function (pathNode) {
+ nextNode.categoryMatchesMap[pathNode.tokenTypeIdx] = true;
+ });
+ forEach(nextNode.CATEGORIES, function (nextCategory) {
+ var newPath = path.concat(nextNode);
+ // avoids infinite loops due to cyclic categories.
+ if (!contains(newPath, nextCategory)) {
+ singleAssignCategoriesToksMap(newPath, nextCategory);
+ }
+ });
+}
+export function hasShortKeyProperty(tokType) {
+ return has(tokType, "tokenTypeIdx");
+}
+export function hasCategoriesProperty(tokType) {
+ return has(tokType, "CATEGORIES");
+}
+export function hasExtendingTokensTypesProperty(tokType) {
+ return has(tokType, "categoryMatches");
+}
+export function hasExtendingTokensTypesMapProperty(tokType) {
+ return has(tokType, "categoryMatchesMap");
+}
+export function isTokenType(tokType) {
+ return has(tokType, "tokenTypeIdx");
+}
+//# sourceMappingURL=tokens.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/scan/tokens_constants.js b/node_modules/chevrotain/lib_esm/src/scan/tokens_constants.js
new file mode 100644
index 0000000..436c089
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/scan/tokens_constants.js
@@ -0,0 +1,2 @@
+export var EOF_TOKEN_TYPE = 1;
+//# sourceMappingURL=tokens_constants.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/scan/tokens_public.js b/node_modules/chevrotain/lib_esm/src/scan/tokens_public.js
new file mode 100644
index 0000000..f9cf652
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/scan/tokens_public.js
@@ -0,0 +1,87 @@
+import { has, isString, isUndefined } from "../utils/utils";
+import { Lexer } from "./lexer_public";
+import { augmentTokenTypes, tokenStructuredMatcher } from "./tokens";
+export function tokenLabel(tokType) {
+ if (hasTokenLabel(tokType)) {
+ return tokType.LABEL;
+ }
+ else {
+ return tokType.name;
+ }
+}
+export function tokenName(tokType) {
+ return tokType.name;
+}
+export function hasTokenLabel(obj) {
+ return 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";
+export function createToken(config) {
+ return createTokenInternal(config);
+}
+function createTokenInternal(config) {
+ var pattern = config.pattern;
+ var tokenType = {};
+ tokenType.name = config.name;
+ if (!isUndefined(pattern)) {
+ tokenType.PATTERN = pattern;
+ }
+ if (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 (has(config, CATEGORIES)) {
+ // casting to ANY as this will be fixed inside `augmentTokenTypes``
+ tokenType.CATEGORIES = config[CATEGORIES];
+ }
+ augmentTokenTypes([tokenType]);
+ if (has(config, LABEL)) {
+ tokenType.LABEL = config[LABEL];
+ }
+ if (has(config, GROUP)) {
+ tokenType.GROUP = config[GROUP];
+ }
+ if (has(config, POP_MODE)) {
+ tokenType.POP_MODE = config[POP_MODE];
+ }
+ if (has(config, PUSH_MODE)) {
+ tokenType.PUSH_MODE = config[PUSH_MODE];
+ }
+ if (has(config, LONGER_ALT)) {
+ tokenType.LONGER_ALT = config[LONGER_ALT];
+ }
+ if (has(config, LINE_BREAKS)) {
+ tokenType.LINE_BREAKS = config[LINE_BREAKS];
+ }
+ if (has(config, START_CHARS_HINT)) {
+ tokenType.START_CHARS_HINT = config[START_CHARS_HINT];
+ }
+ return tokenType;
+}
+export var EOF = createToken({ name: "EOF", pattern: Lexer.NA });
+augmentTokenTypes([EOF]);
+export 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
+ };
+}
+export function tokenMatcher(token, tokType) {
+ return tokenStructuredMatcher(token, tokType);
+}
+//# sourceMappingURL=tokens_public.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/text/range.js b/node_modules/chevrotain/lib_esm/src/text/range.js
new file mode 100644
index 0000000..735da1a
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/text/range.js
@@ -0,0 +1,30 @@
+var Range = /** @class */ (function () {
+ function Range(start, end) {
+ this.start = start;
+ this.end = end;
+ if (!isValidRange(start, end)) {
+ throw new Error("INVALID RANGE");
+ }
+ }
+ Range.prototype.contains = function (num) {
+ return this.start <= num && this.end >= num;
+ };
+ Range.prototype.containsRange = function (other) {
+ return this.start <= other.start && this.end >= other.end;
+ };
+ Range.prototype.isContainedInRange = function (other) {
+ return other.containsRange(this);
+ };
+ Range.prototype.strictlyContainsRange = function (other) {
+ return this.start < other.start && this.end > other.end;
+ };
+ Range.prototype.isStrictlyContainedInRange = function (other) {
+ return other.strictlyContainsRange(this);
+ };
+ return Range;
+}());
+export { Range };
+export function isValidRange(start, end) {
+ return !(start < 0 || end < start);
+}
+//# sourceMappingURL=range.js.map
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/utils/utils.js b/node_modules/chevrotain/lib_esm/src/utils/utils.js
new file mode 100644
index 0000000..36a6bc2
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/utils/utils.js
@@ -0,0 +1,420 @@
+/*
+ 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...
+ */
+export function isEmpty(arr) {
+ return arr && arr.length === 0;
+}
+export function keys(obj) {
+ if (obj === undefined || obj === null) {
+ return [];
+ }
+ return Object.keys(obj);
+}
+export 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;
+}
+export 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;
+}
+export function map(arr, callback) {
+ var result = [];
+ for (var idx = 0; idx < arr.length; idx++) {
+ result.push(callback.call(null, arr[idx], idx));
+ }
+ return result;
+}
+export 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;
+}
+export function first(arr) {
+ return isEmpty(arr) ? undefined : arr[0];
+}
+export function last(arr) {
+ var len = arr && arr.length;
+ return len ? arr[len - 1] : undefined;
+}
+export 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");
+ }
+}
+export function isString(item) {
+ return typeof item === "string";
+}
+export function isUndefined(item) {
+ return item === undefined;
+}
+export function isFunction(item) {
+ return item instanceof Function;
+}
+export function drop(arr, howMuch) {
+ if (howMuch === void 0) { howMuch = 1; }
+ return arr.slice(howMuch, arr.length);
+}
+export function dropRight(arr, howMuch) {
+ if (howMuch === void 0) { howMuch = 1; }
+ return arr.slice(0, arr.length - howMuch);
+}
+export 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;
+}
+export function reject(arr, predicate) {
+ return filter(arr, function (item) { return !predicate(item); });
+}
+export 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;
+}
+export function has(obj, prop) {
+ if (isObject(obj)) {
+ return obj.hasOwnProperty(prop);
+ }
+ return false;
+}
+export function contains(arr, item) {
+ return find(arr, function (currItem) { return currItem === item; }) !== undefined ? true : false;
+}
+/**
+ * shallow clone
+ */
+export function cloneArr(arr) {
+ var newArr = [];
+ for (var i = 0; i < arr.length; i++) {
+ newArr.push(arr[i]);
+ }
+ return newArr;
+}
+/**
+ * shallow clone
+ */
+export 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;
+}
+export 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;
+}
+export 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;
+}
+export 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;
+}
+export function compact(arr) {
+ return reject(arr, function (item) { return item === null || item === undefined; });
+}
+export 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);
+ }
+ }, []);
+}
+export 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);
+}
+export function isArray(obj) {
+ return Array.isArray(obj);
+}
+export function isRegExp(obj) {
+ return obj instanceof RegExp;
+}
+export function isObject(obj) {
+ return obj instanceof Object;
+}
+export function every(arr, predicate) {
+ for (var i = 0; i < arr.length; i++) {
+ if (!predicate(arr[i], i)) {
+ return false;
+ }
+ }
+ return true;
+}
+export function difference(arr, values) {
+ return reject(arr, function (item) { return contains(values, item); });
+}
+export function some(arr, predicate) {
+ for (var i = 0; i < arr.length; i++) {
+ if (predicate(arr[i])) {
+ return true;
+ }
+ }
+ return false;
+}
+export function indexOf(arr, value) {
+ for (var i = 0; i < arr.length; i++) {
+ if (arr[i] === value) {
+ return i;
+ }
+ }
+ return -1;
+}
+export function sortBy(arr, orderFunc) {
+ var result = cloneArr(arr);
+ result.sort(function (a, b) { return orderFunc(a) - orderFunc(b); });
+ return result;
+}
+export 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
+ */
+export 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
+ */
+export 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;
+}
+export function defaults() {
+ var sources = [];
+ for (var _i = 0; _i < arguments.length; _i++) {
+ sources[_i] = arguments[_i];
+ }
+ return assignNoOverwrite.apply(null, [{}].concat(sources));
+}
+export 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
+ */
+export 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;
+}
+export function NOOP() { }
+export function IDENTITY(item) {
+ return item;
+}
+/**
+ * Will return a new packed array with same values.
+ */
+export 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;
+}
+export function PRINT_ERROR(msg) {
+ /* istanbul ignore else - can't override global.console in node.js */
+ if (console && console.error) {
+ console.error("Error: " + msg);
+ }
+}
+export 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);
+ }
+}
+export function isES2015MapSupported() {
+ return typeof Map === "function";
+}
+export 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
+export 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);
+}
+export function peek(arr) {
+ return arr[arr.length - 1];
+}
+/* istanbul ignore next - for performance tracing*/
+export 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
\ No newline at end of file
diff --git a/node_modules/chevrotain/lib_esm/src/version.js b/node_modules/chevrotain/lib_esm/src/version.js
new file mode 100644
index 0000000..30a2e75
--- /dev/null
+++ b/node_modules/chevrotain/lib_esm/src/version.js
@@ -0,0 +1,5 @@
+// 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.
+export var VERSION = "6.5.0";
+//# sourceMappingURL=version.js.map
\ No newline at end of file
diff --git a/node_modules/java-parser/LICENSE b/node_modules/java-parser/LICENSE
new file mode 100644
index 0000000..931a948
--- /dev/null
+++ b/node_modules/java-parser/LICENSE
@@ -0,0 +1,204 @@
+
+ Copyright 2018-2021 the original author or authors from the JHipster project
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/node_modules/java-parser/README.md b/node_modules/java-parser/README.md
new file mode 100644
index 0000000..80688b5
--- /dev/null
+++ b/node_modules/java-parser/README.md
@@ -0,0 +1,78 @@
+[![npm](https://img.shields.io/npm/v/java-parser.svg)](https://www.npmjs.com/package/java-parser)
+
+# java-parser
+
+A Java Parser implemented in JavaScript using the [Chevrotain Parsing ToolKit](https://github.com/Chevrotain/chevrotain).
+It outputs a **C**oncrete **S**yntax **T**ree, rather than an **A**bstract **S**yntax **T**ree.
+
+- [On the Difference between a CST and an AST](https://stackoverflow.com/questions/1888854/what-is-the-difference-between-an-abstract-syntax-tree-and-a-concrete-syntax-tre)
+
+Currently the main focus of this project is to be used in implementing a prettier Java plugin.
+But it could also be used as the basis for other Java related tools in the JavaScript ecosystem.
+
+## Installation
+
+```sh
+npm install java-parser --save-dev
+```
+
+or
+
+```sh
+yarn add java-parser --dev
+```
+
+## Usage
+
+### Parsing
+
+```javascript
+const { parse } = require("java-parser");
+const javaText = `
+public class HelloWorldExample{
+ public static void main(String args[]){
+ System.out.println("Hello World !");
+ }
+}
+`;
+
+const cst = parse(javaText);
+// explore the CST
+```
+
+### Traversing the CST
+
+See relevant [Chevrotain documentation on CST Traversal](http://chevrotain.io/docs/guide/concrete_syntax_tree.html#traversing).
+
+```javascript
+const {
+ BaseJavaCstVisitor,
+ BaseJavaCstVisitorWithDefaults
+} = require("java-parser");
+
+// Use "BaseJavaCstVisitor" if you need to implement all the visitor methods yourself.
+class LambdaArrowsPositionCollector extends BaseJavaCstVisitorWithDefaults {
+ constructor() {
+ super();
+ this.customResult = [];
+ this.validateVisitor();
+ }
+
+ lambdaExpression(ctx) {
+ // Collects all the starting offsets of lambda arrows in lambdas with short (no parenthesis)
+ // single argument lists: e.g:
+ // - n -> n*n (will be collected)
+ // - (n) -> n*n (not collected)
+ if (ctx.lambdaParameters[0].children.Identifier) {
+ this.customResult.push(ctx.Arrow[0].startOffset);
+ }
+ }
+}
+
+const lambdaArrowsCollector = new LambdaArrowsPositionCollector();
+// The CST result from the previous code snippet
+lambdaArrowsCollector.visit(cst);
+lambdaArrowsCollector.customResult.forEach(arrowOffset => {
+ console.log(arrowOffset);
+});
+```
diff --git a/node_modules/java-parser/api.d.ts b/node_modules/java-parser/api.d.ts
new file mode 100644
index 0000000..10da51c
--- /dev/null
+++ b/node_modules/java-parser/api.d.ts
@@ -0,0 +1,3561 @@
+import {
+ CstNode as ChevrotainCstNode,
+ CstNodeLocation,
+ ICstVisitor,
+ IToken as ChevrotainIToken
+} from "chevrotain";
+
+export interface CstNode extends ChevrotainCstNode {
+ children: CstChildrenDictionary;
+ leadingComments?: IToken[];
+ trailingComments?: IToken[];
+ ignore?: boolean;
+ location: CstNodeLocation;
+}
+
+export interface IToken extends ChevrotainIToken {
+ leadingComments?: IToken[];
+ trailingComments?: IToken[];
+ startOffset: number;
+ startLine: number;
+ startColumn: number;
+ endOffset: number;
+ endLine: number;
+ endColumn: number;
+}
+
+export type CstElement = IToken | CstNode;
+
+export declare type CstChildrenDictionary = {
+ [identifier: string]: CstElement[];
+};
+
+export function parse(text: string, startProduction?: string): CstNode;
+
+export const BaseJavaCstVisitor: JavaCstVisitorConstructor;
+export const BaseJavaCstVisitorWithDefaults: JavaCstVisitorWithDefaultsConstructor<
+ any,
+ any
+>;
+
+export abstract class JavaCstVisitor implements ICstVisitor {
+ // No need to implement these two methods
+ // Generic Visit method implemented by the Chevrotain Library
+ visit(cstNode: CstNode | CstNode[], param?: IN): OUT;
+ validateVisitor(): void;
+
+ typeIdentifier(ctx: TypeIdentifierCtx, param?: IN): OUT;
+ literal(ctx: LiteralCtx, param?: IN): OUT;
+ integerLiteral(ctx: IntegerLiteralCtx, param?: IN): OUT;
+ floatingPointLiteral(ctx: FloatingPointLiteralCtx, param?: IN): OUT;
+ booleanLiteral(ctx: BooleanLiteralCtx, param?: IN): OUT;
+ primitiveType(ctx: PrimitiveTypeCtx, param?: IN): OUT;
+ numericType(ctx: NumericTypeCtx, param?: IN): OUT;
+ integralType(ctx: IntegralTypeCtx, param?: IN): OUT;
+ floatingPointType(ctx: FloatingPointTypeCtx, param?: IN): OUT;
+ referenceType(ctx: ReferenceTypeCtx, param?: IN): OUT;
+ classOrInterfaceType(ctx: ClassOrInterfaceTypeCtx, param?: IN): OUT;
+ classType(ctx: ClassTypeCtx, param?: IN): OUT;
+ interfaceType(ctx: InterfaceTypeCtx, param?: IN): OUT;
+ typeVariable(ctx: TypeVariableCtx, param?: IN): OUT;
+ dims(ctx: DimsCtx, param?: IN): OUT;
+ typeParameter(ctx: TypeParameterCtx, param?: IN): OUT;
+ typeParameterModifier(ctx: TypeParameterModifierCtx, param?: IN): OUT;
+ typeBound(ctx: TypeBoundCtx, param?: IN): OUT;
+ additionalBound(ctx: AdditionalBoundCtx, param?: IN): OUT;
+ typeArguments(ctx: TypeArgumentsCtx, param?: IN): OUT;
+ typeArgumentList(ctx: TypeArgumentListCtx, param?: IN): OUT;
+ typeArgument(ctx: TypeArgumentCtx, param?: IN): OUT;
+ wildcard(ctx: WildcardCtx, param?: IN): OUT;
+ wildcardBounds(ctx: WildcardBoundsCtx, param?: IN): OUT;
+ moduleName(ctx: ModuleNameCtx, param?: IN): OUT;
+ packageName(ctx: PackageNameCtx, param?: IN): OUT;
+ typeName(ctx: TypeNameCtx, param?: IN): OUT;
+ expressionName(ctx: ExpressionNameCtx, param?: IN): OUT;
+ methodName(ctx: MethodNameCtx, param?: IN): OUT;
+ packageOrTypeName(ctx: PackageOrTypeNameCtx, param?: IN): OUT;
+ ambiguousName(ctx: AmbiguousNameCtx, param?: IN): OUT;
+ classDeclaration(ctx: ClassDeclarationCtx, param?: IN): OUT;
+ normalClassDeclaration(ctx: NormalClassDeclarationCtx, param?: IN): OUT;
+ classModifier(ctx: ClassModifierCtx, param?: IN): OUT;
+ typeParameters(ctx: TypeParametersCtx, param?: IN): OUT;
+ typeParameterList(ctx: TypeParameterListCtx, param?: IN): OUT;
+ superclass(ctx: SuperclassCtx, param?: IN): OUT;
+ superinterfaces(ctx: SuperinterfacesCtx, param?: IN): OUT;
+ interfaceTypeList(ctx: InterfaceTypeListCtx, param?: IN): OUT;
+ classPermits(ctx: ClassPermitsCtx, param?: IN): OUT;
+ classBody(ctx: ClassBodyCtx, param?: IN): OUT;
+ classBodyDeclaration(ctx: ClassBodyDeclarationCtx, param?: IN): OUT;
+ classMemberDeclaration(ctx: ClassMemberDeclarationCtx, param?: IN): OUT;
+ fieldDeclaration(ctx: FieldDeclarationCtx, param?: IN): OUT;
+ fieldModifier(ctx: FieldModifierCtx, param?: IN): OUT;
+ variableDeclaratorList(ctx: VariableDeclaratorListCtx, param?: IN): OUT;
+ variableDeclarator(ctx: VariableDeclaratorCtx, param?: IN): OUT;
+ variableDeclaratorId(ctx: VariableDeclaratorIdCtx, param?: IN): OUT;
+ variableInitializer(ctx: VariableInitializerCtx, param?: IN): OUT;
+ unannType(ctx: UnannTypeCtx, param?: IN): OUT;
+ unannPrimitiveTypeWithOptionalDimsSuffix(
+ ctx: UnannPrimitiveTypeWithOptionalDimsSuffixCtx,
+ param?: IN
+ ): OUT;
+ unannPrimitiveType(ctx: UnannPrimitiveTypeCtx, param?: IN): OUT;
+ unannReferenceType(ctx: UnannReferenceTypeCtx, param?: IN): OUT;
+ unannClassOrInterfaceType(ctx: UnannClassOrInterfaceTypeCtx, param?: IN): OUT;
+ unannClassType(ctx: UnannClassTypeCtx, param?: IN): OUT;
+ unannInterfaceType(ctx: UnannInterfaceTypeCtx, param?: IN): OUT;
+ unannTypeVariable(ctx: UnannTypeVariableCtx, param?: IN): OUT;
+ methodDeclaration(ctx: MethodDeclarationCtx, param?: IN): OUT;
+ methodModifier(ctx: MethodModifierCtx, param?: IN): OUT;
+ methodHeader(ctx: MethodHeaderCtx, param?: IN): OUT;
+ result(ctx: ResultCtx, param?: IN): OUT;
+ methodDeclarator(ctx: MethodDeclaratorCtx, param?: IN): OUT;
+ receiverParameter(ctx: ReceiverParameterCtx, param?: IN): OUT;
+ formalParameterList(ctx: FormalParameterListCtx, param?: IN): OUT;
+ formalParameter(ctx: FormalParameterCtx, param?: IN): OUT;
+ variableParaRegularParameter(
+ ctx: VariableParaRegularParameterCtx,
+ param?: IN
+ ): OUT;
+ variableArityParameter(ctx: VariableArityParameterCtx, param?: IN): OUT;
+ variableModifier(ctx: VariableModifierCtx, param?: IN): OUT;
+ throws(ctx: ThrowsCtx, param?: IN): OUT;
+ exceptionTypeList(ctx: ExceptionTypeListCtx, param?: IN): OUT;
+ exceptionType(ctx: ExceptionTypeCtx, param?: IN): OUT;
+ methodBody(ctx: MethodBodyCtx, param?: IN): OUT;
+ instanceInitializer(ctx: InstanceInitializerCtx, param?: IN): OUT;
+ staticInitializer(ctx: StaticInitializerCtx, param?: IN): OUT;
+ constructorDeclaration(ctx: ConstructorDeclarationCtx, param?: IN): OUT;
+ constructorModifier(ctx: ConstructorModifierCtx, param?: IN): OUT;
+ constructorDeclarator(ctx: ConstructorDeclaratorCtx, param?: IN): OUT;
+ simpleTypeName(ctx: SimpleTypeNameCtx, param?: IN): OUT;
+ constructorBody(ctx: ConstructorBodyCtx, param?: IN): OUT;
+ explicitConstructorInvocation(
+ ctx: ExplicitConstructorInvocationCtx,
+ param?: IN
+ ): OUT;
+ unqualifiedExplicitConstructorInvocation(
+ ctx: UnqualifiedExplicitConstructorInvocationCtx,
+ param?: IN
+ ): OUT;
+ qualifiedExplicitConstructorInvocation(
+ ctx: QualifiedExplicitConstructorInvocationCtx,
+ param?: IN
+ ): OUT;
+ enumDeclaration(ctx: EnumDeclarationCtx, param?: IN): OUT;
+ enumBody(ctx: EnumBodyCtx, param?: IN): OUT;
+ enumConstantList(ctx: EnumConstantListCtx, param?: IN): OUT;
+ enumConstant(ctx: EnumConstantCtx, param?: IN): OUT;
+ enumConstantModifier(ctx: EnumConstantModifierCtx, param?: IN): OUT;
+ enumBodyDeclarations(ctx: EnumBodyDeclarationsCtx, param?: IN): OUT;
+ recordDeclaration(ctx: RecordDeclarationCtx, param?: IN): OUT;
+ recordHeader(ctx: RecordHeaderCtx, param?: IN): OUT;
+ recordComponentList(ctx: RecordComponentListCtx, param?: IN): OUT;
+ recordComponent(ctx: RecordComponentCtx, param?: IN): OUT;
+ variableArityRecordComponent(
+ ctx: VariableArityRecordComponentCtx,
+ param?: IN
+ ): OUT;
+ recordComponentModifier(ctx: RecordComponentModifierCtx, param?: IN): OUT;
+ recordBody(ctx: RecordBodyCtx, param?: IN): OUT;
+ recordBodyDeclaration(ctx: RecordBodyDeclarationCtx, param?: IN): OUT;
+ compactConstructorDeclaration(
+ ctx: CompactConstructorDeclarationCtx,
+ param?: IN
+ ): OUT;
+ isClassDeclaration(ctx: IsClassDeclarationCtx, param?: IN): OUT;
+ identifyClassBodyDeclarationType(
+ ctx: IdentifyClassBodyDeclarationTypeCtx,
+ param?: IN
+ ): OUT;
+ isDims(ctx: IsDimsCtx, param?: IN): OUT;
+ isCompactConstructorDeclaration(
+ ctx: IsCompactConstructorDeclarationCtx,
+ param?: IN
+ ): OUT;
+ compilationUnit(ctx: CompilationUnitCtx, param?: IN): OUT;
+ ordinaryCompilationUnit(ctx: OrdinaryCompilationUnitCtx, param?: IN): OUT;
+ modularCompilationUnit(ctx: ModularCompilationUnitCtx, param?: IN): OUT;
+ packageDeclaration(ctx: PackageDeclarationCtx, param?: IN): OUT;
+ packageModifier(ctx: PackageModifierCtx, param?: IN): OUT;
+ importDeclaration(ctx: ImportDeclarationCtx, param?: IN): OUT;
+ typeDeclaration(ctx: TypeDeclarationCtx, param?: IN): OUT;
+ moduleDeclaration(ctx: ModuleDeclarationCtx, param?: IN): OUT;
+ moduleDirective(ctx: ModuleDirectiveCtx, param?: IN): OUT;
+ requiresModuleDirective(ctx: RequiresModuleDirectiveCtx, param?: IN): OUT;
+ exportsModuleDirective(ctx: ExportsModuleDirectiveCtx, param?: IN): OUT;
+ opensModuleDirective(ctx: OpensModuleDirectiveCtx, param?: IN): OUT;
+ usesModuleDirective(ctx: UsesModuleDirectiveCtx, param?: IN): OUT;
+ providesModuleDirective(ctx: ProvidesModuleDirectiveCtx, param?: IN): OUT;
+ requiresModifier(ctx: RequiresModifierCtx, param?: IN): OUT;
+ isModuleCompilationUnit(ctx: IsModuleCompilationUnitCtx, param?: IN): OUT;
+ interfaceDeclaration(ctx: InterfaceDeclarationCtx, param?: IN): OUT;
+ normalInterfaceDeclaration(
+ ctx: NormalInterfaceDeclarationCtx,
+ param?: IN
+ ): OUT;
+ interfaceModifier(ctx: InterfaceModifierCtx, param?: IN): OUT;
+ extendsInterfaces(ctx: ExtendsInterfacesCtx, param?: IN): OUT;
+ interfacePermits(ctx: InterfacePermitsCtx, param?: IN): OUT;
+ interfaceBody(ctx: InterfaceBodyCtx, param?: IN): OUT;
+ interfaceMemberDeclaration(
+ ctx: InterfaceMemberDeclarationCtx,
+ param?: IN
+ ): OUT;
+ constantDeclaration(ctx: ConstantDeclarationCtx, param?: IN): OUT;
+ constantModifier(ctx: ConstantModifierCtx, param?: IN): OUT;
+ interfaceMethodDeclaration(
+ ctx: InterfaceMethodDeclarationCtx,
+ param?: IN
+ ): OUT;
+ interfaceMethodModifier(ctx: InterfaceMethodModifierCtx, param?: IN): OUT;
+ annotationTypeDeclaration(ctx: AnnotationTypeDeclarationCtx, param?: IN): OUT;
+ annotationTypeBody(ctx: AnnotationTypeBodyCtx, param?: IN): OUT;
+ annotationTypeMemberDeclaration(
+ ctx: AnnotationTypeMemberDeclarationCtx,
+ param?: IN
+ ): OUT;
+ annotationTypeElementDeclaration(
+ ctx: AnnotationTypeElementDeclarationCtx,
+ param?: IN
+ ): OUT;
+ annotationTypeElementModifier(
+ ctx: AnnotationTypeElementModifierCtx,
+ param?: IN
+ ): OUT;
+ defaultValue(ctx: DefaultValueCtx, param?: IN): OUT;
+ annotation(ctx: AnnotationCtx, param?: IN): OUT;
+ elementValuePairList(ctx: ElementValuePairListCtx, param?: IN): OUT;
+ elementValuePair(ctx: ElementValuePairCtx, param?: IN): OUT;
+ elementValue(ctx: ElementValueCtx, param?: IN): OUT;
+ elementValueArrayInitializer(
+ ctx: ElementValueArrayInitializerCtx,
+ param?: IN
+ ): OUT;
+ elementValueList(ctx: ElementValueListCtx, param?: IN): OUT;
+ identifyInterfaceBodyDeclarationType(
+ ctx: IdentifyInterfaceBodyDeclarationTypeCtx,
+ param?: IN
+ ): OUT;
+ identifyAnnotationBodyDeclarationType(
+ ctx: IdentifyAnnotationBodyDeclarationTypeCtx,
+ param?: IN
+ ): OUT;
+ isSimpleElementValueAnnotation(
+ ctx: IsSimpleElementValueAnnotationCtx,
+ param?: IN
+ ): OUT;
+ arrayInitializer(ctx: ArrayInitializerCtx, param?: IN): OUT;
+ variableInitializerList(ctx: VariableInitializerListCtx, param?: IN): OUT;
+ block(ctx: BlockCtx, param?: IN): OUT;
+ blockStatements(ctx: BlockStatementsCtx, param?: IN): OUT;
+ blockStatement(ctx: BlockStatementCtx, param?: IN): OUT;
+ localVariableDeclarationStatement(
+ ctx: LocalVariableDeclarationStatementCtx,
+ param?: IN
+ ): OUT;
+ localVariableDeclaration(ctx: LocalVariableDeclarationCtx, param?: IN): OUT;
+ localVariableType(ctx: LocalVariableTypeCtx, param?: IN): OUT;
+ statement(ctx: StatementCtx, param?: IN): OUT;
+ statementWithoutTrailingSubstatement(
+ ctx: StatementWithoutTrailingSubstatementCtx,
+ param?: IN
+ ): OUT;
+ emptyStatement(ctx: EmptyStatementCtx, param?: IN): OUT;
+ labeledStatement(ctx: LabeledStatementCtx, param?: IN): OUT;
+ expressionStatement(ctx: ExpressionStatementCtx, param?: IN): OUT;
+ statementExpression(ctx: StatementExpressionCtx, param?: IN): OUT;
+ ifStatement(ctx: IfStatementCtx, param?: IN): OUT;
+ assertStatement(ctx: AssertStatementCtx, param?: IN): OUT;
+ switchStatement(ctx: SwitchStatementCtx, param?: IN): OUT;
+ switchBlock(ctx: SwitchBlockCtx, param?: IN): OUT;
+ switchBlockStatementGroup(ctx: SwitchBlockStatementGroupCtx, param?: IN): OUT;
+ switchLabel(ctx: SwitchLabelCtx, param?: IN): OUT;
+ caseOrDefaultLabel(ctx: CaseOrDefaultLabelCtx, param?: IN): OUT;
+ caseLabelElement(ctx: CaseLabelElementCtx, param?: IN): OUT;
+ switchRule(ctx: SwitchRuleCtx, param?: IN): OUT;
+ caseConstant(ctx: CaseConstantCtx, param?: IN): OUT;
+ whileStatement(ctx: WhileStatementCtx, param?: IN): OUT;
+ doStatement(ctx: DoStatementCtx, param?: IN): OUT;
+ forStatement(ctx: ForStatementCtx, param?: IN): OUT;
+ basicForStatement(ctx: BasicForStatementCtx, param?: IN): OUT;
+ forInit(ctx: ForInitCtx, param?: IN): OUT;
+ forUpdate(ctx: ForUpdateCtx, param?: IN): OUT;
+ statementExpressionList(ctx: StatementExpressionListCtx, param?: IN): OUT;
+ enhancedForStatement(ctx: EnhancedForStatementCtx, param?: IN): OUT;
+ breakStatement(ctx: BreakStatementCtx, param?: IN): OUT;
+ continueStatement(ctx: ContinueStatementCtx, param?: IN): OUT;
+ returnStatement(ctx: ReturnStatementCtx, param?: IN): OUT;
+ throwStatement(ctx: ThrowStatementCtx, param?: IN): OUT;
+ synchronizedStatement(ctx: SynchronizedStatementCtx, param?: IN): OUT;
+ tryStatement(ctx: TryStatementCtx, param?: IN): OUT;
+ catches(ctx: CatchesCtx, param?: IN): OUT;
+ catchClause(ctx: CatchClauseCtx, param?: IN): OUT;
+ catchFormalParameter(ctx: CatchFormalParameterCtx, param?: IN): OUT;
+ catchType(ctx: CatchTypeCtx, param?: IN): OUT;
+ finally(ctx: FinallyCtx, param?: IN): OUT;
+ tryWithResourcesStatement(ctx: TryWithResourcesStatementCtx, param?: IN): OUT;
+ resourceSpecification(ctx: ResourceSpecificationCtx, param?: IN): OUT;
+ resourceList(ctx: ResourceListCtx, param?: IN): OUT;
+ resource(ctx: ResourceCtx, param?: IN): OUT;
+ resourceInit(ctx: ResourceInitCtx, param?: IN): OUT;
+ yieldStatement(ctx: YieldStatementCtx, param?: IN): OUT;
+ variableAccess(ctx: VariableAccessCtx, param?: IN): OUT;
+ isBasicForStatement(ctx: IsBasicForStatementCtx, param?: IN): OUT;
+ isLocalVariableDeclaration(
+ ctx: IsLocalVariableDeclarationCtx,
+ param?: IN
+ ): OUT;
+ isClassicSwitchLabel(ctx: IsClassicSwitchLabelCtx, param?: IN): OUT;
+ expression(ctx: ExpressionCtx, param?: IN): OUT;
+ lambdaExpression(ctx: LambdaExpressionCtx, param?: IN): OUT;
+ lambdaParameters(ctx: LambdaParametersCtx, param?: IN): OUT;
+ lambdaParametersWithBraces(
+ ctx: LambdaParametersWithBracesCtx,
+ param?: IN
+ ): OUT;
+ lambdaParameterList(ctx: LambdaParameterListCtx, param?: IN): OUT;
+ inferredLambdaParameterList(
+ ctx: InferredLambdaParameterListCtx,
+ param?: IN
+ ): OUT;
+ explicitLambdaParameterList(
+ ctx: ExplicitLambdaParameterListCtx,
+ param?: IN
+ ): OUT;
+ lambdaParameter(ctx: LambdaParameterCtx, param?: IN): OUT;
+ regularLambdaParameter(ctx: RegularLambdaParameterCtx, param?: IN): OUT;
+ lambdaParameterType(ctx: LambdaParameterTypeCtx, param?: IN): OUT;
+ lambdaBody(ctx: LambdaBodyCtx, param?: IN): OUT;
+ ternaryExpression(ctx: TernaryExpressionCtx, param?: IN): OUT;
+ binaryExpression(ctx: BinaryExpressionCtx, param?: IN): OUT;
+ unaryExpression(ctx: UnaryExpressionCtx, param?: IN): OUT;
+ unaryExpressionNotPlusMinus(
+ ctx: UnaryExpressionNotPlusMinusCtx,
+ param?: IN
+ ): OUT;
+ primary(ctx: PrimaryCtx, param?: IN): OUT;
+ primaryPrefix(ctx: PrimaryPrefixCtx, param?: IN): OUT;
+ primarySuffix(ctx: PrimarySuffixCtx, param?: IN): OUT;
+ fqnOrRefType(ctx: FqnOrRefTypeCtx, param?: IN): OUT;
+ fqnOrRefTypePartRest(ctx: FqnOrRefTypePartRestCtx, param?: IN): OUT;
+ fqnOrRefTypePartCommon(ctx: FqnOrRefTypePartCommonCtx, param?: IN): OUT;
+ fqnOrRefTypePartFirst(ctx: FqnOrRefTypePartFirstCtx, param?: IN): OUT;
+ parenthesisExpression(ctx: ParenthesisExpressionCtx, param?: IN): OUT;
+ castExpression(ctx: CastExpressionCtx, param?: IN): OUT;
+ primitiveCastExpression(ctx: PrimitiveCastExpressionCtx, param?: IN): OUT;
+ referenceTypeCastExpression(
+ ctx: ReferenceTypeCastExpressionCtx,
+ param?: IN
+ ): OUT;
+ newExpression(ctx: NewExpressionCtx, param?: IN): OUT;
+ unqualifiedClassInstanceCreationExpression(
+ ctx: UnqualifiedClassInstanceCreationExpressionCtx,
+ param?: IN
+ ): OUT;
+ classOrInterfaceTypeToInstantiate(
+ ctx: ClassOrInterfaceTypeToInstantiateCtx,
+ param?: IN
+ ): OUT;
+ typeArgumentsOrDiamond(ctx: TypeArgumentsOrDiamondCtx, param?: IN): OUT;
+ diamond(ctx: DiamondCtx, param?: IN): OUT;
+ methodInvocationSuffix(ctx: MethodInvocationSuffixCtx, param?: IN): OUT;
+ argumentList(ctx: ArgumentListCtx, param?: IN): OUT;
+ arrayCreationExpression(ctx: ArrayCreationExpressionCtx, param?: IN): OUT;
+ arrayCreationDefaultInitSuffix(
+ ctx: ArrayCreationDefaultInitSuffixCtx,
+ param?: IN
+ ): OUT;
+ arrayCreationExplicitInitSuffix(
+ ctx: ArrayCreationExplicitInitSuffixCtx,
+ param?: IN
+ ): OUT;
+ dimExprs(ctx: DimExprsCtx, param?: IN): OUT;
+ dimExpr(ctx: DimExprCtx, param?: IN): OUT;
+ classLiteralSuffix(ctx: ClassLiteralSuffixCtx, param?: IN): OUT;
+ arrayAccessSuffix(ctx: ArrayAccessSuffixCtx, param?: IN): OUT;
+ methodReferenceSuffix(ctx: MethodReferenceSuffixCtx, param?: IN): OUT;
+ pattern(ctx: PatternCtx, param?: IN): OUT;
+ typePattern(ctx: TypePatternCtx, param?: IN): OUT;
+ identifyNewExpressionType(ctx: IdentifyNewExpressionTypeCtx, param?: IN): OUT;
+ isLambdaExpression(ctx: IsLambdaExpressionCtx, param?: IN): OUT;
+ isCastExpression(ctx: IsCastExpressionCtx, param?: IN): OUT;
+ isPrimitiveCastExpression(ctx: IsPrimitiveCastExpressionCtx, param?: IN): OUT;
+ isReferenceTypeCastExpression(
+ ctx: IsReferenceTypeCastExpressionCtx,
+ param?: IN
+ ): OUT;
+ isRefTypeInMethodRef(ctx: IsRefTypeInMethodRefCtx, param?: IN): OUT;
+}
+
+interface JavaCstVisitorConstructor {
+ new (): JavaCstVisitor;
+}
+
+export abstract class JavaCstVisitorWithDefaults
+ implements ICstVisitor
+{
+ // No need to implement these two methods
+ // Generic Visit method implemented by the Chevrotain Library
+ visit(cstNode: CstNode | CstNode[], param?: IN): OUT;
+ validateVisitor(): void;
+
+ typeIdentifier(ctx: TypeIdentifierCtx, param?: IN): OUT;
+ literal(ctx: LiteralCtx, param?: IN): OUT;
+ integerLiteral(ctx: IntegerLiteralCtx, param?: IN): OUT;
+ floatingPointLiteral(ctx: FloatingPointLiteralCtx, param?: IN): OUT;
+ booleanLiteral(ctx: BooleanLiteralCtx, param?: IN): OUT;
+ primitiveType(ctx: PrimitiveTypeCtx, param?: IN): OUT;
+ numericType(ctx: NumericTypeCtx, param?: IN): OUT;
+ integralType(ctx: IntegralTypeCtx, param?: IN): OUT;
+ floatingPointType(ctx: FloatingPointTypeCtx, param?: IN): OUT;
+ referenceType(ctx: ReferenceTypeCtx, param?: IN): OUT;
+ classOrInterfaceType(ctx: ClassOrInterfaceTypeCtx, param?: IN): OUT;
+ classType(ctx: ClassTypeCtx, param?: IN): OUT;
+ interfaceType(ctx: InterfaceTypeCtx, param?: IN): OUT;
+ typeVariable(ctx: TypeVariableCtx, param?: IN): OUT;
+ dims(ctx: DimsCtx, param?: IN): OUT;
+ typeParameter(ctx: TypeParameterCtx, param?: IN): OUT;
+ typeParameterModifier(ctx: TypeParameterModifierCtx, param?: IN): OUT;
+ typeBound(ctx: TypeBoundCtx, param?: IN): OUT;
+ additionalBound(ctx: AdditionalBoundCtx, param?: IN): OUT;
+ typeArguments(ctx: TypeArgumentsCtx, param?: IN): OUT;
+ typeArgumentList(ctx: TypeArgumentListCtx, param?: IN): OUT;
+ typeArgument(ctx: TypeArgumentCtx, param?: IN): OUT;
+ wildcard(ctx: WildcardCtx, param?: IN): OUT;
+ wildcardBounds(ctx: WildcardBoundsCtx, param?: IN): OUT;
+ moduleName(ctx: ModuleNameCtx, param?: IN): OUT;
+ packageName(ctx: PackageNameCtx, param?: IN): OUT;
+ typeName(ctx: TypeNameCtx, param?: IN): OUT;
+ expressionName(ctx: ExpressionNameCtx, param?: IN): OUT;
+ methodName(ctx: MethodNameCtx, param?: IN): OUT;
+ packageOrTypeName(ctx: PackageOrTypeNameCtx, param?: IN): OUT;
+ ambiguousName(ctx: AmbiguousNameCtx, param?: IN): OUT;
+ classDeclaration(ctx: ClassDeclarationCtx, param?: IN): OUT;
+ normalClassDeclaration(ctx: NormalClassDeclarationCtx, param?: IN): OUT;
+ classModifier(ctx: ClassModifierCtx, param?: IN): OUT;
+ typeParameters(ctx: TypeParametersCtx, param?: IN): OUT;
+ typeParameterList(ctx: TypeParameterListCtx, param?: IN): OUT;
+ superclass(ctx: SuperclassCtx, param?: IN): OUT;
+ superinterfaces(ctx: SuperinterfacesCtx, param?: IN): OUT;
+ interfaceTypeList(ctx: InterfaceTypeListCtx, param?: IN): OUT;
+ classPermits(ctx: ClassPermitsCtx, param?: IN): OUT;
+ classBody(ctx: ClassBodyCtx, param?: IN): OUT;
+ classBodyDeclaration(ctx: ClassBodyDeclarationCtx, param?: IN): OUT;
+ classMemberDeclaration(ctx: ClassMemberDeclarationCtx, param?: IN): OUT;
+ fieldDeclaration(ctx: FieldDeclarationCtx, param?: IN): OUT;
+ fieldModifier(ctx: FieldModifierCtx, param?: IN): OUT;
+ variableDeclaratorList(ctx: VariableDeclaratorListCtx, param?: IN): OUT;
+ variableDeclarator(ctx: VariableDeclaratorCtx, param?: IN): OUT;
+ variableDeclaratorId(ctx: VariableDeclaratorIdCtx, param?: IN): OUT;
+ variableInitializer(ctx: VariableInitializerCtx, param?: IN): OUT;
+ unannType(ctx: UnannTypeCtx, param?: IN): OUT;
+ unannPrimitiveTypeWithOptionalDimsSuffix(
+ ctx: UnannPrimitiveTypeWithOptionalDimsSuffixCtx,
+ param?: IN
+ ): OUT;
+ unannPrimitiveType(ctx: UnannPrimitiveTypeCtx, param?: IN): OUT;
+ unannReferenceType(ctx: UnannReferenceTypeCtx, param?: IN): OUT;
+ unannClassOrInterfaceType(ctx: UnannClassOrInterfaceTypeCtx, param?: IN): OUT;
+ unannClassType(ctx: UnannClassTypeCtx, param?: IN): OUT;
+ unannInterfaceType(ctx: UnannInterfaceTypeCtx, param?: IN): OUT;
+ unannTypeVariable(ctx: UnannTypeVariableCtx, param?: IN): OUT;
+ methodDeclaration(ctx: MethodDeclarationCtx, param?: IN): OUT;
+ methodModifier(ctx: MethodModifierCtx, param?: IN): OUT;
+ methodHeader(ctx: MethodHeaderCtx, param?: IN): OUT;
+ result(ctx: ResultCtx, param?: IN): OUT;
+ methodDeclarator(ctx: MethodDeclaratorCtx, param?: IN): OUT;
+ receiverParameter(ctx: ReceiverParameterCtx, param?: IN): OUT;
+ formalParameterList(ctx: FormalParameterListCtx, param?: IN): OUT;
+ formalParameter(ctx: FormalParameterCtx, param?: IN): OUT;
+ variableParaRegularParameter(
+ ctx: VariableParaRegularParameterCtx,
+ param?: IN
+ ): OUT;
+ variableArityParameter(ctx: VariableArityParameterCtx, param?: IN): OUT;
+ variableModifier(ctx: VariableModifierCtx, param?: IN): OUT;
+ throws(ctx: ThrowsCtx, param?: IN): OUT;
+ exceptionTypeList(ctx: ExceptionTypeListCtx, param?: IN): OUT;
+ exceptionType(ctx: ExceptionTypeCtx, param?: IN): OUT;
+ methodBody(ctx: MethodBodyCtx, param?: IN): OUT;
+ instanceInitializer(ctx: InstanceInitializerCtx, param?: IN): OUT;
+ staticInitializer(ctx: StaticInitializerCtx, param?: IN): OUT;
+ constructorDeclaration(ctx: ConstructorDeclarationCtx, param?: IN): OUT;
+ constructorModifier(ctx: ConstructorModifierCtx, param?: IN): OUT;
+ constructorDeclarator(ctx: ConstructorDeclaratorCtx, param?: IN): OUT;
+ simpleTypeName(ctx: SimpleTypeNameCtx, param?: IN): OUT;
+ constructorBody(ctx: ConstructorBodyCtx, param?: IN): OUT;
+ explicitConstructorInvocation(
+ ctx: ExplicitConstructorInvocationCtx,
+ param?: IN
+ ): OUT;
+ unqualifiedExplicitConstructorInvocation(
+ ctx: UnqualifiedExplicitConstructorInvocationCtx,
+ param?: IN
+ ): OUT;
+ qualifiedExplicitConstructorInvocation(
+ ctx: QualifiedExplicitConstructorInvocationCtx,
+ param?: IN
+ ): OUT;
+ enumDeclaration(ctx: EnumDeclarationCtx, param?: IN): OUT;
+ enumBody(ctx: EnumBodyCtx, param?: IN): OUT;
+ enumConstantList(ctx: EnumConstantListCtx, param?: IN): OUT;
+ enumConstant(ctx: EnumConstantCtx, param?: IN): OUT;
+ enumConstantModifier(ctx: EnumConstantModifierCtx, param?: IN): OUT;
+ enumBodyDeclarations(ctx: EnumBodyDeclarationsCtx, param?: IN): OUT;
+ recordDeclaration(ctx: RecordDeclarationCtx, param?: IN): OUT;
+ recordHeader(ctx: RecordHeaderCtx, param?: IN): OUT;
+ recordComponentList(ctx: RecordComponentListCtx, param?: IN): OUT;
+ recordComponent(ctx: RecordComponentCtx, param?: IN): OUT;
+ variableArityRecordComponent(
+ ctx: VariableArityRecordComponentCtx,
+ param?: IN
+ ): OUT;
+ recordComponentModifier(ctx: RecordComponentModifierCtx, param?: IN): OUT;
+ recordBody(ctx: RecordBodyCtx, param?: IN): OUT;
+ recordBodyDeclaration(ctx: RecordBodyDeclarationCtx, param?: IN): OUT;
+ compactConstructorDeclaration(
+ ctx: CompactConstructorDeclarationCtx,
+ param?: IN
+ ): OUT;
+ isClassDeclaration(ctx: IsClassDeclarationCtx, param?: IN): OUT;
+ identifyClassBodyDeclarationType(
+ ctx: IdentifyClassBodyDeclarationTypeCtx,
+ param?: IN
+ ): OUT;
+ isDims(ctx: IsDimsCtx, param?: IN): OUT;
+ isCompactConstructorDeclaration(
+ ctx: IsCompactConstructorDeclarationCtx,
+ param?: IN
+ ): OUT;
+ compilationUnit(ctx: CompilationUnitCtx, param?: IN): OUT;
+ ordinaryCompilationUnit(ctx: OrdinaryCompilationUnitCtx, param?: IN): OUT;
+ modularCompilationUnit(ctx: ModularCompilationUnitCtx, param?: IN): OUT;
+ packageDeclaration(ctx: PackageDeclarationCtx, param?: IN): OUT;
+ packageModifier(ctx: PackageModifierCtx, param?: IN): OUT;
+ importDeclaration(ctx: ImportDeclarationCtx, param?: IN): OUT;
+ typeDeclaration(ctx: TypeDeclarationCtx, param?: IN): OUT;
+ moduleDeclaration(ctx: ModuleDeclarationCtx, param?: IN): OUT;
+ moduleDirective(ctx: ModuleDirectiveCtx, param?: IN): OUT;
+ requiresModuleDirective(ctx: RequiresModuleDirectiveCtx, param?: IN): OUT;
+ exportsModuleDirective(ctx: ExportsModuleDirectiveCtx, param?: IN): OUT;
+ opensModuleDirective(ctx: OpensModuleDirectiveCtx, param?: IN): OUT;
+ usesModuleDirective(ctx: UsesModuleDirectiveCtx, param?: IN): OUT;
+ providesModuleDirective(ctx: ProvidesModuleDirectiveCtx, param?: IN): OUT;
+ requiresModifier(ctx: RequiresModifierCtx, param?: IN): OUT;
+ isModuleCompilationUnit(ctx: IsModuleCompilationUnitCtx, param?: IN): OUT;
+ interfaceDeclaration(ctx: InterfaceDeclarationCtx, param?: IN): OUT;
+ normalInterfaceDeclaration(
+ ctx: NormalInterfaceDeclarationCtx,
+ param?: IN
+ ): OUT;
+ interfaceModifier(ctx: InterfaceModifierCtx, param?: IN): OUT;
+ extendsInterfaces(ctx: ExtendsInterfacesCtx, param?: IN): OUT;
+ interfacePermits(ctx: InterfacePermitsCtx, param?: IN): OUT;
+ interfaceBody(ctx: InterfaceBodyCtx, param?: IN): OUT;
+ interfaceMemberDeclaration(
+ ctx: InterfaceMemberDeclarationCtx,
+ param?: IN
+ ): OUT;
+ constantDeclaration(ctx: ConstantDeclarationCtx, param?: IN): OUT;
+ constantModifier(ctx: ConstantModifierCtx, param?: IN): OUT;
+ interfaceMethodDeclaration(
+ ctx: InterfaceMethodDeclarationCtx,
+ param?: IN
+ ): OUT;
+ interfaceMethodModifier(ctx: InterfaceMethodModifierCtx, param?: IN): OUT;
+ annotationTypeDeclaration(ctx: AnnotationTypeDeclarationCtx, param?: IN): OUT;
+ annotationTypeBody(ctx: AnnotationTypeBodyCtx, param?: IN): OUT;
+ annotationTypeMemberDeclaration(
+ ctx: AnnotationTypeMemberDeclarationCtx,
+ param?: IN
+ ): OUT;
+ annotationTypeElementDeclaration(
+ ctx: AnnotationTypeElementDeclarationCtx,
+ param?: IN
+ ): OUT;
+ annotationTypeElementModifier(
+ ctx: AnnotationTypeElementModifierCtx,
+ param?: IN
+ ): OUT;
+ defaultValue(ctx: DefaultValueCtx, param?: IN): OUT;
+ annotation(ctx: AnnotationCtx, param?: IN): OUT;
+ elementValuePairList(ctx: ElementValuePairListCtx, param?: IN): OUT;
+ elementValuePair(ctx: ElementValuePairCtx, param?: IN): OUT;
+ elementValue(ctx: ElementValueCtx, param?: IN): OUT;
+ elementValueArrayInitializer(
+ ctx: ElementValueArrayInitializerCtx,
+ param?: IN
+ ): OUT;
+ elementValueList(ctx: ElementValueListCtx, param?: IN): OUT;
+ identifyInterfaceBodyDeclarationType(
+ ctx: IdentifyInterfaceBodyDeclarationTypeCtx,
+ param?: IN
+ ): OUT;
+ identifyAnnotationBodyDeclarationType(
+ ctx: IdentifyAnnotationBodyDeclarationTypeCtx,
+ param?: IN
+ ): OUT;
+ isSimpleElementValueAnnotation(
+ ctx: IsSimpleElementValueAnnotationCtx,
+ param?: IN
+ ): OUT;
+ arrayInitializer(ctx: ArrayInitializerCtx, param?: IN): OUT;
+ variableInitializerList(ctx: VariableInitializerListCtx, param?: IN): OUT;
+ block(ctx: BlockCtx, param?: IN): OUT;
+ blockStatements(ctx: BlockStatementsCtx, param?: IN): OUT;
+ blockStatement(ctx: BlockStatementCtx, param?: IN): OUT;
+ localVariableDeclarationStatement(
+ ctx: LocalVariableDeclarationStatementCtx,
+ param?: IN
+ ): OUT;
+ localVariableDeclaration(ctx: LocalVariableDeclarationCtx, param?: IN): OUT;
+ localVariableType(ctx: LocalVariableTypeCtx, param?: IN): OUT;
+ statement(ctx: StatementCtx, param?: IN): OUT;
+ statementWithoutTrailingSubstatement(
+ ctx: StatementWithoutTrailingSubstatementCtx,
+ param?: IN
+ ): OUT;
+ emptyStatement(ctx: EmptyStatementCtx, param?: IN): OUT;
+ labeledStatement(ctx: LabeledStatementCtx, param?: IN): OUT;
+ expressionStatement(ctx: ExpressionStatementCtx, param?: IN): OUT;
+ statementExpression(ctx: StatementExpressionCtx, param?: IN): OUT;
+ ifStatement(ctx: IfStatementCtx, param?: IN): OUT;
+ assertStatement(ctx: AssertStatementCtx, param?: IN): OUT;
+ switchStatement(ctx: SwitchStatementCtx, param?: IN): OUT;
+ switchBlock(ctx: SwitchBlockCtx, param?: IN): OUT;
+ switchBlockStatementGroup(ctx: SwitchBlockStatementGroupCtx, param?: IN): OUT;
+ switchLabel(ctx: SwitchLabelCtx, param?: IN): OUT;
+ switchRule(ctx: SwitchRuleCtx, param?: IN): OUT;
+ caseConstant(ctx: CaseConstantCtx, param?: IN): OUT;
+ whileStatement(ctx: WhileStatementCtx, param?: IN): OUT;
+ doStatement(ctx: DoStatementCtx, param?: IN): OUT;
+ forStatement(ctx: ForStatementCtx, param?: IN): OUT;
+ basicForStatement(ctx: BasicForStatementCtx, param?: IN): OUT;
+ forInit(ctx: ForInitCtx, param?: IN): OUT;
+ forUpdate(ctx: ForUpdateCtx, param?: IN): OUT;
+ statementExpressionList(ctx: StatementExpressionListCtx, param?: IN): OUT;
+ enhancedForStatement(ctx: EnhancedForStatementCtx, param?: IN): OUT;
+ breakStatement(ctx: BreakStatementCtx, param?: IN): OUT;
+ continueStatement(ctx: ContinueStatementCtx, param?: IN): OUT;
+ returnStatement(ctx: ReturnStatementCtx, param?: IN): OUT;
+ throwStatement(ctx: ThrowStatementCtx, param?: IN): OUT;
+ synchronizedStatement(ctx: SynchronizedStatementCtx, param?: IN): OUT;
+ tryStatement(ctx: TryStatementCtx, param?: IN): OUT;
+ catches(ctx: CatchesCtx, param?: IN): OUT;
+ catchClause(ctx: CatchClauseCtx, param?: IN): OUT;
+ catchFormalParameter(ctx: CatchFormalParameterCtx, param?: IN): OUT;
+ catchType(ctx: CatchTypeCtx, param?: IN): OUT;
+ finally(ctx: FinallyCtx, param?: IN): OUT;
+ tryWithResourcesStatement(ctx: TryWithResourcesStatementCtx, param?: IN): OUT;
+ resourceSpecification(ctx: ResourceSpecificationCtx, param?: IN): OUT;
+ resourceList(ctx: ResourceListCtx, param?: IN): OUT;
+ resource(ctx: ResourceCtx, param?: IN): OUT;
+ resourceInit(ctx: ResourceInitCtx, param?: IN): OUT;
+ yieldStatement(ctx: YieldStatementCtx, param?: IN): OUT;
+ variableAccess(ctx: VariableAccessCtx, param?: IN): OUT;
+ isBasicForStatement(ctx: IsBasicForStatementCtx, param?: IN): OUT;
+ isLocalVariableDeclaration(
+ ctx: IsLocalVariableDeclarationCtx,
+ param?: IN
+ ): OUT;
+ isClassicSwitchLabel(ctx: IsClassicSwitchLabelCtx, param?: IN): OUT;
+ expression(ctx: ExpressionCtx, param?: IN): OUT;
+ lambdaExpression(ctx: LambdaExpressionCtx, param?: IN): OUT;
+ lambdaParameters(ctx: LambdaParametersCtx, param?: IN): OUT;
+ lambdaParametersWithBraces(
+ ctx: LambdaParametersWithBracesCtx,
+ param?: IN
+ ): OUT;
+ lambdaParameterList(ctx: LambdaParameterListCtx, param?: IN): OUT;
+ inferredLambdaParameterList(
+ ctx: InferredLambdaParameterListCtx,
+ param?: IN
+ ): OUT;
+ explicitLambdaParameterList(
+ ctx: ExplicitLambdaParameterListCtx,
+ param?: IN
+ ): OUT;
+ lambdaParameter(ctx: LambdaParameterCtx, param?: IN): OUT;
+ regularLambdaParameter(ctx: RegularLambdaParameterCtx, param?: IN): OUT;
+ lambdaParameterType(ctx: LambdaParameterTypeCtx, param?: IN): OUT;
+ lambdaBody(ctx: LambdaBodyCtx, param?: IN): OUT;
+ ternaryExpression(ctx: TernaryExpressionCtx, param?: IN): OUT;
+ binaryExpression(ctx: BinaryExpressionCtx, param?: IN): OUT;
+ unaryExpression(ctx: UnaryExpressionCtx, param?: IN): OUT;
+ unaryExpressionNotPlusMinus(
+ ctx: UnaryExpressionNotPlusMinusCtx,
+ param?: IN
+ ): OUT;
+ primary(ctx: PrimaryCtx, param?: IN): OUT;
+ primaryPrefix(ctx: PrimaryPrefixCtx, param?: IN): OUT;
+ primarySuffix(ctx: PrimarySuffixCtx, param?: IN): OUT;
+ fqnOrRefType(ctx: FqnOrRefTypeCtx, param?: IN): OUT;
+ fqnOrRefTypePartRest(ctx: FqnOrRefTypePartRestCtx, param?: IN): OUT;
+ fqnOrRefTypePartCommon(ctx: FqnOrRefTypePartCommonCtx, param?: IN): OUT;
+ fqnOrRefTypePartFirst(ctx: FqnOrRefTypePartFirstCtx, param?: IN): OUT;
+ parenthesisExpression(ctx: ParenthesisExpressionCtx, param?: IN): OUT;
+ castExpression(ctx: CastExpressionCtx, param?: IN): OUT;
+ primitiveCastExpression(ctx: PrimitiveCastExpressionCtx, param?: IN): OUT;
+ referenceTypeCastExpression(
+ ctx: ReferenceTypeCastExpressionCtx,
+ param?: IN
+ ): OUT;
+ newExpression(ctx: NewExpressionCtx, param?: IN): OUT;
+ unqualifiedClassInstanceCreationExpression(
+ ctx: UnqualifiedClassInstanceCreationExpressionCtx,
+ param?: IN
+ ): OUT;
+ classOrInterfaceTypeToInstantiate(
+ ctx: ClassOrInterfaceTypeToInstantiateCtx,
+ param?: IN
+ ): OUT;
+ typeArgumentsOrDiamond(ctx: TypeArgumentsOrDiamondCtx, param?: IN): OUT;
+ diamond(ctx: DiamondCtx, param?: IN): OUT;
+ methodInvocationSuffix(ctx: MethodInvocationSuffixCtx, param?: IN): OUT;
+ argumentList(ctx: ArgumentListCtx, param?: IN): OUT;
+ arrayCreationExpression(ctx: ArrayCreationExpressionCtx, param?: IN): OUT;
+ arrayCreationDefaultInitSuffix(
+ ctx: ArrayCreationDefaultInitSuffixCtx,
+ param?: IN
+ ): OUT;
+ arrayCreationExplicitInitSuffix(
+ ctx: ArrayCreationExplicitInitSuffixCtx,
+ param?: IN
+ ): OUT;
+ dimExprs(ctx: DimExprsCtx, param?: IN): OUT;
+ dimExpr(ctx: DimExprCtx, param?: IN): OUT;
+ classLiteralSuffix(ctx: ClassLiteralSuffixCtx, param?: IN): OUT;
+ arrayAccessSuffix(ctx: ArrayAccessSuffixCtx, param?: IN): OUT;
+ methodReferenceSuffix(ctx: MethodReferenceSuffixCtx, param?: IN): OUT;
+ pattern(ctx: PatternCtx, param?: IN): OUT;
+ typePattern(ctx: TypePatternCtx, param?: IN): OUT;
+ identifyNewExpressionType(ctx: IdentifyNewExpressionTypeCtx, param?: IN): OUT;
+ isLambdaExpression(ctx: IsLambdaExpressionCtx, param?: IN): OUT;
+ isCastExpression(ctx: IsCastExpressionCtx, param?: IN): OUT;
+ isPrimitiveCastExpression(ctx: IsPrimitiveCastExpressionCtx, param?: IN): OUT;
+ isReferenceTypeCastExpression(
+ ctx: IsReferenceTypeCastExpressionCtx,
+ param?: IN
+ ): OUT;
+ isRefTypeInMethodRef(ctx: IsRefTypeInMethodRefCtx, param?: IN): OUT;
+}
+
+interface JavaCstVisitorWithDefaultsConstructor {
+ new (): JavaCstVisitorWithDefaults;
+}
+export interface TypeIdentifierCstNode extends CstNode {
+ name: "typeIdentifier";
+ children: TypeIdentifierCtx;
+}
+
+export type TypeIdentifierCtx = {
+ Identifier: IToken[];
+};
+
+export interface LiteralCstNode extends CstNode {
+ name: "literal";
+ children: LiteralCtx;
+}
+
+export type LiteralCtx = {
+ integerLiteral?: IntegerLiteralCstNode[];
+ floatingPointLiteral?: FloatingPointLiteralCstNode[];
+ booleanLiteral?: BooleanLiteralCstNode[];
+ CharLiteral?: IToken[];
+ TextBlock?: IToken[];
+ StringLiteral?: IToken[];
+ Null?: IToken[];
+};
+
+export interface IntegerLiteralCstNode extends CstNode {
+ name: "integerLiteral";
+ children: IntegerLiteralCtx;
+}
+
+export type IntegerLiteralCtx = {
+ DecimalLiteral?: IToken[];
+ HexLiteral?: IToken[];
+ OctalLiteral?: IToken[];
+ BinaryLiteral?: IToken[];
+};
+
+export interface FloatingPointLiteralCstNode extends CstNode {
+ name: "floatingPointLiteral";
+ children: FloatingPointLiteralCtx;
+}
+
+export type FloatingPointLiteralCtx = {
+ FloatLiteral?: IToken[];
+ HexFloatLiteral?: IToken[];
+};
+
+export interface BooleanLiteralCstNode extends CstNode {
+ name: "booleanLiteral";
+ children: BooleanLiteralCtx;
+}
+
+export type BooleanLiteralCtx = {
+ True?: IToken[];
+ False?: IToken[];
+};
+
+export interface PrimitiveTypeCstNode extends CstNode {
+ name: "primitiveType";
+ children: PrimitiveTypeCtx;
+}
+
+export type PrimitiveTypeCtx = {
+ annotation?: AnnotationCstNode[];
+ numericType?: NumericTypeCstNode[];
+ Boolean?: IToken[];
+};
+
+export interface NumericTypeCstNode extends CstNode {
+ name: "numericType";
+ children: NumericTypeCtx;
+}
+
+export type NumericTypeCtx = {
+ integralType?: IntegralTypeCstNode[];
+ floatingPointType?: FloatingPointTypeCstNode[];
+};
+
+export interface IntegralTypeCstNode extends CstNode {
+ name: "integralType";
+ children: IntegralTypeCtx;
+}
+
+export type IntegralTypeCtx = {
+ Byte?: IToken[];
+ Short?: IToken[];
+ Int?: IToken[];
+ Long?: IToken[];
+ Char?: IToken[];
+};
+
+export interface FloatingPointTypeCstNode extends CstNode {
+ name: "floatingPointType";
+ children: FloatingPointTypeCtx;
+}
+
+export type FloatingPointTypeCtx = {
+ Float?: IToken[];
+ Double?: IToken[];
+};
+
+export interface ReferenceTypeCstNode extends CstNode {
+ name: "referenceType";
+ children: ReferenceTypeCtx;
+}
+
+export type ReferenceTypeCtx = {
+ annotation?: AnnotationCstNode[];
+ primitiveType?: PrimitiveTypeCstNode[];
+ dims?: DimsCstNode[];
+ classOrInterfaceType?: ClassOrInterfaceTypeCstNode[];
+};
+
+export interface ClassOrInterfaceTypeCstNode extends CstNode {
+ name: "classOrInterfaceType";
+ children: ClassOrInterfaceTypeCtx;
+}
+
+export type ClassOrInterfaceTypeCtx = {
+ classType: ClassTypeCstNode[];
+};
+
+export interface ClassTypeCstNode extends CstNode {
+ name: "classType";
+ children: ClassTypeCtx;
+}
+
+export type ClassTypeCtx = {
+ annotation?: AnnotationCstNode[];
+ Identifier: IToken[];
+ typeArguments?: TypeArgumentsCstNode[];
+ Dot?: IToken[];
+};
+
+export interface InterfaceTypeCstNode extends CstNode {
+ name: "interfaceType";
+ children: InterfaceTypeCtx;
+}
+
+export type InterfaceTypeCtx = {
+ classType: ClassTypeCstNode[];
+};
+
+export interface TypeVariableCstNode extends CstNode {
+ name: "typeVariable";
+ children: TypeVariableCtx;
+}
+
+export type TypeVariableCtx = {
+ annotation?: AnnotationCstNode[];
+ Identifier: IToken[];
+};
+
+export interface DimsCstNode extends CstNode {
+ name: "dims";
+ children: DimsCtx;
+}
+
+export type DimsCtx = {
+ annotation?: AnnotationCstNode[];
+ LSquare: IToken[];
+ RSquare: IToken[];
+};
+
+export interface TypeParameterCstNode extends CstNode {
+ name: "typeParameter";
+ children: TypeParameterCtx;
+}
+
+export type TypeParameterCtx = {
+ typeParameterModifier?: TypeParameterModifierCstNode[];
+ typeIdentifier: TypeIdentifierCstNode[];
+ typeBound?: TypeBoundCstNode[];
+};
+
+export interface TypeParameterModifierCstNode extends CstNode {
+ name: "typeParameterModifier";
+ children: TypeParameterModifierCtx;
+}
+
+export type TypeParameterModifierCtx = {
+ annotation: AnnotationCstNode[];
+};
+
+export interface TypeBoundCstNode extends CstNode {
+ name: "typeBound";
+ children: TypeBoundCtx;
+}
+
+export type TypeBoundCtx = {
+ Extends: IToken[];
+ classOrInterfaceType: ClassOrInterfaceTypeCstNode[];
+ additionalBound?: AdditionalBoundCstNode[];
+};
+
+export interface AdditionalBoundCstNode extends CstNode {
+ name: "additionalBound";
+ children: AdditionalBoundCtx;
+}
+
+export type AdditionalBoundCtx = {
+ And: IToken[];
+ interfaceType: InterfaceTypeCstNode[];
+};
+
+export interface TypeArgumentsCstNode extends CstNode {
+ name: "typeArguments";
+ children: TypeArgumentsCtx;
+}
+
+export type TypeArgumentsCtx = {
+ Less: IToken[];
+ typeArgumentList: TypeArgumentListCstNode[];
+ Greater: IToken[];
+};
+
+export interface TypeArgumentListCstNode extends CstNode {
+ name: "typeArgumentList";
+ children: TypeArgumentListCtx;
+}
+
+export type TypeArgumentListCtx = {
+ typeArgument: TypeArgumentCstNode[];
+ Comma?: IToken[];
+};
+
+export interface TypeArgumentCstNode extends CstNode {
+ name: "typeArgument";
+ children: TypeArgumentCtx;
+}
+
+export type TypeArgumentCtx = {
+ referenceType?: ReferenceTypeCstNode[];
+ wildcard?: WildcardCstNode[];
+};
+
+export interface WildcardCstNode extends CstNode {
+ name: "wildcard";
+ children: WildcardCtx;
+}
+
+export type WildcardCtx = {
+ annotation?: AnnotationCstNode[];
+ QuestionMark: IToken[];
+ wildcardBounds?: WildcardBoundsCstNode[];
+};
+
+export interface WildcardBoundsCstNode extends CstNode {
+ name: "wildcardBounds";
+ children: WildcardBoundsCtx;
+}
+
+export type WildcardBoundsCtx = {
+ Extends?: IToken[];
+ Super?: IToken[];
+ referenceType: ReferenceTypeCstNode[];
+};
+
+export interface ModuleNameCstNode extends CstNode {
+ name: "moduleName";
+ children: ModuleNameCtx;
+}
+
+export type ModuleNameCtx = {
+ Identifier: IToken[];
+ Dot?: IToken[];
+};
+
+export interface PackageNameCstNode extends CstNode {
+ name: "packageName";
+ children: PackageNameCtx;
+}
+
+export type PackageNameCtx = {
+ Identifier: IToken[];
+ Dot?: IToken[];
+};
+
+export interface TypeNameCstNode extends CstNode {
+ name: "typeName";
+ children: TypeNameCtx;
+}
+
+export type TypeNameCtx = {
+ Identifier: IToken[];
+ Dot?: IToken[];
+};
+
+export interface ExpressionNameCstNode extends CstNode {
+ name: "expressionName";
+ children: ExpressionNameCtx;
+}
+
+export type ExpressionNameCtx = {
+ Identifier: IToken[];
+ Dot?: IToken[];
+};
+
+export interface MethodNameCstNode extends CstNode {
+ name: "methodName";
+ children: MethodNameCtx;
+}
+
+export type MethodNameCtx = {
+ Identifier: IToken[];
+};
+
+export interface PackageOrTypeNameCstNode extends CstNode {
+ name: "packageOrTypeName";
+ children: PackageOrTypeNameCtx;
+}
+
+export type PackageOrTypeNameCtx = {
+ Identifier: IToken[];
+ Dot?: IToken[];
+};
+
+export interface AmbiguousNameCstNode extends CstNode {
+ name: "ambiguousName";
+ children: AmbiguousNameCtx;
+}
+
+export type AmbiguousNameCtx = {
+ Identifier: IToken[];
+ Dot?: IToken[];
+};
+
+export interface ClassDeclarationCstNode extends CstNode {
+ name: "classDeclaration";
+ children: ClassDeclarationCtx;
+}
+
+export type ClassDeclarationCtx = {
+ classModifier?: ClassModifierCstNode[];
+ normalClassDeclaration?: NormalClassDeclarationCstNode[];
+ enumDeclaration?: EnumDeclarationCstNode[];
+ recordDeclaration?: RecordDeclarationCstNode[];
+};
+
+export interface NormalClassDeclarationCstNode extends CstNode {
+ name: "normalClassDeclaration";
+ children: NormalClassDeclarationCtx;
+}
+
+export type NormalClassDeclarationCtx = {
+ Class: IToken[];
+ typeIdentifier: TypeIdentifierCstNode[];
+ typeParameters?: TypeParametersCstNode[];
+ superclass?: SuperclassCstNode[];
+ superinterfaces?: SuperinterfacesCstNode[];
+ classPermits?: ClassPermitsCstNode[];
+ classBody: ClassBodyCstNode[];
+};
+
+export interface ClassModifierCstNode extends CstNode {
+ name: "classModifier";
+ children: ClassModifierCtx;
+}
+
+export type ClassModifierCtx = {
+ annotation?: AnnotationCstNode[];
+ Public?: IToken[];
+ Protected?: IToken[];
+ Private?: IToken[];
+ Abstract?: IToken[];
+ Static?: IToken[];
+ Final?: IToken[];
+ Sealed?: IToken[];
+ NonSealed?: IToken[];
+ Strictfp?: IToken[];
+};
+
+export interface TypeParametersCstNode extends CstNode {
+ name: "typeParameters";
+ children: TypeParametersCtx;
+}
+
+export type TypeParametersCtx = {
+ Less: IToken[];
+ typeParameterList: TypeParameterListCstNode[];
+ Greater: IToken[];
+};
+
+export interface TypeParameterListCstNode extends CstNode {
+ name: "typeParameterList";
+ children: TypeParameterListCtx;
+}
+
+export type TypeParameterListCtx = {
+ typeParameter: TypeParameterCstNode[];
+ Comma?: IToken[];
+};
+
+export interface SuperclassCstNode extends CstNode {
+ name: "superclass";
+ children: SuperclassCtx;
+}
+
+export type SuperclassCtx = {
+ Extends: IToken[];
+ classType: ClassTypeCstNode[];
+};
+
+export interface SuperinterfacesCstNode extends CstNode {
+ name: "superinterfaces";
+ children: SuperinterfacesCtx;
+}
+
+export type SuperinterfacesCtx = {
+ Implements: IToken[];
+ interfaceTypeList: InterfaceTypeListCstNode[];
+};
+
+export interface InterfaceTypeListCstNode extends CstNode {
+ name: "interfaceTypeList";
+ children: InterfaceTypeListCtx;
+}
+
+export type InterfaceTypeListCtx = {
+ interfaceType: InterfaceTypeCstNode[];
+ Comma?: IToken[];
+};
+
+export interface ClassPermitsCstNode extends CstNode {
+ name: "classPermits";
+ children: ClassPermitsCtx;
+}
+
+export type ClassPermitsCtx = {
+ Permits: IToken[];
+ typeName: TypeNameCstNode[];
+ Comma?: IToken[];
+};
+
+export interface ClassBodyCstNode extends CstNode {
+ name: "classBody";
+ children: ClassBodyCtx;
+}
+
+export type ClassBodyCtx = {
+ LCurly: IToken[];
+ classBodyDeclaration?: ClassBodyDeclarationCstNode[];
+ RCurly: IToken[];
+};
+
+export interface ClassBodyDeclarationCstNode extends CstNode {
+ name: "classBodyDeclaration";
+ children: ClassBodyDeclarationCtx;
+}
+
+export type ClassBodyDeclarationCtx = {
+ classMemberDeclaration?: ClassMemberDeclarationCstNode[];
+ instanceInitializer?: InstanceInitializerCstNode[];
+ staticInitializer?: StaticInitializerCstNode[];
+ constructorDeclaration?: ConstructorDeclarationCstNode[];
+};
+
+export interface ClassMemberDeclarationCstNode extends CstNode {
+ name: "classMemberDeclaration";
+ children: ClassMemberDeclarationCtx;
+}
+
+export type ClassMemberDeclarationCtx = {
+ fieldDeclaration?: FieldDeclarationCstNode[];
+ methodDeclaration?: MethodDeclarationCstNode[];
+ classDeclaration?: ClassDeclarationCstNode[];
+ interfaceDeclaration?: InterfaceDeclarationCstNode[];
+ Semicolon?: IToken[];
+};
+
+export interface FieldDeclarationCstNode extends CstNode {
+ name: "fieldDeclaration";
+ children: FieldDeclarationCtx;
+}
+
+export type FieldDeclarationCtx = {
+ fieldModifier?: FieldModifierCstNode[];
+ unannType: UnannTypeCstNode[];
+ variableDeclaratorList: VariableDeclaratorListCstNode[];
+ Semicolon: IToken[];
+};
+
+export interface FieldModifierCstNode extends CstNode {
+ name: "fieldModifier";
+ children: FieldModifierCtx;
+}
+
+export type FieldModifierCtx = {
+ annotation?: AnnotationCstNode[];
+ Public?: IToken[];
+ Protected?: IToken[];
+ Private?: IToken[];
+ Static?: IToken[];
+ Final?: IToken[];
+ Transient?: IToken[];
+ Volatile?: IToken[];
+};
+
+export interface VariableDeclaratorListCstNode extends CstNode {
+ name: "variableDeclaratorList";
+ children: VariableDeclaratorListCtx;
+}
+
+export type VariableDeclaratorListCtx = {
+ variableDeclarator: VariableDeclaratorCstNode[];
+ Comma?: IToken[];
+};
+
+export interface VariableDeclaratorCstNode extends CstNode {
+ name: "variableDeclarator";
+ children: VariableDeclaratorCtx;
+}
+
+export type VariableDeclaratorCtx = {
+ variableDeclaratorId: VariableDeclaratorIdCstNode[];
+ Equals?: IToken[];
+ variableInitializer?: VariableInitializerCstNode[];
+};
+
+export interface VariableDeclaratorIdCstNode extends CstNode {
+ name: "variableDeclaratorId";
+ children: VariableDeclaratorIdCtx;
+}
+
+export type VariableDeclaratorIdCtx = {
+ Identifier: IToken[];
+ dims?: DimsCstNode[];
+};
+
+export interface VariableInitializerCstNode extends CstNode {
+ name: "variableInitializer";
+ children: VariableInitializerCtx;
+}
+
+export type VariableInitializerCtx = {
+ expression?: ExpressionCstNode[];
+ arrayInitializer?: ArrayInitializerCstNode[];
+};
+
+export interface UnannTypeCstNode extends CstNode {
+ name: "unannType";
+ children: UnannTypeCtx;
+}
+
+export type UnannTypeCtx = {
+ unannPrimitiveTypeWithOptionalDimsSuffix?: UnannPrimitiveTypeWithOptionalDimsSuffixCstNode[];
+ unannReferenceType?: UnannReferenceTypeCstNode[];
+};
+
+export interface UnannPrimitiveTypeWithOptionalDimsSuffixCstNode
+ extends CstNode {
+ name: "unannPrimitiveTypeWithOptionalDimsSuffix";
+ children: UnannPrimitiveTypeWithOptionalDimsSuffixCtx;
+}
+
+export type UnannPrimitiveTypeWithOptionalDimsSuffixCtx = {
+ unannPrimitiveType: UnannPrimitiveTypeCstNode[];
+ dims?: DimsCstNode[];
+};
+
+export interface UnannPrimitiveTypeCstNode extends CstNode {
+ name: "unannPrimitiveType";
+ children: UnannPrimitiveTypeCtx;
+}
+
+export type UnannPrimitiveTypeCtx = {
+ numericType?: NumericTypeCstNode[];
+ Boolean?: IToken[];
+};
+
+export interface UnannReferenceTypeCstNode extends CstNode {
+ name: "unannReferenceType";
+ children: UnannReferenceTypeCtx;
+}
+
+export type UnannReferenceTypeCtx = {
+ unannClassOrInterfaceType: UnannClassOrInterfaceTypeCstNode[];
+ dims?: DimsCstNode[];
+};
+
+export interface UnannClassOrInterfaceTypeCstNode extends CstNode {
+ name: "unannClassOrInterfaceType";
+ children: UnannClassOrInterfaceTypeCtx;
+}
+
+export type UnannClassOrInterfaceTypeCtx = {
+ unannClassType: UnannClassTypeCstNode[];
+};
+
+export interface UnannClassTypeCstNode extends CstNode {
+ name: "unannClassType";
+ children: UnannClassTypeCtx;
+}
+
+export type UnannClassTypeCtx = {
+ Identifier: IToken[];
+ typeArguments?: TypeArgumentsCstNode[];
+ Dot?: IToken[];
+ annotation?: AnnotationCstNode[];
+};
+
+export interface UnannInterfaceTypeCstNode extends CstNode {
+ name: "unannInterfaceType";
+ children: UnannInterfaceTypeCtx;
+}
+
+export type UnannInterfaceTypeCtx = {
+ unannClassType: UnannClassTypeCstNode[];
+};
+
+export interface UnannTypeVariableCstNode extends CstNode {
+ name: "unannTypeVariable";
+ children: UnannTypeVariableCtx;
+}
+
+export type UnannTypeVariableCtx = {
+ Identifier: IToken[];
+};
+
+export interface MethodDeclarationCstNode extends CstNode {
+ name: "methodDeclaration";
+ children: MethodDeclarationCtx;
+}
+
+export type MethodDeclarationCtx = {
+ methodModifier?: MethodModifierCstNode[];
+ methodHeader: MethodHeaderCstNode[];
+ methodBody: MethodBodyCstNode[];
+};
+
+export interface MethodModifierCstNode extends CstNode {
+ name: "methodModifier";
+ children: MethodModifierCtx;
+}
+
+export type MethodModifierCtx = {
+ annotation?: AnnotationCstNode[];
+ Public?: IToken[];
+ Protected?: IToken[];
+ Private?: IToken[];
+ Abstract?: IToken[];
+ Static?: IToken[];
+ Final?: IToken[];
+ Synchronized?: IToken[];
+ Native?: IToken[];
+ Strictfp?: IToken[];
+};
+
+export interface MethodHeaderCstNode extends CstNode {
+ name: "methodHeader";
+ children: MethodHeaderCtx;
+}
+
+export type MethodHeaderCtx = {
+ typeParameters?: TypeParametersCstNode[];
+ annotation?: AnnotationCstNode[];
+ result: ResultCstNode[];
+ methodDeclarator: MethodDeclaratorCstNode[];
+ throws?: ThrowsCstNode[];
+};
+
+export interface ResultCstNode extends CstNode {
+ name: "result";
+ children: ResultCtx;
+}
+
+export type ResultCtx = {
+ unannType?: UnannTypeCstNode[];
+ Void?: IToken[];
+};
+
+export interface MethodDeclaratorCstNode extends CstNode {
+ name: "methodDeclarator";
+ children: MethodDeclaratorCtx;
+}
+
+export type MethodDeclaratorCtx = {
+ Identifier: IToken[];
+ LBrace: IToken[];
+ formalParameterList?: FormalParameterListCstNode[];
+ RBrace: IToken[];
+ dims?: DimsCstNode[];
+};
+
+export interface ReceiverParameterCstNode extends CstNode {
+ name: "receiverParameter";
+ children: ReceiverParameterCtx;
+}
+
+export type ReceiverParameterCtx = {
+ annotation?: AnnotationCstNode[];
+ unannType: UnannTypeCstNode[];
+ Identifier?: IToken[];
+ Dot?: IToken[];
+ This: IToken[];
+};
+
+export interface FormalParameterListCstNode extends CstNode {
+ name: "formalParameterList";
+ children: FormalParameterListCtx;
+}
+
+export type FormalParameterListCtx = {
+ formalParameter: FormalParameterCstNode[];
+ Comma?: IToken[];
+};
+
+export interface FormalParameterCstNode extends CstNode {
+ name: "formalParameter";
+ children: FormalParameterCtx;
+}
+
+export type FormalParameterCtx = {
+ variableParaRegularParameter?: VariableParaRegularParameterCstNode[];
+ variableArityParameter?: VariableArityParameterCstNode[];
+};
+
+export interface VariableParaRegularParameterCstNode extends CstNode {
+ name: "variableParaRegularParameter";
+ children: VariableParaRegularParameterCtx;
+}
+
+export type VariableParaRegularParameterCtx = {
+ variableModifier?: VariableModifierCstNode[];
+ unannType: UnannTypeCstNode[];
+ variableDeclaratorId: VariableDeclaratorIdCstNode[];
+};
+
+export interface VariableArityParameterCstNode extends CstNode {
+ name: "variableArityParameter";
+ children: VariableArityParameterCtx;
+}
+
+export type VariableArityParameterCtx = {
+ variableModifier?: VariableModifierCstNode[];
+ unannType: UnannTypeCstNode[];
+ annotation?: AnnotationCstNode[];
+ DotDotDot: IToken[];
+ Identifier: IToken[];
+};
+
+export interface VariableModifierCstNode extends CstNode {
+ name: "variableModifier";
+ children: VariableModifierCtx;
+}
+
+export type VariableModifierCtx = {
+ annotation?: AnnotationCstNode[];
+ Final?: IToken[];
+};
+
+export interface ThrowsCstNode extends CstNode {
+ name: "throws";
+ children: ThrowsCtx;
+}
+
+export type ThrowsCtx = {
+ Throws: IToken[];
+ exceptionTypeList: ExceptionTypeListCstNode[];
+};
+
+export interface ExceptionTypeListCstNode extends CstNode {
+ name: "exceptionTypeList";
+ children: ExceptionTypeListCtx;
+}
+
+export type ExceptionTypeListCtx = {
+ exceptionType: ExceptionTypeCstNode[];
+ Comma?: IToken[];
+};
+
+export interface ExceptionTypeCstNode extends CstNode {
+ name: "exceptionType";
+ children: ExceptionTypeCtx;
+}
+
+export type ExceptionTypeCtx = {
+ classType: ClassTypeCstNode[];
+};
+
+export interface MethodBodyCstNode extends CstNode {
+ name: "methodBody";
+ children: MethodBodyCtx;
+}
+
+export type MethodBodyCtx = {
+ block?: BlockCstNode[];
+ Semicolon?: IToken[];
+};
+
+export interface InstanceInitializerCstNode extends CstNode {
+ name: "instanceInitializer";
+ children: InstanceInitializerCtx;
+}
+
+export type InstanceInitializerCtx = {
+ block: BlockCstNode[];
+};
+
+export interface StaticInitializerCstNode extends CstNode {
+ name: "staticInitializer";
+ children: StaticInitializerCtx;
+}
+
+export type StaticInitializerCtx = {
+ Static: IToken[];
+ block: BlockCstNode[];
+};
+
+export interface ConstructorDeclarationCstNode extends CstNode {
+ name: "constructorDeclaration";
+ children: ConstructorDeclarationCtx;
+}
+
+export type ConstructorDeclarationCtx = {
+ constructorModifier?: ConstructorModifierCstNode[];
+ constructorDeclarator: ConstructorDeclaratorCstNode[];
+ throws?: ThrowsCstNode[];
+ constructorBody: ConstructorBodyCstNode[];
+};
+
+export interface ConstructorModifierCstNode extends CstNode {
+ name: "constructorModifier";
+ children: ConstructorModifierCtx;
+}
+
+export type ConstructorModifierCtx = {
+ annotation?: AnnotationCstNode[];
+ Public?: IToken[];
+ Protected?: IToken[];
+ Private?: IToken[];
+};
+
+export interface ConstructorDeclaratorCstNode extends CstNode {
+ name: "constructorDeclarator";
+ children: ConstructorDeclaratorCtx;
+}
+
+export type ConstructorDeclaratorCtx = {
+ typeParameters?: TypeParametersCstNode[];
+ simpleTypeName: SimpleTypeNameCstNode[];
+ LBrace: IToken[];
+ receiverParameter?: ReceiverParameterCstNode[];
+ Comma?: IToken[];
+ formalParameterList?: FormalParameterListCstNode[];
+ RBrace: IToken[];
+};
+
+export interface SimpleTypeNameCstNode extends CstNode {
+ name: "simpleTypeName";
+ children: SimpleTypeNameCtx;
+}
+
+export type SimpleTypeNameCtx = {
+ Identifier: IToken[];
+};
+
+export interface ConstructorBodyCstNode extends CstNode {
+ name: "constructorBody";
+ children: ConstructorBodyCtx;
+}
+
+export type ConstructorBodyCtx = {
+ LCurly: IToken[];
+ explicitConstructorInvocation?: ExplicitConstructorInvocationCstNode[];
+ blockStatements?: BlockStatementsCstNode[];
+ RCurly: IToken[];
+};
+
+export interface ExplicitConstructorInvocationCstNode extends CstNode {
+ name: "explicitConstructorInvocation";
+ children: ExplicitConstructorInvocationCtx;
+}
+
+export type ExplicitConstructorInvocationCtx = {
+ unqualifiedExplicitConstructorInvocation?: UnqualifiedExplicitConstructorInvocationCstNode[];
+ qualifiedExplicitConstructorInvocation?: QualifiedExplicitConstructorInvocationCstNode[];
+};
+
+export interface UnqualifiedExplicitConstructorInvocationCstNode
+ extends CstNode {
+ name: "unqualifiedExplicitConstructorInvocation";
+ children: UnqualifiedExplicitConstructorInvocationCtx;
+}
+
+export type UnqualifiedExplicitConstructorInvocationCtx = {
+ typeArguments?: TypeArgumentsCstNode[];
+ This?: IToken[];
+ Super?: IToken[];
+ LBrace: IToken[];
+ argumentList?: ArgumentListCstNode[];
+ RBrace: IToken[];
+ Semicolon: IToken[];
+};
+
+export interface QualifiedExplicitConstructorInvocationCstNode extends CstNode {
+ name: "qualifiedExplicitConstructorInvocation";
+ children: QualifiedExplicitConstructorInvocationCtx;
+}
+
+export type QualifiedExplicitConstructorInvocationCtx = {
+ expressionName: ExpressionNameCstNode[];
+ Dot: IToken[];
+ typeArguments?: TypeArgumentsCstNode[];
+ Super: IToken[];
+ LBrace: IToken[];
+ argumentList?: ArgumentListCstNode[];
+ RBrace: IToken[];
+ Semicolon: IToken[];
+};
+
+export interface EnumDeclarationCstNode extends CstNode {
+ name: "enumDeclaration";
+ children: EnumDeclarationCtx;
+}
+
+export type EnumDeclarationCtx = {
+ classModifier?: ClassModifierCstNode[];
+ Enum: IToken[];
+ typeIdentifier: TypeIdentifierCstNode[];
+ superinterfaces?: SuperinterfacesCstNode[];
+ enumBody: EnumBodyCstNode[];
+};
+
+export interface EnumBodyCstNode extends CstNode {
+ name: "enumBody";
+ children: EnumBodyCtx;
+}
+
+export type EnumBodyCtx = {
+ LCurly: IToken[];
+ enumConstantList?: EnumConstantListCstNode[];
+ Comma?: IToken[];
+ enumBodyDeclarations?: EnumBodyDeclarationsCstNode[];
+ RCurly: IToken[];
+};
+
+export interface EnumConstantListCstNode extends CstNode {
+ name: "enumConstantList";
+ children: EnumConstantListCtx;
+}
+
+export type EnumConstantListCtx = {
+ enumConstant: EnumConstantCstNode[];
+ Comma?: IToken[];
+};
+
+export interface EnumConstantCstNode extends CstNode {
+ name: "enumConstant";
+ children: EnumConstantCtx;
+}
+
+export type EnumConstantCtx = {
+ enumConstantModifier?: EnumConstantModifierCstNode[];
+ Identifier: IToken[];
+ LBrace?: IToken[];
+ argumentList?: ArgumentListCstNode[];
+ RBrace?: IToken[];
+ classBody?: ClassBodyCstNode[];
+};
+
+export interface EnumConstantModifierCstNode extends CstNode {
+ name: "enumConstantModifier";
+ children: EnumConstantModifierCtx;
+}
+
+export type EnumConstantModifierCtx = {
+ annotation: AnnotationCstNode[];
+};
+
+export interface EnumBodyDeclarationsCstNode extends CstNode {
+ name: "enumBodyDeclarations";
+ children: EnumBodyDeclarationsCtx;
+}
+
+export type EnumBodyDeclarationsCtx = {
+ Semicolon: IToken[];
+ classBodyDeclaration?: ClassBodyDeclarationCstNode[];
+};
+
+export interface RecordDeclarationCstNode extends CstNode {
+ name: "recordDeclaration";
+ children: RecordDeclarationCtx;
+}
+
+export type RecordDeclarationCtx = {
+ Record: IToken[];
+ typeIdentifier: TypeIdentifierCstNode[];
+ typeParameters?: TypeParametersCstNode[];
+ recordHeader: RecordHeaderCstNode[];
+ superinterfaces?: SuperinterfacesCstNode[];
+ recordBody: RecordBodyCstNode[];
+};
+
+export interface RecordHeaderCstNode extends CstNode {
+ name: "recordHeader";
+ children: RecordHeaderCtx;
+}
+
+export type RecordHeaderCtx = {
+ LBrace: IToken[];
+ recordComponentList?: RecordComponentListCstNode[];
+ RBrace: IToken[];
+};
+
+export interface RecordComponentListCstNode extends CstNode {
+ name: "recordComponentList";
+ children: RecordComponentListCtx;
+}
+
+export type RecordComponentListCtx = {
+ recordComponent: RecordComponentCstNode[];
+ Comma?: IToken[];
+};
+
+export interface RecordComponentCstNode extends CstNode {
+ name: "recordComponent";
+ children: RecordComponentCtx;
+}
+
+export type RecordComponentCtx = {
+ recordComponentModifier?: RecordComponentModifierCstNode[];
+ unannType: UnannTypeCstNode[];
+ Identifier?: IToken[];
+ variableArityRecordComponent?: VariableArityRecordComponentCstNode[];
+};
+
+export interface VariableArityRecordComponentCstNode extends CstNode {
+ name: "variableArityRecordComponent";
+ children: VariableArityRecordComponentCtx;
+}
+
+export type VariableArityRecordComponentCtx = {
+ annotation?: AnnotationCstNode[];
+ DotDotDot: IToken[];
+ Identifier: IToken[];
+};
+
+export interface RecordComponentModifierCstNode extends CstNode {
+ name: "recordComponentModifier";
+ children: RecordComponentModifierCtx;
+}
+
+export type RecordComponentModifierCtx = {
+ annotation: AnnotationCstNode[];
+};
+
+export interface RecordBodyCstNode extends CstNode {
+ name: "recordBody";
+ children: RecordBodyCtx;
+}
+
+export type RecordBodyCtx = {
+ LCurly: IToken[];
+ recordBodyDeclaration?: RecordBodyDeclarationCstNode[];
+ RCurly: IToken[];
+};
+
+export interface RecordBodyDeclarationCstNode extends CstNode {
+ name: "recordBodyDeclaration";
+ children: RecordBodyDeclarationCtx;
+}
+
+export type RecordBodyDeclarationCtx = {
+ compactConstructorDeclaration?: CompactConstructorDeclarationCstNode[];
+ classBodyDeclaration?: ClassBodyDeclarationCstNode[];
+};
+
+export interface CompactConstructorDeclarationCstNode extends CstNode {
+ name: "compactConstructorDeclaration";
+ children: CompactConstructorDeclarationCtx;
+}
+
+export type CompactConstructorDeclarationCtx = {
+ constructorModifier?: ConstructorModifierCstNode[];
+ simpleTypeName: SimpleTypeNameCstNode[];
+ constructorBody: ConstructorBodyCstNode[];
+};
+
+export interface IsClassDeclarationCstNode extends CstNode {
+ name: "isClassDeclaration";
+ children: IsClassDeclarationCtx;
+}
+
+export type IsClassDeclarationCtx = {
+ Semicolon?: IToken[];
+ classModifier?: ClassModifierCstNode[];
+};
+
+export interface IdentifyClassBodyDeclarationTypeCstNode extends CstNode {
+ name: "identifyClassBodyDeclarationType";
+ children: IdentifyClassBodyDeclarationTypeCtx;
+}
+
+export type IdentifyClassBodyDeclarationTypeCtx = {
+ annotation?: AnnotationCstNode[];
+ Public?: IToken[];
+ Protected?: IToken[];
+ Private?: IToken[];
+ Abstract?: IToken[];
+ Static?: IToken[];
+ Final?: IToken[];
+ Transient?: IToken[];
+ Volatile?: IToken[];
+ Synchronized?: IToken[];
+ Native?: IToken[];
+ Strictfp?: IToken[];
+ unannType: UnannTypeCstNode[];
+};
+
+export interface IsDimsCstNode extends CstNode {
+ name: "isDims";
+ children: IsDimsCtx;
+}
+
+export type IsDimsCtx = {
+ At?: IToken[];
+ typeName?: TypeNameCstNode[];
+ LBrace?: IToken[];
+ elementValuePairList?: ElementValuePairListCstNode[];
+ elementValue?: ElementValueCstNode[];
+ RBrace?: IToken[];
+};
+
+export interface IsCompactConstructorDeclarationCstNode extends CstNode {
+ name: "isCompactConstructorDeclaration";
+ children: IsCompactConstructorDeclarationCtx;
+}
+
+export type IsCompactConstructorDeclarationCtx = {
+ annotation?: AnnotationCstNode[];
+ Public?: IToken[];
+ Protected?: IToken[];
+ Private?: IToken[];
+ simpleTypeName: SimpleTypeNameCstNode[];
+ LCurly: IToken[];
+};
+
+export interface CompilationUnitCstNode extends CstNode {
+ name: "compilationUnit";
+ children: CompilationUnitCtx;
+}
+
+export type AbstractOrdinaryCompilationUnitCtx = {
+ ordinaryCompilationUnit: OrdinaryCompilationUnitCstNode[];
+ EOF: IToken[];
+};
+
+export type AbstractModularCompilationUnitCtx = {
+ modularCompilationUnit: OrdinaryCompilationUnitCstNode[];
+ EOF: IToken[];
+};
+
+export type CompilationUnitCtx =
+ | AbstractOrdinaryCompilationUnitCtx
+ | AbstractModularCompilationUnitCtx;
+
+export interface OrdinaryCompilationUnitCstNode extends CstNode {
+ name: "ordinaryCompilationUnit";
+ children: OrdinaryCompilationUnitCtx;
+}
+
+export type OrdinaryCompilationUnitCtx = {
+ packageDeclaration?: PackageDeclarationCstNode[];
+ importDeclaration?: ImportDeclarationCstNode[];
+ typeDeclaration?: TypeDeclarationCstNode[];
+};
+
+export interface ModularCompilationUnitCstNode extends CstNode {
+ name: "modularCompilationUnit";
+ children: ModularCompilationUnitCtx;
+}
+
+export type ModularCompilationUnitCtx = {
+ importDeclaration?: ImportDeclarationCstNode[];
+ moduleDeclaration: ModuleDeclarationCstNode[];
+};
+
+export interface PackageDeclarationCstNode extends CstNode {
+ name: "packageDeclaration";
+ children: PackageDeclarationCtx;
+}
+
+export type PackageDeclarationCtx = {
+ packageModifier?: PackageModifierCstNode[];
+ Package: IToken[];
+ Identifier: IToken[];
+ Dot?: IToken[];
+ Semicolon: IToken[];
+};
+
+export interface PackageModifierCstNode extends CstNode {
+ name: "packageModifier";
+ children: PackageModifierCtx;
+}
+
+export type PackageModifierCtx = {
+ annotation: AnnotationCstNode[];
+};
+
+export interface ImportDeclarationCstNode extends CstNode {
+ name: "importDeclaration";
+ children: ImportDeclarationCtx;
+}
+
+export type ImportDeclarationCtx = {
+ Import?: IToken[];
+ Static?: IToken[];
+ packageOrTypeName?: PackageOrTypeNameCstNode[];
+ Dot?: IToken[];
+ Star?: IToken[];
+ Semicolon?: IToken[];
+ emptyStatement?: EmptyStatementCstNode[];
+};
+
+export interface TypeDeclarationCstNode extends CstNode {
+ name: "typeDeclaration";
+ children: TypeDeclarationCtx;
+}
+
+export type TypeDeclarationCtx = {
+ classDeclaration?: ClassDeclarationCstNode[];
+ interfaceDeclaration?: InterfaceDeclarationCstNode[];
+ Semicolon?: IToken[];
+};
+
+export interface ModuleDeclarationCstNode extends CstNode {
+ name: "moduleDeclaration";
+ children: ModuleDeclarationCtx;
+}
+
+export type ModuleDeclarationCtx = {
+ annotation?: AnnotationCstNode[];
+ Open?: IToken[];
+ Module: IToken[];
+ Identifier: IToken[];
+ Dot?: IToken[];
+ LCurly: IToken[];
+ moduleDirective?: ModuleDirectiveCstNode[];
+ RCurly: IToken[];
+};
+
+export interface ModuleDirectiveCstNode extends CstNode {
+ name: "moduleDirective";
+ children: ModuleDirectiveCtx;
+}
+
+export type ModuleDirectiveCtx = {
+ requiresModuleDirective?: RequiresModuleDirectiveCstNode[];
+ exportsModuleDirective?: ExportsModuleDirectiveCstNode[];
+ opensModuleDirective?: OpensModuleDirectiveCstNode[];
+ usesModuleDirective?: UsesModuleDirectiveCstNode[];
+ providesModuleDirective?: ProvidesModuleDirectiveCstNode[];
+};
+
+export interface RequiresModuleDirectiveCstNode extends CstNode {
+ name: "requiresModuleDirective";
+ children: RequiresModuleDirectiveCtx;
+}
+
+export type RequiresModuleDirectiveCtx = {
+ Requires: IToken[];
+ requiresModifier?: RequiresModifierCstNode[];
+ moduleName: ModuleNameCstNode[];
+ Semicolon: IToken[];
+};
+
+export interface ExportsModuleDirectiveCstNode extends CstNode {
+ name: "exportsModuleDirective";
+ children: ExportsModuleDirectiveCtx;
+}
+
+export type ExportsModuleDirectiveCtx = {
+ Exports: IToken[];
+ packageName: PackageNameCstNode[];
+ To?: IToken[];
+ moduleName?: ModuleNameCstNode[];
+ Comma?: IToken[];
+ Semicolon: IToken[];
+};
+
+export interface OpensModuleDirectiveCstNode extends CstNode {
+ name: "opensModuleDirective";
+ children: OpensModuleDirectiveCtx;
+}
+
+export type OpensModuleDirectiveCtx = {
+ Opens: IToken[];
+ packageName: PackageNameCstNode[];
+ To?: IToken[];
+ moduleName?: ModuleNameCstNode[];
+ Comma?: IToken[];
+ Semicolon: IToken[];
+};
+
+export interface UsesModuleDirectiveCstNode extends CstNode {
+ name: "usesModuleDirective";
+ children: UsesModuleDirectiveCtx;
+}
+
+export type UsesModuleDirectiveCtx = {
+ Uses: IToken[];
+ typeName: TypeNameCstNode[];
+ Semicolon: IToken[];
+};
+
+export interface ProvidesModuleDirectiveCstNode extends CstNode {
+ name: "providesModuleDirective";
+ children: ProvidesModuleDirectiveCtx;
+}
+
+export type ProvidesModuleDirectiveCtx = {
+ Provides: IToken[];
+ typeName: TypeNameCstNode[];
+ With: IToken[];
+ Comma?: IToken[];
+ Semicolon: IToken[];
+};
+
+export interface RequiresModifierCstNode extends CstNode {
+ name: "requiresModifier";
+ children: RequiresModifierCtx;
+}
+
+export type RequiresModifierCtx = {
+ Transitive?: IToken[];
+ Static?: IToken[];
+};
+
+export interface IsModuleCompilationUnitCstNode extends CstNode {
+ name: "isModuleCompilationUnit";
+ children: IsModuleCompilationUnitCtx;
+}
+
+export type IsModuleCompilationUnitCtx = {
+ packageDeclaration?: PackageDeclarationCstNode[];
+ importDeclaration?: ImportDeclarationCstNode[];
+ annotation?: AnnotationCstNode[];
+};
+
+export interface InterfaceDeclarationCstNode extends CstNode {
+ name: "interfaceDeclaration";
+ children: InterfaceDeclarationCtx;
+}
+
+export type InterfaceDeclarationCtx = {
+ interfaceModifier?: InterfaceModifierCstNode[];
+ normalInterfaceDeclaration?: NormalInterfaceDeclarationCstNode[];
+ annotationTypeDeclaration?: AnnotationTypeDeclarationCstNode[];
+};
+
+export interface NormalInterfaceDeclarationCstNode extends CstNode {
+ name: "normalInterfaceDeclaration";
+ children: NormalInterfaceDeclarationCtx;
+}
+
+export type NormalInterfaceDeclarationCtx = {
+ Interface: IToken[];
+ typeIdentifier: TypeIdentifierCstNode[];
+ typeParameters?: TypeParametersCstNode[];
+ extendsInterfaces?: ExtendsInterfacesCstNode[];
+ interfacePermits?: InterfacePermitsCstNode[];
+ interfaceBody: InterfaceBodyCstNode[];
+};
+
+export interface InterfaceModifierCstNode extends CstNode {
+ name: "interfaceModifier";
+ children: InterfaceModifierCtx;
+}
+
+export type InterfaceModifierCtx = {
+ annotation?: AnnotationCstNode[];
+ Public?: IToken[];
+ Protected?: IToken[];
+ Private?: IToken[];
+ Abstract?: IToken[];
+ Static?: IToken[];
+ Sealed?: IToken[];
+ NonSealed?: IToken[];
+ Strictfp?: IToken[];
+};
+
+export interface ExtendsInterfacesCstNode extends CstNode {
+ name: "extendsInterfaces";
+ children: ExtendsInterfacesCtx;
+}
+
+export type ExtendsInterfacesCtx = {
+ Extends: IToken[];
+ interfaceTypeList: InterfaceTypeListCstNode[];
+};
+
+export interface InterfacePermitsCstNode extends CstNode {
+ name: "interfacePermits";
+ children: InterfacePermitsCtx;
+}
+
+export type InterfacePermitsCtx = {
+ Permits: IToken[];
+ typeName: TypeNameCstNode[];
+ Comma?: IToken[];
+};
+
+export interface InterfaceBodyCstNode extends CstNode {
+ name: "interfaceBody";
+ children: InterfaceBodyCtx;
+}
+
+export type InterfaceBodyCtx = {
+ LCurly: IToken[];
+ interfaceMemberDeclaration?: InterfaceMemberDeclarationCstNode[];
+ RCurly: IToken[];
+};
+
+export interface InterfaceMemberDeclarationCstNode extends CstNode {
+ name: "interfaceMemberDeclaration";
+ children: InterfaceMemberDeclarationCtx;
+}
+
+export type InterfaceMemberDeclarationCtx = {
+ constantDeclaration?: ConstantDeclarationCstNode[];
+ interfaceMethodDeclaration?: InterfaceMethodDeclarationCstNode[];
+ classDeclaration?: ClassDeclarationCstNode[];
+ interfaceDeclaration?: InterfaceDeclarationCstNode[];
+ Semicolon?: IToken[];
+};
+
+export interface ConstantDeclarationCstNode extends CstNode {
+ name: "constantDeclaration";
+ children: ConstantDeclarationCtx;
+}
+
+export type ConstantDeclarationCtx = {
+ constantModifier?: ConstantModifierCstNode[];
+ unannType: UnannTypeCstNode[];
+ variableDeclaratorList: VariableDeclaratorListCstNode[];
+ Semicolon: IToken[];
+};
+
+export interface ConstantModifierCstNode extends CstNode {
+ name: "constantModifier";
+ children: ConstantModifierCtx;
+}
+
+export type ConstantModifierCtx = {
+ annotation?: AnnotationCstNode[];
+ Public?: IToken[];
+ Static?: IToken[];
+ Final?: IToken[];
+};
+
+export interface InterfaceMethodDeclarationCstNode extends CstNode {
+ name: "interfaceMethodDeclaration";
+ children: InterfaceMethodDeclarationCtx;
+}
+
+export type InterfaceMethodDeclarationCtx = {
+ interfaceMethodModifier?: InterfaceMethodModifierCstNode[];
+ methodHeader: MethodHeaderCstNode[];
+ methodBody: MethodBodyCstNode[];
+};
+
+export interface InterfaceMethodModifierCstNode extends CstNode {
+ name: "interfaceMethodModifier";
+ children: InterfaceMethodModifierCtx;
+}
+
+export type InterfaceMethodModifierCtx = {
+ annotation?: AnnotationCstNode[];
+ Public?: IToken[];
+ Private?: IToken[];
+ Abstract?: IToken[];
+ Default?: IToken[];
+ Static?: IToken[];
+ Strictfp?: IToken[];
+};
+
+export interface AnnotationTypeDeclarationCstNode extends CstNode {
+ name: "annotationTypeDeclaration";
+ children: AnnotationTypeDeclarationCtx;
+}
+
+export type AnnotationTypeDeclarationCtx = {
+ At: IToken[];
+ Interface: IToken[];
+ typeIdentifier: TypeIdentifierCstNode[];
+ annotationTypeBody: AnnotationTypeBodyCstNode[];
+};
+
+export interface AnnotationTypeBodyCstNode extends CstNode {
+ name: "annotationTypeBody";
+ children: AnnotationTypeBodyCtx;
+}
+
+export type AnnotationTypeBodyCtx = {
+ LCurly: IToken[];
+ annotationTypeMemberDeclaration?: AnnotationTypeMemberDeclarationCstNode[];
+ RCurly: IToken[];
+};
+
+export interface AnnotationTypeMemberDeclarationCstNode extends CstNode {
+ name: "annotationTypeMemberDeclaration";
+ children: AnnotationTypeMemberDeclarationCtx;
+}
+
+export type AnnotationTypeMemberDeclarationCtx = {
+ annotationTypeElementDeclaration?: AnnotationTypeElementDeclarationCstNode[];
+ constantDeclaration?: ConstantDeclarationCstNode[];
+ classDeclaration?: ClassDeclarationCstNode[];
+ interfaceDeclaration?: InterfaceDeclarationCstNode[];
+ Semicolon?: IToken[];
+};
+
+export interface AnnotationTypeElementDeclarationCstNode extends CstNode {
+ name: "annotationTypeElementDeclaration";
+ children: AnnotationTypeElementDeclarationCtx;
+}
+
+export type AnnotationTypeElementDeclarationCtx = {
+ annotationTypeElementModifier?: AnnotationTypeElementModifierCstNode[];
+ unannType: UnannTypeCstNode[];
+ Identifier: IToken[];
+ LBrace: IToken[];
+ RBrace: IToken[];
+ dims?: DimsCstNode[];
+ defaultValue?: DefaultValueCstNode[];
+ Semicolon: IToken[];
+};
+
+export interface AnnotationTypeElementModifierCstNode extends CstNode {
+ name: "annotationTypeElementModifier";
+ children: AnnotationTypeElementModifierCtx;
+}
+
+export type AnnotationTypeElementModifierCtx = {
+ annotation?: AnnotationCstNode[];
+ Public?: IToken[];
+ Abstract?: IToken[];
+};
+
+export interface DefaultValueCstNode extends CstNode {
+ name: "defaultValue";
+ children: DefaultValueCtx;
+}
+
+export type DefaultValueCtx = {
+ Default: IToken[];
+ elementValue: ElementValueCstNode[];
+};
+
+export interface AnnotationCstNode extends CstNode {
+ name: "annotation";
+ children: AnnotationCtx;
+}
+
+export type AnnotationCtx = {
+ At: IToken[];
+ typeName: TypeNameCstNode[];
+ LBrace?: IToken[];
+ elementValuePairList?: ElementValuePairListCstNode[];
+ elementValue?: ElementValueCstNode[];
+ RBrace?: IToken[];
+};
+
+export interface ElementValuePairListCstNode extends CstNode {
+ name: "elementValuePairList";
+ children: ElementValuePairListCtx;
+}
+
+export type ElementValuePairListCtx = {
+ elementValuePair: ElementValuePairCstNode[];
+ Comma?: IToken[];
+};
+
+export interface ElementValuePairCstNode extends CstNode {
+ name: "elementValuePair";
+ children: ElementValuePairCtx;
+}
+
+export type ElementValuePairCtx = {
+ Identifier: IToken[];
+ Equals: IToken[];
+ elementValue: ElementValueCstNode[];
+};
+
+export interface ElementValueCstNode extends CstNode {
+ name: "elementValue";
+ children: ElementValueCtx;
+}
+
+export type ElementValueCtx = {
+ expression?: ExpressionCstNode[];
+ elementValueArrayInitializer?: ElementValueArrayInitializerCstNode[];
+ annotation?: AnnotationCstNode[];
+};
+
+export interface ElementValueArrayInitializerCstNode extends CstNode {
+ name: "elementValueArrayInitializer";
+ children: ElementValueArrayInitializerCtx;
+}
+
+export type ElementValueArrayInitializerCtx = {
+ LCurly: IToken[];
+ elementValueList?: ElementValueListCstNode[];
+ Comma?: IToken[];
+ RCurly: IToken[];
+};
+
+export interface ElementValueListCstNode extends CstNode {
+ name: "elementValueList";
+ children: ElementValueListCtx;
+}
+
+export type ElementValueListCtx = {
+ elementValue: ElementValueCstNode[];
+ Comma?: IToken[];
+};
+
+export interface IdentifyInterfaceBodyDeclarationTypeCstNode extends CstNode {
+ name: "identifyInterfaceBodyDeclarationType";
+ children: IdentifyInterfaceBodyDeclarationTypeCtx;
+}
+
+export type IdentifyInterfaceBodyDeclarationTypeCtx = {
+ annotation?: AnnotationCstNode[];
+ Public?: IToken[];
+ Protected?: IToken[];
+ Private?: IToken[];
+ Static?: IToken[];
+ Final?: IToken[];
+ Abstract?: IToken[];
+ Default?: IToken[];
+ Strictfp?: IToken[];
+ unannType: UnannTypeCstNode[];
+};
+
+export interface IdentifyAnnotationBodyDeclarationTypeCstNode extends CstNode {
+ name: "identifyAnnotationBodyDeclarationType";
+ children: IdentifyAnnotationBodyDeclarationTypeCtx;
+}
+
+export type IdentifyAnnotationBodyDeclarationTypeCtx = {
+ annotation?: AnnotationCstNode[];
+ Public?: IToken[];
+ Protected?: IToken[];
+ Private?: IToken[];
+ Abstract?: IToken[];
+ Static?: IToken[];
+ Final?: IToken[];
+ Strictfp?: IToken[];
+ unannType: UnannTypeCstNode[];
+};
+
+export interface IsSimpleElementValueAnnotationCstNode extends CstNode {
+ name: "isSimpleElementValueAnnotation";
+ children: IsSimpleElementValueAnnotationCtx;
+}
+
+export type IsSimpleElementValueAnnotationCtx = {
+ annotation: AnnotationCstNode[];
+};
+
+export interface ArrayInitializerCstNode extends CstNode {
+ name: "arrayInitializer";
+ children: ArrayInitializerCtx;
+}
+
+export type ArrayInitializerCtx = {
+ LCurly: IToken[];
+ variableInitializerList?: VariableInitializerListCstNode[];
+ Comma?: IToken[];
+ RCurly: IToken[];
+};
+
+export interface VariableInitializerListCstNode extends CstNode {
+ name: "variableInitializerList";
+ children: VariableInitializerListCtx;
+}
+
+export type VariableInitializerListCtx = {
+ variableInitializer: VariableInitializerCstNode[];
+ Comma?: IToken[];
+};
+
+export interface BlockCstNode extends CstNode {
+ name: "block";
+ children: BlockCtx;
+}
+
+export type BlockCtx = {
+ LCurly: IToken[];
+ blockStatements?: BlockStatementsCstNode[];
+ RCurly: IToken[];
+};
+
+export interface BlockStatementsCstNode extends CstNode {
+ name: "blockStatements";
+ children: BlockStatementsCtx;
+}
+
+export type BlockStatementsCtx = {
+ blockStatement: BlockStatementCstNode[];
+};
+
+export interface BlockStatementCstNode extends CstNode {
+ name: "blockStatement";
+ children: BlockStatementCtx;
+}
+
+export type BlockStatementCtx = {
+ localVariableDeclarationStatement?: LocalVariableDeclarationStatementCstNode[];
+ classDeclaration?: ClassDeclarationCstNode[];
+ interfaceDeclaration?: InterfaceDeclarationCstNode[];
+ statement?: StatementCstNode[];
+};
+
+export interface LocalVariableDeclarationStatementCstNode extends CstNode {
+ name: "localVariableDeclarationStatement";
+ children: LocalVariableDeclarationStatementCtx;
+}
+
+export type LocalVariableDeclarationStatementCtx = {
+ localVariableDeclaration: LocalVariableDeclarationCstNode[];
+ Semicolon: IToken[];
+};
+
+export interface LocalVariableDeclarationCstNode extends CstNode {
+ name: "localVariableDeclaration";
+ children: LocalVariableDeclarationCtx;
+}
+
+export type LocalVariableDeclarationCtx = {
+ variableModifier?: VariableModifierCstNode[];
+ localVariableType: LocalVariableTypeCstNode[];
+ variableDeclaratorList: VariableDeclaratorListCstNode[];
+};
+
+export interface LocalVariableTypeCstNode extends CstNode {
+ name: "localVariableType";
+ children: LocalVariableTypeCtx;
+}
+
+export type LocalVariableTypeCtx = {
+ unannType?: UnannTypeCstNode[];
+ Var?: IToken[];
+};
+
+export interface StatementCstNode extends CstNode {
+ name: "statement";
+ children: StatementCtx;
+}
+
+export type StatementCtx = {
+ statementWithoutTrailingSubstatement?: StatementWithoutTrailingSubstatementCstNode[];
+ labeledStatement?: LabeledStatementCstNode[];
+ ifStatement?: IfStatementCstNode[];
+ whileStatement?: WhileStatementCstNode[];
+ forStatement?: ForStatementCstNode[];
+};
+
+export interface StatementWithoutTrailingSubstatementCstNode extends CstNode {
+ name: "statementWithoutTrailingSubstatement";
+ children: StatementWithoutTrailingSubstatementCtx;
+}
+
+export type StatementWithoutTrailingSubstatementCtx = {
+ block?: BlockCstNode[];
+ yieldStatement?: YieldStatementCstNode[];
+ emptyStatement?: EmptyStatementCstNode[];
+ expressionStatement?: ExpressionStatementCstNode[];
+ assertStatement?: AssertStatementCstNode[];
+ switchStatement?: SwitchStatementCstNode[];
+ doStatement?: DoStatementCstNode[];
+ breakStatement?: BreakStatementCstNode[];
+ continueStatement?: ContinueStatementCstNode[];
+ returnStatement?: ReturnStatementCstNode[];
+ synchronizedStatement?: SynchronizedStatementCstNode[];
+ throwStatement?: ThrowStatementCstNode[];
+ tryStatement?: TryStatementCstNode[];
+};
+
+export interface EmptyStatementCstNode extends CstNode {
+ name: "emptyStatement";
+ children: EmptyStatementCtx;
+}
+
+export type EmptyStatementCtx = {
+ Semicolon: IToken[];
+};
+
+export interface LabeledStatementCstNode extends CstNode {
+ name: "labeledStatement";
+ children: LabeledStatementCtx;
+}
+
+export type LabeledStatementCtx = {
+ Identifier: IToken[];
+ Colon: IToken[];
+ statement: StatementCstNode[];
+};
+
+export interface ExpressionStatementCstNode extends CstNode {
+ name: "expressionStatement";
+ children: ExpressionStatementCtx;
+}
+
+export type ExpressionStatementCtx = {
+ statementExpression: StatementExpressionCstNode[];
+ Semicolon: IToken[];
+};
+
+export interface StatementExpressionCstNode extends CstNode {
+ name: "statementExpression";
+ children: StatementExpressionCtx;
+}
+
+export type StatementExpressionCtx = {
+ expression: ExpressionCstNode[];
+};
+
+export interface IfStatementCstNode extends CstNode {
+ name: "ifStatement";
+ children: IfStatementCtx;
+}
+
+export type IfStatementCtx = {
+ If: IToken[];
+ LBrace: IToken[];
+ expression: ExpressionCstNode[];
+ RBrace: IToken[];
+ statement: StatementCstNode[];
+ Else?: IToken[];
+};
+
+export interface AssertStatementCstNode extends CstNode {
+ name: "assertStatement";
+ children: AssertStatementCtx;
+}
+
+export type AssertStatementCtx = {
+ Assert: IToken[];
+ expression: ExpressionCstNode[];
+ Colon?: IToken[];
+ Semicolon: IToken[];
+};
+
+export interface SwitchStatementCstNode extends CstNode {
+ name: "switchStatement";
+ children: SwitchStatementCtx;
+}
+
+export type SwitchStatementCtx = {
+ Switch: IToken[];
+ LBrace: IToken[];
+ expression: ExpressionCstNode[];
+ RBrace: IToken[];
+ switchBlock: SwitchBlockCstNode[];
+};
+
+export interface SwitchBlockCstNode extends CstNode {
+ name: "switchBlock";
+ children: SwitchBlockCtx;
+}
+
+export type SwitchBlockCtx = {
+ LCurly: IToken[];
+ switchBlockStatementGroup?: SwitchBlockStatementGroupCstNode[];
+ switchRule?: SwitchRuleCstNode[];
+ RCurly: IToken[];
+};
+
+export interface SwitchBlockStatementGroupCstNode extends CstNode {
+ name: "switchBlockStatementGroup";
+ children: SwitchBlockStatementGroupCtx;
+}
+
+export type SwitchBlockStatementGroupCtx = {
+ switchLabel: SwitchLabelCstNode[];
+ Colon: IToken[];
+ blockStatements: BlockStatementsCstNode[];
+};
+
+export interface SwitchLabelCstNode extends CstNode {
+ name: "switchLabel";
+ children: SwitchLabelCtx;
+}
+
+export type SwitchLabelCtx = {
+ caseOrDefaultLabel: CaseOrDefaultLabelCstNode[];
+ Colon?: IToken[];
+};
+
+export interface CaseOrDefaultLabelCstNode extends CstNode {
+ name: "caseOrDefaultLabel";
+ children: CaseOrDefaultLabelCtx;
+}
+
+export type CaseOrDefaultLabelCtx = {
+ Case?: IToken[];
+ caseLabelElement?: CaseLabelElementCstNode[];
+ Comma?: IToken[];
+ Default?: IToken[];
+};
+
+export interface CaseLabelElementCstNode extends CstNode {
+ name: "caseLabelElement";
+ children: CaseLabelElementCtx;
+}
+
+export type CaseLabelElementCtx = {
+ caseConstant?: CaseConstantCstNode[];
+ pattern?: PatternCstNode[];
+ Null?: IToken[];
+ Default?: IToken[];
+};
+
+export interface SwitchRuleCstNode extends CstNode {
+ name: "switchRule";
+ children: SwitchRuleCtx;
+}
+
+export type SwitchRuleCtx = {
+ switchLabel: SwitchLabelCstNode[];
+ Arrow: IToken[];
+ throwStatement?: ThrowStatementCstNode[];
+ block?: BlockCstNode[];
+ expression?: ExpressionCstNode[];
+ Semicolon?: IToken[];
+};
+
+export interface CaseConstantCstNode extends CstNode {
+ name: "caseConstant";
+ children: CaseConstantCtx;
+}
+
+export type CaseConstantCtx = {
+ ternaryExpression: TernaryExpressionCstNode[];
+};
+
+export interface WhileStatementCstNode extends CstNode {
+ name: "whileStatement";
+ children: WhileStatementCtx;
+}
+
+export type WhileStatementCtx = {
+ While: IToken[];
+ LBrace: IToken[];
+ expression: ExpressionCstNode[];
+ RBrace: IToken[];
+ statement: StatementCstNode[];
+};
+
+export interface DoStatementCstNode extends CstNode {
+ name: "doStatement";
+ children: DoStatementCtx;
+}
+
+export type DoStatementCtx = {
+ Do: IToken[];
+ statement: StatementCstNode[];
+ While: IToken[];
+ LBrace: IToken[];
+ expression: ExpressionCstNode[];
+ RBrace: IToken[];
+ Semicolon: IToken[];
+};
+
+export interface ForStatementCstNode extends CstNode {
+ name: "forStatement";
+ children: ForStatementCtx;
+}
+
+export type ForStatementCtx = {
+ basicForStatement?: BasicForStatementCstNode[];
+ enhancedForStatement?: EnhancedForStatementCstNode[];
+};
+
+export interface BasicForStatementCstNode extends CstNode {
+ name: "basicForStatement";
+ children: BasicForStatementCtx;
+}
+
+export type BasicForStatementCtx = {
+ For: IToken[];
+ LBrace: IToken[];
+ forInit?: ForInitCstNode[];
+ Semicolon: IToken[];
+ expression?: ExpressionCstNode[];
+ forUpdate?: ForUpdateCstNode[];
+ RBrace: IToken[];
+ statement: StatementCstNode[];
+};
+
+export interface ForInitCstNode extends CstNode {
+ name: "forInit";
+ children: ForInitCtx;
+}
+
+export type ForInitCtx = {
+ localVariableDeclaration?: LocalVariableDeclarationCstNode[];
+ statementExpressionList?: StatementExpressionListCstNode[];
+};
+
+export interface ForUpdateCstNode extends CstNode {
+ name: "forUpdate";
+ children: ForUpdateCtx;
+}
+
+export type ForUpdateCtx = {
+ statementExpressionList: StatementExpressionListCstNode[];
+};
+
+export interface StatementExpressionListCstNode extends CstNode {
+ name: "statementExpressionList";
+ children: StatementExpressionListCtx;
+}
+
+export type StatementExpressionListCtx = {
+ statementExpression: StatementExpressionCstNode[];
+ Comma?: IToken[];
+};
+
+export interface EnhancedForStatementCstNode extends CstNode {
+ name: "enhancedForStatement";
+ children: EnhancedForStatementCtx;
+}
+
+export type EnhancedForStatementCtx = {
+ For: IToken[];
+ LBrace: IToken[];
+ variableModifier?: VariableModifierCstNode[];
+ localVariableType: LocalVariableTypeCstNode[];
+ variableDeclaratorId: VariableDeclaratorIdCstNode[];
+ Colon: IToken[];
+ expression: ExpressionCstNode[];
+ RBrace: IToken[];
+ statement: StatementCstNode[];
+};
+
+export interface BreakStatementCstNode extends CstNode {
+ name: "breakStatement";
+ children: BreakStatementCtx;
+}
+
+export type BreakStatementCtx = {
+ Break: IToken[];
+ Identifier?: IToken[];
+ Semicolon: IToken[];
+};
+
+export interface ContinueStatementCstNode extends CstNode {
+ name: "continueStatement";
+ children: ContinueStatementCtx;
+}
+
+export type ContinueStatementCtx = {
+ Continue: IToken[];
+ Identifier?: IToken[];
+ Semicolon: IToken[];
+};
+
+export interface ReturnStatementCstNode extends CstNode {
+ name: "returnStatement";
+ children: ReturnStatementCtx;
+}
+
+export type ReturnStatementCtx = {
+ Return: IToken[];
+ expression?: ExpressionCstNode[];
+ Semicolon: IToken[];
+};
+
+export interface ThrowStatementCstNode extends CstNode {
+ name: "throwStatement";
+ children: ThrowStatementCtx;
+}
+
+export type ThrowStatementCtx = {
+ Throw: IToken[];
+ expression: ExpressionCstNode[];
+ Semicolon: IToken[];
+};
+
+export interface SynchronizedStatementCstNode extends CstNode {
+ name: "synchronizedStatement";
+ children: SynchronizedStatementCtx;
+}
+
+export type SynchronizedStatementCtx = {
+ Synchronized: IToken[];
+ LBrace: IToken[];
+ expression: ExpressionCstNode[];
+ RBrace: IToken[];
+ block: BlockCstNode[];
+};
+
+export interface TryStatementCstNode extends CstNode {
+ name: "tryStatement";
+ children: TryStatementCtx;
+}
+
+export type TryStatementCtx = {
+ Try?: IToken[];
+ block?: BlockCstNode[];
+ catches?: CatchesCstNode[];
+ finally?: FinallyCstNode[];
+ tryWithResourcesStatement?: TryWithResourcesStatementCstNode[];
+};
+
+export interface CatchesCstNode extends CstNode {
+ name: "catches";
+ children: CatchesCtx;
+}
+
+export type CatchesCtx = {
+ catchClause: CatchClauseCstNode[];
+};
+
+export interface CatchClauseCstNode extends CstNode {
+ name: "catchClause";
+ children: CatchClauseCtx;
+}
+
+export type CatchClauseCtx = {
+ Catch: IToken[];
+ LBrace: IToken[];
+ catchFormalParameter: CatchFormalParameterCstNode[];
+ RBrace: IToken[];
+ block: BlockCstNode[];
+};
+
+export interface CatchFormalParameterCstNode extends CstNode {
+ name: "catchFormalParameter";
+ children: CatchFormalParameterCtx;
+}
+
+export type CatchFormalParameterCtx = {
+ variableModifier?: VariableModifierCstNode[];
+ catchType: CatchTypeCstNode[];
+ variableDeclaratorId: VariableDeclaratorIdCstNode[];
+};
+
+export interface CatchTypeCstNode extends CstNode {
+ name: "catchType";
+ children: CatchTypeCtx;
+}
+
+export type CatchTypeCtx = {
+ unannClassType: UnannClassTypeCstNode[];
+ Or?: IToken[];
+ classType?: ClassTypeCstNode[];
+};
+
+export interface FinallyCstNode extends CstNode {
+ name: "finally";
+ children: FinallyCtx;
+}
+
+export type FinallyCtx = {
+ Finally: IToken[];
+ block: BlockCstNode[];
+};
+
+export interface TryWithResourcesStatementCstNode extends CstNode {
+ name: "tryWithResourcesStatement";
+ children: TryWithResourcesStatementCtx;
+}
+
+export type TryWithResourcesStatementCtx = {
+ Try: IToken[];
+ resourceSpecification: ResourceSpecificationCstNode[];
+ block: BlockCstNode[];
+ catches?: CatchesCstNode[];
+ finally?: FinallyCstNode[];
+};
+
+export interface ResourceSpecificationCstNode extends CstNode {
+ name: "resourceSpecification";
+ children: ResourceSpecificationCtx;
+}
+
+export type ResourceSpecificationCtx = {
+ LBrace: IToken[];
+ resourceList: ResourceListCstNode[];
+ Semicolon?: IToken[];
+ RBrace: IToken[];
+};
+
+export interface ResourceListCstNode extends CstNode {
+ name: "resourceList";
+ children: ResourceListCtx;
+}
+
+export type ResourceListCtx = {
+ resource: ResourceCstNode[];
+ Semicolon?: IToken[];
+};
+
+export interface ResourceCstNode extends CstNode {
+ name: "resource";
+ children: ResourceCtx;
+}
+
+export type ResourceCtx = {
+ resourceInit?: ResourceInitCstNode[];
+ variableAccess?: VariableAccessCstNode[];
+};
+
+export interface ResourceInitCstNode extends CstNode {
+ name: "resourceInit";
+ children: ResourceInitCtx;
+}
+
+export type ResourceInitCtx = {
+ variableModifier?: VariableModifierCstNode[];
+ localVariableType: LocalVariableTypeCstNode[];
+ Identifier: IToken[];
+ Equals: IToken[];
+ expression: ExpressionCstNode[];
+};
+
+export interface YieldStatementCstNode extends CstNode {
+ name: "yieldStatement";
+ children: YieldStatementCtx;
+}
+
+export type YieldStatementCtx = {
+ Yield: IToken[];
+ expression: ExpressionCstNode[];
+ Semicolon: IToken[];
+};
+
+export interface VariableAccessCstNode extends CstNode {
+ name: "variableAccess";
+ children: VariableAccessCtx;
+}
+
+export type VariableAccessCtx = {
+ primary: PrimaryCstNode[];
+};
+
+export interface IsBasicForStatementCstNode extends CstNode {
+ name: "isBasicForStatement";
+ children: IsBasicForStatementCtx;
+}
+
+export type IsBasicForStatementCtx = {
+ For: IToken[];
+ LBrace: IToken[];
+ forInit?: ForInitCstNode[];
+ Semicolon: IToken[];
+};
+
+export interface IsLocalVariableDeclarationCstNode extends CstNode {
+ name: "isLocalVariableDeclaration";
+ children: IsLocalVariableDeclarationCtx;
+}
+
+export type IsLocalVariableDeclarationCtx = {
+ variableModifier?: VariableModifierCstNode[];
+ localVariableType: LocalVariableTypeCstNode[];
+ variableDeclaratorId: VariableDeclaratorIdCstNode[];
+};
+
+export interface IsClassicSwitchLabelCstNode extends CstNode {
+ name: "isClassicSwitchLabel";
+ children: IsClassicSwitchLabelCtx;
+}
+
+export type IsClassicSwitchLabelCtx = {
+ switchLabel: SwitchLabelCstNode[];
+ Colon: IToken[];
+};
+
+export interface ExpressionCstNode extends CstNode {
+ name: "expression";
+ children: ExpressionCtx;
+}
+
+export type ExpressionCtx = {
+ lambdaExpression?: LambdaExpressionCstNode[];
+ ternaryExpression?: TernaryExpressionCstNode[];
+};
+
+export interface LambdaExpressionCstNode extends CstNode {
+ name: "lambdaExpression";
+ children: LambdaExpressionCtx;
+}
+
+export type LambdaExpressionCtx = {
+ lambdaParameters: LambdaParametersCstNode[];
+ Arrow: IToken[];
+ lambdaBody: LambdaBodyCstNode[];
+};
+
+export interface LambdaParametersCstNode extends CstNode {
+ name: "lambdaParameters";
+ children: LambdaParametersCtx;
+}
+
+export type LambdaParametersCtx = {
+ lambdaParametersWithBraces?: LambdaParametersWithBracesCstNode[];
+ Identifier?: IToken[];
+};
+
+export interface LambdaParametersWithBracesCstNode extends CstNode {
+ name: "lambdaParametersWithBraces";
+ children: LambdaParametersWithBracesCtx;
+}
+
+export type LambdaParametersWithBracesCtx = {
+ LBrace: IToken[];
+ lambdaParameterList?: LambdaParameterListCstNode[];
+ RBrace: IToken[];
+};
+
+export interface LambdaParameterListCstNode extends CstNode {
+ name: "lambdaParameterList";
+ children: LambdaParameterListCtx;
+}
+
+export type LambdaParameterListCtx = {
+ inferredLambdaParameterList?: InferredLambdaParameterListCstNode[];
+ explicitLambdaParameterList?: ExplicitLambdaParameterListCstNode[];
+};
+
+export interface InferredLambdaParameterListCstNode extends CstNode {
+ name: "inferredLambdaParameterList";
+ children: InferredLambdaParameterListCtx;
+}
+
+export type InferredLambdaParameterListCtx = {
+ Identifier: IToken[];
+ Comma?: IToken[];
+};
+
+export interface ExplicitLambdaParameterListCstNode extends CstNode {
+ name: "explicitLambdaParameterList";
+ children: ExplicitLambdaParameterListCtx;
+}
+
+export type ExplicitLambdaParameterListCtx = {
+ lambdaParameter: LambdaParameterCstNode[];
+ Comma?: IToken[];
+};
+
+export interface LambdaParameterCstNode extends CstNode {
+ name: "lambdaParameter";
+ children: LambdaParameterCtx;
+}
+
+export type LambdaParameterCtx = {
+ regularLambdaParameter?: RegularLambdaParameterCstNode[];
+ variableArityParameter?: VariableArityParameterCstNode[];
+};
+
+export interface RegularLambdaParameterCstNode extends CstNode {
+ name: "regularLambdaParameter";
+ children: RegularLambdaParameterCtx;
+}
+
+export type RegularLambdaParameterCtx = {
+ variableModifier?: VariableModifierCstNode[];
+ lambdaParameterType: LambdaParameterTypeCstNode[];
+ variableDeclaratorId: VariableDeclaratorIdCstNode[];
+};
+
+export interface LambdaParameterTypeCstNode extends CstNode {
+ name: "lambdaParameterType";
+ children: LambdaParameterTypeCtx;
+}
+
+export type LambdaParameterTypeCtx = {
+ unannType?: UnannTypeCstNode[];
+ Var?: IToken[];
+};
+
+export interface LambdaBodyCstNode extends CstNode {
+ name: "lambdaBody";
+ children: LambdaBodyCtx;
+}
+
+export type LambdaBodyCtx = {
+ expression?: ExpressionCstNode[];
+ block?: BlockCstNode[];
+};
+
+export interface TernaryExpressionCstNode extends CstNode {
+ name: "ternaryExpression";
+ children: TernaryExpressionCtx;
+}
+
+export type TernaryExpressionCtx = {
+ binaryExpression: BinaryExpressionCstNode[];
+ QuestionMark?: IToken[];
+ expression?: ExpressionCstNode[];
+ Colon?: IToken[];
+};
+
+export interface BinaryExpressionCstNode extends CstNode {
+ name: "binaryExpression";
+ children: BinaryExpressionCtx;
+}
+
+export type BinaryExpressionCtx = {
+ unaryExpression: UnaryExpressionCstNode[];
+ Instanceof?: IToken[];
+ pattern?: PatternCstNode[];
+ referenceType?: ReferenceTypeCstNode[];
+ AssignmentOperator?: IToken[];
+ expression?: ExpressionCstNode[];
+ Less?: IToken[];
+ Greater?: IToken[];
+ BinaryOperator?: IToken[];
+};
+
+export interface UnaryExpressionCstNode extends CstNode {
+ name: "unaryExpression";
+ children: UnaryExpressionCtx;
+}
+
+export type UnaryExpressionCtx = {
+ UnaryPrefixOperator?: IToken[];
+ primary: PrimaryCstNode[];
+ UnarySuffixOperator?: IToken[];
+};
+
+export interface UnaryExpressionNotPlusMinusCstNode extends CstNode {
+ name: "unaryExpressionNotPlusMinus";
+ children: UnaryExpressionNotPlusMinusCtx;
+}
+
+export type UnaryExpressionNotPlusMinusCtx = {
+ UnaryPrefixOperatorNotPlusMinus?: IToken[];
+ primary: PrimaryCstNode[];
+ UnarySuffixOperator?: IToken[];
+};
+
+export interface PrimaryCstNode extends CstNode {
+ name: "primary";
+ children: PrimaryCtx;
+}
+
+export type PrimaryCtx = {
+ primaryPrefix: PrimaryPrefixCstNode[];
+ primarySuffix?: PrimarySuffixCstNode[];
+};
+
+export interface PrimaryPrefixCstNode extends CstNode {
+ name: "primaryPrefix";
+ children: PrimaryPrefixCtx;
+}
+
+export type PrimaryPrefixCtx = {
+ literal?: LiteralCstNode[];
+ This?: IToken[];
+ Void?: IToken[];
+ unannPrimitiveTypeWithOptionalDimsSuffix?: UnannPrimitiveTypeWithOptionalDimsSuffixCstNode[];
+ fqnOrRefType?: FqnOrRefTypeCstNode[];
+ castExpression?: CastExpressionCstNode[];
+ parenthesisExpression?: ParenthesisExpressionCstNode[];
+ newExpression?: NewExpressionCstNode[];
+ switchStatement?: SwitchStatementCstNode[];
+};
+
+export interface PrimarySuffixCstNode extends CstNode {
+ name: "primarySuffix";
+ children: PrimarySuffixCtx;
+}
+
+export type PrimarySuffixCtx = {
+ Dot?: IToken[];
+ This?: IToken[];
+ unqualifiedClassInstanceCreationExpression?: UnqualifiedClassInstanceCreationExpressionCstNode[];
+ typeArguments?: TypeArgumentsCstNode[];
+ Identifier?: IToken[];
+ methodInvocationSuffix?: MethodInvocationSuffixCstNode[];
+ classLiteralSuffix?: ClassLiteralSuffixCstNode[];
+ arrayAccessSuffix?: ArrayAccessSuffixCstNode[];
+ methodReferenceSuffix?: MethodReferenceSuffixCstNode[];
+};
+
+export interface FqnOrRefTypeCstNode extends CstNode {
+ name: "fqnOrRefType";
+ children: FqnOrRefTypeCtx;
+}
+
+export type FqnOrRefTypeCtx = {
+ fqnOrRefTypePartFirst: FqnOrRefTypePartFirstCstNode[];
+ Dot?: IToken[];
+ fqnOrRefTypePartRest?: FqnOrRefTypePartRestCstNode[];
+ dims?: DimsCstNode[];
+};
+
+export interface FqnOrRefTypePartRestCstNode extends CstNode {
+ name: "fqnOrRefTypePartRest";
+ children: FqnOrRefTypePartRestCtx;
+}
+
+export type FqnOrRefTypePartRestCtx = {
+ annotation?: AnnotationCstNode[];
+ typeArguments?: TypeArgumentsCstNode[];
+ fqnOrRefTypePartCommon: FqnOrRefTypePartCommonCstNode[];
+};
+
+export interface FqnOrRefTypePartCommonCstNode extends CstNode {
+ name: "fqnOrRefTypePartCommon";
+ children: FqnOrRefTypePartCommonCtx;
+}
+
+export type FqnOrRefTypePartCommonCtx = {
+ Identifier?: IToken[];
+ Super?: IToken[];
+ typeArguments?: TypeArgumentsCstNode[];
+};
+
+export interface FqnOrRefTypePartFirstCstNode extends CstNode {
+ name: "fqnOrRefTypePartFirst";
+ children: FqnOrRefTypePartFirstCtx;
+}
+
+export type FqnOrRefTypePartFirstCtx = {
+ annotation?: AnnotationCstNode[];
+ fqnOrRefTypePartCommon: FqnOrRefTypePartCommonCstNode[];
+};
+
+export interface ParenthesisExpressionCstNode extends CstNode {
+ name: "parenthesisExpression";
+ children: ParenthesisExpressionCtx;
+}
+
+export type ParenthesisExpressionCtx = {
+ LBrace: IToken[];
+ expression: ExpressionCstNode[];
+ RBrace: IToken[];
+};
+
+export interface CastExpressionCstNode extends CstNode {
+ name: "castExpression";
+ children: CastExpressionCtx;
+}
+
+export type CastExpressionCtx = {
+ primitiveCastExpression?: PrimitiveCastExpressionCstNode[];
+ referenceTypeCastExpression?: ReferenceTypeCastExpressionCstNode[];
+};
+
+export interface PrimitiveCastExpressionCstNode extends CstNode {
+ name: "primitiveCastExpression";
+ children: PrimitiveCastExpressionCtx;
+}
+
+export type PrimitiveCastExpressionCtx = {
+ LBrace: IToken[];
+ primitiveType: PrimitiveTypeCstNode[];
+ RBrace: IToken[];
+ unaryExpression: UnaryExpressionCstNode[];
+};
+
+export interface ReferenceTypeCastExpressionCstNode extends CstNode {
+ name: "referenceTypeCastExpression";
+ children: ReferenceTypeCastExpressionCtx;
+}
+
+export type ReferenceTypeCastExpressionCtx = {
+ LBrace: IToken[];
+ referenceType: ReferenceTypeCstNode[];
+ additionalBound?: AdditionalBoundCstNode[];
+ RBrace: IToken[];
+ lambdaExpression?: LambdaExpressionCstNode[];
+ unaryExpressionNotPlusMinus?: UnaryExpressionNotPlusMinusCstNode[];
+};
+
+export interface NewExpressionCstNode extends CstNode {
+ name: "newExpression";
+ children: NewExpressionCtx;
+}
+
+export type NewExpressionCtx = {
+ arrayCreationExpression?: ArrayCreationExpressionCstNode[];
+ unqualifiedClassInstanceCreationExpression?: UnqualifiedClassInstanceCreationExpressionCstNode[];
+};
+
+export interface UnqualifiedClassInstanceCreationExpressionCstNode
+ extends CstNode {
+ name: "unqualifiedClassInstanceCreationExpression";
+ children: UnqualifiedClassInstanceCreationExpressionCtx;
+}
+
+export type UnqualifiedClassInstanceCreationExpressionCtx = {
+ New: IToken[];
+ typeArguments?: TypeArgumentsCstNode[];
+ classOrInterfaceTypeToInstantiate: ClassOrInterfaceTypeToInstantiateCstNode[];
+ LBrace: IToken[];
+ argumentList?: ArgumentListCstNode[];
+ RBrace: IToken[];
+ classBody?: ClassBodyCstNode[];
+};
+
+export interface ClassOrInterfaceTypeToInstantiateCstNode extends CstNode {
+ name: "classOrInterfaceTypeToInstantiate";
+ children: ClassOrInterfaceTypeToInstantiateCtx;
+}
+
+export type ClassOrInterfaceTypeToInstantiateCtx = {
+ annotation?: AnnotationCstNode[];
+ Identifier: IToken[];
+ Dot?: IToken[];
+ typeArgumentsOrDiamond?: TypeArgumentsOrDiamondCstNode[];
+};
+
+export interface TypeArgumentsOrDiamondCstNode extends CstNode {
+ name: "typeArgumentsOrDiamond";
+ children: TypeArgumentsOrDiamondCtx;
+}
+
+export type TypeArgumentsOrDiamondCtx = {
+ diamond?: DiamondCstNode[];
+ typeArguments?: TypeArgumentsCstNode[];
+};
+
+export interface DiamondCstNode extends CstNode {
+ name: "diamond";
+ children: DiamondCtx;
+}
+
+export type DiamondCtx = {
+ Less: IToken[];
+ Greater: IToken[];
+};
+
+export interface MethodInvocationSuffixCstNode extends CstNode {
+ name: "methodInvocationSuffix";
+ children: MethodInvocationSuffixCtx;
+}
+
+export type MethodInvocationSuffixCtx = {
+ LBrace: IToken[];
+ argumentList?: ArgumentListCstNode[];
+ RBrace: IToken[];
+};
+
+export interface ArgumentListCstNode extends CstNode {
+ name: "argumentList";
+ children: ArgumentListCtx;
+}
+
+export type ArgumentListCtx = {
+ expression: ExpressionCstNode[];
+ Comma?: IToken[];
+};
+
+export interface ArrayCreationExpressionCstNode extends CstNode {
+ name: "arrayCreationExpression";
+ children: ArrayCreationExpressionCtx;
+}
+
+export type ArrayCreationExpressionCtx = {
+ New: IToken[];
+ primitiveType?: PrimitiveTypeCstNode[];
+ classOrInterfaceType?: ClassOrInterfaceTypeCstNode[];
+ arrayCreationDefaultInitSuffix?: ArrayCreationDefaultInitSuffixCstNode[];
+ arrayCreationExplicitInitSuffix?: ArrayCreationExplicitInitSuffixCstNode[];
+};
+
+export interface ArrayCreationDefaultInitSuffixCstNode extends CstNode {
+ name: "arrayCreationDefaultInitSuffix";
+ children: ArrayCreationDefaultInitSuffixCtx;
+}
+
+export type ArrayCreationDefaultInitSuffixCtx = {
+ dimExprs: DimExprsCstNode[];
+ dims?: DimsCstNode[];
+};
+
+export interface ArrayCreationExplicitInitSuffixCstNode extends CstNode {
+ name: "arrayCreationExplicitInitSuffix";
+ children: ArrayCreationExplicitInitSuffixCtx;
+}
+
+export type ArrayCreationExplicitInitSuffixCtx = {
+ dims: DimsCstNode[];
+ arrayInitializer: ArrayInitializerCstNode[];
+};
+
+export interface DimExprsCstNode extends CstNode {
+ name: "dimExprs";
+ children: DimExprsCtx;
+}
+
+export type DimExprsCtx = {
+ dimExpr: DimExprCstNode[];
+};
+
+export interface DimExprCstNode extends CstNode {
+ name: "dimExpr";
+ children: DimExprCtx;
+}
+
+export type DimExprCtx = {
+ annotation?: AnnotationCstNode[];
+ LSquare: IToken[];
+ expression: ExpressionCstNode[];
+ RSquare: IToken[];
+};
+
+export interface ClassLiteralSuffixCstNode extends CstNode {
+ name: "classLiteralSuffix";
+ children: ClassLiteralSuffixCtx;
+}
+
+export type ClassLiteralSuffixCtx = {
+ LSquare?: IToken[];
+ RSquare?: IToken[];
+ Dot: IToken[];
+ Class: IToken[];
+};
+
+export interface ArrayAccessSuffixCstNode extends CstNode {
+ name: "arrayAccessSuffix";
+ children: ArrayAccessSuffixCtx;
+}
+
+export type ArrayAccessSuffixCtx = {
+ LSquare: IToken[];
+ expression: ExpressionCstNode[];
+ RSquare: IToken[];
+};
+
+export interface MethodReferenceSuffixCstNode extends CstNode {
+ name: "methodReferenceSuffix";
+ children: MethodReferenceSuffixCtx;
+}
+
+export type MethodReferenceSuffixCtx = {
+ ColonColon: IToken[];
+ typeArguments?: TypeArgumentsCstNode[];
+ Identifier?: IToken[];
+ New?: IToken[];
+};
+
+export interface PatternCstNode extends CstNode {
+ name: "pattern";
+ children: PatternCtx;
+}
+
+export type PatternCtx = {
+ typePattern: TypePatternCstNode[];
+};
+
+export interface TypePatternCstNode extends CstNode {
+ name: "typePattern";
+ children: TypePatternCtx;
+}
+
+export type TypePatternCtx = {
+ localVariableDeclaration: LocalVariableDeclarationCstNode[];
+};
+
+export interface IdentifyNewExpressionTypeCstNode extends CstNode {
+ name: "identifyNewExpressionType";
+ children: IdentifyNewExpressionTypeCtx;
+}
+
+export type IdentifyNewExpressionTypeCtx = {
+ New: IToken[];
+ classOrInterfaceTypeToInstantiate: ClassOrInterfaceTypeToInstantiateCstNode[];
+};
+
+export interface IsLambdaExpressionCstNode extends CstNode {
+ name: "isLambdaExpression";
+ children: IsLambdaExpressionCtx;
+}
+
+export type IsLambdaExpressionCtx = {};
+
+export interface IsCastExpressionCstNode extends CstNode {
+ name: "isCastExpression";
+ children: IsCastExpressionCtx;
+}
+
+export type IsCastExpressionCtx = {};
+
+export interface IsPrimitiveCastExpressionCstNode extends CstNode {
+ name: "isPrimitiveCastExpression";
+ children: IsPrimitiveCastExpressionCtx;
+}
+
+export type IsPrimitiveCastExpressionCtx = {
+ LBrace: IToken[];
+ primitiveType: PrimitiveTypeCstNode[];
+ RBrace: IToken[];
+};
+
+export interface IsReferenceTypeCastExpressionCstNode extends CstNode {
+ name: "isReferenceTypeCastExpression";
+ children: IsReferenceTypeCastExpressionCtx;
+}
+
+export type IsReferenceTypeCastExpressionCtx = {
+ LBrace: IToken[];
+ referenceType: ReferenceTypeCstNode[];
+ additionalBound?: AdditionalBoundCstNode[];
+ RBrace: IToken[];
+};
+
+export interface IsRefTypeInMethodRefCstNode extends CstNode {
+ name: "isRefTypeInMethodRef";
+ children: IsRefTypeInMethodRefCtx;
+}
+
+export type IsRefTypeInMethodRefCtx = {
+ typeArguments: TypeArgumentsCstNode[];
+ dims?: DimsCstNode[];
+ Dot?: IToken[];
+ classOrInterfaceType?: ClassOrInterfaceTypeCstNode[];
+};
diff --git a/node_modules/java-parser/src/comments.js b/node_modules/java-parser/src/comments.js
new file mode 100644
index 0000000..cb3b539
--- /dev/null
+++ b/node_modules/java-parser/src/comments.js
@@ -0,0 +1,311 @@
+"use strict";
+
+const findLast = require("lodash/findLast");
+
+/**
+ * Search where is the position of the comment in the token array by
+ * using dichotomic search.
+ * @param {*} tokens ordered array of tokens
+ * @param {*} comment comment token
+ * @return the position of the token next to the comment
+ */
+function findUpperBoundToken(tokens, comment) {
+ let diff;
+ let i;
+ let current;
+
+ let len = tokens.length;
+ i = 0;
+
+ while (len) {
+ diff = len >>> 1;
+ current = i + diff;
+ if (tokens[current].startOffset > comment.startOffset) {
+ len = diff;
+ } else {
+ i = current + 1;
+ len -= diff + 1;
+ }
+ }
+ return i;
+}
+
+function isPrettierIgnoreComment(comment) {
+ return comment.image.match(
+ /(\/\/(\s*)prettier-ignore(\s*))|(\/\*(\s*)prettier-ignore(\s*)\*\/)/gm
+ );
+}
+
+function isFormatterOffOnComment(comment) {
+ return comment.image.match(
+ /(\/\/(\s*)@formatter:(off|on)(\s*))|(\/\*(\s*)@formatter:(off|on)(\s*)\*\/)/gm
+ );
+}
+
+/**
+ * Pre-processing of tokens in order to
+ * complete the parser's mostEnclosiveCstNodeByStartOffset and mostEnclosiveCstNodeByEndOffset structures.
+ *
+ * @param {ITokens[]} tokens - array of tokens
+ * @param {{[startOffset: number]: CSTNode}} mostEnclosiveCstNodeByStartOffset
+ * @param {{[endOffset: number]: CSTNode}} mostEnclosiveCstNodeByEndOffset
+ */
+function completeMostEnclosiveCSTNodeByOffset(
+ tokens,
+ mostEnclosiveCstNodeByStartOffset,
+ mostEnclosiveCstNodeByEndOffset
+) {
+ tokens.forEach(token => {
+ if (mostEnclosiveCstNodeByStartOffset[token.startOffset] === undefined) {
+ mostEnclosiveCstNodeByStartOffset[token.startOffset] = token;
+ }
+
+ if (mostEnclosiveCstNodeByEndOffset[token.endOffset] === undefined) {
+ mostEnclosiveCstNodeByEndOffset[token.endOffset] = token;
+ }
+ });
+}
+
+function extendRangeOffset(comments, tokens) {
+ let position;
+ comments.forEach(comment => {
+ position = findUpperBoundToken(tokens, comment);
+
+ const extendedStartOffset =
+ position - 1 < 0 ? comment.startOffset : tokens[position - 1].endOffset;
+ const extendedEndOffset =
+ position == tokens.length
+ ? comment.endOffset
+ : tokens[position].startOffset;
+ comment.extendedOffset = {
+ startOffset: extendedStartOffset,
+ endOffset: extendedEndOffset
+ };
+ });
+}
+
+/**
+ * Create two data structures we use to know at which offset a comment can be attached.
+ * - commentsByExtendedStartOffset: map a comment by the endOffset of the previous token.
+ * - commentsByExtendedEndOffset: map a comment by the startOffset of the next token
+ *
+ * @param {ITokens[]} tokens - array of tokens
+ *
+ * @return {{commentsByExtendedStartOffset: {[extendedStartOffset: number]: Comment[]}, commentsByExtendedEndOffset: {[extendedEndOffset: number]: Comment[]}}}
+ */
+function mapCommentsByExtendedRange(comments) {
+ const commentsByExtendedEndOffset = {};
+ const commentsByExtendedStartOffset = {};
+
+ comments.forEach(comment => {
+ const extendedStartOffset = comment.extendedOffset.startOffset;
+ const extendedEndOffset = comment.extendedOffset.endOffset;
+
+ if (commentsByExtendedEndOffset[extendedEndOffset] === undefined) {
+ commentsByExtendedEndOffset[extendedEndOffset] = [comment];
+ } else {
+ commentsByExtendedEndOffset[extendedEndOffset].push(comment);
+ }
+
+ if (commentsByExtendedStartOffset[extendedStartOffset] === undefined) {
+ commentsByExtendedStartOffset[extendedStartOffset] = [comment];
+ } else {
+ commentsByExtendedStartOffset[extendedStartOffset].push(comment);
+ }
+ });
+
+ return { commentsByExtendedEndOffset, commentsByExtendedStartOffset };
+}
+
+/**
+ * Determine if a comment should be attached as a trailing comment to a specific node.
+ * A comment should be trailing if it is on the same line than the previous token and
+ * not on the same line than the next token
+ *
+ * @param {*} comment
+ * @param {CSTNode} node
+ * @param {{[startOffset: number]: CSTNode}} mostEnclosiveCstNodeByStartOffset
+ */
+function shouldAttachTrailingComments(
+ comment,
+ node,
+ mostEnclosiveCstNodeByStartOffset
+) {
+ if (isPrettierIgnoreComment(comment)) {
+ return false;
+ }
+
+ const nextNode =
+ mostEnclosiveCstNodeByStartOffset[comment.extendedOffset.endOffset];
+
+ // Last node of the file
+ if (nextNode === undefined) {
+ return true;
+ }
+
+ const nodeEndLine =
+ node.location !== undefined ? node.location.endLine : node.endLine;
+
+ if (comment.startLine !== nodeEndLine) {
+ return false;
+ }
+
+ const nextNodeStartLine =
+ nextNode.location !== undefined
+ ? nextNode.location.startLine
+ : nextNode.startLine;
+ return comment.endLine !== nextNodeStartLine;
+}
+
+/**
+ * Attach comments to the most enclosive CSTNode (node or token)
+ *
+ * @param {ITokens[]} tokens
+ * @param {*} comments
+ * @param {{[startOffset: number]: CSTNode}} mostEnclosiveCstNodeByStartOffset
+ * @param {{[endOffset: number]: CSTNode}} mostEnclosiveCstNodeByEndOffset
+ */
+function attachComments(
+ tokens,
+ comments,
+ mostEnclosiveCstNodeByStartOffset,
+ mostEnclosiveCstNodeByEndOffset
+) {
+ // Edge case: only comments in the file
+ if (tokens.length === 0) {
+ mostEnclosiveCstNodeByStartOffset[NaN].leadingComments = comments;
+ return;
+ }
+
+ // Pre-processing phase to complete the data structures we need to attach
+ // a comment to the right place
+ completeMostEnclosiveCSTNodeByOffset(
+ tokens,
+ mostEnclosiveCstNodeByStartOffset,
+ mostEnclosiveCstNodeByEndOffset
+ );
+
+ extendRangeOffset(comments, tokens);
+ const { commentsByExtendedStartOffset, commentsByExtendedEndOffset } =
+ mapCommentsByExtendedRange(comments);
+
+ /*
+ This set is here to ensure that we attach comments only once
+ If a comment is attached to a node or token, we remove it from this set
+ */
+ const commentsToAttach = new Set(comments);
+
+ // Attach comments as trailing comments if desirable
+ Object.keys(mostEnclosiveCstNodeByEndOffset).forEach(endOffset => {
+ // We look if some comments is directly following this node/token
+ if (commentsByExtendedStartOffset[endOffset] !== undefined) {
+ const nodeTrailingComments = commentsByExtendedStartOffset[
+ endOffset
+ ].filter(comment => {
+ return (
+ shouldAttachTrailingComments(
+ comment,
+ mostEnclosiveCstNodeByEndOffset[endOffset],
+ mostEnclosiveCstNodeByStartOffset
+ ) && commentsToAttach.has(comment)
+ );
+ });
+
+ if (nodeTrailingComments.length > 0) {
+ mostEnclosiveCstNodeByEndOffset[endOffset].trailingComments =
+ nodeTrailingComments;
+ }
+
+ nodeTrailingComments.forEach(comment => {
+ commentsToAttach.delete(comment);
+ });
+ }
+ });
+
+ // Attach rest of comments as leading comments
+ Object.keys(mostEnclosiveCstNodeByStartOffset).forEach(startOffset => {
+ // We look if some comments is directly preceding this node/token
+ if (commentsByExtendedEndOffset[startOffset] !== undefined) {
+ const nodeLeadingComments = commentsByExtendedEndOffset[
+ startOffset
+ ].filter(comment => commentsToAttach.has(comment));
+
+ if (nodeLeadingComments.length > 0) {
+ mostEnclosiveCstNodeByStartOffset[startOffset].leadingComments =
+ nodeLeadingComments;
+ }
+
+ // prettier ignore support
+ for (let i = 0; i < nodeLeadingComments.length; i++) {
+ if (isPrettierIgnoreComment(nodeLeadingComments[i])) {
+ mostEnclosiveCstNodeByStartOffset[startOffset].ignore = true;
+ break;
+ }
+ }
+ }
+ });
+}
+
+/**
+ * Create pairs of formatter:off and formatter:on
+ * @param comments
+ * @returns pairs of formatter:off and formatter:on
+ */
+function matchFormatterOffOnPairs(comments) {
+ const onOffComments = comments.filter(comment =>
+ isFormatterOffOnComment(comment)
+ );
+
+ let isPreviousCommentOff = false;
+ let isCurrentCommentOff = true;
+ const pairs = [];
+ let paired = {};
+ onOffComments.forEach(comment => {
+ isCurrentCommentOff = comment.image.slice(-3) === "off";
+
+ if (!isPreviousCommentOff) {
+ if (isCurrentCommentOff) {
+ paired.off = comment;
+ }
+ } else {
+ if (!isCurrentCommentOff) {
+ paired.on = comment;
+ pairs.push(paired);
+ paired = {};
+ }
+ }
+ isPreviousCommentOff = isCurrentCommentOff;
+ });
+
+ if (onOffComments.length > 0 && isCurrentCommentOff) {
+ paired.on = undefined;
+ pairs.push(paired);
+ }
+
+ return pairs;
+}
+
+/**
+ * Check if the node is between formatter:off and formatter:on and change his ignore state
+ * @param node
+ * @param commentPairs
+ */
+function shouldNotFormat(node, commentPairs) {
+ const matchingPair = findLast(
+ commentPairs,
+ comment => comment.off.endOffset < node.location.startOffset
+ );
+ if (
+ matchingPair !== undefined &&
+ (matchingPair.on === undefined ||
+ matchingPair.on.startOffset > node.location.endOffset)
+ ) {
+ node.ignore = true;
+ }
+}
+
+module.exports = {
+ matchFormatterOffOnPairs,
+ shouldNotFormat,
+ attachComments
+};
diff --git a/node_modules/java-parser/src/index.js b/node_modules/java-parser/src/index.js
new file mode 100644
index 0000000..698f3ad
--- /dev/null
+++ b/node_modules/java-parser/src/index.js
@@ -0,0 +1,67 @@
+"use strict";
+const JavaLexer = require("./lexer");
+const JavaParser = require("./parser");
+const { attachComments, matchFormatterOffOnPairs } = require("./comments");
+
+const parser = new JavaParser();
+
+const BaseJavaCstVisitor = parser.getBaseCstVisitorConstructor();
+const BaseJavaCstVisitorWithDefaults =
+ parser.getBaseCstVisitorConstructorWithDefaults();
+
+function parse(inputText, entryPoint = "compilationUnit") {
+ // Lex
+ const lexResult = JavaLexer.tokenize(inputText);
+
+ if (lexResult.errors.length > 0) {
+ const firstError = lexResult.errors[0];
+ throw Error(
+ "Sad sad panda, lexing errors detected in line: " +
+ firstError.line +
+ ", column: " +
+ firstError.column +
+ "!\n" +
+ firstError.message
+ );
+ }
+
+ parser.input = lexResult.tokens;
+ parser.mostEnclosiveCstNodeByStartOffset = {};
+ parser.mostEnclosiveCstNodeByEndOffset = {};
+
+ parser.setOnOffCommentPairs(
+ matchFormatterOffOnPairs(lexResult.groups.comments)
+ );
+
+ // Automatic CST created when parsing
+ const cst = parser[entryPoint]();
+
+ if (parser.errors.length > 0) {
+ const error = parser.errors[0];
+ throw Error(
+ "Sad sad panda, parsing errors detected in line: " +
+ error.token.startLine +
+ ", column: " +
+ error.token.startColumn +
+ "!\n" +
+ error.message +
+ "!\n\t->" +
+ error.context.ruleStack.join("\n\t->")
+ );
+ }
+
+ attachComments(
+ lexResult.tokens,
+ lexResult.groups.comments,
+ parser.mostEnclosiveCstNodeByStartOffset,
+ parser.mostEnclosiveCstNodeByEndOffset
+ );
+
+ return cst;
+}
+
+module.exports = {
+ parse,
+ BaseJavaCstVisitor,
+ BaseJavaCstVisitorWithDefaults
+};
diff --git a/node_modules/java-parser/src/lexer.js b/node_modules/java-parser/src/lexer.js
new file mode 100644
index 0000000..afe4652
--- /dev/null
+++ b/node_modules/java-parser/src/lexer.js
@@ -0,0 +1,12 @@
+"use strict";
+const chevrotain = require("chevrotain");
+const { allTokens } = require("./tokens");
+const { getSkipValidations } = require("./utils");
+
+const Lexer = chevrotain.Lexer;
+const JavaLexer = new Lexer(allTokens, {
+ ensureOptimizations: true,
+ skipValidations: getSkipValidations()
+});
+
+module.exports = JavaLexer;
diff --git a/node_modules/java-parser/src/parser.js b/node_modules/java-parser/src/parser.js
new file mode 100644
index 0000000..7342164
--- /dev/null
+++ b/node_modules/java-parser/src/parser.js
@@ -0,0 +1,119 @@
+"use strict";
+const { Parser, isRecognitionException } = require("chevrotain");
+const { allTokens, tokens: t } = require("./tokens");
+const lexicalStructure = require("./productions/lexical-structure");
+const typesValuesVariables = require("./productions/types-values-and-variables");
+const names = require("./productions/names");
+const packagesModules = require("./productions/packages-and-modules");
+const classes = require("./productions/classes");
+const interfaces = require("./productions/interfaces");
+const arrays = require("./productions/arrays");
+const blocksStatements = require("./productions/blocks-and-statements");
+const expressions = require("./productions/expressions");
+const { getSkipValidations } = require("./utils");
+const { shouldNotFormat } = require("./comments");
+
+/**
+ * This parser attempts to strongly align with the specs style at:
+ * - https://docs.oracle.com/javase/specs/jls/se11/html/jls-19.html
+ *
+ * Deviations from the spec will be marked.
+ *
+ * Note that deviations from the spec do not mean deviations from Java Grammar.
+ * Rather it means an **equivalent** grammar which was written differently, e.g:
+ * - LL(k) vs LR(K)
+ * - Left Recursions vs Repetitions
+ * - NonTerminals combined together or divided to sub-NonTerminals
+ * - ...
+ *
+ * A special type of spec deviations are the "super grammar" kind.
+ * This means that the parser has been defined in such a way that it accept a
+ * **strict superset** of the inputs the official grammar accepts.
+ *
+ * This technique is used to simplify the parser when narrowing the set
+ * of accepted inputs can more easily be done in a post parsing phase.
+ *
+ * TODO: document guide lines for using back tracking
+ *
+ */
+class JavaParser extends Parser {
+ constructor() {
+ super(allTokens, {
+ maxLookahead: 1,
+ nodeLocationTracking: "full",
+ // traceInitPerf: 2,
+ skipValidations: getSkipValidations()
+ });
+
+ const $ = this;
+
+ this.mostEnclosiveCstNodeByStartOffset = {};
+ this.mostEnclosiveCstNodeByEndOffset = {};
+
+ // ---------------------
+ // Productions from §3 (Lexical Structure)
+ // ---------------------
+ // TODO: move this rule to the correct file
+ $.RULE("typeIdentifier", () => {
+ // TODO: implement: Identifier but not var in the lexer
+ $.CONSUME(t.Identifier);
+ });
+
+ // Include the productions from all "chapters".
+ lexicalStructure.defineRules.call(this, $, t);
+ typesValuesVariables.defineRules.call(this, $, t);
+ names.defineRules.call(this, $, t);
+ classes.defineRules.call(this, $, t);
+ packagesModules.defineRules.call(this, $, t);
+ interfaces.defineRules.call(this, $, t);
+ arrays.defineRules.call(this, $, t);
+ blocksStatements.defineRules.call(this, $, t);
+ expressions.defineRules.call(this, $, t);
+
+ this.firstForUnaryExpressionNotPlusMinus = [];
+ this.performSelfAnalysis();
+ this.firstForUnaryExpressionNotPlusMinus =
+ expressions.computeFirstForUnaryExpressionNotPlusMinus.call(this);
+ }
+
+ cstPostNonTerminal(ruleCstResult, ruleName) {
+ super.cstPostNonTerminal(ruleCstResult, ruleName);
+ if (this.isBackTracking() === false) {
+ this.mostEnclosiveCstNodeByStartOffset[
+ ruleCstResult.location.startOffset
+ ] = ruleCstResult;
+ this.mostEnclosiveCstNodeByEndOffset[ruleCstResult.location.endOffset] =
+ ruleCstResult;
+
+ shouldNotFormat(ruleCstResult, this.onOffCommentPairs);
+ }
+ }
+
+ BACKTRACK_LOOKAHEAD(production, errValue = false) {
+ return this.ACTION(() => {
+ this.isBackTrackingStack.push(1);
+ // TODO: "saveRecogState" does not handle the occurrence stack
+ const orgState = this.saveRecogState();
+ try {
+ // hack to enable outputting none CST values from grammar rules.
+ this.outputCst = false;
+ return production.call(this);
+ } catch (e) {
+ if (isRecognitionException(e)) {
+ return errValue;
+ }
+ throw e;
+ } finally {
+ this.outputCst = true;
+ this.reloadRecogState(orgState);
+ this.isBackTrackingStack.pop();
+ }
+ });
+ }
+
+ setOnOffCommentPairs(onOffCommentPairs) {
+ this.onOffCommentPairs = onOffCommentPairs;
+ }
+}
+
+module.exports = JavaParser;
diff --git a/node_modules/java-parser/src/productions/arrays.js b/node_modules/java-parser/src/productions/arrays.js
new file mode 100644
index 0000000..d97e280
--- /dev/null
+++ b/node_modules/java-parser/src/productions/arrays.js
@@ -0,0 +1,34 @@
+"use strict";
+
+const { tokenMatcher } = require("chevrotain");
+
+function defineRules($, t) {
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-10.html#jls-ArrayInitializer
+ $.RULE("arrayInitializer", () => {
+ $.CONSUME(t.LCurly);
+ $.OPTION(() => {
+ $.SUBRULE($.variableInitializerList);
+ });
+ $.OPTION2(() => {
+ $.CONSUME(t.Comma);
+ });
+ $.CONSUME(t.RCurly);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-10.html#jls-VariableInitializerList
+ $.RULE("variableInitializerList", () => {
+ $.SUBRULE($.variableInitializer);
+ $.MANY({
+ // The optional last "Comma" of an "arrayInitializer"
+ GATE: () => tokenMatcher(this.LA(2).tokenType, t.RCurly) === false,
+ DEF: () => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.variableInitializer);
+ }
+ });
+ });
+}
+
+module.exports = {
+ defineRules
+};
diff --git a/node_modules/java-parser/src/productions/blocks-and-statements.js b/node_modules/java-parser/src/productions/blocks-and-statements.js
new file mode 100644
index 0000000..d19f00b
--- /dev/null
+++ b/node_modules/java-parser/src/productions/blocks-and-statements.js
@@ -0,0 +1,597 @@
+"use strict";
+
+const { tokenMatcher } = require("chevrotain");
+
+// Spec Deviation: The "*NoShortIf" variations were removed as the ambiguity of
+// the dangling else is resolved by attaching an "else" block
+// to the nearest "if"
+function defineRules($, t) {
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-Block
+ $.RULE("block", () => {
+ $.CONSUME(t.LCurly);
+ $.OPTION(() => {
+ $.SUBRULE($.blockStatements);
+ });
+ $.CONSUME(t.RCurly);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-BlockStatements
+ $.RULE("blockStatements", () => {
+ $.SUBRULE($.blockStatement);
+ $.MANY(() => {
+ $.SUBRULE2($.blockStatement);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-BlockStatement
+ $.RULE("blockStatement", () => {
+ const isLocalVariableDeclaration = this.BACKTRACK_LOOKAHEAD(
+ $.isLocalVariableDeclaration
+ );
+
+ const isClassDeclaration = this.BACKTRACK_LOOKAHEAD($.isClassDeclaration);
+
+ $.OR({
+ DEF: [
+ {
+ GATE: () => isLocalVariableDeclaration,
+ ALT: () => $.SUBRULE($.localVariableDeclarationStatement)
+ },
+ {
+ GATE: () => isClassDeclaration,
+ ALT: () => $.SUBRULE($.classDeclaration)
+ },
+ {
+ ALT: () => $.SUBRULE($.interfaceDeclaration)
+ },
+ { ALT: () => $.SUBRULE($.statement) }
+ ],
+ IGNORE_AMBIGUITIES: true
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-LocalVariableDeclarationStatement
+ $.RULE("localVariableDeclarationStatement", () => {
+ $.SUBRULE($.localVariableDeclaration);
+ $.CONSUME(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-LocalVariableDeclaration
+ $.RULE("localVariableDeclaration", () => {
+ $.MANY(() => {
+ $.SUBRULE($.variableModifier);
+ });
+ $.SUBRULE($.localVariableType);
+ $.SUBRULE($.variableDeclaratorList);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-LocalVariableType
+ $.RULE("localVariableType", () => {
+ $.OR({
+ DEF: [
+ { ALT: () => $.SUBRULE($.unannType) },
+ { ALT: () => $.CONSUME(t.Var) }
+ ],
+ IGNORE_AMBIGUITIES: true
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-Statement
+ $.RULE("statement", () => {
+ $.OR({
+ DEF: [
+ {
+ ALT: () => $.SUBRULE($.statementWithoutTrailingSubstatement)
+ },
+ { ALT: () => $.SUBRULE($.labeledStatement) },
+ // Spec deviation: combined "IfThenStatement" and "IfThenElseStatement"
+ { ALT: () => $.SUBRULE($.ifStatement) },
+ { ALT: () => $.SUBRULE($.whileStatement) },
+ { ALT: () => $.SUBRULE($.forStatement) }
+ ],
+ MAX_LOOKAHEAD: 2
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-StatementWithoutTrailingSubstatement
+ $.RULE("statementWithoutTrailingSubstatement", () => {
+ $.OR({
+ DEF: [
+ { ALT: () => $.SUBRULE($.block) },
+ {
+ GATE: () => this.BACKTRACK_LOOKAHEAD($.yieldStatement),
+ ALT: () => $.SUBRULE($.yieldStatement)
+ },
+ { ALT: () => $.SUBRULE($.emptyStatement) },
+ {
+ GATE: () => !tokenMatcher(this.LA(1).tokenType, t.Switch),
+ ALT: () => $.SUBRULE($.expressionStatement)
+ },
+ { ALT: () => $.SUBRULE($.assertStatement) },
+ { ALT: () => $.SUBRULE($.switchStatement) },
+ { ALT: () => $.SUBRULE($.doStatement) },
+ { ALT: () => $.SUBRULE($.breakStatement) },
+ { ALT: () => $.SUBRULE($.continueStatement) },
+ { ALT: () => $.SUBRULE($.returnStatement) },
+ { ALT: () => $.SUBRULE($.synchronizedStatement) },
+ { ALT: () => $.SUBRULE($.throwStatement) },
+ { ALT: () => $.SUBRULE($.tryStatement) }
+ ],
+ IGNORE_AMBIGUITIES: true
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-EmptyStatement
+ $.RULE("emptyStatement", () => {
+ $.CONSUME(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-LabeledStatement
+ $.RULE("labeledStatement", () => {
+ $.CONSUME(t.Identifier);
+ $.CONSUME(t.Colon);
+ $.SUBRULE($.statement);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-ExpressionStatement
+ $.RULE("expressionStatement", () => {
+ $.SUBRULE($.statementExpression);
+ $.CONSUME(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-StatementExpression
+ $.RULE("statementExpression", () => {
+ // Spec deviation: The many alternatives here were replaced with
+ // the "expression" rule as it contains them all,
+ // and distinguishing between the alternatives cannot be done
+ // using a fixed lookahead.
+ // TODO: verify the resulting expression is one of the valid alternatives?
+ $.SUBRULE($.expression);
+ });
+
+ // Spec deviation: combined "IfThenStatement" and "IfThenElseStatement"
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-IfThenStatement
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-IfThenElseStatement
+ $.RULE("ifStatement", () => {
+ $.CONSUME(t.If);
+ $.CONSUME(t.LBrace);
+ $.SUBRULE($.expression);
+ $.CONSUME(t.RBrace);
+ $.SUBRULE($.statement);
+ $.OPTION(() => {
+ $.CONSUME(t.Else);
+ $.SUBRULE2($.statement);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-AssertStatement
+ $.RULE("assertStatement", () => {
+ $.CONSUME(t.Assert);
+ $.SUBRULE($.expression);
+ $.OPTION(() => {
+ $.CONSUME(t.Colon);
+ $.SUBRULE2($.expression);
+ });
+ $.CONSUME(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-SwitchStatement
+ $.RULE("switchStatement", () => {
+ $.CONSUME(t.Switch);
+ $.CONSUME(t.LBrace);
+ $.SUBRULE($.expression);
+ $.CONSUME(t.RBrace);
+ $.SUBRULE($.switchBlock);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-SwitchBlock
+ $.RULE("switchBlock", () => {
+ $.CONSUME(t.LCurly);
+ $.OR([
+ {
+ GATE: () => this.BACKTRACK_LOOKAHEAD($.isClassicSwitchLabel),
+ ALT: () => $.MANY(() => $.SUBRULE($.switchBlockStatementGroup))
+ },
+ {
+ ALT: () => $.MANY2(() => $.SUBRULE($.switchRule))
+ }
+ ]);
+ $.CONSUME(t.RCurly);
+ });
+
+ $.RULE("switchBlockStatementGroup", () => {
+ $.SUBRULE($.switchLabel);
+ $.CONSUME(t.Colon);
+ $.OPTION(() => {
+ $.SUBRULE($.blockStatements);
+ });
+ });
+
+ $.RULE("switchLabel", () => {
+ $.SUBRULE($.caseOrDefaultLabel);
+ $.MANY({
+ GATE: () =>
+ tokenMatcher($.LA(1).tokenType, t.Colon) &&
+ (tokenMatcher($.LA(2).tokenType, t.Case) ||
+ tokenMatcher($.LA(2).tokenType, t.Default)),
+ DEF: () => {
+ $.CONSUME(t.Colon);
+ $.SUBRULE2($.caseOrDefaultLabel);
+ }
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-SwitchLabel
+ $.RULE("caseOrDefaultLabel", () => {
+ $.OR([
+ {
+ ALT: () => {
+ $.CONSUME(t.Case);
+ $.SUBRULE($.caseLabelElement);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.caseLabelElement);
+ });
+ }
+ },
+ {
+ ALT: () => $.CONSUME(t.Default)
+ }
+ ]);
+ });
+
+ $.RULE("caseLabelElement", () => {
+ $.OR([
+ { ALT: () => $.CONSUME(t.Null) },
+ { ALT: () => $.CONSUME(t.Default) },
+ {
+ GATE: () => this.BACKTRACK_LOOKAHEAD($.pattern),
+ ALT: () => $.SUBRULE($.pattern)
+ },
+ {
+ GATE: () => tokenMatcher($.LA(1).tokenType, t.Null) === false,
+ ALT: () => $.SUBRULE($.caseConstant)
+ }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-SwitchRule
+ $.RULE("switchRule", () => {
+ $.SUBRULE($.switchLabel);
+ $.CONSUME(t.Arrow);
+ $.OR([
+ { ALT: () => $.SUBRULE($.throwStatement) },
+ { ALT: () => $.SUBRULE($.block) },
+ {
+ ALT: () => {
+ $.SUBRULE($.expression);
+ $.CONSUME(t.Semicolon);
+ }
+ }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-EnumConstantName
+ $.RULE("caseConstant", () => {
+ $.SUBRULE($.ternaryExpression);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-WhileStatement
+ $.RULE("whileStatement", () => {
+ $.CONSUME(t.While);
+ $.CONSUME(t.LBrace);
+ $.SUBRULE($.expression);
+ $.CONSUME(t.RBrace);
+ $.SUBRULE($.statement);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-DoStatement
+ $.RULE("doStatement", () => {
+ $.CONSUME(t.Do);
+ $.SUBRULE($.statement);
+ $.CONSUME(t.While);
+ $.CONSUME(t.LBrace);
+ $.SUBRULE($.expression);
+ $.CONSUME(t.RBrace);
+ $.CONSUME(t.Semicolon);
+ });
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-ForStatement
+ $.RULE("forStatement", () => {
+ $.OR([
+ {
+ GATE: () => this.BACKTRACK_LOOKAHEAD($.isBasicForStatement),
+ ALT: () => $.SUBRULE($.basicForStatement)
+ },
+ { ALT: () => $.SUBRULE($.enhancedForStatement) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-BasicForStatement
+ $.RULE("basicForStatement", () => {
+ $.CONSUME(t.For);
+ $.CONSUME(t.LBrace);
+ $.OPTION(() => {
+ $.SUBRULE($.forInit);
+ });
+ $.CONSUME(t.Semicolon);
+ $.OPTION2(() => {
+ $.SUBRULE($.expression);
+ });
+ $.CONSUME2(t.Semicolon);
+ $.OPTION3(() => {
+ $.SUBRULE($.forUpdate);
+ });
+ $.CONSUME(t.RBrace);
+ $.SUBRULE($.statement);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-ForInit
+ $.RULE("forInit", () => {
+ $.OR([
+ {
+ GATE: () => $.BACKTRACK_LOOKAHEAD($.isLocalVariableDeclaration),
+ ALT: () => $.SUBRULE($.localVariableDeclaration)
+ },
+ { ALT: () => $.SUBRULE($.statementExpressionList) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-ForUpdate
+ $.RULE("forUpdate", () => {
+ $.SUBRULE($.statementExpressionList);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-StatementExpressionList
+ $.RULE("statementExpressionList", () => {
+ $.SUBRULE($.statementExpression);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.statementExpression);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-EnhancedForStatement
+ $.RULE("enhancedForStatement", () => {
+ $.CONSUME(t.For);
+ $.CONSUME(t.LBrace);
+ $.MANY(() => {
+ $.SUBRULE($.variableModifier);
+ });
+ $.SUBRULE($.localVariableType);
+ $.SUBRULE($.variableDeclaratorId);
+ $.CONSUME(t.Colon);
+ $.SUBRULE($.expression);
+ $.CONSUME(t.RBrace);
+ $.SUBRULE($.statement);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-BreakStatement
+ $.RULE("breakStatement", () => {
+ $.CONSUME(t.Break);
+ $.OPTION(() => {
+ $.CONSUME(t.Identifier);
+ });
+ $.CONSUME(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-ContinueStatement
+ $.RULE("continueStatement", () => {
+ $.CONSUME(t.Continue);
+ $.OPTION(() => {
+ $.CONSUME(t.Identifier);
+ });
+ $.CONSUME(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-ReturnStatement
+ $.RULE("returnStatement", () => {
+ $.CONSUME(t.Return);
+ $.OPTION(() => {
+ $.SUBRULE($.expression);
+ });
+ $.CONSUME(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-ThrowStatement
+ $.RULE("throwStatement", () => {
+ $.CONSUME(t.Throw);
+ $.SUBRULE($.expression);
+ $.CONSUME(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-SynchronizedStatement
+ $.RULE("synchronizedStatement", () => {
+ $.CONSUME(t.Synchronized);
+ $.CONSUME(t.LBrace);
+ $.SUBRULE($.expression);
+ $.CONSUME(t.RBrace);
+ $.SUBRULE($.block);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-TryStatement
+ $.RULE("tryStatement", () => {
+ $.OR({
+ DEF: [
+ {
+ ALT: () => {
+ $.CONSUME(t.Try);
+ $.SUBRULE($.block);
+ $.OR2([
+ {
+ ALT: () => {
+ $.SUBRULE($.catches);
+ $.OPTION(() => {
+ $.SUBRULE($.finally);
+ });
+ }
+ },
+ { ALT: () => $.SUBRULE2($.finally) }
+ ]);
+ }
+ },
+ { ALT: () => $.SUBRULE($.tryWithResourcesStatement) }
+ ],
+ MAX_LOOKAHEAD: 2
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-Catches
+ $.RULE("catches", () => {
+ $.SUBRULE($.catchClause);
+ $.MANY(() => {
+ $.SUBRULE2($.catchClause);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-CatchClause
+ $.RULE("catchClause", () => {
+ $.CONSUME(t.Catch);
+ $.CONSUME(t.LBrace);
+ $.SUBRULE($.catchFormalParameter);
+ $.CONSUME(t.RBrace);
+ $.SUBRULE($.block);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-CatchFormalParameter
+ $.RULE("catchFormalParameter", () => {
+ $.MANY(() => {
+ $.SUBRULE($.variableModifier);
+ });
+ $.SUBRULE($.catchType);
+ $.SUBRULE($.variableDeclaratorId);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-CatchType
+ $.RULE("catchType", () => {
+ $.SUBRULE($.unannClassType);
+ $.MANY(() => {
+ $.CONSUME(t.Or);
+ $.SUBRULE2($.classType);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-Finally
+ $.RULE("finally", () => {
+ $.CONSUME(t.Finally);
+ $.SUBRULE($.block);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-TryWithResourcesStatement
+ $.RULE("tryWithResourcesStatement", () => {
+ $.CONSUME(t.Try);
+ $.SUBRULE($.resourceSpecification);
+ $.SUBRULE($.block);
+ $.OPTION(() => {
+ $.SUBRULE($.catches);
+ });
+ $.OPTION2(() => {
+ $.SUBRULE($.finally);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-ResourceSpecification
+ $.RULE("resourceSpecification", () => {
+ $.CONSUME(t.LBrace);
+ $.SUBRULE($.resourceList);
+ $.OPTION(() => {
+ $.CONSUME(t.Semicolon);
+ });
+ $.CONSUME(t.RBrace);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-ResourceList
+ $.RULE("resourceList", () => {
+ $.SUBRULE($.resource);
+ $.MANY({
+ GATE: () => tokenMatcher($.LA(2).tokenType, t.RBrace) === false,
+ DEF: () => {
+ $.CONSUME(t.Semicolon);
+ $.SUBRULE2($.resource);
+ }
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-Resource
+ $.RULE("resource", () => {
+ $.OR([
+ {
+ GATE: $.BACKTRACK($.resourceInit),
+ // Spec Deviation: extracted this alternative to "resourceInit"
+ // to enable backtracking.
+ ALT: () => $.SUBRULE($.resourceInit)
+ },
+ { ALT: () => $.SUBRULE($.variableAccess) }
+ ]);
+ });
+
+ // Spec Deviation: extracted from "resource"
+ $.RULE("resourceInit", () => {
+ $.MANY(() => {
+ $.SUBRULE($.variableModifier);
+ });
+ $.SUBRULE($.localVariableType);
+ $.CONSUME(t.Identifier);
+ $.CONSUME(t.Equals);
+ $.SUBRULE($.expression);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-YieldStatement
+ $.RULE("yieldStatement", () => {
+ $.CONSUME(t.Yield);
+ $.SUBRULE($.expression);
+ $.CONSUME(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-14.html#jls-VariableAccess
+ $.RULE("variableAccess", () => {
+ // Spec Deviation: both "expressionName" and "fieldAccess" can be parsed
+ // by the "primary" rule
+ // TODO: verify that the primary is a fieldAccess or an expressionName.
+ $.SUBRULE($.primary);
+ });
+
+ // ------------------------------------
+ // Special optimized backtracking rules.
+ // ------------------------------------
+ $.RULE("isBasicForStatement", () => {
+ $.CONSUME(t.For);
+ $.CONSUME(t.LBrace);
+ $.OPTION(() => {
+ $.SUBRULE($.forInit);
+ });
+ $.CONSUME(t.Semicolon);
+ // consuming the first semiColon distinguishes between
+ // "basic" and "enhanced" for statements
+ return true;
+ });
+
+ $.RULE("isLocalVariableDeclaration", () => {
+ $.MANY(() => {
+ $.SUBRULE($.variableModifier);
+ });
+ $.SUBRULE($.localVariableType);
+ $.SUBRULE($.variableDeclaratorId);
+
+ const nextTokenType = this.LA(1).tokenType;
+ switch (nextTokenType) {
+ // Int x;
+ case t.Semicolon:
+ // Int x, y, z;
+ case t.Comma:
+ // Int x = 5;
+ case t.Equals:
+ return true;
+ default:
+ return false;
+ }
+ });
+
+ $.RULE("isClassicSwitchLabel", () => {
+ $.SUBRULE($.switchLabel);
+ $.CONSUME(t.Colon);
+ });
+}
+
+module.exports = {
+ defineRules
+};
diff --git a/node_modules/java-parser/src/productions/classes.js b/node_modules/java-parser/src/productions/classes.js
new file mode 100644
index 0000000..509b195
--- /dev/null
+++ b/node_modules/java-parser/src/productions/classes.js
@@ -0,0 +1,950 @@
+"use strict";
+
+const { isRecognitionException, tokenMatcher } = require("chevrotain");
+
+function defineRules($, t) {
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ClassDeclaration
+ $.RULE("classDeclaration", () => {
+ // Spec Deviation: extracted common "{classModifier}" prefix
+ // extraction is safe because there are no other references to
+ // "normalClassDeclaration" and "enumDeclaration"
+ $.MANY(() => {
+ $.SUBRULE($.classModifier);
+ });
+ $.OR([
+ { ALT: () => $.SUBRULE($.normalClassDeclaration) },
+ { ALT: () => $.SUBRULE($.enumDeclaration) },
+ { ALT: () => $.SUBRULE($.recordDeclaration) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-NormalClassDeclaration
+ $.RULE("normalClassDeclaration", () => {
+ // Spec Deviation: extracted common "{classModifier}" to "classDeclaration"
+ $.CONSUME(t.Class);
+ $.SUBRULE($.typeIdentifier);
+ $.OPTION(() => {
+ $.SUBRULE($.typeParameters);
+ });
+ $.OPTION2(() => {
+ $.SUBRULE($.superclass);
+ });
+ $.OPTION3(() => {
+ $.SUBRULE($.superinterfaces);
+ });
+ $.OPTION4(() => {
+ $.SUBRULE($.classPermits);
+ });
+ $.SUBRULE($.classBody);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ClassModifier
+ $.RULE("classModifier", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.annotation) },
+ { ALT: () => $.CONSUME(t.Public) },
+ { ALT: () => $.CONSUME(t.Protected) },
+ { ALT: () => $.CONSUME(t.Private) },
+ { ALT: () => $.CONSUME(t.Abstract) },
+ { ALT: () => $.CONSUME(t.Static) },
+ { ALT: () => $.CONSUME(t.Final) },
+ { ALT: () => $.CONSUME(t.Sealed) },
+ { ALT: () => $.CONSUME(t.NonSealed) },
+ { ALT: () => $.CONSUME(t.Strictfp) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-TypeParameters
+ $.RULE("typeParameters", () => {
+ $.CONSUME(t.Less);
+ $.SUBRULE($.typeParameterList);
+ $.CONSUME(t.Greater);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-TypeParameterList
+ $.RULE("typeParameterList", () => {
+ $.SUBRULE($.typeParameter);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.typeParameter);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ClassExtends
+ $.RULE("superclass", () => {
+ $.CONSUME(t.Extends);
+ $.SUBRULE($.classType);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ClassImplements
+ $.RULE("superinterfaces", () => {
+ $.CONSUME(t.Implements);
+ $.SUBRULE($.interfaceTypeList);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-InterfaceTypeList
+ $.RULE("interfaceTypeList", () => {
+ $.SUBRULE($.interfaceType);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.interfaceType);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/preview/specs/sealed-classes-jls.html
+ $.RULE("classPermits", () => {
+ $.CONSUME(t.Permits);
+ $.SUBRULE($.typeName);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.typeName);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ClassBody
+ $.RULE("classBody", () => {
+ $.CONSUME(t.LCurly);
+ $.MANY(() => {
+ $.SUBRULE($.classBodyDeclaration);
+ });
+ $.CONSUME(t.RCurly);
+ });
+
+ const classBodyTypes = {
+ unknown: 0,
+ fieldDeclaration: 1,
+ methodDeclaration: 2,
+ classDeclaration: 3,
+ interfaceDeclaration: 4,
+ semiColon: 5,
+ instanceInitializer: 6,
+ staticInitializer: 7,
+ constructorDeclaration: 8
+ };
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ClassBodyDeclaration
+ $.RULE("classBodyDeclaration", () => {
+ const nextRuleType = $.BACKTRACK_LOOKAHEAD(
+ $.identifyClassBodyDeclarationType
+ );
+
+ $.OR([
+ {
+ GATE: () =>
+ nextRuleType >= classBodyTypes.fieldDeclaration &&
+ nextRuleType <= classBodyTypes.semiColon,
+ ALT: () =>
+ $.SUBRULE($.classMemberDeclaration, {
+ ARGS: [nextRuleType]
+ })
+ },
+ // no gate needed for the initializers because these are LL(1) rules.
+ { ALT: () => $.SUBRULE($.instanceInitializer) },
+ { ALT: () => $.SUBRULE($.staticInitializer) },
+ {
+ GATE: () =>
+ tokenMatcher(nextRuleType, classBodyTypes.constructorDeclaration),
+ ALT: () => $.SUBRULE($.constructorDeclaration)
+ }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ClassMemberDeclaration
+ $.RULE("classMemberDeclaration", nextRuleType => {
+ $.OR([
+ {
+ GATE: () => nextRuleType === classBodyTypes.fieldDeclaration,
+ ALT: () => $.SUBRULE($.fieldDeclaration)
+ },
+ {
+ GATE: () => nextRuleType === classBodyTypes.methodDeclaration,
+ ALT: () => $.SUBRULE($.methodDeclaration)
+ },
+ {
+ GATE: () => nextRuleType === classBodyTypes.classDeclaration,
+ ALT: () => $.SUBRULE($.classDeclaration)
+ },
+ {
+ GATE: () => nextRuleType === classBodyTypes.interfaceDeclaration,
+ ALT: () => $.SUBRULE($.interfaceDeclaration)
+ },
+ {
+ // No GATE is needed as this is LL(1)
+ ALT: () => $.CONSUME(t.Semicolon)
+ }
+ ]);
+ });
+
+ // // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-FieldDeclaration
+ $.RULE("fieldDeclaration", () => {
+ $.MANY(() => {
+ $.SUBRULE($.fieldModifier);
+ });
+ $.SUBRULE($.unannType);
+ $.SUBRULE($.variableDeclaratorList);
+ $.CONSUME(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-FieldModifier
+ $.RULE("fieldModifier", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.annotation) },
+ { ALT: () => $.CONSUME(t.Public) },
+ { ALT: () => $.CONSUME(t.Protected) },
+ { ALT: () => $.CONSUME(t.Private) },
+ { ALT: () => $.CONSUME(t.Static) },
+ { ALT: () => $.CONSUME(t.Final) },
+ { ALT: () => $.CONSUME(t.Transient) },
+ { ALT: () => $.CONSUME(t.Volatile) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-VariableDeclaratorList
+ $.RULE("variableDeclaratorList", () => {
+ $.SUBRULE($.variableDeclarator);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.variableDeclarator);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-VariableDeclarator
+ $.RULE("variableDeclarator", () => {
+ $.SUBRULE($.variableDeclaratorId);
+ $.OPTION(() => {
+ $.CONSUME(t.Equals);
+ $.SUBRULE($.variableInitializer);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-VariableDeclaratorId
+ $.RULE("variableDeclaratorId", () => {
+ $.CONSUME(t.Identifier);
+ $.OPTION(() => {
+ $.SUBRULE($.dims);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-VariableInitializer
+ $.RULE("variableInitializer", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.expression) },
+ { ALT: () => $.SUBRULE($.arrayInitializer) }
+ ]);
+ });
+
+ // // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-UnannType
+ $.RULE("unannType", () => {
+ $.OR([
+ // Spec Deviation: The array type "dims" suffix was extracted to this rule
+ // to avoid backtracking for performance reasons.
+ { ALT: () => $.SUBRULE($.unannPrimitiveTypeWithOptionalDimsSuffix) },
+ { ALT: () => $.SUBRULE($.unannReferenceType) }
+ ]);
+ });
+
+ $.RULE("unannPrimitiveTypeWithOptionalDimsSuffix", () => {
+ $.SUBRULE($.unannPrimitiveType);
+ $.OPTION({
+ GATE: () => this.BACKTRACK_LOOKAHEAD($.isDims),
+ DEF: () => $.SUBRULE2($.dims)
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-UnannPrimitiveType
+ $.RULE("unannPrimitiveType", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.numericType) },
+ { ALT: () => $.CONSUME(t.Boolean) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-UnannReferenceType
+ $.RULE("unannReferenceType", () => {
+ $.SUBRULE($.unannClassOrInterfaceType);
+ $.OPTION({
+ GATE: () => this.BACKTRACK_LOOKAHEAD($.isDims),
+ DEF: () => $.SUBRULE2($.dims)
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-UnannClassType
+ $.RULE("unannClassOrInterfaceType", () => {
+ // Spec Deviation: The spec says: "UnannClassType | UnannInterfaceType" but "UnannInterfaceType"
+ // is not mentioned in the parser because it is identical to "UnannClassType"
+ // The distinction is **semantic** not syntactic.
+ $.SUBRULE($.unannClassType);
+ });
+
+ $.RULE("unannClassType", () => {
+ // Spec Deviation: Refactored left recursion and alternation to iterations
+ $.CONSUME(t.Identifier);
+ $.OPTION(() => {
+ $.SUBRULE($.typeArguments);
+ });
+ $.MANY2(() => {
+ $.CONSUME(t.Dot);
+ $.MANY3(() => {
+ $.SUBRULE2($.annotation);
+ });
+ // TODO: Semantic Check: This Identifier cannot be "var"
+ $.CONSUME2(t.Identifier);
+ $.OPTION2(() => {
+ $.SUBRULE2($.typeArguments);
+ });
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-UnannInterfaceType
+ $.RULE("unannInterfaceType", () => {
+ $.SUBRULE($.unannClassType);
+ });
+
+ $.RULE("unannTypeVariable", () => {
+ // TODO: Semantic Check: This Identifier cannot be "var"
+ // TODO: or define as token type?
+ $.CONSUME(t.Identifier);
+ });
+
+ // // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-MethodDeclaration
+ $.RULE("methodDeclaration", () => {
+ $.MANY(() => {
+ $.SUBRULE($.methodModifier);
+ });
+ $.SUBRULE($.methodHeader);
+ $.SUBRULE($.methodBody);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-MethodModifier
+ $.RULE("methodModifier", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.annotation) },
+ { ALT: () => $.CONSUME(t.Public) },
+ { ALT: () => $.CONSUME(t.Protected) },
+ { ALT: () => $.CONSUME(t.Private) },
+ { ALT: () => $.CONSUME(t.Abstract) },
+ { ALT: () => $.CONSUME(t.Static) },
+ { ALT: () => $.CONSUME(t.Final) },
+ { ALT: () => $.CONSUME(t.Synchronized) },
+ { ALT: () => $.CONSUME(t.Native) },
+ { ALT: () => $.CONSUME(t.Strictfp) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-MethodHeader
+ $.RULE("methodHeader", () => {
+ // Spec Deviation: extracted common prefix from both alternatives
+ $.OPTION(() => {
+ $.SUBRULE($.typeParameters);
+ $.MANY(() => {
+ $.SUBRULE($.annotation);
+ });
+ });
+ $.SUBRULE($.result);
+ $.SUBRULE($.methodDeclarator);
+ $.OPTION2(() => {
+ $.SUBRULE($.throws);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-Result
+ $.RULE("result", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.unannType) },
+ { ALT: () => $.CONSUME(t.Void) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-MethodDeclarator
+ $.RULE("methodDeclarator", () => {
+ $.CONSUME(t.Identifier);
+ $.CONSUME(t.LBrace);
+ $.OPTION(() => {
+ $.SUBRULE($.formalParameterList);
+ });
+ $.CONSUME(t.RBrace);
+ $.OPTION2(() => {
+ $.SUBRULE($.dims);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ReceiverParameter
+ $.RULE("receiverParameter", () => {
+ $.MANY(() => {
+ $.SUBRULE($.annotation);
+ });
+ $.SUBRULE($.unannType);
+ $.OPTION(() => {
+ $.CONSUME(t.Identifier);
+ $.CONSUME(t.Dot);
+ });
+ $.CONSUME(t.This);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-FormalParameterList
+ $.RULE("formalParameterList", () => {
+ $.SUBRULE($.formalParameter);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.formalParameter);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-FormalParameter
+ $.RULE("formalParameter", () => {
+ $.OR([
+ // Spec Deviation: extracted to "variableParaRegularParameter"
+ {
+ GATE: $.BACKTRACK($.variableParaRegularParameter),
+ ALT: () => $.SUBRULE($.variableParaRegularParameter)
+ },
+ { ALT: () => $.SUBRULE($.variableArityParameter) }
+ ]);
+ });
+
+ // Spec Deviation: extracted from "formalParameter"
+ $.RULE("variableParaRegularParameter", () => {
+ $.MANY(() => {
+ $.SUBRULE($.variableModifier);
+ });
+ $.SUBRULE($.unannType);
+ $.SUBRULE($.variableDeclaratorId);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-VariableArityParameter
+ $.RULE("variableArityParameter", () => {
+ $.MANY(() => {
+ $.SUBRULE($.variableModifier);
+ });
+ $.SUBRULE($.unannType);
+ $.MANY2(() => {
+ $.SUBRULE($.annotation);
+ });
+ $.CONSUME(t.DotDotDot);
+ $.CONSUME(t.Identifier);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-VariableModifier
+ $.RULE("variableModifier", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.annotation) },
+ { ALT: () => $.CONSUME(t.Final) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-Throws
+ $.RULE("throws", () => {
+ $.CONSUME(t.Throws);
+ $.SUBRULE($.exceptionTypeList);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ExceptionTypeList
+ $.RULE("exceptionTypeList", () => {
+ $.SUBRULE($.exceptionType);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.exceptionType);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ExceptionType
+ $.RULE("exceptionType", () => {
+ // Spec Deviation: "typeVariable" alternative is missing because
+ // it is contained in classType.
+ $.SUBRULE($.classType);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-MethodBody
+ $.RULE("methodBody", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.block) },
+ { ALT: () => $.CONSUME(t.Semicolon) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-InstanceInitializer
+ $.RULE("instanceInitializer", () => {
+ $.SUBRULE($.block);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-StaticInitializer
+ $.RULE("staticInitializer", () => {
+ $.CONSUME(t.Static);
+ $.SUBRULE($.block);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ConstructorDeclaration
+ $.RULE("constructorDeclaration", () => {
+ $.MANY(() => {
+ $.SUBRULE($.constructorModifier);
+ });
+ $.SUBRULE($.constructorDeclarator);
+ $.OPTION(() => {
+ $.SUBRULE($.throws);
+ });
+ $.SUBRULE($.constructorBody);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ConstructorModifier
+ $.RULE("constructorModifier", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.annotation) },
+ { ALT: () => $.CONSUME(t.Public) },
+ { ALT: () => $.CONSUME(t.Protected) },
+ { ALT: () => $.CONSUME(t.Private) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ConstructorDeclarator
+ $.RULE("constructorDeclarator", () => {
+ $.OPTION(() => {
+ $.SUBRULE($.typeParameters);
+ });
+ $.SUBRULE($.simpleTypeName);
+ $.CONSUME(t.LBrace);
+ $.OPTION2({
+ // a "formalParameterList" and a "receiverParameter"
+ // cannot be distinguished using fixed lookahead.
+ GATE: $.BACKTRACK($.receiverParameter),
+ DEF: () => {
+ $.SUBRULE($.receiverParameter);
+ $.CONSUME(t.Comma);
+ }
+ });
+ $.OPTION3(() => {
+ $.SUBRULE($.formalParameterList);
+ });
+ $.CONSUME(t.RBrace);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-SimpleTypeName
+ $.RULE("simpleTypeName", () => {
+ // TODO: implement: Identifier but not var
+ $.CONSUME(t.Identifier);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ConstructorBody
+ $.RULE("constructorBody", () => {
+ $.CONSUME(t.LCurly);
+ $.OPTION({
+ GATE: $.BACKTRACK($.explicitConstructorInvocation),
+ DEF: () => {
+ $.SUBRULE($.explicitConstructorInvocation);
+ }
+ });
+ $.OPTION2(() => {
+ $.SUBRULE($.blockStatements);
+ });
+ $.CONSUME(t.RCurly);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-ExplicitConstructorInvocation
+ $.RULE("explicitConstructorInvocation", () => {
+ // Spec Deviation: split into two separate sub rules.
+ $.OR([
+ {
+ ALT: () => $.SUBRULE($.unqualifiedExplicitConstructorInvocation)
+ },
+ { ALT: () => $.SUBRULE($.qualifiedExplicitConstructorInvocation) }
+ ]);
+ });
+
+ $.RULE("unqualifiedExplicitConstructorInvocation", () => {
+ $.OPTION(() => {
+ $.SUBRULE($.typeArguments);
+ });
+ $.OR([
+ {
+ ALT: () => $.CONSUME(t.This)
+ },
+ {
+ ALT: () => $.CONSUME(t.Super)
+ }
+ ]);
+ $.CONSUME(t.LBrace);
+ $.OPTION2(() => {
+ $.SUBRULE($.argumentList);
+ });
+ $.CONSUME(t.RBrace);
+ $.CONSUME(t.Semicolon);
+ });
+
+ $.RULE("qualifiedExplicitConstructorInvocation", () => {
+ // Spec Deviation: According to the spec the prefix may be a "primary' as well,
+ // however, most primary variants don't make sense here
+ // TODO: discover which primary forms could be valid here
+ // and handle only those specific cases.
+ // It is best if we avoid referencing "primary" rule from
+ // outside the expressions rules as the expressions rules are not aligned
+ // to the spec style, so we want the smallest possible "external api"
+ // for the expressions rules.
+ $.SUBRULE($.expressionName);
+ $.CONSUME(t.Dot);
+ $.OPTION(() => {
+ $.SUBRULE($.typeArguments);
+ });
+ $.CONSUME(t.Super);
+ $.CONSUME(t.LBrace);
+ $.OPTION2(() => {
+ $.SUBRULE($.argumentList);
+ });
+ $.CONSUME(t.RBrace);
+ $.CONSUME(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-EnumDeclaration
+ $.RULE("enumDeclaration", () => {
+ $.MANY(() => {
+ $.SUBRULE($.classModifier);
+ });
+ $.CONSUME(t.Enum);
+ $.SUBRULE($.typeIdentifier);
+ $.OPTION(() => {
+ $.SUBRULE($.superinterfaces);
+ });
+ $.SUBRULE($.enumBody);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-EnumBody
+ $.RULE("enumBody", () => {
+ $.CONSUME(t.LCurly);
+ $.OPTION(() => {
+ $.SUBRULE($.enumConstantList);
+ });
+ $.OPTION2(() => {
+ $.CONSUME(t.Comma);
+ });
+ $.OPTION3(() => {
+ $.SUBRULE($.enumBodyDeclarations);
+ });
+ $.CONSUME(t.RCurly);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-EnumConstantList
+ $.RULE("enumConstantList", () => {
+ $.SUBRULE($.enumConstant);
+ $.MANY({
+ GATE: () => {
+ const nextToken = $.LA(2);
+ return (
+ tokenMatcher(nextToken, t.Identifier) || tokenMatcher(nextToken, t.At)
+ );
+ },
+ DEF: () => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.enumConstant);
+ }
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-EnumConstant
+ $.RULE("enumConstant", () => {
+ $.MANY(() => {
+ $.SUBRULE($.enumConstantModifier);
+ });
+ $.CONSUME(t.Identifier);
+ $.OPTION(() => {
+ $.CONSUME(t.LBrace);
+ $.OPTION2(() => {
+ $.SUBRULE($.argumentList);
+ });
+ $.CONSUME(t.RBrace);
+ });
+ $.OPTION3(() => {
+ $.SUBRULE($.classBody);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-EnumConstantModifier
+ $.RULE("enumConstantModifier", () => {
+ $.SUBRULE($.annotation);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-EnumBodyDeclarations
+ $.RULE("enumBodyDeclarations", () => {
+ $.CONSUME(t.Semicolon);
+ $.MANY(() => {
+ $.SUBRULE($.classBodyDeclaration);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-RecordHeader
+ $.RULE("recordDeclaration", () => {
+ $.CONSUME(t.Record);
+ $.SUBRULE($.typeIdentifier);
+ $.OPTION(() => {
+ $.SUBRULE($.typeParameters);
+ });
+ $.SUBRULE($.recordHeader);
+ $.OPTION2(() => {
+ $.SUBRULE($.superinterfaces);
+ });
+ $.SUBRULE($.recordBody);
+ });
+
+ $.RULE("recordHeader", () => {
+ $.CONSUME(t.LBrace);
+ $.OPTION(() => {
+ $.SUBRULE($.recordComponentList);
+ });
+ $.CONSUME(t.RBrace);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-RecordComponentList
+ $.RULE("recordComponentList", () => {
+ $.SUBRULE($.recordComponent);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.recordComponent);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-RecordComponent
+ $.RULE("recordComponent", () => {
+ // Spec Deviation: extracted common "{recordComponentModifier} unannType" prefix
+ // extraction is safe because there are no other references to
+ // "variableArityRecordComponent"
+ $.MANY(() => {
+ $.SUBRULE($.recordComponentModifier);
+ });
+ $.SUBRULE($.unannType);
+ $.OR([
+ { ALT: () => $.CONSUME(t.Identifier) },
+ { ALT: () => $.SUBRULE($.variableArityRecordComponent) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-VariableArityRecordComponent
+ // Spec Deviation: common "{recordComponentModifier} unannType" prefix was extracted in "recordComponent"
+ $.RULE("variableArityRecordComponent", () => {
+ $.MANY(() => {
+ $.SUBRULE($.annotation);
+ });
+ $.CONSUME(t.DotDotDot);
+ $.CONSUME(t.Identifier);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-RecordComponentModifier
+ $.RULE("recordComponentModifier", () => {
+ $.SUBRULE($.annotation);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-RecordBody
+ $.RULE("recordBody", () => {
+ $.CONSUME(t.LCurly);
+ $.MANY(() => {
+ $.SUBRULE($.recordBodyDeclaration);
+ });
+ $.CONSUME(t.RCurly);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-RecordBodyDeclaration
+ $.RULE("recordBodyDeclaration", () => {
+ $.OR([
+ {
+ GATE: () => this.BACKTRACK_LOOKAHEAD($.isCompactConstructorDeclaration),
+ ALT: () => $.SUBRULE($.compactConstructorDeclaration)
+ },
+ { ALT: () => $.SUBRULE($.classBodyDeclaration) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-CompactConstructorDeclaration
+ $.RULE("compactConstructorDeclaration", () => {
+ $.MANY(() => {
+ $.SUBRULE($.constructorModifier);
+ });
+ $.SUBRULE($.simpleTypeName);
+ $.SUBRULE($.constructorBody);
+ });
+
+ $.RULE("isClassDeclaration", () => {
+ let isEmptyTypeDeclaration = false;
+
+ if (
+ $.OPTION(() => {
+ $.CONSUME(t.Semicolon);
+ })
+ ) {
+ // an empty "TypeDeclaration"
+ isEmptyTypeDeclaration = true;
+ }
+
+ try {
+ // The {classModifier} is a super grammar of the "interfaceModifier"
+ // So we must parse all the "{classModifier}" before we can distinguish
+ // between the alternatives.
+ $.MANY({
+ GATE: () =>
+ (tokenMatcher($.LA(1).tokenType, t.At) &&
+ tokenMatcher($.LA(2).tokenType, t.Interface)) === false,
+ DEF: () => {
+ $.SUBRULE($.classModifier);
+ }
+ });
+ } catch (e) {
+ if (isRecognitionException(e)) {
+ // TODO: add original syntax error?
+ throw "Cannot Identify if the is a or an ";
+ } else {
+ throw e;
+ }
+ }
+
+ if (isEmptyTypeDeclaration) {
+ return false;
+ }
+
+ const nextTokenType = this.LA(1).tokenType;
+ return (
+ tokenMatcher(nextTokenType, t.Class) ||
+ tokenMatcher(nextTokenType, t.Enum) ||
+ (tokenMatcher(nextTokenType, t.Record) &&
+ tokenMatcher(this.LA(2).tokenType, t.Identifier))
+ );
+ });
+
+ $.RULE("identifyClassBodyDeclarationType", () => {
+ try {
+ let nextTokenType = this.LA(1).tokenType;
+ let nextNextTokenType = this.LA(2).tokenType;
+
+ switch (nextTokenType) {
+ case t.Semicolon:
+ return classBodyTypes.semiColon;
+ case t.LCurly:
+ return classBodyTypes.instanceInitializer;
+ case t.Static:
+ switch (nextNextTokenType) {
+ case t.LCurly:
+ return classBodyTypes.staticInitializer;
+ }
+ }
+
+ // We have to look beyond the modifiers to distinguish between the declaration types.
+ $.MANY({
+ GATE: () =>
+ (tokenMatcher($.LA(1).tokenType, t.At) &&
+ tokenMatcher($.LA(2).tokenType, t.Interface)) === false,
+ DEF: () => {
+ // This alternation includes all possible modifiers for all types of "ClassBodyDeclaration"
+ // Certain combinations are syntactically invalid, this is **not** checked here,
+ // Invalid combinations will cause a descriptive parsing error message to be
+ // Created inside the relevant parsing rules **after** this lookahead
+ // analysis.
+ $.OR([
+ {
+ GATE: () =>
+ (tokenMatcher($.LA(1).tokenType, t.At) &&
+ tokenMatcher($.LA(2).tokenType, t.Interface)) === false,
+ ALT: () => $.SUBRULE($.annotation)
+ },
+ { ALT: () => $.CONSUME(t.Public) },
+ { ALT: () => $.CONSUME(t.Protected) },
+ { ALT: () => $.CONSUME(t.Private) },
+ { ALT: () => $.CONSUME(t.Abstract) },
+ { ALT: () => $.CONSUME(t.Static) },
+ { ALT: () => $.CONSUME(t.Final) },
+ { ALT: () => $.CONSUME(t.Transient) },
+ { ALT: () => $.CONSUME(t.Volatile) },
+ { ALT: () => $.CONSUME(t.Synchronized) },
+ { ALT: () => $.CONSUME(t.Native) },
+ { ALT: () => $.CONSUME(t.Sealed) },
+ { ALT: () => $.CONSUME(t.NonSealed) },
+ { ALT: () => $.CONSUME(t.Strictfp) }
+ ]);
+ }
+ });
+
+ nextTokenType = this.LA(1).tokenType;
+ nextNextTokenType = this.LA(2).tokenType;
+ if (
+ tokenMatcher(nextTokenType, t.Identifier) &&
+ tokenMatcher(nextNextTokenType, t.LBrace)
+ ) {
+ return classBodyTypes.constructorDeclaration;
+ }
+
+ if (
+ tokenMatcher(nextTokenType, t.Class) ||
+ tokenMatcher(nextTokenType, t.Enum) ||
+ tokenMatcher(nextTokenType, t.Record)
+ ) {
+ return classBodyTypes.classDeclaration;
+ }
+
+ if (
+ tokenMatcher(nextTokenType, t.Interface) ||
+ tokenMatcher(nextTokenType, t.At)
+ ) {
+ return classBodyTypes.interfaceDeclaration;
+ }
+
+ if (tokenMatcher(nextTokenType, t.Void)) {
+ // method with result type "void"
+ return classBodyTypes.methodDeclaration;
+ }
+
+ // Type Arguments common prefix
+ if (tokenMatcher(nextTokenType, t.Less)) {
+ this.SUBRULE($.typeParameters);
+ const nextTokenType = this.LA(1).tokenType;
+ const nextNextTokenType = this.LA(2).tokenType;
+ // " foo(" -> constructor
+ if (
+ tokenMatcher(nextTokenType, t.Identifier) &&
+ tokenMatcher(nextNextTokenType, t.LBrace)
+ ) {
+ return classBodyTypes.constructorDeclaration;
+ }
+ // typeParameters can only appear in method or constructor
+ // declarations, so if it is not a constructor it must be a method
+ return classBodyTypes.methodDeclaration;
+ }
+
+ // Only field or method declarations may be valid at this point.
+ // All other alternatives should have been attempted.
+ // **both** start with "unannType"
+ this.SUBRULE($.unannType);
+
+ const nextToken = this.LA(1);
+ nextNextTokenType = this.LA(2).tokenType;
+ // "foo(..." --> look like method start
+ if (
+ tokenMatcher(nextToken, t.Identifier) &&
+ tokenMatcher(nextNextTokenType, t.LBrace)
+ ) {
+ return classBodyTypes.methodDeclaration;
+ }
+
+ // a valid field
+ // TODO: because we use token categories we should use tokenMatcher everywhere.
+ if (tokenMatcher(nextToken, t.Identifier)) {
+ return classBodyTypes.fieldDeclaration;
+ }
+
+ return classBodyTypes.unknown;
+ } catch (e) {
+ // TODO: add info from the original error
+ throw Error("Cannot Identify the type of a ");
+ }
+ });
+
+ $.RULE("isDims", () => {
+ $.MANY($.annotation);
+ return (
+ tokenMatcher(this.LA(1).tokenType, t.LSquare) &&
+ tokenMatcher(this.LA(2).tokenType, t.RSquare)
+ );
+ });
+
+ $.RULE("isCompactConstructorDeclaration", () => {
+ $.MANY($.constructorModifier);
+ $.SUBRULE($.simpleTypeName);
+ $.CONSUME(t.LCurly);
+ });
+}
+
+module.exports = {
+ defineRules
+};
diff --git a/node_modules/java-parser/src/productions/expressions.js b/node_modules/java-parser/src/productions/expressions.js
new file mode 100644
index 0000000..41a6500
--- /dev/null
+++ b/node_modules/java-parser/src/productions/expressions.js
@@ -0,0 +1,705 @@
+"use strict";
+const { tokenMatcher } = require("chevrotain");
+function defineRules($, t) {
+ $.RULE("expression", () => {
+ $.OR([
+ {
+ GATE: () => this.BACKTRACK_LOOKAHEAD($.isLambdaExpression),
+ ALT: () => $.SUBRULE($.lambdaExpression)
+ },
+ { ALT: () => $.SUBRULE($.ternaryExpression) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-LambdaExpression
+ $.RULE("lambdaExpression", () => {
+ $.SUBRULE($.lambdaParameters);
+ $.CONSUME(t.Arrow);
+ $.SUBRULE($.lambdaBody);
+ });
+
+ $.RULE("lambdaParameters", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.lambdaParametersWithBraces) },
+ { ALT: () => $.CONSUME(t.Identifier) }
+ ]);
+ });
+
+ $.RULE("lambdaParametersWithBraces", () => {
+ $.CONSUME(t.LBrace);
+ $.OPTION(() => {
+ $.SUBRULE($.lambdaParameterList);
+ });
+ $.CONSUME(t.RBrace);
+ });
+
+ $.RULE("lambdaParameterList", () => {
+ $.OR([
+ {
+ GATE: () => {
+ const nextTokType = this.LA(1).tokenType;
+ const nextNextTokType = this.LA(2).tokenType;
+ return (
+ tokenMatcher(nextTokType, t.Identifier) &&
+ (tokenMatcher(nextNextTokType, t.RBrace) ||
+ tokenMatcher(nextNextTokType, t.Comma))
+ );
+ },
+ ALT: () => $.SUBRULE($.inferredLambdaParameterList)
+ },
+ { ALT: () => $.SUBRULE($.explicitLambdaParameterList) }
+ ]);
+ });
+
+ $.RULE("inferredLambdaParameterList", () => {
+ $.CONSUME(t.Identifier);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.CONSUME2(t.Identifier);
+ });
+ });
+
+ $.RULE("explicitLambdaParameterList", () => {
+ $.SUBRULE($.lambdaParameter);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.lambdaParameter);
+ });
+ });
+
+ $.RULE("lambdaParameter", () => {
+ // TODO: performance, investigate the performance boost that could
+ // be gained by refactoring out the backtracking.
+ $.OR([
+ {
+ GATE: $.BACKTRACK($.regularLambdaParameter),
+ ALT: () => $.SUBRULE($.regularLambdaParameter)
+ },
+ { ALT: () => $.SUBRULE($.variableArityParameter) }
+ ]);
+ });
+
+ $.RULE("regularLambdaParameter", () => {
+ $.MANY(() => {
+ $.SUBRULE($.variableModifier);
+ });
+ $.SUBRULE($.lambdaParameterType);
+ $.SUBRULE($.variableDeclaratorId);
+ });
+
+ $.RULE("lambdaParameterType", () => {
+ $.OR({
+ DEF: [
+ { ALT: () => $.SUBRULE($.unannType) },
+ { ALT: () => $.CONSUME(t.Var) }
+ ],
+ IGNORE_AMBIGUITIES: true
+ });
+ });
+
+ $.RULE("lambdaBody", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.expression) },
+ { ALT: () => $.SUBRULE($.block) }
+ ]);
+ });
+
+ $.RULE("ternaryExpression", () => {
+ $.SUBRULE($.binaryExpression);
+ $.OPTION(() => {
+ $.CONSUME(t.QuestionMark);
+ $.SUBRULE($.expression);
+ $.CONSUME(t.Colon);
+ // TODO: in the grammar this is limited to "lambdaExpression: or "conditionalExpression"
+ $.SUBRULE2($.expression);
+ });
+ });
+
+ $.RULE("binaryExpression", () => {
+ $.SUBRULE($.unaryExpression);
+ $.MANY(() => {
+ $.OR({
+ DEF: [
+ {
+ ALT: () => {
+ $.CONSUME(t.Instanceof);
+ $.OR1([
+ {
+ GATE: () => this.BACKTRACK_LOOKAHEAD($.pattern),
+ ALT: () => $.SUBRULE($.pattern)
+ },
+ {
+ ALT: () => $.SUBRULE($.referenceType)
+ }
+ ]);
+ }
+ },
+ {
+ ALT: () => {
+ $.CONSUME(t.AssignmentOperator);
+ $.SUBRULE2($.expression);
+ }
+ },
+ // This is an example of why Java does not have a well designed grammar
+ // See: https://manas.tech/blog/2008/10/12/why-java-generics-dont-have-problems-with-right-shift-operator.html
+ // TODO: ensure the LT/GT sequences have no whitespace between each other.
+ {
+ // TODO: this is a bug in Chevrotain lookahead calculation. the "BinaryOperator" token can match "Less" or "Greater"
+ // as well, but because it is a **token Category** Chevrotain does not understand it need to looks two tokens ahead.
+ GATE: () =>
+ tokenMatcher($.LA(2).tokenType, t.Less) ||
+ tokenMatcher($.LA(2).tokenType, t.Greater),
+ ALT: () => {
+ $.OR2([
+ {
+ GATE: () => $.LA(1).startOffset + 1 === $.LA(2).startOffset,
+ ALT: () => {
+ $.CONSUME(t.Less);
+ $.CONSUME2(t.Less);
+ }
+ },
+ {
+ GATE: () => $.LA(1).startOffset + 1 === $.LA(2).startOffset,
+ ALT: () => {
+ $.CONSUME(t.Greater);
+ $.CONSUME2(t.Greater);
+ $.OPTION({
+ GATE: () =>
+ $.LA(0).startOffset + 1 === $.LA(1).startOffset,
+ DEF: () => $.CONSUME3(t.Greater)
+ });
+ }
+ }
+ ]);
+ $.SUBRULE2($.unaryExpression);
+ }
+ },
+ {
+ ALT: () => {
+ $.CONSUME(t.BinaryOperator);
+ $.SUBRULE3($.unaryExpression);
+ }
+ }
+ ],
+ IGNORE_AMBIGUITIES: true // the ambiguity between 1 and 4 options is resolved by the order (instanceOf is first)
+ });
+ });
+ });
+
+ $.RULE("unaryExpression", () => {
+ $.MANY(() => {
+ $.CONSUME(t.UnaryPrefixOperator);
+ });
+ $.SUBRULE($.primary);
+ $.MANY2(() => {
+ $.CONSUME(t.UnarySuffixOperator);
+ });
+ });
+
+ $.RULE("unaryExpressionNotPlusMinus", () => {
+ $.MANY(() => {
+ $.CONSUME(t.UnaryPrefixOperatorNotPlusMinus);
+ });
+ $.SUBRULE($.primary);
+ $.MANY2(() => {
+ $.CONSUME(t.UnarySuffixOperator);
+ });
+ });
+
+ $.RULE("primary", () => {
+ $.SUBRULE($.primaryPrefix);
+ $.MANY(() => {
+ $.SUBRULE($.primarySuffix);
+ });
+ });
+
+ $.RULE("primaryPrefix", () => {
+ let isCastExpression = false;
+ if (tokenMatcher($.LA(1).tokenType, t.LBrace)) {
+ isCastExpression = this.BACKTRACK_LOOKAHEAD($.isCastExpression);
+ }
+
+ $.OR([
+ { ALT: () => $.SUBRULE($.literal) },
+ { ALT: () => $.CONSUME(t.This) },
+ { ALT: () => $.CONSUME(t.Void) },
+ { ALT: () => $.SUBRULE($.unannPrimitiveTypeWithOptionalDimsSuffix) },
+ { ALT: () => $.SUBRULE($.fqnOrRefType) },
+ {
+ GATE: () => isCastExpression,
+ ALT: () => $.SUBRULE($.castExpression)
+ },
+ { ALT: () => $.SUBRULE($.parenthesisExpression) },
+ { ALT: () => $.SUBRULE($.newExpression) },
+ { ALT: () => $.SUBRULE($.switchStatement) }
+ ]);
+ });
+
+ $.RULE("primarySuffix", () => {
+ $.OR({
+ DEF: [
+ {
+ ALT: () => {
+ $.CONSUME(t.Dot);
+ $.OR2([
+ { ALT: () => $.CONSUME(t.This) },
+ {
+ ALT: () =>
+ $.SUBRULE($.unqualifiedClassInstanceCreationExpression)
+ },
+ {
+ ALT: () => {
+ $.OPTION(() => {
+ $.SUBRULE($.typeArguments);
+ });
+ $.CONSUME(t.Identifier);
+ }
+ }
+ ]);
+ }
+ },
+ { ALT: () => $.SUBRULE($.methodInvocationSuffix) },
+ { ALT: () => $.SUBRULE($.classLiteralSuffix) },
+ { ALT: () => $.SUBRULE($.arrayAccessSuffix) },
+ { ALT: () => $.SUBRULE($.methodReferenceSuffix) }
+ ],
+ MAX_LOOKAHEAD: 2
+ });
+ });
+
+ // See https://github.com/jhipster/prettier-java/pull/154 to understand
+ // why fqnOrRefTypePart is split in two rules (First and Rest)
+ $.RULE("fqnOrRefType", () => {
+ $.SUBRULE($.fqnOrRefTypePartFirst);
+
+ $.MANY2({
+ // ".class" is a classLiteralSuffix
+ GATE: () =>
+ // avoids ambiguity with ".this" and ".new" which are parsed as a primary suffix.
+ tokenMatcher(this.LA(2).tokenType, t.Class) === false &&
+ tokenMatcher(this.LA(2).tokenType, t.This) === false &&
+ tokenMatcher(this.LA(2).tokenType, t.New) === false,
+ DEF: () => {
+ $.CONSUME(t.Dot);
+ $.SUBRULE2($.fqnOrRefTypePartRest);
+ }
+ });
+
+ // in case of an arrayType
+ $.OPTION({
+ // it is not enough to check only the opening "[", we must avoid conflict with
+ // arrayAccessSuffix
+ GATE: () =>
+ tokenMatcher($.LA(1).tokenType, t.At) ||
+ tokenMatcher($.LA(2).tokenType, t.RSquare),
+ DEF: () => {
+ $.SUBRULE($.dims);
+ }
+ });
+ });
+
+ // TODO: validation:
+ // 1. "annotation" cannot be mixed with "methodTypeArguments" or "Super".
+ // 2. "methodTypeArguments" cannot be mixed with "classTypeArguments" or "annotation".
+ // 3. "Super" cannot be mixed with "classTypeArguments" or "annotation".
+ // 4. At most one "Super" may be used.
+ // 5. "Super" may be last or one before last (last may also be first if there is only a single part).
+ $.RULE("fqnOrRefTypePartRest", () => {
+ $.MANY(() => {
+ $.SUBRULE($.annotation);
+ });
+
+ $.OPTION(() => $.SUBRULE2($.typeArguments));
+
+ $.SUBRULE($.fqnOrRefTypePartCommon);
+ });
+
+ $.RULE("fqnOrRefTypePartCommon", () => {
+ $.OR([
+ { ALT: () => $.CONSUME(t.Identifier) },
+ { ALT: () => $.CONSUME(t.Super) }
+ ]);
+
+ let isRefTypeInMethodRef = false;
+ // Performance optimization, only perform this backtracking when a '<' is found
+ // TODO: performance optimization evaluation: avoid doing this backtracking for every "<" encountered.
+ // we could do it once (using global state) per "fqnOrRefType"
+ // We could do it only once for
+ if (tokenMatcher($.LA(1).tokenType, t.Less)) {
+ isRefTypeInMethodRef = this.BACKTRACK_LOOKAHEAD($.isRefTypeInMethodRef);
+ }
+
+ $.OPTION2({
+ // unrestricted typeArguments here would create an ambiguity with "LessThan" operator
+ // e.g: "var x = a < b;"
+ // The "<" would be parsed as the beginning of a "typeArguments"
+ // and we will get an error: "expecting '>' but found: ';'"
+ GATE: () => isRefTypeInMethodRef,
+ DEF: () => {
+ $.SUBRULE3($.typeArguments);
+ }
+ });
+ });
+
+ $.RULE("fqnOrRefTypePartFirst", () => {
+ $.MANY(() => {
+ $.SUBRULE($.annotation);
+ });
+
+ $.SUBRULE($.fqnOrRefTypePartCommon);
+ });
+
+ $.RULE("parenthesisExpression", () => {
+ $.CONSUME(t.LBrace);
+ $.SUBRULE($.expression);
+ $.CONSUME(t.RBrace);
+ });
+
+ $.RULE("castExpression", () => {
+ $.OR([
+ {
+ // TODO: performance: can avoid backtracking again here, parent rule could have this information
+ // when it checks isCastExpression (refactor needed)
+ GATE: () => this.BACKTRACK_LOOKAHEAD($.isPrimitiveCastExpression),
+ ALT: () => $.SUBRULE($.primitiveCastExpression)
+ },
+ { ALT: () => $.SUBRULE($.referenceTypeCastExpression) }
+ ]);
+ });
+
+ $.RULE("primitiveCastExpression", () => {
+ $.CONSUME(t.LBrace);
+ $.SUBRULE($.primitiveType);
+ $.CONSUME(t.RBrace);
+ $.SUBRULE($.unaryExpression);
+ });
+
+ $.RULE("referenceTypeCastExpression", () => {
+ $.CONSUME(t.LBrace);
+ $.SUBRULE($.referenceType);
+ $.MANY(() => {
+ $.SUBRULE($.additionalBound);
+ });
+ $.CONSUME(t.RBrace);
+ $.OR([
+ {
+ GATE: () => this.BACKTRACK_LOOKAHEAD($.isLambdaExpression),
+ ALT: () => $.SUBRULE($.lambdaExpression)
+ },
+ { ALT: () => $.SUBRULE($.unaryExpressionNotPlusMinus) }
+ ]);
+ });
+
+ const newExpressionTypes = {
+ arrayCreationExpression: 1,
+ unqualifiedClassInstanceCreationExpression: 2
+ };
+ $.RULE("newExpression", () => {
+ const type = this.BACKTRACK_LOOKAHEAD($.identifyNewExpressionType);
+
+ $.OR([
+ {
+ GATE: () => type === newExpressionTypes.arrayCreationExpression,
+ ALT: () => $.SUBRULE($.arrayCreationExpression)
+ },
+ {
+ GATE: () =>
+ type ===
+ newExpressionTypes.unqualifiedClassInstanceCreationExpression,
+ ALT: () => $.SUBRULE($.unqualifiedClassInstanceCreationExpression)
+ }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-UnqualifiedClassInstanceCreationExpression
+ $.RULE("unqualifiedClassInstanceCreationExpression", () => {
+ $.CONSUME(t.New);
+ $.OPTION(() => {
+ $.SUBRULE($.typeArguments);
+ });
+ $.SUBRULE($.classOrInterfaceTypeToInstantiate);
+ $.CONSUME(t.LBrace);
+ $.OPTION2(() => {
+ $.SUBRULE($.argumentList);
+ });
+ $.CONSUME(t.RBrace);
+ $.OPTION3(() => {
+ $.SUBRULE($.classBody);
+ });
+ });
+
+ $.RULE("classOrInterfaceTypeToInstantiate", () => {
+ $.MANY(() => {
+ $.SUBRULE($.annotation);
+ });
+ $.CONSUME(t.Identifier);
+ $.MANY2(() => {
+ $.CONSUME(t.Dot);
+ $.MANY3(() => {
+ $.SUBRULE2($.annotation);
+ });
+ $.CONSUME2(t.Identifier);
+ });
+ $.OPTION(() => {
+ $.SUBRULE($.typeArgumentsOrDiamond);
+ });
+ });
+
+ $.RULE("typeArgumentsOrDiamond", () => {
+ $.OR({
+ DEF: [
+ { ALT: () => $.SUBRULE($.diamond) },
+ { ALT: () => $.SUBRULE($.typeArguments) }
+ ],
+ MAX_LOOKAHEAD: 2
+ });
+ });
+
+ $.RULE("diamond", () => {
+ $.CONSUME(t.Less);
+ $.CONSUME(t.Greater);
+ });
+
+ $.RULE("methodInvocationSuffix", () => {
+ $.CONSUME(t.LBrace);
+ $.OPTION2(() => {
+ $.SUBRULE($.argumentList);
+ });
+ $.CONSUME(t.RBrace);
+ });
+
+ $.RULE("argumentList", () => {
+ $.SUBRULE($.expression);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.expression);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-15.10.1
+ $.RULE("arrayCreationExpression", () => {
+ $.CONSUME(t.New);
+ $.OR([
+ {
+ GATE: $.BACKTRACK($.primitiveType),
+ ALT: () => $.SUBRULE($.primitiveType)
+ },
+ { ALT: () => $.SUBRULE($.classOrInterfaceType) }
+ ]);
+
+ $.OR2([
+ {
+ GATE: $.BACKTRACK($.arrayCreationDefaultInitSuffix),
+ ALT: () => $.SUBRULE($.arrayCreationDefaultInitSuffix)
+ },
+ { ALT: () => $.SUBRULE($.arrayCreationExplicitInitSuffix) }
+ ]);
+ });
+
+ $.RULE("arrayCreationDefaultInitSuffix", () => {
+ $.SUBRULE($.dimExprs);
+ $.OPTION(() => {
+ $.SUBRULE($.dims);
+ });
+ });
+
+ $.RULE("arrayCreationExplicitInitSuffix", () => {
+ $.SUBRULE($.dims);
+ $.SUBRULE($.arrayInitializer);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-DimExprs
+ $.RULE("dimExprs", () => {
+ $.SUBRULE($.dimExpr);
+ $.MANY({
+ // The GATE is to distinguish DimExpr from Dims :
+ // the only difference between these two is the presence of an expression in the DimExpr
+ // Example: If the GATE is not present double[3][] won't be parsed as the parser will try to parse "[]"
+ // as a dimExpr instead of a dims
+ GATE: () => tokenMatcher($.LA(2).tokenType, t.RSquare) === false,
+ DEF: () => $.SUBRULE2($.dimExpr)
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-15.html#jls-DimExpr
+ $.RULE("dimExpr", () => {
+ $.MANY(() => {
+ $.SUBRULE($.annotation);
+ });
+ $.CONSUME(t.LSquare);
+ $.SUBRULE($.expression);
+ $.CONSUME(t.RSquare);
+ });
+
+ $.RULE("classLiteralSuffix", () => {
+ $.MANY(() => {
+ $.CONSUME(t.LSquare);
+ $.CONSUME(t.RSquare);
+ });
+ $.CONSUME(t.Dot);
+ $.CONSUME(t.Class);
+ });
+
+ $.RULE("arrayAccessSuffix", () => {
+ $.CONSUME(t.LSquare);
+ $.SUBRULE($.expression);
+ $.CONSUME(t.RSquare);
+ });
+
+ $.RULE("methodReferenceSuffix", () => {
+ $.CONSUME(t.ColonColon);
+ $.OPTION(() => {
+ $.SUBRULE($.typeArguments);
+ });
+
+ $.OR([
+ { ALT: () => $.CONSUME(t.Identifier) },
+ // TODO: a constructor method reference ("new") can only be used
+ // in specific contexts, but perhaps this verification is best left
+ // for a semantic analysis phase
+ { ALT: () => $.CONSUME(t.New) }
+ ]);
+ });
+
+ $.RULE("pattern", () => {
+ $.SUBRULE($.typePattern);
+ });
+
+ $.RULE("typePattern", () => {
+ $.SUBRULE($.localVariableDeclaration);
+ });
+
+ // backtracking lookahead logic
+ $.RULE("identifyNewExpressionType", () => {
+ $.CONSUME(t.New);
+ const firstTokenAfterNew = this.LA(1).tokenType;
+
+ // not an array initialization due to the prefix "TypeArguments"
+ if (tokenMatcher(firstTokenAfterNew, t.Less)) {
+ return newExpressionTypes.unqualifiedClassInstanceCreationExpression;
+ }
+
+ try {
+ $.SUBRULE($.classOrInterfaceTypeToInstantiate);
+ } catch (e) {
+ // if it is not a "classOrInterfaceTypeToInstantiate" then
+ // (assuming a valid input) we are looking at an "arrayCreationExpression"
+ return newExpressionTypes.arrayCreationExpression;
+ }
+
+ const firstTokenAfterClassType = this.LA(1).tokenType;
+ if (tokenMatcher(firstTokenAfterClassType, t.LBrace)) {
+ return newExpressionTypes.unqualifiedClassInstanceCreationExpression;
+ }
+
+ // The LBrace above is mandatory in "classInstanceCreation..." so
+ // it must be an "arrayCreationExp" (if the input is valid)
+ // TODO: upgrade the logic to return "unknown" type if at this
+ // point it does not match "arrayCreation" either.
+ // - This will provide a better error message to the user
+ // in case of invalid inputs
+ return newExpressionTypes.arrayCreationExpression;
+ });
+
+ // Optimized backtracking, only scan ahead until the arrow("->").
+ $.RULE("isLambdaExpression", () => {
+ // TODO: this check of next two tokens is probably redundant as the normal lookahead should take care of this.
+ const firstTokenType = this.LA(1).tokenType;
+ const secondTokenType = this.LA(2).tokenType;
+ // no parent lambda "x -> x * 2"
+ if (
+ tokenMatcher(firstTokenType, t.Identifier) &&
+ tokenMatcher(secondTokenType, t.Arrow)
+ ) {
+ return true;
+ }
+ // Performance optimizations, fail fast if it is not a LBrace.
+ else if (tokenMatcher(firstTokenType, t.LBrace)) {
+ $.SUBRULE($.lambdaParametersWithBraces);
+ const followedByArrow = tokenMatcher(this.LA(1).tokenType, t.Arrow);
+ return followedByArrow;
+ }
+ return false;
+ });
+
+ $.RULE("isCastExpression", () => {
+ if (this.BACKTRACK_LOOKAHEAD($.isPrimitiveCastExpression)) {
+ return true;
+ }
+ return this.BACKTRACK_LOOKAHEAD($.isReferenceTypeCastExpression);
+ });
+
+ $.RULE("isPrimitiveCastExpression", () => {
+ $.CONSUME(t.LBrace);
+ $.SUBRULE($.primitiveType);
+ // No dims so this is not a reference Type
+ $.CONSUME(t.RBrace);
+ return true;
+ });
+
+ $.RULE("isReferenceTypeCastExpression", () => {
+ $.CONSUME(t.LBrace);
+ $.SUBRULE($.referenceType);
+ $.MANY(() => {
+ $.SUBRULE($.additionalBound);
+ });
+ $.CONSUME(t.RBrace);
+ const firstTokTypeAfterRBrace = this.LA(1).tokenType;
+
+ return (
+ this.firstForUnaryExpressionNotPlusMinus.find(tokType =>
+ tokenMatcher(firstTokTypeAfterRBrace, tokType)
+ ) !== undefined
+ );
+ });
+
+ $.RULE("isRefTypeInMethodRef", () => {
+ let result = undefined;
+ $.SUBRULE($.typeArguments);
+
+ // arrayType
+ const hasDims = $.OPTION(() => {
+ $.SUBRULE($.dims);
+ });
+
+ const firstTokTypeAfterTypeArgs = this.LA(1).tokenType;
+ if (tokenMatcher(firstTokTypeAfterTypeArgs, t.ColonColon)) {
+ result = true;
+ }
+ // we must be at the end of a "referenceType" if "dims" were encountered
+ // So there is not point to check farther
+ else if (hasDims) {
+ result = false;
+ }
+
+ // in the middle of a "classReferenceType"
+ $.OPTION2(() => {
+ $.CONSUME(t.Dot);
+ $.SUBRULE($.classOrInterfaceType);
+ });
+
+ if (result !== undefined) {
+ return result;
+ }
+
+ const firstTokTypeAfterRefType = this.LA(1).tokenType;
+ return tokenMatcher(firstTokTypeAfterRefType, t.ColonColon);
+ });
+}
+
+function computeFirstForUnaryExpressionNotPlusMinus() {
+ const firstUnaryExpressionNotPlusMinus = this.computeContentAssist(
+ "unaryExpressionNotPlusMinus",
+ []
+ );
+ const nextTokTypes = firstUnaryExpressionNotPlusMinus.map(
+ x => x.nextTokenType
+ );
+ // uniq
+ return nextTokTypes.filter((v, i, a) => a.indexOf(v) === i);
+}
+
+module.exports = {
+ defineRules,
+ computeFirstForUnaryExpressionNotPlusMinus
+};
diff --git a/node_modules/java-parser/src/productions/interfaces.js b/node_modules/java-parser/src/productions/interfaces.js
new file mode 100644
index 0000000..2405878
--- /dev/null
+++ b/node_modules/java-parser/src/productions/interfaces.js
@@ -0,0 +1,507 @@
+"use strict";
+const { tokenMatcher } = require("chevrotain");
+
+function defineRules($, t) {
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-InterfaceDeclaration
+ $.RULE("interfaceDeclaration", () => {
+ // Spec Deviation: extracted the common "interfaceModifier" prefix to avoid backtracking.
+ $.MANY({
+ DEF: () => {
+ $.SUBRULE($.interfaceModifier);
+ },
+ MAX_LOOKAHEAD: 2
+ });
+
+ $.OR([
+ { ALT: () => $.SUBRULE($.normalInterfaceDeclaration) },
+ { ALT: () => $.SUBRULE($.annotationTypeDeclaration) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-NormalInterfaceDeclaration
+ $.RULE("normalInterfaceDeclaration", () => {
+ // Spec Deviation: The "interfaceModifier" prefix was extracted to the "interfaceDeclaration"
+ $.CONSUME(t.Interface);
+ $.SUBRULE($.typeIdentifier);
+ $.OPTION(() => {
+ $.SUBRULE($.typeParameters);
+ });
+ $.OPTION2(() => {
+ $.SUBRULE($.extendsInterfaces);
+ });
+ $.OPTION3(() => {
+ $.SUBRULE($.interfacePermits);
+ });
+ $.SUBRULE($.interfaceBody);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-InterfaceModifier
+ $.RULE("interfaceModifier", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.annotation) },
+ { ALT: () => $.CONSUME(t.Public) },
+ { ALT: () => $.CONSUME(t.Protected) },
+ { ALT: () => $.CONSUME(t.Private) },
+ { ALT: () => $.CONSUME(t.Abstract) },
+ { ALT: () => $.CONSUME(t.Static) },
+ { ALT: () => $.CONSUME(t.Sealed) },
+ { ALT: () => $.CONSUME(t.NonSealed) },
+ { ALT: () => $.CONSUME(t.Strictfp) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-InterfaceExtends
+ $.RULE("extendsInterfaces", () => {
+ $.CONSUME(t.Extends);
+ $.SUBRULE($.interfaceTypeList);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/preview/specs/sealed-classes-jls.html
+ $.RULE("interfacePermits", () => {
+ $.CONSUME(t.Permits);
+ $.SUBRULE($.typeName);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.typeName);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-InterfaceBody
+ $.RULE("interfaceBody", () => {
+ $.CONSUME(t.LCurly);
+ $.MANY(() => {
+ $.SUBRULE($.interfaceMemberDeclaration);
+ });
+ $.CONSUME(t.RCurly);
+ });
+
+ const InterfaceBodyTypes = {
+ unknown: 0,
+ constantDeclaration: 1,
+ interfaceMethodDeclaration: 2,
+ classDeclaration: 3,
+ interfaceDeclaration: 4,
+ semiColon: 5
+ };
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-InterfaceMemberDeclaration
+ $.RULE("interfaceMemberDeclaration", () => {
+ const detectedType = this.BACKTRACK_LOOKAHEAD(
+ $.identifyInterfaceBodyDeclarationType
+ );
+
+ $.OR([
+ {
+ GATE: () => detectedType === InterfaceBodyTypes.constantDeclaration,
+ ALT: () => $.SUBRULE($.constantDeclaration)
+ },
+ {
+ GATE: () =>
+ detectedType === InterfaceBodyTypes.interfaceMethodDeclaration,
+ ALT: () => $.SUBRULE($.interfaceMethodDeclaration)
+ },
+ {
+ GATE: () => detectedType === InterfaceBodyTypes.classDeclaration,
+ ALT: () => $.SUBRULE($.classDeclaration)
+ },
+ {
+ GATE: () => detectedType === InterfaceBodyTypes.interfaceDeclaration,
+ ALT: () => $.SUBRULE($.interfaceDeclaration)
+ },
+ {
+ // No GATE is needed as this is LL(1)
+ ALT: () => $.CONSUME(t.Semicolon)
+ }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-ConstantDeclaration
+ $.RULE("constantDeclaration", () => {
+ $.MANY(() => {
+ $.SUBRULE($.constantModifier);
+ });
+ $.SUBRULE($.unannType);
+ $.SUBRULE($.variableDeclaratorList);
+ $.CONSUME(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-ConstantModifier
+ $.RULE("constantModifier", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.annotation) },
+ { ALT: () => $.CONSUME(t.Public) },
+ { ALT: () => $.CONSUME(t.Static) },
+ { ALT: () => $.CONSUME(t.Final) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-InterfaceMethodDeclaration
+ $.RULE("interfaceMethodDeclaration", () => {
+ $.MANY(() => {
+ $.SUBRULE($.interfaceMethodModifier);
+ });
+ $.SUBRULE($.methodHeader);
+ $.SUBRULE($.methodBody);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-InterfaceMethodModifier
+ $.RULE("interfaceMethodModifier", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.annotation) },
+ { ALT: () => $.CONSUME(t.Public) },
+ { ALT: () => $.CONSUME(t.Private) },
+ { ALT: () => $.CONSUME(t.Abstract) },
+ { ALT: () => $.CONSUME(t.Default) },
+ { ALT: () => $.CONSUME(t.Static) },
+ { ALT: () => $.CONSUME(t.Strictfp) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-AnnotationTypeDeclaration
+ $.RULE("annotationTypeDeclaration", () => {
+ // Spec Deviation: The "interfaceModifier" prefix was extracted to the "interfaceDeclaration"
+ $.CONSUME(t.At);
+ $.CONSUME(t.Interface);
+ $.SUBRULE($.typeIdentifier);
+ $.SUBRULE($.annotationTypeBody);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-AnnotationTypeBody
+ $.RULE("annotationTypeBody", () => {
+ $.CONSUME(t.LCurly);
+ $.MANY(() => {
+ $.SUBRULE($.annotationTypeMemberDeclaration);
+ });
+ $.CONSUME(t.RCurly);
+ });
+
+ const AnnotationBodyTypes = {
+ unknown: 0,
+ annotationTypeElementDeclaration: 2,
+ constantDeclaration: 1,
+ classDeclaration: 3,
+ interfaceDeclaration: 4,
+ semiColon: 5
+ };
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-InterfaceMemberDeclaration
+ $.RULE("annotationTypeMemberDeclaration", () => {
+ const detectedType = this.BACKTRACK_LOOKAHEAD(
+ $.identifyAnnotationBodyDeclarationType
+ );
+
+ $.OR([
+ {
+ GATE: () =>
+ detectedType === AnnotationBodyTypes.annotationTypeElementDeclaration,
+ ALT: () => $.SUBRULE($.annotationTypeElementDeclaration)
+ },
+ {
+ GATE: () => detectedType === AnnotationBodyTypes.constantDeclaration,
+ ALT: () => $.SUBRULE($.constantDeclaration)
+ },
+ {
+ GATE: () => detectedType === AnnotationBodyTypes.classDeclaration,
+ ALT: () => $.SUBRULE($.classDeclaration)
+ },
+ {
+ GATE: () => detectedType === AnnotationBodyTypes.interfaceDeclaration,
+ ALT: () => $.SUBRULE($.interfaceDeclaration)
+ },
+ {
+ // No GATE is needed as this is LL(1)
+ ALT: () => $.CONSUME(t.Semicolon)
+ }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-AnnotationTypeElementDeclaration
+ $.RULE("annotationTypeElementDeclaration", () => {
+ $.MANY(() => {
+ $.SUBRULE($.annotationTypeElementModifier);
+ });
+ $.SUBRULE($.unannType);
+ $.CONSUME(t.Identifier);
+ $.CONSUME(t.LBrace);
+ $.CONSUME(t.RBrace);
+ $.OPTION(() => {
+ $.SUBRULE($.dims);
+ });
+ $.OPTION2(() => {
+ $.SUBRULE($.defaultValue);
+ });
+ $.CONSUME(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-AnnotationTypeElementModifier
+ $.RULE("annotationTypeElementModifier", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.annotation) },
+ { ALT: () => $.CONSUME(t.Public) },
+ { ALT: () => $.CONSUME(t.Abstract) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-DefaultValue
+ $.RULE("defaultValue", () => {
+ $.CONSUME(t.Default);
+ $.SUBRULE($.elementValue);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-Annotation
+ $.RULE("annotation", () => {
+ // Spec Deviation: The common prefix for all three annotation types was extracted to this rule.
+ // This was done to avoid the use of backtracking for performance reasons.
+ $.CONSUME(t.At);
+ $.SUBRULE($.typeName);
+
+ // If this optional grammar was not invoked we have a markerAnnotation
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-MarkerAnnotation
+ $.OPTION(() => {
+ $.CONSUME(t.LBrace);
+ $.OR({
+ DEF: [
+ // normal annotation - https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-NormalAnnotation
+ { ALT: () => $.SUBRULE($.elementValuePairList) },
+ // Single Element Annotation - https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-SingleElementAnnotation
+ {
+ ALT: () => $.SUBRULE($.elementValue)
+ },
+ {
+ ALT: () => {
+ /* empty normal annotation contents */
+ }
+ }
+ ],
+ IGNORE_AMBIGUITIES: true,
+ MAX_LOOKAHEAD: 2
+ });
+ $.CONSUME(t.RBrace);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-ElementValuePairList
+ $.RULE("elementValuePairList", () => {
+ $.SUBRULE($.elementValuePair);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.elementValuePair);
+ });
+ });
+
+ $.RULE("elementValuePair", () => {
+ $.CONSUME(t.Identifier);
+ $.CONSUME(t.Equals);
+ $.SUBRULE($.elementValue);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-ElementValue
+ $.RULE("elementValue", () => {
+ const isSimpleElementValueAnnotation = this.BACKTRACK_LOOKAHEAD(
+ $.isSimpleElementValueAnnotation
+ );
+
+ $.OR([
+ // Spec Deviation: "conditionalExpression" replaced with "expression"
+ // Because we cannot differentiate between the two using fixed lookahead.
+ {
+ GATE: () => isSimpleElementValueAnnotation === false,
+ ALT: () => $.SUBRULE($.expression)
+ },
+ { ALT: () => $.SUBRULE($.elementValueArrayInitializer) },
+ {
+ GATE: () => isSimpleElementValueAnnotation === true,
+ ALT: () => $.SUBRULE($.annotation)
+ }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-ElementValueArrayInitializer
+ $.RULE("elementValueArrayInitializer", () => {
+ $.CONSUME(t.LCurly);
+ $.OPTION(() => {
+ $.SUBRULE($.elementValueList);
+ });
+ $.OPTION2(() => {
+ $.CONSUME(t.Comma);
+ });
+ $.CONSUME(t.RCurly);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-9.html#jls-ElementValueList
+ $.RULE("elementValueList", () => {
+ $.SUBRULE($.elementValue);
+ $.MANY({
+ GATE: () => tokenMatcher($.LA(2).tokenType, t.RCurly) === false,
+ DEF: () => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.elementValue);
+ }
+ });
+ });
+
+ // ------------------------------------
+ // Special optimized backtracking rules.
+ // ------------------------------------
+ $.RULE("identifyInterfaceBodyDeclarationType", () => {
+ let nextTokenType = this.LA(1).tokenType;
+ if (tokenMatcher(nextTokenType, t.Semicolon)) {
+ return InterfaceBodyTypes.semiColon;
+ }
+
+ // We have to look beyond the modifiers to distinguish between the declaration types.
+ $.MANY({
+ // To avoid ambiguity with @interface ("AnnotationTypeDeclaration" vs "Annotaion")
+ GATE: () =>
+ (tokenMatcher($.LA(1).tokenType, t.At) &&
+ tokenMatcher($.LA(2).tokenType, t.Interface)) === false,
+ DEF: () => {
+ // This alternation includes all possible modifiers for all types of "interfaceMemberDeclaration"
+ // Certain combinations are syntactically invalid, this is **not** checked here,
+ // Invalid combinations will cause a descriptive parsing error message to be
+ // Created inside the relevant parsing rules **after** this lookahead
+ // analysis.
+ $.OR([
+ { ALT: () => $.SUBRULE($.annotation) },
+ { ALT: () => $.CONSUME(t.Public) },
+ { ALT: () => $.CONSUME(t.Protected) },
+ { ALT: () => $.CONSUME(t.Private) },
+ { ALT: () => $.CONSUME(t.Static) },
+ { ALT: () => $.CONSUME(t.Final) },
+ { ALT: () => $.CONSUME(t.Abstract) },
+ { ALT: () => $.CONSUME(t.Default) },
+ { ALT: () => $.CONSUME(t.Strictfp) }
+ ]);
+ }
+ });
+
+ nextTokenType = this.LA(1).tokenType;
+ if (
+ tokenMatcher(nextTokenType, t.Class) ||
+ tokenMatcher(nextTokenType, t.Enum) ||
+ tokenMatcher(nextTokenType, t.Record)
+ ) {
+ return InterfaceBodyTypes.classDeclaration;
+ }
+ if (
+ tokenMatcher(nextTokenType, t.Interface) ||
+ tokenMatcher(nextTokenType, t.At)
+ ) {
+ return InterfaceBodyTypes.interfaceDeclaration;
+ }
+ if (
+ tokenMatcher(nextTokenType, t.Void) ||
+ tokenMatcher(nextTokenType, t.Less)
+ ) {
+ // method with result type "void"
+ return InterfaceBodyTypes.interfaceMethodDeclaration;
+ }
+
+ // Only constant or interfaceMethod declarations may be valid at this point.
+ // All other alternatives should have been attempted.
+ // **both** start with "unannType"
+ this.SUBRULE($.unannType);
+
+ const nextToken = this.LA(1);
+ const nextNextTokenType = this.LA(2).tokenType;
+ // "foo(..." --> look like method start
+ if (
+ tokenMatcher(nextToken, t.Identifier) &&
+ tokenMatcher(nextNextTokenType, t.LBrace)
+ ) {
+ return InterfaceBodyTypes.interfaceMethodDeclaration;
+ }
+ // a valid constant
+ if (tokenMatcher(nextToken, t.Identifier)) {
+ return InterfaceBodyTypes.constantDeclaration;
+ }
+ return InterfaceBodyTypes.unknown;
+ });
+
+ $.RULE("identifyAnnotationBodyDeclarationType", () => {
+ let nextTokenType = this.LA(1).tokenType;
+ if (tokenMatcher(nextTokenType, t.Semicolon)) {
+ return AnnotationBodyTypes.semiColon;
+ }
+
+ // We have to look beyond the modifiers to distinguish between the declaration types.
+ $.MANY({
+ // To avoid ambiguity with @interface ("AnnotationTypeDeclaration" vs "Annotaion")
+ GATE: () =>
+ (tokenMatcher($.LA(1).tokenType, t.At) &&
+ tokenMatcher($.LA(2).tokenType, t.Interface)) === false,
+ DEF: () => {
+ // This alternation includes all possible modifiers for all types of "annotationTypeMemberDeclaration"
+ // Certain combinations are syntactically invalid, this is **not** checked here,
+ // Invalid combinations will cause a descriptive parsing error message to be
+ // Created inside the relevant parsing rules **after** this lookahead
+ // analysis.
+ $.OR([
+ { ALT: () => $.SUBRULE($.annotation) },
+ { ALT: () => $.CONSUME(t.Public) },
+ { ALT: () => $.CONSUME(t.Protected) },
+ { ALT: () => $.CONSUME(t.Private) },
+ { ALT: () => $.CONSUME(t.Abstract) },
+ { ALT: () => $.CONSUME(t.Static) },
+ { ALT: () => $.CONSUME(t.Final) },
+ { ALT: () => $.CONSUME(t.Strictfp) }
+ ]);
+ }
+ });
+
+ nextTokenType = this.LA(1).tokenType;
+ if (
+ tokenMatcher(nextTokenType, t.Class) ||
+ tokenMatcher(nextTokenType, t.Enum)
+ ) {
+ return AnnotationBodyTypes.classDeclaration;
+ }
+ if (
+ tokenMatcher(nextTokenType, t.Interface) ||
+ tokenMatcher(nextTokenType, t.At)
+ ) {
+ return AnnotationBodyTypes.interfaceDeclaration;
+ }
+
+ // Only constant or annotationTypeElement declarations may be valid at this point.
+ // All other alternatives should have been attempted.
+ // **both** start with "unannType"
+ this.SUBRULE($.unannType);
+
+ nextTokenType = this.LA(1).tokenType;
+ const nextNextTokenType = this.LA(2).tokenType;
+ // "foo(..." --> look like annotationTypeElement start
+ if (
+ tokenMatcher(nextTokenType, t.Identifier) &&
+ tokenMatcher(nextNextTokenType, t.LBrace)
+ ) {
+ return AnnotationBodyTypes.annotationTypeElementDeclaration;
+ }
+ // a valid constant
+ if (tokenMatcher(nextTokenType, t.Identifier)) {
+ return AnnotationBodyTypes.constantDeclaration;
+ }
+ return AnnotationBodyTypes.unknown;
+ });
+
+ $.RULE("isSimpleElementValueAnnotation", () => {
+ $.SUBRULE($.annotation);
+ const nextTokenType = this.LA(1).tokenType;
+ switch (nextTokenType) {
+ // annotation in "ElementValue" would be followed by one of those
+ // any other TokenType would indicate it is an annotation in a "referenceType"
+ // as part of a "methodReference" in "primary"
+ case t.Comma:
+ case t.Semicolon:
+ case t.RCurly:
+ case t.RBrace:
+ return true;
+ default:
+ return false;
+ }
+ });
+}
+
+module.exports = {
+ defineRules
+};
diff --git a/node_modules/java-parser/src/productions/lexical-structure.js b/node_modules/java-parser/src/productions/lexical-structure.js
new file mode 100644
index 0000000..bd08c79
--- /dev/null
+++ b/node_modules/java-parser/src/productions/lexical-structure.js
@@ -0,0 +1,42 @@
+"use strict";
+function defineRules($, t) {
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-3.html#jls-Literal
+ $.RULE("literal", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.integerLiteral) },
+ { ALT: () => $.SUBRULE($.floatingPointLiteral) },
+ { ALT: () => $.SUBRULE($.booleanLiteral) },
+ { ALT: () => $.CONSUME(t.CharLiteral) },
+ { ALT: () => $.CONSUME(t.TextBlock) },
+ { ALT: () => $.CONSUME(t.StringLiteral) },
+ { ALT: () => $.CONSUME(t.Null) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-3.html#jls-IntegerLiteral
+ $.RULE("integerLiteral", () => {
+ $.OR([
+ { ALT: () => $.CONSUME(t.DecimalLiteral) },
+ { ALT: () => $.CONSUME(t.HexLiteral) },
+ { ALT: () => $.CONSUME(t.OctalLiteral) },
+ { ALT: () => $.CONSUME(t.BinaryLiteral) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-3.html#jls-FloatingPointLiteral
+ $.RULE("floatingPointLiteral", () => {
+ $.OR([
+ { ALT: () => $.CONSUME(t.FloatLiteral) },
+ { ALT: () => $.CONSUME(t.HexFloatLiteral) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-3.html#jls-BooleanLiteral
+ $.RULE("booleanLiteral", () => {
+ $.OR([{ ALT: () => $.CONSUME(t.True) }, { ALT: () => $.CONSUME(t.False) }]);
+ });
+}
+
+module.exports = {
+ defineRules
+};
diff --git a/node_modules/java-parser/src/productions/names.js b/node_modules/java-parser/src/productions/names.js
new file mode 100644
index 0000000..80190bc
--- /dev/null
+++ b/node_modules/java-parser/src/productions/names.js
@@ -0,0 +1,86 @@
+"use strict";
+const { tokenMatcher } = require("chevrotain");
+function defineRules($, t) {
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-6.html#jls-ModuleName
+ $.RULE("moduleName", () => {
+ $.CONSUME(t.Identifier);
+ $.MANY(() => {
+ $.CONSUME(t.Dot);
+ $.CONSUME2(t.Identifier);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-6.html#jls-PackageName
+ $.RULE("packageName", () => {
+ $.CONSUME(t.Identifier);
+ $.MANY(() => {
+ $.CONSUME(t.Dot);
+ $.CONSUME2(t.Identifier);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-6.html#jls-TypeName
+ $.RULE("typeName", () => {
+ // Spec Deviation: The last Identifier in a "typeName" may not be be "var"
+ // But the parser does not check for that.
+ // TODO: post parsing semantic check: last "Identifier" in a "typeName"
+ // cannot be the "var" keyword
+ // TODO: option 2 implement "Not Var" Ident using token categories?
+ $.CONSUME(t.Identifier);
+ $.MANY(() => {
+ $.CONSUME(t.Dot);
+ $.CONSUME2(t.Identifier);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-6.html#jls-ExpressionName
+ $.RULE("expressionName", () => {
+ // Spec Deviation: in-lined "ambiguousName" to be LL(K)
+ $.CONSUME(t.Identifier);
+ $.MANY({
+ // expressionName could be called by "qualifiedExplicitConstructorInvocation"
+ // in that case it may be followed by ".super" so we need to look two tokens
+ // ahead.
+ GATE: () => tokenMatcher(this.LA(2).tokenType, t.Identifier),
+ DEF: () => {
+ $.CONSUME(t.Dot);
+ $.CONSUME2(t.Identifier);
+ }
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-6.html#jls-MethodName
+ $.RULE("methodName", () => {
+ $.CONSUME(t.Identifier);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-6.html#jls-PackageOrTypeName
+ $.RULE("packageOrTypeName", () => {
+ $.CONSUME(t.Identifier);
+ $.MANY({
+ // In some contexts a "Dot Star" (.*) may appear
+ // after a "packageOrTypeName", by default Chevrotain will
+ // only look a single token ahead (Dot) to determine if another iteration
+ // exists which will cause a parsing error for inputs such as:
+ // "import a.b.c.*"
+ GATE: () => tokenMatcher(this.LA(2).tokenType, t.Star) === false,
+ DEF: () => {
+ $.CONSUME(t.Dot);
+ $.CONSUME2(t.Identifier);
+ }
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-6.html#jls-AmbiguousName
+ $.RULE("ambiguousName", () => {
+ $.CONSUME(t.Identifier);
+ $.MANY(() => {
+ $.CONSUME(t.Dot);
+ $.CONSUME2(t.Identifier);
+ });
+ });
+}
+
+module.exports = {
+ defineRules
+};
diff --git a/node_modules/java-parser/src/productions/packages-and-modules.js b/node_modules/java-parser/src/productions/packages-and-modules.js
new file mode 100644
index 0000000..ff6a4fd
--- /dev/null
+++ b/node_modules/java-parser/src/productions/packages-and-modules.js
@@ -0,0 +1,273 @@
+"use strict";
+const { isRecognitionException, tokenMatcher, EOF } = require("chevrotain");
+
+function defineRules($, t) {
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-7.html#CompilationUnit
+ $.RULE("compilationUnit", () => {
+ // custom optimized backtracking lookahead logic
+ const isModule = $.BACKTRACK_LOOKAHEAD($.isModuleCompilationUnit);
+
+ $.OR([
+ {
+ GATE: () => isModule === false,
+ ALT: () => $.SUBRULE($.ordinaryCompilationUnit)
+ },
+ {
+ ALT: () => $.SUBRULE($.modularCompilationUnit)
+ }
+ ]);
+ // https://github.com/jhipster/prettier-java/pull/217
+ $.CONSUME(EOF);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-7.html#jls-OrdinaryCompilationUnit
+ $.RULE("ordinaryCompilationUnit", () => {
+ $.OPTION({
+ GATE: $.BACKTRACK($.packageDeclaration),
+ DEF: () => {
+ $.SUBRULE($.packageDeclaration);
+ }
+ });
+ $.MANY(() => {
+ $.SUBRULE3($.importDeclaration);
+ });
+ $.MANY2(() => {
+ $.SUBRULE($.typeDeclaration);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-7.html#jls-ModularCompilationUnit
+ $.RULE("modularCompilationUnit", () => {
+ $.MANY(() => {
+ $.SUBRULE($.importDeclaration);
+ });
+ $.SUBRULE($.moduleDeclaration);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-7.html#jls-PackageDeclaration
+ $.RULE("packageDeclaration", () => {
+ $.MANY(() => {
+ $.SUBRULE($.packageModifier);
+ });
+ $.CONSUME(t.Package);
+ $.CONSUME(t.Identifier);
+ $.MANY2(() => {
+ $.CONSUME(t.Dot);
+ $.CONSUME2(t.Identifier);
+ });
+ $.CONSUME2(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-7.html#jls-PackageModifier
+ $.RULE("packageModifier", () => {
+ $.SUBRULE($.annotation);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-7.html#jls-ImportDeclaration
+ $.RULE("importDeclaration", () => {
+ // Spec Deviation: The spec defines four different kinds of import declarations.
+ // Our grammar however combines those into a single rule due to difficulties
+ // distinguishing between the alternatives due to unbound common prefix.
+ // TODO: A post parsing step is required to align with the official specs.
+ // The Identifier "var" is not allowed in all positions and variations of the importDeclaration
+ $.OR([
+ {
+ ALT: () => {
+ $.CONSUME(t.Import);
+ $.OPTION(() => {
+ $.CONSUME(t.Static);
+ });
+ $.SUBRULE($.packageOrTypeName);
+ $.OPTION2(() => {
+ $.CONSUME(t.Dot);
+ $.CONSUME(t.Star);
+ });
+ $.CONSUME(t.Semicolon);
+ }
+ },
+ // Spec Deviation: The spec do not allow empty statement in between imports.
+ // However Java compiler consider empty statements valid, we chose
+ // to support that case, thus deviate from the spec.
+ // See here: https://github.com/jhipster/prettier-java/pull/158
+ {
+ ALT: () => $.SUBRULE($.emptyStatement)
+ }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-7.html#jls-TypeDeclaration
+ $.RULE("typeDeclaration", () => {
+ // TODO: consider extracting the prefix modifiers here to avoid backtracking
+ const isClassDeclaration = this.BACKTRACK_LOOKAHEAD($.isClassDeclaration);
+
+ $.OR([
+ {
+ GATE: () => isClassDeclaration,
+ ALT: () => $.SUBRULE($.classDeclaration)
+ },
+ { ALT: () => $.SUBRULE($.interfaceDeclaration) },
+ { ALT: () => $.CONSUME(t.Semicolon) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-7.html#jls-ModuleDeclaration
+ $.RULE("moduleDeclaration", () => {
+ $.MANY(() => {
+ $.SUBRULE($.annotation);
+ });
+ $.OPTION(() => {
+ $.CONSUME(t.Open);
+ });
+ $.CONSUME(t.Module);
+ $.CONSUME(t.Identifier);
+ $.MANY2(() => {
+ $.CONSUME(t.Dot);
+ $.CONSUME2(t.Identifier);
+ });
+ $.CONSUME(t.LCurly);
+ $.MANY3(() => {
+ $.SUBRULE($.moduleDirective);
+ });
+ $.CONSUME(t.RCurly);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-7.html#jls-ModuleDirective
+ $.RULE("moduleDirective", () => {
+ // Spec Deviation: Each of the alternatives of "moduleDirective" was extracted
+ // to its own nonTerminal, to reduce verbosity.
+ $.OR([
+ { ALT: () => $.SUBRULE($.requiresModuleDirective) },
+ { ALT: () => $.SUBRULE($.exportsModuleDirective) },
+ { ALT: () => $.SUBRULE($.opensModuleDirective) },
+ { ALT: () => $.SUBRULE($.usesModuleDirective) },
+ { ALT: () => $.SUBRULE($.providesModuleDirective) }
+ ]);
+ });
+
+ $.RULE("requiresModuleDirective", () => {
+ // Spec Deviation: extracted from "moduleDirective"
+ $.CONSUME(t.Requires);
+ $.MANY({
+ GATE: () => {
+ /**
+ * https://docs.oracle.com/javase/specs/jls/se16/html/jls-3.html#jls-3.9 -
+ * There is one exception: immediately to the right of the character sequence `requires` in the ModuleDirective production,
+ * the character sequence `transitive` is tokenized as a keyword unless it is followed by a separator,
+ * in which case it is tokenized as an identifier.
+ */
+ return (
+ (tokenMatcher($.LA(1).tokenType, t.Transitive) &&
+ tokenMatcher($.LA(2).tokenType, t.Separators)) === false
+ );
+ },
+ DEF: () => {
+ $.SUBRULE($.requiresModifier);
+ }
+ });
+ $.SUBRULE($.moduleName);
+ $.CONSUME(t.Semicolon);
+ });
+
+ $.RULE("exportsModuleDirective", () => {
+ // Spec Deviation: extracted from "moduleDirective"
+ $.CONSUME(t.Exports);
+ $.SUBRULE($.packageName);
+ $.OPTION(() => {
+ $.CONSUME(t.To);
+ $.SUBRULE($.moduleName);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.moduleName);
+ });
+ });
+ $.CONSUME(t.Semicolon);
+ });
+
+ $.RULE("opensModuleDirective", () => {
+ // Spec Deviation: extracted from "moduleDirective"
+ $.CONSUME(t.Opens);
+ $.SUBRULE($.packageName);
+ $.OPTION(() => {
+ $.CONSUME(t.To);
+ $.SUBRULE($.moduleName);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.moduleName);
+ });
+ });
+ $.CONSUME(t.Semicolon);
+ });
+
+ $.RULE("usesModuleDirective", () => {
+ // Spec Deviation: extracted from "moduleDirective"
+ $.CONSUME(t.Uses);
+ $.SUBRULE($.typeName);
+ $.CONSUME(t.Semicolon);
+ });
+
+ $.RULE("providesModuleDirective", () => {
+ // Spec Deviation: extracted from "moduleDirective"
+ $.CONSUME(t.Provides);
+ $.SUBRULE($.typeName);
+ $.CONSUME(t.With);
+ $.SUBRULE2($.typeName);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE3($.typeName);
+ });
+ $.CONSUME(t.Semicolon);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-7.html#jls-RequiresModifier
+ $.RULE("requiresModifier", () => {
+ $.OR([
+ { ALT: () => $.CONSUME(t.Transitive) },
+ { ALT: () => $.CONSUME(t.Static) }
+ ]);
+ });
+
+ $.RULE("isModuleCompilationUnit", () => {
+ $.OPTION(() => {
+ $.SUBRULE($.packageDeclaration);
+ // TODO: this return must be outside the OPTION at the top level rule
+ // a Java Module source code may not contain a package declaration.
+ return false;
+ });
+
+ try {
+ // the "{importDeclaration}" is a common prefix
+ $.MANY(() => {
+ $.SUBRULE2($.importDeclaration);
+ });
+
+ $.MANY2({
+ // To avoid ambiguity with @interface ("AnnotationTypeDeclaration" vs "Annotaion")
+ GATE: () =>
+ (tokenMatcher($.LA(1).tokenType, t.At) &&
+ tokenMatcher($.LA(2).tokenType, t.Interface)) === false,
+ DEF: () => {
+ $.SUBRULE($.annotation);
+ }
+ });
+ } catch (e) {
+ // This means we had a syntax error in the imports or annotations
+ // So we can't keep parsing deep enough to make the decision
+ if (isRecognitionException(e)) {
+ // TODO: add original syntax error?
+ throw "Cannot Identify if the source code is an OrdinaryCompilationUnit or ModularCompilationUnit";
+ } else {
+ throw e;
+ }
+ }
+
+ const nextTokenType = this.LA(1).tokenType;
+ return (
+ tokenMatcher(nextTokenType, t.Open) ||
+ tokenMatcher(nextTokenType, t.Module)
+ );
+ });
+}
+
+module.exports = {
+ defineRules
+};
diff --git a/node_modules/java-parser/src/productions/types-values-and-variables.js b/node_modules/java-parser/src/productions/types-values-and-variables.js
new file mode 100644
index 0000000..0936de4
--- /dev/null
+++ b/node_modules/java-parser/src/productions/types-values-and-variables.js
@@ -0,0 +1,236 @@
+"use strict";
+
+const { tokenMatcher } = require("chevrotain");
+
+function defineRules($, t) {
+ // ---------------------
+ // Productions from §4 (Types, Values, and Variables)
+ // ---------------------
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-PrimitiveType
+ $.RULE("primitiveType", () => {
+ $.MANY(() => {
+ $.SUBRULE($.annotation);
+ });
+ $.OR([
+ { ALT: () => $.SUBRULE($.numericType) },
+ { ALT: () => $.CONSUME(t.Boolean) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-NumericType
+ $.RULE("numericType", () => {
+ $.OR([
+ { ALT: () => $.SUBRULE($.integralType) },
+ { ALT: () => $.SUBRULE($.floatingPointType) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-IntegralType
+ $.RULE("integralType", () => {
+ $.OR([
+ { ALT: () => $.CONSUME(t.Byte) },
+ { ALT: () => $.CONSUME(t.Short) },
+ { ALT: () => $.CONSUME(t.Int) },
+ { ALT: () => $.CONSUME(t.Long) },
+ { ALT: () => $.CONSUME(t.Char) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-FloatingPointType
+ $.RULE("floatingPointType", () => {
+ $.OR([
+ { ALT: () => $.CONSUME(t.Float) },
+ { ALT: () => $.CONSUME(t.Double) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-ReferenceType
+ $.RULE("referenceType", () => {
+ $.MANY(() => {
+ // Spec Deviation: by extracting the common "annotation" prefix
+ // we can avoid backtracking and thus improve performance.
+ // Note that the annotation prefix is still present inside
+ // "primitiveType" and "classOrInterfaceType"
+ $.SUBRULE($.annotation);
+ });
+ // Spec Deviation: The array type "dims" suffix was extracted to this rule
+ // to avoid backtracking for performance reasons.
+ $.OR({
+ DEF: [
+ {
+ ALT: () => {
+ $.SUBRULE($.primitiveType);
+ $.SUBRULE($.dims);
+ }
+ },
+ {
+ // Spec Deviation: "typeVariable" alternative is missing because
+ // it is included in "classOrInterfaceType"
+ ALT: () => {
+ $.SUBRULE($.classOrInterfaceType);
+ $.OPTION(() => {
+ $.SUBRULE2($.dims);
+ });
+ }
+ }
+ ],
+ IGNORE_AMBIGUITIES: true // annotation prefix was extracted to remove ambiguities
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-ClassOrInterfaceType
+ $.RULE("classOrInterfaceType", () => {
+ // Spec Deviation: The spec says: "classType | interfaceType" but "interfaceType"
+ // is not mentioned in the parser because it is identical to "classType"
+ // The distinction is **semantic** not syntactic.
+ $.SUBRULE($.classType);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-ClassType
+ $.RULE("classType", () => {
+ // Spec Deviation: Refactored left recursion and alternation to iterations
+ $.MANY(() => {
+ $.SUBRULE($.annotation);
+ });
+ $.CONSUME(t.Identifier);
+ $.OPTION(() => {
+ $.SUBRULE($.typeArguments);
+ });
+ $.MANY2(() => {
+ $.CONSUME(t.Dot);
+ $.MANY3(() => {
+ $.SUBRULE2($.annotation);
+ });
+ // TODO: Semantic Check: This Identifier cannot be "var"
+ $.CONSUME2(t.Identifier);
+ $.OPTION2({
+ // To avoid confusion with "TypeArgumentsOrDiamond" rule
+ // as we use the "classType" rule in the "identifyNewExpressionType"
+ // optimized lookahead rule.
+ GATE: () => tokenMatcher($.LA(2).tokenType, t.Greater) === false,
+ DEF: () => {
+ $.SUBRULE2($.typeArguments);
+ }
+ });
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-InterfaceType
+ $.RULE("interfaceType", () => {
+ $.SUBRULE($.classType);
+ });
+
+ $.RULE("typeVariable", () => {
+ $.MANY(() => {
+ $.SUBRULE($.annotation);
+ });
+ // TODO: Semantic Check: This Identifier cannot be "var"
+ $.CONSUME(t.Identifier);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-Dims
+ $.RULE("dims", () => {
+ $.MANY(() => {
+ $.SUBRULE($.annotation);
+ });
+ $.CONSUME(t.LSquare);
+ $.CONSUME(t.RSquare);
+ $.MANY2({
+ GATE: () => $.BACKTRACK_LOOKAHEAD($.isDims),
+ DEF: () => {
+ $.MANY3(() => {
+ $.SUBRULE2($.annotation);
+ });
+ $.CONSUME2(t.LSquare);
+ $.CONSUME2(t.RSquare);
+ }
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-TypeParameter
+ $.RULE("typeParameter", () => {
+ $.MANY(() => {
+ $.SUBRULE($.typeParameterModifier);
+ });
+ $.SUBRULE($.typeIdentifier);
+ $.OPTION(() => {
+ $.SUBRULE($.typeBound);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-TypeParameterModifier
+ $.RULE("typeParameterModifier", () => {
+ $.SUBRULE($.annotation);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-TypeBound
+ $.RULE("typeBound", () => {
+ $.CONSUME(t.Extends);
+ // Spec Deviation: The alternative with "TypeVariable" is not specified
+ // because it's syntax is included in "classOrInterfaceType"
+ $.SUBRULE($.classOrInterfaceType);
+ $.MANY2(() => {
+ $.SUBRULE($.additionalBound);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-AdditionalBound
+ $.RULE("additionalBound", () => {
+ $.CONSUME(t.And);
+ $.SUBRULE($.interfaceType);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-TypeArguments
+ $.RULE("typeArguments", () => {
+ $.CONSUME(t.Less);
+ $.SUBRULE($.typeArgumentList);
+ $.CONSUME(t.Greater);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-TypeArgumentList
+ $.RULE("typeArgumentList", () => {
+ $.SUBRULE($.typeArgument);
+ $.MANY(() => {
+ $.CONSUME(t.Comma);
+ $.SUBRULE2($.typeArgument);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-TypeArgument
+ $.RULE("typeArgument", () => {
+ // TODO: performance: evaluate flipping the order of alternatives
+ $.OR([
+ {
+ GATE: $.BACKTRACK($.referenceType),
+ ALT: () => $.SUBRULE($.referenceType)
+ },
+ { ALT: () => $.SUBRULE($.wildcard) }
+ ]);
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-Wildcard
+ $.RULE("wildcard", () => {
+ $.MANY(() => {
+ $.SUBRULE($.annotation);
+ });
+ $.CONSUME(t.QuestionMark);
+ $.OPTION(() => {
+ $.SUBRULE($.wildcardBounds);
+ });
+ });
+
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-4.html#jls-WildcardBounds
+ $.RULE("wildcardBounds", () => {
+ // TODO: consider in-lining suffix into the alternatives to match the spec more strongly
+ $.OR([
+ { ALT: () => $.CONSUME(t.Extends) },
+ { ALT: () => $.CONSUME(t.Super) }
+ ]);
+ $.SUBRULE($.referenceType);
+ });
+}
+
+module.exports = {
+ defineRules
+};
diff --git a/node_modules/java-parser/src/tokens.js b/node_modules/java-parser/src/tokens.js
new file mode 100644
index 0000000..c12ff76
--- /dev/null
+++ b/node_modules/java-parser/src/tokens.js
@@ -0,0 +1,536 @@
+"use strict";
+const { createToken: createTokenOrg, Lexer } = require("chevrotain");
+const camelCase = require("lodash/camelCase");
+
+let chars;
+// A little mini DSL for easier lexer definition.
+const fragments = {};
+try {
+ chars = require("./unicodesets");
+} catch (e) {
+ throw Error(
+ "unicodesets.js file could not be found. Did you try to run the command: yarn run build ?"
+ );
+}
+
+function inlineFragments(def) {
+ let inlinedDef = def;
+ Object.keys(fragments).forEach(prevFragmentName => {
+ const prevFragmentDef = fragments[prevFragmentName];
+ const templateRegExp = new RegExp(`{{${prevFragmentName}}}`, "g");
+ inlinedDef = inlinedDef.replace(templateRegExp, prevFragmentDef);
+ });
+ return inlinedDef;
+}
+
+function FRAGMENT(name, def) {
+ fragments[name] = inlineFragments(def);
+}
+
+function MAKE_PATTERN(def, flags) {
+ const inlinedDef = inlineFragments(def);
+ return new RegExp(inlinedDef, flags);
+}
+
+// The order of fragments definitions is important
+FRAGMENT("Digits", "[0-9]([0-9_]*[0-9])?");
+FRAGMENT("ExponentPart", "[eE][+-]?{{Digits}}");
+FRAGMENT("HexDigit", "[0-9a-fA-F]");
+FRAGMENT("HexDigits", "{{HexDigit}}(({{HexDigit}}|'_')*{{HexDigit}})?");
+FRAGMENT("FloatTypeSuffix", "[fFdD]");
+FRAGMENT("LineTerminator", "(\\x0A|(\\x0D(\\x0A)?))");
+FRAGMENT("UnicodeMarker", "uu*");
+FRAGMENT("UnicodeEscape", "\\\\{{UnicodeMarker}}{{HexDigit}}{4}");
+FRAGMENT("RawInputCharacter", "\\\\{{UnicodeMarker}}[0-9a-fA-F]{4}");
+FRAGMENT("UnicodeInputCharacter", "({{UnicodeEscape}}|{{RawInputCharacter}})");
+FRAGMENT("OctalDigit", "[0-7]");
+FRAGMENT("ZeroToThree", "[0-3]");
+FRAGMENT(
+ "OctalEscape",
+ "\\\\({{OctalDigit}}|{{ZeroToThree}}?{{OctalDigit}}{2})"
+);
+FRAGMENT("EscapeSequence", "\\\\[btnfr\"'\\\\]|{{OctalEscape}}");
+// Not using InputCharacter terminology there because CR and LF are already captured in EscapeSequence
+FRAGMENT(
+ "StringCharacter",
+ "(?:(?:{{EscapeSequence}})|{{UnicodeInputCharacter}})"
+);
+
+function matchJavaIdentifier(text, startOffset) {
+ let endOffset = startOffset;
+ let charCode = text.codePointAt(endOffset);
+
+ // We verifiy if the first character is from one of these categories
+ // Corresponds to the isJavaIdentifierStart function from Java
+ if (chars.firstIdentChar.has(charCode)) {
+ endOffset++;
+ // If we encounter a surrogate pair (something that is beyond 65535/FFFF)
+ // We skip another offset because a surrogate pair is of length 2.
+ if (charCode > 65535) {
+ endOffset++;
+ }
+ charCode = text.codePointAt(endOffset);
+ }
+
+ // We verify if the remaining characters is from one of these categories
+ // Corresponds to the isJavaIdentifierPart function from Java
+ while (chars.restIdentChar.has(charCode)) {
+ endOffset++;
+ // See above.
+ if (charCode > 65535) {
+ endOffset++;
+ }
+ charCode = text.codePointAt(endOffset);
+ }
+
+ // No match, must return null to conform with the RegExp.prototype.exec signature
+ if (endOffset === startOffset) {
+ return null;
+ }
+ const matchedString = text.substring(startOffset, endOffset);
+ // according to the RegExp.prototype.exec API the first item in the returned array must be the whole matched string.
+ return [matchedString];
+}
+
+const Identifier = createTokenOrg({
+ name: "Identifier",
+ pattern: { exec: matchJavaIdentifier },
+ line_breaks: false,
+ start_chars_hint: Array.from(chars.firstIdentChar, x =>
+ String.fromCharCode(x)
+ )
+});
+
+const allTokens = [];
+const tokenDictionary = {};
+
+function createToken(options) {
+ // TODO create a test to check all the tokenbs have a label defined
+ if (!options.label) {
+ // simple token (e.g operator)
+ if (typeof options.pattern === "string") {
+ options.label = `'${options.pattern}'`;
+ }
+ // Complex token (e.g literal)
+ else if (options.pattern instanceof RegExp) {
+ options.label = `'${options.name}'`;
+ }
+ }
+
+ const newTokenType = createTokenOrg(options);
+ allTokens.push(newTokenType);
+ tokenDictionary[options.name] = newTokenType;
+ return newTokenType;
+}
+
+function createKeywordLikeToken(options) {
+ // A keyword 'like' token uses the "longer_alt" config option
+ // to resolve ambiguities, see: http://sap.github.io/chevrotain/docs/features/token_alternative_matches.html
+ options.longer_alt = Identifier;
+ return createToken(options);
+}
+
+// Token Categories
+// Used a Token Category to mark all restricted keywords.
+// This could be used in syntax highlights implementation.
+const RestrictedKeyword = createToken({
+ name: "RestrictedKeyword",
+ pattern: Lexer.NA
+});
+
+// Used a Token Category to mark all keywords.
+// This could be used in syntax highlights implementation.
+const Keyword = createToken({
+ name: "Keyword",
+ pattern: Lexer.NA
+});
+
+const AssignmentOperator = createToken({
+ name: "AssignmentOperator",
+ pattern: Lexer.NA
+});
+
+const BinaryOperator = createToken({
+ name: "BinaryOperator",
+ pattern: Lexer.NA
+});
+
+const UnaryPrefixOperator = createToken({
+ name: "UnaryPrefixOperator",
+ pattern: Lexer.NA
+});
+const UnaryPrefixOperatorNotPlusMinus = createToken({
+ name: "UnaryPrefixOperatorNotPlusMinus",
+ pattern: Lexer.NA
+});
+
+const UnarySuffixOperator = createToken({
+ name: "UnarySuffixOperator",
+ pattern: Lexer.NA
+});
+
+// https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.11
+const Separators = createToken({
+ name: "Separators",
+ pattern: Lexer.NA
+});
+
+// https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.6
+// Note [\\x09\\x20\\x0C] is equivalent to [\\t\\x20\\f] and that \\x20 represents
+// space character
+createToken({
+ name: "WhiteSpace",
+ pattern: MAKE_PATTERN("[\\x09\\x20\\x0C]|{{LineTerminator}}"),
+ group: Lexer.SKIPPED
+});
+createToken({
+ name: "LineComment",
+ pattern: /\/\/[^\n\r]*/,
+ group: "comments"
+});
+createToken({
+ name: "TraditionalComment",
+ pattern: /\/\*([^*]|\*(?!\/))*\*\//,
+ group: "comments"
+});
+createToken({ name: "BinaryLiteral", pattern: /0[bB][01]([01_]*[01])?[lL]?/ });
+createToken({
+ name: "FloatLiteral",
+ pattern: MAKE_PATTERN(
+ "{{Digits}}\\.({{Digits}})?({{ExponentPart}})?({{FloatTypeSuffix}})?|" +
+ "\\.{{Digits}}({{ExponentPart}})?({{FloatTypeSuffix}})?|" +
+ "{{Digits}}{{ExponentPart}}({{FloatTypeSuffix}})?|" +
+ "{{Digits}}({{ExponentPart}})?{{FloatTypeSuffix}}"
+ )
+});
+createToken({ name: "OctalLiteral", pattern: /0_*[0-7]([0-7_]*[0-7])?[lL]?/ });
+createToken({
+ name: "HexFloatLiteral",
+ pattern: MAKE_PATTERN(
+ "0[xX]({{HexDigits}}\\.?|({{HexDigits}})?\\.{{HexDigits}})[pP][+-]?{{Digits}}[fFdD]?"
+ )
+});
+createToken({
+ name: "HexLiteral",
+ pattern: /0[xX][0-9a-fA-F]([0-9a-fA-F_]*[0-9a-fA-F])?[lL]?/
+});
+createToken({
+ name: "DecimalLiteral",
+ pattern: MAKE_PATTERN("(0|[1-9](_+{{Digits}}|({{Digits}})?))[lL]?")
+});
+// https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.10.4
+createToken({
+ name: "CharLiteral",
+ // Not using SingleCharacter Terminology because ' and \ are captured in EscapeSequence
+ pattern: MAKE_PATTERN(
+ "'(?:[^\\\\']|(?:(?:{{EscapeSequence}})|{{UnicodeInputCharacter}}))'"
+ )
+});
+
+createToken({
+ name: "TextBlock",
+ pattern: /"""\s*\n(\\"|\s|.)*?"""/
+});
+
+createToken({
+ name: "StringLiteral",
+ pattern: MAKE_PATTERN('"(?:[^\\\\"]|{{StringCharacter}})*"')
+});
+
+// https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.9
+// TODO: how to handle the special rule (see spec above) for "requires" and "transitive"
+const restrictedKeywords = [
+ "open",
+ "module",
+ "requires",
+ "transitive",
+ "exports",
+ "opens",
+ "to",
+ "uses",
+ "provides",
+ "with",
+ "sealed",
+ "non-sealed",
+ "permits"
+];
+
+// By sorting the keywords in descending order we avoid ambiguities
+// of common prefixes.
+sortDescLength(restrictedKeywords).forEach(word => {
+ createKeywordLikeToken({
+ name: word[0].toUpperCase() + camelCase(word.substr(1)),
+ pattern: word,
+ // restricted keywords can also be used as an Identifiers according to the spec.
+ // TODO: inspect this causes no ambiguities
+ categories: [Identifier, RestrictedKeyword]
+ });
+});
+
+// https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.9
+const keywords = [
+ "abstract",
+ "continue",
+ "for",
+ "new",
+ "switch",
+ "assert",
+ "default",
+ "if",
+ "package",
+ "synchronized",
+ "boolean",
+ "do",
+ "goto",
+ "private",
+ "this",
+ "break",
+ "double",
+ "implements",
+ "protected",
+ "throw",
+ "byte",
+ "else",
+ "import",
+ "public",
+ "throws",
+ "case",
+ "enum",
+ // "instanceof", // special handling for "instanceof" operator below
+ "return",
+ "transient",
+ "catch",
+ "extends",
+ "int",
+ "short",
+ "try",
+ "char",
+ "final",
+ "interface",
+ "static",
+ "void",
+ "class",
+ "finally",
+ "long",
+ "strictfp",
+ "volatile",
+ "const",
+ "float",
+ "native",
+ "super",
+ "while",
+ ["_", "underscore"]
+];
+
+sortDescLength(keywords).forEach(word => {
+ // For handling symbols keywords (underscore)
+ const isPair = Array.isArray(word);
+ const actualName = isPair ? word[1] : word;
+ const actualPattern = isPair ? word[0] : word;
+
+ const options = {
+ name: actualName[0].toUpperCase() + actualName.substr(1),
+ pattern: actualPattern,
+ categories: Keyword
+ };
+
+ if (isPair) {
+ options.label = `'${actualName}'`;
+ }
+ createKeywordLikeToken(options);
+});
+
+createKeywordLikeToken({
+ name: "Instanceof",
+ pattern: "instanceof",
+ categories: [Keyword, BinaryOperator]
+});
+
+createKeywordLikeToken({
+ name: "Var",
+ pattern: "var",
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-3.html#jls-3.9
+ // "var is not a keyword, but rather an identifier with special meaning as the type of a local variable declaration"
+ categories: Identifier
+});
+createKeywordLikeToken({
+ name: "Yield",
+ pattern: "yield",
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-3.html#jls-3.9
+ // "yield is not a keyword, but rather an identifier with special meaning as the type of a local variable declaration"
+ categories: Identifier
+});
+createKeywordLikeToken({
+ name: "Record",
+ pattern: "record",
+ // https://docs.oracle.com/javase/specs/jls/se16/html/jls-3.html#jls-3.9
+ // "record is not a keyword, but rather an identifier with special meaning as the type of a local variable declaration"
+ categories: Identifier
+});
+createKeywordLikeToken({ name: "True", pattern: "true" });
+createKeywordLikeToken({ name: "False", pattern: "false" });
+createKeywordLikeToken({ name: "Null", pattern: "null" });
+
+// punctuation and symbols
+createToken({ name: "At", pattern: "@", categories: [Separators] });
+createToken({ name: "Arrow", pattern: "->" });
+createToken({ name: "DotDotDot", pattern: "...", categories: [Separators] });
+createToken({ name: "Dot", pattern: ".", categories: [Separators] });
+createToken({ name: "Comma", pattern: ",", categories: [Separators] });
+createToken({ name: "Semicolon", pattern: ";", categories: [Separators] });
+createToken({ name: "ColonColon", pattern: "::", categories: [Separators] });
+createToken({ name: "Colon", pattern: ":" });
+createToken({ name: "QuestionMark", pattern: "?" });
+createToken({ name: "LBrace", pattern: "(", categories: [Separators] });
+createToken({ name: "RBrace", pattern: ")", categories: [Separators] });
+createToken({ name: "LCurly", pattern: "{", categories: [Separators] });
+createToken({ name: "RCurly", pattern: "}", categories: [Separators] });
+createToken({ name: "LSquare", pattern: "[", categories: [Separators] });
+createToken({ name: "RSquare", pattern: "]", categories: [Separators] });
+
+// prefix and suffix operators
+// must be defined before "-"
+createToken({
+ name: "MinusMinus",
+ pattern: "--",
+ categories: [
+ UnaryPrefixOperator,
+ UnarySuffixOperator,
+ UnaryPrefixOperatorNotPlusMinus
+ ]
+});
+// must be defined before "+"
+createToken({
+ name: "PlusPlus",
+ pattern: "++",
+ categories: [
+ UnaryPrefixOperator,
+ UnarySuffixOperator,
+ UnaryPrefixOperatorNotPlusMinus
+ ]
+});
+createToken({
+ name: "Complement",
+ pattern: "~",
+ categories: [UnaryPrefixOperator, UnaryPrefixOperatorNotPlusMinus]
+});
+
+createToken({
+ name: "LessEquals",
+ pattern: "<=",
+ categories: [BinaryOperator]
+});
+createToken({
+ name: "LessLessEquals",
+ pattern: "<<=",
+ categories: [AssignmentOperator]
+});
+createToken({ name: "Less", pattern: "<", categories: [BinaryOperator] });
+createToken({
+ name: "GreaterEquals",
+ pattern: ">=",
+ categories: [BinaryOperator]
+});
+createToken({
+ name: "GreaterGreaterEquals",
+ pattern: ">>=",
+ categories: [AssignmentOperator]
+});
+createToken({
+ name: "GreaterGreaterGreaterEquals",
+ pattern: ">>>=",
+ categories: [AssignmentOperator]
+});
+createToken({ name: "Greater", pattern: ">", categories: [BinaryOperator] });
+createToken({
+ name: "EqualsEquals",
+ pattern: "==",
+ categories: [BinaryOperator]
+});
+createToken({
+ name: "Equals",
+ pattern: "=",
+ categories: [BinaryOperator, AssignmentOperator]
+});
+createToken({
+ name: "MinusEquals",
+ pattern: "-=",
+ categories: [AssignmentOperator]
+});
+createToken({
+ name: "Minus",
+ pattern: "-",
+ categories: [BinaryOperator, UnaryPrefixOperator]
+});
+createToken({
+ name: "PlusEquals",
+ pattern: "+=",
+ categories: [AssignmentOperator]
+});
+createToken({
+ name: "Plus",
+ pattern: "+",
+ categories: [BinaryOperator, UnaryPrefixOperator]
+});
+createToken({ name: "AndAnd", pattern: "&&", categories: [BinaryOperator] });
+createToken({
+ name: "AndEquals",
+ pattern: "&=",
+ categories: [AssignmentOperator]
+});
+createToken({ name: "And", pattern: "&", categories: [BinaryOperator] });
+createToken({
+ name: "XorEquals",
+ pattern: "^=",
+ categories: [AssignmentOperator]
+});
+createToken({ name: "Xor", pattern: "^", categories: [BinaryOperator] });
+createToken({ name: "NotEquals", pattern: "!=", categories: [BinaryOperator] });
+createToken({ name: "OrOr", pattern: "||", categories: [BinaryOperator] });
+createToken({
+ name: "OrEquals",
+ pattern: "|=",
+ categories: [AssignmentOperator]
+});
+createToken({ name: "Or", pattern: "|", categories: [BinaryOperator] });
+createToken({
+ name: "MultiplyEquals",
+ pattern: "*=",
+ categories: [AssignmentOperator]
+});
+createToken({ name: "Star", pattern: "*", categories: [BinaryOperator] });
+createToken({
+ name: "DivideEquals",
+ pattern: "/=",
+ categories: [AssignmentOperator]
+});
+createToken({ name: "Divide", pattern: "/", categories: [BinaryOperator] });
+createToken({
+ name: "ModuloEquals",
+ pattern: "%=",
+ categories: [AssignmentOperator]
+});
+createToken({ name: "Modulo", pattern: "%", categories: [BinaryOperator] });
+
+// must be defined after "!="
+createToken({
+ name: "Not",
+ pattern: "!",
+ categories: [UnaryPrefixOperator, UnaryPrefixOperatorNotPlusMinus]
+});
+
+// Identifier must appear AFTER all the keywords to avoid ambiguities.
+// See: https://github.com/SAP/chevrotain/blob/master/examples/lexer/keywords_vs_identifiers/keywords_vs_identifiers.js
+allTokens.push(Identifier);
+tokenDictionary["Identifier"] = Identifier;
+
+function sortDescLength(arr) {
+ // sort is not stable, but that will not affect the lexing results.
+ return arr.sort((a, b) => {
+ return b.length - a.length;
+ });
+}
+module.exports = {
+ allTokens,
+ tokens: tokenDictionary
+};
diff --git a/node_modules/java-parser/src/unicodesets.js b/node_modules/java-parser/src/unicodesets.js
new file mode 100644
index 0000000..b768a1c
--- /dev/null
+++ b/node_modules/java-parser/src/unicodesets.js
@@ -0,0 +1,1005 @@
+/*File generated with ../scripts/unicode.js using ../resources/Unicode/UnicodeData.txt.
+ * As Java Identifiers may contains unicodes letters, this file defines two sets of unicode
+ * characters, firstIdentChar used to help to determine if a character can be the first letter
+ * of a JavaIdentifier and the other one (restIdentChar) to determine if it can be part of a
+ * JavaIdentifier other than the first character.
+ * Java uses the same file UnicodeData.txt as the unicode.js script to define the unicodes.
+ * For more:
+ * https://github.com/jhipster/prettier-java/issues/116
+ * https://github.com/jhipster/prettier-java/pull/155
+ */
+"use strict";
+const addRanges = (set, rangesArr) => {
+ for (let i = 0; i < rangesArr.length; i++) {
+ const range = rangesArr[i];
+ const start = range[0];
+ const end = range[1];
+ for (let codePoint = start; codePoint <= end; codePoint++) {
+ set.add(codePoint);
+ }
+ }
+};
+const fic = new Set([
+ 181, 257, 259, 261, 263, 265, 267, 269, 271, 273, 275, 277, 279, 281, 283,
+ 285, 287, 289, 291, 293, 295, 297, 299, 301, 303, 305, 307, 309, 314, 316,
+ 318, 320, 322, 324, 326, 331, 333, 335, 337, 339, 341, 343, 345, 347, 349,
+ 351, 353, 355, 357, 359, 361, 363, 365, 367, 369, 371, 373, 375, 378, 380,
+ 387, 389, 392, 402, 405, 414, 417, 419, 421, 424, 429, 432, 436, 438, 454,
+ 457, 460, 462, 464, 466, 468, 470, 472, 474, 479, 481, 483, 485, 487, 489,
+ 491, 493, 499, 501, 505, 507, 509, 511, 513, 515, 517, 519, 521, 523, 525,
+ 527, 529, 531, 533, 535, 537, 539, 541, 543, 545, 547, 549, 551, 553, 555,
+ 557, 559, 561, 572, 578, 583, 585, 587, 589, 881, 883, 887, 912, 985, 987,
+ 989, 991, 993, 995, 997, 999, 1001, 1003, 1005, 1013, 1016, 1121, 1123, 1125,
+ 1127, 1129, 1131, 1133, 1135, 1137, 1139, 1141, 1143, 1145, 1147, 1149, 1151,
+ 1153, 1163, 1165, 1167, 1169, 1171, 1173, 1175, 1177, 1179, 1181, 1183, 1185,
+ 1187, 1189, 1191, 1193, 1195, 1197, 1199, 1201, 1203, 1205, 1207, 1209, 1211,
+ 1213, 1215, 1218, 1220, 1222, 1224, 1226, 1228, 1233, 1235, 1237, 1239, 1241,
+ 1243, 1245, 1247, 1249, 1251, 1253, 1255, 1257, 1259, 1261, 1263, 1265, 1267,
+ 1269, 1271, 1273, 1275, 1277, 1279, 1281, 1283, 1285, 1287, 1289, 1291, 1293,
+ 1295, 1297, 1299, 1301, 1303, 1305, 1307, 1309, 1311, 1313, 1315, 1317, 1319,
+ 1321, 1323, 1325, 1327, 7681, 7683, 7685, 7687, 7689, 7691, 7693, 7695, 7697,
+ 7699, 7701, 7703, 7705, 7707, 7709, 7711, 7713, 7715, 7717, 7719, 7721, 7723,
+ 7725, 7727, 7729, 7731, 7733, 7735, 7737, 7739, 7741, 7743, 7745, 7747, 7749,
+ 7751, 7753, 7755, 7757, 7759, 7761, 7763, 7765, 7767, 7769, 7771, 7773, 7775,
+ 7777, 7779, 7781, 7783, 7785, 7787, 7789, 7791, 7793, 7795, 7797, 7799, 7801,
+ 7803, 7805, 7807, 7809, 7811, 7813, 7815, 7817, 7819, 7821, 7823, 7825, 7827,
+ 7839, 7841, 7843, 7845, 7847, 7849, 7851, 7853, 7855, 7857, 7859, 7861, 7863,
+ 7865, 7867, 7869, 7871, 7873, 7875, 7877, 7879, 7881, 7883, 7885, 7887, 7889,
+ 7891, 7893, 7895, 7897, 7899, 7901, 7903, 7905, 7907, 7909, 7911, 7913, 7915,
+ 7917, 7919, 7921, 7923, 7925, 7927, 7929, 7931, 7933, 8126, 8458, 8467, 8495,
+ 8500, 8505, 8526, 8580, 11361, 11368, 11370, 11372, 11377, 11393, 11395,
+ 11397, 11399, 11401, 11403, 11405, 11407, 11409, 11411, 11413, 11415, 11417,
+ 11419, 11421, 11423, 11425, 11427, 11429, 11431, 11433, 11435, 11437, 11439,
+ 11441, 11443, 11445, 11447, 11449, 11451, 11453, 11455, 11457, 11459, 11461,
+ 11463, 11465, 11467, 11469, 11471, 11473, 11475, 11477, 11479, 11481, 11483,
+ 11485, 11487, 11489, 11500, 11502, 11507, 11559, 11565, 42561, 42563, 42565,
+ 42567, 42569, 42571, 42573, 42575, 42577, 42579, 42581, 42583, 42585, 42587,
+ 42589, 42591, 42593, 42595, 42597, 42599, 42601, 42603, 42605, 42625, 42627,
+ 42629, 42631, 42633, 42635, 42637, 42639, 42641, 42643, 42645, 42647, 42649,
+ 42651, 42787, 42789, 42791, 42793, 42795, 42797, 42803, 42805, 42807, 42809,
+ 42811, 42813, 42815, 42817, 42819, 42821, 42823, 42825, 42827, 42829, 42831,
+ 42833, 42835, 42837, 42839, 42841, 42843, 42845, 42847, 42849, 42851, 42853,
+ 42855, 42857, 42859, 42861, 42863, 42874, 42876, 42879, 42881, 42883, 42885,
+ 42887, 42892, 42894, 42897, 42903, 42905, 42907, 42909, 42911, 42913, 42915,
+ 42917, 42919, 42921, 42927, 42933, 42935, 42937, 42939, 42941, 42943, 42947,
+ 43002, 119995, 120779, 748, 750, 884, 890, 1369, 1600, 2042, 2074, 2084, 2088,
+ 2417, 3654, 3782, 4348, 6103, 6211, 6823, 7544, 8305, 8319, 11631, 11823,
+ 12293, 12347, 40981, 42508, 42623, 42864, 42888, 43471, 43494, 43632, 43741,
+ 65392, 94179, 125259, 170, 186, 443, 660, 1749, 1791, 1808, 1969, 2365, 2384,
+ 2482, 2493, 2510, 2556, 2654, 2749, 2768, 2809, 2877, 2929, 2947, 2972, 3024,
+ 3133, 3200, 3261, 3294, 3389, 3406, 3517, 3716, 3749, 3773, 3840, 4159, 4193,
+ 4238, 4696, 4800, 6108, 6314, 7418, 12294, 12348, 12447, 12543, 13312, 19968,
+ 42606, 42895, 42999, 43259, 43642, 43697, 43712, 43714, 43762, 44032, 64285,
+ 64318, 67592, 67644, 68096, 69415, 69956, 70006, 70106, 70108, 70280, 70461,
+ 70480, 70751, 70855, 71236, 71352, 71935, 72161, 72163, 72192, 72250, 72272,
+ 72349, 72768, 73030, 73112, 94032, 94208, 123214, 126500, 126503, 126521,
+ 126523, 126530, 126535, 126537, 126539, 126548, 126551, 126553, 126555,
+ 126557, 126559, 126564, 126590, 131072, 173824, 177984, 178208, 183984, 453,
+ 456, 459, 498, 8124, 8140, 8188, 256, 258, 260, 262, 264, 266, 268, 270, 272,
+ 274, 276, 278, 280, 282, 284, 286, 288, 290, 292, 294, 296, 298, 300, 302,
+ 304, 306, 308, 310, 313, 315, 317, 319, 321, 323, 325, 327, 330, 332, 334,
+ 336, 338, 340, 342, 344, 346, 348, 350, 352, 354, 356, 358, 360, 362, 364,
+ 366, 368, 370, 372, 374, 379, 381, 388, 418, 420, 425, 428, 437, 444, 452,
+ 455, 458, 461, 463, 465, 467, 469, 471, 473, 475, 478, 480, 482, 484, 486,
+ 488, 490, 492, 494, 497, 500, 506, 508, 510, 512, 514, 516, 518, 520, 522,
+ 524, 526, 528, 530, 532, 534, 536, 538, 540, 542, 544, 546, 548, 550, 552,
+ 554, 556, 558, 560, 562, 577, 584, 586, 588, 590, 880, 882, 886, 895, 902,
+ 908, 975, 984, 986, 988, 990, 992, 994, 996, 998, 1000, 1002, 1004, 1006,
+ 1012, 1015, 1120, 1122, 1124, 1126, 1128, 1130, 1132, 1134, 1136, 1138, 1140,
+ 1142, 1144, 1146, 1148, 1150, 1152, 1162, 1164, 1166, 1168, 1170, 1172, 1174,
+ 1176, 1178, 1180, 1182, 1184, 1186, 1188, 1190, 1192, 1194, 1196, 1198, 1200,
+ 1202, 1204, 1206, 1208, 1210, 1212, 1214, 1219, 1221, 1223, 1225, 1227, 1229,
+ 1232, 1234, 1236, 1238, 1240, 1242, 1244, 1246, 1248, 1250, 1252, 1254, 1256,
+ 1258, 1260, 1262, 1264, 1266, 1268, 1270, 1272, 1274, 1276, 1278, 1280, 1282,
+ 1284, 1286, 1288, 1290, 1292, 1294, 1296, 1298, 1300, 1302, 1304, 1306, 1308,
+ 1310, 1312, 1314, 1316, 1318, 1320, 1322, 1324, 1326, 4295, 4301, 7680, 7682,
+ 7684, 7686, 7688, 7690, 7692, 7694, 7696, 7698, 7700, 7702, 7704, 7706, 7708,
+ 7710, 7712, 7714, 7716, 7718, 7720, 7722, 7724, 7726, 7728, 7730, 7732, 7734,
+ 7736, 7738, 7740, 7742, 7744, 7746, 7748, 7750, 7752, 7754, 7756, 7758, 7760,
+ 7762, 7764, 7766, 7768, 7770, 7772, 7774, 7776, 7778, 7780, 7782, 7784, 7786,
+ 7788, 7790, 7792, 7794, 7796, 7798, 7800, 7802, 7804, 7806, 7808, 7810, 7812,
+ 7814, 7816, 7818, 7820, 7822, 7824, 7826, 7828, 7838, 7840, 7842, 7844, 7846,
+ 7848, 7850, 7852, 7854, 7856, 7858, 7860, 7862, 7864, 7866, 7868, 7870, 7872,
+ 7874, 7876, 7878, 7880, 7882, 7884, 7886, 7888, 7890, 7892, 7894, 7896, 7898,
+ 7900, 7902, 7904, 7906, 7908, 7910, 7912, 7914, 7916, 7918, 7920, 7922, 7924,
+ 7926, 7928, 7930, 7932, 7934, 8025, 8027, 8029, 8031, 8450, 8455, 8469, 8484,
+ 8486, 8488, 8517, 8579, 11360, 11367, 11369, 11371, 11378, 11381, 11394,
+ 11396, 11398, 11400, 11402, 11404, 11406, 11408, 11410, 11412, 11414, 11416,
+ 11418, 11420, 11422, 11424, 11426, 11428, 11430, 11432, 11434, 11436, 11438,
+ 11440, 11442, 11444, 11446, 11448, 11450, 11452, 11454, 11456, 11458, 11460,
+ 11462, 11464, 11466, 11468, 11470, 11472, 11474, 11476, 11478, 11480, 11482,
+ 11484, 11486, 11488, 11490, 11499, 11501, 11506, 42560, 42562, 42564, 42566,
+ 42568, 42570, 42572, 42574, 42576, 42578, 42580, 42582, 42584, 42586, 42588,
+ 42590, 42592, 42594, 42596, 42598, 42600, 42602, 42604, 42624, 42626, 42628,
+ 42630, 42632, 42634, 42636, 42638, 42640, 42642, 42644, 42646, 42648, 42650,
+ 42786, 42788, 42790, 42792, 42794, 42796, 42798, 42802, 42804, 42806, 42808,
+ 42810, 42812, 42814, 42816, 42818, 42820, 42822, 42824, 42826, 42828, 42830,
+ 42832, 42834, 42836, 42838, 42840, 42842, 42844, 42846, 42848, 42850, 42852,
+ 42854, 42856, 42858, 42860, 42862, 42873, 42875, 42880, 42882, 42884, 42886,
+ 42891, 42893, 42896, 42898, 42902, 42904, 42906, 42908, 42910, 42912, 42914,
+ 42916, 42918, 42920, 42934, 42936, 42938, 42940, 42942, 42946, 119964, 119970,
+ 120134, 120778, 12295, 66369, 66378, 36, 1423, 1547, 2555, 2801, 3065, 3647,
+ 6107, 43064, 65020, 65129, 65284, 123647, 126128, 95, 8276, 65343
+]);
+const fic_a = [
+ [97, 122],
+ [223, 246],
+ [248, 255],
+ [311, 312],
+ [328, 329],
+ [382, 384],
+ [396, 397],
+ [409, 411],
+ [426, 427],
+ [441, 442],
+ [445, 447],
+ [476, 477],
+ [495, 496],
+ [563, 569],
+ [575, 576],
+ [591, 659],
+ [661, 687],
+ [891, 893],
+ [940, 974],
+ [976, 977],
+ [981, 983],
+ [1007, 1011],
+ [1019, 1020],
+ [1072, 1119],
+ [1230, 1231],
+ [1376, 1416],
+ [4304, 4346],
+ [4349, 4351],
+ [5112, 5117],
+ [7296, 7304],
+ [7424, 7467],
+ [7531, 7543],
+ [7545, 7578],
+ [7829, 7837],
+ [7935, 7943],
+ [7952, 7957],
+ [7968, 7975],
+ [7984, 7991],
+ [8000, 8005],
+ [8016, 8023],
+ [8032, 8039],
+ [8048, 8061],
+ [8064, 8071],
+ [8080, 8087],
+ [8096, 8103],
+ [8112, 8116],
+ [8118, 8119],
+ [8130, 8132],
+ [8134, 8135],
+ [8144, 8147],
+ [8150, 8151],
+ [8160, 8167],
+ [8178, 8180],
+ [8182, 8183],
+ [8462, 8463],
+ [8508, 8509],
+ [8518, 8521],
+ [11312, 11358],
+ [11365, 11366],
+ [11379, 11380],
+ [11382, 11387],
+ [11491, 11492],
+ [11520, 11557],
+ [42799, 42801],
+ [42865, 42872],
+ [42899, 42901],
+ [43824, 43866],
+ [43872, 43879],
+ [43888, 43967],
+ [64256, 64262],
+ [64275, 64279],
+ [65345, 65370],
+ [66600, 66639],
+ [66776, 66811],
+ [68800, 68850],
+ [71872, 71903],
+ [93792, 93823],
+ [119834, 119859],
+ [119886, 119892],
+ [119894, 119911],
+ [119938, 119963],
+ [119990, 119993],
+ [119997, 120003],
+ [120005, 120015],
+ [120042, 120067],
+ [120094, 120119],
+ [120146, 120171],
+ [120198, 120223],
+ [120250, 120275],
+ [120302, 120327],
+ [120354, 120379],
+ [120406, 120431],
+ [120458, 120485],
+ [120514, 120538],
+ [120540, 120545],
+ [120572, 120596],
+ [120598, 120603],
+ [120630, 120654],
+ [120656, 120661],
+ [120688, 120712],
+ [120714, 120719],
+ [120746, 120770],
+ [120772, 120777],
+ [125218, 125251],
+ [688, 705],
+ [710, 721],
+ [736, 740],
+ [1765, 1766],
+ [2036, 2037],
+ [7288, 7293],
+ [7468, 7530],
+ [7579, 7615],
+ [8336, 8348],
+ [11388, 11389],
+ [12337, 12341],
+ [12445, 12446],
+ [12540, 12542],
+ [42232, 42237],
+ [42652, 42653],
+ [42775, 42783],
+ [43000, 43001],
+ [43763, 43764],
+ [43868, 43871],
+ [65438, 65439],
+ [92992, 92995],
+ [94099, 94111],
+ [94176, 94177],
+ [123191, 123197],
+ [13313, 19893],
+ [19969, 40943],
+ [44033, 55203],
+ [94209, 100343],
+ [131073, 173782],
+ [173825, 177972],
+ [177985, 178205],
+ [178209, 183969],
+ [183985, 191456],
+ [448, 451],
+ [1488, 1514],
+ [1519, 1522],
+ [1568, 1599],
+ [1601, 1610],
+ [1646, 1647],
+ [1649, 1747],
+ [1774, 1775],
+ [1786, 1788],
+ [1810, 1839],
+ [1869, 1957],
+ [1994, 2026],
+ [2048, 2069],
+ [2112, 2136],
+ [2144, 2154],
+ [2208, 2228],
+ [2230, 2237],
+ [2308, 2361],
+ [2392, 2401],
+ [2418, 2432],
+ [2437, 2444],
+ [2447, 2448],
+ [2451, 2472],
+ [2474, 2480],
+ [2486, 2489],
+ [2524, 2525],
+ [2527, 2529],
+ [2544, 2545],
+ [2565, 2570],
+ [2575, 2576],
+ [2579, 2600],
+ [2602, 2608],
+ [2610, 2611],
+ [2613, 2614],
+ [2616, 2617],
+ [2649, 2652],
+ [2674, 2676],
+ [2693, 2701],
+ [2703, 2705],
+ [2707, 2728],
+ [2730, 2736],
+ [2738, 2739],
+ [2741, 2745],
+ [2784, 2785],
+ [2821, 2828],
+ [2831, 2832],
+ [2835, 2856],
+ [2858, 2864],
+ [2866, 2867],
+ [2869, 2873],
+ [2908, 2909],
+ [2911, 2913],
+ [2949, 2954],
+ [2958, 2960],
+ [2962, 2965],
+ [2969, 2970],
+ [2974, 2975],
+ [2979, 2980],
+ [2984, 2986],
+ [2990, 3001],
+ [3077, 3084],
+ [3086, 3088],
+ [3090, 3112],
+ [3114, 3129],
+ [3160, 3162],
+ [3168, 3169],
+ [3205, 3212],
+ [3214, 3216],
+ [3218, 3240],
+ [3242, 3251],
+ [3253, 3257],
+ [3296, 3297],
+ [3313, 3314],
+ [3333, 3340],
+ [3342, 3344],
+ [3346, 3386],
+ [3412, 3414],
+ [3423, 3425],
+ [3450, 3455],
+ [3461, 3478],
+ [3482, 3505],
+ [3507, 3515],
+ [3520, 3526],
+ [3585, 3632],
+ [3634, 3635],
+ [3648, 3653],
+ [3713, 3714],
+ [3718, 3722],
+ [3724, 3747],
+ [3751, 3760],
+ [3762, 3763],
+ [3776, 3780],
+ [3804, 3807],
+ [3904, 3911],
+ [3913, 3948],
+ [3976, 3980],
+ [4096, 4138],
+ [4176, 4181],
+ [4186, 4189],
+ [4197, 4198],
+ [4206, 4208],
+ [4213, 4225],
+ [4352, 4680],
+ [4682, 4685],
+ [4688, 4694],
+ [4698, 4701],
+ [4704, 4744],
+ [4746, 4749],
+ [4752, 4784],
+ [4786, 4789],
+ [4792, 4798],
+ [4802, 4805],
+ [4808, 4822],
+ [4824, 4880],
+ [4882, 4885],
+ [4888, 4954],
+ [4992, 5007],
+ [5121, 5740],
+ [5743, 5759],
+ [5761, 5786],
+ [5792, 5866],
+ [5873, 5880],
+ [5888, 5900],
+ [5902, 5905],
+ [5920, 5937],
+ [5952, 5969],
+ [5984, 5996],
+ [5998, 6000],
+ [6016, 6067],
+ [6176, 6210],
+ [6212, 6264],
+ [6272, 6276],
+ [6279, 6312],
+ [6320, 6389],
+ [6400, 6430],
+ [6480, 6509],
+ [6512, 6516],
+ [6528, 6571],
+ [6576, 6601],
+ [6656, 6678],
+ [6688, 6740],
+ [6917, 6963],
+ [6981, 6987],
+ [7043, 7072],
+ [7086, 7087],
+ [7098, 7141],
+ [7168, 7203],
+ [7245, 7247],
+ [7258, 7287],
+ [7401, 7404],
+ [7406, 7411],
+ [7413, 7414],
+ [8501, 8504],
+ [11568, 11623],
+ [11648, 11670],
+ [11680, 11686],
+ [11688, 11694],
+ [11696, 11702],
+ [11704, 11710],
+ [11712, 11718],
+ [11720, 11726],
+ [11728, 11734],
+ [11736, 11742],
+ [12353, 12438],
+ [12449, 12538],
+ [12549, 12591],
+ [12593, 12686],
+ [12704, 12730],
+ [12784, 12799],
+ [40960, 40980],
+ [40982, 42124],
+ [42192, 42231],
+ [42240, 42507],
+ [42512, 42527],
+ [42538, 42539],
+ [42656, 42725],
+ [43003, 43009],
+ [43011, 43013],
+ [43015, 43018],
+ [43020, 43042],
+ [43072, 43123],
+ [43138, 43187],
+ [43250, 43255],
+ [43261, 43262],
+ [43274, 43301],
+ [43312, 43334],
+ [43360, 43388],
+ [43396, 43442],
+ [43488, 43492],
+ [43495, 43503],
+ [43514, 43518],
+ [43520, 43560],
+ [43584, 43586],
+ [43588, 43595],
+ [43616, 43631],
+ [43633, 43638],
+ [43646, 43695],
+ [43701, 43702],
+ [43705, 43709],
+ [43739, 43740],
+ [43744, 43754],
+ [43777, 43782],
+ [43785, 43790],
+ [43793, 43798],
+ [43808, 43814],
+ [43816, 43822],
+ [43968, 44002],
+ [55216, 55238],
+ [55243, 55291],
+ [63744, 64109],
+ [64112, 64217],
+ [64287, 64296],
+ [64298, 64310],
+ [64312, 64316],
+ [64320, 64321],
+ [64323, 64324],
+ [64326, 64433],
+ [64467, 64829],
+ [64848, 64911],
+ [64914, 64967],
+ [65008, 65019],
+ [65136, 65140],
+ [65142, 65276],
+ [65382, 65391],
+ [65393, 65437],
+ [65440, 65470],
+ [65474, 65479],
+ [65482, 65487],
+ [65490, 65495],
+ [65498, 65500],
+ [65536, 65547],
+ [65549, 65574],
+ [65576, 65594],
+ [65596, 65597],
+ [65599, 65613],
+ [65616, 65629],
+ [65664, 65786],
+ [66176, 66204],
+ [66208, 66256],
+ [66304, 66335],
+ [66349, 66368],
+ [66370, 66377],
+ [66384, 66421],
+ [66432, 66461],
+ [66464, 66499],
+ [66504, 66511],
+ [66640, 66717],
+ [66816, 66855],
+ [66864, 66915],
+ [67072, 67382],
+ [67392, 67413],
+ [67424, 67431],
+ [67584, 67589],
+ [67594, 67637],
+ [67639, 67640],
+ [67647, 67669],
+ [67680, 67702],
+ [67712, 67742],
+ [67808, 67826],
+ [67828, 67829],
+ [67840, 67861],
+ [67872, 67897],
+ [67968, 68023],
+ [68030, 68031],
+ [68112, 68115],
+ [68117, 68119],
+ [68121, 68149],
+ [68192, 68220],
+ [68224, 68252],
+ [68288, 68295],
+ [68297, 68324],
+ [68352, 68405],
+ [68416, 68437],
+ [68448, 68466],
+ [68480, 68497],
+ [68608, 68680],
+ [68864, 68899],
+ [69376, 69404],
+ [69424, 69445],
+ [69600, 69622],
+ [69635, 69687],
+ [69763, 69807],
+ [69840, 69864],
+ [69891, 69926],
+ [69968, 70002],
+ [70019, 70066],
+ [70081, 70084],
+ [70144, 70161],
+ [70163, 70187],
+ [70272, 70278],
+ [70282, 70285],
+ [70287, 70301],
+ [70303, 70312],
+ [70320, 70366],
+ [70405, 70412],
+ [70415, 70416],
+ [70419, 70440],
+ [70442, 70448],
+ [70450, 70451],
+ [70453, 70457],
+ [70493, 70497],
+ [70656, 70708],
+ [70727, 70730],
+ [70784, 70831],
+ [70852, 70853],
+ [71040, 71086],
+ [71128, 71131],
+ [71168, 71215],
+ [71296, 71338],
+ [71424, 71450],
+ [71680, 71723],
+ [72096, 72103],
+ [72106, 72144],
+ [72203, 72242],
+ [72284, 72329],
+ [72384, 72440],
+ [72704, 72712],
+ [72714, 72750],
+ [72818, 72847],
+ [72960, 72966],
+ [72968, 72969],
+ [72971, 73008],
+ [73056, 73061],
+ [73063, 73064],
+ [73066, 73097],
+ [73440, 73458],
+ [73728, 74649],
+ [74880, 75075],
+ [77824, 78894],
+ [82944, 83526],
+ [92160, 92728],
+ [92736, 92766],
+ [92880, 92909],
+ [92928, 92975],
+ [93027, 93047],
+ [93053, 93071],
+ [93952, 94026],
+ [100352, 101106],
+ [110592, 110878],
+ [110928, 110930],
+ [110948, 110951],
+ [110960, 111355],
+ [113664, 113770],
+ [113776, 113788],
+ [113792, 113800],
+ [113808, 113817],
+ [123136, 123180],
+ [123584, 123627],
+ [124928, 125124],
+ [126464, 126467],
+ [126469, 126495],
+ [126497, 126498],
+ [126505, 126514],
+ [126516, 126519],
+ [126541, 126543],
+ [126545, 126546],
+ [126561, 126562],
+ [126567, 126570],
+ [126572, 126578],
+ [126580, 126583],
+ [126585, 126588],
+ [126592, 126601],
+ [126603, 126619],
+ [126625, 126627],
+ [126629, 126633],
+ [126635, 126651],
+ [194560, 195101],
+ [8072, 8079],
+ [8088, 8095],
+ [8104, 8111],
+ [65, 90],
+ [192, 214],
+ [216, 222],
+ [376, 377],
+ [385, 386],
+ [390, 391],
+ [393, 395],
+ [398, 401],
+ [403, 404],
+ [406, 408],
+ [412, 413],
+ [415, 416],
+ [422, 423],
+ [430, 431],
+ [433, 435],
+ [439, 440],
+ [502, 504],
+ [570, 571],
+ [573, 574],
+ [579, 582],
+ [904, 906],
+ [910, 911],
+ [913, 929],
+ [931, 939],
+ [978, 980],
+ [1017, 1018],
+ [1021, 1071],
+ [1216, 1217],
+ [1329, 1366],
+ [4256, 4293],
+ [5024, 5109],
+ [7312, 7354],
+ [7357, 7359],
+ [7944, 7951],
+ [7960, 7965],
+ [7976, 7983],
+ [7992, 7999],
+ [8008, 8013],
+ [8040, 8047],
+ [8120, 8123],
+ [8136, 8139],
+ [8152, 8155],
+ [8168, 8172],
+ [8184, 8187],
+ [8459, 8461],
+ [8464, 8466],
+ [8473, 8477],
+ [8490, 8493],
+ [8496, 8499],
+ [8510, 8511],
+ [11264, 11310],
+ [11362, 11364],
+ [11373, 11376],
+ [11390, 11392],
+ [42877, 42878],
+ [42922, 42926],
+ [42928, 42932],
+ [42948, 42950],
+ [65313, 65338],
+ [66560, 66599],
+ [66736, 66771],
+ [68736, 68786],
+ [71840, 71871],
+ [93760, 93791],
+ [119808, 119833],
+ [119860, 119885],
+ [119912, 119937],
+ [119966, 119967],
+ [119973, 119974],
+ [119977, 119980],
+ [119982, 119989],
+ [120016, 120041],
+ [120068, 120069],
+ [120071, 120074],
+ [120077, 120084],
+ [120086, 120092],
+ [120120, 120121],
+ [120123, 120126],
+ [120128, 120132],
+ [120138, 120144],
+ [120172, 120197],
+ [120224, 120249],
+ [120276, 120301],
+ [120328, 120353],
+ [120380, 120405],
+ [120432, 120457],
+ [120488, 120512],
+ [120546, 120570],
+ [120604, 120628],
+ [120662, 120686],
+ [120720, 120744],
+ [125184, 125217],
+ [5870, 5872],
+ [8544, 8578],
+ [8581, 8584],
+ [12321, 12329],
+ [12344, 12346],
+ [42726, 42735],
+ [65856, 65908],
+ [66513, 66517],
+ [74752, 74862],
+ [162, 165],
+ [2046, 2047],
+ [2546, 2547],
+ [8352, 8383],
+ [65504, 65505],
+ [65509, 65510],
+ [73693, 73696],
+ [8255, 8256],
+ [65075, 65076],
+ [65101, 65103]
+];
+addRanges(fic, fic_a);
+const ricd = new Set([
+ 1471, 1479, 1648, 1809, 2045, 2362, 2364, 2381, 2433, 2492, 2509, 2558, 2620,
+ 2641, 2677, 2748, 2765, 2817, 2876, 2879, 2893, 2902, 2946, 3008, 3021, 3072,
+ 3076, 3201, 3260, 3263, 3270, 3405, 3530, 3542, 3633, 3761, 3893, 3895, 3897,
+ 4038, 4226, 4237, 4253, 6086, 6109, 6313, 6450, 6683, 6742, 6752, 6754, 6783,
+ 6964, 6972, 6978, 7142, 7149, 7405, 7412, 8417, 11647, 42607, 43010, 43014,
+ 43019, 43263, 43443, 43493, 43587, 43596, 43644, 43696, 43713, 43766, 44005,
+ 44008, 44013, 64286, 66045, 66272, 68159, 69633, 70003, 70196, 70206, 70367,
+ 70464, 70726, 70750, 70842, 71229, 71339, 71341, 71351, 72160, 72263, 72767,
+ 73018, 73031, 73109, 73111, 94031, 121461, 121476, 173, 1564, 1757, 1807,
+ 2274, 6158, 65279, 69821, 69837, 917505
+]);
+const ricd_a = [
+ [768, 879],
+ [1155, 1159],
+ [1425, 1469],
+ [1473, 1474],
+ [1476, 1477],
+ [1552, 1562],
+ [1611, 1631],
+ [1750, 1756],
+ [1759, 1764],
+ [1767, 1768],
+ [1770, 1773],
+ [1840, 1866],
+ [1958, 1968],
+ [2027, 2035],
+ [2070, 2073],
+ [2075, 2083],
+ [2085, 2087],
+ [2089, 2093],
+ [2137, 2139],
+ [2259, 2273],
+ [2275, 2306],
+ [2369, 2376],
+ [2385, 2391],
+ [2402, 2403],
+ [2497, 2500],
+ [2530, 2531],
+ [2561, 2562],
+ [2625, 2626],
+ [2631, 2632],
+ [2635, 2637],
+ [2672, 2673],
+ [2689, 2690],
+ [2753, 2757],
+ [2759, 2760],
+ [2786, 2787],
+ [2810, 2815],
+ [2881, 2884],
+ [2914, 2915],
+ [3134, 3136],
+ [3142, 3144],
+ [3146, 3149],
+ [3157, 3158],
+ [3170, 3171],
+ [3276, 3277],
+ [3298, 3299],
+ [3328, 3329],
+ [3387, 3388],
+ [3393, 3396],
+ [3426, 3427],
+ [3538, 3540],
+ [3636, 3642],
+ [3655, 3662],
+ [3764, 3772],
+ [3784, 3789],
+ [3864, 3865],
+ [3953, 3966],
+ [3968, 3972],
+ [3974, 3975],
+ [3981, 3991],
+ [3993, 4028],
+ [4141, 4144],
+ [4146, 4151],
+ [4153, 4154],
+ [4157, 4158],
+ [4184, 4185],
+ [4190, 4192],
+ [4209, 4212],
+ [4229, 4230],
+ [4957, 4959],
+ [5906, 5908],
+ [5938, 5940],
+ [5970, 5971],
+ [6002, 6003],
+ [6068, 6069],
+ [6071, 6077],
+ [6089, 6099],
+ [6155, 6157],
+ [6277, 6278],
+ [6432, 6434],
+ [6439, 6440],
+ [6457, 6459],
+ [6679, 6680],
+ [6744, 6750],
+ [6757, 6764],
+ [6771, 6780],
+ [6832, 6845],
+ [6912, 6915],
+ [6966, 6970],
+ [7019, 7027],
+ [7040, 7041],
+ [7074, 7077],
+ [7080, 7081],
+ [7083, 7085],
+ [7144, 7145],
+ [7151, 7153],
+ [7212, 7219],
+ [7222, 7223],
+ [7376, 7378],
+ [7380, 7392],
+ [7394, 7400],
+ [7416, 7417],
+ [7616, 7673],
+ [7675, 7679],
+ [8400, 8412],
+ [8421, 8432],
+ [11503, 11505],
+ [11744, 11775],
+ [12330, 12333],
+ [12441, 12442],
+ [42612, 42621],
+ [42654, 42655],
+ [42736, 42737],
+ [43045, 43046],
+ [43204, 43205],
+ [43232, 43249],
+ [43302, 43309],
+ [43335, 43345],
+ [43392, 43394],
+ [43446, 43449],
+ [43452, 43453],
+ [43561, 43566],
+ [43569, 43570],
+ [43573, 43574],
+ [43698, 43700],
+ [43703, 43704],
+ [43710, 43711],
+ [43756, 43757],
+ [65024, 65039],
+ [65056, 65071],
+ [66422, 66426],
+ [68097, 68099],
+ [68101, 68102],
+ [68108, 68111],
+ [68152, 68154],
+ [68325, 68326],
+ [68900, 68903],
+ [69446, 69456],
+ [69688, 69702],
+ [69759, 69761],
+ [69811, 69814],
+ [69817, 69818],
+ [69888, 69890],
+ [69927, 69931],
+ [69933, 69940],
+ [70016, 70017],
+ [70070, 70078],
+ [70089, 70092],
+ [70191, 70193],
+ [70198, 70199],
+ [70371, 70378],
+ [70400, 70401],
+ [70459, 70460],
+ [70502, 70508],
+ [70512, 70516],
+ [70712, 70719],
+ [70722, 70724],
+ [70835, 70840],
+ [70847, 70848],
+ [70850, 70851],
+ [71090, 71093],
+ [71100, 71101],
+ [71103, 71104],
+ [71132, 71133],
+ [71219, 71226],
+ [71231, 71232],
+ [71344, 71349],
+ [71453, 71455],
+ [71458, 71461],
+ [71463, 71467],
+ [71727, 71735],
+ [71737, 71738],
+ [72148, 72151],
+ [72154, 72155],
+ [72193, 72202],
+ [72243, 72248],
+ [72251, 72254],
+ [72273, 72278],
+ [72281, 72283],
+ [72330, 72342],
+ [72344, 72345],
+ [72752, 72758],
+ [72760, 72765],
+ [72850, 72871],
+ [72874, 72880],
+ [72882, 72883],
+ [72885, 72886],
+ [73009, 73014],
+ [73020, 73021],
+ [73023, 73029],
+ [73104, 73105],
+ [73459, 73460],
+ [92912, 92916],
+ [92976, 92982],
+ [94095, 94098],
+ [113821, 113822],
+ [119143, 119145],
+ [119163, 119170],
+ [119173, 119179],
+ [119210, 119213],
+ [119362, 119364],
+ [121344, 121398],
+ [121403, 121452],
+ [121499, 121503],
+ [121505, 121519],
+ [122880, 122886],
+ [122888, 122904],
+ [122907, 122913],
+ [122915, 122916],
+ [122918, 122922],
+ [123184, 123190],
+ [123628, 123631],
+ [125136, 125142],
+ [125252, 125258],
+ [917760, 917999],
+ [1536, 1541],
+ [8203, 8207],
+ [8234, 8238],
+ [8288, 8292],
+ [8294, 8303],
+ [65529, 65531],
+ [78896, 78904],
+ [113824, 113827],
+ [119155, 119162],
+ [917536, 917631]
+];
+addRanges(ricd, ricd_a);
+const mac_a = [
+ [0, 8],
+ [14, 27],
+ [127, 159],
+ [768, 879],
+ [6832, 6911],
+ [7616, 7679],
+ [8400, 8447],
+ [65056, 65071],
+ [48, 57]
+];
+addRanges(ricd, mac_a);
+const ric = new Set(
+ (function* () {
+ yield* fic;
+ yield* ricd;
+ })()
+);
+module.exports = {
+ firstIdentChar: fic,
+ restIdentChar: ric
+};
diff --git a/node_modules/java-parser/src/utils.js b/node_modules/java-parser/src/utils.js
new file mode 100644
index 0000000..1173822
--- /dev/null
+++ b/node_modules/java-parser/src/utils.js
@@ -0,0 +1,21 @@
+"use strict";
+
+/**
+ * Should Parser / Lexer Validations be skipped?
+ *
+ * By default (productive mode) the validations would be skipped to reduce parser initialization time.
+ * But during development flows (e.g testing/CI) they should be enabled to detect possible issues.
+ *
+ * @returns {boolean}
+ */
+function getSkipValidations() {
+ return (
+ (process && // (not every runtime has a global `process` object
+ process.env &&
+ process.env["prettier-java-development-mode"] === "enabled") === false
+ );
+}
+
+module.exports = {
+ getSkipValidations
+};
diff --git a/node_modules/lodash/LICENSE b/node_modules/lodash/LICENSE
new file mode 100644
index 0000000..77c42f1
--- /dev/null
+++ b/node_modules/lodash/LICENSE
@@ -0,0 +1,47 @@
+Copyright OpenJS Foundation and other contributors
+
+Based on Underscore.js, copyright Jeremy Ashkenas,
+DocumentCloud and Investigative Reporters & Editors
+
+This software consists of voluntary contributions made by many
+individuals. For exact contribution history, see the revision history
+available at https://github.com/lodash/lodash
+
+The following license applies to all parts of this software except as
+documented below:
+
+====
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+====
+
+Copyright and related rights for sample code are waived via CC0. Sample
+code is defined as all source code displayed within the prose of the
+documentation.
+
+CC0: http://creativecommons.org/publicdomain/zero/1.0/
+
+====
+
+Files located in the node_modules and vendor directories are externally
+maintained libraries used by this software which have their own
+licenses; we recommend you read them, as their terms may differ from the
+terms above.
diff --git a/node_modules/lodash/README.md b/node_modules/lodash/README.md
new file mode 100644
index 0000000..3ab1a05
--- /dev/null
+++ b/node_modules/lodash/README.md
@@ -0,0 +1,39 @@
+# lodash v4.17.21
+
+The [Lodash](https://lodash.com/) library exported as [Node.js](https://nodejs.org/) modules.
+
+## Installation
+
+Using npm:
+```shell
+$ npm i -g npm
+$ npm i --save lodash
+```
+
+In Node.js:
+```js
+// Load the full build.
+var _ = require('lodash');
+// Load the core build.
+var _ = require('lodash/core');
+// Load the FP build for immutable auto-curried iteratee-first data-last methods.
+var fp = require('lodash/fp');
+
+// Load method categories.
+var array = require('lodash/array');
+var object = require('lodash/fp/object');
+
+// Cherry-pick methods for smaller browserify/rollup/webpack bundles.
+var at = require('lodash/at');
+var curryN = require('lodash/fp/curryN');
+```
+
+See the [package source](https://github.com/lodash/lodash/tree/4.17.21-npm) for more details.
+
+**Note:**
+Install [n_](https://www.npmjs.com/package/n_) for Lodash use in the Node.js < 6 REPL.
+
+## Support
+
+Tested in Chrome 74-75, Firefox 66-67, IE 11, Edge 18, Safari 11-12, & Node.js 8-12.
+Automated [browser](https://saucelabs.com/u/lodash) & [CI](https://travis-ci.org/lodash/lodash/) test runs are available.
diff --git a/node_modules/lodash/_DataView.js b/node_modules/lodash/_DataView.js
new file mode 100644
index 0000000..ac2d57c
--- /dev/null
+++ b/node_modules/lodash/_DataView.js
@@ -0,0 +1,7 @@
+var getNative = require('./_getNative'),
+ root = require('./_root');
+
+/* Built-in method references that are verified to be native. */
+var DataView = getNative(root, 'DataView');
+
+module.exports = DataView;
diff --git a/node_modules/lodash/_Hash.js b/node_modules/lodash/_Hash.js
new file mode 100644
index 0000000..b504fe3
--- /dev/null
+++ b/node_modules/lodash/_Hash.js
@@ -0,0 +1,32 @@
+var hashClear = require('./_hashClear'),
+ hashDelete = require('./_hashDelete'),
+ hashGet = require('./_hashGet'),
+ hashHas = require('./_hashHas'),
+ hashSet = require('./_hashSet');
+
+/**
+ * Creates a hash object.
+ *
+ * @private
+ * @constructor
+ * @param {Array} [entries] The key-value pairs to cache.
+ */
+function Hash(entries) {
+ var index = -1,
+ length = entries == null ? 0 : entries.length;
+
+ this.clear();
+ while (++index < length) {
+ var entry = entries[index];
+ this.set(entry[0], entry[1]);
+ }
+}
+
+// Add methods to `Hash`.
+Hash.prototype.clear = hashClear;
+Hash.prototype['delete'] = hashDelete;
+Hash.prototype.get = hashGet;
+Hash.prototype.has = hashHas;
+Hash.prototype.set = hashSet;
+
+module.exports = Hash;
diff --git a/node_modules/lodash/_LazyWrapper.js b/node_modules/lodash/_LazyWrapper.js
new file mode 100644
index 0000000..81786c7
--- /dev/null
+++ b/node_modules/lodash/_LazyWrapper.js
@@ -0,0 +1,28 @@
+var baseCreate = require('./_baseCreate'),
+ baseLodash = require('./_baseLodash');
+
+/** Used as references for the maximum length and index of an array. */
+var MAX_ARRAY_LENGTH = 4294967295;
+
+/**
+ * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
+ *
+ * @private
+ * @constructor
+ * @param {*} value The value to wrap.
+ */
+function LazyWrapper(value) {
+ this.__wrapped__ = value;
+ this.__actions__ = [];
+ this.__dir__ = 1;
+ this.__filtered__ = false;
+ this.__iteratees__ = [];
+ this.__takeCount__ = MAX_ARRAY_LENGTH;
+ this.__views__ = [];
+}
+
+// Ensure `LazyWrapper` is an instance of `baseLodash`.
+LazyWrapper.prototype = baseCreate(baseLodash.prototype);
+LazyWrapper.prototype.constructor = LazyWrapper;
+
+module.exports = LazyWrapper;
diff --git a/node_modules/lodash/_ListCache.js b/node_modules/lodash/_ListCache.js
new file mode 100644
index 0000000..26895c3
--- /dev/null
+++ b/node_modules/lodash/_ListCache.js
@@ -0,0 +1,32 @@
+var listCacheClear = require('./_listCacheClear'),
+ listCacheDelete = require('./_listCacheDelete'),
+ listCacheGet = require('./_listCacheGet'),
+ listCacheHas = require('./_listCacheHas'),
+ listCacheSet = require('./_listCacheSet');
+
+/**
+ * Creates an list cache object.
+ *
+ * @private
+ * @constructor
+ * @param {Array} [entries] The key-value pairs to cache.
+ */
+function ListCache(entries) {
+ var index = -1,
+ length = entries == null ? 0 : entries.length;
+
+ this.clear();
+ while (++index < length) {
+ var entry = entries[index];
+ this.set(entry[0], entry[1]);
+ }
+}
+
+// Add methods to `ListCache`.
+ListCache.prototype.clear = listCacheClear;
+ListCache.prototype['delete'] = listCacheDelete;
+ListCache.prototype.get = listCacheGet;
+ListCache.prototype.has = listCacheHas;
+ListCache.prototype.set = listCacheSet;
+
+module.exports = ListCache;
diff --git a/node_modules/lodash/_LodashWrapper.js b/node_modules/lodash/_LodashWrapper.js
new file mode 100644
index 0000000..c1e4d9d
--- /dev/null
+++ b/node_modules/lodash/_LodashWrapper.js
@@ -0,0 +1,22 @@
+var baseCreate = require('./_baseCreate'),
+ baseLodash = require('./_baseLodash');
+
+/**
+ * The base constructor for creating `lodash` wrapper objects.
+ *
+ * @private
+ * @param {*} value The value to wrap.
+ * @param {boolean} [chainAll] Enable explicit method chain sequences.
+ */
+function LodashWrapper(value, chainAll) {
+ this.__wrapped__ = value;
+ this.__actions__ = [];
+ this.__chain__ = !!chainAll;
+ this.__index__ = 0;
+ this.__values__ = undefined;
+}
+
+LodashWrapper.prototype = baseCreate(baseLodash.prototype);
+LodashWrapper.prototype.constructor = LodashWrapper;
+
+module.exports = LodashWrapper;
diff --git a/node_modules/lodash/_Map.js b/node_modules/lodash/_Map.js
new file mode 100644
index 0000000..b73f29a
--- /dev/null
+++ b/node_modules/lodash/_Map.js
@@ -0,0 +1,7 @@
+var getNative = require('./_getNative'),
+ root = require('./_root');
+
+/* Built-in method references that are verified to be native. */
+var Map = getNative(root, 'Map');
+
+module.exports = Map;
diff --git a/node_modules/lodash/_MapCache.js b/node_modules/lodash/_MapCache.js
new file mode 100644
index 0000000..4a4eea7
--- /dev/null
+++ b/node_modules/lodash/_MapCache.js
@@ -0,0 +1,32 @@
+var mapCacheClear = require('./_mapCacheClear'),
+ mapCacheDelete = require('./_mapCacheDelete'),
+ mapCacheGet = require('./_mapCacheGet'),
+ mapCacheHas = require('./_mapCacheHas'),
+ mapCacheSet = require('./_mapCacheSet');
+
+/**
+ * Creates a map cache object to store key-value pairs.
+ *
+ * @private
+ * @constructor
+ * @param {Array} [entries] The key-value pairs to cache.
+ */
+function MapCache(entries) {
+ var index = -1,
+ length = entries == null ? 0 : entries.length;
+
+ this.clear();
+ while (++index < length) {
+ var entry = entries[index];
+ this.set(entry[0], entry[1]);
+ }
+}
+
+// Add methods to `MapCache`.
+MapCache.prototype.clear = mapCacheClear;
+MapCache.prototype['delete'] = mapCacheDelete;
+MapCache.prototype.get = mapCacheGet;
+MapCache.prototype.has = mapCacheHas;
+MapCache.prototype.set = mapCacheSet;
+
+module.exports = MapCache;
diff --git a/node_modules/lodash/_Promise.js b/node_modules/lodash/_Promise.js
new file mode 100644
index 0000000..247b9e1
--- /dev/null
+++ b/node_modules/lodash/_Promise.js
@@ -0,0 +1,7 @@
+var getNative = require('./_getNative'),
+ root = require('./_root');
+
+/* Built-in method references that are verified to be native. */
+var Promise = getNative(root, 'Promise');
+
+module.exports = Promise;
diff --git a/node_modules/lodash/_Set.js b/node_modules/lodash/_Set.js
new file mode 100644
index 0000000..b3c8dcb
--- /dev/null
+++ b/node_modules/lodash/_Set.js
@@ -0,0 +1,7 @@
+var getNative = require('./_getNative'),
+ root = require('./_root');
+
+/* Built-in method references that are verified to be native. */
+var Set = getNative(root, 'Set');
+
+module.exports = Set;
diff --git a/node_modules/lodash/_SetCache.js b/node_modules/lodash/_SetCache.js
new file mode 100644
index 0000000..6468b06
--- /dev/null
+++ b/node_modules/lodash/_SetCache.js
@@ -0,0 +1,27 @@
+var MapCache = require('./_MapCache'),
+ setCacheAdd = require('./_setCacheAdd'),
+ setCacheHas = require('./_setCacheHas');
+
+/**
+ *
+ * Creates an array cache object to store unique values.
+ *
+ * @private
+ * @constructor
+ * @param {Array} [values] The values to cache.
+ */
+function SetCache(values) {
+ var index = -1,
+ length = values == null ? 0 : values.length;
+
+ this.__data__ = new MapCache;
+ while (++index < length) {
+ this.add(values[index]);
+ }
+}
+
+// Add methods to `SetCache`.
+SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
+SetCache.prototype.has = setCacheHas;
+
+module.exports = SetCache;
diff --git a/node_modules/lodash/_Stack.js b/node_modules/lodash/_Stack.js
new file mode 100644
index 0000000..80b2cf1
--- /dev/null
+++ b/node_modules/lodash/_Stack.js
@@ -0,0 +1,27 @@
+var ListCache = require('./_ListCache'),
+ stackClear = require('./_stackClear'),
+ stackDelete = require('./_stackDelete'),
+ stackGet = require('./_stackGet'),
+ stackHas = require('./_stackHas'),
+ stackSet = require('./_stackSet');
+
+/**
+ * Creates a stack cache object to store key-value pairs.
+ *
+ * @private
+ * @constructor
+ * @param {Array} [entries] The key-value pairs to cache.
+ */
+function Stack(entries) {
+ var data = this.__data__ = new ListCache(entries);
+ this.size = data.size;
+}
+
+// Add methods to `Stack`.
+Stack.prototype.clear = stackClear;
+Stack.prototype['delete'] = stackDelete;
+Stack.prototype.get = stackGet;
+Stack.prototype.has = stackHas;
+Stack.prototype.set = stackSet;
+
+module.exports = Stack;
diff --git a/node_modules/lodash/_Symbol.js b/node_modules/lodash/_Symbol.js
new file mode 100644
index 0000000..a013f7c
--- /dev/null
+++ b/node_modules/lodash/_Symbol.js
@@ -0,0 +1,6 @@
+var root = require('./_root');
+
+/** Built-in value references. */
+var Symbol = root.Symbol;
+
+module.exports = Symbol;
diff --git a/node_modules/lodash/_Uint8Array.js b/node_modules/lodash/_Uint8Array.js
new file mode 100644
index 0000000..2fb30e1
--- /dev/null
+++ b/node_modules/lodash/_Uint8Array.js
@@ -0,0 +1,6 @@
+var root = require('./_root');
+
+/** Built-in value references. */
+var Uint8Array = root.Uint8Array;
+
+module.exports = Uint8Array;
diff --git a/node_modules/lodash/_WeakMap.js b/node_modules/lodash/_WeakMap.js
new file mode 100644
index 0000000..567f86c
--- /dev/null
+++ b/node_modules/lodash/_WeakMap.js
@@ -0,0 +1,7 @@
+var getNative = require('./_getNative'),
+ root = require('./_root');
+
+/* Built-in method references that are verified to be native. */
+var WeakMap = getNative(root, 'WeakMap');
+
+module.exports = WeakMap;
diff --git a/node_modules/lodash/_apply.js b/node_modules/lodash/_apply.js
new file mode 100644
index 0000000..36436dd
--- /dev/null
+++ b/node_modules/lodash/_apply.js
@@ -0,0 +1,21 @@
+/**
+ * A faster alternative to `Function#apply`, this function invokes `func`
+ * with the `this` binding of `thisArg` and the arguments of `args`.
+ *
+ * @private
+ * @param {Function} func The function to invoke.
+ * @param {*} thisArg The `this` binding of `func`.
+ * @param {Array} args The arguments to invoke `func` with.
+ * @returns {*} Returns the result of `func`.
+ */
+function apply(func, thisArg, args) {
+ switch (args.length) {
+ case 0: return func.call(thisArg);
+ case 1: return func.call(thisArg, args[0]);
+ case 2: return func.call(thisArg, args[0], args[1]);
+ case 3: return func.call(thisArg, args[0], args[1], args[2]);
+ }
+ return func.apply(thisArg, args);
+}
+
+module.exports = apply;
diff --git a/node_modules/lodash/_arrayAggregator.js b/node_modules/lodash/_arrayAggregator.js
new file mode 100644
index 0000000..d96c3ca
--- /dev/null
+++ b/node_modules/lodash/_arrayAggregator.js
@@ -0,0 +1,22 @@
+/**
+ * A specialized version of `baseAggregator` for arrays.
+ *
+ * @private
+ * @param {Array} [array] The array to iterate over.
+ * @param {Function} setter The function to set `accumulator` values.
+ * @param {Function} iteratee The iteratee to transform keys.
+ * @param {Object} accumulator The initial aggregated object.
+ * @returns {Function} Returns `accumulator`.
+ */
+function arrayAggregator(array, setter, iteratee, accumulator) {
+ var index = -1,
+ length = array == null ? 0 : array.length;
+
+ while (++index < length) {
+ var value = array[index];
+ setter(accumulator, value, iteratee(value), array);
+ }
+ return accumulator;
+}
+
+module.exports = arrayAggregator;
diff --git a/node_modules/lodash/_arrayEach.js b/node_modules/lodash/_arrayEach.js
new file mode 100644
index 0000000..2c5f579
--- /dev/null
+++ b/node_modules/lodash/_arrayEach.js
@@ -0,0 +1,22 @@
+/**
+ * A specialized version of `_.forEach` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} [array] The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns `array`.
+ */
+function arrayEach(array, iteratee) {
+ var index = -1,
+ length = array == null ? 0 : array.length;
+
+ while (++index < length) {
+ if (iteratee(array[index], index, array) === false) {
+ break;
+ }
+ }
+ return array;
+}
+
+module.exports = arrayEach;
diff --git a/node_modules/lodash/_arrayEachRight.js b/node_modules/lodash/_arrayEachRight.js
new file mode 100644
index 0000000..976ca5c
--- /dev/null
+++ b/node_modules/lodash/_arrayEachRight.js
@@ -0,0 +1,21 @@
+/**
+ * A specialized version of `_.forEachRight` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} [array] The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns `array`.
+ */
+function arrayEachRight(array, iteratee) {
+ var length = array == null ? 0 : array.length;
+
+ while (length--) {
+ if (iteratee(array[length], length, array) === false) {
+ break;
+ }
+ }
+ return array;
+}
+
+module.exports = arrayEachRight;
diff --git a/node_modules/lodash/_arrayEvery.js b/node_modules/lodash/_arrayEvery.js
new file mode 100644
index 0000000..e26a918
--- /dev/null
+++ b/node_modules/lodash/_arrayEvery.js
@@ -0,0 +1,23 @@
+/**
+ * A specialized version of `_.every` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} [array] The array to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {boolean} Returns `true` if all elements pass the predicate check,
+ * else `false`.
+ */
+function arrayEvery(array, predicate) {
+ var index = -1,
+ length = array == null ? 0 : array.length;
+
+ while (++index < length) {
+ if (!predicate(array[index], index, array)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+module.exports = arrayEvery;
diff --git a/node_modules/lodash/_arrayFilter.js b/node_modules/lodash/_arrayFilter.js
new file mode 100644
index 0000000..75ea254
--- /dev/null
+++ b/node_modules/lodash/_arrayFilter.js
@@ -0,0 +1,25 @@
+/**
+ * A specialized version of `_.filter` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} [array] The array to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {Array} Returns the new filtered array.
+ */
+function arrayFilter(array, predicate) {
+ var index = -1,
+ length = array == null ? 0 : array.length,
+ resIndex = 0,
+ result = [];
+
+ while (++index < length) {
+ var value = array[index];
+ if (predicate(value, index, array)) {
+ result[resIndex++] = value;
+ }
+ }
+ return result;
+}
+
+module.exports = arrayFilter;
diff --git a/node_modules/lodash/_arrayIncludes.js b/node_modules/lodash/_arrayIncludes.js
new file mode 100644
index 0000000..3737a6d
--- /dev/null
+++ b/node_modules/lodash/_arrayIncludes.js
@@ -0,0 +1,17 @@
+var baseIndexOf = require('./_baseIndexOf');
+
+/**
+ * A specialized version of `_.includes` for arrays without support for
+ * specifying an index to search from.
+ *
+ * @private
+ * @param {Array} [array] The array to inspect.
+ * @param {*} target The value to search for.
+ * @returns {boolean} Returns `true` if `target` is found, else `false`.
+ */
+function arrayIncludes(array, value) {
+ var length = array == null ? 0 : array.length;
+ return !!length && baseIndexOf(array, value, 0) > -1;
+}
+
+module.exports = arrayIncludes;
diff --git a/node_modules/lodash/_arrayIncludesWith.js b/node_modules/lodash/_arrayIncludesWith.js
new file mode 100644
index 0000000..235fd97
--- /dev/null
+++ b/node_modules/lodash/_arrayIncludesWith.js
@@ -0,0 +1,22 @@
+/**
+ * This function is like `arrayIncludes` except that it accepts a comparator.
+ *
+ * @private
+ * @param {Array} [array] The array to inspect.
+ * @param {*} target The value to search for.
+ * @param {Function} comparator The comparator invoked per element.
+ * @returns {boolean} Returns `true` if `target` is found, else `false`.
+ */
+function arrayIncludesWith(array, value, comparator) {
+ var index = -1,
+ length = array == null ? 0 : array.length;
+
+ while (++index < length) {
+ if (comparator(value, array[index])) {
+ return true;
+ }
+ }
+ return false;
+}
+
+module.exports = arrayIncludesWith;
diff --git a/node_modules/lodash/_arrayLikeKeys.js b/node_modules/lodash/_arrayLikeKeys.js
new file mode 100644
index 0000000..b2ec9ce
--- /dev/null
+++ b/node_modules/lodash/_arrayLikeKeys.js
@@ -0,0 +1,49 @@
+var baseTimes = require('./_baseTimes'),
+ isArguments = require('./isArguments'),
+ isArray = require('./isArray'),
+ isBuffer = require('./isBuffer'),
+ isIndex = require('./_isIndex'),
+ isTypedArray = require('./isTypedArray');
+
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/**
+ * Creates an array of the enumerable property names of the array-like `value`.
+ *
+ * @private
+ * @param {*} value The value to query.
+ * @param {boolean} inherited Specify returning inherited property names.
+ * @returns {Array} Returns the array of property names.
+ */
+function arrayLikeKeys(value, inherited) {
+ var isArr = isArray(value),
+ isArg = !isArr && isArguments(value),
+ isBuff = !isArr && !isArg && isBuffer(value),
+ isType = !isArr && !isArg && !isBuff && isTypedArray(value),
+ skipIndexes = isArr || isArg || isBuff || isType,
+ result = skipIndexes ? baseTimes(value.length, String) : [],
+ length = result.length;
+
+ for (var key in value) {
+ if ((inherited || hasOwnProperty.call(value, key)) &&
+ !(skipIndexes && (
+ // Safari 9 has enumerable `arguments.length` in strict mode.
+ key == 'length' ||
+ // Node.js 0.10 has enumerable non-index properties on buffers.
+ (isBuff && (key == 'offset' || key == 'parent')) ||
+ // PhantomJS 2 has enumerable non-index properties on typed arrays.
+ (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
+ // Skip index properties.
+ isIndex(key, length)
+ ))) {
+ result.push(key);
+ }
+ }
+ return result;
+}
+
+module.exports = arrayLikeKeys;
diff --git a/node_modules/lodash/_arrayMap.js b/node_modules/lodash/_arrayMap.js
new file mode 100644
index 0000000..22b2246
--- /dev/null
+++ b/node_modules/lodash/_arrayMap.js
@@ -0,0 +1,21 @@
+/**
+ * A specialized version of `_.map` for arrays without support for iteratee
+ * shorthands.
+ *
+ * @private
+ * @param {Array} [array] The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns the new mapped array.
+ */
+function arrayMap(array, iteratee) {
+ var index = -1,
+ length = array == null ? 0 : array.length,
+ result = Array(length);
+
+ while (++index < length) {
+ result[index] = iteratee(array[index], index, array);
+ }
+ return result;
+}
+
+module.exports = arrayMap;
diff --git a/node_modules/lodash/_arrayPush.js b/node_modules/lodash/_arrayPush.js
new file mode 100644
index 0000000..7d742b3
--- /dev/null
+++ b/node_modules/lodash/_arrayPush.js
@@ -0,0 +1,20 @@
+/**
+ * Appends the elements of `values` to `array`.
+ *
+ * @private
+ * @param {Array} array The array to modify.
+ * @param {Array} values The values to append.
+ * @returns {Array} Returns `array`.
+ */
+function arrayPush(array, values) {
+ var index = -1,
+ length = values.length,
+ offset = array.length;
+
+ while (++index < length) {
+ array[offset + index] = values[index];
+ }
+ return array;
+}
+
+module.exports = arrayPush;
diff --git a/node_modules/lodash/_arrayReduce.js b/node_modules/lodash/_arrayReduce.js
new file mode 100644
index 0000000..de8b79b
--- /dev/null
+++ b/node_modules/lodash/_arrayReduce.js
@@ -0,0 +1,26 @@
+/**
+ * A specialized version of `_.reduce` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} [array] The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {*} [accumulator] The initial value.
+ * @param {boolean} [initAccum] Specify using the first element of `array` as
+ * the initial value.
+ * @returns {*} Returns the accumulated value.
+ */
+function arrayReduce(array, iteratee, accumulator, initAccum) {
+ var index = -1,
+ length = array == null ? 0 : array.length;
+
+ if (initAccum && length) {
+ accumulator = array[++index];
+ }
+ while (++index < length) {
+ accumulator = iteratee(accumulator, array[index], index, array);
+ }
+ return accumulator;
+}
+
+module.exports = arrayReduce;
diff --git a/node_modules/lodash/_arrayReduceRight.js b/node_modules/lodash/_arrayReduceRight.js
new file mode 100644
index 0000000..22d8976
--- /dev/null
+++ b/node_modules/lodash/_arrayReduceRight.js
@@ -0,0 +1,24 @@
+/**
+ * A specialized version of `_.reduceRight` for arrays without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} [array] The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {*} [accumulator] The initial value.
+ * @param {boolean} [initAccum] Specify using the last element of `array` as
+ * the initial value.
+ * @returns {*} Returns the accumulated value.
+ */
+function arrayReduceRight(array, iteratee, accumulator, initAccum) {
+ var length = array == null ? 0 : array.length;
+ if (initAccum && length) {
+ accumulator = array[--length];
+ }
+ while (length--) {
+ accumulator = iteratee(accumulator, array[length], length, array);
+ }
+ return accumulator;
+}
+
+module.exports = arrayReduceRight;
diff --git a/node_modules/lodash/_arraySample.js b/node_modules/lodash/_arraySample.js
new file mode 100644
index 0000000..fcab010
--- /dev/null
+++ b/node_modules/lodash/_arraySample.js
@@ -0,0 +1,15 @@
+var baseRandom = require('./_baseRandom');
+
+/**
+ * A specialized version of `_.sample` for arrays.
+ *
+ * @private
+ * @param {Array} array The array to sample.
+ * @returns {*} Returns the random element.
+ */
+function arraySample(array) {
+ var length = array.length;
+ return length ? array[baseRandom(0, length - 1)] : undefined;
+}
+
+module.exports = arraySample;
diff --git a/node_modules/lodash/_arraySampleSize.js b/node_modules/lodash/_arraySampleSize.js
new file mode 100644
index 0000000..8c7e364
--- /dev/null
+++ b/node_modules/lodash/_arraySampleSize.js
@@ -0,0 +1,17 @@
+var baseClamp = require('./_baseClamp'),
+ copyArray = require('./_copyArray'),
+ shuffleSelf = require('./_shuffleSelf');
+
+/**
+ * A specialized version of `_.sampleSize` for arrays.
+ *
+ * @private
+ * @param {Array} array The array to sample.
+ * @param {number} n The number of elements to sample.
+ * @returns {Array} Returns the random elements.
+ */
+function arraySampleSize(array, n) {
+ return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));
+}
+
+module.exports = arraySampleSize;
diff --git a/node_modules/lodash/_arrayShuffle.js b/node_modules/lodash/_arrayShuffle.js
new file mode 100644
index 0000000..46313a3
--- /dev/null
+++ b/node_modules/lodash/_arrayShuffle.js
@@ -0,0 +1,15 @@
+var copyArray = require('./_copyArray'),
+ shuffleSelf = require('./_shuffleSelf');
+
+/**
+ * A specialized version of `_.shuffle` for arrays.
+ *
+ * @private
+ * @param {Array} array The array to shuffle.
+ * @returns {Array} Returns the new shuffled array.
+ */
+function arrayShuffle(array) {
+ return shuffleSelf(copyArray(array));
+}
+
+module.exports = arrayShuffle;
diff --git a/node_modules/lodash/_arraySome.js b/node_modules/lodash/_arraySome.js
new file mode 100644
index 0000000..6fd02fd
--- /dev/null
+++ b/node_modules/lodash/_arraySome.js
@@ -0,0 +1,23 @@
+/**
+ * A specialized version of `_.some` for arrays without support for iteratee
+ * shorthands.
+ *
+ * @private
+ * @param {Array} [array] The array to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {boolean} Returns `true` if any element passes the predicate check,
+ * else `false`.
+ */
+function arraySome(array, predicate) {
+ var index = -1,
+ length = array == null ? 0 : array.length;
+
+ while (++index < length) {
+ if (predicate(array[index], index, array)) {
+ return true;
+ }
+ }
+ return false;
+}
+
+module.exports = arraySome;
diff --git a/node_modules/lodash/_asciiSize.js b/node_modules/lodash/_asciiSize.js
new file mode 100644
index 0000000..11d29c3
--- /dev/null
+++ b/node_modules/lodash/_asciiSize.js
@@ -0,0 +1,12 @@
+var baseProperty = require('./_baseProperty');
+
+/**
+ * Gets the size of an ASCII `string`.
+ *
+ * @private
+ * @param {string} string The string inspect.
+ * @returns {number} Returns the string size.
+ */
+var asciiSize = baseProperty('length');
+
+module.exports = asciiSize;
diff --git a/node_modules/lodash/_asciiToArray.js b/node_modules/lodash/_asciiToArray.js
new file mode 100644
index 0000000..8e3dd5b
--- /dev/null
+++ b/node_modules/lodash/_asciiToArray.js
@@ -0,0 +1,12 @@
+/**
+ * Converts an ASCII `string` to an array.
+ *
+ * @private
+ * @param {string} string The string to convert.
+ * @returns {Array} Returns the converted array.
+ */
+function asciiToArray(string) {
+ return string.split('');
+}
+
+module.exports = asciiToArray;
diff --git a/node_modules/lodash/_asciiWords.js b/node_modules/lodash/_asciiWords.js
new file mode 100644
index 0000000..d765f0f
--- /dev/null
+++ b/node_modules/lodash/_asciiWords.js
@@ -0,0 +1,15 @@
+/** Used to match words composed of alphanumeric characters. */
+var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
+
+/**
+ * Splits an ASCII `string` into an array of its words.
+ *
+ * @private
+ * @param {string} The string to inspect.
+ * @returns {Array} Returns the words of `string`.
+ */
+function asciiWords(string) {
+ return string.match(reAsciiWord) || [];
+}
+
+module.exports = asciiWords;
diff --git a/node_modules/lodash/_assignMergeValue.js b/node_modules/lodash/_assignMergeValue.js
new file mode 100644
index 0000000..cb1185e
--- /dev/null
+++ b/node_modules/lodash/_assignMergeValue.js
@@ -0,0 +1,20 @@
+var baseAssignValue = require('./_baseAssignValue'),
+ eq = require('./eq');
+
+/**
+ * This function is like `assignValue` except that it doesn't assign
+ * `undefined` values.
+ *
+ * @private
+ * @param {Object} object The object to modify.
+ * @param {string} key The key of the property to assign.
+ * @param {*} value The value to assign.
+ */
+function assignMergeValue(object, key, value) {
+ if ((value !== undefined && !eq(object[key], value)) ||
+ (value === undefined && !(key in object))) {
+ baseAssignValue(object, key, value);
+ }
+}
+
+module.exports = assignMergeValue;
diff --git a/node_modules/lodash/_assignValue.js b/node_modules/lodash/_assignValue.js
new file mode 100644
index 0000000..4083957
--- /dev/null
+++ b/node_modules/lodash/_assignValue.js
@@ -0,0 +1,28 @@
+var baseAssignValue = require('./_baseAssignValue'),
+ eq = require('./eq');
+
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/**
+ * Assigns `value` to `key` of `object` if the existing value is not equivalent
+ * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
+ * for equality comparisons.
+ *
+ * @private
+ * @param {Object} object The object to modify.
+ * @param {string} key The key of the property to assign.
+ * @param {*} value The value to assign.
+ */
+function assignValue(object, key, value) {
+ var objValue = object[key];
+ if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
+ (value === undefined && !(key in object))) {
+ baseAssignValue(object, key, value);
+ }
+}
+
+module.exports = assignValue;
diff --git a/node_modules/lodash/_assocIndexOf.js b/node_modules/lodash/_assocIndexOf.js
new file mode 100644
index 0000000..5b77a2b
--- /dev/null
+++ b/node_modules/lodash/_assocIndexOf.js
@@ -0,0 +1,21 @@
+var eq = require('./eq');
+
+/**
+ * Gets the index at which the `key` is found in `array` of key-value pairs.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {*} key The key to search for.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ */
+function assocIndexOf(array, key) {
+ var length = array.length;
+ while (length--) {
+ if (eq(array[length][0], key)) {
+ return length;
+ }
+ }
+ return -1;
+}
+
+module.exports = assocIndexOf;
diff --git a/node_modules/lodash/_baseAggregator.js b/node_modules/lodash/_baseAggregator.js
new file mode 100644
index 0000000..4bc9e91
--- /dev/null
+++ b/node_modules/lodash/_baseAggregator.js
@@ -0,0 +1,21 @@
+var baseEach = require('./_baseEach');
+
+/**
+ * Aggregates elements of `collection` on `accumulator` with keys transformed
+ * by `iteratee` and values set by `setter`.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} setter The function to set `accumulator` values.
+ * @param {Function} iteratee The iteratee to transform keys.
+ * @param {Object} accumulator The initial aggregated object.
+ * @returns {Function} Returns `accumulator`.
+ */
+function baseAggregator(collection, setter, iteratee, accumulator) {
+ baseEach(collection, function(value, key, collection) {
+ setter(accumulator, value, iteratee(value), collection);
+ });
+ return accumulator;
+}
+
+module.exports = baseAggregator;
diff --git a/node_modules/lodash/_baseAssign.js b/node_modules/lodash/_baseAssign.js
new file mode 100644
index 0000000..e5c4a1a
--- /dev/null
+++ b/node_modules/lodash/_baseAssign.js
@@ -0,0 +1,17 @@
+var copyObject = require('./_copyObject'),
+ keys = require('./keys');
+
+/**
+ * The base implementation of `_.assign` without support for multiple sources
+ * or `customizer` functions.
+ *
+ * @private
+ * @param {Object} object The destination object.
+ * @param {Object} source The source object.
+ * @returns {Object} Returns `object`.
+ */
+function baseAssign(object, source) {
+ return object && copyObject(source, keys(source), object);
+}
+
+module.exports = baseAssign;
diff --git a/node_modules/lodash/_baseAssignIn.js b/node_modules/lodash/_baseAssignIn.js
new file mode 100644
index 0000000..6624f90
--- /dev/null
+++ b/node_modules/lodash/_baseAssignIn.js
@@ -0,0 +1,17 @@
+var copyObject = require('./_copyObject'),
+ keysIn = require('./keysIn');
+
+/**
+ * The base implementation of `_.assignIn` without support for multiple sources
+ * or `customizer` functions.
+ *
+ * @private
+ * @param {Object} object The destination object.
+ * @param {Object} source The source object.
+ * @returns {Object} Returns `object`.
+ */
+function baseAssignIn(object, source) {
+ return object && copyObject(source, keysIn(source), object);
+}
+
+module.exports = baseAssignIn;
diff --git a/node_modules/lodash/_baseAssignValue.js b/node_modules/lodash/_baseAssignValue.js
new file mode 100644
index 0000000..d6f66ef
--- /dev/null
+++ b/node_modules/lodash/_baseAssignValue.js
@@ -0,0 +1,25 @@
+var defineProperty = require('./_defineProperty');
+
+/**
+ * The base implementation of `assignValue` and `assignMergeValue` without
+ * value checks.
+ *
+ * @private
+ * @param {Object} object The object to modify.
+ * @param {string} key The key of the property to assign.
+ * @param {*} value The value to assign.
+ */
+function baseAssignValue(object, key, value) {
+ if (key == '__proto__' && defineProperty) {
+ defineProperty(object, key, {
+ 'configurable': true,
+ 'enumerable': true,
+ 'value': value,
+ 'writable': true
+ });
+ } else {
+ object[key] = value;
+ }
+}
+
+module.exports = baseAssignValue;
diff --git a/node_modules/lodash/_baseAt.js b/node_modules/lodash/_baseAt.js
new file mode 100644
index 0000000..90e4237
--- /dev/null
+++ b/node_modules/lodash/_baseAt.js
@@ -0,0 +1,23 @@
+var get = require('./get');
+
+/**
+ * The base implementation of `_.at` without support for individual paths.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {string[]} paths The property paths to pick.
+ * @returns {Array} Returns the picked elements.
+ */
+function baseAt(object, paths) {
+ var index = -1,
+ length = paths.length,
+ result = Array(length),
+ skip = object == null;
+
+ while (++index < length) {
+ result[index] = skip ? undefined : get(object, paths[index]);
+ }
+ return result;
+}
+
+module.exports = baseAt;
diff --git a/node_modules/lodash/_baseClamp.js b/node_modules/lodash/_baseClamp.js
new file mode 100644
index 0000000..a1c5692
--- /dev/null
+++ b/node_modules/lodash/_baseClamp.js
@@ -0,0 +1,22 @@
+/**
+ * The base implementation of `_.clamp` which doesn't coerce arguments.
+ *
+ * @private
+ * @param {number} number The number to clamp.
+ * @param {number} [lower] The lower bound.
+ * @param {number} upper The upper bound.
+ * @returns {number} Returns the clamped number.
+ */
+function baseClamp(number, lower, upper) {
+ if (number === number) {
+ if (upper !== undefined) {
+ number = number <= upper ? number : upper;
+ }
+ if (lower !== undefined) {
+ number = number >= lower ? number : lower;
+ }
+ }
+ return number;
+}
+
+module.exports = baseClamp;
diff --git a/node_modules/lodash/_baseClone.js b/node_modules/lodash/_baseClone.js
new file mode 100644
index 0000000..69f8705
--- /dev/null
+++ b/node_modules/lodash/_baseClone.js
@@ -0,0 +1,166 @@
+var Stack = require('./_Stack'),
+ arrayEach = require('./_arrayEach'),
+ assignValue = require('./_assignValue'),
+ baseAssign = require('./_baseAssign'),
+ baseAssignIn = require('./_baseAssignIn'),
+ cloneBuffer = require('./_cloneBuffer'),
+ copyArray = require('./_copyArray'),
+ copySymbols = require('./_copySymbols'),
+ copySymbolsIn = require('./_copySymbolsIn'),
+ getAllKeys = require('./_getAllKeys'),
+ getAllKeysIn = require('./_getAllKeysIn'),
+ getTag = require('./_getTag'),
+ initCloneArray = require('./_initCloneArray'),
+ initCloneByTag = require('./_initCloneByTag'),
+ initCloneObject = require('./_initCloneObject'),
+ isArray = require('./isArray'),
+ isBuffer = require('./isBuffer'),
+ isMap = require('./isMap'),
+ isObject = require('./isObject'),
+ isSet = require('./isSet'),
+ keys = require('./keys'),
+ keysIn = require('./keysIn');
+
+/** Used to compose bitmasks for cloning. */
+var CLONE_DEEP_FLAG = 1,
+ CLONE_FLAT_FLAG = 2,
+ CLONE_SYMBOLS_FLAG = 4;
+
+/** `Object#toString` result references. */
+var argsTag = '[object Arguments]',
+ arrayTag = '[object Array]',
+ boolTag = '[object Boolean]',
+ dateTag = '[object Date]',
+ errorTag = '[object Error]',
+ funcTag = '[object Function]',
+ genTag = '[object GeneratorFunction]',
+ mapTag = '[object Map]',
+ numberTag = '[object Number]',
+ objectTag = '[object Object]',
+ regexpTag = '[object RegExp]',
+ setTag = '[object Set]',
+ stringTag = '[object String]',
+ symbolTag = '[object Symbol]',
+ weakMapTag = '[object WeakMap]';
+
+var arrayBufferTag = '[object ArrayBuffer]',
+ dataViewTag = '[object DataView]',
+ float32Tag = '[object Float32Array]',
+ float64Tag = '[object Float64Array]',
+ int8Tag = '[object Int8Array]',
+ int16Tag = '[object Int16Array]',
+ int32Tag = '[object Int32Array]',
+ uint8Tag = '[object Uint8Array]',
+ uint8ClampedTag = '[object Uint8ClampedArray]',
+ uint16Tag = '[object Uint16Array]',
+ uint32Tag = '[object Uint32Array]';
+
+/** Used to identify `toStringTag` values supported by `_.clone`. */
+var cloneableTags = {};
+cloneableTags[argsTag] = cloneableTags[arrayTag] =
+cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
+cloneableTags[boolTag] = cloneableTags[dateTag] =
+cloneableTags[float32Tag] = cloneableTags[float64Tag] =
+cloneableTags[int8Tag] = cloneableTags[int16Tag] =
+cloneableTags[int32Tag] = cloneableTags[mapTag] =
+cloneableTags[numberTag] = cloneableTags[objectTag] =
+cloneableTags[regexpTag] = cloneableTags[setTag] =
+cloneableTags[stringTag] = cloneableTags[symbolTag] =
+cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
+cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
+cloneableTags[errorTag] = cloneableTags[funcTag] =
+cloneableTags[weakMapTag] = false;
+
+/**
+ * The base implementation of `_.clone` and `_.cloneDeep` which tracks
+ * traversed objects.
+ *
+ * @private
+ * @param {*} value The value to clone.
+ * @param {boolean} bitmask The bitmask flags.
+ * 1 - Deep clone
+ * 2 - Flatten inherited properties
+ * 4 - Clone symbols
+ * @param {Function} [customizer] The function to customize cloning.
+ * @param {string} [key] The key of `value`.
+ * @param {Object} [object] The parent object of `value`.
+ * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
+ * @returns {*} Returns the cloned value.
+ */
+function baseClone(value, bitmask, customizer, key, object, stack) {
+ var result,
+ isDeep = bitmask & CLONE_DEEP_FLAG,
+ isFlat = bitmask & CLONE_FLAT_FLAG,
+ isFull = bitmask & CLONE_SYMBOLS_FLAG;
+
+ if (customizer) {
+ result = object ? customizer(value, key, object, stack) : customizer(value);
+ }
+ if (result !== undefined) {
+ return result;
+ }
+ if (!isObject(value)) {
+ return value;
+ }
+ var isArr = isArray(value);
+ if (isArr) {
+ result = initCloneArray(value);
+ if (!isDeep) {
+ return copyArray(value, result);
+ }
+ } else {
+ var tag = getTag(value),
+ isFunc = tag == funcTag || tag == genTag;
+
+ if (isBuffer(value)) {
+ return cloneBuffer(value, isDeep);
+ }
+ if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
+ result = (isFlat || isFunc) ? {} : initCloneObject(value);
+ if (!isDeep) {
+ return isFlat
+ ? copySymbolsIn(value, baseAssignIn(result, value))
+ : copySymbols(value, baseAssign(result, value));
+ }
+ } else {
+ if (!cloneableTags[tag]) {
+ return object ? value : {};
+ }
+ result = initCloneByTag(value, tag, isDeep);
+ }
+ }
+ // Check for circular references and return its corresponding clone.
+ stack || (stack = new Stack);
+ var stacked = stack.get(value);
+ if (stacked) {
+ return stacked;
+ }
+ stack.set(value, result);
+
+ if (isSet(value)) {
+ value.forEach(function(subValue) {
+ result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
+ });
+ } else if (isMap(value)) {
+ value.forEach(function(subValue, key) {
+ result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
+ });
+ }
+
+ var keysFunc = isFull
+ ? (isFlat ? getAllKeysIn : getAllKeys)
+ : (isFlat ? keysIn : keys);
+
+ var props = isArr ? undefined : keysFunc(value);
+ arrayEach(props || value, function(subValue, key) {
+ if (props) {
+ key = subValue;
+ subValue = value[key];
+ }
+ // Recursively populate clone (susceptible to call stack limits).
+ assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
+ });
+ return result;
+}
+
+module.exports = baseClone;
diff --git a/node_modules/lodash/_baseConforms.js b/node_modules/lodash/_baseConforms.js
new file mode 100644
index 0000000..947e20d
--- /dev/null
+++ b/node_modules/lodash/_baseConforms.js
@@ -0,0 +1,18 @@
+var baseConformsTo = require('./_baseConformsTo'),
+ keys = require('./keys');
+
+/**
+ * The base implementation of `_.conforms` which doesn't clone `source`.
+ *
+ * @private
+ * @param {Object} source The object of property predicates to conform to.
+ * @returns {Function} Returns the new spec function.
+ */
+function baseConforms(source) {
+ var props = keys(source);
+ return function(object) {
+ return baseConformsTo(object, source, props);
+ };
+}
+
+module.exports = baseConforms;
diff --git a/node_modules/lodash/_baseConformsTo.js b/node_modules/lodash/_baseConformsTo.js
new file mode 100644
index 0000000..e449cb8
--- /dev/null
+++ b/node_modules/lodash/_baseConformsTo.js
@@ -0,0 +1,27 @@
+/**
+ * The base implementation of `_.conformsTo` which accepts `props` to check.
+ *
+ * @private
+ * @param {Object} object The object to inspect.
+ * @param {Object} source The object of property predicates to conform to.
+ * @returns {boolean} Returns `true` if `object` conforms, else `false`.
+ */
+function baseConformsTo(object, source, props) {
+ var length = props.length;
+ if (object == null) {
+ return !length;
+ }
+ object = Object(object);
+ while (length--) {
+ var key = props[length],
+ predicate = source[key],
+ value = object[key];
+
+ if ((value === undefined && !(key in object)) || !predicate(value)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+module.exports = baseConformsTo;
diff --git a/node_modules/lodash/_baseCreate.js b/node_modules/lodash/_baseCreate.js
new file mode 100644
index 0000000..ffa6a52
--- /dev/null
+++ b/node_modules/lodash/_baseCreate.js
@@ -0,0 +1,30 @@
+var isObject = require('./isObject');
+
+/** Built-in value references. */
+var objectCreate = Object.create;
+
+/**
+ * The base implementation of `_.create` without support for assigning
+ * properties to the created object.
+ *
+ * @private
+ * @param {Object} proto The object to inherit from.
+ * @returns {Object} Returns the new object.
+ */
+var baseCreate = (function() {
+ function object() {}
+ return function(proto) {
+ if (!isObject(proto)) {
+ return {};
+ }
+ if (objectCreate) {
+ return objectCreate(proto);
+ }
+ object.prototype = proto;
+ var result = new object;
+ object.prototype = undefined;
+ return result;
+ };
+}());
+
+module.exports = baseCreate;
diff --git a/node_modules/lodash/_baseDelay.js b/node_modules/lodash/_baseDelay.js
new file mode 100644
index 0000000..1486d69
--- /dev/null
+++ b/node_modules/lodash/_baseDelay.js
@@ -0,0 +1,21 @@
+/** Error message constants. */
+var FUNC_ERROR_TEXT = 'Expected a function';
+
+/**
+ * The base implementation of `_.delay` and `_.defer` which accepts `args`
+ * to provide to `func`.
+ *
+ * @private
+ * @param {Function} func The function to delay.
+ * @param {number} wait The number of milliseconds to delay invocation.
+ * @param {Array} args The arguments to provide to `func`.
+ * @returns {number|Object} Returns the timer id or timeout object.
+ */
+function baseDelay(func, wait, args) {
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ return setTimeout(function() { func.apply(undefined, args); }, wait);
+}
+
+module.exports = baseDelay;
diff --git a/node_modules/lodash/_baseDifference.js b/node_modules/lodash/_baseDifference.js
new file mode 100644
index 0000000..343ac19
--- /dev/null
+++ b/node_modules/lodash/_baseDifference.js
@@ -0,0 +1,67 @@
+var SetCache = require('./_SetCache'),
+ arrayIncludes = require('./_arrayIncludes'),
+ arrayIncludesWith = require('./_arrayIncludesWith'),
+ arrayMap = require('./_arrayMap'),
+ baseUnary = require('./_baseUnary'),
+ cacheHas = require('./_cacheHas');
+
+/** Used as the size to enable large array optimizations. */
+var LARGE_ARRAY_SIZE = 200;
+
+/**
+ * The base implementation of methods like `_.difference` without support
+ * for excluding multiple arrays or iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {Array} values The values to exclude.
+ * @param {Function} [iteratee] The iteratee invoked per element.
+ * @param {Function} [comparator] The comparator invoked per element.
+ * @returns {Array} Returns the new array of filtered values.
+ */
+function baseDifference(array, values, iteratee, comparator) {
+ var index = -1,
+ includes = arrayIncludes,
+ isCommon = true,
+ length = array.length,
+ result = [],
+ valuesLength = values.length;
+
+ if (!length) {
+ return result;
+ }
+ if (iteratee) {
+ values = arrayMap(values, baseUnary(iteratee));
+ }
+ if (comparator) {
+ includes = arrayIncludesWith;
+ isCommon = false;
+ }
+ else if (values.length >= LARGE_ARRAY_SIZE) {
+ includes = cacheHas;
+ isCommon = false;
+ values = new SetCache(values);
+ }
+ outer:
+ while (++index < length) {
+ var value = array[index],
+ computed = iteratee == null ? value : iteratee(value);
+
+ value = (comparator || value !== 0) ? value : 0;
+ if (isCommon && computed === computed) {
+ var valuesIndex = valuesLength;
+ while (valuesIndex--) {
+ if (values[valuesIndex] === computed) {
+ continue outer;
+ }
+ }
+ result.push(value);
+ }
+ else if (!includes(values, computed, comparator)) {
+ result.push(value);
+ }
+ }
+ return result;
+}
+
+module.exports = baseDifference;
diff --git a/node_modules/lodash/_baseEach.js b/node_modules/lodash/_baseEach.js
new file mode 100644
index 0000000..512c067
--- /dev/null
+++ b/node_modules/lodash/_baseEach.js
@@ -0,0 +1,14 @@
+var baseForOwn = require('./_baseForOwn'),
+ createBaseEach = require('./_createBaseEach');
+
+/**
+ * The base implementation of `_.forEach` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array|Object} Returns `collection`.
+ */
+var baseEach = createBaseEach(baseForOwn);
+
+module.exports = baseEach;
diff --git a/node_modules/lodash/_baseEachRight.js b/node_modules/lodash/_baseEachRight.js
new file mode 100644
index 0000000..0a8feec
--- /dev/null
+++ b/node_modules/lodash/_baseEachRight.js
@@ -0,0 +1,14 @@
+var baseForOwnRight = require('./_baseForOwnRight'),
+ createBaseEach = require('./_createBaseEach');
+
+/**
+ * The base implementation of `_.forEachRight` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array|Object} Returns `collection`.
+ */
+var baseEachRight = createBaseEach(baseForOwnRight, true);
+
+module.exports = baseEachRight;
diff --git a/node_modules/lodash/_baseEvery.js b/node_modules/lodash/_baseEvery.js
new file mode 100644
index 0000000..fa52f7b
--- /dev/null
+++ b/node_modules/lodash/_baseEvery.js
@@ -0,0 +1,21 @@
+var baseEach = require('./_baseEach');
+
+/**
+ * The base implementation of `_.every` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {boolean} Returns `true` if all elements pass the predicate check,
+ * else `false`
+ */
+function baseEvery(collection, predicate) {
+ var result = true;
+ baseEach(collection, function(value, index, collection) {
+ result = !!predicate(value, index, collection);
+ return result;
+ });
+ return result;
+}
+
+module.exports = baseEvery;
diff --git a/node_modules/lodash/_baseExtremum.js b/node_modules/lodash/_baseExtremum.js
new file mode 100644
index 0000000..9d6aa77
--- /dev/null
+++ b/node_modules/lodash/_baseExtremum.js
@@ -0,0 +1,32 @@
+var isSymbol = require('./isSymbol');
+
+/**
+ * The base implementation of methods like `_.max` and `_.min` which accepts a
+ * `comparator` to determine the extremum value.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The iteratee invoked per iteration.
+ * @param {Function} comparator The comparator used to compare values.
+ * @returns {*} Returns the extremum value.
+ */
+function baseExtremum(array, iteratee, comparator) {
+ var index = -1,
+ length = array.length;
+
+ while (++index < length) {
+ var value = array[index],
+ current = iteratee(value);
+
+ if (current != null && (computed === undefined
+ ? (current === current && !isSymbol(current))
+ : comparator(current, computed)
+ )) {
+ var computed = current,
+ result = value;
+ }
+ }
+ return result;
+}
+
+module.exports = baseExtremum;
diff --git a/node_modules/lodash/_baseFill.js b/node_modules/lodash/_baseFill.js
new file mode 100644
index 0000000..46ef9c7
--- /dev/null
+++ b/node_modules/lodash/_baseFill.js
@@ -0,0 +1,32 @@
+var toInteger = require('./toInteger'),
+ toLength = require('./toLength');
+
+/**
+ * The base implementation of `_.fill` without an iteratee call guard.
+ *
+ * @private
+ * @param {Array} array The array to fill.
+ * @param {*} value The value to fill `array` with.
+ * @param {number} [start=0] The start position.
+ * @param {number} [end=array.length] The end position.
+ * @returns {Array} Returns `array`.
+ */
+function baseFill(array, value, start, end) {
+ var length = array.length;
+
+ start = toInteger(start);
+ if (start < 0) {
+ start = -start > length ? 0 : (length + start);
+ }
+ end = (end === undefined || end > length) ? length : toInteger(end);
+ if (end < 0) {
+ end += length;
+ }
+ end = start > end ? 0 : toLength(end);
+ while (start < end) {
+ array[start++] = value;
+ }
+ return array;
+}
+
+module.exports = baseFill;
diff --git a/node_modules/lodash/_baseFilter.js b/node_modules/lodash/_baseFilter.js
new file mode 100644
index 0000000..4678477
--- /dev/null
+++ b/node_modules/lodash/_baseFilter.js
@@ -0,0 +1,21 @@
+var baseEach = require('./_baseEach');
+
+/**
+ * The base implementation of `_.filter` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {Array} Returns the new filtered array.
+ */
+function baseFilter(collection, predicate) {
+ var result = [];
+ baseEach(collection, function(value, index, collection) {
+ if (predicate(value, index, collection)) {
+ result.push(value);
+ }
+ });
+ return result;
+}
+
+module.exports = baseFilter;
diff --git a/node_modules/lodash/_baseFindIndex.js b/node_modules/lodash/_baseFindIndex.js
new file mode 100644
index 0000000..e3f5d8a
--- /dev/null
+++ b/node_modules/lodash/_baseFindIndex.js
@@ -0,0 +1,24 @@
+/**
+ * The base implementation of `_.findIndex` and `_.findLastIndex` without
+ * support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {Function} predicate The function invoked per iteration.
+ * @param {number} fromIndex The index to search from.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ */
+function baseFindIndex(array, predicate, fromIndex, fromRight) {
+ var length = array.length,
+ index = fromIndex + (fromRight ? 1 : -1);
+
+ while ((fromRight ? index-- : ++index < length)) {
+ if (predicate(array[index], index, array)) {
+ return index;
+ }
+ }
+ return -1;
+}
+
+module.exports = baseFindIndex;
diff --git a/node_modules/lodash/_baseFindKey.js b/node_modules/lodash/_baseFindKey.js
new file mode 100644
index 0000000..2e430f3
--- /dev/null
+++ b/node_modules/lodash/_baseFindKey.js
@@ -0,0 +1,23 @@
+/**
+ * The base implementation of methods like `_.findKey` and `_.findLastKey`,
+ * without support for iteratee shorthands, which iterates over `collection`
+ * using `eachFunc`.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to inspect.
+ * @param {Function} predicate The function invoked per iteration.
+ * @param {Function} eachFunc The function to iterate over `collection`.
+ * @returns {*} Returns the found element or its key, else `undefined`.
+ */
+function baseFindKey(collection, predicate, eachFunc) {
+ var result;
+ eachFunc(collection, function(value, key, collection) {
+ if (predicate(value, key, collection)) {
+ result = key;
+ return false;
+ }
+ });
+ return result;
+}
+
+module.exports = baseFindKey;
diff --git a/node_modules/lodash/_baseFlatten.js b/node_modules/lodash/_baseFlatten.js
new file mode 100644
index 0000000..4b1e009
--- /dev/null
+++ b/node_modules/lodash/_baseFlatten.js
@@ -0,0 +1,38 @@
+var arrayPush = require('./_arrayPush'),
+ isFlattenable = require('./_isFlattenable');
+
+/**
+ * The base implementation of `_.flatten` with support for restricting flattening.
+ *
+ * @private
+ * @param {Array} array The array to flatten.
+ * @param {number} depth The maximum recursion depth.
+ * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
+ * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
+ * @param {Array} [result=[]] The initial result value.
+ * @returns {Array} Returns the new flattened array.
+ */
+function baseFlatten(array, depth, predicate, isStrict, result) {
+ var index = -1,
+ length = array.length;
+
+ predicate || (predicate = isFlattenable);
+ result || (result = []);
+
+ while (++index < length) {
+ var value = array[index];
+ if (depth > 0 && predicate(value)) {
+ if (depth > 1) {
+ // Recursively flatten arrays (susceptible to call stack limits).
+ baseFlatten(value, depth - 1, predicate, isStrict, result);
+ } else {
+ arrayPush(result, value);
+ }
+ } else if (!isStrict) {
+ result[result.length] = value;
+ }
+ }
+ return result;
+}
+
+module.exports = baseFlatten;
diff --git a/node_modules/lodash/_baseFor.js b/node_modules/lodash/_baseFor.js
new file mode 100644
index 0000000..d946590
--- /dev/null
+++ b/node_modules/lodash/_baseFor.js
@@ -0,0 +1,16 @@
+var createBaseFor = require('./_createBaseFor');
+
+/**
+ * The base implementation of `baseForOwn` which iterates over `object`
+ * properties returned by `keysFunc` and invokes `iteratee` for each property.
+ * Iteratee functions may exit iteration early by explicitly returning `false`.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {Function} keysFunc The function to get the keys of `object`.
+ * @returns {Object} Returns `object`.
+ */
+var baseFor = createBaseFor();
+
+module.exports = baseFor;
diff --git a/node_modules/lodash/_baseForOwn.js b/node_modules/lodash/_baseForOwn.js
new file mode 100644
index 0000000..503d523
--- /dev/null
+++ b/node_modules/lodash/_baseForOwn.js
@@ -0,0 +1,16 @@
+var baseFor = require('./_baseFor'),
+ keys = require('./keys');
+
+/**
+ * The base implementation of `_.forOwn` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Object} Returns `object`.
+ */
+function baseForOwn(object, iteratee) {
+ return object && baseFor(object, iteratee, keys);
+}
+
+module.exports = baseForOwn;
diff --git a/node_modules/lodash/_baseForOwnRight.js b/node_modules/lodash/_baseForOwnRight.js
new file mode 100644
index 0000000..a4b10e6
--- /dev/null
+++ b/node_modules/lodash/_baseForOwnRight.js
@@ -0,0 +1,16 @@
+var baseForRight = require('./_baseForRight'),
+ keys = require('./keys');
+
+/**
+ * The base implementation of `_.forOwnRight` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Object} Returns `object`.
+ */
+function baseForOwnRight(object, iteratee) {
+ return object && baseForRight(object, iteratee, keys);
+}
+
+module.exports = baseForOwnRight;
diff --git a/node_modules/lodash/_baseForRight.js b/node_modules/lodash/_baseForRight.js
new file mode 100644
index 0000000..32842cd
--- /dev/null
+++ b/node_modules/lodash/_baseForRight.js
@@ -0,0 +1,15 @@
+var createBaseFor = require('./_createBaseFor');
+
+/**
+ * This function is like `baseFor` except that it iterates over properties
+ * in the opposite order.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {Function} keysFunc The function to get the keys of `object`.
+ * @returns {Object} Returns `object`.
+ */
+var baseForRight = createBaseFor(true);
+
+module.exports = baseForRight;
diff --git a/node_modules/lodash/_baseFunctions.js b/node_modules/lodash/_baseFunctions.js
new file mode 100644
index 0000000..d23bc9b
--- /dev/null
+++ b/node_modules/lodash/_baseFunctions.js
@@ -0,0 +1,19 @@
+var arrayFilter = require('./_arrayFilter'),
+ isFunction = require('./isFunction');
+
+/**
+ * The base implementation of `_.functions` which creates an array of
+ * `object` function property names filtered from `props`.
+ *
+ * @private
+ * @param {Object} object The object to inspect.
+ * @param {Array} props The property names to filter.
+ * @returns {Array} Returns the function names.
+ */
+function baseFunctions(object, props) {
+ return arrayFilter(props, function(key) {
+ return isFunction(object[key]);
+ });
+}
+
+module.exports = baseFunctions;
diff --git a/node_modules/lodash/_baseGet.js b/node_modules/lodash/_baseGet.js
new file mode 100644
index 0000000..a194913
--- /dev/null
+++ b/node_modules/lodash/_baseGet.js
@@ -0,0 +1,24 @@
+var castPath = require('./_castPath'),
+ toKey = require('./_toKey');
+
+/**
+ * The base implementation of `_.get` without support for default values.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path of the property to get.
+ * @returns {*} Returns the resolved value.
+ */
+function baseGet(object, path) {
+ path = castPath(path, object);
+
+ var index = 0,
+ length = path.length;
+
+ while (object != null && index < length) {
+ object = object[toKey(path[index++])];
+ }
+ return (index && index == length) ? object : undefined;
+}
+
+module.exports = baseGet;
diff --git a/node_modules/lodash/_baseGetAllKeys.js b/node_modules/lodash/_baseGetAllKeys.js
new file mode 100644
index 0000000..8ad204e
--- /dev/null
+++ b/node_modules/lodash/_baseGetAllKeys.js
@@ -0,0 +1,20 @@
+var arrayPush = require('./_arrayPush'),
+ isArray = require('./isArray');
+
+/**
+ * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
+ * `keysFunc` and `symbolsFunc` to get the enumerable property names and
+ * symbols of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Function} keysFunc The function to get the keys of `object`.
+ * @param {Function} symbolsFunc The function to get the symbols of `object`.
+ * @returns {Array} Returns the array of property names and symbols.
+ */
+function baseGetAllKeys(object, keysFunc, symbolsFunc) {
+ var result = keysFunc(object);
+ return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
+}
+
+module.exports = baseGetAllKeys;
diff --git a/node_modules/lodash/_baseGetTag.js b/node_modules/lodash/_baseGetTag.js
new file mode 100644
index 0000000..b927ccc
--- /dev/null
+++ b/node_modules/lodash/_baseGetTag.js
@@ -0,0 +1,28 @@
+var Symbol = require('./_Symbol'),
+ getRawTag = require('./_getRawTag'),
+ objectToString = require('./_objectToString');
+
+/** `Object#toString` result references. */
+var nullTag = '[object Null]',
+ undefinedTag = '[object Undefined]';
+
+/** Built-in value references. */
+var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
+
+/**
+ * The base implementation of `getTag` without fallbacks for buggy environments.
+ *
+ * @private
+ * @param {*} value The value to query.
+ * @returns {string} Returns the `toStringTag`.
+ */
+function baseGetTag(value) {
+ if (value == null) {
+ return value === undefined ? undefinedTag : nullTag;
+ }
+ return (symToStringTag && symToStringTag in Object(value))
+ ? getRawTag(value)
+ : objectToString(value);
+}
+
+module.exports = baseGetTag;
diff --git a/node_modules/lodash/_baseGt.js b/node_modules/lodash/_baseGt.js
new file mode 100644
index 0000000..502d273
--- /dev/null
+++ b/node_modules/lodash/_baseGt.js
@@ -0,0 +1,14 @@
+/**
+ * The base implementation of `_.gt` which doesn't coerce arguments.
+ *
+ * @private
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {boolean} Returns `true` if `value` is greater than `other`,
+ * else `false`.
+ */
+function baseGt(value, other) {
+ return value > other;
+}
+
+module.exports = baseGt;
diff --git a/node_modules/lodash/_baseHas.js b/node_modules/lodash/_baseHas.js
new file mode 100644
index 0000000..1b73032
--- /dev/null
+++ b/node_modules/lodash/_baseHas.js
@@ -0,0 +1,19 @@
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/**
+ * The base implementation of `_.has` without support for deep paths.
+ *
+ * @private
+ * @param {Object} [object] The object to query.
+ * @param {Array|string} key The key to check.
+ * @returns {boolean} Returns `true` if `key` exists, else `false`.
+ */
+function baseHas(object, key) {
+ return object != null && hasOwnProperty.call(object, key);
+}
+
+module.exports = baseHas;
diff --git a/node_modules/lodash/_baseHasIn.js b/node_modules/lodash/_baseHasIn.js
new file mode 100644
index 0000000..2e0d042
--- /dev/null
+++ b/node_modules/lodash/_baseHasIn.js
@@ -0,0 +1,13 @@
+/**
+ * The base implementation of `_.hasIn` without support for deep paths.
+ *
+ * @private
+ * @param {Object} [object] The object to query.
+ * @param {Array|string} key The key to check.
+ * @returns {boolean} Returns `true` if `key` exists, else `false`.
+ */
+function baseHasIn(object, key) {
+ return object != null && key in Object(object);
+}
+
+module.exports = baseHasIn;
diff --git a/node_modules/lodash/_baseInRange.js b/node_modules/lodash/_baseInRange.js
new file mode 100644
index 0000000..ec95666
--- /dev/null
+++ b/node_modules/lodash/_baseInRange.js
@@ -0,0 +1,18 @@
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeMax = Math.max,
+ nativeMin = Math.min;
+
+/**
+ * The base implementation of `_.inRange` which doesn't coerce arguments.
+ *
+ * @private
+ * @param {number} number The number to check.
+ * @param {number} start The start of the range.
+ * @param {number} end The end of the range.
+ * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
+ */
+function baseInRange(number, start, end) {
+ return number >= nativeMin(start, end) && number < nativeMax(start, end);
+}
+
+module.exports = baseInRange;
diff --git a/node_modules/lodash/_baseIndexOf.js b/node_modules/lodash/_baseIndexOf.js
new file mode 100644
index 0000000..167e706
--- /dev/null
+++ b/node_modules/lodash/_baseIndexOf.js
@@ -0,0 +1,20 @@
+var baseFindIndex = require('./_baseFindIndex'),
+ baseIsNaN = require('./_baseIsNaN'),
+ strictIndexOf = require('./_strictIndexOf');
+
+/**
+ * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {*} value The value to search for.
+ * @param {number} fromIndex The index to search from.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ */
+function baseIndexOf(array, value, fromIndex) {
+ return value === value
+ ? strictIndexOf(array, value, fromIndex)
+ : baseFindIndex(array, baseIsNaN, fromIndex);
+}
+
+module.exports = baseIndexOf;
diff --git a/node_modules/lodash/_baseIndexOfWith.js b/node_modules/lodash/_baseIndexOfWith.js
new file mode 100644
index 0000000..f815fe0
--- /dev/null
+++ b/node_modules/lodash/_baseIndexOfWith.js
@@ -0,0 +1,23 @@
+/**
+ * This function is like `baseIndexOf` except that it accepts a comparator.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {*} value The value to search for.
+ * @param {number} fromIndex The index to search from.
+ * @param {Function} comparator The comparator invoked per element.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ */
+function baseIndexOfWith(array, value, fromIndex, comparator) {
+ var index = fromIndex - 1,
+ length = array.length;
+
+ while (++index < length) {
+ if (comparator(array[index], value)) {
+ return index;
+ }
+ }
+ return -1;
+}
+
+module.exports = baseIndexOfWith;
diff --git a/node_modules/lodash/_baseIntersection.js b/node_modules/lodash/_baseIntersection.js
new file mode 100644
index 0000000..c1d250c
--- /dev/null
+++ b/node_modules/lodash/_baseIntersection.js
@@ -0,0 +1,74 @@
+var SetCache = require('./_SetCache'),
+ arrayIncludes = require('./_arrayIncludes'),
+ arrayIncludesWith = require('./_arrayIncludesWith'),
+ arrayMap = require('./_arrayMap'),
+ baseUnary = require('./_baseUnary'),
+ cacheHas = require('./_cacheHas');
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeMin = Math.min;
+
+/**
+ * The base implementation of methods like `_.intersection`, without support
+ * for iteratee shorthands, that accepts an array of arrays to inspect.
+ *
+ * @private
+ * @param {Array} arrays The arrays to inspect.
+ * @param {Function} [iteratee] The iteratee invoked per element.
+ * @param {Function} [comparator] The comparator invoked per element.
+ * @returns {Array} Returns the new array of shared values.
+ */
+function baseIntersection(arrays, iteratee, comparator) {
+ var includes = comparator ? arrayIncludesWith : arrayIncludes,
+ length = arrays[0].length,
+ othLength = arrays.length,
+ othIndex = othLength,
+ caches = Array(othLength),
+ maxLength = Infinity,
+ result = [];
+
+ while (othIndex--) {
+ var array = arrays[othIndex];
+ if (othIndex && iteratee) {
+ array = arrayMap(array, baseUnary(iteratee));
+ }
+ maxLength = nativeMin(array.length, maxLength);
+ caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
+ ? new SetCache(othIndex && array)
+ : undefined;
+ }
+ array = arrays[0];
+
+ var index = -1,
+ seen = caches[0];
+
+ outer:
+ while (++index < length && result.length < maxLength) {
+ var value = array[index],
+ computed = iteratee ? iteratee(value) : value;
+
+ value = (comparator || value !== 0) ? value : 0;
+ if (!(seen
+ ? cacheHas(seen, computed)
+ : includes(result, computed, comparator)
+ )) {
+ othIndex = othLength;
+ while (--othIndex) {
+ var cache = caches[othIndex];
+ if (!(cache
+ ? cacheHas(cache, computed)
+ : includes(arrays[othIndex], computed, comparator))
+ ) {
+ continue outer;
+ }
+ }
+ if (seen) {
+ seen.push(computed);
+ }
+ result.push(value);
+ }
+ }
+ return result;
+}
+
+module.exports = baseIntersection;
diff --git a/node_modules/lodash/_baseInverter.js b/node_modules/lodash/_baseInverter.js
new file mode 100644
index 0000000..fbc337f
--- /dev/null
+++ b/node_modules/lodash/_baseInverter.js
@@ -0,0 +1,21 @@
+var baseForOwn = require('./_baseForOwn');
+
+/**
+ * The base implementation of `_.invert` and `_.invertBy` which inverts
+ * `object` with values transformed by `iteratee` and set by `setter`.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} setter The function to set `accumulator` values.
+ * @param {Function} iteratee The iteratee to transform values.
+ * @param {Object} accumulator The initial inverted object.
+ * @returns {Function} Returns `accumulator`.
+ */
+function baseInverter(object, setter, iteratee, accumulator) {
+ baseForOwn(object, function(value, key, object) {
+ setter(accumulator, iteratee(value), key, object);
+ });
+ return accumulator;
+}
+
+module.exports = baseInverter;
diff --git a/node_modules/lodash/_baseInvoke.js b/node_modules/lodash/_baseInvoke.js
new file mode 100644
index 0000000..49bcf3c
--- /dev/null
+++ b/node_modules/lodash/_baseInvoke.js
@@ -0,0 +1,24 @@
+var apply = require('./_apply'),
+ castPath = require('./_castPath'),
+ last = require('./last'),
+ parent = require('./_parent'),
+ toKey = require('./_toKey');
+
+/**
+ * The base implementation of `_.invoke` without support for individual
+ * method arguments.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path of the method to invoke.
+ * @param {Array} args The arguments to invoke the method with.
+ * @returns {*} Returns the result of the invoked method.
+ */
+function baseInvoke(object, path, args) {
+ path = castPath(path, object);
+ object = parent(object, path);
+ var func = object == null ? object : object[toKey(last(path))];
+ return func == null ? undefined : apply(func, object, args);
+}
+
+module.exports = baseInvoke;
diff --git a/node_modules/lodash/_baseIsArguments.js b/node_modules/lodash/_baseIsArguments.js
new file mode 100644
index 0000000..b3562cc
--- /dev/null
+++ b/node_modules/lodash/_baseIsArguments.js
@@ -0,0 +1,18 @@
+var baseGetTag = require('./_baseGetTag'),
+ isObjectLike = require('./isObjectLike');
+
+/** `Object#toString` result references. */
+var argsTag = '[object Arguments]';
+
+/**
+ * The base implementation of `_.isArguments`.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,
+ */
+function baseIsArguments(value) {
+ return isObjectLike(value) && baseGetTag(value) == argsTag;
+}
+
+module.exports = baseIsArguments;
diff --git a/node_modules/lodash/_baseIsArrayBuffer.js b/node_modules/lodash/_baseIsArrayBuffer.js
new file mode 100644
index 0000000..a2c4f30
--- /dev/null
+++ b/node_modules/lodash/_baseIsArrayBuffer.js
@@ -0,0 +1,17 @@
+var baseGetTag = require('./_baseGetTag'),
+ isObjectLike = require('./isObjectLike');
+
+var arrayBufferTag = '[object ArrayBuffer]';
+
+/**
+ * The base implementation of `_.isArrayBuffer` without Node.js optimizations.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
+ */
+function baseIsArrayBuffer(value) {
+ return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;
+}
+
+module.exports = baseIsArrayBuffer;
diff --git a/node_modules/lodash/_baseIsDate.js b/node_modules/lodash/_baseIsDate.js
new file mode 100644
index 0000000..ba67c78
--- /dev/null
+++ b/node_modules/lodash/_baseIsDate.js
@@ -0,0 +1,18 @@
+var baseGetTag = require('./_baseGetTag'),
+ isObjectLike = require('./isObjectLike');
+
+/** `Object#toString` result references. */
+var dateTag = '[object Date]';
+
+/**
+ * The base implementation of `_.isDate` without Node.js optimizations.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
+ */
+function baseIsDate(value) {
+ return isObjectLike(value) && baseGetTag(value) == dateTag;
+}
+
+module.exports = baseIsDate;
diff --git a/node_modules/lodash/_baseIsEqual.js b/node_modules/lodash/_baseIsEqual.js
new file mode 100644
index 0000000..00a68a4
--- /dev/null
+++ b/node_modules/lodash/_baseIsEqual.js
@@ -0,0 +1,28 @@
+var baseIsEqualDeep = require('./_baseIsEqualDeep'),
+ isObjectLike = require('./isObjectLike');
+
+/**
+ * The base implementation of `_.isEqual` which supports partial comparisons
+ * and tracks traversed objects.
+ *
+ * @private
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @param {boolean} bitmask The bitmask flags.
+ * 1 - Unordered comparison
+ * 2 - Partial comparison
+ * @param {Function} [customizer] The function to customize comparisons.
+ * @param {Object} [stack] Tracks traversed `value` and `other` objects.
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+ */
+function baseIsEqual(value, other, bitmask, customizer, stack) {
+ if (value === other) {
+ return true;
+ }
+ if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
+ return value !== value && other !== other;
+ }
+ return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
+}
+
+module.exports = baseIsEqual;
diff --git a/node_modules/lodash/_baseIsEqualDeep.js b/node_modules/lodash/_baseIsEqualDeep.js
new file mode 100644
index 0000000..e3cfd6a
--- /dev/null
+++ b/node_modules/lodash/_baseIsEqualDeep.js
@@ -0,0 +1,83 @@
+var Stack = require('./_Stack'),
+ equalArrays = require('./_equalArrays'),
+ equalByTag = require('./_equalByTag'),
+ equalObjects = require('./_equalObjects'),
+ getTag = require('./_getTag'),
+ isArray = require('./isArray'),
+ isBuffer = require('./isBuffer'),
+ isTypedArray = require('./isTypedArray');
+
+/** Used to compose bitmasks for value comparisons. */
+var COMPARE_PARTIAL_FLAG = 1;
+
+/** `Object#toString` result references. */
+var argsTag = '[object Arguments]',
+ arrayTag = '[object Array]',
+ objectTag = '[object Object]';
+
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/**
+ * A specialized version of `baseIsEqual` for arrays and objects which performs
+ * deep comparisons and tracks traversed objects enabling objects with circular
+ * references to be compared.
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
+ * @param {Function} customizer The function to customize comparisons.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Object} [stack] Tracks traversed `object` and `other` objects.
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ */
+function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
+ var objIsArr = isArray(object),
+ othIsArr = isArray(other),
+ objTag = objIsArr ? arrayTag : getTag(object),
+ othTag = othIsArr ? arrayTag : getTag(other);
+
+ objTag = objTag == argsTag ? objectTag : objTag;
+ othTag = othTag == argsTag ? objectTag : othTag;
+
+ var objIsObj = objTag == objectTag,
+ othIsObj = othTag == objectTag,
+ isSameTag = objTag == othTag;
+
+ if (isSameTag && isBuffer(object)) {
+ if (!isBuffer(other)) {
+ return false;
+ }
+ objIsArr = true;
+ objIsObj = false;
+ }
+ if (isSameTag && !objIsObj) {
+ stack || (stack = new Stack);
+ return (objIsArr || isTypedArray(object))
+ ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
+ : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
+ }
+ if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
+ var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
+ othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
+
+ if (objIsWrapped || othIsWrapped) {
+ var objUnwrapped = objIsWrapped ? object.value() : object,
+ othUnwrapped = othIsWrapped ? other.value() : other;
+
+ stack || (stack = new Stack);
+ return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
+ }
+ }
+ if (!isSameTag) {
+ return false;
+ }
+ stack || (stack = new Stack);
+ return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
+}
+
+module.exports = baseIsEqualDeep;
diff --git a/node_modules/lodash/_baseIsMap.js b/node_modules/lodash/_baseIsMap.js
new file mode 100644
index 0000000..02a4021
--- /dev/null
+++ b/node_modules/lodash/_baseIsMap.js
@@ -0,0 +1,18 @@
+var getTag = require('./_getTag'),
+ isObjectLike = require('./isObjectLike');
+
+/** `Object#toString` result references. */
+var mapTag = '[object Map]';
+
+/**
+ * The base implementation of `_.isMap` without Node.js optimizations.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a map, else `false`.
+ */
+function baseIsMap(value) {
+ return isObjectLike(value) && getTag(value) == mapTag;
+}
+
+module.exports = baseIsMap;
diff --git a/node_modules/lodash/_baseIsMatch.js b/node_modules/lodash/_baseIsMatch.js
new file mode 100644
index 0000000..72494be
--- /dev/null
+++ b/node_modules/lodash/_baseIsMatch.js
@@ -0,0 +1,62 @@
+var Stack = require('./_Stack'),
+ baseIsEqual = require('./_baseIsEqual');
+
+/** Used to compose bitmasks for value comparisons. */
+var COMPARE_PARTIAL_FLAG = 1,
+ COMPARE_UNORDERED_FLAG = 2;
+
+/**
+ * The base implementation of `_.isMatch` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Object} object The object to inspect.
+ * @param {Object} source The object of property values to match.
+ * @param {Array} matchData The property names, values, and compare flags to match.
+ * @param {Function} [customizer] The function to customize comparisons.
+ * @returns {boolean} Returns `true` if `object` is a match, else `false`.
+ */
+function baseIsMatch(object, source, matchData, customizer) {
+ var index = matchData.length,
+ length = index,
+ noCustomizer = !customizer;
+
+ if (object == null) {
+ return !length;
+ }
+ object = Object(object);
+ while (index--) {
+ var data = matchData[index];
+ if ((noCustomizer && data[2])
+ ? data[1] !== object[data[0]]
+ : !(data[0] in object)
+ ) {
+ return false;
+ }
+ }
+ while (++index < length) {
+ data = matchData[index];
+ var key = data[0],
+ objValue = object[key],
+ srcValue = data[1];
+
+ if (noCustomizer && data[2]) {
+ if (objValue === undefined && !(key in object)) {
+ return false;
+ }
+ } else {
+ var stack = new Stack;
+ if (customizer) {
+ var result = customizer(objValue, srcValue, key, object, source, stack);
+ }
+ if (!(result === undefined
+ ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
+ : result
+ )) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+module.exports = baseIsMatch;
diff --git a/node_modules/lodash/_baseIsNaN.js b/node_modules/lodash/_baseIsNaN.js
new file mode 100644
index 0000000..316f1eb
--- /dev/null
+++ b/node_modules/lodash/_baseIsNaN.js
@@ -0,0 +1,12 @@
+/**
+ * The base implementation of `_.isNaN` without support for number objects.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
+ */
+function baseIsNaN(value) {
+ return value !== value;
+}
+
+module.exports = baseIsNaN;
diff --git a/node_modules/lodash/_baseIsNative.js b/node_modules/lodash/_baseIsNative.js
new file mode 100644
index 0000000..8702330
--- /dev/null
+++ b/node_modules/lodash/_baseIsNative.js
@@ -0,0 +1,47 @@
+var isFunction = require('./isFunction'),
+ isMasked = require('./_isMasked'),
+ isObject = require('./isObject'),
+ toSource = require('./_toSource');
+
+/**
+ * Used to match `RegExp`
+ * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
+ */
+var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
+
+/** Used to detect host constructors (Safari). */
+var reIsHostCtor = /^\[object .+?Constructor\]$/;
+
+/** Used for built-in method references. */
+var funcProto = Function.prototype,
+ objectProto = Object.prototype;
+
+/** Used to resolve the decompiled source of functions. */
+var funcToString = funcProto.toString;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/** Used to detect if a method is native. */
+var reIsNative = RegExp('^' +
+ funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
+ .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
+);
+
+/**
+ * The base implementation of `_.isNative` without bad shim checks.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a native function,
+ * else `false`.
+ */
+function baseIsNative(value) {
+ if (!isObject(value) || isMasked(value)) {
+ return false;
+ }
+ var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
+ return pattern.test(toSource(value));
+}
+
+module.exports = baseIsNative;
diff --git a/node_modules/lodash/_baseIsRegExp.js b/node_modules/lodash/_baseIsRegExp.js
new file mode 100644
index 0000000..6cd7c1a
--- /dev/null
+++ b/node_modules/lodash/_baseIsRegExp.js
@@ -0,0 +1,18 @@
+var baseGetTag = require('./_baseGetTag'),
+ isObjectLike = require('./isObjectLike');
+
+/** `Object#toString` result references. */
+var regexpTag = '[object RegExp]';
+
+/**
+ * The base implementation of `_.isRegExp` without Node.js optimizations.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
+ */
+function baseIsRegExp(value) {
+ return isObjectLike(value) && baseGetTag(value) == regexpTag;
+}
+
+module.exports = baseIsRegExp;
diff --git a/node_modules/lodash/_baseIsSet.js b/node_modules/lodash/_baseIsSet.js
new file mode 100644
index 0000000..6dee367
--- /dev/null
+++ b/node_modules/lodash/_baseIsSet.js
@@ -0,0 +1,18 @@
+var getTag = require('./_getTag'),
+ isObjectLike = require('./isObjectLike');
+
+/** `Object#toString` result references. */
+var setTag = '[object Set]';
+
+/**
+ * The base implementation of `_.isSet` without Node.js optimizations.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a set, else `false`.
+ */
+function baseIsSet(value) {
+ return isObjectLike(value) && getTag(value) == setTag;
+}
+
+module.exports = baseIsSet;
diff --git a/node_modules/lodash/_baseIsTypedArray.js b/node_modules/lodash/_baseIsTypedArray.js
new file mode 100644
index 0000000..1edb32f
--- /dev/null
+++ b/node_modules/lodash/_baseIsTypedArray.js
@@ -0,0 +1,60 @@
+var baseGetTag = require('./_baseGetTag'),
+ isLength = require('./isLength'),
+ isObjectLike = require('./isObjectLike');
+
+/** `Object#toString` result references. */
+var argsTag = '[object Arguments]',
+ arrayTag = '[object Array]',
+ boolTag = '[object Boolean]',
+ dateTag = '[object Date]',
+ errorTag = '[object Error]',
+ funcTag = '[object Function]',
+ mapTag = '[object Map]',
+ numberTag = '[object Number]',
+ objectTag = '[object Object]',
+ regexpTag = '[object RegExp]',
+ setTag = '[object Set]',
+ stringTag = '[object String]',
+ weakMapTag = '[object WeakMap]';
+
+var arrayBufferTag = '[object ArrayBuffer]',
+ dataViewTag = '[object DataView]',
+ float32Tag = '[object Float32Array]',
+ float64Tag = '[object Float64Array]',
+ int8Tag = '[object Int8Array]',
+ int16Tag = '[object Int16Array]',
+ int32Tag = '[object Int32Array]',
+ uint8Tag = '[object Uint8Array]',
+ uint8ClampedTag = '[object Uint8ClampedArray]',
+ uint16Tag = '[object Uint16Array]',
+ uint32Tag = '[object Uint32Array]';
+
+/** Used to identify `toStringTag` values of typed arrays. */
+var typedArrayTags = {};
+typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
+typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
+typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
+typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
+typedArrayTags[uint32Tag] = true;
+typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
+typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
+typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
+typedArrayTags[errorTag] = typedArrayTags[funcTag] =
+typedArrayTags[mapTag] = typedArrayTags[numberTag] =
+typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
+typedArrayTags[setTag] = typedArrayTags[stringTag] =
+typedArrayTags[weakMapTag] = false;
+
+/**
+ * The base implementation of `_.isTypedArray` without Node.js optimizations.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
+ */
+function baseIsTypedArray(value) {
+ return isObjectLike(value) &&
+ isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
+}
+
+module.exports = baseIsTypedArray;
diff --git a/node_modules/lodash/_baseIteratee.js b/node_modules/lodash/_baseIteratee.js
new file mode 100644
index 0000000..995c257
--- /dev/null
+++ b/node_modules/lodash/_baseIteratee.js
@@ -0,0 +1,31 @@
+var baseMatches = require('./_baseMatches'),
+ baseMatchesProperty = require('./_baseMatchesProperty'),
+ identity = require('./identity'),
+ isArray = require('./isArray'),
+ property = require('./property');
+
+/**
+ * The base implementation of `_.iteratee`.
+ *
+ * @private
+ * @param {*} [value=_.identity] The value to convert to an iteratee.
+ * @returns {Function} Returns the iteratee.
+ */
+function baseIteratee(value) {
+ // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
+ // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
+ if (typeof value == 'function') {
+ return value;
+ }
+ if (value == null) {
+ return identity;
+ }
+ if (typeof value == 'object') {
+ return isArray(value)
+ ? baseMatchesProperty(value[0], value[1])
+ : baseMatches(value);
+ }
+ return property(value);
+}
+
+module.exports = baseIteratee;
diff --git a/node_modules/lodash/_baseKeys.js b/node_modules/lodash/_baseKeys.js
new file mode 100644
index 0000000..45e9e6f
--- /dev/null
+++ b/node_modules/lodash/_baseKeys.js
@@ -0,0 +1,30 @@
+var isPrototype = require('./_isPrototype'),
+ nativeKeys = require('./_nativeKeys');
+
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/**
+ * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ */
+function baseKeys(object) {
+ if (!isPrototype(object)) {
+ return nativeKeys(object);
+ }
+ var result = [];
+ for (var key in Object(object)) {
+ if (hasOwnProperty.call(object, key) && key != 'constructor') {
+ result.push(key);
+ }
+ }
+ return result;
+}
+
+module.exports = baseKeys;
diff --git a/node_modules/lodash/_baseKeysIn.js b/node_modules/lodash/_baseKeysIn.js
new file mode 100644
index 0000000..ea8a0a1
--- /dev/null
+++ b/node_modules/lodash/_baseKeysIn.js
@@ -0,0 +1,33 @@
+var isObject = require('./isObject'),
+ isPrototype = require('./_isPrototype'),
+ nativeKeysIn = require('./_nativeKeysIn');
+
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/**
+ * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ */
+function baseKeysIn(object) {
+ if (!isObject(object)) {
+ return nativeKeysIn(object);
+ }
+ var isProto = isPrototype(object),
+ result = [];
+
+ for (var key in object) {
+ if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
+ result.push(key);
+ }
+ }
+ return result;
+}
+
+module.exports = baseKeysIn;
diff --git a/node_modules/lodash/_baseLodash.js b/node_modules/lodash/_baseLodash.js
new file mode 100644
index 0000000..f76c790
--- /dev/null
+++ b/node_modules/lodash/_baseLodash.js
@@ -0,0 +1,10 @@
+/**
+ * The function whose prototype chain sequence wrappers inherit from.
+ *
+ * @private
+ */
+function baseLodash() {
+ // No operation performed.
+}
+
+module.exports = baseLodash;
diff --git a/node_modules/lodash/_baseLt.js b/node_modules/lodash/_baseLt.js
new file mode 100644
index 0000000..8674d29
--- /dev/null
+++ b/node_modules/lodash/_baseLt.js
@@ -0,0 +1,14 @@
+/**
+ * The base implementation of `_.lt` which doesn't coerce arguments.
+ *
+ * @private
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {boolean} Returns `true` if `value` is less than `other`,
+ * else `false`.
+ */
+function baseLt(value, other) {
+ return value < other;
+}
+
+module.exports = baseLt;
diff --git a/node_modules/lodash/_baseMap.js b/node_modules/lodash/_baseMap.js
new file mode 100644
index 0000000..0bf5cea
--- /dev/null
+++ b/node_modules/lodash/_baseMap.js
@@ -0,0 +1,22 @@
+var baseEach = require('./_baseEach'),
+ isArrayLike = require('./isArrayLike');
+
+/**
+ * The base implementation of `_.map` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns the new mapped array.
+ */
+function baseMap(collection, iteratee) {
+ var index = -1,
+ result = isArrayLike(collection) ? Array(collection.length) : [];
+
+ baseEach(collection, function(value, key, collection) {
+ result[++index] = iteratee(value, key, collection);
+ });
+ return result;
+}
+
+module.exports = baseMap;
diff --git a/node_modules/lodash/_baseMatches.js b/node_modules/lodash/_baseMatches.js
new file mode 100644
index 0000000..e56582a
--- /dev/null
+++ b/node_modules/lodash/_baseMatches.js
@@ -0,0 +1,22 @@
+var baseIsMatch = require('./_baseIsMatch'),
+ getMatchData = require('./_getMatchData'),
+ matchesStrictComparable = require('./_matchesStrictComparable');
+
+/**
+ * The base implementation of `_.matches` which doesn't clone `source`.
+ *
+ * @private
+ * @param {Object} source The object of property values to match.
+ * @returns {Function} Returns the new spec function.
+ */
+function baseMatches(source) {
+ var matchData = getMatchData(source);
+ if (matchData.length == 1 && matchData[0][2]) {
+ return matchesStrictComparable(matchData[0][0], matchData[0][1]);
+ }
+ return function(object) {
+ return object === source || baseIsMatch(object, source, matchData);
+ };
+}
+
+module.exports = baseMatches;
diff --git a/node_modules/lodash/_baseMatchesProperty.js b/node_modules/lodash/_baseMatchesProperty.js
new file mode 100644
index 0000000..24afd89
--- /dev/null
+++ b/node_modules/lodash/_baseMatchesProperty.js
@@ -0,0 +1,33 @@
+var baseIsEqual = require('./_baseIsEqual'),
+ get = require('./get'),
+ hasIn = require('./hasIn'),
+ isKey = require('./_isKey'),
+ isStrictComparable = require('./_isStrictComparable'),
+ matchesStrictComparable = require('./_matchesStrictComparable'),
+ toKey = require('./_toKey');
+
+/** Used to compose bitmasks for value comparisons. */
+var COMPARE_PARTIAL_FLAG = 1,
+ COMPARE_UNORDERED_FLAG = 2;
+
+/**
+ * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
+ *
+ * @private
+ * @param {string} path The path of the property to get.
+ * @param {*} srcValue The value to match.
+ * @returns {Function} Returns the new spec function.
+ */
+function baseMatchesProperty(path, srcValue) {
+ if (isKey(path) && isStrictComparable(srcValue)) {
+ return matchesStrictComparable(toKey(path), srcValue);
+ }
+ return function(object) {
+ var objValue = get(object, path);
+ return (objValue === undefined && objValue === srcValue)
+ ? hasIn(object, path)
+ : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
+ };
+}
+
+module.exports = baseMatchesProperty;
diff --git a/node_modules/lodash/_baseMean.js b/node_modules/lodash/_baseMean.js
new file mode 100644
index 0000000..fa9e00a
--- /dev/null
+++ b/node_modules/lodash/_baseMean.js
@@ -0,0 +1,20 @@
+var baseSum = require('./_baseSum');
+
+/** Used as references for various `Number` constants. */
+var NAN = 0 / 0;
+
+/**
+ * The base implementation of `_.mean` and `_.meanBy` without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {number} Returns the mean.
+ */
+function baseMean(array, iteratee) {
+ var length = array == null ? 0 : array.length;
+ return length ? (baseSum(array, iteratee) / length) : NAN;
+}
+
+module.exports = baseMean;
diff --git a/node_modules/lodash/_baseMerge.js b/node_modules/lodash/_baseMerge.js
new file mode 100644
index 0000000..c98b5eb
--- /dev/null
+++ b/node_modules/lodash/_baseMerge.js
@@ -0,0 +1,42 @@
+var Stack = require('./_Stack'),
+ assignMergeValue = require('./_assignMergeValue'),
+ baseFor = require('./_baseFor'),
+ baseMergeDeep = require('./_baseMergeDeep'),
+ isObject = require('./isObject'),
+ keysIn = require('./keysIn'),
+ safeGet = require('./_safeGet');
+
+/**
+ * The base implementation of `_.merge` without support for multiple sources.
+ *
+ * @private
+ * @param {Object} object The destination object.
+ * @param {Object} source The source object.
+ * @param {number} srcIndex The index of `source`.
+ * @param {Function} [customizer] The function to customize merged values.
+ * @param {Object} [stack] Tracks traversed source values and their merged
+ * counterparts.
+ */
+function baseMerge(object, source, srcIndex, customizer, stack) {
+ if (object === source) {
+ return;
+ }
+ baseFor(source, function(srcValue, key) {
+ stack || (stack = new Stack);
+ if (isObject(srcValue)) {
+ baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
+ }
+ else {
+ var newValue = customizer
+ ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
+ : undefined;
+
+ if (newValue === undefined) {
+ newValue = srcValue;
+ }
+ assignMergeValue(object, key, newValue);
+ }
+ }, keysIn);
+}
+
+module.exports = baseMerge;
diff --git a/node_modules/lodash/_baseMergeDeep.js b/node_modules/lodash/_baseMergeDeep.js
new file mode 100644
index 0000000..4679e8d
--- /dev/null
+++ b/node_modules/lodash/_baseMergeDeep.js
@@ -0,0 +1,94 @@
+var assignMergeValue = require('./_assignMergeValue'),
+ cloneBuffer = require('./_cloneBuffer'),
+ cloneTypedArray = require('./_cloneTypedArray'),
+ copyArray = require('./_copyArray'),
+ initCloneObject = require('./_initCloneObject'),
+ isArguments = require('./isArguments'),
+ isArray = require('./isArray'),
+ isArrayLikeObject = require('./isArrayLikeObject'),
+ isBuffer = require('./isBuffer'),
+ isFunction = require('./isFunction'),
+ isObject = require('./isObject'),
+ isPlainObject = require('./isPlainObject'),
+ isTypedArray = require('./isTypedArray'),
+ safeGet = require('./_safeGet'),
+ toPlainObject = require('./toPlainObject');
+
+/**
+ * A specialized version of `baseMerge` for arrays and objects which performs
+ * deep merges and tracks traversed objects enabling objects with circular
+ * references to be merged.
+ *
+ * @private
+ * @param {Object} object The destination object.
+ * @param {Object} source The source object.
+ * @param {string} key The key of the value to merge.
+ * @param {number} srcIndex The index of `source`.
+ * @param {Function} mergeFunc The function to merge values.
+ * @param {Function} [customizer] The function to customize assigned values.
+ * @param {Object} [stack] Tracks traversed source values and their merged
+ * counterparts.
+ */
+function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
+ var objValue = safeGet(object, key),
+ srcValue = safeGet(source, key),
+ stacked = stack.get(srcValue);
+
+ if (stacked) {
+ assignMergeValue(object, key, stacked);
+ return;
+ }
+ var newValue = customizer
+ ? customizer(objValue, srcValue, (key + ''), object, source, stack)
+ : undefined;
+
+ var isCommon = newValue === undefined;
+
+ if (isCommon) {
+ var isArr = isArray(srcValue),
+ isBuff = !isArr && isBuffer(srcValue),
+ isTyped = !isArr && !isBuff && isTypedArray(srcValue);
+
+ newValue = srcValue;
+ if (isArr || isBuff || isTyped) {
+ if (isArray(objValue)) {
+ newValue = objValue;
+ }
+ else if (isArrayLikeObject(objValue)) {
+ newValue = copyArray(objValue);
+ }
+ else if (isBuff) {
+ isCommon = false;
+ newValue = cloneBuffer(srcValue, true);
+ }
+ else if (isTyped) {
+ isCommon = false;
+ newValue = cloneTypedArray(srcValue, true);
+ }
+ else {
+ newValue = [];
+ }
+ }
+ else if (isPlainObject(srcValue) || isArguments(srcValue)) {
+ newValue = objValue;
+ if (isArguments(objValue)) {
+ newValue = toPlainObject(objValue);
+ }
+ else if (!isObject(objValue) || isFunction(objValue)) {
+ newValue = initCloneObject(srcValue);
+ }
+ }
+ else {
+ isCommon = false;
+ }
+ }
+ if (isCommon) {
+ // Recursively merge objects and arrays (susceptible to call stack limits).
+ stack.set(srcValue, newValue);
+ mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
+ stack['delete'](srcValue);
+ }
+ assignMergeValue(object, key, newValue);
+}
+
+module.exports = baseMergeDeep;
diff --git a/node_modules/lodash/_baseNth.js b/node_modules/lodash/_baseNth.js
new file mode 100644
index 0000000..0403c2a
--- /dev/null
+++ b/node_modules/lodash/_baseNth.js
@@ -0,0 +1,20 @@
+var isIndex = require('./_isIndex');
+
+/**
+ * The base implementation of `_.nth` which doesn't coerce arguments.
+ *
+ * @private
+ * @param {Array} array The array to query.
+ * @param {number} n The index of the element to return.
+ * @returns {*} Returns the nth element of `array`.
+ */
+function baseNth(array, n) {
+ var length = array.length;
+ if (!length) {
+ return;
+ }
+ n += n < 0 ? length : 0;
+ return isIndex(n, length) ? array[n] : undefined;
+}
+
+module.exports = baseNth;
diff --git a/node_modules/lodash/_baseOrderBy.js b/node_modules/lodash/_baseOrderBy.js
new file mode 100644
index 0000000..775a017
--- /dev/null
+++ b/node_modules/lodash/_baseOrderBy.js
@@ -0,0 +1,49 @@
+var arrayMap = require('./_arrayMap'),
+ baseGet = require('./_baseGet'),
+ baseIteratee = require('./_baseIteratee'),
+ baseMap = require('./_baseMap'),
+ baseSortBy = require('./_baseSortBy'),
+ baseUnary = require('./_baseUnary'),
+ compareMultiple = require('./_compareMultiple'),
+ identity = require('./identity'),
+ isArray = require('./isArray');
+
+/**
+ * The base implementation of `_.orderBy` without param guards.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
+ * @param {string[]} orders The sort orders of `iteratees`.
+ * @returns {Array} Returns the new sorted array.
+ */
+function baseOrderBy(collection, iteratees, orders) {
+ if (iteratees.length) {
+ iteratees = arrayMap(iteratees, function(iteratee) {
+ if (isArray(iteratee)) {
+ return function(value) {
+ return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
+ }
+ }
+ return iteratee;
+ });
+ } else {
+ iteratees = [identity];
+ }
+
+ var index = -1;
+ iteratees = arrayMap(iteratees, baseUnary(baseIteratee));
+
+ var result = baseMap(collection, function(value, key, collection) {
+ var criteria = arrayMap(iteratees, function(iteratee) {
+ return iteratee(value);
+ });
+ return { 'criteria': criteria, 'index': ++index, 'value': value };
+ });
+
+ return baseSortBy(result, function(object, other) {
+ return compareMultiple(object, other, orders);
+ });
+}
+
+module.exports = baseOrderBy;
diff --git a/node_modules/lodash/_basePick.js b/node_modules/lodash/_basePick.js
new file mode 100644
index 0000000..09b458a
--- /dev/null
+++ b/node_modules/lodash/_basePick.js
@@ -0,0 +1,19 @@
+var basePickBy = require('./_basePickBy'),
+ hasIn = require('./hasIn');
+
+/**
+ * The base implementation of `_.pick` without support for individual
+ * property identifiers.
+ *
+ * @private
+ * @param {Object} object The source object.
+ * @param {string[]} paths The property paths to pick.
+ * @returns {Object} Returns the new object.
+ */
+function basePick(object, paths) {
+ return basePickBy(object, paths, function(value, path) {
+ return hasIn(object, path);
+ });
+}
+
+module.exports = basePick;
diff --git a/node_modules/lodash/_basePickBy.js b/node_modules/lodash/_basePickBy.js
new file mode 100644
index 0000000..85be68c
--- /dev/null
+++ b/node_modules/lodash/_basePickBy.js
@@ -0,0 +1,30 @@
+var baseGet = require('./_baseGet'),
+ baseSet = require('./_baseSet'),
+ castPath = require('./_castPath');
+
+/**
+ * The base implementation of `_.pickBy` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Object} object The source object.
+ * @param {string[]} paths The property paths to pick.
+ * @param {Function} predicate The function invoked per property.
+ * @returns {Object} Returns the new object.
+ */
+function basePickBy(object, paths, predicate) {
+ var index = -1,
+ length = paths.length,
+ result = {};
+
+ while (++index < length) {
+ var path = paths[index],
+ value = baseGet(object, path);
+
+ if (predicate(value, path)) {
+ baseSet(result, castPath(path, object), value);
+ }
+ }
+ return result;
+}
+
+module.exports = basePickBy;
diff --git a/node_modules/lodash/_baseProperty.js b/node_modules/lodash/_baseProperty.js
new file mode 100644
index 0000000..496281e
--- /dev/null
+++ b/node_modules/lodash/_baseProperty.js
@@ -0,0 +1,14 @@
+/**
+ * The base implementation of `_.property` without support for deep paths.
+ *
+ * @private
+ * @param {string} key The key of the property to get.
+ * @returns {Function} Returns the new accessor function.
+ */
+function baseProperty(key) {
+ return function(object) {
+ return object == null ? undefined : object[key];
+ };
+}
+
+module.exports = baseProperty;
diff --git a/node_modules/lodash/_basePropertyDeep.js b/node_modules/lodash/_basePropertyDeep.js
new file mode 100644
index 0000000..1e5aae5
--- /dev/null
+++ b/node_modules/lodash/_basePropertyDeep.js
@@ -0,0 +1,16 @@
+var baseGet = require('./_baseGet');
+
+/**
+ * A specialized version of `baseProperty` which supports deep paths.
+ *
+ * @private
+ * @param {Array|string} path The path of the property to get.
+ * @returns {Function} Returns the new accessor function.
+ */
+function basePropertyDeep(path) {
+ return function(object) {
+ return baseGet(object, path);
+ };
+}
+
+module.exports = basePropertyDeep;
diff --git a/node_modules/lodash/_basePropertyOf.js b/node_modules/lodash/_basePropertyOf.js
new file mode 100644
index 0000000..4617399
--- /dev/null
+++ b/node_modules/lodash/_basePropertyOf.js
@@ -0,0 +1,14 @@
+/**
+ * The base implementation of `_.propertyOf` without support for deep paths.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Function} Returns the new accessor function.
+ */
+function basePropertyOf(object) {
+ return function(key) {
+ return object == null ? undefined : object[key];
+ };
+}
+
+module.exports = basePropertyOf;
diff --git a/node_modules/lodash/_basePullAll.js b/node_modules/lodash/_basePullAll.js
new file mode 100644
index 0000000..305720e
--- /dev/null
+++ b/node_modules/lodash/_basePullAll.js
@@ -0,0 +1,51 @@
+var arrayMap = require('./_arrayMap'),
+ baseIndexOf = require('./_baseIndexOf'),
+ baseIndexOfWith = require('./_baseIndexOfWith'),
+ baseUnary = require('./_baseUnary'),
+ copyArray = require('./_copyArray');
+
+/** Used for built-in method references. */
+var arrayProto = Array.prototype;
+
+/** Built-in value references. */
+var splice = arrayProto.splice;
+
+/**
+ * The base implementation of `_.pullAllBy` without support for iteratee
+ * shorthands.
+ *
+ * @private
+ * @param {Array} array The array to modify.
+ * @param {Array} values The values to remove.
+ * @param {Function} [iteratee] The iteratee invoked per element.
+ * @param {Function} [comparator] The comparator invoked per element.
+ * @returns {Array} Returns `array`.
+ */
+function basePullAll(array, values, iteratee, comparator) {
+ var indexOf = comparator ? baseIndexOfWith : baseIndexOf,
+ index = -1,
+ length = values.length,
+ seen = array;
+
+ if (array === values) {
+ values = copyArray(values);
+ }
+ if (iteratee) {
+ seen = arrayMap(array, baseUnary(iteratee));
+ }
+ while (++index < length) {
+ var fromIndex = 0,
+ value = values[index],
+ computed = iteratee ? iteratee(value) : value;
+
+ while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
+ if (seen !== array) {
+ splice.call(seen, fromIndex, 1);
+ }
+ splice.call(array, fromIndex, 1);
+ }
+ }
+ return array;
+}
+
+module.exports = basePullAll;
diff --git a/node_modules/lodash/_basePullAt.js b/node_modules/lodash/_basePullAt.js
new file mode 100644
index 0000000..c3e9e71
--- /dev/null
+++ b/node_modules/lodash/_basePullAt.js
@@ -0,0 +1,37 @@
+var baseUnset = require('./_baseUnset'),
+ isIndex = require('./_isIndex');
+
+/** Used for built-in method references. */
+var arrayProto = Array.prototype;
+
+/** Built-in value references. */
+var splice = arrayProto.splice;
+
+/**
+ * The base implementation of `_.pullAt` without support for individual
+ * indexes or capturing the removed elements.
+ *
+ * @private
+ * @param {Array} array The array to modify.
+ * @param {number[]} indexes The indexes of elements to remove.
+ * @returns {Array} Returns `array`.
+ */
+function basePullAt(array, indexes) {
+ var length = array ? indexes.length : 0,
+ lastIndex = length - 1;
+
+ while (length--) {
+ var index = indexes[length];
+ if (length == lastIndex || index !== previous) {
+ var previous = index;
+ if (isIndex(index)) {
+ splice.call(array, index, 1);
+ } else {
+ baseUnset(array, index);
+ }
+ }
+ }
+ return array;
+}
+
+module.exports = basePullAt;
diff --git a/node_modules/lodash/_baseRandom.js b/node_modules/lodash/_baseRandom.js
new file mode 100644
index 0000000..94f76a7
--- /dev/null
+++ b/node_modules/lodash/_baseRandom.js
@@ -0,0 +1,18 @@
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeFloor = Math.floor,
+ nativeRandom = Math.random;
+
+/**
+ * The base implementation of `_.random` without support for returning
+ * floating-point numbers.
+ *
+ * @private
+ * @param {number} lower The lower bound.
+ * @param {number} upper The upper bound.
+ * @returns {number} Returns the random number.
+ */
+function baseRandom(lower, upper) {
+ return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
+}
+
+module.exports = baseRandom;
diff --git a/node_modules/lodash/_baseRange.js b/node_modules/lodash/_baseRange.js
new file mode 100644
index 0000000..0fb8e41
--- /dev/null
+++ b/node_modules/lodash/_baseRange.js
@@ -0,0 +1,28 @@
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeCeil = Math.ceil,
+ nativeMax = Math.max;
+
+/**
+ * The base implementation of `_.range` and `_.rangeRight` which doesn't
+ * coerce arguments.
+ *
+ * @private
+ * @param {number} start The start of the range.
+ * @param {number} end The end of the range.
+ * @param {number} step The value to increment or decrement by.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Array} Returns the range of numbers.
+ */
+function baseRange(start, end, step, fromRight) {
+ var index = -1,
+ length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
+ result = Array(length);
+
+ while (length--) {
+ result[fromRight ? length : ++index] = start;
+ start += step;
+ }
+ return result;
+}
+
+module.exports = baseRange;
diff --git a/node_modules/lodash/_baseReduce.js b/node_modules/lodash/_baseReduce.js
new file mode 100644
index 0000000..5a1f8b5
--- /dev/null
+++ b/node_modules/lodash/_baseReduce.js
@@ -0,0 +1,23 @@
+/**
+ * The base implementation of `_.reduce` and `_.reduceRight`, without support
+ * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {*} accumulator The initial value.
+ * @param {boolean} initAccum Specify using the first or last element of
+ * `collection` as the initial value.
+ * @param {Function} eachFunc The function to iterate over `collection`.
+ * @returns {*} Returns the accumulated value.
+ */
+function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
+ eachFunc(collection, function(value, index, collection) {
+ accumulator = initAccum
+ ? (initAccum = false, value)
+ : iteratee(accumulator, value, index, collection);
+ });
+ return accumulator;
+}
+
+module.exports = baseReduce;
diff --git a/node_modules/lodash/_baseRepeat.js b/node_modules/lodash/_baseRepeat.js
new file mode 100644
index 0000000..ee44c31
--- /dev/null
+++ b/node_modules/lodash/_baseRepeat.js
@@ -0,0 +1,35 @@
+/** Used as references for various `Number` constants. */
+var MAX_SAFE_INTEGER = 9007199254740991;
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeFloor = Math.floor;
+
+/**
+ * The base implementation of `_.repeat` which doesn't coerce arguments.
+ *
+ * @private
+ * @param {string} string The string to repeat.
+ * @param {number} n The number of times to repeat the string.
+ * @returns {string} Returns the repeated string.
+ */
+function baseRepeat(string, n) {
+ var result = '';
+ if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
+ return result;
+ }
+ // Leverage the exponentiation by squaring algorithm for a faster repeat.
+ // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
+ do {
+ if (n % 2) {
+ result += string;
+ }
+ n = nativeFloor(n / 2);
+ if (n) {
+ string += string;
+ }
+ } while (n);
+
+ return result;
+}
+
+module.exports = baseRepeat;
diff --git a/node_modules/lodash/_baseRest.js b/node_modules/lodash/_baseRest.js
new file mode 100644
index 0000000..d0dc4bd
--- /dev/null
+++ b/node_modules/lodash/_baseRest.js
@@ -0,0 +1,17 @@
+var identity = require('./identity'),
+ overRest = require('./_overRest'),
+ setToString = require('./_setToString');
+
+/**
+ * The base implementation of `_.rest` which doesn't validate or coerce arguments.
+ *
+ * @private
+ * @param {Function} func The function to apply a rest parameter to.
+ * @param {number} [start=func.length-1] The start position of the rest parameter.
+ * @returns {Function} Returns the new function.
+ */
+function baseRest(func, start) {
+ return setToString(overRest(func, start, identity), func + '');
+}
+
+module.exports = baseRest;
diff --git a/node_modules/lodash/_baseSample.js b/node_modules/lodash/_baseSample.js
new file mode 100644
index 0000000..58582b9
--- /dev/null
+++ b/node_modules/lodash/_baseSample.js
@@ -0,0 +1,15 @@
+var arraySample = require('./_arraySample'),
+ values = require('./values');
+
+/**
+ * The base implementation of `_.sample`.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to sample.
+ * @returns {*} Returns the random element.
+ */
+function baseSample(collection) {
+ return arraySample(values(collection));
+}
+
+module.exports = baseSample;
diff --git a/node_modules/lodash/_baseSampleSize.js b/node_modules/lodash/_baseSampleSize.js
new file mode 100644
index 0000000..5c90ec5
--- /dev/null
+++ b/node_modules/lodash/_baseSampleSize.js
@@ -0,0 +1,18 @@
+var baseClamp = require('./_baseClamp'),
+ shuffleSelf = require('./_shuffleSelf'),
+ values = require('./values');
+
+/**
+ * The base implementation of `_.sampleSize` without param guards.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to sample.
+ * @param {number} n The number of elements to sample.
+ * @returns {Array} Returns the random elements.
+ */
+function baseSampleSize(collection, n) {
+ var array = values(collection);
+ return shuffleSelf(array, baseClamp(n, 0, array.length));
+}
+
+module.exports = baseSampleSize;
diff --git a/node_modules/lodash/_baseSet.js b/node_modules/lodash/_baseSet.js
new file mode 100644
index 0000000..99f4fbf
--- /dev/null
+++ b/node_modules/lodash/_baseSet.js
@@ -0,0 +1,51 @@
+var assignValue = require('./_assignValue'),
+ castPath = require('./_castPath'),
+ isIndex = require('./_isIndex'),
+ isObject = require('./isObject'),
+ toKey = require('./_toKey');
+
+/**
+ * The base implementation of `_.set`.
+ *
+ * @private
+ * @param {Object} object The object to modify.
+ * @param {Array|string} path The path of the property to set.
+ * @param {*} value The value to set.
+ * @param {Function} [customizer] The function to customize path creation.
+ * @returns {Object} Returns `object`.
+ */
+function baseSet(object, path, value, customizer) {
+ if (!isObject(object)) {
+ return object;
+ }
+ path = castPath(path, object);
+
+ var index = -1,
+ length = path.length,
+ lastIndex = length - 1,
+ nested = object;
+
+ while (nested != null && ++index < length) {
+ var key = toKey(path[index]),
+ newValue = value;
+
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
+ return object;
+ }
+
+ if (index != lastIndex) {
+ var objValue = nested[key];
+ newValue = customizer ? customizer(objValue, key, nested) : undefined;
+ if (newValue === undefined) {
+ newValue = isObject(objValue)
+ ? objValue
+ : (isIndex(path[index + 1]) ? [] : {});
+ }
+ }
+ assignValue(nested, key, newValue);
+ nested = nested[key];
+ }
+ return object;
+}
+
+module.exports = baseSet;
diff --git a/node_modules/lodash/_baseSetData.js b/node_modules/lodash/_baseSetData.js
new file mode 100644
index 0000000..c409947
--- /dev/null
+++ b/node_modules/lodash/_baseSetData.js
@@ -0,0 +1,17 @@
+var identity = require('./identity'),
+ metaMap = require('./_metaMap');
+
+/**
+ * The base implementation of `setData` without support for hot loop shorting.
+ *
+ * @private
+ * @param {Function} func The function to associate metadata with.
+ * @param {*} data The metadata.
+ * @returns {Function} Returns `func`.
+ */
+var baseSetData = !metaMap ? identity : function(func, data) {
+ metaMap.set(func, data);
+ return func;
+};
+
+module.exports = baseSetData;
diff --git a/node_modules/lodash/_baseSetToString.js b/node_modules/lodash/_baseSetToString.js
new file mode 100644
index 0000000..89eaca3
--- /dev/null
+++ b/node_modules/lodash/_baseSetToString.js
@@ -0,0 +1,22 @@
+var constant = require('./constant'),
+ defineProperty = require('./_defineProperty'),
+ identity = require('./identity');
+
+/**
+ * The base implementation of `setToString` without support for hot loop shorting.
+ *
+ * @private
+ * @param {Function} func The function to modify.
+ * @param {Function} string The `toString` result.
+ * @returns {Function} Returns `func`.
+ */
+var baseSetToString = !defineProperty ? identity : function(func, string) {
+ return defineProperty(func, 'toString', {
+ 'configurable': true,
+ 'enumerable': false,
+ 'value': constant(string),
+ 'writable': true
+ });
+};
+
+module.exports = baseSetToString;
diff --git a/node_modules/lodash/_baseShuffle.js b/node_modules/lodash/_baseShuffle.js
new file mode 100644
index 0000000..023077a
--- /dev/null
+++ b/node_modules/lodash/_baseShuffle.js
@@ -0,0 +1,15 @@
+var shuffleSelf = require('./_shuffleSelf'),
+ values = require('./values');
+
+/**
+ * The base implementation of `_.shuffle`.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to shuffle.
+ * @returns {Array} Returns the new shuffled array.
+ */
+function baseShuffle(collection) {
+ return shuffleSelf(values(collection));
+}
+
+module.exports = baseShuffle;
diff --git a/node_modules/lodash/_baseSlice.js b/node_modules/lodash/_baseSlice.js
new file mode 100644
index 0000000..786f6c9
--- /dev/null
+++ b/node_modules/lodash/_baseSlice.js
@@ -0,0 +1,31 @@
+/**
+ * The base implementation of `_.slice` without an iteratee call guard.
+ *
+ * @private
+ * @param {Array} array The array to slice.
+ * @param {number} [start=0] The start position.
+ * @param {number} [end=array.length] The end position.
+ * @returns {Array} Returns the slice of `array`.
+ */
+function baseSlice(array, start, end) {
+ var index = -1,
+ length = array.length;
+
+ if (start < 0) {
+ start = -start > length ? 0 : (length + start);
+ }
+ end = end > length ? length : end;
+ if (end < 0) {
+ end += length;
+ }
+ length = start > end ? 0 : ((end - start) >>> 0);
+ start >>>= 0;
+
+ var result = Array(length);
+ while (++index < length) {
+ result[index] = array[index + start];
+ }
+ return result;
+}
+
+module.exports = baseSlice;
diff --git a/node_modules/lodash/_baseSome.js b/node_modules/lodash/_baseSome.js
new file mode 100644
index 0000000..58f3f44
--- /dev/null
+++ b/node_modules/lodash/_baseSome.js
@@ -0,0 +1,22 @@
+var baseEach = require('./_baseEach');
+
+/**
+ * The base implementation of `_.some` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {boolean} Returns `true` if any element passes the predicate check,
+ * else `false`.
+ */
+function baseSome(collection, predicate) {
+ var result;
+
+ baseEach(collection, function(value, index, collection) {
+ result = predicate(value, index, collection);
+ return !result;
+ });
+ return !!result;
+}
+
+module.exports = baseSome;
diff --git a/node_modules/lodash/_baseSortBy.js b/node_modules/lodash/_baseSortBy.js
new file mode 100644
index 0000000..a25c92e
--- /dev/null
+++ b/node_modules/lodash/_baseSortBy.js
@@ -0,0 +1,21 @@
+/**
+ * The base implementation of `_.sortBy` which uses `comparer` to define the
+ * sort order of `array` and replaces criteria objects with their corresponding
+ * values.
+ *
+ * @private
+ * @param {Array} array The array to sort.
+ * @param {Function} comparer The function to define sort order.
+ * @returns {Array} Returns `array`.
+ */
+function baseSortBy(array, comparer) {
+ var length = array.length;
+
+ array.sort(comparer);
+ while (length--) {
+ array[length] = array[length].value;
+ }
+ return array;
+}
+
+module.exports = baseSortBy;
diff --git a/node_modules/lodash/_baseSortedIndex.js b/node_modules/lodash/_baseSortedIndex.js
new file mode 100644
index 0000000..638c366
--- /dev/null
+++ b/node_modules/lodash/_baseSortedIndex.js
@@ -0,0 +1,42 @@
+var baseSortedIndexBy = require('./_baseSortedIndexBy'),
+ identity = require('./identity'),
+ isSymbol = require('./isSymbol');
+
+/** Used as references for the maximum length and index of an array. */
+var MAX_ARRAY_LENGTH = 4294967295,
+ HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
+
+/**
+ * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
+ * performs a binary search of `array` to determine the index at which `value`
+ * should be inserted into `array` in order to maintain its sort order.
+ *
+ * @private
+ * @param {Array} array The sorted array to inspect.
+ * @param {*} value The value to evaluate.
+ * @param {boolean} [retHighest] Specify returning the highest qualified index.
+ * @returns {number} Returns the index at which `value` should be inserted
+ * into `array`.
+ */
+function baseSortedIndex(array, value, retHighest) {
+ var low = 0,
+ high = array == null ? low : array.length;
+
+ if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
+ while (low < high) {
+ var mid = (low + high) >>> 1,
+ computed = array[mid];
+
+ if (computed !== null && !isSymbol(computed) &&
+ (retHighest ? (computed <= value) : (computed < value))) {
+ low = mid + 1;
+ } else {
+ high = mid;
+ }
+ }
+ return high;
+ }
+ return baseSortedIndexBy(array, value, identity, retHighest);
+}
+
+module.exports = baseSortedIndex;
diff --git a/node_modules/lodash/_baseSortedIndexBy.js b/node_modules/lodash/_baseSortedIndexBy.js
new file mode 100644
index 0000000..c247b37
--- /dev/null
+++ b/node_modules/lodash/_baseSortedIndexBy.js
@@ -0,0 +1,67 @@
+var isSymbol = require('./isSymbol');
+
+/** Used as references for the maximum length and index of an array. */
+var MAX_ARRAY_LENGTH = 4294967295,
+ MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1;
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeFloor = Math.floor,
+ nativeMin = Math.min;
+
+/**
+ * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
+ * which invokes `iteratee` for `value` and each element of `array` to compute
+ * their sort ranking. The iteratee is invoked with one argument; (value).
+ *
+ * @private
+ * @param {Array} array The sorted array to inspect.
+ * @param {*} value The value to evaluate.
+ * @param {Function} iteratee The iteratee invoked per element.
+ * @param {boolean} [retHighest] Specify returning the highest qualified index.
+ * @returns {number} Returns the index at which `value` should be inserted
+ * into `array`.
+ */
+function baseSortedIndexBy(array, value, iteratee, retHighest) {
+ var low = 0,
+ high = array == null ? 0 : array.length;
+ if (high === 0) {
+ return 0;
+ }
+
+ value = iteratee(value);
+ var valIsNaN = value !== value,
+ valIsNull = value === null,
+ valIsSymbol = isSymbol(value),
+ valIsUndefined = value === undefined;
+
+ while (low < high) {
+ var mid = nativeFloor((low + high) / 2),
+ computed = iteratee(array[mid]),
+ othIsDefined = computed !== undefined,
+ othIsNull = computed === null,
+ othIsReflexive = computed === computed,
+ othIsSymbol = isSymbol(computed);
+
+ if (valIsNaN) {
+ var setLow = retHighest || othIsReflexive;
+ } else if (valIsUndefined) {
+ setLow = othIsReflexive && (retHighest || othIsDefined);
+ } else if (valIsNull) {
+ setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
+ } else if (valIsSymbol) {
+ setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
+ } else if (othIsNull || othIsSymbol) {
+ setLow = false;
+ } else {
+ setLow = retHighest ? (computed <= value) : (computed < value);
+ }
+ if (setLow) {
+ low = mid + 1;
+ } else {
+ high = mid;
+ }
+ }
+ return nativeMin(high, MAX_ARRAY_INDEX);
+}
+
+module.exports = baseSortedIndexBy;
diff --git a/node_modules/lodash/_baseSortedUniq.js b/node_modules/lodash/_baseSortedUniq.js
new file mode 100644
index 0000000..802159a
--- /dev/null
+++ b/node_modules/lodash/_baseSortedUniq.js
@@ -0,0 +1,30 @@
+var eq = require('./eq');
+
+/**
+ * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
+ * support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {Function} [iteratee] The iteratee invoked per element.
+ * @returns {Array} Returns the new duplicate free array.
+ */
+function baseSortedUniq(array, iteratee) {
+ var index = -1,
+ length = array.length,
+ resIndex = 0,
+ result = [];
+
+ while (++index < length) {
+ var value = array[index],
+ computed = iteratee ? iteratee(value) : value;
+
+ if (!index || !eq(computed, seen)) {
+ var seen = computed;
+ result[resIndex++] = value === 0 ? 0 : value;
+ }
+ }
+ return result;
+}
+
+module.exports = baseSortedUniq;
diff --git a/node_modules/lodash/_baseSum.js b/node_modules/lodash/_baseSum.js
new file mode 100644
index 0000000..a9e84c1
--- /dev/null
+++ b/node_modules/lodash/_baseSum.js
@@ -0,0 +1,24 @@
+/**
+ * The base implementation of `_.sum` and `_.sumBy` without support for
+ * iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {number} Returns the sum.
+ */
+function baseSum(array, iteratee) {
+ var result,
+ index = -1,
+ length = array.length;
+
+ while (++index < length) {
+ var current = iteratee(array[index]);
+ if (current !== undefined) {
+ result = result === undefined ? current : (result + current);
+ }
+ }
+ return result;
+}
+
+module.exports = baseSum;
diff --git a/node_modules/lodash/_baseTimes.js b/node_modules/lodash/_baseTimes.js
new file mode 100644
index 0000000..0603fc3
--- /dev/null
+++ b/node_modules/lodash/_baseTimes.js
@@ -0,0 +1,20 @@
+/**
+ * The base implementation of `_.times` without support for iteratee shorthands
+ * or max array length checks.
+ *
+ * @private
+ * @param {number} n The number of times to invoke `iteratee`.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns the array of results.
+ */
+function baseTimes(n, iteratee) {
+ var index = -1,
+ result = Array(n);
+
+ while (++index < n) {
+ result[index] = iteratee(index);
+ }
+ return result;
+}
+
+module.exports = baseTimes;
diff --git a/node_modules/lodash/_baseToNumber.js b/node_modules/lodash/_baseToNumber.js
new file mode 100644
index 0000000..04859f3
--- /dev/null
+++ b/node_modules/lodash/_baseToNumber.js
@@ -0,0 +1,24 @@
+var isSymbol = require('./isSymbol');
+
+/** Used as references for various `Number` constants. */
+var NAN = 0 / 0;
+
+/**
+ * The base implementation of `_.toNumber` which doesn't ensure correct
+ * conversions of binary, hexadecimal, or octal string values.
+ *
+ * @private
+ * @param {*} value The value to process.
+ * @returns {number} Returns the number.
+ */
+function baseToNumber(value) {
+ if (typeof value == 'number') {
+ return value;
+ }
+ if (isSymbol(value)) {
+ return NAN;
+ }
+ return +value;
+}
+
+module.exports = baseToNumber;
diff --git a/node_modules/lodash/_baseToPairs.js b/node_modules/lodash/_baseToPairs.js
new file mode 100644
index 0000000..bff1991
--- /dev/null
+++ b/node_modules/lodash/_baseToPairs.js
@@ -0,0 +1,18 @@
+var arrayMap = require('./_arrayMap');
+
+/**
+ * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
+ * of key-value pairs for `object` corresponding to the property names of `props`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array} props The property names to get values for.
+ * @returns {Object} Returns the key-value pairs.
+ */
+function baseToPairs(object, props) {
+ return arrayMap(props, function(key) {
+ return [key, object[key]];
+ });
+}
+
+module.exports = baseToPairs;
diff --git a/node_modules/lodash/_baseToString.js b/node_modules/lodash/_baseToString.js
new file mode 100644
index 0000000..ada6ad2
--- /dev/null
+++ b/node_modules/lodash/_baseToString.js
@@ -0,0 +1,37 @@
+var Symbol = require('./_Symbol'),
+ arrayMap = require('./_arrayMap'),
+ isArray = require('./isArray'),
+ isSymbol = require('./isSymbol');
+
+/** Used as references for various `Number` constants. */
+var INFINITY = 1 / 0;
+
+/** Used to convert symbols to primitives and strings. */
+var symbolProto = Symbol ? Symbol.prototype : undefined,
+ symbolToString = symbolProto ? symbolProto.toString : undefined;
+
+/**
+ * The base implementation of `_.toString` which doesn't convert nullish
+ * values to empty strings.
+ *
+ * @private
+ * @param {*} value The value to process.
+ * @returns {string} Returns the string.
+ */
+function baseToString(value) {
+ // Exit early for strings to avoid a performance hit in some environments.
+ if (typeof value == 'string') {
+ return value;
+ }
+ if (isArray(value)) {
+ // Recursively convert values (susceptible to call stack limits).
+ return arrayMap(value, baseToString) + '';
+ }
+ if (isSymbol(value)) {
+ return symbolToString ? symbolToString.call(value) : '';
+ }
+ var result = (value + '');
+ return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
+}
+
+module.exports = baseToString;
diff --git a/node_modules/lodash/_baseTrim.js b/node_modules/lodash/_baseTrim.js
new file mode 100644
index 0000000..3e2797d
--- /dev/null
+++ b/node_modules/lodash/_baseTrim.js
@@ -0,0 +1,19 @@
+var trimmedEndIndex = require('./_trimmedEndIndex');
+
+/** Used to match leading whitespace. */
+var reTrimStart = /^\s+/;
+
+/**
+ * The base implementation of `_.trim`.
+ *
+ * @private
+ * @param {string} string The string to trim.
+ * @returns {string} Returns the trimmed string.
+ */
+function baseTrim(string) {
+ return string
+ ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '')
+ : string;
+}
+
+module.exports = baseTrim;
diff --git a/node_modules/lodash/_baseUnary.js b/node_modules/lodash/_baseUnary.js
new file mode 100644
index 0000000..98639e9
--- /dev/null
+++ b/node_modules/lodash/_baseUnary.js
@@ -0,0 +1,14 @@
+/**
+ * The base implementation of `_.unary` without support for storing metadata.
+ *
+ * @private
+ * @param {Function} func The function to cap arguments for.
+ * @returns {Function} Returns the new capped function.
+ */
+function baseUnary(func) {
+ return function(value) {
+ return func(value);
+ };
+}
+
+module.exports = baseUnary;
diff --git a/node_modules/lodash/_baseUniq.js b/node_modules/lodash/_baseUniq.js
new file mode 100644
index 0000000..aea459d
--- /dev/null
+++ b/node_modules/lodash/_baseUniq.js
@@ -0,0 +1,72 @@
+var SetCache = require('./_SetCache'),
+ arrayIncludes = require('./_arrayIncludes'),
+ arrayIncludesWith = require('./_arrayIncludesWith'),
+ cacheHas = require('./_cacheHas'),
+ createSet = require('./_createSet'),
+ setToArray = require('./_setToArray');
+
+/** Used as the size to enable large array optimizations. */
+var LARGE_ARRAY_SIZE = 200;
+
+/**
+ * The base implementation of `_.uniqBy` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {Function} [iteratee] The iteratee invoked per element.
+ * @param {Function} [comparator] The comparator invoked per element.
+ * @returns {Array} Returns the new duplicate free array.
+ */
+function baseUniq(array, iteratee, comparator) {
+ var index = -1,
+ includes = arrayIncludes,
+ length = array.length,
+ isCommon = true,
+ result = [],
+ seen = result;
+
+ if (comparator) {
+ isCommon = false;
+ includes = arrayIncludesWith;
+ }
+ else if (length >= LARGE_ARRAY_SIZE) {
+ var set = iteratee ? null : createSet(array);
+ if (set) {
+ return setToArray(set);
+ }
+ isCommon = false;
+ includes = cacheHas;
+ seen = new SetCache;
+ }
+ else {
+ seen = iteratee ? [] : result;
+ }
+ outer:
+ while (++index < length) {
+ var value = array[index],
+ computed = iteratee ? iteratee(value) : value;
+
+ value = (comparator || value !== 0) ? value : 0;
+ if (isCommon && computed === computed) {
+ var seenIndex = seen.length;
+ while (seenIndex--) {
+ if (seen[seenIndex] === computed) {
+ continue outer;
+ }
+ }
+ if (iteratee) {
+ seen.push(computed);
+ }
+ result.push(value);
+ }
+ else if (!includes(seen, computed, comparator)) {
+ if (seen !== result) {
+ seen.push(computed);
+ }
+ result.push(value);
+ }
+ }
+ return result;
+}
+
+module.exports = baseUniq;
diff --git a/node_modules/lodash/_baseUnset.js b/node_modules/lodash/_baseUnset.js
new file mode 100644
index 0000000..eefc6e3
--- /dev/null
+++ b/node_modules/lodash/_baseUnset.js
@@ -0,0 +1,20 @@
+var castPath = require('./_castPath'),
+ last = require('./last'),
+ parent = require('./_parent'),
+ toKey = require('./_toKey');
+
+/**
+ * The base implementation of `_.unset`.
+ *
+ * @private
+ * @param {Object} object The object to modify.
+ * @param {Array|string} path The property path to unset.
+ * @returns {boolean} Returns `true` if the property is deleted, else `false`.
+ */
+function baseUnset(object, path) {
+ path = castPath(path, object);
+ object = parent(object, path);
+ return object == null || delete object[toKey(last(path))];
+}
+
+module.exports = baseUnset;
diff --git a/node_modules/lodash/_baseUpdate.js b/node_modules/lodash/_baseUpdate.js
new file mode 100644
index 0000000..92a6237
--- /dev/null
+++ b/node_modules/lodash/_baseUpdate.js
@@ -0,0 +1,18 @@
+var baseGet = require('./_baseGet'),
+ baseSet = require('./_baseSet');
+
+/**
+ * The base implementation of `_.update`.
+ *
+ * @private
+ * @param {Object} object The object to modify.
+ * @param {Array|string} path The path of the property to update.
+ * @param {Function} updater The function to produce the updated value.
+ * @param {Function} [customizer] The function to customize path creation.
+ * @returns {Object} Returns `object`.
+ */
+function baseUpdate(object, path, updater, customizer) {
+ return baseSet(object, path, updater(baseGet(object, path)), customizer);
+}
+
+module.exports = baseUpdate;
diff --git a/node_modules/lodash/_baseValues.js b/node_modules/lodash/_baseValues.js
new file mode 100644
index 0000000..b95faad
--- /dev/null
+++ b/node_modules/lodash/_baseValues.js
@@ -0,0 +1,19 @@
+var arrayMap = require('./_arrayMap');
+
+/**
+ * The base implementation of `_.values` and `_.valuesIn` which creates an
+ * array of `object` property values corresponding to the property names
+ * of `props`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array} props The property names to get values for.
+ * @returns {Object} Returns the array of property values.
+ */
+function baseValues(object, props) {
+ return arrayMap(props, function(key) {
+ return object[key];
+ });
+}
+
+module.exports = baseValues;
diff --git a/node_modules/lodash/_baseWhile.js b/node_modules/lodash/_baseWhile.js
new file mode 100644
index 0000000..07eac61
--- /dev/null
+++ b/node_modules/lodash/_baseWhile.js
@@ -0,0 +1,26 @@
+var baseSlice = require('./_baseSlice');
+
+/**
+ * The base implementation of methods like `_.dropWhile` and `_.takeWhile`
+ * without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to query.
+ * @param {Function} predicate The function invoked per iteration.
+ * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Array} Returns the slice of `array`.
+ */
+function baseWhile(array, predicate, isDrop, fromRight) {
+ var length = array.length,
+ index = fromRight ? length : -1;
+
+ while ((fromRight ? index-- : ++index < length) &&
+ predicate(array[index], index, array)) {}
+
+ return isDrop
+ ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
+ : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
+}
+
+module.exports = baseWhile;
diff --git a/node_modules/lodash/_baseWrapperValue.js b/node_modules/lodash/_baseWrapperValue.js
new file mode 100644
index 0000000..443e0df
--- /dev/null
+++ b/node_modules/lodash/_baseWrapperValue.js
@@ -0,0 +1,25 @@
+var LazyWrapper = require('./_LazyWrapper'),
+ arrayPush = require('./_arrayPush'),
+ arrayReduce = require('./_arrayReduce');
+
+/**
+ * The base implementation of `wrapperValue` which returns the result of
+ * performing a sequence of actions on the unwrapped `value`, where each
+ * successive action is supplied the return value of the previous.
+ *
+ * @private
+ * @param {*} value The unwrapped value.
+ * @param {Array} actions Actions to perform to resolve the unwrapped value.
+ * @returns {*} Returns the resolved value.
+ */
+function baseWrapperValue(value, actions) {
+ var result = value;
+ if (result instanceof LazyWrapper) {
+ result = result.value();
+ }
+ return arrayReduce(actions, function(result, action) {
+ return action.func.apply(action.thisArg, arrayPush([result], action.args));
+ }, result);
+}
+
+module.exports = baseWrapperValue;
diff --git a/node_modules/lodash/_baseXor.js b/node_modules/lodash/_baseXor.js
new file mode 100644
index 0000000..8e69338
--- /dev/null
+++ b/node_modules/lodash/_baseXor.js
@@ -0,0 +1,36 @@
+var baseDifference = require('./_baseDifference'),
+ baseFlatten = require('./_baseFlatten'),
+ baseUniq = require('./_baseUniq');
+
+/**
+ * The base implementation of methods like `_.xor`, without support for
+ * iteratee shorthands, that accepts an array of arrays to inspect.
+ *
+ * @private
+ * @param {Array} arrays The arrays to inspect.
+ * @param {Function} [iteratee] The iteratee invoked per element.
+ * @param {Function} [comparator] The comparator invoked per element.
+ * @returns {Array} Returns the new array of values.
+ */
+function baseXor(arrays, iteratee, comparator) {
+ var length = arrays.length;
+ if (length < 2) {
+ return length ? baseUniq(arrays[0]) : [];
+ }
+ var index = -1,
+ result = Array(length);
+
+ while (++index < length) {
+ var array = arrays[index],
+ othIndex = -1;
+
+ while (++othIndex < length) {
+ if (othIndex != index) {
+ result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);
+ }
+ }
+ }
+ return baseUniq(baseFlatten(result, 1), iteratee, comparator);
+}
+
+module.exports = baseXor;
diff --git a/node_modules/lodash/_baseZipObject.js b/node_modules/lodash/_baseZipObject.js
new file mode 100644
index 0000000..401f85b
--- /dev/null
+++ b/node_modules/lodash/_baseZipObject.js
@@ -0,0 +1,23 @@
+/**
+ * This base implementation of `_.zipObject` which assigns values using `assignFunc`.
+ *
+ * @private
+ * @param {Array} props The property identifiers.
+ * @param {Array} values The property values.
+ * @param {Function} assignFunc The function to assign values.
+ * @returns {Object} Returns the new object.
+ */
+function baseZipObject(props, values, assignFunc) {
+ var index = -1,
+ length = props.length,
+ valsLength = values.length,
+ result = {};
+
+ while (++index < length) {
+ var value = index < valsLength ? values[index] : undefined;
+ assignFunc(result, props[index], value);
+ }
+ return result;
+}
+
+module.exports = baseZipObject;
diff --git a/node_modules/lodash/_cacheHas.js b/node_modules/lodash/_cacheHas.js
new file mode 100644
index 0000000..2dec892
--- /dev/null
+++ b/node_modules/lodash/_cacheHas.js
@@ -0,0 +1,13 @@
+/**
+ * Checks if a `cache` value for `key` exists.
+ *
+ * @private
+ * @param {Object} cache The cache to query.
+ * @param {string} key The key of the entry to check.
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
+ */
+function cacheHas(cache, key) {
+ return cache.has(key);
+}
+
+module.exports = cacheHas;
diff --git a/node_modules/lodash/_castArrayLikeObject.js b/node_modules/lodash/_castArrayLikeObject.js
new file mode 100644
index 0000000..92c75fa
--- /dev/null
+++ b/node_modules/lodash/_castArrayLikeObject.js
@@ -0,0 +1,14 @@
+var isArrayLikeObject = require('./isArrayLikeObject');
+
+/**
+ * Casts `value` to an empty array if it's not an array like object.
+ *
+ * @private
+ * @param {*} value The value to inspect.
+ * @returns {Array|Object} Returns the cast array-like object.
+ */
+function castArrayLikeObject(value) {
+ return isArrayLikeObject(value) ? value : [];
+}
+
+module.exports = castArrayLikeObject;
diff --git a/node_modules/lodash/_castFunction.js b/node_modules/lodash/_castFunction.js
new file mode 100644
index 0000000..98c91ae
--- /dev/null
+++ b/node_modules/lodash/_castFunction.js
@@ -0,0 +1,14 @@
+var identity = require('./identity');
+
+/**
+ * Casts `value` to `identity` if it's not a function.
+ *
+ * @private
+ * @param {*} value The value to inspect.
+ * @returns {Function} Returns cast function.
+ */
+function castFunction(value) {
+ return typeof value == 'function' ? value : identity;
+}
+
+module.exports = castFunction;
diff --git a/node_modules/lodash/_castPath.js b/node_modules/lodash/_castPath.js
new file mode 100644
index 0000000..017e4c1
--- /dev/null
+++ b/node_modules/lodash/_castPath.js
@@ -0,0 +1,21 @@
+var isArray = require('./isArray'),
+ isKey = require('./_isKey'),
+ stringToPath = require('./_stringToPath'),
+ toString = require('./toString');
+
+/**
+ * Casts `value` to a path array if it's not one.
+ *
+ * @private
+ * @param {*} value The value to inspect.
+ * @param {Object} [object] The object to query keys on.
+ * @returns {Array} Returns the cast property path array.
+ */
+function castPath(value, object) {
+ if (isArray(value)) {
+ return value;
+ }
+ return isKey(value, object) ? [value] : stringToPath(toString(value));
+}
+
+module.exports = castPath;
diff --git a/node_modules/lodash/_castRest.js b/node_modules/lodash/_castRest.js
new file mode 100644
index 0000000..213c66f
--- /dev/null
+++ b/node_modules/lodash/_castRest.js
@@ -0,0 +1,14 @@
+var baseRest = require('./_baseRest');
+
+/**
+ * A `baseRest` alias which can be replaced with `identity` by module
+ * replacement plugins.
+ *
+ * @private
+ * @type {Function}
+ * @param {Function} func The function to apply a rest parameter to.
+ * @returns {Function} Returns the new function.
+ */
+var castRest = baseRest;
+
+module.exports = castRest;
diff --git a/node_modules/lodash/_castSlice.js b/node_modules/lodash/_castSlice.js
new file mode 100644
index 0000000..071faeb
--- /dev/null
+++ b/node_modules/lodash/_castSlice.js
@@ -0,0 +1,18 @@
+var baseSlice = require('./_baseSlice');
+
+/**
+ * Casts `array` to a slice if it's needed.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {number} start The start position.
+ * @param {number} [end=array.length] The end position.
+ * @returns {Array} Returns the cast slice.
+ */
+function castSlice(array, start, end) {
+ var length = array.length;
+ end = end === undefined ? length : end;
+ return (!start && end >= length) ? array : baseSlice(array, start, end);
+}
+
+module.exports = castSlice;
diff --git a/node_modules/lodash/_charsEndIndex.js b/node_modules/lodash/_charsEndIndex.js
new file mode 100644
index 0000000..07908ff
--- /dev/null
+++ b/node_modules/lodash/_charsEndIndex.js
@@ -0,0 +1,19 @@
+var baseIndexOf = require('./_baseIndexOf');
+
+/**
+ * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
+ * that is not found in the character symbols.
+ *
+ * @private
+ * @param {Array} strSymbols The string symbols to inspect.
+ * @param {Array} chrSymbols The character symbols to find.
+ * @returns {number} Returns the index of the last unmatched string symbol.
+ */
+function charsEndIndex(strSymbols, chrSymbols) {
+ var index = strSymbols.length;
+
+ while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
+ return index;
+}
+
+module.exports = charsEndIndex;
diff --git a/node_modules/lodash/_charsStartIndex.js b/node_modules/lodash/_charsStartIndex.js
new file mode 100644
index 0000000..b17afd2
--- /dev/null
+++ b/node_modules/lodash/_charsStartIndex.js
@@ -0,0 +1,20 @@
+var baseIndexOf = require('./_baseIndexOf');
+
+/**
+ * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
+ * that is not found in the character symbols.
+ *
+ * @private
+ * @param {Array} strSymbols The string symbols to inspect.
+ * @param {Array} chrSymbols The character symbols to find.
+ * @returns {number} Returns the index of the first unmatched string symbol.
+ */
+function charsStartIndex(strSymbols, chrSymbols) {
+ var index = -1,
+ length = strSymbols.length;
+
+ while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
+ return index;
+}
+
+module.exports = charsStartIndex;
diff --git a/node_modules/lodash/_cloneArrayBuffer.js b/node_modules/lodash/_cloneArrayBuffer.js
new file mode 100644
index 0000000..c3d8f6e
--- /dev/null
+++ b/node_modules/lodash/_cloneArrayBuffer.js
@@ -0,0 +1,16 @@
+var Uint8Array = require('./_Uint8Array');
+
+/**
+ * Creates a clone of `arrayBuffer`.
+ *
+ * @private
+ * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
+ * @returns {ArrayBuffer} Returns the cloned array buffer.
+ */
+function cloneArrayBuffer(arrayBuffer) {
+ var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
+ new Uint8Array(result).set(new Uint8Array(arrayBuffer));
+ return result;
+}
+
+module.exports = cloneArrayBuffer;
diff --git a/node_modules/lodash/_cloneBuffer.js b/node_modules/lodash/_cloneBuffer.js
new file mode 100644
index 0000000..27c4810
--- /dev/null
+++ b/node_modules/lodash/_cloneBuffer.js
@@ -0,0 +1,35 @@
+var root = require('./_root');
+
+/** Detect free variable `exports`. */
+var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
+
+/** Detect free variable `module`. */
+var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
+
+/** Detect the popular CommonJS extension `module.exports`. */
+var moduleExports = freeModule && freeModule.exports === freeExports;
+
+/** Built-in value references. */
+var Buffer = moduleExports ? root.Buffer : undefined,
+ allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined;
+
+/**
+ * Creates a clone of `buffer`.
+ *
+ * @private
+ * @param {Buffer} buffer The buffer to clone.
+ * @param {boolean} [isDeep] Specify a deep clone.
+ * @returns {Buffer} Returns the cloned buffer.
+ */
+function cloneBuffer(buffer, isDeep) {
+ if (isDeep) {
+ return buffer.slice();
+ }
+ var length = buffer.length,
+ result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
+
+ buffer.copy(result);
+ return result;
+}
+
+module.exports = cloneBuffer;
diff --git a/node_modules/lodash/_cloneDataView.js b/node_modules/lodash/_cloneDataView.js
new file mode 100644
index 0000000..9c9b7b0
--- /dev/null
+++ b/node_modules/lodash/_cloneDataView.js
@@ -0,0 +1,16 @@
+var cloneArrayBuffer = require('./_cloneArrayBuffer');
+
+/**
+ * Creates a clone of `dataView`.
+ *
+ * @private
+ * @param {Object} dataView The data view to clone.
+ * @param {boolean} [isDeep] Specify a deep clone.
+ * @returns {Object} Returns the cloned data view.
+ */
+function cloneDataView(dataView, isDeep) {
+ var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
+ return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
+}
+
+module.exports = cloneDataView;
diff --git a/node_modules/lodash/_cloneRegExp.js b/node_modules/lodash/_cloneRegExp.js
new file mode 100644
index 0000000..64a30df
--- /dev/null
+++ b/node_modules/lodash/_cloneRegExp.js
@@ -0,0 +1,17 @@
+/** Used to match `RegExp` flags from their coerced string values. */
+var reFlags = /\w*$/;
+
+/**
+ * Creates a clone of `regexp`.
+ *
+ * @private
+ * @param {Object} regexp The regexp to clone.
+ * @returns {Object} Returns the cloned regexp.
+ */
+function cloneRegExp(regexp) {
+ var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
+ result.lastIndex = regexp.lastIndex;
+ return result;
+}
+
+module.exports = cloneRegExp;
diff --git a/node_modules/lodash/_cloneSymbol.js b/node_modules/lodash/_cloneSymbol.js
new file mode 100644
index 0000000..bede39f
--- /dev/null
+++ b/node_modules/lodash/_cloneSymbol.js
@@ -0,0 +1,18 @@
+var Symbol = require('./_Symbol');
+
+/** Used to convert symbols to primitives and strings. */
+var symbolProto = Symbol ? Symbol.prototype : undefined,
+ symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
+
+/**
+ * Creates a clone of the `symbol` object.
+ *
+ * @private
+ * @param {Object} symbol The symbol object to clone.
+ * @returns {Object} Returns the cloned symbol object.
+ */
+function cloneSymbol(symbol) {
+ return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
+}
+
+module.exports = cloneSymbol;
diff --git a/node_modules/lodash/_cloneTypedArray.js b/node_modules/lodash/_cloneTypedArray.js
new file mode 100644
index 0000000..7aad84d
--- /dev/null
+++ b/node_modules/lodash/_cloneTypedArray.js
@@ -0,0 +1,16 @@
+var cloneArrayBuffer = require('./_cloneArrayBuffer');
+
+/**
+ * Creates a clone of `typedArray`.
+ *
+ * @private
+ * @param {Object} typedArray The typed array to clone.
+ * @param {boolean} [isDeep] Specify a deep clone.
+ * @returns {Object} Returns the cloned typed array.
+ */
+function cloneTypedArray(typedArray, isDeep) {
+ var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
+ return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
+}
+
+module.exports = cloneTypedArray;
diff --git a/node_modules/lodash/_compareAscending.js b/node_modules/lodash/_compareAscending.js
new file mode 100644
index 0000000..8dc2791
--- /dev/null
+++ b/node_modules/lodash/_compareAscending.js
@@ -0,0 +1,41 @@
+var isSymbol = require('./isSymbol');
+
+/**
+ * Compares values to sort them in ascending order.
+ *
+ * @private
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {number} Returns the sort order indicator for `value`.
+ */
+function compareAscending(value, other) {
+ if (value !== other) {
+ var valIsDefined = value !== undefined,
+ valIsNull = value === null,
+ valIsReflexive = value === value,
+ valIsSymbol = isSymbol(value);
+
+ var othIsDefined = other !== undefined,
+ othIsNull = other === null,
+ othIsReflexive = other === other,
+ othIsSymbol = isSymbol(other);
+
+ if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
+ (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
+ (valIsNull && othIsDefined && othIsReflexive) ||
+ (!valIsDefined && othIsReflexive) ||
+ !valIsReflexive) {
+ return 1;
+ }
+ if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
+ (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
+ (othIsNull && valIsDefined && valIsReflexive) ||
+ (!othIsDefined && valIsReflexive) ||
+ !othIsReflexive) {
+ return -1;
+ }
+ }
+ return 0;
+}
+
+module.exports = compareAscending;
diff --git a/node_modules/lodash/_compareMultiple.js b/node_modules/lodash/_compareMultiple.js
new file mode 100644
index 0000000..ad61f0f
--- /dev/null
+++ b/node_modules/lodash/_compareMultiple.js
@@ -0,0 +1,44 @@
+var compareAscending = require('./_compareAscending');
+
+/**
+ * Used by `_.orderBy` to compare multiple properties of a value to another
+ * and stable sort them.
+ *
+ * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
+ * specify an order of "desc" for descending or "asc" for ascending sort order
+ * of corresponding values.
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @param {boolean[]|string[]} orders The order to sort by for each property.
+ * @returns {number} Returns the sort order indicator for `object`.
+ */
+function compareMultiple(object, other, orders) {
+ var index = -1,
+ objCriteria = object.criteria,
+ othCriteria = other.criteria,
+ length = objCriteria.length,
+ ordersLength = orders.length;
+
+ while (++index < length) {
+ var result = compareAscending(objCriteria[index], othCriteria[index]);
+ if (result) {
+ if (index >= ordersLength) {
+ return result;
+ }
+ var order = orders[index];
+ return result * (order == 'desc' ? -1 : 1);
+ }
+ }
+ // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
+ // that causes it, under certain circumstances, to provide the same value for
+ // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
+ // for more details.
+ //
+ // This also ensures a stable sort in V8 and other engines.
+ // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
+ return object.index - other.index;
+}
+
+module.exports = compareMultiple;
diff --git a/node_modules/lodash/_composeArgs.js b/node_modules/lodash/_composeArgs.js
new file mode 100644
index 0000000..1ce40f4
--- /dev/null
+++ b/node_modules/lodash/_composeArgs.js
@@ -0,0 +1,39 @@
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeMax = Math.max;
+
+/**
+ * Creates an array that is the composition of partially applied arguments,
+ * placeholders, and provided arguments into a single array of arguments.
+ *
+ * @private
+ * @param {Array} args The provided arguments.
+ * @param {Array} partials The arguments to prepend to those provided.
+ * @param {Array} holders The `partials` placeholder indexes.
+ * @params {boolean} [isCurried] Specify composing for a curried function.
+ * @returns {Array} Returns the new array of composed arguments.
+ */
+function composeArgs(args, partials, holders, isCurried) {
+ var argsIndex = -1,
+ argsLength = args.length,
+ holdersLength = holders.length,
+ leftIndex = -1,
+ leftLength = partials.length,
+ rangeLength = nativeMax(argsLength - holdersLength, 0),
+ result = Array(leftLength + rangeLength),
+ isUncurried = !isCurried;
+
+ while (++leftIndex < leftLength) {
+ result[leftIndex] = partials[leftIndex];
+ }
+ while (++argsIndex < holdersLength) {
+ if (isUncurried || argsIndex < argsLength) {
+ result[holders[argsIndex]] = args[argsIndex];
+ }
+ }
+ while (rangeLength--) {
+ result[leftIndex++] = args[argsIndex++];
+ }
+ return result;
+}
+
+module.exports = composeArgs;
diff --git a/node_modules/lodash/_composeArgsRight.js b/node_modules/lodash/_composeArgsRight.js
new file mode 100644
index 0000000..8dc588d
--- /dev/null
+++ b/node_modules/lodash/_composeArgsRight.js
@@ -0,0 +1,41 @@
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeMax = Math.max;
+
+/**
+ * This function is like `composeArgs` except that the arguments composition
+ * is tailored for `_.partialRight`.
+ *
+ * @private
+ * @param {Array} args The provided arguments.
+ * @param {Array} partials The arguments to append to those provided.
+ * @param {Array} holders The `partials` placeholder indexes.
+ * @params {boolean} [isCurried] Specify composing for a curried function.
+ * @returns {Array} Returns the new array of composed arguments.
+ */
+function composeArgsRight(args, partials, holders, isCurried) {
+ var argsIndex = -1,
+ argsLength = args.length,
+ holdersIndex = -1,
+ holdersLength = holders.length,
+ rightIndex = -1,
+ rightLength = partials.length,
+ rangeLength = nativeMax(argsLength - holdersLength, 0),
+ result = Array(rangeLength + rightLength),
+ isUncurried = !isCurried;
+
+ while (++argsIndex < rangeLength) {
+ result[argsIndex] = args[argsIndex];
+ }
+ var offset = argsIndex;
+ while (++rightIndex < rightLength) {
+ result[offset + rightIndex] = partials[rightIndex];
+ }
+ while (++holdersIndex < holdersLength) {
+ if (isUncurried || argsIndex < argsLength) {
+ result[offset + holders[holdersIndex]] = args[argsIndex++];
+ }
+ }
+ return result;
+}
+
+module.exports = composeArgsRight;
diff --git a/node_modules/lodash/_copyArray.js b/node_modules/lodash/_copyArray.js
new file mode 100644
index 0000000..cd94d5d
--- /dev/null
+++ b/node_modules/lodash/_copyArray.js
@@ -0,0 +1,20 @@
+/**
+ * Copies the values of `source` to `array`.
+ *
+ * @private
+ * @param {Array} source The array to copy values from.
+ * @param {Array} [array=[]] The array to copy values to.
+ * @returns {Array} Returns `array`.
+ */
+function copyArray(source, array) {
+ var index = -1,
+ length = source.length;
+
+ array || (array = Array(length));
+ while (++index < length) {
+ array[index] = source[index];
+ }
+ return array;
+}
+
+module.exports = copyArray;
diff --git a/node_modules/lodash/_copyObject.js b/node_modules/lodash/_copyObject.js
new file mode 100644
index 0000000..2f2a5c2
--- /dev/null
+++ b/node_modules/lodash/_copyObject.js
@@ -0,0 +1,40 @@
+var assignValue = require('./_assignValue'),
+ baseAssignValue = require('./_baseAssignValue');
+
+/**
+ * Copies properties of `source` to `object`.
+ *
+ * @private
+ * @param {Object} source The object to copy properties from.
+ * @param {Array} props The property identifiers to copy.
+ * @param {Object} [object={}] The object to copy properties to.
+ * @param {Function} [customizer] The function to customize copied values.
+ * @returns {Object} Returns `object`.
+ */
+function copyObject(source, props, object, customizer) {
+ var isNew = !object;
+ object || (object = {});
+
+ var index = -1,
+ length = props.length;
+
+ while (++index < length) {
+ var key = props[index];
+
+ var newValue = customizer
+ ? customizer(object[key], source[key], key, object, source)
+ : undefined;
+
+ if (newValue === undefined) {
+ newValue = source[key];
+ }
+ if (isNew) {
+ baseAssignValue(object, key, newValue);
+ } else {
+ assignValue(object, key, newValue);
+ }
+ }
+ return object;
+}
+
+module.exports = copyObject;
diff --git a/node_modules/lodash/_copySymbols.js b/node_modules/lodash/_copySymbols.js
new file mode 100644
index 0000000..c35944a
--- /dev/null
+++ b/node_modules/lodash/_copySymbols.js
@@ -0,0 +1,16 @@
+var copyObject = require('./_copyObject'),
+ getSymbols = require('./_getSymbols');
+
+/**
+ * Copies own symbols of `source` to `object`.
+ *
+ * @private
+ * @param {Object} source The object to copy symbols from.
+ * @param {Object} [object={}] The object to copy symbols to.
+ * @returns {Object} Returns `object`.
+ */
+function copySymbols(source, object) {
+ return copyObject(source, getSymbols(source), object);
+}
+
+module.exports = copySymbols;
diff --git a/node_modules/lodash/_copySymbolsIn.js b/node_modules/lodash/_copySymbolsIn.js
new file mode 100644
index 0000000..fdf20a7
--- /dev/null
+++ b/node_modules/lodash/_copySymbolsIn.js
@@ -0,0 +1,16 @@
+var copyObject = require('./_copyObject'),
+ getSymbolsIn = require('./_getSymbolsIn');
+
+/**
+ * Copies own and inherited symbols of `source` to `object`.
+ *
+ * @private
+ * @param {Object} source The object to copy symbols from.
+ * @param {Object} [object={}] The object to copy symbols to.
+ * @returns {Object} Returns `object`.
+ */
+function copySymbolsIn(source, object) {
+ return copyObject(source, getSymbolsIn(source), object);
+}
+
+module.exports = copySymbolsIn;
diff --git a/node_modules/lodash/_coreJsData.js b/node_modules/lodash/_coreJsData.js
new file mode 100644
index 0000000..f8e5b4e
--- /dev/null
+++ b/node_modules/lodash/_coreJsData.js
@@ -0,0 +1,6 @@
+var root = require('./_root');
+
+/** Used to detect overreaching core-js shims. */
+var coreJsData = root['__core-js_shared__'];
+
+module.exports = coreJsData;
diff --git a/node_modules/lodash/_countHolders.js b/node_modules/lodash/_countHolders.js
new file mode 100644
index 0000000..718fcda
--- /dev/null
+++ b/node_modules/lodash/_countHolders.js
@@ -0,0 +1,21 @@
+/**
+ * Gets the number of `placeholder` occurrences in `array`.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {*} placeholder The placeholder to search for.
+ * @returns {number} Returns the placeholder count.
+ */
+function countHolders(array, placeholder) {
+ var length = array.length,
+ result = 0;
+
+ while (length--) {
+ if (array[length] === placeholder) {
+ ++result;
+ }
+ }
+ return result;
+}
+
+module.exports = countHolders;
diff --git a/node_modules/lodash/_createAggregator.js b/node_modules/lodash/_createAggregator.js
new file mode 100644
index 0000000..0be42c4
--- /dev/null
+++ b/node_modules/lodash/_createAggregator.js
@@ -0,0 +1,23 @@
+var arrayAggregator = require('./_arrayAggregator'),
+ baseAggregator = require('./_baseAggregator'),
+ baseIteratee = require('./_baseIteratee'),
+ isArray = require('./isArray');
+
+/**
+ * Creates a function like `_.groupBy`.
+ *
+ * @private
+ * @param {Function} setter The function to set accumulator values.
+ * @param {Function} [initializer] The accumulator object initializer.
+ * @returns {Function} Returns the new aggregator function.
+ */
+function createAggregator(setter, initializer) {
+ return function(collection, iteratee) {
+ var func = isArray(collection) ? arrayAggregator : baseAggregator,
+ accumulator = initializer ? initializer() : {};
+
+ return func(collection, setter, baseIteratee(iteratee, 2), accumulator);
+ };
+}
+
+module.exports = createAggregator;
diff --git a/node_modules/lodash/_createAssigner.js b/node_modules/lodash/_createAssigner.js
new file mode 100644
index 0000000..1f904c5
--- /dev/null
+++ b/node_modules/lodash/_createAssigner.js
@@ -0,0 +1,37 @@
+var baseRest = require('./_baseRest'),
+ isIterateeCall = require('./_isIterateeCall');
+
+/**
+ * Creates a function like `_.assign`.
+ *
+ * @private
+ * @param {Function} assigner The function to assign values.
+ * @returns {Function} Returns the new assigner function.
+ */
+function createAssigner(assigner) {
+ return baseRest(function(object, sources) {
+ var index = -1,
+ length = sources.length,
+ customizer = length > 1 ? sources[length - 1] : undefined,
+ guard = length > 2 ? sources[2] : undefined;
+
+ customizer = (assigner.length > 3 && typeof customizer == 'function')
+ ? (length--, customizer)
+ : undefined;
+
+ if (guard && isIterateeCall(sources[0], sources[1], guard)) {
+ customizer = length < 3 ? undefined : customizer;
+ length = 1;
+ }
+ object = Object(object);
+ while (++index < length) {
+ var source = sources[index];
+ if (source) {
+ assigner(object, source, index, customizer);
+ }
+ }
+ return object;
+ });
+}
+
+module.exports = createAssigner;
diff --git a/node_modules/lodash/_createBaseEach.js b/node_modules/lodash/_createBaseEach.js
new file mode 100644
index 0000000..d24fdd1
--- /dev/null
+++ b/node_modules/lodash/_createBaseEach.js
@@ -0,0 +1,32 @@
+var isArrayLike = require('./isArrayLike');
+
+/**
+ * Creates a `baseEach` or `baseEachRight` function.
+ *
+ * @private
+ * @param {Function} eachFunc The function to iterate over a collection.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new base function.
+ */
+function createBaseEach(eachFunc, fromRight) {
+ return function(collection, iteratee) {
+ if (collection == null) {
+ return collection;
+ }
+ if (!isArrayLike(collection)) {
+ return eachFunc(collection, iteratee);
+ }
+ var length = collection.length,
+ index = fromRight ? length : -1,
+ iterable = Object(collection);
+
+ while ((fromRight ? index-- : ++index < length)) {
+ if (iteratee(iterable[index], index, iterable) === false) {
+ break;
+ }
+ }
+ return collection;
+ };
+}
+
+module.exports = createBaseEach;
diff --git a/node_modules/lodash/_createBaseFor.js b/node_modules/lodash/_createBaseFor.js
new file mode 100644
index 0000000..94cbf29
--- /dev/null
+++ b/node_modules/lodash/_createBaseFor.js
@@ -0,0 +1,25 @@
+/**
+ * Creates a base function for methods like `_.forIn` and `_.forOwn`.
+ *
+ * @private
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new base function.
+ */
+function createBaseFor(fromRight) {
+ return function(object, iteratee, keysFunc) {
+ var index = -1,
+ iterable = Object(object),
+ props = keysFunc(object),
+ length = props.length;
+
+ while (length--) {
+ var key = props[fromRight ? length : ++index];
+ if (iteratee(iterable[key], key, iterable) === false) {
+ break;
+ }
+ }
+ return object;
+ };
+}
+
+module.exports = createBaseFor;
diff --git a/node_modules/lodash/_createBind.js b/node_modules/lodash/_createBind.js
new file mode 100644
index 0000000..07cb99f
--- /dev/null
+++ b/node_modules/lodash/_createBind.js
@@ -0,0 +1,28 @@
+var createCtor = require('./_createCtor'),
+ root = require('./_root');
+
+/** Used to compose bitmasks for function metadata. */
+var WRAP_BIND_FLAG = 1;
+
+/**
+ * Creates a function that wraps `func` to invoke it with the optional `this`
+ * binding of `thisArg`.
+ *
+ * @private
+ * @param {Function} func The function to wrap.
+ * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
+ * @param {*} [thisArg] The `this` binding of `func`.
+ * @returns {Function} Returns the new wrapped function.
+ */
+function createBind(func, bitmask, thisArg) {
+ var isBind = bitmask & WRAP_BIND_FLAG,
+ Ctor = createCtor(func);
+
+ function wrapper() {
+ var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
+ return fn.apply(isBind ? thisArg : this, arguments);
+ }
+ return wrapper;
+}
+
+module.exports = createBind;
diff --git a/node_modules/lodash/_createCaseFirst.js b/node_modules/lodash/_createCaseFirst.js
new file mode 100644
index 0000000..fe8ea48
--- /dev/null
+++ b/node_modules/lodash/_createCaseFirst.js
@@ -0,0 +1,33 @@
+var castSlice = require('./_castSlice'),
+ hasUnicode = require('./_hasUnicode'),
+ stringToArray = require('./_stringToArray'),
+ toString = require('./toString');
+
+/**
+ * Creates a function like `_.lowerFirst`.
+ *
+ * @private
+ * @param {string} methodName The name of the `String` case method to use.
+ * @returns {Function} Returns the new case function.
+ */
+function createCaseFirst(methodName) {
+ return function(string) {
+ string = toString(string);
+
+ var strSymbols = hasUnicode(string)
+ ? stringToArray(string)
+ : undefined;
+
+ var chr = strSymbols
+ ? strSymbols[0]
+ : string.charAt(0);
+
+ var trailing = strSymbols
+ ? castSlice(strSymbols, 1).join('')
+ : string.slice(1);
+
+ return chr[methodName]() + trailing;
+ };
+}
+
+module.exports = createCaseFirst;
diff --git a/node_modules/lodash/_createCompounder.js b/node_modules/lodash/_createCompounder.js
new file mode 100644
index 0000000..8d4cee2
--- /dev/null
+++ b/node_modules/lodash/_createCompounder.js
@@ -0,0 +1,24 @@
+var arrayReduce = require('./_arrayReduce'),
+ deburr = require('./deburr'),
+ words = require('./words');
+
+/** Used to compose unicode capture groups. */
+var rsApos = "['\u2019]";
+
+/** Used to match apostrophes. */
+var reApos = RegExp(rsApos, 'g');
+
+/**
+ * Creates a function like `_.camelCase`.
+ *
+ * @private
+ * @param {Function} callback The function to combine each word.
+ * @returns {Function} Returns the new compounder function.
+ */
+function createCompounder(callback) {
+ return function(string) {
+ return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
+ };
+}
+
+module.exports = createCompounder;
diff --git a/node_modules/lodash/_createCtor.js b/node_modules/lodash/_createCtor.js
new file mode 100644
index 0000000..9047aa5
--- /dev/null
+++ b/node_modules/lodash/_createCtor.js
@@ -0,0 +1,37 @@
+var baseCreate = require('./_baseCreate'),
+ isObject = require('./isObject');
+
+/**
+ * Creates a function that produces an instance of `Ctor` regardless of
+ * whether it was invoked as part of a `new` expression or by `call` or `apply`.
+ *
+ * @private
+ * @param {Function} Ctor The constructor to wrap.
+ * @returns {Function} Returns the new wrapped function.
+ */
+function createCtor(Ctor) {
+ return function() {
+ // Use a `switch` statement to work with class constructors. See
+ // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
+ // for more details.
+ var args = arguments;
+ switch (args.length) {
+ case 0: return new Ctor;
+ case 1: return new Ctor(args[0]);
+ case 2: return new Ctor(args[0], args[1]);
+ case 3: return new Ctor(args[0], args[1], args[2]);
+ case 4: return new Ctor(args[0], args[1], args[2], args[3]);
+ case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
+ case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
+ case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
+ }
+ var thisBinding = baseCreate(Ctor.prototype),
+ result = Ctor.apply(thisBinding, args);
+
+ // Mimic the constructor's `return` behavior.
+ // See https://es5.github.io/#x13.2.2 for more details.
+ return isObject(result) ? result : thisBinding;
+ };
+}
+
+module.exports = createCtor;
diff --git a/node_modules/lodash/_createCurry.js b/node_modules/lodash/_createCurry.js
new file mode 100644
index 0000000..f06c2cd
--- /dev/null
+++ b/node_modules/lodash/_createCurry.js
@@ -0,0 +1,46 @@
+var apply = require('./_apply'),
+ createCtor = require('./_createCtor'),
+ createHybrid = require('./_createHybrid'),
+ createRecurry = require('./_createRecurry'),
+ getHolder = require('./_getHolder'),
+ replaceHolders = require('./_replaceHolders'),
+ root = require('./_root');
+
+/**
+ * Creates a function that wraps `func` to enable currying.
+ *
+ * @private
+ * @param {Function} func The function to wrap.
+ * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
+ * @param {number} arity The arity of `func`.
+ * @returns {Function} Returns the new wrapped function.
+ */
+function createCurry(func, bitmask, arity) {
+ var Ctor = createCtor(func);
+
+ function wrapper() {
+ var length = arguments.length,
+ args = Array(length),
+ index = length,
+ placeholder = getHolder(wrapper);
+
+ while (index--) {
+ args[index] = arguments[index];
+ }
+ var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
+ ? []
+ : replaceHolders(args, placeholder);
+
+ length -= holders.length;
+ if (length < arity) {
+ return createRecurry(
+ func, bitmask, createHybrid, wrapper.placeholder, undefined,
+ args, holders, undefined, undefined, arity - length);
+ }
+ var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
+ return apply(fn, this, args);
+ }
+ return wrapper;
+}
+
+module.exports = createCurry;
diff --git a/node_modules/lodash/_createFind.js b/node_modules/lodash/_createFind.js
new file mode 100644
index 0000000..8859ff8
--- /dev/null
+++ b/node_modules/lodash/_createFind.js
@@ -0,0 +1,25 @@
+var baseIteratee = require('./_baseIteratee'),
+ isArrayLike = require('./isArrayLike'),
+ keys = require('./keys');
+
+/**
+ * Creates a `_.find` or `_.findLast` function.
+ *
+ * @private
+ * @param {Function} findIndexFunc The function to find the collection index.
+ * @returns {Function} Returns the new find function.
+ */
+function createFind(findIndexFunc) {
+ return function(collection, predicate, fromIndex) {
+ var iterable = Object(collection);
+ if (!isArrayLike(collection)) {
+ var iteratee = baseIteratee(predicate, 3);
+ collection = keys(collection);
+ predicate = function(key) { return iteratee(iterable[key], key, iterable); };
+ }
+ var index = findIndexFunc(collection, predicate, fromIndex);
+ return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
+ };
+}
+
+module.exports = createFind;
diff --git a/node_modules/lodash/_createFlow.js b/node_modules/lodash/_createFlow.js
new file mode 100644
index 0000000..baaddbf
--- /dev/null
+++ b/node_modules/lodash/_createFlow.js
@@ -0,0 +1,78 @@
+var LodashWrapper = require('./_LodashWrapper'),
+ flatRest = require('./_flatRest'),
+ getData = require('./_getData'),
+ getFuncName = require('./_getFuncName'),
+ isArray = require('./isArray'),
+ isLaziable = require('./_isLaziable');
+
+/** Error message constants. */
+var FUNC_ERROR_TEXT = 'Expected a function';
+
+/** Used to compose bitmasks for function metadata. */
+var WRAP_CURRY_FLAG = 8,
+ WRAP_PARTIAL_FLAG = 32,
+ WRAP_ARY_FLAG = 128,
+ WRAP_REARG_FLAG = 256;
+
+/**
+ * Creates a `_.flow` or `_.flowRight` function.
+ *
+ * @private
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new flow function.
+ */
+function createFlow(fromRight) {
+ return flatRest(function(funcs) {
+ var length = funcs.length,
+ index = length,
+ prereq = LodashWrapper.prototype.thru;
+
+ if (fromRight) {
+ funcs.reverse();
+ }
+ while (index--) {
+ var func = funcs[index];
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
+ var wrapper = new LodashWrapper([], true);
+ }
+ }
+ index = wrapper ? index : length;
+ while (++index < length) {
+ func = funcs[index];
+
+ var funcName = getFuncName(func),
+ data = funcName == 'wrapper' ? getData(func) : undefined;
+
+ if (data && isLaziable(data[0]) &&
+ data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&
+ !data[4].length && data[9] == 1
+ ) {
+ wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
+ } else {
+ wrapper = (func.length == 1 && isLaziable(func))
+ ? wrapper[funcName]()
+ : wrapper.thru(func);
+ }
+ }
+ return function() {
+ var args = arguments,
+ value = args[0];
+
+ if (wrapper && args.length == 1 && isArray(value)) {
+ return wrapper.plant(value).value();
+ }
+ var index = 0,
+ result = length ? funcs[index].apply(this, args) : value;
+
+ while (++index < length) {
+ result = funcs[index].call(this, result);
+ }
+ return result;
+ };
+ });
+}
+
+module.exports = createFlow;
diff --git a/node_modules/lodash/_createHybrid.js b/node_modules/lodash/_createHybrid.js
new file mode 100644
index 0000000..b671bd1
--- /dev/null
+++ b/node_modules/lodash/_createHybrid.js
@@ -0,0 +1,92 @@
+var composeArgs = require('./_composeArgs'),
+ composeArgsRight = require('./_composeArgsRight'),
+ countHolders = require('./_countHolders'),
+ createCtor = require('./_createCtor'),
+ createRecurry = require('./_createRecurry'),
+ getHolder = require('./_getHolder'),
+ reorder = require('./_reorder'),
+ replaceHolders = require('./_replaceHolders'),
+ root = require('./_root');
+
+/** Used to compose bitmasks for function metadata. */
+var WRAP_BIND_FLAG = 1,
+ WRAP_BIND_KEY_FLAG = 2,
+ WRAP_CURRY_FLAG = 8,
+ WRAP_CURRY_RIGHT_FLAG = 16,
+ WRAP_ARY_FLAG = 128,
+ WRAP_FLIP_FLAG = 512;
+
+/**
+ * Creates a function that wraps `func` to invoke it with optional `this`
+ * binding of `thisArg`, partial application, and currying.
+ *
+ * @private
+ * @param {Function|string} func The function or method name to wrap.
+ * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
+ * @param {*} [thisArg] The `this` binding of `func`.
+ * @param {Array} [partials] The arguments to prepend to those provided to
+ * the new function.
+ * @param {Array} [holders] The `partials` placeholder indexes.
+ * @param {Array} [partialsRight] The arguments to append to those provided
+ * to the new function.
+ * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
+ * @param {Array} [argPos] The argument positions of the new function.
+ * @param {number} [ary] The arity cap of `func`.
+ * @param {number} [arity] The arity of `func`.
+ * @returns {Function} Returns the new wrapped function.
+ */
+function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
+ var isAry = bitmask & WRAP_ARY_FLAG,
+ isBind = bitmask & WRAP_BIND_FLAG,
+ isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
+ isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
+ isFlip = bitmask & WRAP_FLIP_FLAG,
+ Ctor = isBindKey ? undefined : createCtor(func);
+
+ function wrapper() {
+ var length = arguments.length,
+ args = Array(length),
+ index = length;
+
+ while (index--) {
+ args[index] = arguments[index];
+ }
+ if (isCurried) {
+ var placeholder = getHolder(wrapper),
+ holdersCount = countHolders(args, placeholder);
+ }
+ if (partials) {
+ args = composeArgs(args, partials, holders, isCurried);
+ }
+ if (partialsRight) {
+ args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
+ }
+ length -= holdersCount;
+ if (isCurried && length < arity) {
+ var newHolders = replaceHolders(args, placeholder);
+ return createRecurry(
+ func, bitmask, createHybrid, wrapper.placeholder, thisArg,
+ args, newHolders, argPos, ary, arity - length
+ );
+ }
+ var thisBinding = isBind ? thisArg : this,
+ fn = isBindKey ? thisBinding[func] : func;
+
+ length = args.length;
+ if (argPos) {
+ args = reorder(args, argPos);
+ } else if (isFlip && length > 1) {
+ args.reverse();
+ }
+ if (isAry && ary < length) {
+ args.length = ary;
+ }
+ if (this && this !== root && this instanceof wrapper) {
+ fn = Ctor || createCtor(fn);
+ }
+ return fn.apply(thisBinding, args);
+ }
+ return wrapper;
+}
+
+module.exports = createHybrid;
diff --git a/node_modules/lodash/_createInverter.js b/node_modules/lodash/_createInverter.js
new file mode 100644
index 0000000..6c0c562
--- /dev/null
+++ b/node_modules/lodash/_createInverter.js
@@ -0,0 +1,17 @@
+var baseInverter = require('./_baseInverter');
+
+/**
+ * Creates a function like `_.invertBy`.
+ *
+ * @private
+ * @param {Function} setter The function to set accumulator values.
+ * @param {Function} toIteratee The function to resolve iteratees.
+ * @returns {Function} Returns the new inverter function.
+ */
+function createInverter(setter, toIteratee) {
+ return function(object, iteratee) {
+ return baseInverter(object, setter, toIteratee(iteratee), {});
+ };
+}
+
+module.exports = createInverter;
diff --git a/node_modules/lodash/_createMathOperation.js b/node_modules/lodash/_createMathOperation.js
new file mode 100644
index 0000000..f1e238a
--- /dev/null
+++ b/node_modules/lodash/_createMathOperation.js
@@ -0,0 +1,38 @@
+var baseToNumber = require('./_baseToNumber'),
+ baseToString = require('./_baseToString');
+
+/**
+ * Creates a function that performs a mathematical operation on two values.
+ *
+ * @private
+ * @param {Function} operator The function to perform the operation.
+ * @param {number} [defaultValue] The value used for `undefined` arguments.
+ * @returns {Function} Returns the new mathematical operation function.
+ */
+function createMathOperation(operator, defaultValue) {
+ return function(value, other) {
+ var result;
+ if (value === undefined && other === undefined) {
+ return defaultValue;
+ }
+ if (value !== undefined) {
+ result = value;
+ }
+ if (other !== undefined) {
+ if (result === undefined) {
+ return other;
+ }
+ if (typeof value == 'string' || typeof other == 'string') {
+ value = baseToString(value);
+ other = baseToString(other);
+ } else {
+ value = baseToNumber(value);
+ other = baseToNumber(other);
+ }
+ result = operator(value, other);
+ }
+ return result;
+ };
+}
+
+module.exports = createMathOperation;
diff --git a/node_modules/lodash/_createOver.js b/node_modules/lodash/_createOver.js
new file mode 100644
index 0000000..3b94551
--- /dev/null
+++ b/node_modules/lodash/_createOver.js
@@ -0,0 +1,27 @@
+var apply = require('./_apply'),
+ arrayMap = require('./_arrayMap'),
+ baseIteratee = require('./_baseIteratee'),
+ baseRest = require('./_baseRest'),
+ baseUnary = require('./_baseUnary'),
+ flatRest = require('./_flatRest');
+
+/**
+ * Creates a function like `_.over`.
+ *
+ * @private
+ * @param {Function} arrayFunc The function to iterate over iteratees.
+ * @returns {Function} Returns the new over function.
+ */
+function createOver(arrayFunc) {
+ return flatRest(function(iteratees) {
+ iteratees = arrayMap(iteratees, baseUnary(baseIteratee));
+ return baseRest(function(args) {
+ var thisArg = this;
+ return arrayFunc(iteratees, function(iteratee) {
+ return apply(iteratee, thisArg, args);
+ });
+ });
+ });
+}
+
+module.exports = createOver;
diff --git a/node_modules/lodash/_createPadding.js b/node_modules/lodash/_createPadding.js
new file mode 100644
index 0000000..2124612
--- /dev/null
+++ b/node_modules/lodash/_createPadding.js
@@ -0,0 +1,33 @@
+var baseRepeat = require('./_baseRepeat'),
+ baseToString = require('./_baseToString'),
+ castSlice = require('./_castSlice'),
+ hasUnicode = require('./_hasUnicode'),
+ stringSize = require('./_stringSize'),
+ stringToArray = require('./_stringToArray');
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeCeil = Math.ceil;
+
+/**
+ * Creates the padding for `string` based on `length`. The `chars` string
+ * is truncated if the number of characters exceeds `length`.
+ *
+ * @private
+ * @param {number} length The padding length.
+ * @param {string} [chars=' '] The string used as padding.
+ * @returns {string} Returns the padding for `string`.
+ */
+function createPadding(length, chars) {
+ chars = chars === undefined ? ' ' : baseToString(chars);
+
+ var charsLength = chars.length;
+ if (charsLength < 2) {
+ return charsLength ? baseRepeat(chars, length) : chars;
+ }
+ var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
+ return hasUnicode(chars)
+ ? castSlice(stringToArray(result), 0, length).join('')
+ : result.slice(0, length);
+}
+
+module.exports = createPadding;
diff --git a/node_modules/lodash/_createPartial.js b/node_modules/lodash/_createPartial.js
new file mode 100644
index 0000000..e16c248
--- /dev/null
+++ b/node_modules/lodash/_createPartial.js
@@ -0,0 +1,43 @@
+var apply = require('./_apply'),
+ createCtor = require('./_createCtor'),
+ root = require('./_root');
+
+/** Used to compose bitmasks for function metadata. */
+var WRAP_BIND_FLAG = 1;
+
+/**
+ * Creates a function that wraps `func` to invoke it with the `this` binding
+ * of `thisArg` and `partials` prepended to the arguments it receives.
+ *
+ * @private
+ * @param {Function} func The function to wrap.
+ * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
+ * @param {*} thisArg The `this` binding of `func`.
+ * @param {Array} partials The arguments to prepend to those provided to
+ * the new function.
+ * @returns {Function} Returns the new wrapped function.
+ */
+function createPartial(func, bitmask, thisArg, partials) {
+ var isBind = bitmask & WRAP_BIND_FLAG,
+ Ctor = createCtor(func);
+
+ function wrapper() {
+ var argsIndex = -1,
+ argsLength = arguments.length,
+ leftIndex = -1,
+ leftLength = partials.length,
+ args = Array(leftLength + argsLength),
+ fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
+
+ while (++leftIndex < leftLength) {
+ args[leftIndex] = partials[leftIndex];
+ }
+ while (argsLength--) {
+ args[leftIndex++] = arguments[++argsIndex];
+ }
+ return apply(fn, isBind ? thisArg : this, args);
+ }
+ return wrapper;
+}
+
+module.exports = createPartial;
diff --git a/node_modules/lodash/_createRange.js b/node_modules/lodash/_createRange.js
new file mode 100644
index 0000000..9f52c77
--- /dev/null
+++ b/node_modules/lodash/_createRange.js
@@ -0,0 +1,30 @@
+var baseRange = require('./_baseRange'),
+ isIterateeCall = require('./_isIterateeCall'),
+ toFinite = require('./toFinite');
+
+/**
+ * Creates a `_.range` or `_.rangeRight` function.
+ *
+ * @private
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new range function.
+ */
+function createRange(fromRight) {
+ return function(start, end, step) {
+ if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
+ end = step = undefined;
+ }
+ // Ensure the sign of `-0` is preserved.
+ start = toFinite(start);
+ if (end === undefined) {
+ end = start;
+ start = 0;
+ } else {
+ end = toFinite(end);
+ }
+ step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
+ return baseRange(start, end, step, fromRight);
+ };
+}
+
+module.exports = createRange;
diff --git a/node_modules/lodash/_createRecurry.js b/node_modules/lodash/_createRecurry.js
new file mode 100644
index 0000000..eb29fb2
--- /dev/null
+++ b/node_modules/lodash/_createRecurry.js
@@ -0,0 +1,56 @@
+var isLaziable = require('./_isLaziable'),
+ setData = require('./_setData'),
+ setWrapToString = require('./_setWrapToString');
+
+/** Used to compose bitmasks for function metadata. */
+var WRAP_BIND_FLAG = 1,
+ WRAP_BIND_KEY_FLAG = 2,
+ WRAP_CURRY_BOUND_FLAG = 4,
+ WRAP_CURRY_FLAG = 8,
+ WRAP_PARTIAL_FLAG = 32,
+ WRAP_PARTIAL_RIGHT_FLAG = 64;
+
+/**
+ * Creates a function that wraps `func` to continue currying.
+ *
+ * @private
+ * @param {Function} func The function to wrap.
+ * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
+ * @param {Function} wrapFunc The function to create the `func` wrapper.
+ * @param {*} placeholder The placeholder value.
+ * @param {*} [thisArg] The `this` binding of `func`.
+ * @param {Array} [partials] The arguments to prepend to those provided to
+ * the new function.
+ * @param {Array} [holders] The `partials` placeholder indexes.
+ * @param {Array} [argPos] The argument positions of the new function.
+ * @param {number} [ary] The arity cap of `func`.
+ * @param {number} [arity] The arity of `func`.
+ * @returns {Function} Returns the new wrapped function.
+ */
+function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
+ var isCurry = bitmask & WRAP_CURRY_FLAG,
+ newHolders = isCurry ? holders : undefined,
+ newHoldersRight = isCurry ? undefined : holders,
+ newPartials = isCurry ? partials : undefined,
+ newPartialsRight = isCurry ? undefined : partials;
+
+ bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
+ bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
+
+ if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
+ bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
+ }
+ var newData = [
+ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
+ newHoldersRight, argPos, ary, arity
+ ];
+
+ var result = wrapFunc.apply(undefined, newData);
+ if (isLaziable(func)) {
+ setData(result, newData);
+ }
+ result.placeholder = placeholder;
+ return setWrapToString(result, func, bitmask);
+}
+
+module.exports = createRecurry;
diff --git a/node_modules/lodash/_createRelationalOperation.js b/node_modules/lodash/_createRelationalOperation.js
new file mode 100644
index 0000000..a17c6b5
--- /dev/null
+++ b/node_modules/lodash/_createRelationalOperation.js
@@ -0,0 +1,20 @@
+var toNumber = require('./toNumber');
+
+/**
+ * Creates a function that performs a relational operation on two values.
+ *
+ * @private
+ * @param {Function} operator The function to perform the operation.
+ * @returns {Function} Returns the new relational operation function.
+ */
+function createRelationalOperation(operator) {
+ return function(value, other) {
+ if (!(typeof value == 'string' && typeof other == 'string')) {
+ value = toNumber(value);
+ other = toNumber(other);
+ }
+ return operator(value, other);
+ };
+}
+
+module.exports = createRelationalOperation;
diff --git a/node_modules/lodash/_createRound.js b/node_modules/lodash/_createRound.js
new file mode 100644
index 0000000..88be5df
--- /dev/null
+++ b/node_modules/lodash/_createRound.js
@@ -0,0 +1,35 @@
+var root = require('./_root'),
+ toInteger = require('./toInteger'),
+ toNumber = require('./toNumber'),
+ toString = require('./toString');
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeIsFinite = root.isFinite,
+ nativeMin = Math.min;
+
+/**
+ * Creates a function like `_.round`.
+ *
+ * @private
+ * @param {string} methodName The name of the `Math` method to use when rounding.
+ * @returns {Function} Returns the new round function.
+ */
+function createRound(methodName) {
+ var func = Math[methodName];
+ return function(number, precision) {
+ number = toNumber(number);
+ precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);
+ if (precision && nativeIsFinite(number)) {
+ // Shift with exponential notation to avoid floating-point issues.
+ // See [MDN](https://mdn.io/round#Examples) for more details.
+ var pair = (toString(number) + 'e').split('e'),
+ value = func(pair[0] + 'e' + (+pair[1] + precision));
+
+ pair = (toString(value) + 'e').split('e');
+ return +(pair[0] + 'e' + (+pair[1] - precision));
+ }
+ return func(number);
+ };
+}
+
+module.exports = createRound;
diff --git a/node_modules/lodash/_createSet.js b/node_modules/lodash/_createSet.js
new file mode 100644
index 0000000..0f644ee
--- /dev/null
+++ b/node_modules/lodash/_createSet.js
@@ -0,0 +1,19 @@
+var Set = require('./_Set'),
+ noop = require('./noop'),
+ setToArray = require('./_setToArray');
+
+/** Used as references for various `Number` constants. */
+var INFINITY = 1 / 0;
+
+/**
+ * Creates a set object of `values`.
+ *
+ * @private
+ * @param {Array} values The values to add to the set.
+ * @returns {Object} Returns the new set.
+ */
+var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
+ return new Set(values);
+};
+
+module.exports = createSet;
diff --git a/node_modules/lodash/_createToPairs.js b/node_modules/lodash/_createToPairs.js
new file mode 100644
index 0000000..568417a
--- /dev/null
+++ b/node_modules/lodash/_createToPairs.js
@@ -0,0 +1,30 @@
+var baseToPairs = require('./_baseToPairs'),
+ getTag = require('./_getTag'),
+ mapToArray = require('./_mapToArray'),
+ setToPairs = require('./_setToPairs');
+
+/** `Object#toString` result references. */
+var mapTag = '[object Map]',
+ setTag = '[object Set]';
+
+/**
+ * Creates a `_.toPairs` or `_.toPairsIn` function.
+ *
+ * @private
+ * @param {Function} keysFunc The function to get the keys of a given object.
+ * @returns {Function} Returns the new pairs function.
+ */
+function createToPairs(keysFunc) {
+ return function(object) {
+ var tag = getTag(object);
+ if (tag == mapTag) {
+ return mapToArray(object);
+ }
+ if (tag == setTag) {
+ return setToPairs(object);
+ }
+ return baseToPairs(object, keysFunc(object));
+ };
+}
+
+module.exports = createToPairs;
diff --git a/node_modules/lodash/_createWrap.js b/node_modules/lodash/_createWrap.js
new file mode 100644
index 0000000..33f0633
--- /dev/null
+++ b/node_modules/lodash/_createWrap.js
@@ -0,0 +1,106 @@
+var baseSetData = require('./_baseSetData'),
+ createBind = require('./_createBind'),
+ createCurry = require('./_createCurry'),
+ createHybrid = require('./_createHybrid'),
+ createPartial = require('./_createPartial'),
+ getData = require('./_getData'),
+ mergeData = require('./_mergeData'),
+ setData = require('./_setData'),
+ setWrapToString = require('./_setWrapToString'),
+ toInteger = require('./toInteger');
+
+/** Error message constants. */
+var FUNC_ERROR_TEXT = 'Expected a function';
+
+/** Used to compose bitmasks for function metadata. */
+var WRAP_BIND_FLAG = 1,
+ WRAP_BIND_KEY_FLAG = 2,
+ WRAP_CURRY_FLAG = 8,
+ WRAP_CURRY_RIGHT_FLAG = 16,
+ WRAP_PARTIAL_FLAG = 32,
+ WRAP_PARTIAL_RIGHT_FLAG = 64;
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeMax = Math.max;
+
+/**
+ * Creates a function that either curries or invokes `func` with optional
+ * `this` binding and partially applied arguments.
+ *
+ * @private
+ * @param {Function|string} func The function or method name to wrap.
+ * @param {number} bitmask The bitmask flags.
+ * 1 - `_.bind`
+ * 2 - `_.bindKey`
+ * 4 - `_.curry` or `_.curryRight` of a bound function
+ * 8 - `_.curry`
+ * 16 - `_.curryRight`
+ * 32 - `_.partial`
+ * 64 - `_.partialRight`
+ * 128 - `_.rearg`
+ * 256 - `_.ary`
+ * 512 - `_.flip`
+ * @param {*} [thisArg] The `this` binding of `func`.
+ * @param {Array} [partials] The arguments to be partially applied.
+ * @param {Array} [holders] The `partials` placeholder indexes.
+ * @param {Array} [argPos] The argument positions of the new function.
+ * @param {number} [ary] The arity cap of `func`.
+ * @param {number} [arity] The arity of `func`.
+ * @returns {Function} Returns the new wrapped function.
+ */
+function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
+ var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
+ if (!isBindKey && typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ var length = partials ? partials.length : 0;
+ if (!length) {
+ bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
+ partials = holders = undefined;
+ }
+ ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
+ arity = arity === undefined ? arity : toInteger(arity);
+ length -= holders ? holders.length : 0;
+
+ if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
+ var partialsRight = partials,
+ holdersRight = holders;
+
+ partials = holders = undefined;
+ }
+ var data = isBindKey ? undefined : getData(func);
+
+ var newData = [
+ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
+ argPos, ary, arity
+ ];
+
+ if (data) {
+ mergeData(newData, data);
+ }
+ func = newData[0];
+ bitmask = newData[1];
+ thisArg = newData[2];
+ partials = newData[3];
+ holders = newData[4];
+ arity = newData[9] = newData[9] === undefined
+ ? (isBindKey ? 0 : func.length)
+ : nativeMax(newData[9] - length, 0);
+
+ if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
+ bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
+ }
+ if (!bitmask || bitmask == WRAP_BIND_FLAG) {
+ var result = createBind(func, bitmask, thisArg);
+ } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
+ result = createCurry(func, bitmask, arity);
+ } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
+ result = createPartial(func, bitmask, thisArg, partials);
+ } else {
+ result = createHybrid.apply(undefined, newData);
+ }
+ var setter = data ? baseSetData : setData;
+ return setWrapToString(setter(result, newData), func, bitmask);
+}
+
+module.exports = createWrap;
diff --git a/node_modules/lodash/_customDefaultsAssignIn.js b/node_modules/lodash/_customDefaultsAssignIn.js
new file mode 100644
index 0000000..1f49e6f
--- /dev/null
+++ b/node_modules/lodash/_customDefaultsAssignIn.js
@@ -0,0 +1,29 @@
+var eq = require('./eq');
+
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/**
+ * Used by `_.defaults` to customize its `_.assignIn` use to assign properties
+ * of source objects to the destination object for all destination properties
+ * that resolve to `undefined`.
+ *
+ * @private
+ * @param {*} objValue The destination value.
+ * @param {*} srcValue The source value.
+ * @param {string} key The key of the property to assign.
+ * @param {Object} object The parent object of `objValue`.
+ * @returns {*} Returns the value to assign.
+ */
+function customDefaultsAssignIn(objValue, srcValue, key, object) {
+ if (objValue === undefined ||
+ (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
+ return srcValue;
+ }
+ return objValue;
+}
+
+module.exports = customDefaultsAssignIn;
diff --git a/node_modules/lodash/_customDefaultsMerge.js b/node_modules/lodash/_customDefaultsMerge.js
new file mode 100644
index 0000000..4cab317
--- /dev/null
+++ b/node_modules/lodash/_customDefaultsMerge.js
@@ -0,0 +1,28 @@
+var baseMerge = require('./_baseMerge'),
+ isObject = require('./isObject');
+
+/**
+ * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source
+ * objects into destination objects that are passed thru.
+ *
+ * @private
+ * @param {*} objValue The destination value.
+ * @param {*} srcValue The source value.
+ * @param {string} key The key of the property to merge.
+ * @param {Object} object The parent object of `objValue`.
+ * @param {Object} source The parent object of `srcValue`.
+ * @param {Object} [stack] Tracks traversed source values and their merged
+ * counterparts.
+ * @returns {*} Returns the value to assign.
+ */
+function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {
+ if (isObject(objValue) && isObject(srcValue)) {
+ // Recursively merge objects and arrays (susceptible to call stack limits).
+ stack.set(srcValue, objValue);
+ baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);
+ stack['delete'](srcValue);
+ }
+ return objValue;
+}
+
+module.exports = customDefaultsMerge;
diff --git a/node_modules/lodash/_customOmitClone.js b/node_modules/lodash/_customOmitClone.js
new file mode 100644
index 0000000..968db2e
--- /dev/null
+++ b/node_modules/lodash/_customOmitClone.js
@@ -0,0 +1,16 @@
+var isPlainObject = require('./isPlainObject');
+
+/**
+ * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
+ * objects.
+ *
+ * @private
+ * @param {*} value The value to inspect.
+ * @param {string} key The key of the property to inspect.
+ * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
+ */
+function customOmitClone(value) {
+ return isPlainObject(value) ? undefined : value;
+}
+
+module.exports = customOmitClone;
diff --git a/node_modules/lodash/_deburrLetter.js b/node_modules/lodash/_deburrLetter.js
new file mode 100644
index 0000000..3e531ed
--- /dev/null
+++ b/node_modules/lodash/_deburrLetter.js
@@ -0,0 +1,71 @@
+var basePropertyOf = require('./_basePropertyOf');
+
+/** Used to map Latin Unicode letters to basic Latin letters. */
+var deburredLetters = {
+ // Latin-1 Supplement block.
+ '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
+ '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
+ '\xc7': 'C', '\xe7': 'c',
+ '\xd0': 'D', '\xf0': 'd',
+ '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
+ '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
+ '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
+ '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
+ '\xd1': 'N', '\xf1': 'n',
+ '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
+ '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
+ '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
+ '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
+ '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
+ '\xc6': 'Ae', '\xe6': 'ae',
+ '\xde': 'Th', '\xfe': 'th',
+ '\xdf': 'ss',
+ // Latin Extended-A block.
+ '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
+ '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
+ '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
+ '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
+ '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
+ '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
+ '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
+ '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
+ '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
+ '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
+ '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
+ '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
+ '\u0134': 'J', '\u0135': 'j',
+ '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
+ '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
+ '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
+ '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
+ '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
+ '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
+ '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
+ '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
+ '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
+ '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
+ '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
+ '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
+ '\u0163': 't', '\u0165': 't', '\u0167': 't',
+ '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
+ '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
+ '\u0174': 'W', '\u0175': 'w',
+ '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
+ '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
+ '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
+ '\u0132': 'IJ', '\u0133': 'ij',
+ '\u0152': 'Oe', '\u0153': 'oe',
+ '\u0149': "'n", '\u017f': 's'
+};
+
+/**
+ * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
+ * letters to basic Latin letters.
+ *
+ * @private
+ * @param {string} letter The matched letter to deburr.
+ * @returns {string} Returns the deburred letter.
+ */
+var deburrLetter = basePropertyOf(deburredLetters);
+
+module.exports = deburrLetter;
diff --git a/node_modules/lodash/_defineProperty.js b/node_modules/lodash/_defineProperty.js
new file mode 100644
index 0000000..b6116d9
--- /dev/null
+++ b/node_modules/lodash/_defineProperty.js
@@ -0,0 +1,11 @@
+var getNative = require('./_getNative');
+
+var defineProperty = (function() {
+ try {
+ var func = getNative(Object, 'defineProperty');
+ func({}, '', {});
+ return func;
+ } catch (e) {}
+}());
+
+module.exports = defineProperty;
diff --git a/node_modules/lodash/_equalArrays.js b/node_modules/lodash/_equalArrays.js
new file mode 100644
index 0000000..824228c
--- /dev/null
+++ b/node_modules/lodash/_equalArrays.js
@@ -0,0 +1,84 @@
+var SetCache = require('./_SetCache'),
+ arraySome = require('./_arraySome'),
+ cacheHas = require('./_cacheHas');
+
+/** Used to compose bitmasks for value comparisons. */
+var COMPARE_PARTIAL_FLAG = 1,
+ COMPARE_UNORDERED_FLAG = 2;
+
+/**
+ * A specialized version of `baseIsEqualDeep` for arrays with support for
+ * partial deep comparisons.
+ *
+ * @private
+ * @param {Array} array The array to compare.
+ * @param {Array} other The other array to compare.
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
+ * @param {Function} customizer The function to customize comparisons.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Object} stack Tracks traversed `array` and `other` objects.
+ * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
+ */
+function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
+ arrLength = array.length,
+ othLength = other.length;
+
+ if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
+ return false;
+ }
+ // Check that cyclic values are equal.
+ var arrStacked = stack.get(array);
+ var othStacked = stack.get(other);
+ if (arrStacked && othStacked) {
+ return arrStacked == other && othStacked == array;
+ }
+ var index = -1,
+ result = true,
+ seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
+
+ stack.set(array, other);
+ stack.set(other, array);
+
+ // Ignore non-index properties.
+ while (++index < arrLength) {
+ var arrValue = array[index],
+ othValue = other[index];
+
+ if (customizer) {
+ var compared = isPartial
+ ? customizer(othValue, arrValue, index, other, array, stack)
+ : customizer(arrValue, othValue, index, array, other, stack);
+ }
+ if (compared !== undefined) {
+ if (compared) {
+ continue;
+ }
+ result = false;
+ break;
+ }
+ // Recursively compare arrays (susceptible to call stack limits).
+ if (seen) {
+ if (!arraySome(other, function(othValue, othIndex) {
+ if (!cacheHas(seen, othIndex) &&
+ (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
+ return seen.push(othIndex);
+ }
+ })) {
+ result = false;
+ break;
+ }
+ } else if (!(
+ arrValue === othValue ||
+ equalFunc(arrValue, othValue, bitmask, customizer, stack)
+ )) {
+ result = false;
+ break;
+ }
+ }
+ stack['delete'](array);
+ stack['delete'](other);
+ return result;
+}
+
+module.exports = equalArrays;
diff --git a/node_modules/lodash/_equalByTag.js b/node_modules/lodash/_equalByTag.js
new file mode 100644
index 0000000..71919e8
--- /dev/null
+++ b/node_modules/lodash/_equalByTag.js
@@ -0,0 +1,112 @@
+var Symbol = require('./_Symbol'),
+ Uint8Array = require('./_Uint8Array'),
+ eq = require('./eq'),
+ equalArrays = require('./_equalArrays'),
+ mapToArray = require('./_mapToArray'),
+ setToArray = require('./_setToArray');
+
+/** Used to compose bitmasks for value comparisons. */
+var COMPARE_PARTIAL_FLAG = 1,
+ COMPARE_UNORDERED_FLAG = 2;
+
+/** `Object#toString` result references. */
+var boolTag = '[object Boolean]',
+ dateTag = '[object Date]',
+ errorTag = '[object Error]',
+ mapTag = '[object Map]',
+ numberTag = '[object Number]',
+ regexpTag = '[object RegExp]',
+ setTag = '[object Set]',
+ stringTag = '[object String]',
+ symbolTag = '[object Symbol]';
+
+var arrayBufferTag = '[object ArrayBuffer]',
+ dataViewTag = '[object DataView]';
+
+/** Used to convert symbols to primitives and strings. */
+var symbolProto = Symbol ? Symbol.prototype : undefined,
+ symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;
+
+/**
+ * A specialized version of `baseIsEqualDeep` for comparing objects of
+ * the same `toStringTag`.
+ *
+ * **Note:** This function only supports comparing values with tags of
+ * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @param {string} tag The `toStringTag` of the objects to compare.
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
+ * @param {Function} customizer The function to customize comparisons.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Object} stack Tracks traversed `object` and `other` objects.
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ */
+function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
+ switch (tag) {
+ case dataViewTag:
+ if ((object.byteLength != other.byteLength) ||
+ (object.byteOffset != other.byteOffset)) {
+ return false;
+ }
+ object = object.buffer;
+ other = other.buffer;
+
+ case arrayBufferTag:
+ if ((object.byteLength != other.byteLength) ||
+ !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
+ return false;
+ }
+ return true;
+
+ case boolTag:
+ case dateTag:
+ case numberTag:
+ // Coerce booleans to `1` or `0` and dates to milliseconds.
+ // Invalid dates are coerced to `NaN`.
+ return eq(+object, +other);
+
+ case errorTag:
+ return object.name == other.name && object.message == other.message;
+
+ case regexpTag:
+ case stringTag:
+ // Coerce regexes to strings and treat strings, primitives and objects,
+ // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
+ // for more details.
+ return object == (other + '');
+
+ case mapTag:
+ var convert = mapToArray;
+
+ case setTag:
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
+ convert || (convert = setToArray);
+
+ if (object.size != other.size && !isPartial) {
+ return false;
+ }
+ // Assume cyclic values are equal.
+ var stacked = stack.get(object);
+ if (stacked) {
+ return stacked == other;
+ }
+ bitmask |= COMPARE_UNORDERED_FLAG;
+
+ // Recursively compare objects (susceptible to call stack limits).
+ stack.set(object, other);
+ var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
+ stack['delete'](object);
+ return result;
+
+ case symbolTag:
+ if (symbolValueOf) {
+ return symbolValueOf.call(object) == symbolValueOf.call(other);
+ }
+ }
+ return false;
+}
+
+module.exports = equalByTag;
diff --git a/node_modules/lodash/_equalObjects.js b/node_modules/lodash/_equalObjects.js
new file mode 100644
index 0000000..cdaacd2
--- /dev/null
+++ b/node_modules/lodash/_equalObjects.js
@@ -0,0 +1,90 @@
+var getAllKeys = require('./_getAllKeys');
+
+/** Used to compose bitmasks for value comparisons. */
+var COMPARE_PARTIAL_FLAG = 1;
+
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/**
+ * A specialized version of `baseIsEqualDeep` for objects with support for
+ * partial deep comparisons.
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
+ * @param {Function} customizer The function to customize comparisons.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Object} stack Tracks traversed `object` and `other` objects.
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ */
+function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
+ objProps = getAllKeys(object),
+ objLength = objProps.length,
+ othProps = getAllKeys(other),
+ othLength = othProps.length;
+
+ if (objLength != othLength && !isPartial) {
+ return false;
+ }
+ var index = objLength;
+ while (index--) {
+ var key = objProps[index];
+ if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
+ return false;
+ }
+ }
+ // Check that cyclic values are equal.
+ var objStacked = stack.get(object);
+ var othStacked = stack.get(other);
+ if (objStacked && othStacked) {
+ return objStacked == other && othStacked == object;
+ }
+ var result = true;
+ stack.set(object, other);
+ stack.set(other, object);
+
+ var skipCtor = isPartial;
+ while (++index < objLength) {
+ key = objProps[index];
+ var objValue = object[key],
+ othValue = other[key];
+
+ if (customizer) {
+ var compared = isPartial
+ ? customizer(othValue, objValue, key, other, object, stack)
+ : customizer(objValue, othValue, key, object, other, stack);
+ }
+ // Recursively compare objects (susceptible to call stack limits).
+ if (!(compared === undefined
+ ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
+ : compared
+ )) {
+ result = false;
+ break;
+ }
+ skipCtor || (skipCtor = key == 'constructor');
+ }
+ if (result && !skipCtor) {
+ var objCtor = object.constructor,
+ othCtor = other.constructor;
+
+ // Non `Object` object instances with different constructors are not equal.
+ if (objCtor != othCtor &&
+ ('constructor' in object && 'constructor' in other) &&
+ !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
+ typeof othCtor == 'function' && othCtor instanceof othCtor)) {
+ result = false;
+ }
+ }
+ stack['delete'](object);
+ stack['delete'](other);
+ return result;
+}
+
+module.exports = equalObjects;
diff --git a/node_modules/lodash/_escapeHtmlChar.js b/node_modules/lodash/_escapeHtmlChar.js
new file mode 100644
index 0000000..7ca68ee
--- /dev/null
+++ b/node_modules/lodash/_escapeHtmlChar.js
@@ -0,0 +1,21 @@
+var basePropertyOf = require('./_basePropertyOf');
+
+/** Used to map characters to HTML entities. */
+var htmlEscapes = {
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ "'": '''
+};
+
+/**
+ * Used by `_.escape` to convert characters to HTML entities.
+ *
+ * @private
+ * @param {string} chr The matched character to escape.
+ * @returns {string} Returns the escaped character.
+ */
+var escapeHtmlChar = basePropertyOf(htmlEscapes);
+
+module.exports = escapeHtmlChar;
diff --git a/node_modules/lodash/_escapeStringChar.js b/node_modules/lodash/_escapeStringChar.js
new file mode 100644
index 0000000..44eca96
--- /dev/null
+++ b/node_modules/lodash/_escapeStringChar.js
@@ -0,0 +1,22 @@
+/** Used to escape characters for inclusion in compiled string literals. */
+var stringEscapes = {
+ '\\': '\\',
+ "'": "'",
+ '\n': 'n',
+ '\r': 'r',
+ '\u2028': 'u2028',
+ '\u2029': 'u2029'
+};
+
+/**
+ * Used by `_.template` to escape characters for inclusion in compiled string literals.
+ *
+ * @private
+ * @param {string} chr The matched character to escape.
+ * @returns {string} Returns the escaped character.
+ */
+function escapeStringChar(chr) {
+ return '\\' + stringEscapes[chr];
+}
+
+module.exports = escapeStringChar;
diff --git a/node_modules/lodash/_flatRest.js b/node_modules/lodash/_flatRest.js
new file mode 100644
index 0000000..94ab6cc
--- /dev/null
+++ b/node_modules/lodash/_flatRest.js
@@ -0,0 +1,16 @@
+var flatten = require('./flatten'),
+ overRest = require('./_overRest'),
+ setToString = require('./_setToString');
+
+/**
+ * A specialized version of `baseRest` which flattens the rest array.
+ *
+ * @private
+ * @param {Function} func The function to apply a rest parameter to.
+ * @returns {Function} Returns the new function.
+ */
+function flatRest(func) {
+ return setToString(overRest(func, undefined, flatten), func + '');
+}
+
+module.exports = flatRest;
diff --git a/node_modules/lodash/_freeGlobal.js b/node_modules/lodash/_freeGlobal.js
new file mode 100644
index 0000000..bbec998
--- /dev/null
+++ b/node_modules/lodash/_freeGlobal.js
@@ -0,0 +1,4 @@
+/** Detect free variable `global` from Node.js. */
+var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
+
+module.exports = freeGlobal;
diff --git a/node_modules/lodash/_getAllKeys.js b/node_modules/lodash/_getAllKeys.js
new file mode 100644
index 0000000..a9ce699
--- /dev/null
+++ b/node_modules/lodash/_getAllKeys.js
@@ -0,0 +1,16 @@
+var baseGetAllKeys = require('./_baseGetAllKeys'),
+ getSymbols = require('./_getSymbols'),
+ keys = require('./keys');
+
+/**
+ * Creates an array of own enumerable property names and symbols of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names and symbols.
+ */
+function getAllKeys(object) {
+ return baseGetAllKeys(object, keys, getSymbols);
+}
+
+module.exports = getAllKeys;
diff --git a/node_modules/lodash/_getAllKeysIn.js b/node_modules/lodash/_getAllKeysIn.js
new file mode 100644
index 0000000..1b46678
--- /dev/null
+++ b/node_modules/lodash/_getAllKeysIn.js
@@ -0,0 +1,17 @@
+var baseGetAllKeys = require('./_baseGetAllKeys'),
+ getSymbolsIn = require('./_getSymbolsIn'),
+ keysIn = require('./keysIn');
+
+/**
+ * Creates an array of own and inherited enumerable property names and
+ * symbols of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names and symbols.
+ */
+function getAllKeysIn(object) {
+ return baseGetAllKeys(object, keysIn, getSymbolsIn);
+}
+
+module.exports = getAllKeysIn;
diff --git a/node_modules/lodash/_getData.js b/node_modules/lodash/_getData.js
new file mode 100644
index 0000000..a1fe7b7
--- /dev/null
+++ b/node_modules/lodash/_getData.js
@@ -0,0 +1,15 @@
+var metaMap = require('./_metaMap'),
+ noop = require('./noop');
+
+/**
+ * Gets metadata for `func`.
+ *
+ * @private
+ * @param {Function} func The function to query.
+ * @returns {*} Returns the metadata for `func`.
+ */
+var getData = !metaMap ? noop : function(func) {
+ return metaMap.get(func);
+};
+
+module.exports = getData;
diff --git a/node_modules/lodash/_getFuncName.js b/node_modules/lodash/_getFuncName.js
new file mode 100644
index 0000000..21e15b3
--- /dev/null
+++ b/node_modules/lodash/_getFuncName.js
@@ -0,0 +1,31 @@
+var realNames = require('./_realNames');
+
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/**
+ * Gets the name of `func`.
+ *
+ * @private
+ * @param {Function} func The function to query.
+ * @returns {string} Returns the function name.
+ */
+function getFuncName(func) {
+ var result = (func.name + ''),
+ array = realNames[result],
+ length = hasOwnProperty.call(realNames, result) ? array.length : 0;
+
+ while (length--) {
+ var data = array[length],
+ otherFunc = data.func;
+ if (otherFunc == null || otherFunc == func) {
+ return data.name;
+ }
+ }
+ return result;
+}
+
+module.exports = getFuncName;
diff --git a/node_modules/lodash/_getHolder.js b/node_modules/lodash/_getHolder.js
new file mode 100644
index 0000000..65e94b5
--- /dev/null
+++ b/node_modules/lodash/_getHolder.js
@@ -0,0 +1,13 @@
+/**
+ * Gets the argument placeholder value for `func`.
+ *
+ * @private
+ * @param {Function} func The function to inspect.
+ * @returns {*} Returns the placeholder value.
+ */
+function getHolder(func) {
+ var object = func;
+ return object.placeholder;
+}
+
+module.exports = getHolder;
diff --git a/node_modules/lodash/_getMapData.js b/node_modules/lodash/_getMapData.js
new file mode 100644
index 0000000..17f6303
--- /dev/null
+++ b/node_modules/lodash/_getMapData.js
@@ -0,0 +1,18 @@
+var isKeyable = require('./_isKeyable');
+
+/**
+ * Gets the data for `map`.
+ *
+ * @private
+ * @param {Object} map The map to query.
+ * @param {string} key The reference key.
+ * @returns {*} Returns the map data.
+ */
+function getMapData(map, key) {
+ var data = map.__data__;
+ return isKeyable(key)
+ ? data[typeof key == 'string' ? 'string' : 'hash']
+ : data.map;
+}
+
+module.exports = getMapData;
diff --git a/node_modules/lodash/_getMatchData.js b/node_modules/lodash/_getMatchData.js
new file mode 100644
index 0000000..2cc70f9
--- /dev/null
+++ b/node_modules/lodash/_getMatchData.js
@@ -0,0 +1,24 @@
+var isStrictComparable = require('./_isStrictComparable'),
+ keys = require('./keys');
+
+/**
+ * Gets the property names, values, and compare flags of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the match data of `object`.
+ */
+function getMatchData(object) {
+ var result = keys(object),
+ length = result.length;
+
+ while (length--) {
+ var key = result[length],
+ value = object[key];
+
+ result[length] = [key, value, isStrictComparable(value)];
+ }
+ return result;
+}
+
+module.exports = getMatchData;
diff --git a/node_modules/lodash/_getNative.js b/node_modules/lodash/_getNative.js
new file mode 100644
index 0000000..97a622b
--- /dev/null
+++ b/node_modules/lodash/_getNative.js
@@ -0,0 +1,17 @@
+var baseIsNative = require('./_baseIsNative'),
+ getValue = require('./_getValue');
+
+/**
+ * Gets the native function at `key` of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {string} key The key of the method to get.
+ * @returns {*} Returns the function if it's native, else `undefined`.
+ */
+function getNative(object, key) {
+ var value = getValue(object, key);
+ return baseIsNative(value) ? value : undefined;
+}
+
+module.exports = getNative;
diff --git a/node_modules/lodash/_getPrototype.js b/node_modules/lodash/_getPrototype.js
new file mode 100644
index 0000000..e808612
--- /dev/null
+++ b/node_modules/lodash/_getPrototype.js
@@ -0,0 +1,6 @@
+var overArg = require('./_overArg');
+
+/** Built-in value references. */
+var getPrototype = overArg(Object.getPrototypeOf, Object);
+
+module.exports = getPrototype;
diff --git a/node_modules/lodash/_getRawTag.js b/node_modules/lodash/_getRawTag.js
new file mode 100644
index 0000000..49a95c9
--- /dev/null
+++ b/node_modules/lodash/_getRawTag.js
@@ -0,0 +1,46 @@
+var Symbol = require('./_Symbol');
+
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/**
+ * Used to resolve the
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
+ * of values.
+ */
+var nativeObjectToString = objectProto.toString;
+
+/** Built-in value references. */
+var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
+
+/**
+ * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
+ *
+ * @private
+ * @param {*} value The value to query.
+ * @returns {string} Returns the raw `toStringTag`.
+ */
+function getRawTag(value) {
+ var isOwn = hasOwnProperty.call(value, symToStringTag),
+ tag = value[symToStringTag];
+
+ try {
+ value[symToStringTag] = undefined;
+ var unmasked = true;
+ } catch (e) {}
+
+ var result = nativeObjectToString.call(value);
+ if (unmasked) {
+ if (isOwn) {
+ value[symToStringTag] = tag;
+ } else {
+ delete value[symToStringTag];
+ }
+ }
+ return result;
+}
+
+module.exports = getRawTag;
diff --git a/node_modules/lodash/_getSymbols.js b/node_modules/lodash/_getSymbols.js
new file mode 100644
index 0000000..7d6eafe
--- /dev/null
+++ b/node_modules/lodash/_getSymbols.js
@@ -0,0 +1,30 @@
+var arrayFilter = require('./_arrayFilter'),
+ stubArray = require('./stubArray');
+
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Built-in value references. */
+var propertyIsEnumerable = objectProto.propertyIsEnumerable;
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeGetSymbols = Object.getOwnPropertySymbols;
+
+/**
+ * Creates an array of the own enumerable symbols of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of symbols.
+ */
+var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
+ if (object == null) {
+ return [];
+ }
+ object = Object(object);
+ return arrayFilter(nativeGetSymbols(object), function(symbol) {
+ return propertyIsEnumerable.call(object, symbol);
+ });
+};
+
+module.exports = getSymbols;
diff --git a/node_modules/lodash/_getSymbolsIn.js b/node_modules/lodash/_getSymbolsIn.js
new file mode 100644
index 0000000..cec0855
--- /dev/null
+++ b/node_modules/lodash/_getSymbolsIn.js
@@ -0,0 +1,25 @@
+var arrayPush = require('./_arrayPush'),
+ getPrototype = require('./_getPrototype'),
+ getSymbols = require('./_getSymbols'),
+ stubArray = require('./stubArray');
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeGetSymbols = Object.getOwnPropertySymbols;
+
+/**
+ * Creates an array of the own and inherited enumerable symbols of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of symbols.
+ */
+var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
+ var result = [];
+ while (object) {
+ arrayPush(result, getSymbols(object));
+ object = getPrototype(object);
+ }
+ return result;
+};
+
+module.exports = getSymbolsIn;
diff --git a/node_modules/lodash/_getTag.js b/node_modules/lodash/_getTag.js
new file mode 100644
index 0000000..deaf89d
--- /dev/null
+++ b/node_modules/lodash/_getTag.js
@@ -0,0 +1,58 @@
+var DataView = require('./_DataView'),
+ Map = require('./_Map'),
+ Promise = require('./_Promise'),
+ Set = require('./_Set'),
+ WeakMap = require('./_WeakMap'),
+ baseGetTag = require('./_baseGetTag'),
+ toSource = require('./_toSource');
+
+/** `Object#toString` result references. */
+var mapTag = '[object Map]',
+ objectTag = '[object Object]',
+ promiseTag = '[object Promise]',
+ setTag = '[object Set]',
+ weakMapTag = '[object WeakMap]';
+
+var dataViewTag = '[object DataView]';
+
+/** Used to detect maps, sets, and weakmaps. */
+var dataViewCtorString = toSource(DataView),
+ mapCtorString = toSource(Map),
+ promiseCtorString = toSource(Promise),
+ setCtorString = toSource(Set),
+ weakMapCtorString = toSource(WeakMap);
+
+/**
+ * Gets the `toStringTag` of `value`.
+ *
+ * @private
+ * @param {*} value The value to query.
+ * @returns {string} Returns the `toStringTag`.
+ */
+var getTag = baseGetTag;
+
+// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
+if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
+ (Map && getTag(new Map) != mapTag) ||
+ (Promise && getTag(Promise.resolve()) != promiseTag) ||
+ (Set && getTag(new Set) != setTag) ||
+ (WeakMap && getTag(new WeakMap) != weakMapTag)) {
+ getTag = function(value) {
+ var result = baseGetTag(value),
+ Ctor = result == objectTag ? value.constructor : undefined,
+ ctorString = Ctor ? toSource(Ctor) : '';
+
+ if (ctorString) {
+ switch (ctorString) {
+ case dataViewCtorString: return dataViewTag;
+ case mapCtorString: return mapTag;
+ case promiseCtorString: return promiseTag;
+ case setCtorString: return setTag;
+ case weakMapCtorString: return weakMapTag;
+ }
+ }
+ return result;
+ };
+}
+
+module.exports = getTag;
diff --git a/node_modules/lodash/_getValue.js b/node_modules/lodash/_getValue.js
new file mode 100644
index 0000000..5f7d773
--- /dev/null
+++ b/node_modules/lodash/_getValue.js
@@ -0,0 +1,13 @@
+/**
+ * Gets the value at `key` of `object`.
+ *
+ * @private
+ * @param {Object} [object] The object to query.
+ * @param {string} key The key of the property to get.
+ * @returns {*} Returns the property value.
+ */
+function getValue(object, key) {
+ return object == null ? undefined : object[key];
+}
+
+module.exports = getValue;
diff --git a/node_modules/lodash/_getView.js b/node_modules/lodash/_getView.js
new file mode 100644
index 0000000..df1e5d4
--- /dev/null
+++ b/node_modules/lodash/_getView.js
@@ -0,0 +1,33 @@
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeMax = Math.max,
+ nativeMin = Math.min;
+
+/**
+ * Gets the view, applying any `transforms` to the `start` and `end` positions.
+ *
+ * @private
+ * @param {number} start The start of the view.
+ * @param {number} end The end of the view.
+ * @param {Array} transforms The transformations to apply to the view.
+ * @returns {Object} Returns an object containing the `start` and `end`
+ * positions of the view.
+ */
+function getView(start, end, transforms) {
+ var index = -1,
+ length = transforms.length;
+
+ while (++index < length) {
+ var data = transforms[index],
+ size = data.size;
+
+ switch (data.type) {
+ case 'drop': start += size; break;
+ case 'dropRight': end -= size; break;
+ case 'take': end = nativeMin(end, start + size); break;
+ case 'takeRight': start = nativeMax(start, end - size); break;
+ }
+ }
+ return { 'start': start, 'end': end };
+}
+
+module.exports = getView;
diff --git a/node_modules/lodash/_getWrapDetails.js b/node_modules/lodash/_getWrapDetails.js
new file mode 100644
index 0000000..3bcc6e4
--- /dev/null
+++ b/node_modules/lodash/_getWrapDetails.js
@@ -0,0 +1,17 @@
+/** Used to match wrap detail comments. */
+var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
+ reSplitDetails = /,? & /;
+
+/**
+ * Extracts wrapper details from the `source` body comment.
+ *
+ * @private
+ * @param {string} source The source to inspect.
+ * @returns {Array} Returns the wrapper details.
+ */
+function getWrapDetails(source) {
+ var match = source.match(reWrapDetails);
+ return match ? match[1].split(reSplitDetails) : [];
+}
+
+module.exports = getWrapDetails;
diff --git a/node_modules/lodash/_hasPath.js b/node_modules/lodash/_hasPath.js
new file mode 100644
index 0000000..93dbde1
--- /dev/null
+++ b/node_modules/lodash/_hasPath.js
@@ -0,0 +1,39 @@
+var castPath = require('./_castPath'),
+ isArguments = require('./isArguments'),
+ isArray = require('./isArray'),
+ isIndex = require('./_isIndex'),
+ isLength = require('./isLength'),
+ toKey = require('./_toKey');
+
+/**
+ * Checks if `path` exists on `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path to check.
+ * @param {Function} hasFunc The function to check properties.
+ * @returns {boolean} Returns `true` if `path` exists, else `false`.
+ */
+function hasPath(object, path, hasFunc) {
+ path = castPath(path, object);
+
+ var index = -1,
+ length = path.length,
+ result = false;
+
+ while (++index < length) {
+ var key = toKey(path[index]);
+ if (!(result = object != null && hasFunc(object, key))) {
+ break;
+ }
+ object = object[key];
+ }
+ if (result || ++index != length) {
+ return result;
+ }
+ length = object == null ? 0 : object.length;
+ return !!length && isLength(length) && isIndex(key, length) &&
+ (isArray(object) || isArguments(object));
+}
+
+module.exports = hasPath;
diff --git a/node_modules/lodash/_hasUnicode.js b/node_modules/lodash/_hasUnicode.js
new file mode 100644
index 0000000..cb6ca15
--- /dev/null
+++ b/node_modules/lodash/_hasUnicode.js
@@ -0,0 +1,26 @@
+/** Used to compose unicode character classes. */
+var rsAstralRange = '\\ud800-\\udfff',
+ rsComboMarksRange = '\\u0300-\\u036f',
+ reComboHalfMarksRange = '\\ufe20-\\ufe2f',
+ rsComboSymbolsRange = '\\u20d0-\\u20ff',
+ rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
+ rsVarRange = '\\ufe0e\\ufe0f';
+
+/** Used to compose unicode capture groups. */
+var rsZWJ = '\\u200d';
+
+/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
+var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
+
+/**
+ * Checks if `string` contains Unicode symbols.
+ *
+ * @private
+ * @param {string} string The string to inspect.
+ * @returns {boolean} Returns `true` if a symbol is found, else `false`.
+ */
+function hasUnicode(string) {
+ return reHasUnicode.test(string);
+}
+
+module.exports = hasUnicode;
diff --git a/node_modules/lodash/_hasUnicodeWord.js b/node_modules/lodash/_hasUnicodeWord.js
new file mode 100644
index 0000000..95d52c4
--- /dev/null
+++ b/node_modules/lodash/_hasUnicodeWord.js
@@ -0,0 +1,15 @@
+/** Used to detect strings that need a more robust regexp to match words. */
+var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
+
+/**
+ * Checks if `string` contains a word composed of Unicode symbols.
+ *
+ * @private
+ * @param {string} string The string to inspect.
+ * @returns {boolean} Returns `true` if a word is found, else `false`.
+ */
+function hasUnicodeWord(string) {
+ return reHasUnicodeWord.test(string);
+}
+
+module.exports = hasUnicodeWord;
diff --git a/node_modules/lodash/_hashClear.js b/node_modules/lodash/_hashClear.js
new file mode 100644
index 0000000..5d4b70c
--- /dev/null
+++ b/node_modules/lodash/_hashClear.js
@@ -0,0 +1,15 @@
+var nativeCreate = require('./_nativeCreate');
+
+/**
+ * Removes all key-value entries from the hash.
+ *
+ * @private
+ * @name clear
+ * @memberOf Hash
+ */
+function hashClear() {
+ this.__data__ = nativeCreate ? nativeCreate(null) : {};
+ this.size = 0;
+}
+
+module.exports = hashClear;
diff --git a/node_modules/lodash/_hashDelete.js b/node_modules/lodash/_hashDelete.js
new file mode 100644
index 0000000..ea9dabf
--- /dev/null
+++ b/node_modules/lodash/_hashDelete.js
@@ -0,0 +1,17 @@
+/**
+ * Removes `key` and its value from the hash.
+ *
+ * @private
+ * @name delete
+ * @memberOf Hash
+ * @param {Object} hash The hash to modify.
+ * @param {string} key The key of the value to remove.
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
+ */
+function hashDelete(key) {
+ var result = this.has(key) && delete this.__data__[key];
+ this.size -= result ? 1 : 0;
+ return result;
+}
+
+module.exports = hashDelete;
diff --git a/node_modules/lodash/_hashGet.js b/node_modules/lodash/_hashGet.js
new file mode 100644
index 0000000..1fc2f34
--- /dev/null
+++ b/node_modules/lodash/_hashGet.js
@@ -0,0 +1,30 @@
+var nativeCreate = require('./_nativeCreate');
+
+/** Used to stand-in for `undefined` hash values. */
+var HASH_UNDEFINED = '__lodash_hash_undefined__';
+
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/**
+ * Gets the hash value for `key`.
+ *
+ * @private
+ * @name get
+ * @memberOf Hash
+ * @param {string} key The key of the value to get.
+ * @returns {*} Returns the entry value.
+ */
+function hashGet(key) {
+ var data = this.__data__;
+ if (nativeCreate) {
+ var result = data[key];
+ return result === HASH_UNDEFINED ? undefined : result;
+ }
+ return hasOwnProperty.call(data, key) ? data[key] : undefined;
+}
+
+module.exports = hashGet;
diff --git a/node_modules/lodash/_hashHas.js b/node_modules/lodash/_hashHas.js
new file mode 100644
index 0000000..281a551
--- /dev/null
+++ b/node_modules/lodash/_hashHas.js
@@ -0,0 +1,23 @@
+var nativeCreate = require('./_nativeCreate');
+
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/**
+ * Checks if a hash value for `key` exists.
+ *
+ * @private
+ * @name has
+ * @memberOf Hash
+ * @param {string} key The key of the entry to check.
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
+ */
+function hashHas(key) {
+ var data = this.__data__;
+ return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
+}
+
+module.exports = hashHas;
diff --git a/node_modules/lodash/_hashSet.js b/node_modules/lodash/_hashSet.js
new file mode 100644
index 0000000..e105528
--- /dev/null
+++ b/node_modules/lodash/_hashSet.js
@@ -0,0 +1,23 @@
+var nativeCreate = require('./_nativeCreate');
+
+/** Used to stand-in for `undefined` hash values. */
+var HASH_UNDEFINED = '__lodash_hash_undefined__';
+
+/**
+ * Sets the hash `key` to `value`.
+ *
+ * @private
+ * @name set
+ * @memberOf Hash
+ * @param {string} key The key of the value to set.
+ * @param {*} value The value to set.
+ * @returns {Object} Returns the hash instance.
+ */
+function hashSet(key, value) {
+ var data = this.__data__;
+ this.size += this.has(key) ? 0 : 1;
+ data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
+ return this;
+}
+
+module.exports = hashSet;
diff --git a/node_modules/lodash/_initCloneArray.js b/node_modules/lodash/_initCloneArray.js
new file mode 100644
index 0000000..078c15a
--- /dev/null
+++ b/node_modules/lodash/_initCloneArray.js
@@ -0,0 +1,26 @@
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/**
+ * Initializes an array clone.
+ *
+ * @private
+ * @param {Array} array The array to clone.
+ * @returns {Array} Returns the initialized clone.
+ */
+function initCloneArray(array) {
+ var length = array.length,
+ result = new array.constructor(length);
+
+ // Add properties assigned by `RegExp#exec`.
+ if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
+ result.index = array.index;
+ result.input = array.input;
+ }
+ return result;
+}
+
+module.exports = initCloneArray;
diff --git a/node_modules/lodash/_initCloneByTag.js b/node_modules/lodash/_initCloneByTag.js
new file mode 100644
index 0000000..f69a008
--- /dev/null
+++ b/node_modules/lodash/_initCloneByTag.js
@@ -0,0 +1,77 @@
+var cloneArrayBuffer = require('./_cloneArrayBuffer'),
+ cloneDataView = require('./_cloneDataView'),
+ cloneRegExp = require('./_cloneRegExp'),
+ cloneSymbol = require('./_cloneSymbol'),
+ cloneTypedArray = require('./_cloneTypedArray');
+
+/** `Object#toString` result references. */
+var boolTag = '[object Boolean]',
+ dateTag = '[object Date]',
+ mapTag = '[object Map]',
+ numberTag = '[object Number]',
+ regexpTag = '[object RegExp]',
+ setTag = '[object Set]',
+ stringTag = '[object String]',
+ symbolTag = '[object Symbol]';
+
+var arrayBufferTag = '[object ArrayBuffer]',
+ dataViewTag = '[object DataView]',
+ float32Tag = '[object Float32Array]',
+ float64Tag = '[object Float64Array]',
+ int8Tag = '[object Int8Array]',
+ int16Tag = '[object Int16Array]',
+ int32Tag = '[object Int32Array]',
+ uint8Tag = '[object Uint8Array]',
+ uint8ClampedTag = '[object Uint8ClampedArray]',
+ uint16Tag = '[object Uint16Array]',
+ uint32Tag = '[object Uint32Array]';
+
+/**
+ * Initializes an object clone based on its `toStringTag`.
+ *
+ * **Note:** This function only supports cloning values with tags of
+ * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
+ *
+ * @private
+ * @param {Object} object The object to clone.
+ * @param {string} tag The `toStringTag` of the object to clone.
+ * @param {boolean} [isDeep] Specify a deep clone.
+ * @returns {Object} Returns the initialized clone.
+ */
+function initCloneByTag(object, tag, isDeep) {
+ var Ctor = object.constructor;
+ switch (tag) {
+ case arrayBufferTag:
+ return cloneArrayBuffer(object);
+
+ case boolTag:
+ case dateTag:
+ return new Ctor(+object);
+
+ case dataViewTag:
+ return cloneDataView(object, isDeep);
+
+ case float32Tag: case float64Tag:
+ case int8Tag: case int16Tag: case int32Tag:
+ case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
+ return cloneTypedArray(object, isDeep);
+
+ case mapTag:
+ return new Ctor;
+
+ case numberTag:
+ case stringTag:
+ return new Ctor(object);
+
+ case regexpTag:
+ return cloneRegExp(object);
+
+ case setTag:
+ return new Ctor;
+
+ case symbolTag:
+ return cloneSymbol(object);
+ }
+}
+
+module.exports = initCloneByTag;
diff --git a/node_modules/lodash/_initCloneObject.js b/node_modules/lodash/_initCloneObject.js
new file mode 100644
index 0000000..5a13e64
--- /dev/null
+++ b/node_modules/lodash/_initCloneObject.js
@@ -0,0 +1,18 @@
+var baseCreate = require('./_baseCreate'),
+ getPrototype = require('./_getPrototype'),
+ isPrototype = require('./_isPrototype');
+
+/**
+ * Initializes an object clone.
+ *
+ * @private
+ * @param {Object} object The object to clone.
+ * @returns {Object} Returns the initialized clone.
+ */
+function initCloneObject(object) {
+ return (typeof object.constructor == 'function' && !isPrototype(object))
+ ? baseCreate(getPrototype(object))
+ : {};
+}
+
+module.exports = initCloneObject;
diff --git a/node_modules/lodash/_insertWrapDetails.js b/node_modules/lodash/_insertWrapDetails.js
new file mode 100644
index 0000000..e790808
--- /dev/null
+++ b/node_modules/lodash/_insertWrapDetails.js
@@ -0,0 +1,23 @@
+/** Used to match wrap detail comments. */
+var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;
+
+/**
+ * Inserts wrapper `details` in a comment at the top of the `source` body.
+ *
+ * @private
+ * @param {string} source The source to modify.
+ * @returns {Array} details The details to insert.
+ * @returns {string} Returns the modified source.
+ */
+function insertWrapDetails(source, details) {
+ var length = details.length;
+ if (!length) {
+ return source;
+ }
+ var lastIndex = length - 1;
+ details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
+ details = details.join(length > 2 ? ', ' : ' ');
+ return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
+}
+
+module.exports = insertWrapDetails;
diff --git a/node_modules/lodash/_isFlattenable.js b/node_modules/lodash/_isFlattenable.js
new file mode 100644
index 0000000..4cc2c24
--- /dev/null
+++ b/node_modules/lodash/_isFlattenable.js
@@ -0,0 +1,20 @@
+var Symbol = require('./_Symbol'),
+ isArguments = require('./isArguments'),
+ isArray = require('./isArray');
+
+/** Built-in value references. */
+var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined;
+
+/**
+ * Checks if `value` is a flattenable `arguments` object or array.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
+ */
+function isFlattenable(value) {
+ return isArray(value) || isArguments(value) ||
+ !!(spreadableSymbol && value && value[spreadableSymbol]);
+}
+
+module.exports = isFlattenable;
diff --git a/node_modules/lodash/_isIndex.js b/node_modules/lodash/_isIndex.js
new file mode 100644
index 0000000..061cd39
--- /dev/null
+++ b/node_modules/lodash/_isIndex.js
@@ -0,0 +1,25 @@
+/** Used as references for various `Number` constants. */
+var MAX_SAFE_INTEGER = 9007199254740991;
+
+/** Used to detect unsigned integer values. */
+var reIsUint = /^(?:0|[1-9]\d*)$/;
+
+/**
+ * Checks if `value` is a valid array-like index.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
+ * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
+ */
+function isIndex(value, length) {
+ var type = typeof value;
+ length = length == null ? MAX_SAFE_INTEGER : length;
+
+ return !!length &&
+ (type == 'number' ||
+ (type != 'symbol' && reIsUint.test(value))) &&
+ (value > -1 && value % 1 == 0 && value < length);
+}
+
+module.exports = isIndex;
diff --git a/node_modules/lodash/_isIterateeCall.js b/node_modules/lodash/_isIterateeCall.js
new file mode 100644
index 0000000..a0bb5a9
--- /dev/null
+++ b/node_modules/lodash/_isIterateeCall.js
@@ -0,0 +1,30 @@
+var eq = require('./eq'),
+ isArrayLike = require('./isArrayLike'),
+ isIndex = require('./_isIndex'),
+ isObject = require('./isObject');
+
+/**
+ * Checks if the given arguments are from an iteratee call.
+ *
+ * @private
+ * @param {*} value The potential iteratee value argument.
+ * @param {*} index The potential iteratee index or key argument.
+ * @param {*} object The potential iteratee object argument.
+ * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
+ * else `false`.
+ */
+function isIterateeCall(value, index, object) {
+ if (!isObject(object)) {
+ return false;
+ }
+ var type = typeof index;
+ if (type == 'number'
+ ? (isArrayLike(object) && isIndex(index, object.length))
+ : (type == 'string' && index in object)
+ ) {
+ return eq(object[index], value);
+ }
+ return false;
+}
+
+module.exports = isIterateeCall;
diff --git a/node_modules/lodash/_isKey.js b/node_modules/lodash/_isKey.js
new file mode 100644
index 0000000..ff08b06
--- /dev/null
+++ b/node_modules/lodash/_isKey.js
@@ -0,0 +1,29 @@
+var isArray = require('./isArray'),
+ isSymbol = require('./isSymbol');
+
+/** Used to match property names within property paths. */
+var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
+ reIsPlainProp = /^\w*$/;
+
+/**
+ * Checks if `value` is a property name and not a property path.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @param {Object} [object] The object to query keys on.
+ * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
+ */
+function isKey(value, object) {
+ if (isArray(value)) {
+ return false;
+ }
+ var type = typeof value;
+ if (type == 'number' || type == 'symbol' || type == 'boolean' ||
+ value == null || isSymbol(value)) {
+ return true;
+ }
+ return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
+ (object != null && value in Object(object));
+}
+
+module.exports = isKey;
diff --git a/node_modules/lodash/_isKeyable.js b/node_modules/lodash/_isKeyable.js
new file mode 100644
index 0000000..39f1828
--- /dev/null
+++ b/node_modules/lodash/_isKeyable.js
@@ -0,0 +1,15 @@
+/**
+ * Checks if `value` is suitable for use as unique object key.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
+ */
+function isKeyable(value) {
+ var type = typeof value;
+ return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
+ ? (value !== '__proto__')
+ : (value === null);
+}
+
+module.exports = isKeyable;
diff --git a/node_modules/lodash/_isLaziable.js b/node_modules/lodash/_isLaziable.js
new file mode 100644
index 0000000..a57c4f2
--- /dev/null
+++ b/node_modules/lodash/_isLaziable.js
@@ -0,0 +1,28 @@
+var LazyWrapper = require('./_LazyWrapper'),
+ getData = require('./_getData'),
+ getFuncName = require('./_getFuncName'),
+ lodash = require('./wrapperLodash');
+
+/**
+ * Checks if `func` has a lazy counterpart.
+ *
+ * @private
+ * @param {Function} func The function to check.
+ * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
+ * else `false`.
+ */
+function isLaziable(func) {
+ var funcName = getFuncName(func),
+ other = lodash[funcName];
+
+ if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
+ return false;
+ }
+ if (func === other) {
+ return true;
+ }
+ var data = getData(other);
+ return !!data && func === data[0];
+}
+
+module.exports = isLaziable;
diff --git a/node_modules/lodash/_isMaskable.js b/node_modules/lodash/_isMaskable.js
new file mode 100644
index 0000000..eb98d09
--- /dev/null
+++ b/node_modules/lodash/_isMaskable.js
@@ -0,0 +1,14 @@
+var coreJsData = require('./_coreJsData'),
+ isFunction = require('./isFunction'),
+ stubFalse = require('./stubFalse');
+
+/**
+ * Checks if `func` is capable of being masked.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `func` is maskable, else `false`.
+ */
+var isMaskable = coreJsData ? isFunction : stubFalse;
+
+module.exports = isMaskable;
diff --git a/node_modules/lodash/_isMasked.js b/node_modules/lodash/_isMasked.js
new file mode 100644
index 0000000..4b0f21b
--- /dev/null
+++ b/node_modules/lodash/_isMasked.js
@@ -0,0 +1,20 @@
+var coreJsData = require('./_coreJsData');
+
+/** Used to detect methods masquerading as native. */
+var maskSrcKey = (function() {
+ var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
+ return uid ? ('Symbol(src)_1.' + uid) : '';
+}());
+
+/**
+ * Checks if `func` has its source masked.
+ *
+ * @private
+ * @param {Function} func The function to check.
+ * @returns {boolean} Returns `true` if `func` is masked, else `false`.
+ */
+function isMasked(func) {
+ return !!maskSrcKey && (maskSrcKey in func);
+}
+
+module.exports = isMasked;
diff --git a/node_modules/lodash/_isPrototype.js b/node_modules/lodash/_isPrototype.js
new file mode 100644
index 0000000..0f29498
--- /dev/null
+++ b/node_modules/lodash/_isPrototype.js
@@ -0,0 +1,18 @@
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/**
+ * Checks if `value` is likely a prototype object.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
+ */
+function isPrototype(value) {
+ var Ctor = value && value.constructor,
+ proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
+
+ return value === proto;
+}
+
+module.exports = isPrototype;
diff --git a/node_modules/lodash/_isStrictComparable.js b/node_modules/lodash/_isStrictComparable.js
new file mode 100644
index 0000000..b59f40b
--- /dev/null
+++ b/node_modules/lodash/_isStrictComparable.js
@@ -0,0 +1,15 @@
+var isObject = require('./isObject');
+
+/**
+ * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` if suitable for strict
+ * equality comparisons, else `false`.
+ */
+function isStrictComparable(value) {
+ return value === value && !isObject(value);
+}
+
+module.exports = isStrictComparable;
diff --git a/node_modules/lodash/_iteratorToArray.js b/node_modules/lodash/_iteratorToArray.js
new file mode 100644
index 0000000..4768566
--- /dev/null
+++ b/node_modules/lodash/_iteratorToArray.js
@@ -0,0 +1,18 @@
+/**
+ * Converts `iterator` to an array.
+ *
+ * @private
+ * @param {Object} iterator The iterator to convert.
+ * @returns {Array} Returns the converted array.
+ */
+function iteratorToArray(iterator) {
+ var data,
+ result = [];
+
+ while (!(data = iterator.next()).done) {
+ result.push(data.value);
+ }
+ return result;
+}
+
+module.exports = iteratorToArray;
diff --git a/node_modules/lodash/_lazyClone.js b/node_modules/lodash/_lazyClone.js
new file mode 100644
index 0000000..d8a51f8
--- /dev/null
+++ b/node_modules/lodash/_lazyClone.js
@@ -0,0 +1,23 @@
+var LazyWrapper = require('./_LazyWrapper'),
+ copyArray = require('./_copyArray');
+
+/**
+ * Creates a clone of the lazy wrapper object.
+ *
+ * @private
+ * @name clone
+ * @memberOf LazyWrapper
+ * @returns {Object} Returns the cloned `LazyWrapper` object.
+ */
+function lazyClone() {
+ var result = new LazyWrapper(this.__wrapped__);
+ result.__actions__ = copyArray(this.__actions__);
+ result.__dir__ = this.__dir__;
+ result.__filtered__ = this.__filtered__;
+ result.__iteratees__ = copyArray(this.__iteratees__);
+ result.__takeCount__ = this.__takeCount__;
+ result.__views__ = copyArray(this.__views__);
+ return result;
+}
+
+module.exports = lazyClone;
diff --git a/node_modules/lodash/_lazyReverse.js b/node_modules/lodash/_lazyReverse.js
new file mode 100644
index 0000000..c5b5219
--- /dev/null
+++ b/node_modules/lodash/_lazyReverse.js
@@ -0,0 +1,23 @@
+var LazyWrapper = require('./_LazyWrapper');
+
+/**
+ * Reverses the direction of lazy iteration.
+ *
+ * @private
+ * @name reverse
+ * @memberOf LazyWrapper
+ * @returns {Object} Returns the new reversed `LazyWrapper` object.
+ */
+function lazyReverse() {
+ if (this.__filtered__) {
+ var result = new LazyWrapper(this);
+ result.__dir__ = -1;
+ result.__filtered__ = true;
+ } else {
+ result = this.clone();
+ result.__dir__ *= -1;
+ }
+ return result;
+}
+
+module.exports = lazyReverse;
diff --git a/node_modules/lodash/_lazyValue.js b/node_modules/lodash/_lazyValue.js
new file mode 100644
index 0000000..371ca8d
--- /dev/null
+++ b/node_modules/lodash/_lazyValue.js
@@ -0,0 +1,69 @@
+var baseWrapperValue = require('./_baseWrapperValue'),
+ getView = require('./_getView'),
+ isArray = require('./isArray');
+
+/** Used to indicate the type of lazy iteratees. */
+var LAZY_FILTER_FLAG = 1,
+ LAZY_MAP_FLAG = 2;
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeMin = Math.min;
+
+/**
+ * Extracts the unwrapped value from its lazy wrapper.
+ *
+ * @private
+ * @name value
+ * @memberOf LazyWrapper
+ * @returns {*} Returns the unwrapped value.
+ */
+function lazyValue() {
+ var array = this.__wrapped__.value(),
+ dir = this.__dir__,
+ isArr = isArray(array),
+ isRight = dir < 0,
+ arrLength = isArr ? array.length : 0,
+ view = getView(0, arrLength, this.__views__),
+ start = view.start,
+ end = view.end,
+ length = end - start,
+ index = isRight ? end : (start - 1),
+ iteratees = this.__iteratees__,
+ iterLength = iteratees.length,
+ resIndex = 0,
+ takeCount = nativeMin(length, this.__takeCount__);
+
+ if (!isArr || (!isRight && arrLength == length && takeCount == length)) {
+ return baseWrapperValue(array, this.__actions__);
+ }
+ var result = [];
+
+ outer:
+ while (length-- && resIndex < takeCount) {
+ index += dir;
+
+ var iterIndex = -1,
+ value = array[index];
+
+ while (++iterIndex < iterLength) {
+ var data = iteratees[iterIndex],
+ iteratee = data.iteratee,
+ type = data.type,
+ computed = iteratee(value);
+
+ if (type == LAZY_MAP_FLAG) {
+ value = computed;
+ } else if (!computed) {
+ if (type == LAZY_FILTER_FLAG) {
+ continue outer;
+ } else {
+ break outer;
+ }
+ }
+ }
+ result[resIndex++] = value;
+ }
+ return result;
+}
+
+module.exports = lazyValue;
diff --git a/node_modules/lodash/_listCacheClear.js b/node_modules/lodash/_listCacheClear.js
new file mode 100644
index 0000000..acbe39a
--- /dev/null
+++ b/node_modules/lodash/_listCacheClear.js
@@ -0,0 +1,13 @@
+/**
+ * Removes all key-value entries from the list cache.
+ *
+ * @private
+ * @name clear
+ * @memberOf ListCache
+ */
+function listCacheClear() {
+ this.__data__ = [];
+ this.size = 0;
+}
+
+module.exports = listCacheClear;
diff --git a/node_modules/lodash/_listCacheDelete.js b/node_modules/lodash/_listCacheDelete.js
new file mode 100644
index 0000000..b1384ad
--- /dev/null
+++ b/node_modules/lodash/_listCacheDelete.js
@@ -0,0 +1,35 @@
+var assocIndexOf = require('./_assocIndexOf');
+
+/** Used for built-in method references. */
+var arrayProto = Array.prototype;
+
+/** Built-in value references. */
+var splice = arrayProto.splice;
+
+/**
+ * Removes `key` and its value from the list cache.
+ *
+ * @private
+ * @name delete
+ * @memberOf ListCache
+ * @param {string} key The key of the value to remove.
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
+ */
+function listCacheDelete(key) {
+ var data = this.__data__,
+ index = assocIndexOf(data, key);
+
+ if (index < 0) {
+ return false;
+ }
+ var lastIndex = data.length - 1;
+ if (index == lastIndex) {
+ data.pop();
+ } else {
+ splice.call(data, index, 1);
+ }
+ --this.size;
+ return true;
+}
+
+module.exports = listCacheDelete;
diff --git a/node_modules/lodash/_listCacheGet.js b/node_modules/lodash/_listCacheGet.js
new file mode 100644
index 0000000..f8192fc
--- /dev/null
+++ b/node_modules/lodash/_listCacheGet.js
@@ -0,0 +1,19 @@
+var assocIndexOf = require('./_assocIndexOf');
+
+/**
+ * Gets the list cache value for `key`.
+ *
+ * @private
+ * @name get
+ * @memberOf ListCache
+ * @param {string} key The key of the value to get.
+ * @returns {*} Returns the entry value.
+ */
+function listCacheGet(key) {
+ var data = this.__data__,
+ index = assocIndexOf(data, key);
+
+ return index < 0 ? undefined : data[index][1];
+}
+
+module.exports = listCacheGet;
diff --git a/node_modules/lodash/_listCacheHas.js b/node_modules/lodash/_listCacheHas.js
new file mode 100644
index 0000000..2adf671
--- /dev/null
+++ b/node_modules/lodash/_listCacheHas.js
@@ -0,0 +1,16 @@
+var assocIndexOf = require('./_assocIndexOf');
+
+/**
+ * Checks if a list cache value for `key` exists.
+ *
+ * @private
+ * @name has
+ * @memberOf ListCache
+ * @param {string} key The key of the entry to check.
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
+ */
+function listCacheHas(key) {
+ return assocIndexOf(this.__data__, key) > -1;
+}
+
+module.exports = listCacheHas;
diff --git a/node_modules/lodash/_listCacheSet.js b/node_modules/lodash/_listCacheSet.js
new file mode 100644
index 0000000..5855c95
--- /dev/null
+++ b/node_modules/lodash/_listCacheSet.js
@@ -0,0 +1,26 @@
+var assocIndexOf = require('./_assocIndexOf');
+
+/**
+ * Sets the list cache `key` to `value`.
+ *
+ * @private
+ * @name set
+ * @memberOf ListCache
+ * @param {string} key The key of the value to set.
+ * @param {*} value The value to set.
+ * @returns {Object} Returns the list cache instance.
+ */
+function listCacheSet(key, value) {
+ var data = this.__data__,
+ index = assocIndexOf(data, key);
+
+ if (index < 0) {
+ ++this.size;
+ data.push([key, value]);
+ } else {
+ data[index][1] = value;
+ }
+ return this;
+}
+
+module.exports = listCacheSet;
diff --git a/node_modules/lodash/_mapCacheClear.js b/node_modules/lodash/_mapCacheClear.js
new file mode 100644
index 0000000..bc9ca20
--- /dev/null
+++ b/node_modules/lodash/_mapCacheClear.js
@@ -0,0 +1,21 @@
+var Hash = require('./_Hash'),
+ ListCache = require('./_ListCache'),
+ Map = require('./_Map');
+
+/**
+ * Removes all key-value entries from the map.
+ *
+ * @private
+ * @name clear
+ * @memberOf MapCache
+ */
+function mapCacheClear() {
+ this.size = 0;
+ this.__data__ = {
+ 'hash': new Hash,
+ 'map': new (Map || ListCache),
+ 'string': new Hash
+ };
+}
+
+module.exports = mapCacheClear;
diff --git a/node_modules/lodash/_mapCacheDelete.js b/node_modules/lodash/_mapCacheDelete.js
new file mode 100644
index 0000000..946ca3c
--- /dev/null
+++ b/node_modules/lodash/_mapCacheDelete.js
@@ -0,0 +1,18 @@
+var getMapData = require('./_getMapData');
+
+/**
+ * Removes `key` and its value from the map.
+ *
+ * @private
+ * @name delete
+ * @memberOf MapCache
+ * @param {string} key The key of the value to remove.
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
+ */
+function mapCacheDelete(key) {
+ var result = getMapData(this, key)['delete'](key);
+ this.size -= result ? 1 : 0;
+ return result;
+}
+
+module.exports = mapCacheDelete;
diff --git a/node_modules/lodash/_mapCacheGet.js b/node_modules/lodash/_mapCacheGet.js
new file mode 100644
index 0000000..f29f55c
--- /dev/null
+++ b/node_modules/lodash/_mapCacheGet.js
@@ -0,0 +1,16 @@
+var getMapData = require('./_getMapData');
+
+/**
+ * Gets the map value for `key`.
+ *
+ * @private
+ * @name get
+ * @memberOf MapCache
+ * @param {string} key The key of the value to get.
+ * @returns {*} Returns the entry value.
+ */
+function mapCacheGet(key) {
+ return getMapData(this, key).get(key);
+}
+
+module.exports = mapCacheGet;
diff --git a/node_modules/lodash/_mapCacheHas.js b/node_modules/lodash/_mapCacheHas.js
new file mode 100644
index 0000000..a1214c0
--- /dev/null
+++ b/node_modules/lodash/_mapCacheHas.js
@@ -0,0 +1,16 @@
+var getMapData = require('./_getMapData');
+
+/**
+ * Checks if a map value for `key` exists.
+ *
+ * @private
+ * @name has
+ * @memberOf MapCache
+ * @param {string} key The key of the entry to check.
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
+ */
+function mapCacheHas(key) {
+ return getMapData(this, key).has(key);
+}
+
+module.exports = mapCacheHas;
diff --git a/node_modules/lodash/_mapCacheSet.js b/node_modules/lodash/_mapCacheSet.js
new file mode 100644
index 0000000..7346849
--- /dev/null
+++ b/node_modules/lodash/_mapCacheSet.js
@@ -0,0 +1,22 @@
+var getMapData = require('./_getMapData');
+
+/**
+ * Sets the map `key` to `value`.
+ *
+ * @private
+ * @name set
+ * @memberOf MapCache
+ * @param {string} key The key of the value to set.
+ * @param {*} value The value to set.
+ * @returns {Object} Returns the map cache instance.
+ */
+function mapCacheSet(key, value) {
+ var data = getMapData(this, key),
+ size = data.size;
+
+ data.set(key, value);
+ this.size += data.size == size ? 0 : 1;
+ return this;
+}
+
+module.exports = mapCacheSet;
diff --git a/node_modules/lodash/_mapToArray.js b/node_modules/lodash/_mapToArray.js
new file mode 100644
index 0000000..fe3dd53
--- /dev/null
+++ b/node_modules/lodash/_mapToArray.js
@@ -0,0 +1,18 @@
+/**
+ * Converts `map` to its key-value pairs.
+ *
+ * @private
+ * @param {Object} map The map to convert.
+ * @returns {Array} Returns the key-value pairs.
+ */
+function mapToArray(map) {
+ var index = -1,
+ result = Array(map.size);
+
+ map.forEach(function(value, key) {
+ result[++index] = [key, value];
+ });
+ return result;
+}
+
+module.exports = mapToArray;
diff --git a/node_modules/lodash/_matchesStrictComparable.js b/node_modules/lodash/_matchesStrictComparable.js
new file mode 100644
index 0000000..f608af9
--- /dev/null
+++ b/node_modules/lodash/_matchesStrictComparable.js
@@ -0,0 +1,20 @@
+/**
+ * A specialized version of `matchesProperty` for source values suitable
+ * for strict equality comparisons, i.e. `===`.
+ *
+ * @private
+ * @param {string} key The key of the property to get.
+ * @param {*} srcValue The value to match.
+ * @returns {Function} Returns the new spec function.
+ */
+function matchesStrictComparable(key, srcValue) {
+ return function(object) {
+ if (object == null) {
+ return false;
+ }
+ return object[key] === srcValue &&
+ (srcValue !== undefined || (key in Object(object)));
+ };
+}
+
+module.exports = matchesStrictComparable;
diff --git a/node_modules/lodash/_memoizeCapped.js b/node_modules/lodash/_memoizeCapped.js
new file mode 100644
index 0000000..7f71c8f
--- /dev/null
+++ b/node_modules/lodash/_memoizeCapped.js
@@ -0,0 +1,26 @@
+var memoize = require('./memoize');
+
+/** Used as the maximum memoize cache size. */
+var MAX_MEMOIZE_SIZE = 500;
+
+/**
+ * A specialized version of `_.memoize` which clears the memoized function's
+ * cache when it exceeds `MAX_MEMOIZE_SIZE`.
+ *
+ * @private
+ * @param {Function} func The function to have its output memoized.
+ * @returns {Function} Returns the new memoized function.
+ */
+function memoizeCapped(func) {
+ var result = memoize(func, function(key) {
+ if (cache.size === MAX_MEMOIZE_SIZE) {
+ cache.clear();
+ }
+ return key;
+ });
+
+ var cache = result.cache;
+ return result;
+}
+
+module.exports = memoizeCapped;
diff --git a/node_modules/lodash/_mergeData.js b/node_modules/lodash/_mergeData.js
new file mode 100644
index 0000000..cb570f9
--- /dev/null
+++ b/node_modules/lodash/_mergeData.js
@@ -0,0 +1,90 @@
+var composeArgs = require('./_composeArgs'),
+ composeArgsRight = require('./_composeArgsRight'),
+ replaceHolders = require('./_replaceHolders');
+
+/** Used as the internal argument placeholder. */
+var PLACEHOLDER = '__lodash_placeholder__';
+
+/** Used to compose bitmasks for function metadata. */
+var WRAP_BIND_FLAG = 1,
+ WRAP_BIND_KEY_FLAG = 2,
+ WRAP_CURRY_BOUND_FLAG = 4,
+ WRAP_CURRY_FLAG = 8,
+ WRAP_ARY_FLAG = 128,
+ WRAP_REARG_FLAG = 256;
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeMin = Math.min;
+
+/**
+ * Merges the function metadata of `source` into `data`.
+ *
+ * Merging metadata reduces the number of wrappers used to invoke a function.
+ * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
+ * may be applied regardless of execution order. Methods like `_.ary` and
+ * `_.rearg` modify function arguments, making the order in which they are
+ * executed important, preventing the merging of metadata. However, we make
+ * an exception for a safe combined case where curried functions have `_.ary`
+ * and or `_.rearg` applied.
+ *
+ * @private
+ * @param {Array} data The destination metadata.
+ * @param {Array} source The source metadata.
+ * @returns {Array} Returns `data`.
+ */
+function mergeData(data, source) {
+ var bitmask = data[1],
+ srcBitmask = source[1],
+ newBitmask = bitmask | srcBitmask,
+ isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
+
+ var isCombo =
+ ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
+ ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
+ ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));
+
+ // Exit early if metadata can't be merged.
+ if (!(isCommon || isCombo)) {
+ return data;
+ }
+ // Use source `thisArg` if available.
+ if (srcBitmask & WRAP_BIND_FLAG) {
+ data[2] = source[2];
+ // Set when currying a bound function.
+ newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
+ }
+ // Compose partial arguments.
+ var value = source[3];
+ if (value) {
+ var partials = data[3];
+ data[3] = partials ? composeArgs(partials, value, source[4]) : value;
+ data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
+ }
+ // Compose partial right arguments.
+ value = source[5];
+ if (value) {
+ partials = data[5];
+ data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
+ data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
+ }
+ // Use source `argPos` if available.
+ value = source[7];
+ if (value) {
+ data[7] = value;
+ }
+ // Use source `ary` if it's smaller.
+ if (srcBitmask & WRAP_ARY_FLAG) {
+ data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
+ }
+ // Use source `arity` if one is not provided.
+ if (data[9] == null) {
+ data[9] = source[9];
+ }
+ // Use source `func` and merge bitmasks.
+ data[0] = source[0];
+ data[1] = newBitmask;
+
+ return data;
+}
+
+module.exports = mergeData;
diff --git a/node_modules/lodash/_metaMap.js b/node_modules/lodash/_metaMap.js
new file mode 100644
index 0000000..0157a0b
--- /dev/null
+++ b/node_modules/lodash/_metaMap.js
@@ -0,0 +1,6 @@
+var WeakMap = require('./_WeakMap');
+
+/** Used to store function metadata. */
+var metaMap = WeakMap && new WeakMap;
+
+module.exports = metaMap;
diff --git a/node_modules/lodash/_nativeCreate.js b/node_modules/lodash/_nativeCreate.js
new file mode 100644
index 0000000..c7aede8
--- /dev/null
+++ b/node_modules/lodash/_nativeCreate.js
@@ -0,0 +1,6 @@
+var getNative = require('./_getNative');
+
+/* Built-in method references that are verified to be native. */
+var nativeCreate = getNative(Object, 'create');
+
+module.exports = nativeCreate;
diff --git a/node_modules/lodash/_nativeKeys.js b/node_modules/lodash/_nativeKeys.js
new file mode 100644
index 0000000..479a104
--- /dev/null
+++ b/node_modules/lodash/_nativeKeys.js
@@ -0,0 +1,6 @@
+var overArg = require('./_overArg');
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeKeys = overArg(Object.keys, Object);
+
+module.exports = nativeKeys;
diff --git a/node_modules/lodash/_nativeKeysIn.js b/node_modules/lodash/_nativeKeysIn.js
new file mode 100644
index 0000000..00ee505
--- /dev/null
+++ b/node_modules/lodash/_nativeKeysIn.js
@@ -0,0 +1,20 @@
+/**
+ * This function is like
+ * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
+ * except that it includes inherited enumerable properties.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ */
+function nativeKeysIn(object) {
+ var result = [];
+ if (object != null) {
+ for (var key in Object(object)) {
+ result.push(key);
+ }
+ }
+ return result;
+}
+
+module.exports = nativeKeysIn;
diff --git a/node_modules/lodash/_nodeUtil.js b/node_modules/lodash/_nodeUtil.js
new file mode 100644
index 0000000..983d78f
--- /dev/null
+++ b/node_modules/lodash/_nodeUtil.js
@@ -0,0 +1,30 @@
+var freeGlobal = require('./_freeGlobal');
+
+/** Detect free variable `exports`. */
+var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
+
+/** Detect free variable `module`. */
+var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
+
+/** Detect the popular CommonJS extension `module.exports`. */
+var moduleExports = freeModule && freeModule.exports === freeExports;
+
+/** Detect free variable `process` from Node.js. */
+var freeProcess = moduleExports && freeGlobal.process;
+
+/** Used to access faster Node.js helpers. */
+var nodeUtil = (function() {
+ try {
+ // Use `util.types` for Node.js 10+.
+ var types = freeModule && freeModule.require && freeModule.require('util').types;
+
+ if (types) {
+ return types;
+ }
+
+ // Legacy `process.binding('util')` for Node.js < 10.
+ return freeProcess && freeProcess.binding && freeProcess.binding('util');
+ } catch (e) {}
+}());
+
+module.exports = nodeUtil;
diff --git a/node_modules/lodash/_objectToString.js b/node_modules/lodash/_objectToString.js
new file mode 100644
index 0000000..c614ec0
--- /dev/null
+++ b/node_modules/lodash/_objectToString.js
@@ -0,0 +1,22 @@
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/**
+ * Used to resolve the
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
+ * of values.
+ */
+var nativeObjectToString = objectProto.toString;
+
+/**
+ * Converts `value` to a string using `Object.prototype.toString`.
+ *
+ * @private
+ * @param {*} value The value to convert.
+ * @returns {string} Returns the converted string.
+ */
+function objectToString(value) {
+ return nativeObjectToString.call(value);
+}
+
+module.exports = objectToString;
diff --git a/node_modules/lodash/_overArg.js b/node_modules/lodash/_overArg.js
new file mode 100644
index 0000000..651c5c5
--- /dev/null
+++ b/node_modules/lodash/_overArg.js
@@ -0,0 +1,15 @@
+/**
+ * Creates a unary function that invokes `func` with its argument transformed.
+ *
+ * @private
+ * @param {Function} func The function to wrap.
+ * @param {Function} transform The argument transform.
+ * @returns {Function} Returns the new function.
+ */
+function overArg(func, transform) {
+ return function(arg) {
+ return func(transform(arg));
+ };
+}
+
+module.exports = overArg;
diff --git a/node_modules/lodash/_overRest.js b/node_modules/lodash/_overRest.js
new file mode 100644
index 0000000..c7cdef3
--- /dev/null
+++ b/node_modules/lodash/_overRest.js
@@ -0,0 +1,36 @@
+var apply = require('./_apply');
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeMax = Math.max;
+
+/**
+ * A specialized version of `baseRest` which transforms the rest array.
+ *
+ * @private
+ * @param {Function} func The function to apply a rest parameter to.
+ * @param {number} [start=func.length-1] The start position of the rest parameter.
+ * @param {Function} transform The rest array transform.
+ * @returns {Function} Returns the new function.
+ */
+function overRest(func, start, transform) {
+ start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
+ return function() {
+ var args = arguments,
+ index = -1,
+ length = nativeMax(args.length - start, 0),
+ array = Array(length);
+
+ while (++index < length) {
+ array[index] = args[start + index];
+ }
+ index = -1;
+ var otherArgs = Array(start + 1);
+ while (++index < start) {
+ otherArgs[index] = args[index];
+ }
+ otherArgs[start] = transform(array);
+ return apply(func, this, otherArgs);
+ };
+}
+
+module.exports = overRest;
diff --git a/node_modules/lodash/_parent.js b/node_modules/lodash/_parent.js
new file mode 100644
index 0000000..f174328
--- /dev/null
+++ b/node_modules/lodash/_parent.js
@@ -0,0 +1,16 @@
+var baseGet = require('./_baseGet'),
+ baseSlice = require('./_baseSlice');
+
+/**
+ * Gets the parent value at `path` of `object`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array} path The path to get the parent value of.
+ * @returns {*} Returns the parent value.
+ */
+function parent(object, path) {
+ return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
+}
+
+module.exports = parent;
diff --git a/node_modules/lodash/_reEscape.js b/node_modules/lodash/_reEscape.js
new file mode 100644
index 0000000..7f47eda
--- /dev/null
+++ b/node_modules/lodash/_reEscape.js
@@ -0,0 +1,4 @@
+/** Used to match template delimiters. */
+var reEscape = /<%-([\s\S]+?)%>/g;
+
+module.exports = reEscape;
diff --git a/node_modules/lodash/_reEvaluate.js b/node_modules/lodash/_reEvaluate.js
new file mode 100644
index 0000000..6adfc31
--- /dev/null
+++ b/node_modules/lodash/_reEvaluate.js
@@ -0,0 +1,4 @@
+/** Used to match template delimiters. */
+var reEvaluate = /<%([\s\S]+?)%>/g;
+
+module.exports = reEvaluate;
diff --git a/node_modules/lodash/_reInterpolate.js b/node_modules/lodash/_reInterpolate.js
new file mode 100644
index 0000000..d02ff0b
--- /dev/null
+++ b/node_modules/lodash/_reInterpolate.js
@@ -0,0 +1,4 @@
+/** Used to match template delimiters. */
+var reInterpolate = /<%=([\s\S]+?)%>/g;
+
+module.exports = reInterpolate;
diff --git a/node_modules/lodash/_realNames.js b/node_modules/lodash/_realNames.js
new file mode 100644
index 0000000..aa0d529
--- /dev/null
+++ b/node_modules/lodash/_realNames.js
@@ -0,0 +1,4 @@
+/** Used to lookup unminified function names. */
+var realNames = {};
+
+module.exports = realNames;
diff --git a/node_modules/lodash/_reorder.js b/node_modules/lodash/_reorder.js
new file mode 100644
index 0000000..a3502b0
--- /dev/null
+++ b/node_modules/lodash/_reorder.js
@@ -0,0 +1,29 @@
+var copyArray = require('./_copyArray'),
+ isIndex = require('./_isIndex');
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeMin = Math.min;
+
+/**
+ * Reorder `array` according to the specified indexes where the element at
+ * the first index is assigned as the first element, the element at
+ * the second index is assigned as the second element, and so on.
+ *
+ * @private
+ * @param {Array} array The array to reorder.
+ * @param {Array} indexes The arranged array indexes.
+ * @returns {Array} Returns `array`.
+ */
+function reorder(array, indexes) {
+ var arrLength = array.length,
+ length = nativeMin(indexes.length, arrLength),
+ oldArray = copyArray(array);
+
+ while (length--) {
+ var index = indexes[length];
+ array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
+ }
+ return array;
+}
+
+module.exports = reorder;
diff --git a/node_modules/lodash/_replaceHolders.js b/node_modules/lodash/_replaceHolders.js
new file mode 100644
index 0000000..74360ec
--- /dev/null
+++ b/node_modules/lodash/_replaceHolders.js
@@ -0,0 +1,29 @@
+/** Used as the internal argument placeholder. */
+var PLACEHOLDER = '__lodash_placeholder__';
+
+/**
+ * Replaces all `placeholder` elements in `array` with an internal placeholder
+ * and returns an array of their indexes.
+ *
+ * @private
+ * @param {Array} array The array to modify.
+ * @param {*} placeholder The placeholder to replace.
+ * @returns {Array} Returns the new array of placeholder indexes.
+ */
+function replaceHolders(array, placeholder) {
+ var index = -1,
+ length = array.length,
+ resIndex = 0,
+ result = [];
+
+ while (++index < length) {
+ var value = array[index];
+ if (value === placeholder || value === PLACEHOLDER) {
+ array[index] = PLACEHOLDER;
+ result[resIndex++] = index;
+ }
+ }
+ return result;
+}
+
+module.exports = replaceHolders;
diff --git a/node_modules/lodash/_root.js b/node_modules/lodash/_root.js
new file mode 100644
index 0000000..d2852be
--- /dev/null
+++ b/node_modules/lodash/_root.js
@@ -0,0 +1,9 @@
+var freeGlobal = require('./_freeGlobal');
+
+/** Detect free variable `self`. */
+var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
+
+/** Used as a reference to the global object. */
+var root = freeGlobal || freeSelf || Function('return this')();
+
+module.exports = root;
diff --git a/node_modules/lodash/_safeGet.js b/node_modules/lodash/_safeGet.js
new file mode 100644
index 0000000..b070897
--- /dev/null
+++ b/node_modules/lodash/_safeGet.js
@@ -0,0 +1,21 @@
+/**
+ * Gets the value at `key`, unless `key` is "__proto__" or "constructor".
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {string} key The key of the property to get.
+ * @returns {*} Returns the property value.
+ */
+function safeGet(object, key) {
+ if (key === 'constructor' && typeof object[key] === 'function') {
+ return;
+ }
+
+ if (key == '__proto__') {
+ return;
+ }
+
+ return object[key];
+}
+
+module.exports = safeGet;
diff --git a/node_modules/lodash/_setCacheAdd.js b/node_modules/lodash/_setCacheAdd.js
new file mode 100644
index 0000000..1081a74
--- /dev/null
+++ b/node_modules/lodash/_setCacheAdd.js
@@ -0,0 +1,19 @@
+/** Used to stand-in for `undefined` hash values. */
+var HASH_UNDEFINED = '__lodash_hash_undefined__';
+
+/**
+ * Adds `value` to the array cache.
+ *
+ * @private
+ * @name add
+ * @memberOf SetCache
+ * @alias push
+ * @param {*} value The value to cache.
+ * @returns {Object} Returns the cache instance.
+ */
+function setCacheAdd(value) {
+ this.__data__.set(value, HASH_UNDEFINED);
+ return this;
+}
+
+module.exports = setCacheAdd;
diff --git a/node_modules/lodash/_setCacheHas.js b/node_modules/lodash/_setCacheHas.js
new file mode 100644
index 0000000..9a49255
--- /dev/null
+++ b/node_modules/lodash/_setCacheHas.js
@@ -0,0 +1,14 @@
+/**
+ * Checks if `value` is in the array cache.
+ *
+ * @private
+ * @name has
+ * @memberOf SetCache
+ * @param {*} value The value to search for.
+ * @returns {number} Returns `true` if `value` is found, else `false`.
+ */
+function setCacheHas(value) {
+ return this.__data__.has(value);
+}
+
+module.exports = setCacheHas;
diff --git a/node_modules/lodash/_setData.js b/node_modules/lodash/_setData.js
new file mode 100644
index 0000000..e5cf3eb
--- /dev/null
+++ b/node_modules/lodash/_setData.js
@@ -0,0 +1,20 @@
+var baseSetData = require('./_baseSetData'),
+ shortOut = require('./_shortOut');
+
+/**
+ * Sets metadata for `func`.
+ *
+ * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
+ * period of time, it will trip its breaker and transition to an identity
+ * function to avoid garbage collection pauses in V8. See
+ * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
+ * for more details.
+ *
+ * @private
+ * @param {Function} func The function to associate metadata with.
+ * @param {*} data The metadata.
+ * @returns {Function} Returns `func`.
+ */
+var setData = shortOut(baseSetData);
+
+module.exports = setData;
diff --git a/node_modules/lodash/_setToArray.js b/node_modules/lodash/_setToArray.js
new file mode 100644
index 0000000..b87f074
--- /dev/null
+++ b/node_modules/lodash/_setToArray.js
@@ -0,0 +1,18 @@
+/**
+ * Converts `set` to an array of its values.
+ *
+ * @private
+ * @param {Object} set The set to convert.
+ * @returns {Array} Returns the values.
+ */
+function setToArray(set) {
+ var index = -1,
+ result = Array(set.size);
+
+ set.forEach(function(value) {
+ result[++index] = value;
+ });
+ return result;
+}
+
+module.exports = setToArray;
diff --git a/node_modules/lodash/_setToPairs.js b/node_modules/lodash/_setToPairs.js
new file mode 100644
index 0000000..36ad37a
--- /dev/null
+++ b/node_modules/lodash/_setToPairs.js
@@ -0,0 +1,18 @@
+/**
+ * Converts `set` to its value-value pairs.
+ *
+ * @private
+ * @param {Object} set The set to convert.
+ * @returns {Array} Returns the value-value pairs.
+ */
+function setToPairs(set) {
+ var index = -1,
+ result = Array(set.size);
+
+ set.forEach(function(value) {
+ result[++index] = [value, value];
+ });
+ return result;
+}
+
+module.exports = setToPairs;
diff --git a/node_modules/lodash/_setToString.js b/node_modules/lodash/_setToString.js
new file mode 100644
index 0000000..6ca8419
--- /dev/null
+++ b/node_modules/lodash/_setToString.js
@@ -0,0 +1,14 @@
+var baseSetToString = require('./_baseSetToString'),
+ shortOut = require('./_shortOut');
+
+/**
+ * Sets the `toString` method of `func` to return `string`.
+ *
+ * @private
+ * @param {Function} func The function to modify.
+ * @param {Function} string The `toString` result.
+ * @returns {Function} Returns `func`.
+ */
+var setToString = shortOut(baseSetToString);
+
+module.exports = setToString;
diff --git a/node_modules/lodash/_setWrapToString.js b/node_modules/lodash/_setWrapToString.js
new file mode 100644
index 0000000..decdc44
--- /dev/null
+++ b/node_modules/lodash/_setWrapToString.js
@@ -0,0 +1,21 @@
+var getWrapDetails = require('./_getWrapDetails'),
+ insertWrapDetails = require('./_insertWrapDetails'),
+ setToString = require('./_setToString'),
+ updateWrapDetails = require('./_updateWrapDetails');
+
+/**
+ * Sets the `toString` method of `wrapper` to mimic the source of `reference`
+ * with wrapper details in a comment at the top of the source body.
+ *
+ * @private
+ * @param {Function} wrapper The function to modify.
+ * @param {Function} reference The reference function.
+ * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
+ * @returns {Function} Returns `wrapper`.
+ */
+function setWrapToString(wrapper, reference, bitmask) {
+ var source = (reference + '');
+ return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
+}
+
+module.exports = setWrapToString;
diff --git a/node_modules/lodash/_shortOut.js b/node_modules/lodash/_shortOut.js
new file mode 100644
index 0000000..3300a07
--- /dev/null
+++ b/node_modules/lodash/_shortOut.js
@@ -0,0 +1,37 @@
+/** Used to detect hot functions by number of calls within a span of milliseconds. */
+var HOT_COUNT = 800,
+ HOT_SPAN = 16;
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeNow = Date.now;
+
+/**
+ * Creates a function that'll short out and invoke `identity` instead
+ * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
+ * milliseconds.
+ *
+ * @private
+ * @param {Function} func The function to restrict.
+ * @returns {Function} Returns the new shortable function.
+ */
+function shortOut(func) {
+ var count = 0,
+ lastCalled = 0;
+
+ return function() {
+ var stamp = nativeNow(),
+ remaining = HOT_SPAN - (stamp - lastCalled);
+
+ lastCalled = stamp;
+ if (remaining > 0) {
+ if (++count >= HOT_COUNT) {
+ return arguments[0];
+ }
+ } else {
+ count = 0;
+ }
+ return func.apply(undefined, arguments);
+ };
+}
+
+module.exports = shortOut;
diff --git a/node_modules/lodash/_shuffleSelf.js b/node_modules/lodash/_shuffleSelf.js
new file mode 100644
index 0000000..8bcc4f5
--- /dev/null
+++ b/node_modules/lodash/_shuffleSelf.js
@@ -0,0 +1,28 @@
+var baseRandom = require('./_baseRandom');
+
+/**
+ * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
+ *
+ * @private
+ * @param {Array} array The array to shuffle.
+ * @param {number} [size=array.length] The size of `array`.
+ * @returns {Array} Returns `array`.
+ */
+function shuffleSelf(array, size) {
+ var index = -1,
+ length = array.length,
+ lastIndex = length - 1;
+
+ size = size === undefined ? length : size;
+ while (++index < size) {
+ var rand = baseRandom(index, lastIndex),
+ value = array[rand];
+
+ array[rand] = array[index];
+ array[index] = value;
+ }
+ array.length = size;
+ return array;
+}
+
+module.exports = shuffleSelf;
diff --git a/node_modules/lodash/_stackClear.js b/node_modules/lodash/_stackClear.js
new file mode 100644
index 0000000..ce8e5a9
--- /dev/null
+++ b/node_modules/lodash/_stackClear.js
@@ -0,0 +1,15 @@
+var ListCache = require('./_ListCache');
+
+/**
+ * Removes all key-value entries from the stack.
+ *
+ * @private
+ * @name clear
+ * @memberOf Stack
+ */
+function stackClear() {
+ this.__data__ = new ListCache;
+ this.size = 0;
+}
+
+module.exports = stackClear;
diff --git a/node_modules/lodash/_stackDelete.js b/node_modules/lodash/_stackDelete.js
new file mode 100644
index 0000000..ff9887a
--- /dev/null
+++ b/node_modules/lodash/_stackDelete.js
@@ -0,0 +1,18 @@
+/**
+ * Removes `key` and its value from the stack.
+ *
+ * @private
+ * @name delete
+ * @memberOf Stack
+ * @param {string} key The key of the value to remove.
+ * @returns {boolean} Returns `true` if the entry was removed, else `false`.
+ */
+function stackDelete(key) {
+ var data = this.__data__,
+ result = data['delete'](key);
+
+ this.size = data.size;
+ return result;
+}
+
+module.exports = stackDelete;
diff --git a/node_modules/lodash/_stackGet.js b/node_modules/lodash/_stackGet.js
new file mode 100644
index 0000000..1cdf004
--- /dev/null
+++ b/node_modules/lodash/_stackGet.js
@@ -0,0 +1,14 @@
+/**
+ * Gets the stack value for `key`.
+ *
+ * @private
+ * @name get
+ * @memberOf Stack
+ * @param {string} key The key of the value to get.
+ * @returns {*} Returns the entry value.
+ */
+function stackGet(key) {
+ return this.__data__.get(key);
+}
+
+module.exports = stackGet;
diff --git a/node_modules/lodash/_stackHas.js b/node_modules/lodash/_stackHas.js
new file mode 100644
index 0000000..16a3ad1
--- /dev/null
+++ b/node_modules/lodash/_stackHas.js
@@ -0,0 +1,14 @@
+/**
+ * Checks if a stack value for `key` exists.
+ *
+ * @private
+ * @name has
+ * @memberOf Stack
+ * @param {string} key The key of the entry to check.
+ * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
+ */
+function stackHas(key) {
+ return this.__data__.has(key);
+}
+
+module.exports = stackHas;
diff --git a/node_modules/lodash/_stackSet.js b/node_modules/lodash/_stackSet.js
new file mode 100644
index 0000000..b790ac5
--- /dev/null
+++ b/node_modules/lodash/_stackSet.js
@@ -0,0 +1,34 @@
+var ListCache = require('./_ListCache'),
+ Map = require('./_Map'),
+ MapCache = require('./_MapCache');
+
+/** Used as the size to enable large array optimizations. */
+var LARGE_ARRAY_SIZE = 200;
+
+/**
+ * Sets the stack `key` to `value`.
+ *
+ * @private
+ * @name set
+ * @memberOf Stack
+ * @param {string} key The key of the value to set.
+ * @param {*} value The value to set.
+ * @returns {Object} Returns the stack cache instance.
+ */
+function stackSet(key, value) {
+ var data = this.__data__;
+ if (data instanceof ListCache) {
+ var pairs = data.__data__;
+ if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
+ pairs.push([key, value]);
+ this.size = ++data.size;
+ return this;
+ }
+ data = this.__data__ = new MapCache(pairs);
+ }
+ data.set(key, value);
+ this.size = data.size;
+ return this;
+}
+
+module.exports = stackSet;
diff --git a/node_modules/lodash/_strictIndexOf.js b/node_modules/lodash/_strictIndexOf.js
new file mode 100644
index 0000000..0486a49
--- /dev/null
+++ b/node_modules/lodash/_strictIndexOf.js
@@ -0,0 +1,23 @@
+/**
+ * A specialized version of `_.indexOf` which performs strict equality
+ * comparisons of values, i.e. `===`.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {*} value The value to search for.
+ * @param {number} fromIndex The index to search from.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ */
+function strictIndexOf(array, value, fromIndex) {
+ var index = fromIndex - 1,
+ length = array.length;
+
+ while (++index < length) {
+ if (array[index] === value) {
+ return index;
+ }
+ }
+ return -1;
+}
+
+module.exports = strictIndexOf;
diff --git a/node_modules/lodash/_strictLastIndexOf.js b/node_modules/lodash/_strictLastIndexOf.js
new file mode 100644
index 0000000..d7310dc
--- /dev/null
+++ b/node_modules/lodash/_strictLastIndexOf.js
@@ -0,0 +1,21 @@
+/**
+ * A specialized version of `_.lastIndexOf` which performs strict equality
+ * comparisons of values, i.e. `===`.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {*} value The value to search for.
+ * @param {number} fromIndex The index to search from.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ */
+function strictLastIndexOf(array, value, fromIndex) {
+ var index = fromIndex + 1;
+ while (index--) {
+ if (array[index] === value) {
+ return index;
+ }
+ }
+ return index;
+}
+
+module.exports = strictLastIndexOf;
diff --git a/node_modules/lodash/_stringSize.js b/node_modules/lodash/_stringSize.js
new file mode 100644
index 0000000..17ef462
--- /dev/null
+++ b/node_modules/lodash/_stringSize.js
@@ -0,0 +1,18 @@
+var asciiSize = require('./_asciiSize'),
+ hasUnicode = require('./_hasUnicode'),
+ unicodeSize = require('./_unicodeSize');
+
+/**
+ * Gets the number of symbols in `string`.
+ *
+ * @private
+ * @param {string} string The string to inspect.
+ * @returns {number} Returns the string size.
+ */
+function stringSize(string) {
+ return hasUnicode(string)
+ ? unicodeSize(string)
+ : asciiSize(string);
+}
+
+module.exports = stringSize;
diff --git a/node_modules/lodash/_stringToArray.js b/node_modules/lodash/_stringToArray.js
new file mode 100644
index 0000000..d161158
--- /dev/null
+++ b/node_modules/lodash/_stringToArray.js
@@ -0,0 +1,18 @@
+var asciiToArray = require('./_asciiToArray'),
+ hasUnicode = require('./_hasUnicode'),
+ unicodeToArray = require('./_unicodeToArray');
+
+/**
+ * Converts `string` to an array.
+ *
+ * @private
+ * @param {string} string The string to convert.
+ * @returns {Array} Returns the converted array.
+ */
+function stringToArray(string) {
+ return hasUnicode(string)
+ ? unicodeToArray(string)
+ : asciiToArray(string);
+}
+
+module.exports = stringToArray;
diff --git a/node_modules/lodash/_stringToPath.js b/node_modules/lodash/_stringToPath.js
new file mode 100644
index 0000000..8f39f8a
--- /dev/null
+++ b/node_modules/lodash/_stringToPath.js
@@ -0,0 +1,27 @@
+var memoizeCapped = require('./_memoizeCapped');
+
+/** Used to match property names within property paths. */
+var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
+
+/** Used to match backslashes in property paths. */
+var reEscapeChar = /\\(\\)?/g;
+
+/**
+ * Converts `string` to a property path array.
+ *
+ * @private
+ * @param {string} string The string to convert.
+ * @returns {Array} Returns the property path array.
+ */
+var stringToPath = memoizeCapped(function(string) {
+ var result = [];
+ if (string.charCodeAt(0) === 46 /* . */) {
+ result.push('');
+ }
+ string.replace(rePropName, function(match, number, quote, subString) {
+ result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
+ });
+ return result;
+});
+
+module.exports = stringToPath;
diff --git a/node_modules/lodash/_toKey.js b/node_modules/lodash/_toKey.js
new file mode 100644
index 0000000..c6d645c
--- /dev/null
+++ b/node_modules/lodash/_toKey.js
@@ -0,0 +1,21 @@
+var isSymbol = require('./isSymbol');
+
+/** Used as references for various `Number` constants. */
+var INFINITY = 1 / 0;
+
+/**
+ * Converts `value` to a string key if it's not a string or symbol.
+ *
+ * @private
+ * @param {*} value The value to inspect.
+ * @returns {string|symbol} Returns the key.
+ */
+function toKey(value) {
+ if (typeof value == 'string' || isSymbol(value)) {
+ return value;
+ }
+ var result = (value + '');
+ return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
+}
+
+module.exports = toKey;
diff --git a/node_modules/lodash/_toSource.js b/node_modules/lodash/_toSource.js
new file mode 100644
index 0000000..a020b38
--- /dev/null
+++ b/node_modules/lodash/_toSource.js
@@ -0,0 +1,26 @@
+/** Used for built-in method references. */
+var funcProto = Function.prototype;
+
+/** Used to resolve the decompiled source of functions. */
+var funcToString = funcProto.toString;
+
+/**
+ * Converts `func` to its source code.
+ *
+ * @private
+ * @param {Function} func The function to convert.
+ * @returns {string} Returns the source code.
+ */
+function toSource(func) {
+ if (func != null) {
+ try {
+ return funcToString.call(func);
+ } catch (e) {}
+ try {
+ return (func + '');
+ } catch (e) {}
+ }
+ return '';
+}
+
+module.exports = toSource;
diff --git a/node_modules/lodash/_trimmedEndIndex.js b/node_modules/lodash/_trimmedEndIndex.js
new file mode 100644
index 0000000..139439a
--- /dev/null
+++ b/node_modules/lodash/_trimmedEndIndex.js
@@ -0,0 +1,19 @@
+/** Used to match a single whitespace character. */
+var reWhitespace = /\s/;
+
+/**
+ * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace
+ * character of `string`.
+ *
+ * @private
+ * @param {string} string The string to inspect.
+ * @returns {number} Returns the index of the last non-whitespace character.
+ */
+function trimmedEndIndex(string) {
+ var index = string.length;
+
+ while (index-- && reWhitespace.test(string.charAt(index))) {}
+ return index;
+}
+
+module.exports = trimmedEndIndex;
diff --git a/node_modules/lodash/_unescapeHtmlChar.js b/node_modules/lodash/_unescapeHtmlChar.js
new file mode 100644
index 0000000..a71fecb
--- /dev/null
+++ b/node_modules/lodash/_unescapeHtmlChar.js
@@ -0,0 +1,21 @@
+var basePropertyOf = require('./_basePropertyOf');
+
+/** Used to map HTML entities to characters. */
+var htmlUnescapes = {
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ ''': "'"
+};
+
+/**
+ * Used by `_.unescape` to convert HTML entities to characters.
+ *
+ * @private
+ * @param {string} chr The matched character to unescape.
+ * @returns {string} Returns the unescaped character.
+ */
+var unescapeHtmlChar = basePropertyOf(htmlUnescapes);
+
+module.exports = unescapeHtmlChar;
diff --git a/node_modules/lodash/_unicodeSize.js b/node_modules/lodash/_unicodeSize.js
new file mode 100644
index 0000000..68137ec
--- /dev/null
+++ b/node_modules/lodash/_unicodeSize.js
@@ -0,0 +1,44 @@
+/** Used to compose unicode character classes. */
+var rsAstralRange = '\\ud800-\\udfff',
+ rsComboMarksRange = '\\u0300-\\u036f',
+ reComboHalfMarksRange = '\\ufe20-\\ufe2f',
+ rsComboSymbolsRange = '\\u20d0-\\u20ff',
+ rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
+ rsVarRange = '\\ufe0e\\ufe0f';
+
+/** Used to compose unicode capture groups. */
+var rsAstral = '[' + rsAstralRange + ']',
+ rsCombo = '[' + rsComboRange + ']',
+ rsFitz = '\\ud83c[\\udffb-\\udfff]',
+ rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
+ rsNonAstral = '[^' + rsAstralRange + ']',
+ rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
+ rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
+ rsZWJ = '\\u200d';
+
+/** Used to compose unicode regexes. */
+var reOptMod = rsModifier + '?',
+ rsOptVar = '[' + rsVarRange + ']?',
+ rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
+ rsSeq = rsOptVar + reOptMod + rsOptJoin,
+ rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
+
+/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
+var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
+
+/**
+ * Gets the size of a Unicode `string`.
+ *
+ * @private
+ * @param {string} string The string inspect.
+ * @returns {number} Returns the string size.
+ */
+function unicodeSize(string) {
+ var result = reUnicode.lastIndex = 0;
+ while (reUnicode.test(string)) {
+ ++result;
+ }
+ return result;
+}
+
+module.exports = unicodeSize;
diff --git a/node_modules/lodash/_unicodeToArray.js b/node_modules/lodash/_unicodeToArray.js
new file mode 100644
index 0000000..2a725c0
--- /dev/null
+++ b/node_modules/lodash/_unicodeToArray.js
@@ -0,0 +1,40 @@
+/** Used to compose unicode character classes. */
+var rsAstralRange = '\\ud800-\\udfff',
+ rsComboMarksRange = '\\u0300-\\u036f',
+ reComboHalfMarksRange = '\\ufe20-\\ufe2f',
+ rsComboSymbolsRange = '\\u20d0-\\u20ff',
+ rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
+ rsVarRange = '\\ufe0e\\ufe0f';
+
+/** Used to compose unicode capture groups. */
+var rsAstral = '[' + rsAstralRange + ']',
+ rsCombo = '[' + rsComboRange + ']',
+ rsFitz = '\\ud83c[\\udffb-\\udfff]',
+ rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
+ rsNonAstral = '[^' + rsAstralRange + ']',
+ rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
+ rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
+ rsZWJ = '\\u200d';
+
+/** Used to compose unicode regexes. */
+var reOptMod = rsModifier + '?',
+ rsOptVar = '[' + rsVarRange + ']?',
+ rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
+ rsSeq = rsOptVar + reOptMod + rsOptJoin,
+ rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
+
+/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
+var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
+
+/**
+ * Converts a Unicode `string` to an array.
+ *
+ * @private
+ * @param {string} string The string to convert.
+ * @returns {Array} Returns the converted array.
+ */
+function unicodeToArray(string) {
+ return string.match(reUnicode) || [];
+}
+
+module.exports = unicodeToArray;
diff --git a/node_modules/lodash/_unicodeWords.js b/node_modules/lodash/_unicodeWords.js
new file mode 100644
index 0000000..e72e6e0
--- /dev/null
+++ b/node_modules/lodash/_unicodeWords.js
@@ -0,0 +1,69 @@
+/** Used to compose unicode character classes. */
+var rsAstralRange = '\\ud800-\\udfff',
+ rsComboMarksRange = '\\u0300-\\u036f',
+ reComboHalfMarksRange = '\\ufe20-\\ufe2f',
+ rsComboSymbolsRange = '\\u20d0-\\u20ff',
+ rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
+ rsDingbatRange = '\\u2700-\\u27bf',
+ rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
+ rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
+ rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
+ rsPunctuationRange = '\\u2000-\\u206f',
+ rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
+ rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
+ rsVarRange = '\\ufe0e\\ufe0f',
+ rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
+
+/** Used to compose unicode capture groups. */
+var rsApos = "['\u2019]",
+ rsBreak = '[' + rsBreakRange + ']',
+ rsCombo = '[' + rsComboRange + ']',
+ rsDigits = '\\d+',
+ rsDingbat = '[' + rsDingbatRange + ']',
+ rsLower = '[' + rsLowerRange + ']',
+ rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
+ rsFitz = '\\ud83c[\\udffb-\\udfff]',
+ rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
+ rsNonAstral = '[^' + rsAstralRange + ']',
+ rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
+ rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
+ rsUpper = '[' + rsUpperRange + ']',
+ rsZWJ = '\\u200d';
+
+/** Used to compose unicode regexes. */
+var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',
+ rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',
+ rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
+ rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
+ reOptMod = rsModifier + '?',
+ rsOptVar = '[' + rsVarRange + ']?',
+ rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
+ rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',
+ rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',
+ rsSeq = rsOptVar + reOptMod + rsOptJoin,
+ rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq;
+
+/** Used to match complex or compound words. */
+var reUnicodeWord = RegExp([
+ rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
+ rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',
+ rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,
+ rsUpper + '+' + rsOptContrUpper,
+ rsOrdUpper,
+ rsOrdLower,
+ rsDigits,
+ rsEmoji
+].join('|'), 'g');
+
+/**
+ * Splits a Unicode `string` into an array of its words.
+ *
+ * @private
+ * @param {string} The string to inspect.
+ * @returns {Array} Returns the words of `string`.
+ */
+function unicodeWords(string) {
+ return string.match(reUnicodeWord) || [];
+}
+
+module.exports = unicodeWords;
diff --git a/node_modules/lodash/_updateWrapDetails.js b/node_modules/lodash/_updateWrapDetails.js
new file mode 100644
index 0000000..8759fbd
--- /dev/null
+++ b/node_modules/lodash/_updateWrapDetails.js
@@ -0,0 +1,46 @@
+var arrayEach = require('./_arrayEach'),
+ arrayIncludes = require('./_arrayIncludes');
+
+/** Used to compose bitmasks for function metadata. */
+var WRAP_BIND_FLAG = 1,
+ WRAP_BIND_KEY_FLAG = 2,
+ WRAP_CURRY_FLAG = 8,
+ WRAP_CURRY_RIGHT_FLAG = 16,
+ WRAP_PARTIAL_FLAG = 32,
+ WRAP_PARTIAL_RIGHT_FLAG = 64,
+ WRAP_ARY_FLAG = 128,
+ WRAP_REARG_FLAG = 256,
+ WRAP_FLIP_FLAG = 512;
+
+/** Used to associate wrap methods with their bit flags. */
+var wrapFlags = [
+ ['ary', WRAP_ARY_FLAG],
+ ['bind', WRAP_BIND_FLAG],
+ ['bindKey', WRAP_BIND_KEY_FLAG],
+ ['curry', WRAP_CURRY_FLAG],
+ ['curryRight', WRAP_CURRY_RIGHT_FLAG],
+ ['flip', WRAP_FLIP_FLAG],
+ ['partial', WRAP_PARTIAL_FLAG],
+ ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
+ ['rearg', WRAP_REARG_FLAG]
+];
+
+/**
+ * Updates wrapper `details` based on `bitmask` flags.
+ *
+ * @private
+ * @returns {Array} details The details to modify.
+ * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
+ * @returns {Array} Returns `details`.
+ */
+function updateWrapDetails(details, bitmask) {
+ arrayEach(wrapFlags, function(pair) {
+ var value = '_.' + pair[0];
+ if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
+ details.push(value);
+ }
+ });
+ return details.sort();
+}
+
+module.exports = updateWrapDetails;
diff --git a/node_modules/lodash/_wrapperClone.js b/node_modules/lodash/_wrapperClone.js
new file mode 100644
index 0000000..7bb58a2
--- /dev/null
+++ b/node_modules/lodash/_wrapperClone.js
@@ -0,0 +1,23 @@
+var LazyWrapper = require('./_LazyWrapper'),
+ LodashWrapper = require('./_LodashWrapper'),
+ copyArray = require('./_copyArray');
+
+/**
+ * Creates a clone of `wrapper`.
+ *
+ * @private
+ * @param {Object} wrapper The wrapper to clone.
+ * @returns {Object} Returns the cloned wrapper.
+ */
+function wrapperClone(wrapper) {
+ if (wrapper instanceof LazyWrapper) {
+ return wrapper.clone();
+ }
+ var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
+ result.__actions__ = copyArray(wrapper.__actions__);
+ result.__index__ = wrapper.__index__;
+ result.__values__ = wrapper.__values__;
+ return result;
+}
+
+module.exports = wrapperClone;
diff --git a/node_modules/lodash/add.js b/node_modules/lodash/add.js
new file mode 100644
index 0000000..f069515
--- /dev/null
+++ b/node_modules/lodash/add.js
@@ -0,0 +1,22 @@
+var createMathOperation = require('./_createMathOperation');
+
+/**
+ * Adds two numbers.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.4.0
+ * @category Math
+ * @param {number} augend The first number in an addition.
+ * @param {number} addend The second number in an addition.
+ * @returns {number} Returns the total.
+ * @example
+ *
+ * _.add(6, 4);
+ * // => 10
+ */
+var add = createMathOperation(function(augend, addend) {
+ return augend + addend;
+}, 0);
+
+module.exports = add;
diff --git a/node_modules/lodash/after.js b/node_modules/lodash/after.js
new file mode 100644
index 0000000..3900c97
--- /dev/null
+++ b/node_modules/lodash/after.js
@@ -0,0 +1,42 @@
+var toInteger = require('./toInteger');
+
+/** Error message constants. */
+var FUNC_ERROR_TEXT = 'Expected a function';
+
+/**
+ * The opposite of `_.before`; this method creates a function that invokes
+ * `func` once it's called `n` or more times.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Function
+ * @param {number} n The number of calls before `func` is invoked.
+ * @param {Function} func The function to restrict.
+ * @returns {Function} Returns the new restricted function.
+ * @example
+ *
+ * var saves = ['profile', 'settings'];
+ *
+ * var done = _.after(saves.length, function() {
+ * console.log('done saving!');
+ * });
+ *
+ * _.forEach(saves, function(type) {
+ * asyncSave({ 'type': type, 'complete': done });
+ * });
+ * // => Logs 'done saving!' after the two async saves have completed.
+ */
+function after(n, func) {
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ n = toInteger(n);
+ return function() {
+ if (--n < 1) {
+ return func.apply(this, arguments);
+ }
+ };
+}
+
+module.exports = after;
diff --git a/node_modules/lodash/array.js b/node_modules/lodash/array.js
new file mode 100644
index 0000000..af688d3
--- /dev/null
+++ b/node_modules/lodash/array.js
@@ -0,0 +1,67 @@
+module.exports = {
+ 'chunk': require('./chunk'),
+ 'compact': require('./compact'),
+ 'concat': require('./concat'),
+ 'difference': require('./difference'),
+ 'differenceBy': require('./differenceBy'),
+ 'differenceWith': require('./differenceWith'),
+ 'drop': require('./drop'),
+ 'dropRight': require('./dropRight'),
+ 'dropRightWhile': require('./dropRightWhile'),
+ 'dropWhile': require('./dropWhile'),
+ 'fill': require('./fill'),
+ 'findIndex': require('./findIndex'),
+ 'findLastIndex': require('./findLastIndex'),
+ 'first': require('./first'),
+ 'flatten': require('./flatten'),
+ 'flattenDeep': require('./flattenDeep'),
+ 'flattenDepth': require('./flattenDepth'),
+ 'fromPairs': require('./fromPairs'),
+ 'head': require('./head'),
+ 'indexOf': require('./indexOf'),
+ 'initial': require('./initial'),
+ 'intersection': require('./intersection'),
+ 'intersectionBy': require('./intersectionBy'),
+ 'intersectionWith': require('./intersectionWith'),
+ 'join': require('./join'),
+ 'last': require('./last'),
+ 'lastIndexOf': require('./lastIndexOf'),
+ 'nth': require('./nth'),
+ 'pull': require('./pull'),
+ 'pullAll': require('./pullAll'),
+ 'pullAllBy': require('./pullAllBy'),
+ 'pullAllWith': require('./pullAllWith'),
+ 'pullAt': require('./pullAt'),
+ 'remove': require('./remove'),
+ 'reverse': require('./reverse'),
+ 'slice': require('./slice'),
+ 'sortedIndex': require('./sortedIndex'),
+ 'sortedIndexBy': require('./sortedIndexBy'),
+ 'sortedIndexOf': require('./sortedIndexOf'),
+ 'sortedLastIndex': require('./sortedLastIndex'),
+ 'sortedLastIndexBy': require('./sortedLastIndexBy'),
+ 'sortedLastIndexOf': require('./sortedLastIndexOf'),
+ 'sortedUniq': require('./sortedUniq'),
+ 'sortedUniqBy': require('./sortedUniqBy'),
+ 'tail': require('./tail'),
+ 'take': require('./take'),
+ 'takeRight': require('./takeRight'),
+ 'takeRightWhile': require('./takeRightWhile'),
+ 'takeWhile': require('./takeWhile'),
+ 'union': require('./union'),
+ 'unionBy': require('./unionBy'),
+ 'unionWith': require('./unionWith'),
+ 'uniq': require('./uniq'),
+ 'uniqBy': require('./uniqBy'),
+ 'uniqWith': require('./uniqWith'),
+ 'unzip': require('./unzip'),
+ 'unzipWith': require('./unzipWith'),
+ 'without': require('./without'),
+ 'xor': require('./xor'),
+ 'xorBy': require('./xorBy'),
+ 'xorWith': require('./xorWith'),
+ 'zip': require('./zip'),
+ 'zipObject': require('./zipObject'),
+ 'zipObjectDeep': require('./zipObjectDeep'),
+ 'zipWith': require('./zipWith')
+};
diff --git a/node_modules/lodash/ary.js b/node_modules/lodash/ary.js
new file mode 100644
index 0000000..70c87d0
--- /dev/null
+++ b/node_modules/lodash/ary.js
@@ -0,0 +1,29 @@
+var createWrap = require('./_createWrap');
+
+/** Used to compose bitmasks for function metadata. */
+var WRAP_ARY_FLAG = 128;
+
+/**
+ * Creates a function that invokes `func`, with up to `n` arguments,
+ * ignoring any additional arguments.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category Function
+ * @param {Function} func The function to cap arguments for.
+ * @param {number} [n=func.length] The arity cap.
+ * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
+ * @returns {Function} Returns the new capped function.
+ * @example
+ *
+ * _.map(['6', '8', '10'], _.ary(parseInt, 1));
+ * // => [6, 8, 10]
+ */
+function ary(func, n, guard) {
+ n = guard ? undefined : n;
+ n = (func && n == null) ? func.length : n;
+ return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
+}
+
+module.exports = ary;
diff --git a/node_modules/lodash/assign.js b/node_modules/lodash/assign.js
new file mode 100644
index 0000000..909db26
--- /dev/null
+++ b/node_modules/lodash/assign.js
@@ -0,0 +1,58 @@
+var assignValue = require('./_assignValue'),
+ copyObject = require('./_copyObject'),
+ createAssigner = require('./_createAssigner'),
+ isArrayLike = require('./isArrayLike'),
+ isPrototype = require('./_isPrototype'),
+ keys = require('./keys');
+
+/** Used for built-in method references. */
+var objectProto = Object.prototype;
+
+/** Used to check objects for own properties. */
+var hasOwnProperty = objectProto.hasOwnProperty;
+
+/**
+ * Assigns own enumerable string keyed properties of source objects to the
+ * destination object. Source objects are applied from left to right.
+ * Subsequent sources overwrite property assignments of previous sources.
+ *
+ * **Note:** This method mutates `object` and is loosely based on
+ * [`Object.assign`](https://mdn.io/Object/assign).
+ *
+ * @static
+ * @memberOf _
+ * @since 0.10.0
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} [sources] The source objects.
+ * @returns {Object} Returns `object`.
+ * @see _.assignIn
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * }
+ *
+ * function Bar() {
+ * this.c = 3;
+ * }
+ *
+ * Foo.prototype.b = 2;
+ * Bar.prototype.d = 4;
+ *
+ * _.assign({ 'a': 0 }, new Foo, new Bar);
+ * // => { 'a': 1, 'c': 3 }
+ */
+var assign = createAssigner(function(object, source) {
+ if (isPrototype(source) || isArrayLike(source)) {
+ copyObject(source, keys(source), object);
+ return;
+ }
+ for (var key in source) {
+ if (hasOwnProperty.call(source, key)) {
+ assignValue(object, key, source[key]);
+ }
+ }
+});
+
+module.exports = assign;
diff --git a/node_modules/lodash/assignIn.js b/node_modules/lodash/assignIn.js
new file mode 100644
index 0000000..e663473
--- /dev/null
+++ b/node_modules/lodash/assignIn.js
@@ -0,0 +1,40 @@
+var copyObject = require('./_copyObject'),
+ createAssigner = require('./_createAssigner'),
+ keysIn = require('./keysIn');
+
+/**
+ * This method is like `_.assign` except that it iterates over own and
+ * inherited source properties.
+ *
+ * **Note:** This method mutates `object`.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @alias extend
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} [sources] The source objects.
+ * @returns {Object} Returns `object`.
+ * @see _.assign
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * }
+ *
+ * function Bar() {
+ * this.c = 3;
+ * }
+ *
+ * Foo.prototype.b = 2;
+ * Bar.prototype.d = 4;
+ *
+ * _.assignIn({ 'a': 0 }, new Foo, new Bar);
+ * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
+ */
+var assignIn = createAssigner(function(object, source) {
+ copyObject(source, keysIn(source), object);
+});
+
+module.exports = assignIn;
diff --git a/node_modules/lodash/assignInWith.js b/node_modules/lodash/assignInWith.js
new file mode 100644
index 0000000..68fcc0b
--- /dev/null
+++ b/node_modules/lodash/assignInWith.js
@@ -0,0 +1,38 @@
+var copyObject = require('./_copyObject'),
+ createAssigner = require('./_createAssigner'),
+ keysIn = require('./keysIn');
+
+/**
+ * This method is like `_.assignIn` except that it accepts `customizer`
+ * which is invoked to produce the assigned values. If `customizer` returns
+ * `undefined`, assignment is handled by the method instead. The `customizer`
+ * is invoked with five arguments: (objValue, srcValue, key, object, source).
+ *
+ * **Note:** This method mutates `object`.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @alias extendWith
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} sources The source objects.
+ * @param {Function} [customizer] The function to customize assigned values.
+ * @returns {Object} Returns `object`.
+ * @see _.assignWith
+ * @example
+ *
+ * function customizer(objValue, srcValue) {
+ * return _.isUndefined(objValue) ? srcValue : objValue;
+ * }
+ *
+ * var defaults = _.partialRight(_.assignInWith, customizer);
+ *
+ * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
+ * // => { 'a': 1, 'b': 2 }
+ */
+var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
+ copyObject(source, keysIn(source), object, customizer);
+});
+
+module.exports = assignInWith;
diff --git a/node_modules/lodash/assignWith.js b/node_modules/lodash/assignWith.js
new file mode 100644
index 0000000..7dc6c76
--- /dev/null
+++ b/node_modules/lodash/assignWith.js
@@ -0,0 +1,37 @@
+var copyObject = require('./_copyObject'),
+ createAssigner = require('./_createAssigner'),
+ keys = require('./keys');
+
+/**
+ * This method is like `_.assign` except that it accepts `customizer`
+ * which is invoked to produce the assigned values. If `customizer` returns
+ * `undefined`, assignment is handled by the method instead. The `customizer`
+ * is invoked with five arguments: (objValue, srcValue, key, object, source).
+ *
+ * **Note:** This method mutates `object`.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} sources The source objects.
+ * @param {Function} [customizer] The function to customize assigned values.
+ * @returns {Object} Returns `object`.
+ * @see _.assignInWith
+ * @example
+ *
+ * function customizer(objValue, srcValue) {
+ * return _.isUndefined(objValue) ? srcValue : objValue;
+ * }
+ *
+ * var defaults = _.partialRight(_.assignWith, customizer);
+ *
+ * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
+ * // => { 'a': 1, 'b': 2 }
+ */
+var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
+ copyObject(source, keys(source), object, customizer);
+});
+
+module.exports = assignWith;
diff --git a/node_modules/lodash/at.js b/node_modules/lodash/at.js
new file mode 100644
index 0000000..781ee9e
--- /dev/null
+++ b/node_modules/lodash/at.js
@@ -0,0 +1,23 @@
+var baseAt = require('./_baseAt'),
+ flatRest = require('./_flatRest');
+
+/**
+ * Creates an array of values corresponding to `paths` of `object`.
+ *
+ * @static
+ * @memberOf _
+ * @since 1.0.0
+ * @category Object
+ * @param {Object} object The object to iterate over.
+ * @param {...(string|string[])} [paths] The property paths to pick.
+ * @returns {Array} Returns the picked values.
+ * @example
+ *
+ * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
+ *
+ * _.at(object, ['a[0].b.c', 'a[1]']);
+ * // => [3, 4]
+ */
+var at = flatRest(baseAt);
+
+module.exports = at;
diff --git a/node_modules/lodash/attempt.js b/node_modules/lodash/attempt.js
new file mode 100644
index 0000000..624d015
--- /dev/null
+++ b/node_modules/lodash/attempt.js
@@ -0,0 +1,35 @@
+var apply = require('./_apply'),
+ baseRest = require('./_baseRest'),
+ isError = require('./isError');
+
+/**
+ * Attempts to invoke `func`, returning either the result or the caught error
+ * object. Any additional arguments are provided to `func` when it's invoked.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category Util
+ * @param {Function} func The function to attempt.
+ * @param {...*} [args] The arguments to invoke `func` with.
+ * @returns {*} Returns the `func` result or error object.
+ * @example
+ *
+ * // Avoid throwing errors for invalid selectors.
+ * var elements = _.attempt(function(selector) {
+ * return document.querySelectorAll(selector);
+ * }, '>_>');
+ *
+ * if (_.isError(elements)) {
+ * elements = [];
+ * }
+ */
+var attempt = baseRest(function(func, args) {
+ try {
+ return apply(func, undefined, args);
+ } catch (e) {
+ return isError(e) ? e : new Error(e);
+ }
+});
+
+module.exports = attempt;
diff --git a/node_modules/lodash/before.js b/node_modules/lodash/before.js
new file mode 100644
index 0000000..a3e0a16
--- /dev/null
+++ b/node_modules/lodash/before.js
@@ -0,0 +1,40 @@
+var toInteger = require('./toInteger');
+
+/** Error message constants. */
+var FUNC_ERROR_TEXT = 'Expected a function';
+
+/**
+ * Creates a function that invokes `func`, with the `this` binding and arguments
+ * of the created function, while it's called less than `n` times. Subsequent
+ * calls to the created function return the result of the last `func` invocation.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category Function
+ * @param {number} n The number of calls at which `func` is no longer invoked.
+ * @param {Function} func The function to restrict.
+ * @returns {Function} Returns the new restricted function.
+ * @example
+ *
+ * jQuery(element).on('click', _.before(5, addContactToList));
+ * // => Allows adding up to 4 contacts to the list.
+ */
+function before(n, func) {
+ var result;
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ n = toInteger(n);
+ return function() {
+ if (--n > 0) {
+ result = func.apply(this, arguments);
+ }
+ if (n <= 1) {
+ func = undefined;
+ }
+ return result;
+ };
+}
+
+module.exports = before;
diff --git a/node_modules/lodash/bind.js b/node_modules/lodash/bind.js
new file mode 100644
index 0000000..b1076e9
--- /dev/null
+++ b/node_modules/lodash/bind.js
@@ -0,0 +1,57 @@
+var baseRest = require('./_baseRest'),
+ createWrap = require('./_createWrap'),
+ getHolder = require('./_getHolder'),
+ replaceHolders = require('./_replaceHolders');
+
+/** Used to compose bitmasks for function metadata. */
+var WRAP_BIND_FLAG = 1,
+ WRAP_PARTIAL_FLAG = 32;
+
+/**
+ * Creates a function that invokes `func` with the `this` binding of `thisArg`
+ * and `partials` prepended to the arguments it receives.
+ *
+ * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
+ * may be used as a placeholder for partially applied arguments.
+ *
+ * **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
+ * property of bound functions.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Function
+ * @param {Function} func The function to bind.
+ * @param {*} thisArg The `this` binding of `func`.
+ * @param {...*} [partials] The arguments to be partially applied.
+ * @returns {Function} Returns the new bound function.
+ * @example
+ *
+ * function greet(greeting, punctuation) {
+ * return greeting + ' ' + this.user + punctuation;
+ * }
+ *
+ * var object = { 'user': 'fred' };
+ *
+ * var bound = _.bind(greet, object, 'hi');
+ * bound('!');
+ * // => 'hi fred!'
+ *
+ * // Bound with placeholders.
+ * var bound = _.bind(greet, object, _, '!');
+ * bound('hi');
+ * // => 'hi fred!'
+ */
+var bind = baseRest(function(func, thisArg, partials) {
+ var bitmask = WRAP_BIND_FLAG;
+ if (partials.length) {
+ var holders = replaceHolders(partials, getHolder(bind));
+ bitmask |= WRAP_PARTIAL_FLAG;
+ }
+ return createWrap(func, bitmask, thisArg, partials, holders);
+});
+
+// Assign default placeholders.
+bind.placeholder = {};
+
+module.exports = bind;
diff --git a/node_modules/lodash/bindAll.js b/node_modules/lodash/bindAll.js
new file mode 100644
index 0000000..a35706d
--- /dev/null
+++ b/node_modules/lodash/bindAll.js
@@ -0,0 +1,41 @@
+var arrayEach = require('./_arrayEach'),
+ baseAssignValue = require('./_baseAssignValue'),
+ bind = require('./bind'),
+ flatRest = require('./_flatRest'),
+ toKey = require('./_toKey');
+
+/**
+ * Binds methods of an object to the object itself, overwriting the existing
+ * method.
+ *
+ * **Note:** This method doesn't set the "length" property of bound functions.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Util
+ * @param {Object} object The object to bind and assign the bound methods to.
+ * @param {...(string|string[])} methodNames The object method names to bind.
+ * @returns {Object} Returns `object`.
+ * @example
+ *
+ * var view = {
+ * 'label': 'docs',
+ * 'click': function() {
+ * console.log('clicked ' + this.label);
+ * }
+ * };
+ *
+ * _.bindAll(view, ['click']);
+ * jQuery(element).on('click', view.click);
+ * // => Logs 'clicked docs' when clicked.
+ */
+var bindAll = flatRest(function(object, methodNames) {
+ arrayEach(methodNames, function(key) {
+ key = toKey(key);
+ baseAssignValue(object, key, bind(object[key], object));
+ });
+ return object;
+});
+
+module.exports = bindAll;
diff --git a/node_modules/lodash/bindKey.js b/node_modules/lodash/bindKey.js
new file mode 100644
index 0000000..f7fd64c
--- /dev/null
+++ b/node_modules/lodash/bindKey.js
@@ -0,0 +1,68 @@
+var baseRest = require('./_baseRest'),
+ createWrap = require('./_createWrap'),
+ getHolder = require('./_getHolder'),
+ replaceHolders = require('./_replaceHolders');
+
+/** Used to compose bitmasks for function metadata. */
+var WRAP_BIND_FLAG = 1,
+ WRAP_BIND_KEY_FLAG = 2,
+ WRAP_PARTIAL_FLAG = 32;
+
+/**
+ * Creates a function that invokes the method at `object[key]` with `partials`
+ * prepended to the arguments it receives.
+ *
+ * This method differs from `_.bind` by allowing bound functions to reference
+ * methods that may be redefined or don't yet exist. See
+ * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
+ * for more details.
+ *
+ * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
+ * builds, may be used as a placeholder for partially applied arguments.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.10.0
+ * @category Function
+ * @param {Object} object The object to invoke the method on.
+ * @param {string} key The key of the method.
+ * @param {...*} [partials] The arguments to be partially applied.
+ * @returns {Function} Returns the new bound function.
+ * @example
+ *
+ * var object = {
+ * 'user': 'fred',
+ * 'greet': function(greeting, punctuation) {
+ * return greeting + ' ' + this.user + punctuation;
+ * }
+ * };
+ *
+ * var bound = _.bindKey(object, 'greet', 'hi');
+ * bound('!');
+ * // => 'hi fred!'
+ *
+ * object.greet = function(greeting, punctuation) {
+ * return greeting + 'ya ' + this.user + punctuation;
+ * };
+ *
+ * bound('!');
+ * // => 'hiya fred!'
+ *
+ * // Bound with placeholders.
+ * var bound = _.bindKey(object, 'greet', _, '!');
+ * bound('hi');
+ * // => 'hiya fred!'
+ */
+var bindKey = baseRest(function(object, key, partials) {
+ var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
+ if (partials.length) {
+ var holders = replaceHolders(partials, getHolder(bindKey));
+ bitmask |= WRAP_PARTIAL_FLAG;
+ }
+ return createWrap(key, bitmask, object, partials, holders);
+});
+
+// Assign default placeholders.
+bindKey.placeholder = {};
+
+module.exports = bindKey;
diff --git a/node_modules/lodash/camelCase.js b/node_modules/lodash/camelCase.js
new file mode 100644
index 0000000..d7390de
--- /dev/null
+++ b/node_modules/lodash/camelCase.js
@@ -0,0 +1,29 @@
+var capitalize = require('./capitalize'),
+ createCompounder = require('./_createCompounder');
+
+/**
+ * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category String
+ * @param {string} [string=''] The string to convert.
+ * @returns {string} Returns the camel cased string.
+ * @example
+ *
+ * _.camelCase('Foo Bar');
+ * // => 'fooBar'
+ *
+ * _.camelCase('--foo-bar--');
+ * // => 'fooBar'
+ *
+ * _.camelCase('__FOO_BAR__');
+ * // => 'fooBar'
+ */
+var camelCase = createCompounder(function(result, word, index) {
+ word = word.toLowerCase();
+ return result + (index ? capitalize(word) : word);
+});
+
+module.exports = camelCase;
diff --git a/node_modules/lodash/capitalize.js b/node_modules/lodash/capitalize.js
new file mode 100644
index 0000000..3e1600e
--- /dev/null
+++ b/node_modules/lodash/capitalize.js
@@ -0,0 +1,23 @@
+var toString = require('./toString'),
+ upperFirst = require('./upperFirst');
+
+/**
+ * Converts the first character of `string` to upper case and the remaining
+ * to lower case.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category String
+ * @param {string} [string=''] The string to capitalize.
+ * @returns {string} Returns the capitalized string.
+ * @example
+ *
+ * _.capitalize('FRED');
+ * // => 'Fred'
+ */
+function capitalize(string) {
+ return upperFirst(toString(string).toLowerCase());
+}
+
+module.exports = capitalize;
diff --git a/node_modules/lodash/castArray.js b/node_modules/lodash/castArray.js
new file mode 100644
index 0000000..e470bdb
--- /dev/null
+++ b/node_modules/lodash/castArray.js
@@ -0,0 +1,44 @@
+var isArray = require('./isArray');
+
+/**
+ * Casts `value` as an array if it's not one.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.4.0
+ * @category Lang
+ * @param {*} value The value to inspect.
+ * @returns {Array} Returns the cast array.
+ * @example
+ *
+ * _.castArray(1);
+ * // => [1]
+ *
+ * _.castArray({ 'a': 1 });
+ * // => [{ 'a': 1 }]
+ *
+ * _.castArray('abc');
+ * // => ['abc']
+ *
+ * _.castArray(null);
+ * // => [null]
+ *
+ * _.castArray(undefined);
+ * // => [undefined]
+ *
+ * _.castArray();
+ * // => []
+ *
+ * var array = [1, 2, 3];
+ * console.log(_.castArray(array) === array);
+ * // => true
+ */
+function castArray() {
+ if (!arguments.length) {
+ return [];
+ }
+ var value = arguments[0];
+ return isArray(value) ? value : [value];
+}
+
+module.exports = castArray;
diff --git a/node_modules/lodash/ceil.js b/node_modules/lodash/ceil.js
new file mode 100644
index 0000000..56c8722
--- /dev/null
+++ b/node_modules/lodash/ceil.js
@@ -0,0 +1,26 @@
+var createRound = require('./_createRound');
+
+/**
+ * Computes `number` rounded up to `precision`.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.10.0
+ * @category Math
+ * @param {number} number The number to round up.
+ * @param {number} [precision=0] The precision to round up to.
+ * @returns {number} Returns the rounded up number.
+ * @example
+ *
+ * _.ceil(4.006);
+ * // => 5
+ *
+ * _.ceil(6.004, 2);
+ * // => 6.01
+ *
+ * _.ceil(6040, -2);
+ * // => 6100
+ */
+var ceil = createRound('ceil');
+
+module.exports = ceil;
diff --git a/node_modules/lodash/chain.js b/node_modules/lodash/chain.js
new file mode 100644
index 0000000..f6cd647
--- /dev/null
+++ b/node_modules/lodash/chain.js
@@ -0,0 +1,38 @@
+var lodash = require('./wrapperLodash');
+
+/**
+ * Creates a `lodash` wrapper instance that wraps `value` with explicit method
+ * chain sequences enabled. The result of such sequences must be unwrapped
+ * with `_#value`.
+ *
+ * @static
+ * @memberOf _
+ * @since 1.3.0
+ * @category Seq
+ * @param {*} value The value to wrap.
+ * @returns {Object} Returns the new `lodash` wrapper instance.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36 },
+ * { 'user': 'fred', 'age': 40 },
+ * { 'user': 'pebbles', 'age': 1 }
+ * ];
+ *
+ * var youngest = _
+ * .chain(users)
+ * .sortBy('age')
+ * .map(function(o) {
+ * return o.user + ' is ' + o.age;
+ * })
+ * .head()
+ * .value();
+ * // => 'pebbles is 1'
+ */
+function chain(value) {
+ var result = lodash(value);
+ result.__chain__ = true;
+ return result;
+}
+
+module.exports = chain;
diff --git a/node_modules/lodash/chunk.js b/node_modules/lodash/chunk.js
new file mode 100644
index 0000000..5b562fe
--- /dev/null
+++ b/node_modules/lodash/chunk.js
@@ -0,0 +1,50 @@
+var baseSlice = require('./_baseSlice'),
+ isIterateeCall = require('./_isIterateeCall'),
+ toInteger = require('./toInteger');
+
+/* Built-in method references for those with the same name as other `lodash` methods. */
+var nativeCeil = Math.ceil,
+ nativeMax = Math.max;
+
+/**
+ * Creates an array of elements split into groups the length of `size`.
+ * If `array` can't be split evenly, the final chunk will be the remaining
+ * elements.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category Array
+ * @param {Array} array The array to process.
+ * @param {number} [size=1] The length of each chunk
+ * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
+ * @returns {Array} Returns the new array of chunks.
+ * @example
+ *
+ * _.chunk(['a', 'b', 'c', 'd'], 2);
+ * // => [['a', 'b'], ['c', 'd']]
+ *
+ * _.chunk(['a', 'b', 'c', 'd'], 3);
+ * // => [['a', 'b', 'c'], ['d']]
+ */
+function chunk(array, size, guard) {
+ if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
+ size = 1;
+ } else {
+ size = nativeMax(toInteger(size), 0);
+ }
+ var length = array == null ? 0 : array.length;
+ if (!length || size < 1) {
+ return [];
+ }
+ var index = 0,
+ resIndex = 0,
+ result = Array(nativeCeil(length / size));
+
+ while (index < length) {
+ result[resIndex++] = baseSlice(array, index, (index += size));
+ }
+ return result;
+}
+
+module.exports = chunk;
diff --git a/node_modules/lodash/clamp.js b/node_modules/lodash/clamp.js
new file mode 100644
index 0000000..91a72c9
--- /dev/null
+++ b/node_modules/lodash/clamp.js
@@ -0,0 +1,39 @@
+var baseClamp = require('./_baseClamp'),
+ toNumber = require('./toNumber');
+
+/**
+ * Clamps `number` within the inclusive `lower` and `upper` bounds.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Number
+ * @param {number} number The number to clamp.
+ * @param {number} [lower] The lower bound.
+ * @param {number} upper The upper bound.
+ * @returns {number} Returns the clamped number.
+ * @example
+ *
+ * _.clamp(-10, -5, 5);
+ * // => -5
+ *
+ * _.clamp(10, -5, 5);
+ * // => 5
+ */
+function clamp(number, lower, upper) {
+ if (upper === undefined) {
+ upper = lower;
+ lower = undefined;
+ }
+ if (upper !== undefined) {
+ upper = toNumber(upper);
+ upper = upper === upper ? upper : 0;
+ }
+ if (lower !== undefined) {
+ lower = toNumber(lower);
+ lower = lower === lower ? lower : 0;
+ }
+ return baseClamp(toNumber(number), lower, upper);
+}
+
+module.exports = clamp;
diff --git a/node_modules/lodash/clone.js b/node_modules/lodash/clone.js
new file mode 100644
index 0000000..dd439d6
--- /dev/null
+++ b/node_modules/lodash/clone.js
@@ -0,0 +1,36 @@
+var baseClone = require('./_baseClone');
+
+/** Used to compose bitmasks for cloning. */
+var CLONE_SYMBOLS_FLAG = 4;
+
+/**
+ * Creates a shallow clone of `value`.
+ *
+ * **Note:** This method is loosely based on the
+ * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
+ * and supports cloning arrays, array buffers, booleans, date objects, maps,
+ * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
+ * arrays. The own enumerable properties of `arguments` objects are cloned
+ * as plain objects. An empty object is returned for uncloneable values such
+ * as error objects, functions, DOM nodes, and WeakMaps.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to clone.
+ * @returns {*} Returns the cloned value.
+ * @see _.cloneDeep
+ * @example
+ *
+ * var objects = [{ 'a': 1 }, { 'b': 2 }];
+ *
+ * var shallow = _.clone(objects);
+ * console.log(shallow[0] === objects[0]);
+ * // => true
+ */
+function clone(value) {
+ return baseClone(value, CLONE_SYMBOLS_FLAG);
+}
+
+module.exports = clone;
diff --git a/node_modules/lodash/cloneDeep.js b/node_modules/lodash/cloneDeep.js
new file mode 100644
index 0000000..4425fbe
--- /dev/null
+++ b/node_modules/lodash/cloneDeep.js
@@ -0,0 +1,29 @@
+var baseClone = require('./_baseClone');
+
+/** Used to compose bitmasks for cloning. */
+var CLONE_DEEP_FLAG = 1,
+ CLONE_SYMBOLS_FLAG = 4;
+
+/**
+ * This method is like `_.clone` except that it recursively clones `value`.
+ *
+ * @static
+ * @memberOf _
+ * @since 1.0.0
+ * @category Lang
+ * @param {*} value The value to recursively clone.
+ * @returns {*} Returns the deep cloned value.
+ * @see _.clone
+ * @example
+ *
+ * var objects = [{ 'a': 1 }, { 'b': 2 }];
+ *
+ * var deep = _.cloneDeep(objects);
+ * console.log(deep[0] === objects[0]);
+ * // => false
+ */
+function cloneDeep(value) {
+ return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
+}
+
+module.exports = cloneDeep;
diff --git a/node_modules/lodash/cloneDeepWith.js b/node_modules/lodash/cloneDeepWith.js
new file mode 100644
index 0000000..fd9c6c0
--- /dev/null
+++ b/node_modules/lodash/cloneDeepWith.js
@@ -0,0 +1,40 @@
+var baseClone = require('./_baseClone');
+
+/** Used to compose bitmasks for cloning. */
+var CLONE_DEEP_FLAG = 1,
+ CLONE_SYMBOLS_FLAG = 4;
+
+/**
+ * This method is like `_.cloneWith` except that it recursively clones `value`.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to recursively clone.
+ * @param {Function} [customizer] The function to customize cloning.
+ * @returns {*} Returns the deep cloned value.
+ * @see _.cloneWith
+ * @example
+ *
+ * function customizer(value) {
+ * if (_.isElement(value)) {
+ * return value.cloneNode(true);
+ * }
+ * }
+ *
+ * var el = _.cloneDeepWith(document.body, customizer);
+ *
+ * console.log(el === document.body);
+ * // => false
+ * console.log(el.nodeName);
+ * // => 'BODY'
+ * console.log(el.childNodes.length);
+ * // => 20
+ */
+function cloneDeepWith(value, customizer) {
+ customizer = typeof customizer == 'function' ? customizer : undefined;
+ return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);
+}
+
+module.exports = cloneDeepWith;
diff --git a/node_modules/lodash/cloneWith.js b/node_modules/lodash/cloneWith.js
new file mode 100644
index 0000000..d2f4e75
--- /dev/null
+++ b/node_modules/lodash/cloneWith.js
@@ -0,0 +1,42 @@
+var baseClone = require('./_baseClone');
+
+/** Used to compose bitmasks for cloning. */
+var CLONE_SYMBOLS_FLAG = 4;
+
+/**
+ * This method is like `_.clone` except that it accepts `customizer` which
+ * is invoked to produce the cloned value. If `customizer` returns `undefined`,
+ * cloning is handled by the method instead. The `customizer` is invoked with
+ * up to four arguments; (value [, index|key, object, stack]).
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to clone.
+ * @param {Function} [customizer] The function to customize cloning.
+ * @returns {*} Returns the cloned value.
+ * @see _.cloneDeepWith
+ * @example
+ *
+ * function customizer(value) {
+ * if (_.isElement(value)) {
+ * return value.cloneNode(false);
+ * }
+ * }
+ *
+ * var el = _.cloneWith(document.body, customizer);
+ *
+ * console.log(el === document.body);
+ * // => false
+ * console.log(el.nodeName);
+ * // => 'BODY'
+ * console.log(el.childNodes.length);
+ * // => 0
+ */
+function cloneWith(value, customizer) {
+ customizer = typeof customizer == 'function' ? customizer : undefined;
+ return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);
+}
+
+module.exports = cloneWith;
diff --git a/node_modules/lodash/collection.js b/node_modules/lodash/collection.js
new file mode 100644
index 0000000..77fe837
--- /dev/null
+++ b/node_modules/lodash/collection.js
@@ -0,0 +1,30 @@
+module.exports = {
+ 'countBy': require('./countBy'),
+ 'each': require('./each'),
+ 'eachRight': require('./eachRight'),
+ 'every': require('./every'),
+ 'filter': require('./filter'),
+ 'find': require('./find'),
+ 'findLast': require('./findLast'),
+ 'flatMap': require('./flatMap'),
+ 'flatMapDeep': require('./flatMapDeep'),
+ 'flatMapDepth': require('./flatMapDepth'),
+ 'forEach': require('./forEach'),
+ 'forEachRight': require('./forEachRight'),
+ 'groupBy': require('./groupBy'),
+ 'includes': require('./includes'),
+ 'invokeMap': require('./invokeMap'),
+ 'keyBy': require('./keyBy'),
+ 'map': require('./map'),
+ 'orderBy': require('./orderBy'),
+ 'partition': require('./partition'),
+ 'reduce': require('./reduce'),
+ 'reduceRight': require('./reduceRight'),
+ 'reject': require('./reject'),
+ 'sample': require('./sample'),
+ 'sampleSize': require('./sampleSize'),
+ 'shuffle': require('./shuffle'),
+ 'size': require('./size'),
+ 'some': require('./some'),
+ 'sortBy': require('./sortBy')
+};
diff --git a/node_modules/lodash/commit.js b/node_modules/lodash/commit.js
new file mode 100644
index 0000000..fe4db71
--- /dev/null
+++ b/node_modules/lodash/commit.js
@@ -0,0 +1,33 @@
+var LodashWrapper = require('./_LodashWrapper');
+
+/**
+ * Executes the chain sequence and returns the wrapped result.
+ *
+ * @name commit
+ * @memberOf _
+ * @since 3.2.0
+ * @category Seq
+ * @returns {Object} Returns the new `lodash` wrapper instance.
+ * @example
+ *
+ * var array = [1, 2];
+ * var wrapped = _(array).push(3);
+ *
+ * console.log(array);
+ * // => [1, 2]
+ *
+ * wrapped = wrapped.commit();
+ * console.log(array);
+ * // => [1, 2, 3]
+ *
+ * wrapped.last();
+ * // => 3
+ *
+ * console.log(array);
+ * // => [1, 2, 3]
+ */
+function wrapperCommit() {
+ return new LodashWrapper(this.value(), this.__chain__);
+}
+
+module.exports = wrapperCommit;
diff --git a/node_modules/lodash/compact.js b/node_modules/lodash/compact.js
new file mode 100644
index 0000000..031fab4
--- /dev/null
+++ b/node_modules/lodash/compact.js
@@ -0,0 +1,31 @@
+/**
+ * Creates an array with all falsey values removed. The values `false`, `null`,
+ * `0`, `""`, `undefined`, and `NaN` are falsey.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Array
+ * @param {Array} array The array to compact.
+ * @returns {Array} Returns the new array of filtered values.
+ * @example
+ *
+ * _.compact([0, 1, false, 2, '', 3]);
+ * // => [1, 2, 3]
+ */
+function compact(array) {
+ var index = -1,
+ length = array == null ? 0 : array.length,
+ resIndex = 0,
+ result = [];
+
+ while (++index < length) {
+ var value = array[index];
+ if (value) {
+ result[resIndex++] = value;
+ }
+ }
+ return result;
+}
+
+module.exports = compact;
diff --git a/node_modules/lodash/concat.js b/node_modules/lodash/concat.js
new file mode 100644
index 0000000..1da48a4
--- /dev/null
+++ b/node_modules/lodash/concat.js
@@ -0,0 +1,43 @@
+var arrayPush = require('./_arrayPush'),
+ baseFlatten = require('./_baseFlatten'),
+ copyArray = require('./_copyArray'),
+ isArray = require('./isArray');
+
+/**
+ * Creates a new array concatenating `array` with any additional arrays
+ * and/or values.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Array
+ * @param {Array} array The array to concatenate.
+ * @param {...*} [values] The values to concatenate.
+ * @returns {Array} Returns the new concatenated array.
+ * @example
+ *
+ * var array = [1];
+ * var other = _.concat(array, 2, [3], [[4]]);
+ *
+ * console.log(other);
+ * // => [1, 2, 3, [4]]
+ *
+ * console.log(array);
+ * // => [1]
+ */
+function concat() {
+ var length = arguments.length;
+ if (!length) {
+ return [];
+ }
+ var args = Array(length - 1),
+ array = arguments[0],
+ index = length;
+
+ while (index--) {
+ args[index - 1] = arguments[index];
+ }
+ return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
+}
+
+module.exports = concat;
diff --git a/node_modules/lodash/cond.js b/node_modules/lodash/cond.js
new file mode 100644
index 0000000..6455598
--- /dev/null
+++ b/node_modules/lodash/cond.js
@@ -0,0 +1,60 @@
+var apply = require('./_apply'),
+ arrayMap = require('./_arrayMap'),
+ baseIteratee = require('./_baseIteratee'),
+ baseRest = require('./_baseRest');
+
+/** Error message constants. */
+var FUNC_ERROR_TEXT = 'Expected a function';
+
+/**
+ * Creates a function that iterates over `pairs` and invokes the corresponding
+ * function of the first predicate to return truthy. The predicate-function
+ * pairs are invoked with the `this` binding and arguments of the created
+ * function.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Util
+ * @param {Array} pairs The predicate-function pairs.
+ * @returns {Function} Returns the new composite function.
+ * @example
+ *
+ * var func = _.cond([
+ * [_.matches({ 'a': 1 }), _.constant('matches A')],
+ * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
+ * [_.stubTrue, _.constant('no match')]
+ * ]);
+ *
+ * func({ 'a': 1, 'b': 2 });
+ * // => 'matches A'
+ *
+ * func({ 'a': 0, 'b': 1 });
+ * // => 'matches B'
+ *
+ * func({ 'a': '1', 'b': '2' });
+ * // => 'no match'
+ */
+function cond(pairs) {
+ var length = pairs == null ? 0 : pairs.length,
+ toIteratee = baseIteratee;
+
+ pairs = !length ? [] : arrayMap(pairs, function(pair) {
+ if (typeof pair[1] != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ return [toIteratee(pair[0]), pair[1]];
+ });
+
+ return baseRest(function(args) {
+ var index = -1;
+ while (++index < length) {
+ var pair = pairs[index];
+ if (apply(pair[0], this, args)) {
+ return apply(pair[1], this, args);
+ }
+ }
+ });
+}
+
+module.exports = cond;
diff --git a/node_modules/lodash/conforms.js b/node_modules/lodash/conforms.js
new file mode 100644
index 0000000..5501a94
--- /dev/null
+++ b/node_modules/lodash/conforms.js
@@ -0,0 +1,35 @@
+var baseClone = require('./_baseClone'),
+ baseConforms = require('./_baseConforms');
+
+/** Used to compose bitmasks for cloning. */
+var CLONE_DEEP_FLAG = 1;
+
+/**
+ * Creates a function that invokes the predicate properties of `source` with
+ * the corresponding property values of a given object, returning `true` if
+ * all predicates return truthy, else `false`.
+ *
+ * **Note:** The created function is equivalent to `_.conformsTo` with
+ * `source` partially applied.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Util
+ * @param {Object} source The object of property predicates to conform to.
+ * @returns {Function} Returns the new spec function.
+ * @example
+ *
+ * var objects = [
+ * { 'a': 2, 'b': 1 },
+ * { 'a': 1, 'b': 2 }
+ * ];
+ *
+ * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
+ * // => [{ 'a': 1, 'b': 2 }]
+ */
+function conforms(source) {
+ return baseConforms(baseClone(source, CLONE_DEEP_FLAG));
+}
+
+module.exports = conforms;
diff --git a/node_modules/lodash/conformsTo.js b/node_modules/lodash/conformsTo.js
new file mode 100644
index 0000000..b8a93eb
--- /dev/null
+++ b/node_modules/lodash/conformsTo.js
@@ -0,0 +1,32 @@
+var baseConformsTo = require('./_baseConformsTo'),
+ keys = require('./keys');
+
+/**
+ * Checks if `object` conforms to `source` by invoking the predicate
+ * properties of `source` with the corresponding property values of `object`.
+ *
+ * **Note:** This method is equivalent to `_.conforms` when `source` is
+ * partially applied.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.14.0
+ * @category Lang
+ * @param {Object} object The object to inspect.
+ * @param {Object} source The object of property predicates to conform to.
+ * @returns {boolean} Returns `true` if `object` conforms, else `false`.
+ * @example
+ *
+ * var object = { 'a': 1, 'b': 2 };
+ *
+ * _.conformsTo(object, { 'b': function(n) { return n > 1; } });
+ * // => true
+ *
+ * _.conformsTo(object, { 'b': function(n) { return n > 2; } });
+ * // => false
+ */
+function conformsTo(object, source) {
+ return source == null || baseConformsTo(object, source, keys(source));
+}
+
+module.exports = conformsTo;
diff --git a/node_modules/lodash/constant.js b/node_modules/lodash/constant.js
new file mode 100644
index 0000000..655ece3
--- /dev/null
+++ b/node_modules/lodash/constant.js
@@ -0,0 +1,26 @@
+/**
+ * Creates a function that returns `value`.
+ *
+ * @static
+ * @memberOf _
+ * @since 2.4.0
+ * @category Util
+ * @param {*} value The value to return from the new function.
+ * @returns {Function} Returns the new constant function.
+ * @example
+ *
+ * var objects = _.times(2, _.constant({ 'a': 1 }));
+ *
+ * console.log(objects);
+ * // => [{ 'a': 1 }, { 'a': 1 }]
+ *
+ * console.log(objects[0] === objects[1]);
+ * // => true
+ */
+function constant(value) {
+ return function() {
+ return value;
+ };
+}
+
+module.exports = constant;
diff --git a/node_modules/lodash/core.js b/node_modules/lodash/core.js
new file mode 100644
index 0000000..be1d567
--- /dev/null
+++ b/node_modules/lodash/core.js
@@ -0,0 +1,3877 @@
+/**
+ * @license
+ * Lodash (Custom Build)
+ * Build: `lodash core -o ./dist/lodash.core.js`
+ * Copyright OpenJS Foundation and other contributors
+ * Released under MIT license
+ * Based on Underscore.js 1.8.3
+ * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+ */
+;(function() {
+
+ /** Used as a safe reference for `undefined` in pre-ES5 environments. */
+ var undefined;
+
+ /** Used as the semantic version number. */
+ var VERSION = '4.17.21';
+
+ /** Error message constants. */
+ var FUNC_ERROR_TEXT = 'Expected a function';
+
+ /** Used to compose bitmasks for value comparisons. */
+ var COMPARE_PARTIAL_FLAG = 1,
+ COMPARE_UNORDERED_FLAG = 2;
+
+ /** Used to compose bitmasks for function metadata. */
+ var WRAP_BIND_FLAG = 1,
+ WRAP_PARTIAL_FLAG = 32;
+
+ /** Used as references for various `Number` constants. */
+ var INFINITY = 1 / 0,
+ MAX_SAFE_INTEGER = 9007199254740991;
+
+ /** `Object#toString` result references. */
+ var argsTag = '[object Arguments]',
+ arrayTag = '[object Array]',
+ asyncTag = '[object AsyncFunction]',
+ boolTag = '[object Boolean]',
+ dateTag = '[object Date]',
+ errorTag = '[object Error]',
+ funcTag = '[object Function]',
+ genTag = '[object GeneratorFunction]',
+ numberTag = '[object Number]',
+ objectTag = '[object Object]',
+ proxyTag = '[object Proxy]',
+ regexpTag = '[object RegExp]',
+ stringTag = '[object String]';
+
+ /** Used to match HTML entities and HTML characters. */
+ var reUnescapedHtml = /[&<>"']/g,
+ reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
+
+ /** Used to detect unsigned integer values. */
+ var reIsUint = /^(?:0|[1-9]\d*)$/;
+
+ /** Used to map characters to HTML entities. */
+ var htmlEscapes = {
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ "'": '''
+ };
+
+ /** Detect free variable `global` from Node.js. */
+ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
+
+ /** Detect free variable `self`. */
+ var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
+
+ /** Used as a reference to the global object. */
+ var root = freeGlobal || freeSelf || Function('return this')();
+
+ /** Detect free variable `exports`. */
+ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
+
+ /** Detect free variable `module`. */
+ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
+
+ /*--------------------------------------------------------------------------*/
+
+ /**
+ * Appends the elements of `values` to `array`.
+ *
+ * @private
+ * @param {Array} array The array to modify.
+ * @param {Array} values The values to append.
+ * @returns {Array} Returns `array`.
+ */
+ function arrayPush(array, values) {
+ array.push.apply(array, values);
+ return array;
+ }
+
+ /**
+ * The base implementation of `_.findIndex` and `_.findLastIndex` without
+ * support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array} array The array to inspect.
+ * @param {Function} predicate The function invoked per iteration.
+ * @param {number} fromIndex The index to search from.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ */
+ function baseFindIndex(array, predicate, fromIndex, fromRight) {
+ var length = array.length,
+ index = fromIndex + (fromRight ? 1 : -1);
+
+ while ((fromRight ? index-- : ++index < length)) {
+ if (predicate(array[index], index, array)) {
+ return index;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ * The base implementation of `_.property` without support for deep paths.
+ *
+ * @private
+ * @param {string} key The key of the property to get.
+ * @returns {Function} Returns the new accessor function.
+ */
+ function baseProperty(key) {
+ return function(object) {
+ return object == null ? undefined : object[key];
+ };
+ }
+
+ /**
+ * The base implementation of `_.propertyOf` without support for deep paths.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Function} Returns the new accessor function.
+ */
+ function basePropertyOf(object) {
+ return function(key) {
+ return object == null ? undefined : object[key];
+ };
+ }
+
+ /**
+ * The base implementation of `_.reduce` and `_.reduceRight`, without support
+ * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {*} accumulator The initial value.
+ * @param {boolean} initAccum Specify using the first or last element of
+ * `collection` as the initial value.
+ * @param {Function} eachFunc The function to iterate over `collection`.
+ * @returns {*} Returns the accumulated value.
+ */
+ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
+ eachFunc(collection, function(value, index, collection) {
+ accumulator = initAccum
+ ? (initAccum = false, value)
+ : iteratee(accumulator, value, index, collection);
+ });
+ return accumulator;
+ }
+
+ /**
+ * The base implementation of `_.values` and `_.valuesIn` which creates an
+ * array of `object` property values corresponding to the property names
+ * of `props`.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @param {Array} props The property names to get values for.
+ * @returns {Object} Returns the array of property values.
+ */
+ function baseValues(object, props) {
+ return baseMap(props, function(key) {
+ return object[key];
+ });
+ }
+
+ /**
+ * Used by `_.escape` to convert characters to HTML entities.
+ *
+ * @private
+ * @param {string} chr The matched character to escape.
+ * @returns {string} Returns the escaped character.
+ */
+ var escapeHtmlChar = basePropertyOf(htmlEscapes);
+
+ /**
+ * Creates a unary function that invokes `func` with its argument transformed.
+ *
+ * @private
+ * @param {Function} func The function to wrap.
+ * @param {Function} transform The argument transform.
+ * @returns {Function} Returns the new function.
+ */
+ function overArg(func, transform) {
+ return function(arg) {
+ return func(transform(arg));
+ };
+ }
+
+ /*--------------------------------------------------------------------------*/
+
+ /** Used for built-in method references. */
+ var arrayProto = Array.prototype,
+ objectProto = Object.prototype;
+
+ /** Used to check objects for own properties. */
+ var hasOwnProperty = objectProto.hasOwnProperty;
+
+ /** Used to generate unique IDs. */
+ var idCounter = 0;
+
+ /**
+ * Used to resolve the
+ * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
+ * of values.
+ */
+ var nativeObjectToString = objectProto.toString;
+
+ /** Used to restore the original `_` reference in `_.noConflict`. */
+ var oldDash = root._;
+
+ /** Built-in value references. */
+ var objectCreate = Object.create,
+ propertyIsEnumerable = objectProto.propertyIsEnumerable;
+
+ /* Built-in method references for those with the same name as other `lodash` methods. */
+ var nativeIsFinite = root.isFinite,
+ nativeKeys = overArg(Object.keys, Object),
+ nativeMax = Math.max;
+
+ /*------------------------------------------------------------------------*/
+
+ /**
+ * Creates a `lodash` object which wraps `value` to enable implicit method
+ * chain sequences. Methods that operate on and return arrays, collections,
+ * and functions can be chained together. Methods that retrieve a single value
+ * or may return a primitive value will automatically end the chain sequence
+ * and return the unwrapped value. Otherwise, the value must be unwrapped
+ * with `_#value`.
+ *
+ * Explicit chain sequences, which must be unwrapped with `_#value`, may be
+ * enabled using `_.chain`.
+ *
+ * The execution of chained methods is lazy, that is, it's deferred until
+ * `_#value` is implicitly or explicitly called.
+ *
+ * Lazy evaluation allows several methods to support shortcut fusion.
+ * Shortcut fusion is an optimization to merge iteratee calls; this avoids
+ * the creation of intermediate arrays and can greatly reduce the number of
+ * iteratee executions. Sections of a chain sequence qualify for shortcut
+ * fusion if the section is applied to an array and iteratees accept only
+ * one argument. The heuristic for whether a section qualifies for shortcut
+ * fusion is subject to change.
+ *
+ * Chaining is supported in custom builds as long as the `_#value` method is
+ * directly or indirectly included in the build.
+ *
+ * In addition to lodash methods, wrappers have `Array` and `String` methods.
+ *
+ * The wrapper `Array` methods are:
+ * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
+ *
+ * The wrapper `String` methods are:
+ * `replace` and `split`
+ *
+ * The wrapper methods that support shortcut fusion are:
+ * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
+ * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
+ * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
+ *
+ * The chainable wrapper methods are:
+ * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
+ * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
+ * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
+ * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
+ * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
+ * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
+ * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
+ * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
+ * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
+ * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
+ * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
+ * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
+ * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
+ * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
+ * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
+ * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
+ * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
+ * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
+ * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
+ * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
+ * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
+ * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
+ * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
+ * `zipObject`, `zipObjectDeep`, and `zipWith`
+ *
+ * The wrapper methods that are **not** chainable by default are:
+ * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
+ * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
+ * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
+ * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
+ * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
+ * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
+ * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
+ * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
+ * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
+ * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
+ * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
+ * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
+ * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
+ * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
+ * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
+ * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
+ * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
+ * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
+ * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
+ * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
+ * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
+ * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
+ * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
+ * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
+ * `upperFirst`, `value`, and `words`
+ *
+ * @name _
+ * @constructor
+ * @category Seq
+ * @param {*} value The value to wrap in a `lodash` instance.
+ * @returns {Object} Returns the new `lodash` wrapper instance.
+ * @example
+ *
+ * function square(n) {
+ * return n * n;
+ * }
+ *
+ * var wrapped = _([1, 2, 3]);
+ *
+ * // Returns an unwrapped value.
+ * wrapped.reduce(_.add);
+ * // => 6
+ *
+ * // Returns a wrapped value.
+ * var squares = wrapped.map(square);
+ *
+ * _.isArray(squares);
+ * // => false
+ *
+ * _.isArray(squares.value());
+ * // => true
+ */
+ function lodash(value) {
+ return value instanceof LodashWrapper
+ ? value
+ : new LodashWrapper(value);
+ }
+
+ /**
+ * The base implementation of `_.create` without support for assigning
+ * properties to the created object.
+ *
+ * @private
+ * @param {Object} proto The object to inherit from.
+ * @returns {Object} Returns the new object.
+ */
+ var baseCreate = (function() {
+ function object() {}
+ return function(proto) {
+ if (!isObject(proto)) {
+ return {};
+ }
+ if (objectCreate) {
+ return objectCreate(proto);
+ }
+ object.prototype = proto;
+ var result = new object;
+ object.prototype = undefined;
+ return result;
+ };
+ }());
+
+ /**
+ * The base constructor for creating `lodash` wrapper objects.
+ *
+ * @private
+ * @param {*} value The value to wrap.
+ * @param {boolean} [chainAll] Enable explicit method chain sequences.
+ */
+ function LodashWrapper(value, chainAll) {
+ this.__wrapped__ = value;
+ this.__actions__ = [];
+ this.__chain__ = !!chainAll;
+ }
+
+ LodashWrapper.prototype = baseCreate(lodash.prototype);
+ LodashWrapper.prototype.constructor = LodashWrapper;
+
+ /*------------------------------------------------------------------------*/
+
+ /**
+ * Assigns `value` to `key` of `object` if the existing value is not equivalent
+ * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
+ * for equality comparisons.
+ *
+ * @private
+ * @param {Object} object The object to modify.
+ * @param {string} key The key of the property to assign.
+ * @param {*} value The value to assign.
+ */
+ function assignValue(object, key, value) {
+ var objValue = object[key];
+ if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
+ (value === undefined && !(key in object))) {
+ baseAssignValue(object, key, value);
+ }
+ }
+
+ /**
+ * The base implementation of `assignValue` and `assignMergeValue` without
+ * value checks.
+ *
+ * @private
+ * @param {Object} object The object to modify.
+ * @param {string} key The key of the property to assign.
+ * @param {*} value The value to assign.
+ */
+ function baseAssignValue(object, key, value) {
+ object[key] = value;
+ }
+
+ /**
+ * The base implementation of `_.delay` and `_.defer` which accepts `args`
+ * to provide to `func`.
+ *
+ * @private
+ * @param {Function} func The function to delay.
+ * @param {number} wait The number of milliseconds to delay invocation.
+ * @param {Array} args The arguments to provide to `func`.
+ * @returns {number|Object} Returns the timer id or timeout object.
+ */
+ function baseDelay(func, wait, args) {
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ return setTimeout(function() { func.apply(undefined, args); }, wait);
+ }
+
+ /**
+ * The base implementation of `_.forEach` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array|Object} Returns `collection`.
+ */
+ var baseEach = createBaseEach(baseForOwn);
+
+ /**
+ * The base implementation of `_.every` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {boolean} Returns `true` if all elements pass the predicate check,
+ * else `false`
+ */
+ function baseEvery(collection, predicate) {
+ var result = true;
+ baseEach(collection, function(value, index, collection) {
+ result = !!predicate(value, index, collection);
+ return result;
+ });
+ return result;
+ }
+
+ /**
+ * The base implementation of methods like `_.max` and `_.min` which accepts a
+ * `comparator` to determine the extremum value.
+ *
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} iteratee The iteratee invoked per iteration.
+ * @param {Function} comparator The comparator used to compare values.
+ * @returns {*} Returns the extremum value.
+ */
+ function baseExtremum(array, iteratee, comparator) {
+ var index = -1,
+ length = array.length;
+
+ while (++index < length) {
+ var value = array[index],
+ current = iteratee(value);
+
+ if (current != null && (computed === undefined
+ ? (current === current && !false)
+ : comparator(current, computed)
+ )) {
+ var computed = current,
+ result = value;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * The base implementation of `_.filter` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {Array} Returns the new filtered array.
+ */
+ function baseFilter(collection, predicate) {
+ var result = [];
+ baseEach(collection, function(value, index, collection) {
+ if (predicate(value, index, collection)) {
+ result.push(value);
+ }
+ });
+ return result;
+ }
+
+ /**
+ * The base implementation of `_.flatten` with support for restricting flattening.
+ *
+ * @private
+ * @param {Array} array The array to flatten.
+ * @param {number} depth The maximum recursion depth.
+ * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
+ * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
+ * @param {Array} [result=[]] The initial result value.
+ * @returns {Array} Returns the new flattened array.
+ */
+ function baseFlatten(array, depth, predicate, isStrict, result) {
+ var index = -1,
+ length = array.length;
+
+ predicate || (predicate = isFlattenable);
+ result || (result = []);
+
+ while (++index < length) {
+ var value = array[index];
+ if (depth > 0 && predicate(value)) {
+ if (depth > 1) {
+ // Recursively flatten arrays (susceptible to call stack limits).
+ baseFlatten(value, depth - 1, predicate, isStrict, result);
+ } else {
+ arrayPush(result, value);
+ }
+ } else if (!isStrict) {
+ result[result.length] = value;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * The base implementation of `baseForOwn` which iterates over `object`
+ * properties returned by `keysFunc` and invokes `iteratee` for each property.
+ * Iteratee functions may exit iteration early by explicitly returning `false`.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @param {Function} keysFunc The function to get the keys of `object`.
+ * @returns {Object} Returns `object`.
+ */
+ var baseFor = createBaseFor();
+
+ /**
+ * The base implementation of `_.forOwn` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Object} object The object to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Object} Returns `object`.
+ */
+ function baseForOwn(object, iteratee) {
+ return object && baseFor(object, iteratee, keys);
+ }
+
+ /**
+ * The base implementation of `_.functions` which creates an array of
+ * `object` function property names filtered from `props`.
+ *
+ * @private
+ * @param {Object} object The object to inspect.
+ * @param {Array} props The property names to filter.
+ * @returns {Array} Returns the function names.
+ */
+ function baseFunctions(object, props) {
+ return baseFilter(props, function(key) {
+ return isFunction(object[key]);
+ });
+ }
+
+ /**
+ * The base implementation of `getTag` without fallbacks for buggy environments.
+ *
+ * @private
+ * @param {*} value The value to query.
+ * @returns {string} Returns the `toStringTag`.
+ */
+ function baseGetTag(value) {
+ return objectToString(value);
+ }
+
+ /**
+ * The base implementation of `_.gt` which doesn't coerce arguments.
+ *
+ * @private
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {boolean} Returns `true` if `value` is greater than `other`,
+ * else `false`.
+ */
+ function baseGt(value, other) {
+ return value > other;
+ }
+
+ /**
+ * The base implementation of `_.isArguments`.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,
+ */
+ var baseIsArguments = noop;
+
+ /**
+ * The base implementation of `_.isDate` without Node.js optimizations.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
+ */
+ function baseIsDate(value) {
+ return isObjectLike(value) && baseGetTag(value) == dateTag;
+ }
+
+ /**
+ * The base implementation of `_.isEqual` which supports partial comparisons
+ * and tracks traversed objects.
+ *
+ * @private
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @param {boolean} bitmask The bitmask flags.
+ * 1 - Unordered comparison
+ * 2 - Partial comparison
+ * @param {Function} [customizer] The function to customize comparisons.
+ * @param {Object} [stack] Tracks traversed `value` and `other` objects.
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+ */
+ function baseIsEqual(value, other, bitmask, customizer, stack) {
+ if (value === other) {
+ return true;
+ }
+ if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
+ return value !== value && other !== other;
+ }
+ return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
+ }
+
+ /**
+ * A specialized version of `baseIsEqual` for arrays and objects which performs
+ * deep comparisons and tracks traversed objects enabling objects with circular
+ * references to be compared.
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
+ * @param {Function} customizer The function to customize comparisons.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Object} [stack] Tracks traversed `object` and `other` objects.
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ */
+ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
+ var objIsArr = isArray(object),
+ othIsArr = isArray(other),
+ objTag = objIsArr ? arrayTag : baseGetTag(object),
+ othTag = othIsArr ? arrayTag : baseGetTag(other);
+
+ objTag = objTag == argsTag ? objectTag : objTag;
+ othTag = othTag == argsTag ? objectTag : othTag;
+
+ var objIsObj = objTag == objectTag,
+ othIsObj = othTag == objectTag,
+ isSameTag = objTag == othTag;
+
+ stack || (stack = []);
+ var objStack = find(stack, function(entry) {
+ return entry[0] == object;
+ });
+ var othStack = find(stack, function(entry) {
+ return entry[0] == other;
+ });
+ if (objStack && othStack) {
+ return objStack[1] == other;
+ }
+ stack.push([object, other]);
+ stack.push([other, object]);
+ if (isSameTag && !objIsObj) {
+ var result = (objIsArr)
+ ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
+ : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
+ stack.pop();
+ return result;
+ }
+ if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
+ var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
+ othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
+
+ if (objIsWrapped || othIsWrapped) {
+ var objUnwrapped = objIsWrapped ? object.value() : object,
+ othUnwrapped = othIsWrapped ? other.value() : other;
+
+ var result = equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
+ stack.pop();
+ return result;
+ }
+ }
+ if (!isSameTag) {
+ return false;
+ }
+ var result = equalObjects(object, other, bitmask, customizer, equalFunc, stack);
+ stack.pop();
+ return result;
+ }
+
+ /**
+ * The base implementation of `_.isRegExp` without Node.js optimizations.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
+ */
+ function baseIsRegExp(value) {
+ return isObjectLike(value) && baseGetTag(value) == regexpTag;
+ }
+
+ /**
+ * The base implementation of `_.iteratee`.
+ *
+ * @private
+ * @param {*} [value=_.identity] The value to convert to an iteratee.
+ * @returns {Function} Returns the iteratee.
+ */
+ function baseIteratee(func) {
+ if (typeof func == 'function') {
+ return func;
+ }
+ if (func == null) {
+ return identity;
+ }
+ return (typeof func == 'object' ? baseMatches : baseProperty)(func);
+ }
+
+ /**
+ * The base implementation of `_.lt` which doesn't coerce arguments.
+ *
+ * @private
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {boolean} Returns `true` if `value` is less than `other`,
+ * else `false`.
+ */
+ function baseLt(value, other) {
+ return value < other;
+ }
+
+ /**
+ * The base implementation of `_.map` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} iteratee The function invoked per iteration.
+ * @returns {Array} Returns the new mapped array.
+ */
+ function baseMap(collection, iteratee) {
+ var index = -1,
+ result = isArrayLike(collection) ? Array(collection.length) : [];
+
+ baseEach(collection, function(value, key, collection) {
+ result[++index] = iteratee(value, key, collection);
+ });
+ return result;
+ }
+
+ /**
+ * The base implementation of `_.matches` which doesn't clone `source`.
+ *
+ * @private
+ * @param {Object} source The object of property values to match.
+ * @returns {Function} Returns the new spec function.
+ */
+ function baseMatches(source) {
+ var props = nativeKeys(source);
+ return function(object) {
+ var length = props.length;
+ if (object == null) {
+ return !length;
+ }
+ object = Object(object);
+ while (length--) {
+ var key = props[length];
+ if (!(key in object &&
+ baseIsEqual(source[key], object[key], COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG)
+ )) {
+ return false;
+ }
+ }
+ return true;
+ };
+ }
+
+ /**
+ * The base implementation of `_.pick` without support for individual
+ * property identifiers.
+ *
+ * @private
+ * @param {Object} object The source object.
+ * @param {string[]} paths The property paths to pick.
+ * @returns {Object} Returns the new object.
+ */
+ function basePick(object, props) {
+ object = Object(object);
+ return reduce(props, function(result, key) {
+ if (key in object) {
+ result[key] = object[key];
+ }
+ return result;
+ }, {});
+ }
+
+ /**
+ * The base implementation of `_.rest` which doesn't validate or coerce arguments.
+ *
+ * @private
+ * @param {Function} func The function to apply a rest parameter to.
+ * @param {number} [start=func.length-1] The start position of the rest parameter.
+ * @returns {Function} Returns the new function.
+ */
+ function baseRest(func, start) {
+ return setToString(overRest(func, start, identity), func + '');
+ }
+
+ /**
+ * The base implementation of `_.slice` without an iteratee call guard.
+ *
+ * @private
+ * @param {Array} array The array to slice.
+ * @param {number} [start=0] The start position.
+ * @param {number} [end=array.length] The end position.
+ * @returns {Array} Returns the slice of `array`.
+ */
+ function baseSlice(array, start, end) {
+ var index = -1,
+ length = array.length;
+
+ if (start < 0) {
+ start = -start > length ? 0 : (length + start);
+ }
+ end = end > length ? length : end;
+ if (end < 0) {
+ end += length;
+ }
+ length = start > end ? 0 : ((end - start) >>> 0);
+ start >>>= 0;
+
+ var result = Array(length);
+ while (++index < length) {
+ result[index] = array[index + start];
+ }
+ return result;
+ }
+
+ /**
+ * Copies the values of `source` to `array`.
+ *
+ * @private
+ * @param {Array} source The array to copy values from.
+ * @param {Array} [array=[]] The array to copy values to.
+ * @returns {Array} Returns `array`.
+ */
+ function copyArray(source) {
+ return baseSlice(source, 0, source.length);
+ }
+
+ /**
+ * The base implementation of `_.some` without support for iteratee shorthands.
+ *
+ * @private
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} predicate The function invoked per iteration.
+ * @returns {boolean} Returns `true` if any element passes the predicate check,
+ * else `false`.
+ */
+ function baseSome(collection, predicate) {
+ var result;
+
+ baseEach(collection, function(value, index, collection) {
+ result = predicate(value, index, collection);
+ return !result;
+ });
+ return !!result;
+ }
+
+ /**
+ * The base implementation of `wrapperValue` which returns the result of
+ * performing a sequence of actions on the unwrapped `value`, where each
+ * successive action is supplied the return value of the previous.
+ *
+ * @private
+ * @param {*} value The unwrapped value.
+ * @param {Array} actions Actions to perform to resolve the unwrapped value.
+ * @returns {*} Returns the resolved value.
+ */
+ function baseWrapperValue(value, actions) {
+ var result = value;
+ return reduce(actions, function(result, action) {
+ return action.func.apply(action.thisArg, arrayPush([result], action.args));
+ }, result);
+ }
+
+ /**
+ * Compares values to sort them in ascending order.
+ *
+ * @private
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {number} Returns the sort order indicator for `value`.
+ */
+ function compareAscending(value, other) {
+ if (value !== other) {
+ var valIsDefined = value !== undefined,
+ valIsNull = value === null,
+ valIsReflexive = value === value,
+ valIsSymbol = false;
+
+ var othIsDefined = other !== undefined,
+ othIsNull = other === null,
+ othIsReflexive = other === other,
+ othIsSymbol = false;
+
+ if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
+ (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
+ (valIsNull && othIsDefined && othIsReflexive) ||
+ (!valIsDefined && othIsReflexive) ||
+ !valIsReflexive) {
+ return 1;
+ }
+ if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
+ (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
+ (othIsNull && valIsDefined && valIsReflexive) ||
+ (!othIsDefined && valIsReflexive) ||
+ !othIsReflexive) {
+ return -1;
+ }
+ }
+ return 0;
+ }
+
+ /**
+ * Copies properties of `source` to `object`.
+ *
+ * @private
+ * @param {Object} source The object to copy properties from.
+ * @param {Array} props The property identifiers to copy.
+ * @param {Object} [object={}] The object to copy properties to.
+ * @param {Function} [customizer] The function to customize copied values.
+ * @returns {Object} Returns `object`.
+ */
+ function copyObject(source, props, object, customizer) {
+ var isNew = !object;
+ object || (object = {});
+
+ var index = -1,
+ length = props.length;
+
+ while (++index < length) {
+ var key = props[index];
+
+ var newValue = customizer
+ ? customizer(object[key], source[key], key, object, source)
+ : undefined;
+
+ if (newValue === undefined) {
+ newValue = source[key];
+ }
+ if (isNew) {
+ baseAssignValue(object, key, newValue);
+ } else {
+ assignValue(object, key, newValue);
+ }
+ }
+ return object;
+ }
+
+ /**
+ * Creates a function like `_.assign`.
+ *
+ * @private
+ * @param {Function} assigner The function to assign values.
+ * @returns {Function} Returns the new assigner function.
+ */
+ function createAssigner(assigner) {
+ return baseRest(function(object, sources) {
+ var index = -1,
+ length = sources.length,
+ customizer = length > 1 ? sources[length - 1] : undefined;
+
+ customizer = (assigner.length > 3 && typeof customizer == 'function')
+ ? (length--, customizer)
+ : undefined;
+
+ object = Object(object);
+ while (++index < length) {
+ var source = sources[index];
+ if (source) {
+ assigner(object, source, index, customizer);
+ }
+ }
+ return object;
+ });
+ }
+
+ /**
+ * Creates a `baseEach` or `baseEachRight` function.
+ *
+ * @private
+ * @param {Function} eachFunc The function to iterate over a collection.
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new base function.
+ */
+ function createBaseEach(eachFunc, fromRight) {
+ return function(collection, iteratee) {
+ if (collection == null) {
+ return collection;
+ }
+ if (!isArrayLike(collection)) {
+ return eachFunc(collection, iteratee);
+ }
+ var length = collection.length,
+ index = fromRight ? length : -1,
+ iterable = Object(collection);
+
+ while ((fromRight ? index-- : ++index < length)) {
+ if (iteratee(iterable[index], index, iterable) === false) {
+ break;
+ }
+ }
+ return collection;
+ };
+ }
+
+ /**
+ * Creates a base function for methods like `_.forIn` and `_.forOwn`.
+ *
+ * @private
+ * @param {boolean} [fromRight] Specify iterating from right to left.
+ * @returns {Function} Returns the new base function.
+ */
+ function createBaseFor(fromRight) {
+ return function(object, iteratee, keysFunc) {
+ var index = -1,
+ iterable = Object(object),
+ props = keysFunc(object),
+ length = props.length;
+
+ while (length--) {
+ var key = props[fromRight ? length : ++index];
+ if (iteratee(iterable[key], key, iterable) === false) {
+ break;
+ }
+ }
+ return object;
+ };
+ }
+
+ /**
+ * Creates a function that produces an instance of `Ctor` regardless of
+ * whether it was invoked as part of a `new` expression or by `call` or `apply`.
+ *
+ * @private
+ * @param {Function} Ctor The constructor to wrap.
+ * @returns {Function} Returns the new wrapped function.
+ */
+ function createCtor(Ctor) {
+ return function() {
+ // Use a `switch` statement to work with class constructors. See
+ // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
+ // for more details.
+ var args = arguments;
+ var thisBinding = baseCreate(Ctor.prototype),
+ result = Ctor.apply(thisBinding, args);
+
+ // Mimic the constructor's `return` behavior.
+ // See https://es5.github.io/#x13.2.2 for more details.
+ return isObject(result) ? result : thisBinding;
+ };
+ }
+
+ /**
+ * Creates a `_.find` or `_.findLast` function.
+ *
+ * @private
+ * @param {Function} findIndexFunc The function to find the collection index.
+ * @returns {Function} Returns the new find function.
+ */
+ function createFind(findIndexFunc) {
+ return function(collection, predicate, fromIndex) {
+ var iterable = Object(collection);
+ if (!isArrayLike(collection)) {
+ var iteratee = baseIteratee(predicate, 3);
+ collection = keys(collection);
+ predicate = function(key) { return iteratee(iterable[key], key, iterable); };
+ }
+ var index = findIndexFunc(collection, predicate, fromIndex);
+ return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
+ };
+ }
+
+ /**
+ * Creates a function that wraps `func` to invoke it with the `this` binding
+ * of `thisArg` and `partials` prepended to the arguments it receives.
+ *
+ * @private
+ * @param {Function} func The function to wrap.
+ * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
+ * @param {*} thisArg The `this` binding of `func`.
+ * @param {Array} partials The arguments to prepend to those provided to
+ * the new function.
+ * @returns {Function} Returns the new wrapped function.
+ */
+ function createPartial(func, bitmask, thisArg, partials) {
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ var isBind = bitmask & WRAP_BIND_FLAG,
+ Ctor = createCtor(func);
+
+ function wrapper() {
+ var argsIndex = -1,
+ argsLength = arguments.length,
+ leftIndex = -1,
+ leftLength = partials.length,
+ args = Array(leftLength + argsLength),
+ fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
+
+ while (++leftIndex < leftLength) {
+ args[leftIndex] = partials[leftIndex];
+ }
+ while (argsLength--) {
+ args[leftIndex++] = arguments[++argsIndex];
+ }
+ return fn.apply(isBind ? thisArg : this, args);
+ }
+ return wrapper;
+ }
+
+ /**
+ * A specialized version of `baseIsEqualDeep` for arrays with support for
+ * partial deep comparisons.
+ *
+ * @private
+ * @param {Array} array The array to compare.
+ * @param {Array} other The other array to compare.
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
+ * @param {Function} customizer The function to customize comparisons.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Object} stack Tracks traversed `array` and `other` objects.
+ * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
+ */
+ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
+ arrLength = array.length,
+ othLength = other.length;
+
+ if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
+ return false;
+ }
+ // Check that cyclic values are equal.
+ var arrStacked = stack.get(array);
+ var othStacked = stack.get(other);
+ if (arrStacked && othStacked) {
+ return arrStacked == other && othStacked == array;
+ }
+ var index = -1,
+ result = true,
+ seen = (bitmask & COMPARE_UNORDERED_FLAG) ? [] : undefined;
+
+ // Ignore non-index properties.
+ while (++index < arrLength) {
+ var arrValue = array[index],
+ othValue = other[index];
+
+ var compared;
+ if (compared !== undefined) {
+ if (compared) {
+ continue;
+ }
+ result = false;
+ break;
+ }
+ // Recursively compare arrays (susceptible to call stack limits).
+ if (seen) {
+ if (!baseSome(other, function(othValue, othIndex) {
+ if (!indexOf(seen, othIndex) &&
+ (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
+ return seen.push(othIndex);
+ }
+ })) {
+ result = false;
+ break;
+ }
+ } else if (!(
+ arrValue === othValue ||
+ equalFunc(arrValue, othValue, bitmask, customizer, stack)
+ )) {
+ result = false;
+ break;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * A specialized version of `baseIsEqualDeep` for comparing objects of
+ * the same `toStringTag`.
+ *
+ * **Note:** This function only supports comparing values with tags of
+ * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @param {string} tag The `toStringTag` of the objects to compare.
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
+ * @param {Function} customizer The function to customize comparisons.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Object} stack Tracks traversed `object` and `other` objects.
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ */
+ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
+ switch (tag) {
+
+ case boolTag:
+ case dateTag:
+ case numberTag:
+ // Coerce booleans to `1` or `0` and dates to milliseconds.
+ // Invalid dates are coerced to `NaN`.
+ return eq(+object, +other);
+
+ case errorTag:
+ return object.name == other.name && object.message == other.message;
+
+ case regexpTag:
+ case stringTag:
+ // Coerce regexes to strings and treat strings, primitives and objects,
+ // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
+ // for more details.
+ return object == (other + '');
+
+ }
+ return false;
+ }
+
+ /**
+ * A specialized version of `baseIsEqualDeep` for objects with support for
+ * partial deep comparisons.
+ *
+ * @private
+ * @param {Object} object The object to compare.
+ * @param {Object} other The other object to compare.
+ * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
+ * @param {Function} customizer The function to customize comparisons.
+ * @param {Function} equalFunc The function to determine equivalents of values.
+ * @param {Object} stack Tracks traversed `object` and `other` objects.
+ * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
+ */
+ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
+ objProps = keys(object),
+ objLength = objProps.length,
+ othProps = keys(other),
+ othLength = othProps.length;
+
+ if (objLength != othLength && !isPartial) {
+ return false;
+ }
+ var index = objLength;
+ while (index--) {
+ var key = objProps[index];
+ if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
+ return false;
+ }
+ }
+ // Check that cyclic values are equal.
+ var objStacked = stack.get(object);
+ var othStacked = stack.get(other);
+ if (objStacked && othStacked) {
+ return objStacked == other && othStacked == object;
+ }
+ var result = true;
+
+ var skipCtor = isPartial;
+ while (++index < objLength) {
+ key = objProps[index];
+ var objValue = object[key],
+ othValue = other[key];
+
+ var compared;
+ // Recursively compare objects (susceptible to call stack limits).
+ if (!(compared === undefined
+ ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
+ : compared
+ )) {
+ result = false;
+ break;
+ }
+ skipCtor || (skipCtor = key == 'constructor');
+ }
+ if (result && !skipCtor) {
+ var objCtor = object.constructor,
+ othCtor = other.constructor;
+
+ // Non `Object` object instances with different constructors are not equal.
+ if (objCtor != othCtor &&
+ ('constructor' in object && 'constructor' in other) &&
+ !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
+ typeof othCtor == 'function' && othCtor instanceof othCtor)) {
+ result = false;
+ }
+ }
+ return result;
+ }
+
+ /**
+ * A specialized version of `baseRest` which flattens the rest array.
+ *
+ * @private
+ * @param {Function} func The function to apply a rest parameter to.
+ * @returns {Function} Returns the new function.
+ */
+ function flatRest(func) {
+ return setToString(overRest(func, undefined, flatten), func + '');
+ }
+
+ /**
+ * Checks if `value` is a flattenable `arguments` object or array.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
+ */
+ function isFlattenable(value) {
+ return isArray(value) || isArguments(value);
+ }
+
+ /**
+ * Checks if `value` is a valid array-like index.
+ *
+ * @private
+ * @param {*} value The value to check.
+ * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
+ * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
+ */
+ function isIndex(value, length) {
+ var type = typeof value;
+ length = length == null ? MAX_SAFE_INTEGER : length;
+
+ return !!length &&
+ (type == 'number' ||
+ (type != 'symbol' && reIsUint.test(value))) &&
+ (value > -1 && value % 1 == 0 && value < length);
+ }
+
+ /**
+ * Checks if the given arguments are from an iteratee call.
+ *
+ * @private
+ * @param {*} value The potential iteratee value argument.
+ * @param {*} index The potential iteratee index or key argument.
+ * @param {*} object The potential iteratee object argument.
+ * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
+ * else `false`.
+ */
+ function isIterateeCall(value, index, object) {
+ if (!isObject(object)) {
+ return false;
+ }
+ var type = typeof index;
+ if (type == 'number'
+ ? (isArrayLike(object) && isIndex(index, object.length))
+ : (type == 'string' && index in object)
+ ) {
+ return eq(object[index], value);
+ }
+ return false;
+ }
+
+ /**
+ * This function is like
+ * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
+ * except that it includes inherited enumerable properties.
+ *
+ * @private
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ */
+ function nativeKeysIn(object) {
+ var result = [];
+ if (object != null) {
+ for (var key in Object(object)) {
+ result.push(key);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Converts `value` to a string using `Object.prototype.toString`.
+ *
+ * @private
+ * @param {*} value The value to convert.
+ * @returns {string} Returns the converted string.
+ */
+ function objectToString(value) {
+ return nativeObjectToString.call(value);
+ }
+
+ /**
+ * A specialized version of `baseRest` which transforms the rest array.
+ *
+ * @private
+ * @param {Function} func The function to apply a rest parameter to.
+ * @param {number} [start=func.length-1] The start position of the rest parameter.
+ * @param {Function} transform The rest array transform.
+ * @returns {Function} Returns the new function.
+ */
+ function overRest(func, start, transform) {
+ start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
+ return function() {
+ var args = arguments,
+ index = -1,
+ length = nativeMax(args.length - start, 0),
+ array = Array(length);
+
+ while (++index < length) {
+ array[index] = args[start + index];
+ }
+ index = -1;
+ var otherArgs = Array(start + 1);
+ while (++index < start) {
+ otherArgs[index] = args[index];
+ }
+ otherArgs[start] = transform(array);
+ return func.apply(this, otherArgs);
+ };
+ }
+
+ /**
+ * Sets the `toString` method of `func` to return `string`.
+ *
+ * @private
+ * @param {Function} func The function to modify.
+ * @param {Function} string The `toString` result.
+ * @returns {Function} Returns `func`.
+ */
+ var setToString = identity;
+
+ /*------------------------------------------------------------------------*/
+
+ /**
+ * Creates an array with all falsey values removed. The values `false`, `null`,
+ * `0`, `""`, `undefined`, and `NaN` are falsey.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Array
+ * @param {Array} array The array to compact.
+ * @returns {Array} Returns the new array of filtered values.
+ * @example
+ *
+ * _.compact([0, 1, false, 2, '', 3]);
+ * // => [1, 2, 3]
+ */
+ function compact(array) {
+ return baseFilter(array, Boolean);
+ }
+
+ /**
+ * Creates a new array concatenating `array` with any additional arrays
+ * and/or values.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Array
+ * @param {Array} array The array to concatenate.
+ * @param {...*} [values] The values to concatenate.
+ * @returns {Array} Returns the new concatenated array.
+ * @example
+ *
+ * var array = [1];
+ * var other = _.concat(array, 2, [3], [[4]]);
+ *
+ * console.log(other);
+ * // => [1, 2, 3, [4]]
+ *
+ * console.log(array);
+ * // => [1]
+ */
+ function concat() {
+ var length = arguments.length;
+ if (!length) {
+ return [];
+ }
+ var args = Array(length - 1),
+ array = arguments[0],
+ index = length;
+
+ while (index--) {
+ args[index - 1] = arguments[index];
+ }
+ return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
+ }
+
+ /**
+ * This method is like `_.find` except that it returns the index of the first
+ * element `predicate` returns truthy for instead of the element itself.
+ *
+ * @static
+ * @memberOf _
+ * @since 1.1.0
+ * @category Array
+ * @param {Array} array The array to inspect.
+ * @param {Function} [predicate=_.identity] The function invoked per iteration.
+ * @param {number} [fromIndex=0] The index to search from.
+ * @returns {number} Returns the index of the found element, else `-1`.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'active': false },
+ * { 'user': 'fred', 'active': false },
+ * { 'user': 'pebbles', 'active': true }
+ * ];
+ *
+ * _.findIndex(users, function(o) { return o.user == 'barney'; });
+ * // => 0
+ *
+ * // The `_.matches` iteratee shorthand.
+ * _.findIndex(users, { 'user': 'fred', 'active': false });
+ * // => 1
+ *
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.findIndex(users, ['active', false]);
+ * // => 0
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.findIndex(users, 'active');
+ * // => 2
+ */
+ function findIndex(array, predicate, fromIndex) {
+ var length = array == null ? 0 : array.length;
+ if (!length) {
+ return -1;
+ }
+ var index = fromIndex == null ? 0 : toInteger(fromIndex);
+ if (index < 0) {
+ index = nativeMax(length + index, 0);
+ }
+ return baseFindIndex(array, baseIteratee(predicate, 3), index);
+ }
+
+ /**
+ * Flattens `array` a single level deep.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Array
+ * @param {Array} array The array to flatten.
+ * @returns {Array} Returns the new flattened array.
+ * @example
+ *
+ * _.flatten([1, [2, [3, [4]], 5]]);
+ * // => [1, 2, [3, [4]], 5]
+ */
+ function flatten(array) {
+ var length = array == null ? 0 : array.length;
+ return length ? baseFlatten(array, 1) : [];
+ }
+
+ /**
+ * Recursively flattens `array`.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category Array
+ * @param {Array} array The array to flatten.
+ * @returns {Array} Returns the new flattened array.
+ * @example
+ *
+ * _.flattenDeep([1, [2, [3, [4]], 5]]);
+ * // => [1, 2, 3, 4, 5]
+ */
+ function flattenDeep(array) {
+ var length = array == null ? 0 : array.length;
+ return length ? baseFlatten(array, INFINITY) : [];
+ }
+
+ /**
+ * Gets the first element of `array`.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @alias first
+ * @category Array
+ * @param {Array} array The array to query.
+ * @returns {*} Returns the first element of `array`.
+ * @example
+ *
+ * _.head([1, 2, 3]);
+ * // => 1
+ *
+ * _.head([]);
+ * // => undefined
+ */
+ function head(array) {
+ return (array && array.length) ? array[0] : undefined;
+ }
+
+ /**
+ * Gets the index at which the first occurrence of `value` is found in `array`
+ * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
+ * for equality comparisons. If `fromIndex` is negative, it's used as the
+ * offset from the end of `array`.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Array
+ * @param {Array} array The array to inspect.
+ * @param {*} value The value to search for.
+ * @param {number} [fromIndex=0] The index to search from.
+ * @returns {number} Returns the index of the matched value, else `-1`.
+ * @example
+ *
+ * _.indexOf([1, 2, 1, 2], 2);
+ * // => 1
+ *
+ * // Search from the `fromIndex`.
+ * _.indexOf([1, 2, 1, 2], 2, 2);
+ * // => 3
+ */
+ function indexOf(array, value, fromIndex) {
+ var length = array == null ? 0 : array.length;
+ if (typeof fromIndex == 'number') {
+ fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex;
+ } else {
+ fromIndex = 0;
+ }
+ var index = (fromIndex || 0) - 1,
+ isReflexive = value === value;
+
+ while (++index < length) {
+ var other = array[index];
+ if ((isReflexive ? other === value : other !== other)) {
+ return index;
+ }
+ }
+ return -1;
+ }
+
+ /**
+ * Gets the last element of `array`.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Array
+ * @param {Array} array The array to query.
+ * @returns {*} Returns the last element of `array`.
+ * @example
+ *
+ * _.last([1, 2, 3]);
+ * // => 3
+ */
+ function last(array) {
+ var length = array == null ? 0 : array.length;
+ return length ? array[length - 1] : undefined;
+ }
+
+ /**
+ * Creates a slice of `array` from `start` up to, but not including, `end`.
+ *
+ * **Note:** This method is used instead of
+ * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
+ * returned.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category Array
+ * @param {Array} array The array to slice.
+ * @param {number} [start=0] The start position.
+ * @param {number} [end=array.length] The end position.
+ * @returns {Array} Returns the slice of `array`.
+ */
+ function slice(array, start, end) {
+ var length = array == null ? 0 : array.length;
+ start = start == null ? 0 : +start;
+ end = end === undefined ? length : +end;
+ return length ? baseSlice(array, start, end) : [];
+ }
+
+ /*------------------------------------------------------------------------*/
+
+ /**
+ * Creates a `lodash` wrapper instance that wraps `value` with explicit method
+ * chain sequences enabled. The result of such sequences must be unwrapped
+ * with `_#value`.
+ *
+ * @static
+ * @memberOf _
+ * @since 1.3.0
+ * @category Seq
+ * @param {*} value The value to wrap.
+ * @returns {Object} Returns the new `lodash` wrapper instance.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36 },
+ * { 'user': 'fred', 'age': 40 },
+ * { 'user': 'pebbles', 'age': 1 }
+ * ];
+ *
+ * var youngest = _
+ * .chain(users)
+ * .sortBy('age')
+ * .map(function(o) {
+ * return o.user + ' is ' + o.age;
+ * })
+ * .head()
+ * .value();
+ * // => 'pebbles is 1'
+ */
+ function chain(value) {
+ var result = lodash(value);
+ result.__chain__ = true;
+ return result;
+ }
+
+ /**
+ * This method invokes `interceptor` and returns `value`. The interceptor
+ * is invoked with one argument; (value). The purpose of this method is to
+ * "tap into" a method chain sequence in order to modify intermediate results.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Seq
+ * @param {*} value The value to provide to `interceptor`.
+ * @param {Function} interceptor The function to invoke.
+ * @returns {*} Returns `value`.
+ * @example
+ *
+ * _([1, 2, 3])
+ * .tap(function(array) {
+ * // Mutate input array.
+ * array.pop();
+ * })
+ * .reverse()
+ * .value();
+ * // => [2, 1]
+ */
+ function tap(value, interceptor) {
+ interceptor(value);
+ return value;
+ }
+
+ /**
+ * This method is like `_.tap` except that it returns the result of `interceptor`.
+ * The purpose of this method is to "pass thru" values replacing intermediate
+ * results in a method chain sequence.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category Seq
+ * @param {*} value The value to provide to `interceptor`.
+ * @param {Function} interceptor The function to invoke.
+ * @returns {*} Returns the result of `interceptor`.
+ * @example
+ *
+ * _(' abc ')
+ * .chain()
+ * .trim()
+ * .thru(function(value) {
+ * return [value];
+ * })
+ * .value();
+ * // => ['abc']
+ */
+ function thru(value, interceptor) {
+ return interceptor(value);
+ }
+
+ /**
+ * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
+ *
+ * @name chain
+ * @memberOf _
+ * @since 0.1.0
+ * @category Seq
+ * @returns {Object} Returns the new `lodash` wrapper instance.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36 },
+ * { 'user': 'fred', 'age': 40 }
+ * ];
+ *
+ * // A sequence without explicit chaining.
+ * _(users).head();
+ * // => { 'user': 'barney', 'age': 36 }
+ *
+ * // A sequence with explicit chaining.
+ * _(users)
+ * .chain()
+ * .head()
+ * .pick('user')
+ * .value();
+ * // => { 'user': 'barney' }
+ */
+ function wrapperChain() {
+ return chain(this);
+ }
+
+ /**
+ * Executes the chain sequence to resolve the unwrapped value.
+ *
+ * @name value
+ * @memberOf _
+ * @since 0.1.0
+ * @alias toJSON, valueOf
+ * @category Seq
+ * @returns {*} Returns the resolved unwrapped value.
+ * @example
+ *
+ * _([1, 2, 3]).value();
+ * // => [1, 2, 3]
+ */
+ function wrapperValue() {
+ return baseWrapperValue(this.__wrapped__, this.__actions__);
+ }
+
+ /*------------------------------------------------------------------------*/
+
+ /**
+ * Checks if `predicate` returns truthy for **all** elements of `collection`.
+ * Iteration is stopped once `predicate` returns falsey. The predicate is
+ * invoked with three arguments: (value, index|key, collection).
+ *
+ * **Note:** This method returns `true` for
+ * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
+ * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
+ * elements of empty collections.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Collection
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} [predicate=_.identity] The function invoked per iteration.
+ * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
+ * @returns {boolean} Returns `true` if all elements pass the predicate check,
+ * else `false`.
+ * @example
+ *
+ * _.every([true, 1, null, 'yes'], Boolean);
+ * // => false
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36, 'active': false },
+ * { 'user': 'fred', 'age': 40, 'active': false }
+ * ];
+ *
+ * // The `_.matches` iteratee shorthand.
+ * _.every(users, { 'user': 'barney', 'active': false });
+ * // => false
+ *
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.every(users, ['active', false]);
+ * // => true
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.every(users, 'active');
+ * // => false
+ */
+ function every(collection, predicate, guard) {
+ predicate = guard ? undefined : predicate;
+ return baseEvery(collection, baseIteratee(predicate));
+ }
+
+ /**
+ * Iterates over elements of `collection`, returning an array of all elements
+ * `predicate` returns truthy for. The predicate is invoked with three
+ * arguments: (value, index|key, collection).
+ *
+ * **Note:** Unlike `_.remove`, this method returns a new array.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Collection
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} [predicate=_.identity] The function invoked per iteration.
+ * @returns {Array} Returns the new filtered array.
+ * @see _.reject
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36, 'active': true },
+ * { 'user': 'fred', 'age': 40, 'active': false }
+ * ];
+ *
+ * _.filter(users, function(o) { return !o.active; });
+ * // => objects for ['fred']
+ *
+ * // The `_.matches` iteratee shorthand.
+ * _.filter(users, { 'age': 36, 'active': true });
+ * // => objects for ['barney']
+ *
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.filter(users, ['active', false]);
+ * // => objects for ['fred']
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.filter(users, 'active');
+ * // => objects for ['barney']
+ *
+ * // Combining several predicates using `_.overEvery` or `_.overSome`.
+ * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
+ * // => objects for ['fred', 'barney']
+ */
+ function filter(collection, predicate) {
+ return baseFilter(collection, baseIteratee(predicate));
+ }
+
+ /**
+ * Iterates over elements of `collection`, returning the first element
+ * `predicate` returns truthy for. The predicate is invoked with three
+ * arguments: (value, index|key, collection).
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Collection
+ * @param {Array|Object} collection The collection to inspect.
+ * @param {Function} [predicate=_.identity] The function invoked per iteration.
+ * @param {number} [fromIndex=0] The index to search from.
+ * @returns {*} Returns the matched element, else `undefined`.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36, 'active': true },
+ * { 'user': 'fred', 'age': 40, 'active': false },
+ * { 'user': 'pebbles', 'age': 1, 'active': true }
+ * ];
+ *
+ * _.find(users, function(o) { return o.age < 40; });
+ * // => object for 'barney'
+ *
+ * // The `_.matches` iteratee shorthand.
+ * _.find(users, { 'age': 1, 'active': true });
+ * // => object for 'pebbles'
+ *
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.find(users, ['active', false]);
+ * // => object for 'fred'
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.find(users, 'active');
+ * // => object for 'barney'
+ */
+ var find = createFind(findIndex);
+
+ /**
+ * Iterates over elements of `collection` and invokes `iteratee` for each element.
+ * The iteratee is invoked with three arguments: (value, index|key, collection).
+ * Iteratee functions may exit iteration early by explicitly returning `false`.
+ *
+ * **Note:** As with other "Collections" methods, objects with a "length"
+ * property are iterated like arrays. To avoid this behavior use `_.forIn`
+ * or `_.forOwn` for object iteration.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @alias each
+ * @category Collection
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
+ * @returns {Array|Object} Returns `collection`.
+ * @see _.forEachRight
+ * @example
+ *
+ * _.forEach([1, 2], function(value) {
+ * console.log(value);
+ * });
+ * // => Logs `1` then `2`.
+ *
+ * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
+ * console.log(key);
+ * });
+ * // => Logs 'a' then 'b' (iteration order is not guaranteed).
+ */
+ function forEach(collection, iteratee) {
+ return baseEach(collection, baseIteratee(iteratee));
+ }
+
+ /**
+ * Creates an array of values by running each element in `collection` thru
+ * `iteratee`. The iteratee is invoked with three arguments:
+ * (value, index|key, collection).
+ *
+ * Many lodash methods are guarded to work as iteratees for methods like
+ * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
+ *
+ * The guarded methods are:
+ * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
+ * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
+ * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
+ * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Collection
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
+ * @returns {Array} Returns the new mapped array.
+ * @example
+ *
+ * function square(n) {
+ * return n * n;
+ * }
+ *
+ * _.map([4, 8], square);
+ * // => [16, 64]
+ *
+ * _.map({ 'a': 4, 'b': 8 }, square);
+ * // => [16, 64] (iteration order is not guaranteed)
+ *
+ * var users = [
+ * { 'user': 'barney' },
+ * { 'user': 'fred' }
+ * ];
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.map(users, 'user');
+ * // => ['barney', 'fred']
+ */
+ function map(collection, iteratee) {
+ return baseMap(collection, baseIteratee(iteratee));
+ }
+
+ /**
+ * Reduces `collection` to a value which is the accumulated result of running
+ * each element in `collection` thru `iteratee`, where each successive
+ * invocation is supplied the return value of the previous. If `accumulator`
+ * is not given, the first element of `collection` is used as the initial
+ * value. The iteratee is invoked with four arguments:
+ * (accumulator, value, index|key, collection).
+ *
+ * Many lodash methods are guarded to work as iteratees for methods like
+ * `_.reduce`, `_.reduceRight`, and `_.transform`.
+ *
+ * The guarded methods are:
+ * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
+ * and `sortBy`
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Collection
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} [iteratee=_.identity] The function invoked per iteration.
+ * @param {*} [accumulator] The initial value.
+ * @returns {*} Returns the accumulated value.
+ * @see _.reduceRight
+ * @example
+ *
+ * _.reduce([1, 2], function(sum, n) {
+ * return sum + n;
+ * }, 0);
+ * // => 3
+ *
+ * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
+ * (result[value] || (result[value] = [])).push(key);
+ * return result;
+ * }, {});
+ * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
+ */
+ function reduce(collection, iteratee, accumulator) {
+ return baseReduce(collection, baseIteratee(iteratee), accumulator, arguments.length < 3, baseEach);
+ }
+
+ /**
+ * Gets the size of `collection` by returning its length for array-like
+ * values or the number of own enumerable string keyed properties for objects.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Collection
+ * @param {Array|Object|string} collection The collection to inspect.
+ * @returns {number} Returns the collection size.
+ * @example
+ *
+ * _.size([1, 2, 3]);
+ * // => 3
+ *
+ * _.size({ 'a': 1, 'b': 2 });
+ * // => 2
+ *
+ * _.size('pebbles');
+ * // => 7
+ */
+ function size(collection) {
+ if (collection == null) {
+ return 0;
+ }
+ collection = isArrayLike(collection) ? collection : nativeKeys(collection);
+ return collection.length;
+ }
+
+ /**
+ * Checks if `predicate` returns truthy for **any** element of `collection`.
+ * Iteration is stopped once `predicate` returns truthy. The predicate is
+ * invoked with three arguments: (value, index|key, collection).
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Collection
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {Function} [predicate=_.identity] The function invoked per iteration.
+ * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
+ * @returns {boolean} Returns `true` if any element passes the predicate check,
+ * else `false`.
+ * @example
+ *
+ * _.some([null, 0, 'yes', false], Boolean);
+ * // => true
+ *
+ * var users = [
+ * { 'user': 'barney', 'active': true },
+ * { 'user': 'fred', 'active': false }
+ * ];
+ *
+ * // The `_.matches` iteratee shorthand.
+ * _.some(users, { 'user': 'barney', 'active': false });
+ * // => false
+ *
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.some(users, ['active', false]);
+ * // => true
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.some(users, 'active');
+ * // => true
+ */
+ function some(collection, predicate, guard) {
+ predicate = guard ? undefined : predicate;
+ return baseSome(collection, baseIteratee(predicate));
+ }
+
+ /**
+ * Creates an array of elements, sorted in ascending order by the results of
+ * running each element in a collection thru each iteratee. This method
+ * performs a stable sort, that is, it preserves the original sort order of
+ * equal elements. The iteratees are invoked with one argument: (value).
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Collection
+ * @param {Array|Object} collection The collection to iterate over.
+ * @param {...(Function|Function[])} [iteratees=[_.identity]]
+ * The iteratees to sort by.
+ * @returns {Array} Returns the new sorted array.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'fred', 'age': 48 },
+ * { 'user': 'barney', 'age': 36 },
+ * { 'user': 'fred', 'age': 30 },
+ * { 'user': 'barney', 'age': 34 }
+ * ];
+ *
+ * _.sortBy(users, [function(o) { return o.user; }]);
+ * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
+ *
+ * _.sortBy(users, ['user', 'age']);
+ * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
+ */
+ function sortBy(collection, iteratee) {
+ var index = 0;
+ iteratee = baseIteratee(iteratee);
+
+ return baseMap(baseMap(collection, function(value, key, collection) {
+ return { 'value': value, 'index': index++, 'criteria': iteratee(value, key, collection) };
+ }).sort(function(object, other) {
+ return compareAscending(object.criteria, other.criteria) || (object.index - other.index);
+ }), baseProperty('value'));
+ }
+
+ /*------------------------------------------------------------------------*/
+
+ /**
+ * Creates a function that invokes `func`, with the `this` binding and arguments
+ * of the created function, while it's called less than `n` times. Subsequent
+ * calls to the created function return the result of the last `func` invocation.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category Function
+ * @param {number} n The number of calls at which `func` is no longer invoked.
+ * @param {Function} func The function to restrict.
+ * @returns {Function} Returns the new restricted function.
+ * @example
+ *
+ * jQuery(element).on('click', _.before(5, addContactToList));
+ * // => Allows adding up to 4 contacts to the list.
+ */
+ function before(n, func) {
+ var result;
+ if (typeof func != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ n = toInteger(n);
+ return function() {
+ if (--n > 0) {
+ result = func.apply(this, arguments);
+ }
+ if (n <= 1) {
+ func = undefined;
+ }
+ return result;
+ };
+ }
+
+ /**
+ * Creates a function that invokes `func` with the `this` binding of `thisArg`
+ * and `partials` prepended to the arguments it receives.
+ *
+ * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
+ * may be used as a placeholder for partially applied arguments.
+ *
+ * **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
+ * property of bound functions.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Function
+ * @param {Function} func The function to bind.
+ * @param {*} thisArg The `this` binding of `func`.
+ * @param {...*} [partials] The arguments to be partially applied.
+ * @returns {Function} Returns the new bound function.
+ * @example
+ *
+ * function greet(greeting, punctuation) {
+ * return greeting + ' ' + this.user + punctuation;
+ * }
+ *
+ * var object = { 'user': 'fred' };
+ *
+ * var bound = _.bind(greet, object, 'hi');
+ * bound('!');
+ * // => 'hi fred!'
+ *
+ * // Bound with placeholders.
+ * var bound = _.bind(greet, object, _, '!');
+ * bound('hi');
+ * // => 'hi fred!'
+ */
+ var bind = baseRest(function(func, thisArg, partials) {
+ return createPartial(func, WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG, thisArg, partials);
+ });
+
+ /**
+ * Defers invoking the `func` until the current call stack has cleared. Any
+ * additional arguments are provided to `func` when it's invoked.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Function
+ * @param {Function} func The function to defer.
+ * @param {...*} [args] The arguments to invoke `func` with.
+ * @returns {number} Returns the timer id.
+ * @example
+ *
+ * _.defer(function(text) {
+ * console.log(text);
+ * }, 'deferred');
+ * // => Logs 'deferred' after one millisecond.
+ */
+ var defer = baseRest(function(func, args) {
+ return baseDelay(func, 1, args);
+ });
+
+ /**
+ * Invokes `func` after `wait` milliseconds. Any additional arguments are
+ * provided to `func` when it's invoked.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Function
+ * @param {Function} func The function to delay.
+ * @param {number} wait The number of milliseconds to delay invocation.
+ * @param {...*} [args] The arguments to invoke `func` with.
+ * @returns {number} Returns the timer id.
+ * @example
+ *
+ * _.delay(function(text) {
+ * console.log(text);
+ * }, 1000, 'later');
+ * // => Logs 'later' after one second.
+ */
+ var delay = baseRest(function(func, wait, args) {
+ return baseDelay(func, toNumber(wait) || 0, args);
+ });
+
+ /**
+ * Creates a function that negates the result of the predicate `func`. The
+ * `func` predicate is invoked with the `this` binding and arguments of the
+ * created function.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category Function
+ * @param {Function} predicate The predicate to negate.
+ * @returns {Function} Returns the new negated function.
+ * @example
+ *
+ * function isEven(n) {
+ * return n % 2 == 0;
+ * }
+ *
+ * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
+ * // => [1, 3, 5]
+ */
+ function negate(predicate) {
+ if (typeof predicate != 'function') {
+ throw new TypeError(FUNC_ERROR_TEXT);
+ }
+ return function() {
+ var args = arguments;
+ return !predicate.apply(this, args);
+ };
+ }
+
+ /**
+ * Creates a function that is restricted to invoking `func` once. Repeat calls
+ * to the function return the value of the first invocation. The `func` is
+ * invoked with the `this` binding and arguments of the created function.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Function
+ * @param {Function} func The function to restrict.
+ * @returns {Function} Returns the new restricted function.
+ * @example
+ *
+ * var initialize = _.once(createApplication);
+ * initialize();
+ * initialize();
+ * // => `createApplication` is invoked once
+ */
+ function once(func) {
+ return before(2, func);
+ }
+
+ /*------------------------------------------------------------------------*/
+
+ /**
+ * Creates a shallow clone of `value`.
+ *
+ * **Note:** This method is loosely based on the
+ * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
+ * and supports cloning arrays, array buffers, booleans, date objects, maps,
+ * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
+ * arrays. The own enumerable properties of `arguments` objects are cloned
+ * as plain objects. An empty object is returned for uncloneable values such
+ * as error objects, functions, DOM nodes, and WeakMaps.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to clone.
+ * @returns {*} Returns the cloned value.
+ * @see _.cloneDeep
+ * @example
+ *
+ * var objects = [{ 'a': 1 }, { 'b': 2 }];
+ *
+ * var shallow = _.clone(objects);
+ * console.log(shallow[0] === objects[0]);
+ * // => true
+ */
+ function clone(value) {
+ if (!isObject(value)) {
+ return value;
+ }
+ return isArray(value) ? copyArray(value) : copyObject(value, nativeKeys(value));
+ }
+
+ /**
+ * Performs a
+ * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
+ * comparison between two values to determine if they are equivalent.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+ * @example
+ *
+ * var object = { 'a': 1 };
+ * var other = { 'a': 1 };
+ *
+ * _.eq(object, object);
+ * // => true
+ *
+ * _.eq(object, other);
+ * // => false
+ *
+ * _.eq('a', 'a');
+ * // => true
+ *
+ * _.eq('a', Object('a'));
+ * // => false
+ *
+ * _.eq(NaN, NaN);
+ * // => true
+ */
+ function eq(value, other) {
+ return value === other || (value !== value && other !== other);
+ }
+
+ /**
+ * Checks if `value` is likely an `arguments` object.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an `arguments` object,
+ * else `false`.
+ * @example
+ *
+ * _.isArguments(function() { return arguments; }());
+ * // => true
+ *
+ * _.isArguments([1, 2, 3]);
+ * // => false
+ */
+ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
+ return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
+ !propertyIsEnumerable.call(value, 'callee');
+ };
+
+ /**
+ * Checks if `value` is classified as an `Array` object.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an array, else `false`.
+ * @example
+ *
+ * _.isArray([1, 2, 3]);
+ * // => true
+ *
+ * _.isArray(document.body.children);
+ * // => false
+ *
+ * _.isArray('abc');
+ * // => false
+ *
+ * _.isArray(_.noop);
+ * // => false
+ */
+ var isArray = Array.isArray;
+
+ /**
+ * Checks if `value` is array-like. A value is considered array-like if it's
+ * not a function and has a `value.length` that's an integer greater than or
+ * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
+ * @example
+ *
+ * _.isArrayLike([1, 2, 3]);
+ * // => true
+ *
+ * _.isArrayLike(document.body.children);
+ * // => true
+ *
+ * _.isArrayLike('abc');
+ * // => true
+ *
+ * _.isArrayLike(_.noop);
+ * // => false
+ */
+ function isArrayLike(value) {
+ return value != null && isLength(value.length) && !isFunction(value);
+ }
+
+ /**
+ * Checks if `value` is classified as a boolean primitive or object.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
+ * @example
+ *
+ * _.isBoolean(false);
+ * // => true
+ *
+ * _.isBoolean(null);
+ * // => false
+ */
+ function isBoolean(value) {
+ return value === true || value === false ||
+ (isObjectLike(value) && baseGetTag(value) == boolTag);
+ }
+
+ /**
+ * Checks if `value` is classified as a `Date` object.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
+ * @example
+ *
+ * _.isDate(new Date);
+ * // => true
+ *
+ * _.isDate('Mon April 23 2012');
+ * // => false
+ */
+ var isDate = baseIsDate;
+
+ /**
+ * Checks if `value` is an empty object, collection, map, or set.
+ *
+ * Objects are considered empty if they have no own enumerable string keyed
+ * properties.
+ *
+ * Array-like values such as `arguments` objects, arrays, buffers, strings, or
+ * jQuery-like collections are considered empty if they have a `length` of `0`.
+ * Similarly, maps and sets are considered empty if they have a `size` of `0`.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is empty, else `false`.
+ * @example
+ *
+ * _.isEmpty(null);
+ * // => true
+ *
+ * _.isEmpty(true);
+ * // => true
+ *
+ * _.isEmpty(1);
+ * // => true
+ *
+ * _.isEmpty([1, 2, 3]);
+ * // => false
+ *
+ * _.isEmpty({ 'a': 1 });
+ * // => false
+ */
+ function isEmpty(value) {
+ if (isArrayLike(value) &&
+ (isArray(value) || isString(value) ||
+ isFunction(value.splice) || isArguments(value))) {
+ return !value.length;
+ }
+ return !nativeKeys(value).length;
+ }
+
+ /**
+ * Performs a deep comparison between two values to determine if they are
+ * equivalent.
+ *
+ * **Note:** This method supports comparing arrays, array buffers, booleans,
+ * date objects, error objects, maps, numbers, `Object` objects, regexes,
+ * sets, strings, symbols, and typed arrays. `Object` objects are compared
+ * by their own, not inherited, enumerable properties. Functions and DOM
+ * nodes are compared by strict equality, i.e. `===`.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to compare.
+ * @param {*} other The other value to compare.
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
+ * @example
+ *
+ * var object = { 'a': 1 };
+ * var other = { 'a': 1 };
+ *
+ * _.isEqual(object, other);
+ * // => true
+ *
+ * object === other;
+ * // => false
+ */
+ function isEqual(value, other) {
+ return baseIsEqual(value, other);
+ }
+
+ /**
+ * Checks if `value` is a finite primitive number.
+ *
+ * **Note:** This method is based on
+ * [`Number.isFinite`](https://mdn.io/Number/isFinite).
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
+ * @example
+ *
+ * _.isFinite(3);
+ * // => true
+ *
+ * _.isFinite(Number.MIN_VALUE);
+ * // => true
+ *
+ * _.isFinite(Infinity);
+ * // => false
+ *
+ * _.isFinite('3');
+ * // => false
+ */
+ function isFinite(value) {
+ return typeof value == 'number' && nativeIsFinite(value);
+ }
+
+ /**
+ * Checks if `value` is classified as a `Function` object.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a function, else `false`.
+ * @example
+ *
+ * _.isFunction(_);
+ * // => true
+ *
+ * _.isFunction(/abc/);
+ * // => false
+ */
+ function isFunction(value) {
+ if (!isObject(value)) {
+ return false;
+ }
+ // The use of `Object#toString` avoids issues with the `typeof` operator
+ // in Safari 9 which returns 'object' for typed arrays and other constructors.
+ var tag = baseGetTag(value);
+ return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
+ }
+
+ /**
+ * Checks if `value` is a valid array-like length.
+ *
+ * **Note:** This method is loosely based on
+ * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
+ * @example
+ *
+ * _.isLength(3);
+ * // => true
+ *
+ * _.isLength(Number.MIN_VALUE);
+ * // => false
+ *
+ * _.isLength(Infinity);
+ * // => false
+ *
+ * _.isLength('3');
+ * // => false
+ */
+ function isLength(value) {
+ return typeof value == 'number' &&
+ value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
+ }
+
+ /**
+ * Checks if `value` is the
+ * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
+ * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is an object, else `false`.
+ * @example
+ *
+ * _.isObject({});
+ * // => true
+ *
+ * _.isObject([1, 2, 3]);
+ * // => true
+ *
+ * _.isObject(_.noop);
+ * // => true
+ *
+ * _.isObject(null);
+ * // => false
+ */
+ function isObject(value) {
+ var type = typeof value;
+ return value != null && (type == 'object' || type == 'function');
+ }
+
+ /**
+ * Checks if `value` is object-like. A value is object-like if it's not `null`
+ * and has a `typeof` result of "object".
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
+ * @example
+ *
+ * _.isObjectLike({});
+ * // => true
+ *
+ * _.isObjectLike([1, 2, 3]);
+ * // => true
+ *
+ * _.isObjectLike(_.noop);
+ * // => false
+ *
+ * _.isObjectLike(null);
+ * // => false
+ */
+ function isObjectLike(value) {
+ return value != null && typeof value == 'object';
+ }
+
+ /**
+ * Checks if `value` is `NaN`.
+ *
+ * **Note:** This method is based on
+ * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
+ * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
+ * `undefined` and other non-number values.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
+ * @example
+ *
+ * _.isNaN(NaN);
+ * // => true
+ *
+ * _.isNaN(new Number(NaN));
+ * // => true
+ *
+ * isNaN(undefined);
+ * // => true
+ *
+ * _.isNaN(undefined);
+ * // => false
+ */
+ function isNaN(value) {
+ // An `NaN` primitive is the only value that is not equal to itself.
+ // Perform the `toStringTag` check first to avoid errors with some
+ // ActiveX objects in IE.
+ return isNumber(value) && value != +value;
+ }
+
+ /**
+ * Checks if `value` is `null`.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
+ * @example
+ *
+ * _.isNull(null);
+ * // => true
+ *
+ * _.isNull(void 0);
+ * // => false
+ */
+ function isNull(value) {
+ return value === null;
+ }
+
+ /**
+ * Checks if `value` is classified as a `Number` primitive or object.
+ *
+ * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
+ * classified as numbers, use the `_.isFinite` method.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a number, else `false`.
+ * @example
+ *
+ * _.isNumber(3);
+ * // => true
+ *
+ * _.isNumber(Number.MIN_VALUE);
+ * // => true
+ *
+ * _.isNumber(Infinity);
+ * // => true
+ *
+ * _.isNumber('3');
+ * // => false
+ */
+ function isNumber(value) {
+ return typeof value == 'number' ||
+ (isObjectLike(value) && baseGetTag(value) == numberTag);
+ }
+
+ /**
+ * Checks if `value` is classified as a `RegExp` object.
+ *
+ * @static
+ * @memberOf _
+ * @since 0.1.0
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
+ * @example
+ *
+ * _.isRegExp(/abc/);
+ * // => true
+ *
+ * _.isRegExp('/abc/');
+ * // => false
+ */
+ var isRegExp = baseIsRegExp;
+
+ /**
+ * Checks if `value` is classified as a `String` primitive or object.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is a string, else `false`.
+ * @example
+ *
+ * _.isString('abc');
+ * // => true
+ *
+ * _.isString(1);
+ * // => false
+ */
+ function isString(value) {
+ return typeof value == 'string' ||
+ (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
+ }
+
+ /**
+ * Checks if `value` is `undefined`.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to check.
+ * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
+ * @example
+ *
+ * _.isUndefined(void 0);
+ * // => true
+ *
+ * _.isUndefined(null);
+ * // => false
+ */
+ function isUndefined(value) {
+ return value === undefined;
+ }
+
+ /**
+ * Converts `value` to an array.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Lang
+ * @param {*} value The value to convert.
+ * @returns {Array} Returns the converted array.
+ * @example
+ *
+ * _.toArray({ 'a': 1, 'b': 2 });
+ * // => [1, 2]
+ *
+ * _.toArray('abc');
+ * // => ['a', 'b', 'c']
+ *
+ * _.toArray(1);
+ * // => []
+ *
+ * _.toArray(null);
+ * // => []
+ */
+ function toArray(value) {
+ if (!isArrayLike(value)) {
+ return values(value);
+ }
+ return value.length ? copyArray(value) : [];
+ }
+
+ /**
+ * Converts `value` to an integer.
+ *
+ * **Note:** This method is loosely based on
+ * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to convert.
+ * @returns {number} Returns the converted integer.
+ * @example
+ *
+ * _.toInteger(3.2);
+ * // => 3
+ *
+ * _.toInteger(Number.MIN_VALUE);
+ * // => 0
+ *
+ * _.toInteger(Infinity);
+ * // => 1.7976931348623157e+308
+ *
+ * _.toInteger('3.2');
+ * // => 3
+ */
+ var toInteger = Number;
+
+ /**
+ * Converts `value` to a number.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to process.
+ * @returns {number} Returns the number.
+ * @example
+ *
+ * _.toNumber(3.2);
+ * // => 3.2
+ *
+ * _.toNumber(Number.MIN_VALUE);
+ * // => 5e-324
+ *
+ * _.toNumber(Infinity);
+ * // => Infinity
+ *
+ * _.toNumber('3.2');
+ * // => 3.2
+ */
+ var toNumber = Number;
+
+ /**
+ * Converts `value` to a string. An empty string is returned for `null`
+ * and `undefined` values. The sign of `-0` is preserved.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @category Lang
+ * @param {*} value The value to convert.
+ * @returns {string} Returns the converted string.
+ * @example
+ *
+ * _.toString(null);
+ * // => ''
+ *
+ * _.toString(-0);
+ * // => '-0'
+ *
+ * _.toString([1, 2, 3]);
+ * // => '1,2,3'
+ */
+ function toString(value) {
+ if (typeof value == 'string') {
+ return value;
+ }
+ return value == null ? '' : (value + '');
+ }
+
+ /*------------------------------------------------------------------------*/
+
+ /**
+ * Assigns own enumerable string keyed properties of source objects to the
+ * destination object. Source objects are applied from left to right.
+ * Subsequent sources overwrite property assignments of previous sources.
+ *
+ * **Note:** This method mutates `object` and is loosely based on
+ * [`Object.assign`](https://mdn.io/Object/assign).
+ *
+ * @static
+ * @memberOf _
+ * @since 0.10.0
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} [sources] The source objects.
+ * @returns {Object} Returns `object`.
+ * @see _.assignIn
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * }
+ *
+ * function Bar() {
+ * this.c = 3;
+ * }
+ *
+ * Foo.prototype.b = 2;
+ * Bar.prototype.d = 4;
+ *
+ * _.assign({ 'a': 0 }, new Foo, new Bar);
+ * // => { 'a': 1, 'c': 3 }
+ */
+ var assign = createAssigner(function(object, source) {
+ copyObject(source, nativeKeys(source), object);
+ });
+
+ /**
+ * This method is like `_.assign` except that it iterates over own and
+ * inherited source properties.
+ *
+ * **Note:** This method mutates `object`.
+ *
+ * @static
+ * @memberOf _
+ * @since 4.0.0
+ * @alias extend
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} [sources] The source objects.
+ * @returns {Object} Returns `object`.
+ * @see _.assign
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * }
+ *
+ * function Bar() {
+ * this.c = 3;
+ * }
+ *
+ * Foo.prototype.b = 2;
+ * Bar.prototype.d = 4;
+ *
+ * _.assignIn({ 'a': 0 }, new Foo, new Bar);
+ * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
+ */
+ var assignIn = createAssigner(function(object, source) {
+ copyObject(source, nativeKeysIn(source), object);
+ });
+
+ /**
+ * Creates an object that inherits from the `prototype` object. If a
+ * `properties` object is given, its own enumerable string keyed properties
+ * are assigned to the created object.
+ *
+ * @static
+ * @memberOf _
+ * @since 2.3.0
+ * @category Object
+ * @param {Object} prototype The object to inherit from.
+ * @param {Object} [properties] The properties to assign to the object.
+ * @returns {Object} Returns the new object.
+ * @example
+ *
+ * function Shape() {
+ * this.x = 0;
+ * this.y = 0;
+ * }
+ *
+ * function Circle() {
+ * Shape.call(this);
+ * }
+ *
+ * Circle.prototype = _.create(Shape.prototype, {
+ * 'constructor': Circle
+ * });
+ *
+ * var circle = new Circle;
+ * circle instanceof Circle;
+ * // => true
+ *
+ * circle instanceof Shape;
+ * // => true
+ */
+ function create(prototype, properties) {
+ var result = baseCreate(prototype);
+ return properties == null ? result : assign(result, properties);
+ }
+
+ /**
+ * Assigns own and inherited enumerable string keyed properties of source
+ * objects to the destination object for all destination properties that
+ * resolve to `undefined`. Source objects are applied from left to right.
+ * Once a property is set, additional values of the same property are ignored.
+ *
+ * **Note:** This method mutates `object`.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The destination object.
+ * @param {...Object} [sources] The source objects.
+ * @returns {Object} Returns `object`.
+ * @see _.defaultsDeep
+ * @example
+ *
+ * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
+ * // => { 'a': 1, 'b': 2 }
+ */
+ var defaults = baseRest(function(object, sources) {
+ object = Object(object);
+
+ var index = -1;
+ var length = sources.length;
+ var guard = length > 2 ? sources[2] : undefined;
+
+ if (guard && isIterateeCall(sources[0], sources[1], guard)) {
+ length = 1;
+ }
+
+ while (++index < length) {
+ var source = sources[index];
+ var props = keysIn(source);
+ var propsIndex = -1;
+ var propsLength = props.length;
+
+ while (++propsIndex < propsLength) {
+ var key = props[propsIndex];
+ var value = object[key];
+
+ if (value === undefined ||
+ (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {
+ object[key] = source[key];
+ }
+ }
+ }
+
+ return object;
+ });
+
+ /**
+ * Checks if `path` is a direct property of `object`.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path to check.
+ * @returns {boolean} Returns `true` if `path` exists, else `false`.
+ * @example
+ *
+ * var object = { 'a': { 'b': 2 } };
+ * var other = _.create({ 'a': _.create({ 'b': 2 }) });
+ *
+ * _.has(object, 'a');
+ * // => true
+ *
+ * _.has(object, 'a.b');
+ * // => true
+ *
+ * _.has(object, ['a', 'b']);
+ * // => true
+ *
+ * _.has(other, 'a');
+ * // => false
+ */
+ function has(object, path) {
+ return object != null && hasOwnProperty.call(object, path);
+ }
+
+ /**
+ * Creates an array of the own enumerable property names of `object`.
+ *
+ * **Note:** Non-object values are coerced to objects. See the
+ * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
+ * for more details.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.keys(new Foo);
+ * // => ['a', 'b'] (iteration order is not guaranteed)
+ *
+ * _.keys('hi');
+ * // => ['0', '1']
+ */
+ var keys = nativeKeys;
+
+ /**
+ * Creates an array of the own and inherited enumerable property names of `object`.
+ *
+ * **Note:** Non-object values are coerced to objects.
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category Object
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property names.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.keysIn(new Foo);
+ * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
+ */
+ var keysIn = nativeKeysIn;
+
+ /**
+ * Creates an object composed of the picked `object` properties.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The source object.
+ * @param {...(string|string[])} [paths] The property paths to pick.
+ * @returns {Object} Returns the new object.
+ * @example
+ *
+ * var object = { 'a': 1, 'b': '2', 'c': 3 };
+ *
+ * _.pick(object, ['a', 'c']);
+ * // => { 'a': 1, 'c': 3 }
+ */
+ var pick = flatRest(function(object, paths) {
+ return object == null ? {} : basePick(object, paths);
+ });
+
+ /**
+ * This method is like `_.get` except that if the resolved value is a
+ * function it's invoked with the `this` binding of its parent object and
+ * its result is returned.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @param {Array|string} path The path of the property to resolve.
+ * @param {*} [defaultValue] The value returned for `undefined` resolved values.
+ * @returns {*} Returns the resolved value.
+ * @example
+ *
+ * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
+ *
+ * _.result(object, 'a[0].b.c1');
+ * // => 3
+ *
+ * _.result(object, 'a[0].b.c2');
+ * // => 4
+ *
+ * _.result(object, 'a[0].b.c3', 'default');
+ * // => 'default'
+ *
+ * _.result(object, 'a[0].b.c3', _.constant('default'));
+ * // => 'default'
+ */
+ function result(object, path, defaultValue) {
+ var value = object == null ? undefined : object[path];
+ if (value === undefined) {
+ value = defaultValue;
+ }
+ return isFunction(value) ? value.call(object) : value;
+ }
+
+ /**
+ * Creates an array of the own enumerable string keyed property values of `object`.
+ *
+ * **Note:** Non-object values are coerced to objects.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Object
+ * @param {Object} object The object to query.
+ * @returns {Array} Returns the array of property values.
+ * @example
+ *
+ * function Foo() {
+ * this.a = 1;
+ * this.b = 2;
+ * }
+ *
+ * Foo.prototype.c = 3;
+ *
+ * _.values(new Foo);
+ * // => [1, 2] (iteration order is not guaranteed)
+ *
+ * _.values('hi');
+ * // => ['h', 'i']
+ */
+ function values(object) {
+ return object == null ? [] : baseValues(object, keys(object));
+ }
+
+ /*------------------------------------------------------------------------*/
+
+ /**
+ * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
+ * corresponding HTML entities.
+ *
+ * **Note:** No other characters are escaped. To escape additional
+ * characters use a third-party library like [_he_](https://mths.be/he).
+ *
+ * Though the ">" character is escaped for symmetry, characters like
+ * ">" and "/" don't need escaping in HTML and have no special meaning
+ * unless they're part of a tag or unquoted attribute value. See
+ * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
+ * (under "semi-related fun fact") for more details.
+ *
+ * When working with HTML you should always
+ * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
+ * XSS vectors.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category String
+ * @param {string} [string=''] The string to escape.
+ * @returns {string} Returns the escaped string.
+ * @example
+ *
+ * _.escape('fred, barney, & pebbles');
+ * // => 'fred, barney, & pebbles'
+ */
+ function escape(string) {
+ string = toString(string);
+ return (string && reHasUnescapedHtml.test(string))
+ ? string.replace(reUnescapedHtml, escapeHtmlChar)
+ : string;
+ }
+
+ /*------------------------------------------------------------------------*/
+
+ /**
+ * This method returns the first argument it receives.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Util
+ * @param {*} value Any value.
+ * @returns {*} Returns `value`.
+ * @example
+ *
+ * var object = { 'a': 1 };
+ *
+ * console.log(_.identity(object) === object);
+ * // => true
+ */
+ function identity(value) {
+ return value;
+ }
+
+ /**
+ * Creates a function that invokes `func` with the arguments of the created
+ * function. If `func` is a property name, the created function returns the
+ * property value for a given element. If `func` is an array or object, the
+ * created function returns `true` for elements that contain the equivalent
+ * source properties, otherwise it returns `false`.
+ *
+ * @static
+ * @since 4.0.0
+ * @memberOf _
+ * @category Util
+ * @param {*} [func=_.identity] The value to convert to a callback.
+ * @returns {Function} Returns the callback.
+ * @example
+ *
+ * var users = [
+ * { 'user': 'barney', 'age': 36, 'active': true },
+ * { 'user': 'fred', 'age': 40, 'active': false }
+ * ];
+ *
+ * // The `_.matches` iteratee shorthand.
+ * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
+ * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
+ *
+ * // The `_.matchesProperty` iteratee shorthand.
+ * _.filter(users, _.iteratee(['user', 'fred']));
+ * // => [{ 'user': 'fred', 'age': 40 }]
+ *
+ * // The `_.property` iteratee shorthand.
+ * _.map(users, _.iteratee('user'));
+ * // => ['barney', 'fred']
+ *
+ * // Create custom iteratee shorthands.
+ * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
+ * return !_.isRegExp(func) ? iteratee(func) : function(string) {
+ * return func.test(string);
+ * };
+ * });
+ *
+ * _.filter(['abc', 'def'], /ef/);
+ * // => ['def']
+ */
+ var iteratee = baseIteratee;
+
+ /**
+ * Creates a function that performs a partial deep comparison between a given
+ * object and `source`, returning `true` if the given object has equivalent
+ * property values, else `false`.
+ *
+ * **Note:** The created function is equivalent to `_.isMatch` with `source`
+ * partially applied.
+ *
+ * Partial comparisons will match empty array and empty object `source`
+ * values against any array or object value, respectively. See `_.isEqual`
+ * for a list of supported value comparisons.
+ *
+ * **Note:** Multiple values can be checked by combining several matchers
+ * using `_.overSome`
+ *
+ * @static
+ * @memberOf _
+ * @since 3.0.0
+ * @category Util
+ * @param {Object} source The object of property values to match.
+ * @returns {Function} Returns the new spec function.
+ * @example
+ *
+ * var objects = [
+ * { 'a': 1, 'b': 2, 'c': 3 },
+ * { 'a': 4, 'b': 5, 'c': 6 }
+ * ];
+ *
+ * _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
+ * // => [{ 'a': 4, 'b': 5, 'c': 6 }]
+ *
+ * // Checking for several possible values
+ * _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })]));
+ * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
+ */
+ function matches(source) {
+ return baseMatches(assign({}, source));
+ }
+
+ /**
+ * Adds all own enumerable string keyed function properties of a source
+ * object to the destination object. If `object` is a function, then methods
+ * are added to its prototype as well.
+ *
+ * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
+ * avoid conflicts caused by modifying the original.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Util
+ * @param {Function|Object} [object=lodash] The destination object.
+ * @param {Object} source The object of functions to add.
+ * @param {Object} [options={}] The options object.
+ * @param {boolean} [options.chain=true] Specify whether mixins are chainable.
+ * @returns {Function|Object} Returns `object`.
+ * @example
+ *
+ * function vowels(string) {
+ * return _.filter(string, function(v) {
+ * return /[aeiou]/i.test(v);
+ * });
+ * }
+ *
+ * _.mixin({ 'vowels': vowels });
+ * _.vowels('fred');
+ * // => ['e']
+ *
+ * _('fred').vowels().value();
+ * // => ['e']
+ *
+ * _.mixin({ 'vowels': vowels }, { 'chain': false });
+ * _('fred').vowels();
+ * // => ['e']
+ */
+ function mixin(object, source, options) {
+ var props = keys(source),
+ methodNames = baseFunctions(source, props);
+
+ if (options == null &&
+ !(isObject(source) && (methodNames.length || !props.length))) {
+ options = source;
+ source = object;
+ object = this;
+ methodNames = baseFunctions(source, keys(source));
+ }
+ var chain = !(isObject(options) && 'chain' in options) || !!options.chain,
+ isFunc = isFunction(object);
+
+ baseEach(methodNames, function(methodName) {
+ var func = source[methodName];
+ object[methodName] = func;
+ if (isFunc) {
+ object.prototype[methodName] = function() {
+ var chainAll = this.__chain__;
+ if (chain || chainAll) {
+ var result = object(this.__wrapped__),
+ actions = result.__actions__ = copyArray(this.__actions__);
+
+ actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
+ result.__chain__ = chainAll;
+ return result;
+ }
+ return func.apply(object, arrayPush([this.value()], arguments));
+ };
+ }
+ });
+
+ return object;
+ }
+
+ /**
+ * Reverts the `_` variable to its previous value and returns a reference to
+ * the `lodash` function.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Util
+ * @returns {Function} Returns the `lodash` function.
+ * @example
+ *
+ * var lodash = _.noConflict();
+ */
+ function noConflict() {
+ if (root._ === this) {
+ root._ = oldDash;
+ }
+ return this;
+ }
+
+ /**
+ * This method returns `undefined`.
+ *
+ * @static
+ * @memberOf _
+ * @since 2.3.0
+ * @category Util
+ * @example
+ *
+ * _.times(2, _.noop);
+ * // => [undefined, undefined]
+ */
+ function noop() {
+ // No operation performed.
+ }
+
+ /**
+ * Generates a unique ID. If `prefix` is given, the ID is appended to it.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Util
+ * @param {string} [prefix=''] The value to prefix the ID with.
+ * @returns {string} Returns the unique ID.
+ * @example
+ *
+ * _.uniqueId('contact_');
+ * // => 'contact_104'
+ *
+ * _.uniqueId();
+ * // => '105'
+ */
+ function uniqueId(prefix) {
+ var id = ++idCounter;
+ return toString(prefix) + id;
+ }
+
+ /*------------------------------------------------------------------------*/
+
+ /**
+ * Computes the maximum value of `array`. If `array` is empty or falsey,
+ * `undefined` is returned.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Math
+ * @param {Array} array The array to iterate over.
+ * @returns {*} Returns the maximum value.
+ * @example
+ *
+ * _.max([4, 2, 8, 6]);
+ * // => 8
+ *
+ * _.max([]);
+ * // => undefined
+ */
+ function max(array) {
+ return (array && array.length)
+ ? baseExtremum(array, identity, baseGt)
+ : undefined;
+ }
+
+ /**
+ * Computes the minimum value of `array`. If `array` is empty or falsey,
+ * `undefined` is returned.
+ *
+ * @static
+ * @since 0.1.0
+ * @memberOf _
+ * @category Math
+ * @param {Array} array The array to iterate over.
+ * @returns {*} Returns the minimum value.
+ * @example
+ *
+ * _.min([4, 2, 8, 6]);
+ * // => 2
+ *
+ * _.min([]);
+ * // => undefined
+ */
+ function min(array) {
+ return (array && array.length)
+ ? baseExtremum(array, identity, baseLt)
+ : undefined;
+ }
+
+ /*------------------------------------------------------------------------*/
+
+ // Add methods that return wrapped values in chain sequences.
+ lodash.assignIn = assignIn;
+ lodash.before = before;
+ lodash.bind = bind;
+ lodash.chain = chain;
+ lodash.compact = compact;
+ lodash.concat = concat;
+ lodash.create = create;
+ lodash.defaults = defaults;
+ lodash.defer = defer;
+ lodash.delay = delay;
+ lodash.filter = filter;
+ lodash.flatten = flatten;
+ lodash.flattenDeep = flattenDeep;
+ lodash.iteratee = iteratee;
+ lodash.keys = keys;
+ lodash.map = map;
+ lodash.matches = matches;
+ lodash.mixin = mixin;
+ lodash.negate = negate;
+ lodash.once = once;
+ lodash.pick = pick;
+ lodash.slice = slice;
+ lodash.sortBy = sortBy;
+ lodash.tap = tap;
+ lodash.thru = thru;
+ lodash.toArray = toArray;
+ lodash.values = values;
+
+ // Add aliases.
+ lodash.extend = assignIn;
+
+ // Add methods to `lodash.prototype`.
+ mixin(lodash, lodash);
+
+ /*------------------------------------------------------------------------*/
+
+ // Add methods that return unwrapped values in chain sequences.
+ lodash.clone = clone;
+ lodash.escape = escape;
+ lodash.every = every;
+ lodash.find = find;
+ lodash.forEach = forEach;
+ lodash.has = has;
+ lodash.head = head;
+ lodash.identity = identity;
+ lodash.indexOf = indexOf;
+ lodash.isArguments = isArguments;
+ lodash.isArray = isArray;
+ lodash.isBoolean = isBoolean;
+ lodash.isDate = isDate;
+ lodash.isEmpty = isEmpty;
+ lodash.isEqual = isEqual;
+ lodash.isFinite = isFinite;
+ lodash.isFunction = isFunction;
+ lodash.isNaN = isNaN;
+ lodash.isNull = isNull;
+ lodash.isNumber = isNumber;
+ lodash.isObject = isObject;
+ lodash.isRegExp = isRegExp;
+ lodash.isString = isString;
+ lodash.isUndefined = isUndefined;
+ lodash.last = last;
+ lodash.max = max;
+ lodash.min = min;
+ lodash.noConflict = noConflict;
+ lodash.noop = noop;
+ lodash.reduce = reduce;
+ lodash.result = result;
+ lodash.size = size;
+ lodash.some = some;
+ lodash.uniqueId = uniqueId;
+
+ // Add aliases.
+ lodash.each = forEach;
+ lodash.first = head;
+
+ mixin(lodash, (function() {
+ var source = {};
+ baseForOwn(lodash, function(func, methodName) {
+ if (!hasOwnProperty.call(lodash.prototype, methodName)) {
+ source[methodName] = func;
+ }
+ });
+ return source;
+ }()), { 'chain': false });
+
+ /*------------------------------------------------------------------------*/
+
+ /**
+ * The semantic version number.
+ *
+ * @static
+ * @memberOf _
+ * @type {string}
+ */
+ lodash.VERSION = VERSION;
+
+ // Add `Array` methods to `lodash.prototype`.
+ baseEach(['pop', 'join', 'replace', 'reverse', 'split', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
+ var func = (/^(?:replace|split)$/.test(methodName) ? String.prototype : arrayProto)[methodName],
+ chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
+ retUnwrapped = /^(?:pop|join|replace|shift)$/.test(methodName);
+
+ lodash.prototype[methodName] = function() {
+ var args = arguments;
+ if (retUnwrapped && !this.__chain__) {
+ var value = this.value();
+ return func.apply(isArray(value) ? value : [], args);
+ }
+ return this[chainName](function(value) {
+ return func.apply(isArray(value) ? value : [], args);
+ });
+ };
+ });
+
+ // Add chain sequence methods to the `lodash` wrapper.
+ lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
+
+ /*--------------------------------------------------------------------------*/
+
+ // Some AMD build optimizers, like r.js, check for condition patterns like:
+ if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
+ // Expose Lodash on the global object to prevent errors when Lodash is
+ // loaded by a script tag in the presence of an AMD loader.
+ // See http://requirejs.org/docs/errors.html#mismatch for more details.
+ // Use `_.noConflict` to remove Lodash from the global object.
+ root._ = lodash;
+
+ // Define as an anonymous module so, through path mapping, it can be
+ // referenced as the "underscore" module.
+ define(function() {
+ return lodash;
+ });
+ }
+ // Check for `exports` after `define` in case a build optimizer adds it.
+ else if (freeModule) {
+ // Export for Node.js.
+ (freeModule.exports = lodash)._ = lodash;
+ // Export for CommonJS support.
+ freeExports._ = lodash;
+ }
+ else {
+ // Export to the global object.
+ root._ = lodash;
+ }
+}.call(this));
diff --git a/node_modules/lodash/core.min.js b/node_modules/lodash/core.min.js
new file mode 100644
index 0000000..e425e4d
--- /dev/null
+++ b/node_modules/lodash/core.min.js
@@ -0,0 +1,29 @@
+/**
+ * @license
+ * Lodash (Custom Build) lodash.com/license | Underscore.js 1.8.3 underscorejs.org/LICENSE
+ * Build: `lodash core -o ./dist/lodash.core.js`
+ */
+;(function(){function n(n){return H(n)&&pn.call(n,"callee")&&!yn.call(n,"callee")}function t(n,t){return n.push.apply(n,t),n}function r(n){return function(t){return null==t?Z:t[n]}}function e(n,t,r,e,u){return u(n,function(n,u,o){r=e?(e=false,n):t(r,n,u,o)}),r}function u(n,t){return j(t,function(t){return n[t]})}function o(n){return n instanceof i?n:new i(n)}function i(n,t){this.__wrapped__=n,this.__actions__=[],this.__chain__=!!t}function c(n,t,r){if(typeof n!="function")throw new TypeError("Expected a function");
+return setTimeout(function(){n.apply(Z,r)},t)}function f(n,t){var r=true;return mn(n,function(n,e,u){return r=!!t(n,e,u)}),r}function a(n,t,r){for(var e=-1,u=n.length;++et}function b(n,t,r,e,u){return n===t||(null==n||null==t||!H(n)&&!H(t)?n!==n&&t!==t:y(n,t,r,e,b,u))}function y(n,t,r,e,u,o){var i=Nn(n),c=Nn(t),f=i?"[object Array]":hn.call(n),a=c?"[object Array]":hn.call(t),f="[object Arguments]"==f?"[object Object]":f,a="[object Arguments]"==a?"[object Object]":a,l="[object Object]"==f,c="[object Object]"==a,a=f==a;o||(o=[]);var p=An(o,function(t){return t[0]==n}),s=An(o,function(n){
+return n[0]==t});if(p&&s)return p[1]==t;if(o.push([n,t]),o.push([t,n]),a&&!l){if(i)r=T(n,t,r,e,u,o);else n:{switch(f){case"[object Boolean]":case"[object Date]":case"[object Number]":r=J(+n,+t);break n;case"[object Error]":r=n.name==t.name&&n.message==t.message;break n;case"[object RegExp]":case"[object String]":r=n==t+"";break n}r=false}return o.pop(),r}return 1&r||(i=l&&pn.call(n,"__wrapped__"),f=c&&pn.call(t,"__wrapped__"),!i&&!f)?!!a&&(r=B(n,t,r,e,u,o),o.pop(),r):(i=i?n.value():n,f=f?t.value():t,
+r=u(i,f,r,e,o),o.pop(),r)}function g(n){return typeof n=="function"?n:null==n?X:(typeof n=="object"?d:r)(n)}function _(n,t){return nt&&(t=-t>u?0:u+t),r=r>u?u:r,0>r&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0,r=Array(u);++ei))return false;var c=o.get(n),f=o.get(t);if(c&&f)return c==t&&f==n;for(var c=-1,f=true,a=2&r?[]:Z;++cr?jn(e+r,0):r:0,r=(r||0)-1;for(var u=t===t;++rarguments.length,mn);
+}function G(n,t){var r;if(typeof t!="function")throw new TypeError("Expected a function");return n=Fn(n),function(){return 0<--n&&(r=t.apply(this,arguments)),1>=n&&(t=Z),r}}function J(n,t){return n===t||n!==n&&t!==t}function M(n){var t;return(t=null!=n)&&(t=n.length,t=typeof t=="number"&&-1=t),t&&!U(n)}function U(n){return!!V(n)&&(n=hn.call(n),"[object Function]"==n||"[object GeneratorFunction]"==n||"[object AsyncFunction]"==n||"[object Proxy]"==n)}function V(n){var t=typeof n;
+return null!=n&&("object"==t||"function"==t)}function H(n){return null!=n&&typeof n=="object"}function K(n){return typeof n=="number"||H(n)&&"[object Number]"==hn.call(n)}function L(n){return typeof n=="string"||!Nn(n)&&H(n)&&"[object String]"==hn.call(n)}function Q(n){return typeof n=="string"?n:null==n?"":n+""}function W(n){return null==n?[]:u(n,Dn(n))}function X(n){return n}function Y(n,r,e){var u=Dn(r),o=h(r,u);null!=e||V(r)&&(o.length||!u.length)||(e=r,r=n,n=this,o=h(r,Dn(r)));var i=!(V(e)&&"chain"in e&&!e.chain),c=U(n);
+return mn(o,function(e){var u=r[e];n[e]=u,c&&(n.prototype[e]=function(){var r=this.__chain__;if(i||r){var e=n(this.__wrapped__);return(e.__actions__=A(this.__actions__)).push({func:u,args:arguments,thisArg:n}),e.__chain__=r,e}return u.apply(n,t([this.value()],arguments))})}),n}var Z,nn=1/0,tn=/[&<>"']/g,rn=RegExp(tn.source),en=/^(?:0|[1-9]\d*)$/,un=typeof self=="object"&&self&&self.Object===Object&&self,on=typeof global=="object"&&global&&global.Object===Object&&global||un||Function("return this")(),cn=(un=typeof exports=="object"&&exports&&!exports.nodeType&&exports)&&typeof module=="object"&&module&&!module.nodeType&&module,fn=function(n){
+return function(t){return null==n?Z:n[t]}}({"&":"&","<":"<",">":">",'"':""","'":"'"}),an=Array.prototype,ln=Object.prototype,pn=ln.hasOwnProperty,sn=0,hn=ln.toString,vn=on._,bn=Object.create,yn=ln.propertyIsEnumerable,gn=on.isFinite,_n=function(n,t){return function(r){return n(t(r))}}(Object.keys,Object),jn=Math.max,dn=function(){function n(){}return function(t){return V(t)?bn?bn(t):(n.prototype=t,t=new n,n.prototype=Z,t):{}}}();i.prototype=dn(o.prototype),i.prototype.constructor=i;
+var mn=function(n,t){return function(r,e){if(null==r)return r;if(!M(r))return n(r,e);for(var u=r.length,o=t?u:-1,i=Object(r);(t?o--:++or&&(r=jn(e+r,0));n:{for(t=g(t),e=n.length,r+=-1;++re||o&&c&&a||!u&&a||!i){r=1;break n}if(!o&&r