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 += "\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 { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ +var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } +}); + +module.exports = countBy; diff --git a/node_modules/lodash/create.js b/node_modules/lodash/create.js new file mode 100644 index 0000000..919edb8 --- /dev/null +++ b/node_modules/lodash/create.js @@ -0,0 +1,43 @@ +var baseAssign = require('./_baseAssign'), + baseCreate = require('./_baseCreate'); + +/** + * 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 : baseAssign(result, properties); +} + +module.exports = create; diff --git a/node_modules/lodash/curry.js b/node_modules/lodash/curry.js new file mode 100644 index 0000000..918db1a --- /dev/null +++ b/node_modules/lodash/curry.js @@ -0,0 +1,57 @@ +var createWrap = require('./_createWrap'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_CURRY_FLAG = 8; + +/** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ +function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; +} + +// Assign default placeholders. +curry.placeholder = {}; + +module.exports = curry; diff --git a/node_modules/lodash/curryRight.js b/node_modules/lodash/curryRight.js new file mode 100644 index 0000000..c85b6f3 --- /dev/null +++ b/node_modules/lodash/curryRight.js @@ -0,0 +1,54 @@ +var createWrap = require('./_createWrap'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_CURRY_RIGHT_FLAG = 16; + +/** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ +function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; +} + +// Assign default placeholders. +curryRight.placeholder = {}; + +module.exports = curryRight; diff --git a/node_modules/lodash/date.js b/node_modules/lodash/date.js new file mode 100644 index 0000000..cbf5b41 --- /dev/null +++ b/node_modules/lodash/date.js @@ -0,0 +1,3 @@ +module.exports = { + 'now': require('./now') +}; diff --git a/node_modules/lodash/debounce.js b/node_modules/lodash/debounce.js new file mode 100644 index 0000000..8f751d5 --- /dev/null +++ b/node_modules/lodash/debounce.js @@ -0,0 +1,191 @@ +var isObject = require('./isObject'), + now = require('./now'), + toNumber = require('./toNumber'); + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ +function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + timeWaiting = wait - timeSinceLastCall; + + return maxing + ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) + : timeWaiting; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + clearTimeout(timerId); + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; +} + +module.exports = debounce; diff --git a/node_modules/lodash/deburr.js b/node_modules/lodash/deburr.js new file mode 100644 index 0000000..f85e314 --- /dev/null +++ b/node_modules/lodash/deburr.js @@ -0,0 +1,45 @@ +var deburrLetter = require('./_deburrLetter'), + toString = require('./toString'); + +/** Used to match Latin Unicode letters (excluding mathematical operators). */ +var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + +/** Used to compose unicode character classes. */ +var rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange; + +/** Used to compose unicode capture groups. */ +var rsCombo = '[' + rsComboRange + ']'; + +/** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ +var reComboMark = RegExp(rsCombo, 'g'); + +/** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ +function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); +} + +module.exports = deburr; diff --git a/node_modules/lodash/defaultTo.js b/node_modules/lodash/defaultTo.js new file mode 100644 index 0000000..5b33359 --- /dev/null +++ b/node_modules/lodash/defaultTo.js @@ -0,0 +1,25 @@ +/** + * Checks `value` to determine whether a default value should be returned in + * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, + * or `undefined`. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Util + * @param {*} value The value to check. + * @param {*} defaultValue The default value. + * @returns {*} Returns the resolved value. + * @example + * + * _.defaultTo(1, 10); + * // => 1 + * + * _.defaultTo(undefined, 10); + * // => 10 + */ +function defaultTo(value, defaultValue) { + return (value == null || value !== value) ? defaultValue : value; +} + +module.exports = defaultTo; diff --git a/node_modules/lodash/defaults.js b/node_modules/lodash/defaults.js new file mode 100644 index 0000000..c74df04 --- /dev/null +++ b/node_modules/lodash/defaults.js @@ -0,0 +1,64 @@ +var baseRest = require('./_baseRest'), + eq = require('./eq'), + isIterateeCall = require('./_isIterateeCall'), + keysIn = require('./keysIn'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * 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; +}); + +module.exports = defaults; diff --git a/node_modules/lodash/defaultsDeep.js b/node_modules/lodash/defaultsDeep.js new file mode 100644 index 0000000..9b5fa3e --- /dev/null +++ b/node_modules/lodash/defaultsDeep.js @@ -0,0 +1,30 @@ +var apply = require('./_apply'), + baseRest = require('./_baseRest'), + customDefaultsMerge = require('./_customDefaultsMerge'), + mergeWith = require('./mergeWith'); + +/** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ +var defaultsDeep = baseRest(function(args) { + args.push(undefined, customDefaultsMerge); + return apply(mergeWith, undefined, args); +}); + +module.exports = defaultsDeep; diff --git a/node_modules/lodash/defer.js b/node_modules/lodash/defer.js new file mode 100644 index 0000000..f6d6c6f --- /dev/null +++ b/node_modules/lodash/defer.js @@ -0,0 +1,26 @@ +var baseDelay = require('./_baseDelay'), + baseRest = require('./_baseRest'); + +/** + * 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); +}); + +module.exports = defer; diff --git a/node_modules/lodash/delay.js b/node_modules/lodash/delay.js new file mode 100644 index 0000000..bd55479 --- /dev/null +++ b/node_modules/lodash/delay.js @@ -0,0 +1,28 @@ +var baseDelay = require('./_baseDelay'), + baseRest = require('./_baseRest'), + toNumber = require('./toNumber'); + +/** + * 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); +}); + +module.exports = delay; diff --git a/node_modules/lodash/difference.js b/node_modules/lodash/difference.js new file mode 100644 index 0000000..fa28bb3 --- /dev/null +++ b/node_modules/lodash/difference.js @@ -0,0 +1,33 @@ +var baseDifference = require('./_baseDifference'), + baseFlatten = require('./_baseFlatten'), + baseRest = require('./_baseRest'), + isArrayLikeObject = require('./isArrayLikeObject'); + +/** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ +var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; +}); + +module.exports = difference; diff --git a/node_modules/lodash/differenceBy.js b/node_modules/lodash/differenceBy.js new file mode 100644 index 0000000..2cd63e7 --- /dev/null +++ b/node_modules/lodash/differenceBy.js @@ -0,0 +1,44 @@ +var baseDifference = require('./_baseDifference'), + baseFlatten = require('./_baseFlatten'), + baseIteratee = require('./_baseIteratee'), + baseRest = require('./_baseRest'), + isArrayLikeObject = require('./isArrayLikeObject'), + last = require('./last'); + +/** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ +var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), baseIteratee(iteratee, 2)) + : []; +}); + +module.exports = differenceBy; diff --git a/node_modules/lodash/differenceWith.js b/node_modules/lodash/differenceWith.js new file mode 100644 index 0000000..c0233f4 --- /dev/null +++ b/node_modules/lodash/differenceWith.js @@ -0,0 +1,40 @@ +var baseDifference = require('./_baseDifference'), + baseFlatten = require('./_baseFlatten'), + baseRest = require('./_baseRest'), + isArrayLikeObject = require('./isArrayLikeObject'), + last = require('./last'); + +/** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ +var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; +}); + +module.exports = differenceWith; diff --git a/node_modules/lodash/divide.js b/node_modules/lodash/divide.js new file mode 100644 index 0000000..8cae0cd --- /dev/null +++ b/node_modules/lodash/divide.js @@ -0,0 +1,22 @@ +var createMathOperation = require('./_createMathOperation'); + +/** + * Divide two numbers. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Math + * @param {number} dividend The first number in a division. + * @param {number} divisor The second number in a division. + * @returns {number} Returns the quotient. + * @example + * + * _.divide(6, 4); + * // => 1.5 + */ +var divide = createMathOperation(function(dividend, divisor) { + return dividend / divisor; +}, 1); + +module.exports = divide; diff --git a/node_modules/lodash/drop.js b/node_modules/lodash/drop.js new file mode 100644 index 0000000..d5c3cba --- /dev/null +++ b/node_modules/lodash/drop.js @@ -0,0 +1,38 @@ +var baseSlice = require('./_baseSlice'), + toInteger = require('./toInteger'); + +/** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ +function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); +} + +module.exports = drop; diff --git a/node_modules/lodash/dropRight.js b/node_modules/lodash/dropRight.js new file mode 100644 index 0000000..441fe99 --- /dev/null +++ b/node_modules/lodash/dropRight.js @@ -0,0 +1,39 @@ +var baseSlice = require('./_baseSlice'), + toInteger = require('./toInteger'); + +/** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ +function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); +} + +module.exports = dropRight; diff --git a/node_modules/lodash/dropRightWhile.js b/node_modules/lodash/dropRightWhile.js new file mode 100644 index 0000000..9ad36a0 --- /dev/null +++ b/node_modules/lodash/dropRightWhile.js @@ -0,0 +1,45 @@ +var baseIteratee = require('./_baseIteratee'), + baseWhile = require('./_baseWhile'); + +/** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ +function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, baseIteratee(predicate, 3), true, true) + : []; +} + +module.exports = dropRightWhile; diff --git a/node_modules/lodash/dropWhile.js b/node_modules/lodash/dropWhile.js new file mode 100644 index 0000000..903ef56 --- /dev/null +++ b/node_modules/lodash/dropWhile.js @@ -0,0 +1,45 @@ +var baseIteratee = require('./_baseIteratee'), + baseWhile = require('./_baseWhile'); + +/** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ +function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, baseIteratee(predicate, 3), true) + : []; +} + +module.exports = dropWhile; diff --git a/node_modules/lodash/each.js b/node_modules/lodash/each.js new file mode 100644 index 0000000..8800f42 --- /dev/null +++ b/node_modules/lodash/each.js @@ -0,0 +1 @@ +module.exports = require('./forEach'); diff --git a/node_modules/lodash/eachRight.js b/node_modules/lodash/eachRight.js new file mode 100644 index 0000000..3252b2a --- /dev/null +++ b/node_modules/lodash/eachRight.js @@ -0,0 +1 @@ +module.exports = require('./forEachRight'); diff --git a/node_modules/lodash/endsWith.js b/node_modules/lodash/endsWith.js new file mode 100644 index 0000000..76fc866 --- /dev/null +++ b/node_modules/lodash/endsWith.js @@ -0,0 +1,43 @@ +var baseClamp = require('./_baseClamp'), + baseToString = require('./_baseToString'), + toInteger = require('./toInteger'), + toString = require('./toString'); + +/** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ +function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; +} + +module.exports = endsWith; diff --git a/node_modules/lodash/entries.js b/node_modules/lodash/entries.js new file mode 100644 index 0000000..7a88df2 --- /dev/null +++ b/node_modules/lodash/entries.js @@ -0,0 +1 @@ +module.exports = require('./toPairs'); diff --git a/node_modules/lodash/entriesIn.js b/node_modules/lodash/entriesIn.js new file mode 100644 index 0000000..f6c6331 --- /dev/null +++ b/node_modules/lodash/entriesIn.js @@ -0,0 +1 @@ +module.exports = require('./toPairsIn'); diff --git a/node_modules/lodash/eq.js b/node_modules/lodash/eq.js new file mode 100644 index 0000000..a940688 --- /dev/null +++ b/node_modules/lodash/eq.js @@ -0,0 +1,37 @@ +/** + * 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); +} + +module.exports = eq; diff --git a/node_modules/lodash/escape.js b/node_modules/lodash/escape.js new file mode 100644 index 0000000..9247e00 --- /dev/null +++ b/node_modules/lodash/escape.js @@ -0,0 +1,43 @@ +var escapeHtmlChar = require('./_escapeHtmlChar'), + toString = require('./toString'); + +/** Used to match HTML entities and HTML characters. */ +var reUnescapedHtml = /[&<>"']/g, + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + +/** + * 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; +} + +module.exports = escape; diff --git a/node_modules/lodash/escapeRegExp.js b/node_modules/lodash/escapeRegExp.js new file mode 100644 index 0000000..0a58c69 --- /dev/null +++ b/node_modules/lodash/escapeRegExp.js @@ -0,0 +1,32 @@ +var toString = require('./toString'); + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + +/** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ +function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; +} + +module.exports = escapeRegExp; diff --git a/node_modules/lodash/every.js b/node_modules/lodash/every.js new file mode 100644 index 0000000..25080da --- /dev/null +++ b/node_modules/lodash/every.js @@ -0,0 +1,56 @@ +var arrayEvery = require('./_arrayEvery'), + baseEvery = require('./_baseEvery'), + baseIteratee = require('./_baseIteratee'), + isArray = require('./isArray'), + isIterateeCall = require('./_isIterateeCall'); + +/** + * 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) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, baseIteratee(predicate, 3)); +} + +module.exports = every; diff --git a/node_modules/lodash/extend.js b/node_modules/lodash/extend.js new file mode 100644 index 0000000..e00166c --- /dev/null +++ b/node_modules/lodash/extend.js @@ -0,0 +1 @@ +module.exports = require('./assignIn'); diff --git a/node_modules/lodash/extendWith.js b/node_modules/lodash/extendWith.js new file mode 100644 index 0000000..dbdcb3b --- /dev/null +++ b/node_modules/lodash/extendWith.js @@ -0,0 +1 @@ +module.exports = require('./assignInWith'); diff --git a/node_modules/lodash/fill.js b/node_modules/lodash/fill.js new file mode 100644 index 0000000..ae13aa1 --- /dev/null +++ b/node_modules/lodash/fill.js @@ -0,0 +1,45 @@ +var baseFill = require('./_baseFill'), + isIterateeCall = require('./_isIterateeCall'); + +/** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @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`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ +function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); +} + +module.exports = fill; diff --git a/node_modules/lodash/filter.js b/node_modules/lodash/filter.js new file mode 100644 index 0000000..89e0c8c --- /dev/null +++ b/node_modules/lodash/filter.js @@ -0,0 +1,52 @@ +var arrayFilter = require('./_arrayFilter'), + baseFilter = require('./_baseFilter'), + baseIteratee = require('./_baseIteratee'), + isArray = require('./isArray'); + +/** + * 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) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, baseIteratee(predicate, 3)); +} + +module.exports = filter; diff --git a/node_modules/lodash/find.js b/node_modules/lodash/find.js new file mode 100644 index 0000000..de732cc --- /dev/null +++ b/node_modules/lodash/find.js @@ -0,0 +1,42 @@ +var createFind = require('./_createFind'), + findIndex = require('./findIndex'); + +/** + * 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); + +module.exports = find; diff --git a/node_modules/lodash/findIndex.js b/node_modules/lodash/findIndex.js new file mode 100644 index 0000000..4689069 --- /dev/null +++ b/node_modules/lodash/findIndex.js @@ -0,0 +1,55 @@ +var baseFindIndex = require('./_baseFindIndex'), + baseIteratee = require('./_baseIteratee'), + toInteger = require('./toInteger'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * 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); +} + +module.exports = findIndex; diff --git a/node_modules/lodash/findKey.js b/node_modules/lodash/findKey.js new file mode 100644 index 0000000..cac0248 --- /dev/null +++ b/node_modules/lodash/findKey.js @@ -0,0 +1,44 @@ +var baseFindKey = require('./_baseFindKey'), + baseForOwn = require('./_baseForOwn'), + baseIteratee = require('./_baseIteratee'); + +/** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ +function findKey(object, predicate) { + return baseFindKey(object, baseIteratee(predicate, 3), baseForOwn); +} + +module.exports = findKey; diff --git a/node_modules/lodash/findLast.js b/node_modules/lodash/findLast.js new file mode 100644 index 0000000..70b4271 --- /dev/null +++ b/node_modules/lodash/findLast.js @@ -0,0 +1,25 @@ +var createFind = require('./_createFind'), + findLastIndex = require('./findLastIndex'); + +/** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ +var findLast = createFind(findLastIndex); + +module.exports = findLast; diff --git a/node_modules/lodash/findLastIndex.js b/node_modules/lodash/findLastIndex.js new file mode 100644 index 0000000..7da3431 --- /dev/null +++ b/node_modules/lodash/findLastIndex.js @@ -0,0 +1,59 @@ +var baseFindIndex = require('./_baseFindIndex'), + baseIteratee = require('./_baseIteratee'), + toInteger = require('./toInteger'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ +function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, baseIteratee(predicate, 3), index, true); +} + +module.exports = findLastIndex; diff --git a/node_modules/lodash/findLastKey.js b/node_modules/lodash/findLastKey.js new file mode 100644 index 0000000..66fb9fb --- /dev/null +++ b/node_modules/lodash/findLastKey.js @@ -0,0 +1,44 @@ +var baseFindKey = require('./_baseFindKey'), + baseForOwnRight = require('./_baseForOwnRight'), + baseIteratee = require('./_baseIteratee'); + +/** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ +function findLastKey(object, predicate) { + return baseFindKey(object, baseIteratee(predicate, 3), baseForOwnRight); +} + +module.exports = findLastKey; diff --git a/node_modules/lodash/first.js b/node_modules/lodash/first.js new file mode 100644 index 0000000..53f4ad1 --- /dev/null +++ b/node_modules/lodash/first.js @@ -0,0 +1 @@ +module.exports = require('./head'); diff --git a/node_modules/lodash/flake.lock b/node_modules/lodash/flake.lock new file mode 100644 index 0000000..dd03252 --- /dev/null +++ b/node_modules/lodash/flake.lock @@ -0,0 +1,40 @@ +{ + "nodes": { + "nixpkgs": { + "locked": { + "lastModified": 1613582597, + "narHash": "sha256-6LvipIvFuhyorHpUqK3HjySC5Y6gshXHFBhU9EJ4DoM=", + "path": "/nix/store/srvplqq673sqd9vyfhyc5w1p88y1gfm4-source", + "rev": "6b1057b452c55bb3b463f0d7055bc4ec3fd1f381", + "type": "path" + }, + "original": { + "id": "nixpkgs", + "type": "indirect" + } + }, + "root": { + "inputs": { + "nixpkgs": "nixpkgs", + "utils": "utils" + } + }, + "utils": { + "locked": { + "lastModified": 1610051610, + "narHash": "sha256-U9rPz/usA1/Aohhk7Cmc2gBrEEKRzcW4nwPWMPwja4Y=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "3982c9903e93927c2164caa727cd3f6a0e6d14cc", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + } + }, + "root": "root", + "version": 7 +} diff --git a/node_modules/lodash/flake.nix b/node_modules/lodash/flake.nix new file mode 100644 index 0000000..15a451c --- /dev/null +++ b/node_modules/lodash/flake.nix @@ -0,0 +1,20 @@ +{ + inputs = { + utils.url = "github:numtide/flake-utils"; + }; + + outputs = { self, nixpkgs, utils }: + utils.lib.eachDefaultSystem (system: + let + pkgs = nixpkgs.legacyPackages."${system}"; + in rec { + devShell = pkgs.mkShell { + nativeBuildInputs = with pkgs; [ + yarn + nodejs-14_x + nodePackages.typescript-language-server + nodePackages.eslint + ]; + }; + }); +} diff --git a/node_modules/lodash/flatMap.js b/node_modules/lodash/flatMap.js new file mode 100644 index 0000000..e668506 --- /dev/null +++ b/node_modules/lodash/flatMap.js @@ -0,0 +1,29 @@ +var baseFlatten = require('./_baseFlatten'), + map = require('./map'); + +/** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.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 flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ +function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); +} + +module.exports = flatMap; diff --git a/node_modules/lodash/flatMapDeep.js b/node_modules/lodash/flatMapDeep.js new file mode 100644 index 0000000..4653d60 --- /dev/null +++ b/node_modules/lodash/flatMapDeep.js @@ -0,0 +1,31 @@ +var baseFlatten = require('./_baseFlatten'), + map = require('./map'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.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 flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ +function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); +} + +module.exports = flatMapDeep; diff --git a/node_modules/lodash/flatMapDepth.js b/node_modules/lodash/flatMapDepth.js new file mode 100644 index 0000000..6d72005 --- /dev/null +++ b/node_modules/lodash/flatMapDepth.js @@ -0,0 +1,31 @@ +var baseFlatten = require('./_baseFlatten'), + map = require('./map'), + toInteger = require('./toInteger'); + +/** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ +function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); +} + +module.exports = flatMapDepth; diff --git a/node_modules/lodash/flatten.js b/node_modules/lodash/flatten.js new file mode 100644 index 0000000..3f09f7f --- /dev/null +++ b/node_modules/lodash/flatten.js @@ -0,0 +1,22 @@ +var baseFlatten = require('./_baseFlatten'); + +/** + * 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) : []; +} + +module.exports = flatten; diff --git a/node_modules/lodash/flattenDeep.js b/node_modules/lodash/flattenDeep.js new file mode 100644 index 0000000..8ad585c --- /dev/null +++ b/node_modules/lodash/flattenDeep.js @@ -0,0 +1,25 @@ +var baseFlatten = require('./_baseFlatten'); + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** + * 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) : []; +} + +module.exports = flattenDeep; diff --git a/node_modules/lodash/flattenDepth.js b/node_modules/lodash/flattenDepth.js new file mode 100644 index 0000000..441fdcc --- /dev/null +++ b/node_modules/lodash/flattenDepth.js @@ -0,0 +1,33 @@ +var baseFlatten = require('./_baseFlatten'), + toInteger = require('./toInteger'); + +/** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ +function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); +} + +module.exports = flattenDepth; diff --git a/node_modules/lodash/flip.js b/node_modules/lodash/flip.js new file mode 100644 index 0000000..c28dd78 --- /dev/null +++ b/node_modules/lodash/flip.js @@ -0,0 +1,28 @@ +var createWrap = require('./_createWrap'); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_FLIP_FLAG = 512; + +/** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ +function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); +} + +module.exports = flip; diff --git a/node_modules/lodash/floor.js b/node_modules/lodash/floor.js new file mode 100644 index 0000000..ab6dfa2 --- /dev/null +++ b/node_modules/lodash/floor.js @@ -0,0 +1,26 @@ +var createRound = require('./_createRound'); + +/** + * Computes `number` rounded down to `precision`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Math + * @param {number} number The number to round down. + * @param {number} [precision=0] The precision to round down to. + * @returns {number} Returns the rounded down number. + * @example + * + * _.floor(4.006); + * // => 4 + * + * _.floor(0.046, 2); + * // => 0.04 + * + * _.floor(4060, -2); + * // => 4000 + */ +var floor = createRound('floor'); + +module.exports = floor; diff --git a/node_modules/lodash/flow.js b/node_modules/lodash/flow.js new file mode 100644 index 0000000..74b6b62 --- /dev/null +++ b/node_modules/lodash/flow.js @@ -0,0 +1,27 @@ +var createFlow = require('./_createFlow'); + +/** + * Creates a function that returns the result of invoking the given functions + * with the `this` binding of the created function, where each successive + * invocation is supplied the return value of the previous. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {...(Function|Function[])} [funcs] The functions to invoke. + * @returns {Function} Returns the new composite function. + * @see _.flowRight + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flow([_.add, square]); + * addSquare(1, 2); + * // => 9 + */ +var flow = createFlow(); + +module.exports = flow; diff --git a/node_modules/lodash/flowRight.js b/node_modules/lodash/flowRight.js new file mode 100644 index 0000000..1146141 --- /dev/null +++ b/node_modules/lodash/flowRight.js @@ -0,0 +1,26 @@ +var createFlow = require('./_createFlow'); + +/** + * This method is like `_.flow` except that it creates a function that + * invokes the given functions from right to left. + * + * @static + * @since 3.0.0 + * @memberOf _ + * @category Util + * @param {...(Function|Function[])} [funcs] The functions to invoke. + * @returns {Function} Returns the new composite function. + * @see _.flow + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flowRight([square, _.add]); + * addSquare(1, 2); + * // => 9 + */ +var flowRight = createFlow(true); + +module.exports = flowRight; diff --git a/node_modules/lodash/forEach.js b/node_modules/lodash/forEach.js new file mode 100644 index 0000000..c64eaa7 --- /dev/null +++ b/node_modules/lodash/forEach.js @@ -0,0 +1,41 @@ +var arrayEach = require('./_arrayEach'), + baseEach = require('./_baseEach'), + castFunction = require('./_castFunction'), + isArray = require('./isArray'); + +/** + * 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) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, castFunction(iteratee)); +} + +module.exports = forEach; diff --git a/node_modules/lodash/forEachRight.js b/node_modules/lodash/forEachRight.js new file mode 100644 index 0000000..7390eba --- /dev/null +++ b/node_modules/lodash/forEachRight.js @@ -0,0 +1,31 @@ +var arrayEachRight = require('./_arrayEachRight'), + baseEachRight = require('./_baseEachRight'), + castFunction = require('./_castFunction'), + isArray = require('./isArray'); + +/** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @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 _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ +function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, castFunction(iteratee)); +} + +module.exports = forEachRight; diff --git a/node_modules/lodash/forIn.js b/node_modules/lodash/forIn.js new file mode 100644 index 0000000..583a596 --- /dev/null +++ b/node_modules/lodash/forIn.js @@ -0,0 +1,39 @@ +var baseFor = require('./_baseFor'), + castFunction = require('./_castFunction'), + keysIn = require('./keysIn'); + +/** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ +function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, castFunction(iteratee), keysIn); +} + +module.exports = forIn; diff --git a/node_modules/lodash/forInRight.js b/node_modules/lodash/forInRight.js new file mode 100644 index 0000000..4aedf58 --- /dev/null +++ b/node_modules/lodash/forInRight.js @@ -0,0 +1,37 @@ +var baseForRight = require('./_baseForRight'), + castFunction = require('./_castFunction'), + keysIn = require('./keysIn'); + +/** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ +function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, castFunction(iteratee), keysIn); +} + +module.exports = forInRight; diff --git a/node_modules/lodash/forOwn.js b/node_modules/lodash/forOwn.js new file mode 100644 index 0000000..94eed84 --- /dev/null +++ b/node_modules/lodash/forOwn.js @@ -0,0 +1,36 @@ +var baseForOwn = require('./_baseForOwn'), + castFunction = require('./_castFunction'); + +/** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ +function forOwn(object, iteratee) { + return object && baseForOwn(object, castFunction(iteratee)); +} + +module.exports = forOwn; diff --git a/node_modules/lodash/forOwnRight.js b/node_modules/lodash/forOwnRight.js new file mode 100644 index 0000000..86f338f --- /dev/null +++ b/node_modules/lodash/forOwnRight.js @@ -0,0 +1,34 @@ +var baseForOwnRight = require('./_baseForOwnRight'), + castFunction = require('./_castFunction'); + +/** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ +function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, castFunction(iteratee)); +} + +module.exports = forOwnRight; diff --git a/node_modules/lodash/fp.js b/node_modules/lodash/fp.js new file mode 100644 index 0000000..e372dbb --- /dev/null +++ b/node_modules/lodash/fp.js @@ -0,0 +1,2 @@ +var _ = require('./lodash.min').runInContext(); +module.exports = require('./fp/_baseConvert')(_, _); diff --git a/node_modules/lodash/fp/F.js b/node_modules/lodash/fp/F.js new file mode 100644 index 0000000..a05a63a --- /dev/null +++ b/node_modules/lodash/fp/F.js @@ -0,0 +1 @@ +module.exports = require('./stubFalse'); diff --git a/node_modules/lodash/fp/T.js b/node_modules/lodash/fp/T.js new file mode 100644 index 0000000..e2ba8ea --- /dev/null +++ b/node_modules/lodash/fp/T.js @@ -0,0 +1 @@ +module.exports = require('./stubTrue'); diff --git a/node_modules/lodash/fp/__.js b/node_modules/lodash/fp/__.js new file mode 100644 index 0000000..4af98de --- /dev/null +++ b/node_modules/lodash/fp/__.js @@ -0,0 +1 @@ +module.exports = require('./placeholder'); diff --git a/node_modules/lodash/fp/_baseConvert.js b/node_modules/lodash/fp/_baseConvert.js new file mode 100644 index 0000000..9baf8e1 --- /dev/null +++ b/node_modules/lodash/fp/_baseConvert.js @@ -0,0 +1,569 @@ +var mapping = require('./_mapping'), + fallbackHolder = require('./placeholder'); + +/** Built-in value reference. */ +var push = Array.prototype.push; + +/** + * Creates a function, with an arity of `n`, that invokes `func` with the + * arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} n The arity of the new function. + * @returns {Function} Returns the new function. + */ +function baseArity(func, n) { + return n == 2 + ? function(a, b) { return func.apply(undefined, arguments); } + : function(a) { return func.apply(undefined, arguments); }; +} + +/** + * Creates a function that invokes `func`, with up to `n` arguments, ignoring + * any additional arguments. + * + * @private + * @param {Function} func The function to cap arguments for. + * @param {number} n The arity cap. + * @returns {Function} Returns the new function. + */ +function baseAry(func, n) { + return n == 2 + ? function(a, b) { return func(a, b); } + : function(a) { return func(a); }; +} + +/** + * Creates a clone of `array`. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the cloned array. + */ +function cloneArray(array) { + var length = array ? array.length : 0, + result = Array(length); + + while (length--) { + result[length] = array[length]; + } + return result; +} + +/** + * Creates a function that clones a given object using the assignment `func`. + * + * @private + * @param {Function} func The assignment function. + * @returns {Function} Returns the new cloner function. + */ +function createCloner(func) { + return function(object) { + return func({}, object); + }; +} + +/** + * A specialized version of `_.spread` which flattens the spread array into + * the arguments of the invoked `func`. + * + * @private + * @param {Function} func The function to spread arguments over. + * @param {number} start The start position of the spread. + * @returns {Function} Returns the new function. + */ +function flatSpread(func, start) { + return function() { + var length = arguments.length, + lastIndex = length - 1, + args = Array(length); + + while (length--) { + args[length] = arguments[length]; + } + var array = args[start], + otherArgs = args.slice(0, start); + + if (array) { + push.apply(otherArgs, array); + } + if (start != lastIndex) { + push.apply(otherArgs, args.slice(start + 1)); + } + return func.apply(this, otherArgs); + }; +} + +/** + * Creates a function that wraps `func` and uses `cloner` to clone the first + * argument it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} cloner The function to clone arguments. + * @returns {Function} Returns the new immutable function. + */ +function wrapImmutable(func, cloner) { + return function() { + var length = arguments.length; + if (!length) { + return; + } + var args = Array(length); + while (length--) { + args[length] = arguments[length]; + } + var result = args[0] = cloner.apply(undefined, args); + func.apply(undefined, args); + return result; + }; +} + +/** + * The base implementation of `convert` which accepts a `util` object of methods + * required to perform conversions. + * + * @param {Object} util The util object. + * @param {string} name The name of the function to convert. + * @param {Function} func The function to convert. + * @param {Object} [options] The options object. + * @param {boolean} [options.cap=true] Specify capping iteratee arguments. + * @param {boolean} [options.curry=true] Specify currying. + * @param {boolean} [options.fixed=true] Specify fixed arity. + * @param {boolean} [options.immutable=true] Specify immutable operations. + * @param {boolean} [options.rearg=true] Specify rearranging arguments. + * @returns {Function|Object} Returns the converted function or object. + */ +function baseConvert(util, name, func, options) { + var isLib = typeof name == 'function', + isObj = name === Object(name); + + if (isObj) { + options = func; + func = name; + name = undefined; + } + if (func == null) { + throw new TypeError; + } + options || (options = {}); + + var config = { + 'cap': 'cap' in options ? options.cap : true, + 'curry': 'curry' in options ? options.curry : true, + 'fixed': 'fixed' in options ? options.fixed : true, + 'immutable': 'immutable' in options ? options.immutable : true, + 'rearg': 'rearg' in options ? options.rearg : true + }; + + var defaultHolder = isLib ? func : fallbackHolder, + forceCurry = ('curry' in options) && options.curry, + forceFixed = ('fixed' in options) && options.fixed, + forceRearg = ('rearg' in options) && options.rearg, + pristine = isLib ? func.runInContext() : undefined; + + var helpers = isLib ? func : { + 'ary': util.ary, + 'assign': util.assign, + 'clone': util.clone, + 'curry': util.curry, + 'forEach': util.forEach, + 'isArray': util.isArray, + 'isError': util.isError, + 'isFunction': util.isFunction, + 'isWeakMap': util.isWeakMap, + 'iteratee': util.iteratee, + 'keys': util.keys, + 'rearg': util.rearg, + 'toInteger': util.toInteger, + 'toPath': util.toPath + }; + + var ary = helpers.ary, + assign = helpers.assign, + clone = helpers.clone, + curry = helpers.curry, + each = helpers.forEach, + isArray = helpers.isArray, + isError = helpers.isError, + isFunction = helpers.isFunction, + isWeakMap = helpers.isWeakMap, + keys = helpers.keys, + rearg = helpers.rearg, + toInteger = helpers.toInteger, + toPath = helpers.toPath; + + var aryMethodKeys = keys(mapping.aryMethod); + + var wrappers = { + 'castArray': function(castArray) { + return function() { + var value = arguments[0]; + return isArray(value) + ? castArray(cloneArray(value)) + : castArray.apply(undefined, arguments); + }; + }, + 'iteratee': function(iteratee) { + return function() { + var func = arguments[0], + arity = arguments[1], + result = iteratee(func, arity), + length = result.length; + + if (config.cap && typeof arity == 'number') { + arity = arity > 2 ? (arity - 2) : 1; + return (length && length <= arity) ? result : baseAry(result, arity); + } + return result; + }; + }, + 'mixin': function(mixin) { + return function(source) { + var func = this; + if (!isFunction(func)) { + return mixin(func, Object(source)); + } + var pairs = []; + each(keys(source), function(key) { + if (isFunction(source[key])) { + pairs.push([key, func.prototype[key]]); + } + }); + + mixin(func, Object(source)); + + each(pairs, function(pair) { + var value = pair[1]; + if (isFunction(value)) { + func.prototype[pair[0]] = value; + } else { + delete func.prototype[pair[0]]; + } + }); + return func; + }; + }, + 'nthArg': function(nthArg) { + return function(n) { + var arity = n < 0 ? 1 : (toInteger(n) + 1); + return curry(nthArg(n), arity); + }; + }, + 'rearg': function(rearg) { + return function(func, indexes) { + var arity = indexes ? indexes.length : 0; + return curry(rearg(func, indexes), arity); + }; + }, + 'runInContext': function(runInContext) { + return function(context) { + return baseConvert(util, runInContext(context), options); + }; + } + }; + + /*--------------------------------------------------------------------------*/ + + /** + * Casts `func` to a function with an arity capped iteratee if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @returns {Function} Returns the cast function. + */ + function castCap(name, func) { + if (config.cap) { + var indexes = mapping.iterateeRearg[name]; + if (indexes) { + return iterateeRearg(func, indexes); + } + var n = !isLib && mapping.iterateeAry[name]; + if (n) { + return iterateeAry(func, n); + } + } + return func; + } + + /** + * Casts `func` to a curried function if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @param {number} n The arity of `func`. + * @returns {Function} Returns the cast function. + */ + function castCurry(name, func, n) { + return (forceCurry || (config.curry && n > 1)) + ? curry(func, n) + : func; + } + + /** + * Casts `func` to a fixed arity function if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @param {number} n The arity cap. + * @returns {Function} Returns the cast function. + */ + function castFixed(name, func, n) { + if (config.fixed && (forceFixed || !mapping.skipFixed[name])) { + var data = mapping.methodSpread[name], + start = data && data.start; + + return start === undefined ? ary(func, n) : flatSpread(func, start); + } + return func; + } + + /** + * Casts `func` to an rearged function if needed. + * + * @private + * @param {string} name The name of the function to inspect. + * @param {Function} func The function to inspect. + * @param {number} n The arity of `func`. + * @returns {Function} Returns the cast function. + */ + function castRearg(name, func, n) { + return (config.rearg && n > 1 && (forceRearg || !mapping.skipRearg[name])) + ? rearg(func, mapping.methodRearg[name] || mapping.aryRearg[n]) + : func; + } + + /** + * Creates a clone of `object` by `path`. + * + * @private + * @param {Object} object The object to clone. + * @param {Array|string} path The path to clone by. + * @returns {Object} Returns the cloned object. + */ + function cloneByPath(object, path) { + path = toPath(path); + + var index = -1, + length = path.length, + lastIndex = length - 1, + result = clone(Object(object)), + nested = result; + + while (nested != null && ++index < length) { + var key = path[index], + value = nested[key]; + + if (value != null && + !(isFunction(value) || isError(value) || isWeakMap(value))) { + nested[key] = clone(index == lastIndex ? value : Object(value)); + } + nested = nested[key]; + } + return result; + } + + /** + * Converts `lodash` to an immutable auto-curried iteratee-first data-last + * version with conversion `options` applied. + * + * @param {Object} [options] The options object. See `baseConvert` for more details. + * @returns {Function} Returns the converted `lodash`. + */ + function convertLib(options) { + return _.runInContext.convert(options)(undefined); + } + + /** + * Create a converter function for `func` of `name`. + * + * @param {string} name The name of the function to convert. + * @param {Function} func The function to convert. + * @returns {Function} Returns the new converter function. + */ + function createConverter(name, func) { + var realName = mapping.aliasToReal[name] || name, + methodName = mapping.remap[realName] || realName, + oldOptions = options; + + return function(options) { + var newUtil = isLib ? pristine : helpers, + newFunc = isLib ? pristine[methodName] : func, + newOptions = assign(assign({}, oldOptions), options); + + return baseConvert(newUtil, realName, newFunc, newOptions); + }; + } + + /** + * Creates a function that wraps `func` to invoke its iteratee, with up to `n` + * arguments, ignoring any additional arguments. + * + * @private + * @param {Function} func The function to cap iteratee arguments for. + * @param {number} n The arity cap. + * @returns {Function} Returns the new function. + */ + function iterateeAry(func, n) { + return overArg(func, function(func) { + return typeof func == 'function' ? baseAry(func, n) : func; + }); + } + + /** + * Creates a function that wraps `func` to invoke its iteratee with arguments + * arranged according to the specified `indexes` where the argument value at + * the first index is provided as the first argument, the argument value at + * the second index is provided as the second argument, and so on. + * + * @private + * @param {Function} func The function to rearrange iteratee arguments for. + * @param {number[]} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + */ + function iterateeRearg(func, indexes) { + return overArg(func, function(func) { + var n = indexes.length; + return baseArity(rearg(baseAry(func, n), indexes), n); + }); + } + + /** + * Creates a function that invokes `func` with its first 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() { + var length = arguments.length; + if (!length) { + return func(); + } + var args = Array(length); + while (length--) { + args[length] = arguments[length]; + } + var index = config.rearg ? 0 : (length - 1); + args[index] = transform(args[index]); + return func.apply(undefined, args); + }; + } + + /** + * Creates a function that wraps `func` and applys the conversions + * rules by `name`. + * + * @private + * @param {string} name The name of the function to wrap. + * @param {Function} func The function to wrap. + * @returns {Function} Returns the converted function. + */ + function wrap(name, func, placeholder) { + var result, + realName = mapping.aliasToReal[name] || name, + wrapped = func, + wrapper = wrappers[realName]; + + if (wrapper) { + wrapped = wrapper(func); + } + else if (config.immutable) { + if (mapping.mutate.array[realName]) { + wrapped = wrapImmutable(func, cloneArray); + } + else if (mapping.mutate.object[realName]) { + wrapped = wrapImmutable(func, createCloner(func)); + } + else if (mapping.mutate.set[realName]) { + wrapped = wrapImmutable(func, cloneByPath); + } + } + each(aryMethodKeys, function(aryKey) { + each(mapping.aryMethod[aryKey], function(otherName) { + if (realName == otherName) { + var data = mapping.methodSpread[realName], + afterRearg = data && data.afterRearg; + + result = afterRearg + ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey) + : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey); + + result = castCap(realName, result); + result = castCurry(realName, result, aryKey); + return false; + } + }); + return !result; + }); + + result || (result = wrapped); + if (result == func) { + result = forceCurry ? curry(result, 1) : function() { + return func.apply(this, arguments); + }; + } + result.convert = createConverter(realName, func); + result.placeholder = func.placeholder = placeholder; + + return result; + } + + /*--------------------------------------------------------------------------*/ + + if (!isObj) { + return wrap(name, func, defaultHolder); + } + var _ = func; + + // Convert methods by ary cap. + var pairs = []; + each(aryMethodKeys, function(aryKey) { + each(mapping.aryMethod[aryKey], function(key) { + var func = _[mapping.remap[key] || key]; + if (func) { + pairs.push([key, wrap(key, func, _)]); + } + }); + }); + + // Convert remaining methods. + each(keys(_), function(key) { + var func = _[key]; + if (typeof func == 'function') { + var length = pairs.length; + while (length--) { + if (pairs[length][0] == key) { + return; + } + } + func.convert = createConverter(key, func); + pairs.push([key, func]); + } + }); + + // Assign to `_` leaving `_.prototype` unchanged to allow chaining. + each(pairs, function(pair) { + _[pair[0]] = pair[1]; + }); + + _.convert = convertLib; + _.placeholder = _; + + // Assign aliases. + each(keys(_), function(key) { + each(mapping.realToAlias[key] || [], function(alias) { + _[alias] = _[key]; + }); + }); + + return _; +} + +module.exports = baseConvert; diff --git a/node_modules/lodash/fp/_convertBrowser.js b/node_modules/lodash/fp/_convertBrowser.js new file mode 100644 index 0000000..bde030d --- /dev/null +++ b/node_modules/lodash/fp/_convertBrowser.js @@ -0,0 +1,18 @@ +var baseConvert = require('./_baseConvert'); + +/** + * Converts `lodash` to an immutable auto-curried iteratee-first data-last + * version with conversion `options` applied. + * + * @param {Function} lodash The lodash function to convert. + * @param {Object} [options] The options object. See `baseConvert` for more details. + * @returns {Function} Returns the converted `lodash`. + */ +function browserConvert(lodash, options) { + return baseConvert(lodash, lodash, options); +} + +if (typeof _ == 'function' && typeof _.runInContext == 'function') { + _ = browserConvert(_.runInContext()); +} +module.exports = browserConvert; diff --git a/node_modules/lodash/fp/_falseOptions.js b/node_modules/lodash/fp/_falseOptions.js new file mode 100644 index 0000000..773235e --- /dev/null +++ b/node_modules/lodash/fp/_falseOptions.js @@ -0,0 +1,7 @@ +module.exports = { + 'cap': false, + 'curry': false, + 'fixed': false, + 'immutable': false, + 'rearg': false +}; diff --git a/node_modules/lodash/fp/_mapping.js b/node_modules/lodash/fp/_mapping.js new file mode 100644 index 0000000..a642ec0 --- /dev/null +++ b/node_modules/lodash/fp/_mapping.js @@ -0,0 +1,358 @@ +/** Used to map aliases to their real names. */ +exports.aliasToReal = { + + // Lodash aliases. + 'each': 'forEach', + 'eachRight': 'forEachRight', + 'entries': 'toPairs', + 'entriesIn': 'toPairsIn', + 'extend': 'assignIn', + 'extendAll': 'assignInAll', + 'extendAllWith': 'assignInAllWith', + 'extendWith': 'assignInWith', + 'first': 'head', + + // Methods that are curried variants of others. + 'conforms': 'conformsTo', + 'matches': 'isMatch', + 'property': 'get', + + // Ramda aliases. + '__': 'placeholder', + 'F': 'stubFalse', + 'T': 'stubTrue', + 'all': 'every', + 'allPass': 'overEvery', + 'always': 'constant', + 'any': 'some', + 'anyPass': 'overSome', + 'apply': 'spread', + 'assoc': 'set', + 'assocPath': 'set', + 'complement': 'negate', + 'compose': 'flowRight', + 'contains': 'includes', + 'dissoc': 'unset', + 'dissocPath': 'unset', + 'dropLast': 'dropRight', + 'dropLastWhile': 'dropRightWhile', + 'equals': 'isEqual', + 'identical': 'eq', + 'indexBy': 'keyBy', + 'init': 'initial', + 'invertObj': 'invert', + 'juxt': 'over', + 'omitAll': 'omit', + 'nAry': 'ary', + 'path': 'get', + 'pathEq': 'matchesProperty', + 'pathOr': 'getOr', + 'paths': 'at', + 'pickAll': 'pick', + 'pipe': 'flow', + 'pluck': 'map', + 'prop': 'get', + 'propEq': 'matchesProperty', + 'propOr': 'getOr', + 'props': 'at', + 'symmetricDifference': 'xor', + 'symmetricDifferenceBy': 'xorBy', + 'symmetricDifferenceWith': 'xorWith', + 'takeLast': 'takeRight', + 'takeLastWhile': 'takeRightWhile', + 'unapply': 'rest', + 'unnest': 'flatten', + 'useWith': 'overArgs', + 'where': 'conformsTo', + 'whereEq': 'isMatch', + 'zipObj': 'zipObject' +}; + +/** Used to map ary to method names. */ +exports.aryMethod = { + '1': [ + 'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create', + 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow', + 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll', + 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse', + 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart', + 'uniqueId', 'words', 'zipAll' + ], + '2': [ + 'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith', + 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith', + 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN', + 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference', + 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq', + 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', + 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach', + 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get', + 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection', + 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy', + 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty', + 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit', + 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial', + 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll', + 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove', + 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex', + 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy', + 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight', + 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars', + 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith', + 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject', + 'zipObjectDeep' + ], + '3': [ + 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith', + 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr', + 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith', + 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth', + 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd', + 'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight', + 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy', + 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy', + 'xorWith', 'zipWith' + ], + '4': [ + 'fill', 'setWith', 'updateWith' + ] +}; + +/** Used to map ary to rearg configs. */ +exports.aryRearg = { + '2': [1, 0], + '3': [2, 0, 1], + '4': [3, 2, 0, 1] +}; + +/** Used to map method names to their iteratee ary. */ +exports.iterateeAry = { + 'dropRightWhile': 1, + 'dropWhile': 1, + 'every': 1, + 'filter': 1, + 'find': 1, + 'findFrom': 1, + 'findIndex': 1, + 'findIndexFrom': 1, + 'findKey': 1, + 'findLast': 1, + 'findLastFrom': 1, + 'findLastIndex': 1, + 'findLastIndexFrom': 1, + 'findLastKey': 1, + 'flatMap': 1, + 'flatMapDeep': 1, + 'flatMapDepth': 1, + 'forEach': 1, + 'forEachRight': 1, + 'forIn': 1, + 'forInRight': 1, + 'forOwn': 1, + 'forOwnRight': 1, + 'map': 1, + 'mapKeys': 1, + 'mapValues': 1, + 'partition': 1, + 'reduce': 2, + 'reduceRight': 2, + 'reject': 1, + 'remove': 1, + 'some': 1, + 'takeRightWhile': 1, + 'takeWhile': 1, + 'times': 1, + 'transform': 2 +}; + +/** Used to map method names to iteratee rearg configs. */ +exports.iterateeRearg = { + 'mapKeys': [1], + 'reduceRight': [1, 0] +}; + +/** Used to map method names to rearg configs. */ +exports.methodRearg = { + 'assignInAllWith': [1, 0], + 'assignInWith': [1, 2, 0], + 'assignAllWith': [1, 0], + 'assignWith': [1, 2, 0], + 'differenceBy': [1, 2, 0], + 'differenceWith': [1, 2, 0], + 'getOr': [2, 1, 0], + 'intersectionBy': [1, 2, 0], + 'intersectionWith': [1, 2, 0], + 'isEqualWith': [1, 2, 0], + 'isMatchWith': [2, 1, 0], + 'mergeAllWith': [1, 0], + 'mergeWith': [1, 2, 0], + 'padChars': [2, 1, 0], + 'padCharsEnd': [2, 1, 0], + 'padCharsStart': [2, 1, 0], + 'pullAllBy': [2, 1, 0], + 'pullAllWith': [2, 1, 0], + 'rangeStep': [1, 2, 0], + 'rangeStepRight': [1, 2, 0], + 'setWith': [3, 1, 2, 0], + 'sortedIndexBy': [2, 1, 0], + 'sortedLastIndexBy': [2, 1, 0], + 'unionBy': [1, 2, 0], + 'unionWith': [1, 2, 0], + 'updateWith': [3, 1, 2, 0], + 'xorBy': [1, 2, 0], + 'xorWith': [1, 2, 0], + 'zipWith': [1, 2, 0] +}; + +/** Used to map method names to spread configs. */ +exports.methodSpread = { + 'assignAll': { 'start': 0 }, + 'assignAllWith': { 'start': 0 }, + 'assignInAll': { 'start': 0 }, + 'assignInAllWith': { 'start': 0 }, + 'defaultsAll': { 'start': 0 }, + 'defaultsDeepAll': { 'start': 0 }, + 'invokeArgs': { 'start': 2 }, + 'invokeArgsMap': { 'start': 2 }, + 'mergeAll': { 'start': 0 }, + 'mergeAllWith': { 'start': 0 }, + 'partial': { 'start': 1 }, + 'partialRight': { 'start': 1 }, + 'without': { 'start': 1 }, + 'zipAll': { 'start': 0 } +}; + +/** Used to identify methods which mutate arrays or objects. */ +exports.mutate = { + 'array': { + 'fill': true, + 'pull': true, + 'pullAll': true, + 'pullAllBy': true, + 'pullAllWith': true, + 'pullAt': true, + 'remove': true, + 'reverse': true + }, + 'object': { + 'assign': true, + 'assignAll': true, + 'assignAllWith': true, + 'assignIn': true, + 'assignInAll': true, + 'assignInAllWith': true, + 'assignInWith': true, + 'assignWith': true, + 'defaults': true, + 'defaultsAll': true, + 'defaultsDeep': true, + 'defaultsDeepAll': true, + 'merge': true, + 'mergeAll': true, + 'mergeAllWith': true, + 'mergeWith': true, + }, + 'set': { + 'set': true, + 'setWith': true, + 'unset': true, + 'update': true, + 'updateWith': true + } +}; + +/** Used to map real names to their aliases. */ +exports.realToAlias = (function() { + var hasOwnProperty = Object.prototype.hasOwnProperty, + object = exports.aliasToReal, + result = {}; + + for (var key in object) { + var value = object[key]; + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + } + return result; +}()); + +/** Used to map method names to other names. */ +exports.remap = { + 'assignAll': 'assign', + 'assignAllWith': 'assignWith', + 'assignInAll': 'assignIn', + 'assignInAllWith': 'assignInWith', + 'curryN': 'curry', + 'curryRightN': 'curryRight', + 'defaultsAll': 'defaults', + 'defaultsDeepAll': 'defaultsDeep', + 'findFrom': 'find', + 'findIndexFrom': 'findIndex', + 'findLastFrom': 'findLast', + 'findLastIndexFrom': 'findLastIndex', + 'getOr': 'get', + 'includesFrom': 'includes', + 'indexOfFrom': 'indexOf', + 'invokeArgs': 'invoke', + 'invokeArgsMap': 'invokeMap', + 'lastIndexOfFrom': 'lastIndexOf', + 'mergeAll': 'merge', + 'mergeAllWith': 'mergeWith', + 'padChars': 'pad', + 'padCharsEnd': 'padEnd', + 'padCharsStart': 'padStart', + 'propertyOf': 'get', + 'rangeStep': 'range', + 'rangeStepRight': 'rangeRight', + 'restFrom': 'rest', + 'spreadFrom': 'spread', + 'trimChars': 'trim', + 'trimCharsEnd': 'trimEnd', + 'trimCharsStart': 'trimStart', + 'zipAll': 'zip' +}; + +/** Used to track methods that skip fixing their arity. */ +exports.skipFixed = { + 'castArray': true, + 'flow': true, + 'flowRight': true, + 'iteratee': true, + 'mixin': true, + 'rearg': true, + 'runInContext': true +}; + +/** Used to track methods that skip rearranging arguments. */ +exports.skipRearg = { + 'add': true, + 'assign': true, + 'assignIn': true, + 'bind': true, + 'bindKey': true, + 'concat': true, + 'difference': true, + 'divide': true, + 'eq': true, + 'gt': true, + 'gte': true, + 'isEqual': true, + 'lt': true, + 'lte': true, + 'matchesProperty': true, + 'merge': true, + 'multiply': true, + 'overArgs': true, + 'partial': true, + 'partialRight': true, + 'propertyOf': true, + 'random': true, + 'range': true, + 'rangeRight': true, + 'subtract': true, + 'zip': true, + 'zipObject': true, + 'zipObjectDeep': true +}; diff --git a/node_modules/lodash/fp/_util.js b/node_modules/lodash/fp/_util.js new file mode 100644 index 0000000..1dbf36f --- /dev/null +++ b/node_modules/lodash/fp/_util.js @@ -0,0 +1,16 @@ +module.exports = { + 'ary': require('../ary'), + 'assign': require('../_baseAssign'), + 'clone': require('../clone'), + 'curry': require('../curry'), + 'forEach': require('../_arrayEach'), + 'isArray': require('../isArray'), + 'isError': require('../isError'), + 'isFunction': require('../isFunction'), + 'isWeakMap': require('../isWeakMap'), + 'iteratee': require('../iteratee'), + 'keys': require('../_baseKeys'), + 'rearg': require('../rearg'), + 'toInteger': require('../toInteger'), + 'toPath': require('../toPath') +}; diff --git a/node_modules/lodash/fp/add.js b/node_modules/lodash/fp/add.js new file mode 100644 index 0000000..816eeec --- /dev/null +++ b/node_modules/lodash/fp/add.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('add', require('../add')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/after.js b/node_modules/lodash/fp/after.js new file mode 100644 index 0000000..21a0167 --- /dev/null +++ b/node_modules/lodash/fp/after.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('after', require('../after')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/all.js b/node_modules/lodash/fp/all.js new file mode 100644 index 0000000..d0839f7 --- /dev/null +++ b/node_modules/lodash/fp/all.js @@ -0,0 +1 @@ +module.exports = require('./every'); diff --git a/node_modules/lodash/fp/allPass.js b/node_modules/lodash/fp/allPass.js new file mode 100644 index 0000000..79b73ef --- /dev/null +++ b/node_modules/lodash/fp/allPass.js @@ -0,0 +1 @@ +module.exports = require('./overEvery'); diff --git a/node_modules/lodash/fp/always.js b/node_modules/lodash/fp/always.js new file mode 100644 index 0000000..9887703 --- /dev/null +++ b/node_modules/lodash/fp/always.js @@ -0,0 +1 @@ +module.exports = require('./constant'); diff --git a/node_modules/lodash/fp/any.js b/node_modules/lodash/fp/any.js new file mode 100644 index 0000000..900ac25 --- /dev/null +++ b/node_modules/lodash/fp/any.js @@ -0,0 +1 @@ +module.exports = require('./some'); diff --git a/node_modules/lodash/fp/anyPass.js b/node_modules/lodash/fp/anyPass.js new file mode 100644 index 0000000..2774ab3 --- /dev/null +++ b/node_modules/lodash/fp/anyPass.js @@ -0,0 +1 @@ +module.exports = require('./overSome'); diff --git a/node_modules/lodash/fp/apply.js b/node_modules/lodash/fp/apply.js new file mode 100644 index 0000000..2b75712 --- /dev/null +++ b/node_modules/lodash/fp/apply.js @@ -0,0 +1 @@ +module.exports = require('./spread'); diff --git a/node_modules/lodash/fp/array.js b/node_modules/lodash/fp/array.js new file mode 100644 index 0000000..fe939c2 --- /dev/null +++ b/node_modules/lodash/fp/array.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../array')); diff --git a/node_modules/lodash/fp/ary.js b/node_modules/lodash/fp/ary.js new file mode 100644 index 0000000..8edf187 --- /dev/null +++ b/node_modules/lodash/fp/ary.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('ary', require('../ary')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assign.js b/node_modules/lodash/fp/assign.js new file mode 100644 index 0000000..23f47af --- /dev/null +++ b/node_modules/lodash/fp/assign.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assign', require('../assign')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assignAll.js b/node_modules/lodash/fp/assignAll.js new file mode 100644 index 0000000..b1d36c7 --- /dev/null +++ b/node_modules/lodash/fp/assignAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignAll', require('../assign')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assignAllWith.js b/node_modules/lodash/fp/assignAllWith.js new file mode 100644 index 0000000..21e836e --- /dev/null +++ b/node_modules/lodash/fp/assignAllWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignAllWith', require('../assignWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assignIn.js b/node_modules/lodash/fp/assignIn.js new file mode 100644 index 0000000..6e7c65f --- /dev/null +++ b/node_modules/lodash/fp/assignIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignIn', require('../assignIn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assignInAll.js b/node_modules/lodash/fp/assignInAll.js new file mode 100644 index 0000000..7ba75db --- /dev/null +++ b/node_modules/lodash/fp/assignInAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignInAll', require('../assignIn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assignInAllWith.js b/node_modules/lodash/fp/assignInAllWith.js new file mode 100644 index 0000000..e766903 --- /dev/null +++ b/node_modules/lodash/fp/assignInAllWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignInAllWith', require('../assignInWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assignInWith.js b/node_modules/lodash/fp/assignInWith.js new file mode 100644 index 0000000..acb5923 --- /dev/null +++ b/node_modules/lodash/fp/assignInWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignInWith', require('../assignInWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assignWith.js b/node_modules/lodash/fp/assignWith.js new file mode 100644 index 0000000..eb92521 --- /dev/null +++ b/node_modules/lodash/fp/assignWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('assignWith', require('../assignWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/assoc.js b/node_modules/lodash/fp/assoc.js new file mode 100644 index 0000000..7648820 --- /dev/null +++ b/node_modules/lodash/fp/assoc.js @@ -0,0 +1 @@ +module.exports = require('./set'); diff --git a/node_modules/lodash/fp/assocPath.js b/node_modules/lodash/fp/assocPath.js new file mode 100644 index 0000000..7648820 --- /dev/null +++ b/node_modules/lodash/fp/assocPath.js @@ -0,0 +1 @@ +module.exports = require('./set'); diff --git a/node_modules/lodash/fp/at.js b/node_modules/lodash/fp/at.js new file mode 100644 index 0000000..cc39d25 --- /dev/null +++ b/node_modules/lodash/fp/at.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('at', require('../at')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/attempt.js b/node_modules/lodash/fp/attempt.js new file mode 100644 index 0000000..26ca42e --- /dev/null +++ b/node_modules/lodash/fp/attempt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('attempt', require('../attempt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/before.js b/node_modules/lodash/fp/before.js new file mode 100644 index 0000000..7a2de65 --- /dev/null +++ b/node_modules/lodash/fp/before.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('before', require('../before')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/bind.js b/node_modules/lodash/fp/bind.js new file mode 100644 index 0000000..5cbe4f3 --- /dev/null +++ b/node_modules/lodash/fp/bind.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('bind', require('../bind')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/bindAll.js b/node_modules/lodash/fp/bindAll.js new file mode 100644 index 0000000..6b4a4a0 --- /dev/null +++ b/node_modules/lodash/fp/bindAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('bindAll', require('../bindAll')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/bindKey.js b/node_modules/lodash/fp/bindKey.js new file mode 100644 index 0000000..6a46c6b --- /dev/null +++ b/node_modules/lodash/fp/bindKey.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('bindKey', require('../bindKey')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/camelCase.js b/node_modules/lodash/fp/camelCase.js new file mode 100644 index 0000000..87b77b4 --- /dev/null +++ b/node_modules/lodash/fp/camelCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('camelCase', require('../camelCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/capitalize.js b/node_modules/lodash/fp/capitalize.js new file mode 100644 index 0000000..cac74e1 --- /dev/null +++ b/node_modules/lodash/fp/capitalize.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('capitalize', require('../capitalize'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/castArray.js b/node_modules/lodash/fp/castArray.js new file mode 100644 index 0000000..8681c09 --- /dev/null +++ b/node_modules/lodash/fp/castArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('castArray', require('../castArray')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/ceil.js b/node_modules/lodash/fp/ceil.js new file mode 100644 index 0000000..f416b72 --- /dev/null +++ b/node_modules/lodash/fp/ceil.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('ceil', require('../ceil')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/chain.js b/node_modules/lodash/fp/chain.js new file mode 100644 index 0000000..604fe39 --- /dev/null +++ b/node_modules/lodash/fp/chain.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('chain', require('../chain'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/chunk.js b/node_modules/lodash/fp/chunk.js new file mode 100644 index 0000000..871ab08 --- /dev/null +++ b/node_modules/lodash/fp/chunk.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('chunk', require('../chunk')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/clamp.js b/node_modules/lodash/fp/clamp.js new file mode 100644 index 0000000..3b06c01 --- /dev/null +++ b/node_modules/lodash/fp/clamp.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('clamp', require('../clamp')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/clone.js b/node_modules/lodash/fp/clone.js new file mode 100644 index 0000000..cadb59c --- /dev/null +++ b/node_modules/lodash/fp/clone.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('clone', require('../clone'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/cloneDeep.js b/node_modules/lodash/fp/cloneDeep.js new file mode 100644 index 0000000..a6107aa --- /dev/null +++ b/node_modules/lodash/fp/cloneDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('cloneDeep', require('../cloneDeep'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/cloneDeepWith.js b/node_modules/lodash/fp/cloneDeepWith.js new file mode 100644 index 0000000..6f01e44 --- /dev/null +++ b/node_modules/lodash/fp/cloneDeepWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('cloneDeepWith', require('../cloneDeepWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/cloneWith.js b/node_modules/lodash/fp/cloneWith.js new file mode 100644 index 0000000..aa88578 --- /dev/null +++ b/node_modules/lodash/fp/cloneWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('cloneWith', require('../cloneWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/collection.js b/node_modules/lodash/fp/collection.js new file mode 100644 index 0000000..fc8b328 --- /dev/null +++ b/node_modules/lodash/fp/collection.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../collection')); diff --git a/node_modules/lodash/fp/commit.js b/node_modules/lodash/fp/commit.js new file mode 100644 index 0000000..130a894 --- /dev/null +++ b/node_modules/lodash/fp/commit.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('commit', require('../commit'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/compact.js b/node_modules/lodash/fp/compact.js new file mode 100644 index 0000000..ce8f7a1 --- /dev/null +++ b/node_modules/lodash/fp/compact.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('compact', require('../compact'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/complement.js b/node_modules/lodash/fp/complement.js new file mode 100644 index 0000000..93eb462 --- /dev/null +++ b/node_modules/lodash/fp/complement.js @@ -0,0 +1 @@ +module.exports = require('./negate'); diff --git a/node_modules/lodash/fp/compose.js b/node_modules/lodash/fp/compose.js new file mode 100644 index 0000000..1954e94 --- /dev/null +++ b/node_modules/lodash/fp/compose.js @@ -0,0 +1 @@ +module.exports = require('./flowRight'); diff --git a/node_modules/lodash/fp/concat.js b/node_modules/lodash/fp/concat.js new file mode 100644 index 0000000..e59346a --- /dev/null +++ b/node_modules/lodash/fp/concat.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('concat', require('../concat')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/cond.js b/node_modules/lodash/fp/cond.js new file mode 100644 index 0000000..6a0120e --- /dev/null +++ b/node_modules/lodash/fp/cond.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('cond', require('../cond'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/conforms.js b/node_modules/lodash/fp/conforms.js new file mode 100644 index 0000000..3247f64 --- /dev/null +++ b/node_modules/lodash/fp/conforms.js @@ -0,0 +1 @@ +module.exports = require('./conformsTo'); diff --git a/node_modules/lodash/fp/conformsTo.js b/node_modules/lodash/fp/conformsTo.js new file mode 100644 index 0000000..aa7f41e --- /dev/null +++ b/node_modules/lodash/fp/conformsTo.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('conformsTo', require('../conformsTo')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/constant.js b/node_modules/lodash/fp/constant.js new file mode 100644 index 0000000..9e406fc --- /dev/null +++ b/node_modules/lodash/fp/constant.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('constant', require('../constant'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/contains.js b/node_modules/lodash/fp/contains.js new file mode 100644 index 0000000..594722a --- /dev/null +++ b/node_modules/lodash/fp/contains.js @@ -0,0 +1 @@ +module.exports = require('./includes'); diff --git a/node_modules/lodash/fp/convert.js b/node_modules/lodash/fp/convert.js new file mode 100644 index 0000000..4795dc4 --- /dev/null +++ b/node_modules/lodash/fp/convert.js @@ -0,0 +1,18 @@ +var baseConvert = require('./_baseConvert'), + util = require('./_util'); + +/** + * Converts `func` of `name` to an immutable auto-curried iteratee-first data-last + * version with conversion `options` applied. If `name` is an object its methods + * will be converted. + * + * @param {string} name The name of the function to wrap. + * @param {Function} [func] The function to wrap. + * @param {Object} [options] The options object. See `baseConvert` for more details. + * @returns {Function|Object} Returns the converted function or object. + */ +function convert(name, func, options) { + return baseConvert(util, name, func, options); +} + +module.exports = convert; diff --git a/node_modules/lodash/fp/countBy.js b/node_modules/lodash/fp/countBy.js new file mode 100644 index 0000000..dfa4643 --- /dev/null +++ b/node_modules/lodash/fp/countBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('countBy', require('../countBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/create.js b/node_modules/lodash/fp/create.js new file mode 100644 index 0000000..752025f --- /dev/null +++ b/node_modules/lodash/fp/create.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('create', require('../create')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/curry.js b/node_modules/lodash/fp/curry.js new file mode 100644 index 0000000..b0b4168 --- /dev/null +++ b/node_modules/lodash/fp/curry.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('curry', require('../curry')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/curryN.js b/node_modules/lodash/fp/curryN.js new file mode 100644 index 0000000..2ae7d00 --- /dev/null +++ b/node_modules/lodash/fp/curryN.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('curryN', require('../curry')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/curryRight.js b/node_modules/lodash/fp/curryRight.js new file mode 100644 index 0000000..cb619eb --- /dev/null +++ b/node_modules/lodash/fp/curryRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('curryRight', require('../curryRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/curryRightN.js b/node_modules/lodash/fp/curryRightN.js new file mode 100644 index 0000000..2495afc --- /dev/null +++ b/node_modules/lodash/fp/curryRightN.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('curryRightN', require('../curryRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/date.js b/node_modules/lodash/fp/date.js new file mode 100644 index 0000000..82cb952 --- /dev/null +++ b/node_modules/lodash/fp/date.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../date')); diff --git a/node_modules/lodash/fp/debounce.js b/node_modules/lodash/fp/debounce.js new file mode 100644 index 0000000..2612229 --- /dev/null +++ b/node_modules/lodash/fp/debounce.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('debounce', require('../debounce')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/deburr.js b/node_modules/lodash/fp/deburr.js new file mode 100644 index 0000000..96463ab --- /dev/null +++ b/node_modules/lodash/fp/deburr.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('deburr', require('../deburr'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/defaultTo.js b/node_modules/lodash/fp/defaultTo.js new file mode 100644 index 0000000..d6b52a4 --- /dev/null +++ b/node_modules/lodash/fp/defaultTo.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaultTo', require('../defaultTo')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/defaults.js b/node_modules/lodash/fp/defaults.js new file mode 100644 index 0000000..e1a8e6e --- /dev/null +++ b/node_modules/lodash/fp/defaults.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaults', require('../defaults')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/defaultsAll.js b/node_modules/lodash/fp/defaultsAll.js new file mode 100644 index 0000000..238fcc3 --- /dev/null +++ b/node_modules/lodash/fp/defaultsAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaultsAll', require('../defaults')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/defaultsDeep.js b/node_modules/lodash/fp/defaultsDeep.js new file mode 100644 index 0000000..1f172ff --- /dev/null +++ b/node_modules/lodash/fp/defaultsDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaultsDeep', require('../defaultsDeep')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/defaultsDeepAll.js b/node_modules/lodash/fp/defaultsDeepAll.js new file mode 100644 index 0000000..6835f2f --- /dev/null +++ b/node_modules/lodash/fp/defaultsDeepAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defaultsDeepAll', require('../defaultsDeep')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/defer.js b/node_modules/lodash/fp/defer.js new file mode 100644 index 0000000..ec7990f --- /dev/null +++ b/node_modules/lodash/fp/defer.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('defer', require('../defer'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/delay.js b/node_modules/lodash/fp/delay.js new file mode 100644 index 0000000..556dbd5 --- /dev/null +++ b/node_modules/lodash/fp/delay.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('delay', require('../delay')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/difference.js b/node_modules/lodash/fp/difference.js new file mode 100644 index 0000000..2d03765 --- /dev/null +++ b/node_modules/lodash/fp/difference.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('difference', require('../difference')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/differenceBy.js b/node_modules/lodash/fp/differenceBy.js new file mode 100644 index 0000000..2f91491 --- /dev/null +++ b/node_modules/lodash/fp/differenceBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('differenceBy', require('../differenceBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/differenceWith.js b/node_modules/lodash/fp/differenceWith.js new file mode 100644 index 0000000..bcf5ad2 --- /dev/null +++ b/node_modules/lodash/fp/differenceWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('differenceWith', require('../differenceWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/dissoc.js b/node_modules/lodash/fp/dissoc.js new file mode 100644 index 0000000..7ec7be1 --- /dev/null +++ b/node_modules/lodash/fp/dissoc.js @@ -0,0 +1 @@ +module.exports = require('./unset'); diff --git a/node_modules/lodash/fp/dissocPath.js b/node_modules/lodash/fp/dissocPath.js new file mode 100644 index 0000000..7ec7be1 --- /dev/null +++ b/node_modules/lodash/fp/dissocPath.js @@ -0,0 +1 @@ +module.exports = require('./unset'); diff --git a/node_modules/lodash/fp/divide.js b/node_modules/lodash/fp/divide.js new file mode 100644 index 0000000..82048c5 --- /dev/null +++ b/node_modules/lodash/fp/divide.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('divide', require('../divide')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/drop.js b/node_modules/lodash/fp/drop.js new file mode 100644 index 0000000..2fa9b4f --- /dev/null +++ b/node_modules/lodash/fp/drop.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('drop', require('../drop')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/dropLast.js b/node_modules/lodash/fp/dropLast.js new file mode 100644 index 0000000..174e525 --- /dev/null +++ b/node_modules/lodash/fp/dropLast.js @@ -0,0 +1 @@ +module.exports = require('./dropRight'); diff --git a/node_modules/lodash/fp/dropLastWhile.js b/node_modules/lodash/fp/dropLastWhile.js new file mode 100644 index 0000000..be2a9d2 --- /dev/null +++ b/node_modules/lodash/fp/dropLastWhile.js @@ -0,0 +1 @@ +module.exports = require('./dropRightWhile'); diff --git a/node_modules/lodash/fp/dropRight.js b/node_modules/lodash/fp/dropRight.js new file mode 100644 index 0000000..e98881f --- /dev/null +++ b/node_modules/lodash/fp/dropRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('dropRight', require('../dropRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/dropRightWhile.js b/node_modules/lodash/fp/dropRightWhile.js new file mode 100644 index 0000000..cacaa70 --- /dev/null +++ b/node_modules/lodash/fp/dropRightWhile.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('dropRightWhile', require('../dropRightWhile')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/dropWhile.js b/node_modules/lodash/fp/dropWhile.js new file mode 100644 index 0000000..285f864 --- /dev/null +++ b/node_modules/lodash/fp/dropWhile.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('dropWhile', require('../dropWhile')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/each.js b/node_modules/lodash/fp/each.js new file mode 100644 index 0000000..8800f42 --- /dev/null +++ b/node_modules/lodash/fp/each.js @@ -0,0 +1 @@ +module.exports = require('./forEach'); diff --git a/node_modules/lodash/fp/eachRight.js b/node_modules/lodash/fp/eachRight.js new file mode 100644 index 0000000..3252b2a --- /dev/null +++ b/node_modules/lodash/fp/eachRight.js @@ -0,0 +1 @@ +module.exports = require('./forEachRight'); diff --git a/node_modules/lodash/fp/endsWith.js b/node_modules/lodash/fp/endsWith.js new file mode 100644 index 0000000..17dc2a4 --- /dev/null +++ b/node_modules/lodash/fp/endsWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('endsWith', require('../endsWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/entries.js b/node_modules/lodash/fp/entries.js new file mode 100644 index 0000000..7a88df2 --- /dev/null +++ b/node_modules/lodash/fp/entries.js @@ -0,0 +1 @@ +module.exports = require('./toPairs'); diff --git a/node_modules/lodash/fp/entriesIn.js b/node_modules/lodash/fp/entriesIn.js new file mode 100644 index 0000000..f6c6331 --- /dev/null +++ b/node_modules/lodash/fp/entriesIn.js @@ -0,0 +1 @@ +module.exports = require('./toPairsIn'); diff --git a/node_modules/lodash/fp/eq.js b/node_modules/lodash/fp/eq.js new file mode 100644 index 0000000..9a3d21b --- /dev/null +++ b/node_modules/lodash/fp/eq.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('eq', require('../eq')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/equals.js b/node_modules/lodash/fp/equals.js new file mode 100644 index 0000000..e6a5ce0 --- /dev/null +++ b/node_modules/lodash/fp/equals.js @@ -0,0 +1 @@ +module.exports = require('./isEqual'); diff --git a/node_modules/lodash/fp/escape.js b/node_modules/lodash/fp/escape.js new file mode 100644 index 0000000..52c1fbb --- /dev/null +++ b/node_modules/lodash/fp/escape.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('escape', require('../escape'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/escapeRegExp.js b/node_modules/lodash/fp/escapeRegExp.js new file mode 100644 index 0000000..369b2ef --- /dev/null +++ b/node_modules/lodash/fp/escapeRegExp.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('escapeRegExp', require('../escapeRegExp'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/every.js b/node_modules/lodash/fp/every.js new file mode 100644 index 0000000..95c2776 --- /dev/null +++ b/node_modules/lodash/fp/every.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('every', require('../every')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/extend.js b/node_modules/lodash/fp/extend.js new file mode 100644 index 0000000..e00166c --- /dev/null +++ b/node_modules/lodash/fp/extend.js @@ -0,0 +1 @@ +module.exports = require('./assignIn'); diff --git a/node_modules/lodash/fp/extendAll.js b/node_modules/lodash/fp/extendAll.js new file mode 100644 index 0000000..cc55b64 --- /dev/null +++ b/node_modules/lodash/fp/extendAll.js @@ -0,0 +1 @@ +module.exports = require('./assignInAll'); diff --git a/node_modules/lodash/fp/extendAllWith.js b/node_modules/lodash/fp/extendAllWith.js new file mode 100644 index 0000000..6679d20 --- /dev/null +++ b/node_modules/lodash/fp/extendAllWith.js @@ -0,0 +1 @@ +module.exports = require('./assignInAllWith'); diff --git a/node_modules/lodash/fp/extendWith.js b/node_modules/lodash/fp/extendWith.js new file mode 100644 index 0000000..dbdcb3b --- /dev/null +++ b/node_modules/lodash/fp/extendWith.js @@ -0,0 +1 @@ +module.exports = require('./assignInWith'); diff --git a/node_modules/lodash/fp/fill.js b/node_modules/lodash/fp/fill.js new file mode 100644 index 0000000..b2d47e8 --- /dev/null +++ b/node_modules/lodash/fp/fill.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('fill', require('../fill')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/filter.js b/node_modules/lodash/fp/filter.js new file mode 100644 index 0000000..796d501 --- /dev/null +++ b/node_modules/lodash/fp/filter.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('filter', require('../filter')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/find.js b/node_modules/lodash/fp/find.js new file mode 100644 index 0000000..f805d33 --- /dev/null +++ b/node_modules/lodash/fp/find.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('find', require('../find')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findFrom.js b/node_modules/lodash/fp/findFrom.js new file mode 100644 index 0000000..da8275e --- /dev/null +++ b/node_modules/lodash/fp/findFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findFrom', require('../find')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findIndex.js b/node_modules/lodash/fp/findIndex.js new file mode 100644 index 0000000..8c15fd1 --- /dev/null +++ b/node_modules/lodash/fp/findIndex.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findIndex', require('../findIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findIndexFrom.js b/node_modules/lodash/fp/findIndexFrom.js new file mode 100644 index 0000000..32e98cb --- /dev/null +++ b/node_modules/lodash/fp/findIndexFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findIndexFrom', require('../findIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findKey.js b/node_modules/lodash/fp/findKey.js new file mode 100644 index 0000000..475bcfa --- /dev/null +++ b/node_modules/lodash/fp/findKey.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findKey', require('../findKey')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findLast.js b/node_modules/lodash/fp/findLast.js new file mode 100644 index 0000000..093fe94 --- /dev/null +++ b/node_modules/lodash/fp/findLast.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLast', require('../findLast')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findLastFrom.js b/node_modules/lodash/fp/findLastFrom.js new file mode 100644 index 0000000..76c38fb --- /dev/null +++ b/node_modules/lodash/fp/findLastFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLastFrom', require('../findLast')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findLastIndex.js b/node_modules/lodash/fp/findLastIndex.js new file mode 100644 index 0000000..36986df --- /dev/null +++ b/node_modules/lodash/fp/findLastIndex.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLastIndex', require('../findLastIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findLastIndexFrom.js b/node_modules/lodash/fp/findLastIndexFrom.js new file mode 100644 index 0000000..34c8176 --- /dev/null +++ b/node_modules/lodash/fp/findLastIndexFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLastIndexFrom', require('../findLastIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/findLastKey.js b/node_modules/lodash/fp/findLastKey.js new file mode 100644 index 0000000..5f81b60 --- /dev/null +++ b/node_modules/lodash/fp/findLastKey.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('findLastKey', require('../findLastKey')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/first.js b/node_modules/lodash/fp/first.js new file mode 100644 index 0000000..53f4ad1 --- /dev/null +++ b/node_modules/lodash/fp/first.js @@ -0,0 +1 @@ +module.exports = require('./head'); diff --git a/node_modules/lodash/fp/flatMap.js b/node_modules/lodash/fp/flatMap.js new file mode 100644 index 0000000..d01dc4d --- /dev/null +++ b/node_modules/lodash/fp/flatMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flatMap', require('../flatMap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flatMapDeep.js b/node_modules/lodash/fp/flatMapDeep.js new file mode 100644 index 0000000..569c42e --- /dev/null +++ b/node_modules/lodash/fp/flatMapDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flatMapDeep', require('../flatMapDeep')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flatMapDepth.js b/node_modules/lodash/fp/flatMapDepth.js new file mode 100644 index 0000000..6eb68fd --- /dev/null +++ b/node_modules/lodash/fp/flatMapDepth.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flatMapDepth', require('../flatMapDepth')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flatten.js b/node_modules/lodash/fp/flatten.js new file mode 100644 index 0000000..30425d8 --- /dev/null +++ b/node_modules/lodash/fp/flatten.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flatten', require('../flatten'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flattenDeep.js b/node_modules/lodash/fp/flattenDeep.js new file mode 100644 index 0000000..aed5db2 --- /dev/null +++ b/node_modules/lodash/fp/flattenDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flattenDeep', require('../flattenDeep'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flattenDepth.js b/node_modules/lodash/fp/flattenDepth.js new file mode 100644 index 0000000..ad65e37 --- /dev/null +++ b/node_modules/lodash/fp/flattenDepth.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flattenDepth', require('../flattenDepth')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flip.js b/node_modules/lodash/fp/flip.js new file mode 100644 index 0000000..0547e7b --- /dev/null +++ b/node_modules/lodash/fp/flip.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flip', require('../flip'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/floor.js b/node_modules/lodash/fp/floor.js new file mode 100644 index 0000000..a6cf335 --- /dev/null +++ b/node_modules/lodash/fp/floor.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('floor', require('../floor')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flow.js b/node_modules/lodash/fp/flow.js new file mode 100644 index 0000000..cd83677 --- /dev/null +++ b/node_modules/lodash/fp/flow.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flow', require('../flow')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/flowRight.js b/node_modules/lodash/fp/flowRight.js new file mode 100644 index 0000000..972a5b9 --- /dev/null +++ b/node_modules/lodash/fp/flowRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('flowRight', require('../flowRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/forEach.js b/node_modules/lodash/fp/forEach.js new file mode 100644 index 0000000..2f49452 --- /dev/null +++ b/node_modules/lodash/fp/forEach.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forEach', require('../forEach')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/forEachRight.js b/node_modules/lodash/fp/forEachRight.js new file mode 100644 index 0000000..3ff9733 --- /dev/null +++ b/node_modules/lodash/fp/forEachRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forEachRight', require('../forEachRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/forIn.js b/node_modules/lodash/fp/forIn.js new file mode 100644 index 0000000..9341749 --- /dev/null +++ b/node_modules/lodash/fp/forIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forIn', require('../forIn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/forInRight.js b/node_modules/lodash/fp/forInRight.js new file mode 100644 index 0000000..cecf8bb --- /dev/null +++ b/node_modules/lodash/fp/forInRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forInRight', require('../forInRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/forOwn.js b/node_modules/lodash/fp/forOwn.js new file mode 100644 index 0000000..246449e --- /dev/null +++ b/node_modules/lodash/fp/forOwn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forOwn', require('../forOwn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/forOwnRight.js b/node_modules/lodash/fp/forOwnRight.js new file mode 100644 index 0000000..c5e826e --- /dev/null +++ b/node_modules/lodash/fp/forOwnRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('forOwnRight', require('../forOwnRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/fromPairs.js b/node_modules/lodash/fp/fromPairs.js new file mode 100644 index 0000000..f8cc596 --- /dev/null +++ b/node_modules/lodash/fp/fromPairs.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('fromPairs', require('../fromPairs')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/function.js b/node_modules/lodash/fp/function.js new file mode 100644 index 0000000..dfe69b1 --- /dev/null +++ b/node_modules/lodash/fp/function.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../function')); diff --git a/node_modules/lodash/fp/functions.js b/node_modules/lodash/fp/functions.js new file mode 100644 index 0000000..09d1bb1 --- /dev/null +++ b/node_modules/lodash/fp/functions.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('functions', require('../functions'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/functionsIn.js b/node_modules/lodash/fp/functionsIn.js new file mode 100644 index 0000000..2cfeb83 --- /dev/null +++ b/node_modules/lodash/fp/functionsIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('functionsIn', require('../functionsIn'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/get.js b/node_modules/lodash/fp/get.js new file mode 100644 index 0000000..6d3a328 --- /dev/null +++ b/node_modules/lodash/fp/get.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('get', require('../get')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/getOr.js b/node_modules/lodash/fp/getOr.js new file mode 100644 index 0000000..7dbf771 --- /dev/null +++ b/node_modules/lodash/fp/getOr.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('getOr', require('../get')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/groupBy.js b/node_modules/lodash/fp/groupBy.js new file mode 100644 index 0000000..fc0bc78 --- /dev/null +++ b/node_modules/lodash/fp/groupBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('groupBy', require('../groupBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/gt.js b/node_modules/lodash/fp/gt.js new file mode 100644 index 0000000..9e57c80 --- /dev/null +++ b/node_modules/lodash/fp/gt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('gt', require('../gt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/gte.js b/node_modules/lodash/fp/gte.js new file mode 100644 index 0000000..4584786 --- /dev/null +++ b/node_modules/lodash/fp/gte.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('gte', require('../gte')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/has.js b/node_modules/lodash/fp/has.js new file mode 100644 index 0000000..b901298 --- /dev/null +++ b/node_modules/lodash/fp/has.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('has', require('../has')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/hasIn.js b/node_modules/lodash/fp/hasIn.js new file mode 100644 index 0000000..b3c3d1a --- /dev/null +++ b/node_modules/lodash/fp/hasIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('hasIn', require('../hasIn')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/head.js b/node_modules/lodash/fp/head.js new file mode 100644 index 0000000..2694f0a --- /dev/null +++ b/node_modules/lodash/fp/head.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('head', require('../head'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/identical.js b/node_modules/lodash/fp/identical.js new file mode 100644 index 0000000..85563f4 --- /dev/null +++ b/node_modules/lodash/fp/identical.js @@ -0,0 +1 @@ +module.exports = require('./eq'); diff --git a/node_modules/lodash/fp/identity.js b/node_modules/lodash/fp/identity.js new file mode 100644 index 0000000..096415a --- /dev/null +++ b/node_modules/lodash/fp/identity.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('identity', require('../identity'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/inRange.js b/node_modules/lodash/fp/inRange.js new file mode 100644 index 0000000..202d940 --- /dev/null +++ b/node_modules/lodash/fp/inRange.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('inRange', require('../inRange')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/includes.js b/node_modules/lodash/fp/includes.js new file mode 100644 index 0000000..1146780 --- /dev/null +++ b/node_modules/lodash/fp/includes.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('includes', require('../includes')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/includesFrom.js b/node_modules/lodash/fp/includesFrom.js new file mode 100644 index 0000000..683afdb --- /dev/null +++ b/node_modules/lodash/fp/includesFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('includesFrom', require('../includes')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/indexBy.js b/node_modules/lodash/fp/indexBy.js new file mode 100644 index 0000000..7e64bc0 --- /dev/null +++ b/node_modules/lodash/fp/indexBy.js @@ -0,0 +1 @@ +module.exports = require('./keyBy'); diff --git a/node_modules/lodash/fp/indexOf.js b/node_modules/lodash/fp/indexOf.js new file mode 100644 index 0000000..524658e --- /dev/null +++ b/node_modules/lodash/fp/indexOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('indexOf', require('../indexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/indexOfFrom.js b/node_modules/lodash/fp/indexOfFrom.js new file mode 100644 index 0000000..d99c822 --- /dev/null +++ b/node_modules/lodash/fp/indexOfFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('indexOfFrom', require('../indexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/init.js b/node_modules/lodash/fp/init.js new file mode 100644 index 0000000..2f88d8b --- /dev/null +++ b/node_modules/lodash/fp/init.js @@ -0,0 +1 @@ +module.exports = require('./initial'); diff --git a/node_modules/lodash/fp/initial.js b/node_modules/lodash/fp/initial.js new file mode 100644 index 0000000..b732ba0 --- /dev/null +++ b/node_modules/lodash/fp/initial.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('initial', require('../initial'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/intersection.js b/node_modules/lodash/fp/intersection.js new file mode 100644 index 0000000..52936d5 --- /dev/null +++ b/node_modules/lodash/fp/intersection.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('intersection', require('../intersection')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/intersectionBy.js b/node_modules/lodash/fp/intersectionBy.js new file mode 100644 index 0000000..72629f2 --- /dev/null +++ b/node_modules/lodash/fp/intersectionBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('intersectionBy', require('../intersectionBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/intersectionWith.js b/node_modules/lodash/fp/intersectionWith.js new file mode 100644 index 0000000..e064f40 --- /dev/null +++ b/node_modules/lodash/fp/intersectionWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('intersectionWith', require('../intersectionWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/invert.js b/node_modules/lodash/fp/invert.js new file mode 100644 index 0000000..2d5d1f0 --- /dev/null +++ b/node_modules/lodash/fp/invert.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invert', require('../invert')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/invertBy.js b/node_modules/lodash/fp/invertBy.js new file mode 100644 index 0000000..63ca97e --- /dev/null +++ b/node_modules/lodash/fp/invertBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invertBy', require('../invertBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/invertObj.js b/node_modules/lodash/fp/invertObj.js new file mode 100644 index 0000000..f1d842e --- /dev/null +++ b/node_modules/lodash/fp/invertObj.js @@ -0,0 +1 @@ +module.exports = require('./invert'); diff --git a/node_modules/lodash/fp/invoke.js b/node_modules/lodash/fp/invoke.js new file mode 100644 index 0000000..fcf17f0 --- /dev/null +++ b/node_modules/lodash/fp/invoke.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invoke', require('../invoke')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/invokeArgs.js b/node_modules/lodash/fp/invokeArgs.js new file mode 100644 index 0000000..d3f2953 --- /dev/null +++ b/node_modules/lodash/fp/invokeArgs.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invokeArgs', require('../invoke')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/invokeArgsMap.js b/node_modules/lodash/fp/invokeArgsMap.js new file mode 100644 index 0000000..eaa9f84 --- /dev/null +++ b/node_modules/lodash/fp/invokeArgsMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invokeArgsMap', require('../invokeMap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/invokeMap.js b/node_modules/lodash/fp/invokeMap.js new file mode 100644 index 0000000..6515fd7 --- /dev/null +++ b/node_modules/lodash/fp/invokeMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('invokeMap', require('../invokeMap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isArguments.js b/node_modules/lodash/fp/isArguments.js new file mode 100644 index 0000000..1d93c9e --- /dev/null +++ b/node_modules/lodash/fp/isArguments.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArguments', require('../isArguments'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isArray.js b/node_modules/lodash/fp/isArray.js new file mode 100644 index 0000000..ba7ade8 --- /dev/null +++ b/node_modules/lodash/fp/isArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArray', require('../isArray'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isArrayBuffer.js b/node_modules/lodash/fp/isArrayBuffer.js new file mode 100644 index 0000000..5088513 --- /dev/null +++ b/node_modules/lodash/fp/isArrayBuffer.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArrayBuffer', require('../isArrayBuffer'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isArrayLike.js b/node_modules/lodash/fp/isArrayLike.js new file mode 100644 index 0000000..8f1856b --- /dev/null +++ b/node_modules/lodash/fp/isArrayLike.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArrayLike', require('../isArrayLike'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isArrayLikeObject.js b/node_modules/lodash/fp/isArrayLikeObject.js new file mode 100644 index 0000000..2108498 --- /dev/null +++ b/node_modules/lodash/fp/isArrayLikeObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isArrayLikeObject', require('../isArrayLikeObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isBoolean.js b/node_modules/lodash/fp/isBoolean.js new file mode 100644 index 0000000..9339f75 --- /dev/null +++ b/node_modules/lodash/fp/isBoolean.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isBoolean', require('../isBoolean'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isBuffer.js b/node_modules/lodash/fp/isBuffer.js new file mode 100644 index 0000000..e60b123 --- /dev/null +++ b/node_modules/lodash/fp/isBuffer.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isBuffer', require('../isBuffer'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isDate.js b/node_modules/lodash/fp/isDate.js new file mode 100644 index 0000000..dc41d08 --- /dev/null +++ b/node_modules/lodash/fp/isDate.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isDate', require('../isDate'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isElement.js b/node_modules/lodash/fp/isElement.js new file mode 100644 index 0000000..18ee039 --- /dev/null +++ b/node_modules/lodash/fp/isElement.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isElement', require('../isElement'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isEmpty.js b/node_modules/lodash/fp/isEmpty.js new file mode 100644 index 0000000..0f4ae84 --- /dev/null +++ b/node_modules/lodash/fp/isEmpty.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isEmpty', require('../isEmpty'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isEqual.js b/node_modules/lodash/fp/isEqual.js new file mode 100644 index 0000000..4138386 --- /dev/null +++ b/node_modules/lodash/fp/isEqual.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isEqual', require('../isEqual')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isEqualWith.js b/node_modules/lodash/fp/isEqualWith.js new file mode 100644 index 0000000..029ff5c --- /dev/null +++ b/node_modules/lodash/fp/isEqualWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isEqualWith', require('../isEqualWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isError.js b/node_modules/lodash/fp/isError.js new file mode 100644 index 0000000..3dfd81c --- /dev/null +++ b/node_modules/lodash/fp/isError.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isError', require('../isError'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isFinite.js b/node_modules/lodash/fp/isFinite.js new file mode 100644 index 0000000..0b647b8 --- /dev/null +++ b/node_modules/lodash/fp/isFinite.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isFinite', require('../isFinite'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isFunction.js b/node_modules/lodash/fp/isFunction.js new file mode 100644 index 0000000..ff8e5c4 --- /dev/null +++ b/node_modules/lodash/fp/isFunction.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isFunction', require('../isFunction'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isInteger.js b/node_modules/lodash/fp/isInteger.js new file mode 100644 index 0000000..67af4ff --- /dev/null +++ b/node_modules/lodash/fp/isInteger.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isInteger', require('../isInteger'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isLength.js b/node_modules/lodash/fp/isLength.js new file mode 100644 index 0000000..fc101c5 --- /dev/null +++ b/node_modules/lodash/fp/isLength.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isLength', require('../isLength'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isMap.js b/node_modules/lodash/fp/isMap.js new file mode 100644 index 0000000..a209aa6 --- /dev/null +++ b/node_modules/lodash/fp/isMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isMap', require('../isMap'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isMatch.js b/node_modules/lodash/fp/isMatch.js new file mode 100644 index 0000000..6264ca1 --- /dev/null +++ b/node_modules/lodash/fp/isMatch.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isMatch', require('../isMatch')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isMatchWith.js b/node_modules/lodash/fp/isMatchWith.js new file mode 100644 index 0000000..d95f319 --- /dev/null +++ b/node_modules/lodash/fp/isMatchWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isMatchWith', require('../isMatchWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isNaN.js b/node_modules/lodash/fp/isNaN.js new file mode 100644 index 0000000..66a978f --- /dev/null +++ b/node_modules/lodash/fp/isNaN.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNaN', require('../isNaN'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isNative.js b/node_modules/lodash/fp/isNative.js new file mode 100644 index 0000000..3d775ba --- /dev/null +++ b/node_modules/lodash/fp/isNative.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNative', require('../isNative'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isNil.js b/node_modules/lodash/fp/isNil.js new file mode 100644 index 0000000..5952c02 --- /dev/null +++ b/node_modules/lodash/fp/isNil.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNil', require('../isNil'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isNull.js b/node_modules/lodash/fp/isNull.js new file mode 100644 index 0000000..f201a35 --- /dev/null +++ b/node_modules/lodash/fp/isNull.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNull', require('../isNull'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isNumber.js b/node_modules/lodash/fp/isNumber.js new file mode 100644 index 0000000..a2b5fa0 --- /dev/null +++ b/node_modules/lodash/fp/isNumber.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isNumber', require('../isNumber'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isObject.js b/node_modules/lodash/fp/isObject.js new file mode 100644 index 0000000..231ace0 --- /dev/null +++ b/node_modules/lodash/fp/isObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isObject', require('../isObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isObjectLike.js b/node_modules/lodash/fp/isObjectLike.js new file mode 100644 index 0000000..f16082e --- /dev/null +++ b/node_modules/lodash/fp/isObjectLike.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isObjectLike', require('../isObjectLike'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isPlainObject.js b/node_modules/lodash/fp/isPlainObject.js new file mode 100644 index 0000000..b5bea90 --- /dev/null +++ b/node_modules/lodash/fp/isPlainObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isPlainObject', require('../isPlainObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isRegExp.js b/node_modules/lodash/fp/isRegExp.js new file mode 100644 index 0000000..12a1a3d --- /dev/null +++ b/node_modules/lodash/fp/isRegExp.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isRegExp', require('../isRegExp'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isSafeInteger.js b/node_modules/lodash/fp/isSafeInteger.js new file mode 100644 index 0000000..7230f55 --- /dev/null +++ b/node_modules/lodash/fp/isSafeInteger.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isSafeInteger', require('../isSafeInteger'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isSet.js b/node_modules/lodash/fp/isSet.js new file mode 100644 index 0000000..35c01f6 --- /dev/null +++ b/node_modules/lodash/fp/isSet.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isSet', require('../isSet'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isString.js b/node_modules/lodash/fp/isString.js new file mode 100644 index 0000000..1fd0679 --- /dev/null +++ b/node_modules/lodash/fp/isString.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isString', require('../isString'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isSymbol.js b/node_modules/lodash/fp/isSymbol.js new file mode 100644 index 0000000..3867695 --- /dev/null +++ b/node_modules/lodash/fp/isSymbol.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isSymbol', require('../isSymbol'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isTypedArray.js b/node_modules/lodash/fp/isTypedArray.js new file mode 100644 index 0000000..8567953 --- /dev/null +++ b/node_modules/lodash/fp/isTypedArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isTypedArray', require('../isTypedArray'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isUndefined.js b/node_modules/lodash/fp/isUndefined.js new file mode 100644 index 0000000..ddbca31 --- /dev/null +++ b/node_modules/lodash/fp/isUndefined.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isUndefined', require('../isUndefined'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isWeakMap.js b/node_modules/lodash/fp/isWeakMap.js new file mode 100644 index 0000000..ef60c61 --- /dev/null +++ b/node_modules/lodash/fp/isWeakMap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isWeakMap', require('../isWeakMap'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/isWeakSet.js b/node_modules/lodash/fp/isWeakSet.js new file mode 100644 index 0000000..c99bfaa --- /dev/null +++ b/node_modules/lodash/fp/isWeakSet.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('isWeakSet', require('../isWeakSet'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/iteratee.js b/node_modules/lodash/fp/iteratee.js new file mode 100644 index 0000000..9f0f717 --- /dev/null +++ b/node_modules/lodash/fp/iteratee.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('iteratee', require('../iteratee')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/join.js b/node_modules/lodash/fp/join.js new file mode 100644 index 0000000..a220e00 --- /dev/null +++ b/node_modules/lodash/fp/join.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('join', require('../join')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/juxt.js b/node_modules/lodash/fp/juxt.js new file mode 100644 index 0000000..f71e04e --- /dev/null +++ b/node_modules/lodash/fp/juxt.js @@ -0,0 +1 @@ +module.exports = require('./over'); diff --git a/node_modules/lodash/fp/kebabCase.js b/node_modules/lodash/fp/kebabCase.js new file mode 100644 index 0000000..60737f1 --- /dev/null +++ b/node_modules/lodash/fp/kebabCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('kebabCase', require('../kebabCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/keyBy.js b/node_modules/lodash/fp/keyBy.js new file mode 100644 index 0000000..9a6a85d --- /dev/null +++ b/node_modules/lodash/fp/keyBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('keyBy', require('../keyBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/keys.js b/node_modules/lodash/fp/keys.js new file mode 100644 index 0000000..e12bb07 --- /dev/null +++ b/node_modules/lodash/fp/keys.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('keys', require('../keys'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/keysIn.js b/node_modules/lodash/fp/keysIn.js new file mode 100644 index 0000000..f3eb36a --- /dev/null +++ b/node_modules/lodash/fp/keysIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('keysIn', require('../keysIn'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/lang.js b/node_modules/lodash/fp/lang.js new file mode 100644 index 0000000..08cc9c1 --- /dev/null +++ b/node_modules/lodash/fp/lang.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../lang')); diff --git a/node_modules/lodash/fp/last.js b/node_modules/lodash/fp/last.js new file mode 100644 index 0000000..0f71699 --- /dev/null +++ b/node_modules/lodash/fp/last.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('last', require('../last'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/lastIndexOf.js b/node_modules/lodash/fp/lastIndexOf.js new file mode 100644 index 0000000..ddf39c3 --- /dev/null +++ b/node_modules/lodash/fp/lastIndexOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lastIndexOf', require('../lastIndexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/lastIndexOfFrom.js b/node_modules/lodash/fp/lastIndexOfFrom.js new file mode 100644 index 0000000..1ff6a0b --- /dev/null +++ b/node_modules/lodash/fp/lastIndexOfFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lastIndexOfFrom', require('../lastIndexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/lowerCase.js b/node_modules/lodash/fp/lowerCase.js new file mode 100644 index 0000000..ea64bc1 --- /dev/null +++ b/node_modules/lodash/fp/lowerCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lowerCase', require('../lowerCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/lowerFirst.js b/node_modules/lodash/fp/lowerFirst.js new file mode 100644 index 0000000..539720a --- /dev/null +++ b/node_modules/lodash/fp/lowerFirst.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lowerFirst', require('../lowerFirst'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/lt.js b/node_modules/lodash/fp/lt.js new file mode 100644 index 0000000..a31d21e --- /dev/null +++ b/node_modules/lodash/fp/lt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lt', require('../lt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/lte.js b/node_modules/lodash/fp/lte.js new file mode 100644 index 0000000..d795d10 --- /dev/null +++ b/node_modules/lodash/fp/lte.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('lte', require('../lte')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/map.js b/node_modules/lodash/fp/map.js new file mode 100644 index 0000000..cf98794 --- /dev/null +++ b/node_modules/lodash/fp/map.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('map', require('../map')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/mapKeys.js b/node_modules/lodash/fp/mapKeys.js new file mode 100644 index 0000000..1684587 --- /dev/null +++ b/node_modules/lodash/fp/mapKeys.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mapKeys', require('../mapKeys')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/mapValues.js b/node_modules/lodash/fp/mapValues.js new file mode 100644 index 0000000..4004972 --- /dev/null +++ b/node_modules/lodash/fp/mapValues.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mapValues', require('../mapValues')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/matches.js b/node_modules/lodash/fp/matches.js new file mode 100644 index 0000000..29d1e1e --- /dev/null +++ b/node_modules/lodash/fp/matches.js @@ -0,0 +1 @@ +module.exports = require('./isMatch'); diff --git a/node_modules/lodash/fp/matchesProperty.js b/node_modules/lodash/fp/matchesProperty.js new file mode 100644 index 0000000..4575bd2 --- /dev/null +++ b/node_modules/lodash/fp/matchesProperty.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('matchesProperty', require('../matchesProperty')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/math.js b/node_modules/lodash/fp/math.js new file mode 100644 index 0000000..e8f50f7 --- /dev/null +++ b/node_modules/lodash/fp/math.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../math')); diff --git a/node_modules/lodash/fp/max.js b/node_modules/lodash/fp/max.js new file mode 100644 index 0000000..a66acac --- /dev/null +++ b/node_modules/lodash/fp/max.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('max', require('../max'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/maxBy.js b/node_modules/lodash/fp/maxBy.js new file mode 100644 index 0000000..d083fd6 --- /dev/null +++ b/node_modules/lodash/fp/maxBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('maxBy', require('../maxBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/mean.js b/node_modules/lodash/fp/mean.js new file mode 100644 index 0000000..3117246 --- /dev/null +++ b/node_modules/lodash/fp/mean.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mean', require('../mean'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/meanBy.js b/node_modules/lodash/fp/meanBy.js new file mode 100644 index 0000000..556f25e --- /dev/null +++ b/node_modules/lodash/fp/meanBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('meanBy', require('../meanBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/memoize.js b/node_modules/lodash/fp/memoize.js new file mode 100644 index 0000000..638eec6 --- /dev/null +++ b/node_modules/lodash/fp/memoize.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('memoize', require('../memoize')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/merge.js b/node_modules/lodash/fp/merge.js new file mode 100644 index 0000000..ac66add --- /dev/null +++ b/node_modules/lodash/fp/merge.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('merge', require('../merge')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/mergeAll.js b/node_modules/lodash/fp/mergeAll.js new file mode 100644 index 0000000..a3674d6 --- /dev/null +++ b/node_modules/lodash/fp/mergeAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mergeAll', require('../merge')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/mergeAllWith.js b/node_modules/lodash/fp/mergeAllWith.js new file mode 100644 index 0000000..4bd4206 --- /dev/null +++ b/node_modules/lodash/fp/mergeAllWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mergeAllWith', require('../mergeWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/mergeWith.js b/node_modules/lodash/fp/mergeWith.js new file mode 100644 index 0000000..00d44d5 --- /dev/null +++ b/node_modules/lodash/fp/mergeWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mergeWith', require('../mergeWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/method.js b/node_modules/lodash/fp/method.js new file mode 100644 index 0000000..f4060c6 --- /dev/null +++ b/node_modules/lodash/fp/method.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('method', require('../method')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/methodOf.js b/node_modules/lodash/fp/methodOf.js new file mode 100644 index 0000000..6139905 --- /dev/null +++ b/node_modules/lodash/fp/methodOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('methodOf', require('../methodOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/min.js b/node_modules/lodash/fp/min.js new file mode 100644 index 0000000..d12c6b4 --- /dev/null +++ b/node_modules/lodash/fp/min.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('min', require('../min'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/minBy.js b/node_modules/lodash/fp/minBy.js new file mode 100644 index 0000000..fdb9e24 --- /dev/null +++ b/node_modules/lodash/fp/minBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('minBy', require('../minBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/mixin.js b/node_modules/lodash/fp/mixin.js new file mode 100644 index 0000000..332e6fb --- /dev/null +++ b/node_modules/lodash/fp/mixin.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('mixin', require('../mixin')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/multiply.js b/node_modules/lodash/fp/multiply.js new file mode 100644 index 0000000..4dcf0b0 --- /dev/null +++ b/node_modules/lodash/fp/multiply.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('multiply', require('../multiply')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/nAry.js b/node_modules/lodash/fp/nAry.js new file mode 100644 index 0000000..f262a76 --- /dev/null +++ b/node_modules/lodash/fp/nAry.js @@ -0,0 +1 @@ +module.exports = require('./ary'); diff --git a/node_modules/lodash/fp/negate.js b/node_modules/lodash/fp/negate.js new file mode 100644 index 0000000..8b6dc7c --- /dev/null +++ b/node_modules/lodash/fp/negate.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('negate', require('../negate'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/next.js b/node_modules/lodash/fp/next.js new file mode 100644 index 0000000..140155e --- /dev/null +++ b/node_modules/lodash/fp/next.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('next', require('../next'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/noop.js b/node_modules/lodash/fp/noop.js new file mode 100644 index 0000000..b9e32cc --- /dev/null +++ b/node_modules/lodash/fp/noop.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('noop', require('../noop'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/now.js b/node_modules/lodash/fp/now.js new file mode 100644 index 0000000..6de2068 --- /dev/null +++ b/node_modules/lodash/fp/now.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('now', require('../now'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/nth.js b/node_modules/lodash/fp/nth.js new file mode 100644 index 0000000..da4fda7 --- /dev/null +++ b/node_modules/lodash/fp/nth.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('nth', require('../nth')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/nthArg.js b/node_modules/lodash/fp/nthArg.js new file mode 100644 index 0000000..fce3165 --- /dev/null +++ b/node_modules/lodash/fp/nthArg.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('nthArg', require('../nthArg')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/number.js b/node_modules/lodash/fp/number.js new file mode 100644 index 0000000..5c10b88 --- /dev/null +++ b/node_modules/lodash/fp/number.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../number')); diff --git a/node_modules/lodash/fp/object.js b/node_modules/lodash/fp/object.js new file mode 100644 index 0000000..ae39a13 --- /dev/null +++ b/node_modules/lodash/fp/object.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../object')); diff --git a/node_modules/lodash/fp/omit.js b/node_modules/lodash/fp/omit.js new file mode 100644 index 0000000..fd68529 --- /dev/null +++ b/node_modules/lodash/fp/omit.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('omit', require('../omit')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/omitAll.js b/node_modules/lodash/fp/omitAll.js new file mode 100644 index 0000000..144cf4b --- /dev/null +++ b/node_modules/lodash/fp/omitAll.js @@ -0,0 +1 @@ +module.exports = require('./omit'); diff --git a/node_modules/lodash/fp/omitBy.js b/node_modules/lodash/fp/omitBy.js new file mode 100644 index 0000000..90df738 --- /dev/null +++ b/node_modules/lodash/fp/omitBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('omitBy', require('../omitBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/once.js b/node_modules/lodash/fp/once.js new file mode 100644 index 0000000..f8f0a5c --- /dev/null +++ b/node_modules/lodash/fp/once.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('once', require('../once'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/orderBy.js b/node_modules/lodash/fp/orderBy.js new file mode 100644 index 0000000..848e210 --- /dev/null +++ b/node_modules/lodash/fp/orderBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('orderBy', require('../orderBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/over.js b/node_modules/lodash/fp/over.js new file mode 100644 index 0000000..01eba7b --- /dev/null +++ b/node_modules/lodash/fp/over.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('over', require('../over')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/overArgs.js b/node_modules/lodash/fp/overArgs.js new file mode 100644 index 0000000..738556f --- /dev/null +++ b/node_modules/lodash/fp/overArgs.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('overArgs', require('../overArgs')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/overEvery.js b/node_modules/lodash/fp/overEvery.js new file mode 100644 index 0000000..9f5a032 --- /dev/null +++ b/node_modules/lodash/fp/overEvery.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('overEvery', require('../overEvery')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/overSome.js b/node_modules/lodash/fp/overSome.js new file mode 100644 index 0000000..15939d5 --- /dev/null +++ b/node_modules/lodash/fp/overSome.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('overSome', require('../overSome')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pad.js b/node_modules/lodash/fp/pad.js new file mode 100644 index 0000000..f1dea4a --- /dev/null +++ b/node_modules/lodash/fp/pad.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pad', require('../pad')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/padChars.js b/node_modules/lodash/fp/padChars.js new file mode 100644 index 0000000..d6e0804 --- /dev/null +++ b/node_modules/lodash/fp/padChars.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padChars', require('../pad')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/padCharsEnd.js b/node_modules/lodash/fp/padCharsEnd.js new file mode 100644 index 0000000..d4ab79a --- /dev/null +++ b/node_modules/lodash/fp/padCharsEnd.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padCharsEnd', require('../padEnd')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/padCharsStart.js b/node_modules/lodash/fp/padCharsStart.js new file mode 100644 index 0000000..a08a300 --- /dev/null +++ b/node_modules/lodash/fp/padCharsStart.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padCharsStart', require('../padStart')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/padEnd.js b/node_modules/lodash/fp/padEnd.js new file mode 100644 index 0000000..a8522ec --- /dev/null +++ b/node_modules/lodash/fp/padEnd.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padEnd', require('../padEnd')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/padStart.js b/node_modules/lodash/fp/padStart.js new file mode 100644 index 0000000..f4ca79d --- /dev/null +++ b/node_modules/lodash/fp/padStart.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('padStart', require('../padStart')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/parseInt.js b/node_modules/lodash/fp/parseInt.js new file mode 100644 index 0000000..27314cc --- /dev/null +++ b/node_modules/lodash/fp/parseInt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('parseInt', require('../parseInt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/partial.js b/node_modules/lodash/fp/partial.js new file mode 100644 index 0000000..5d46015 --- /dev/null +++ b/node_modules/lodash/fp/partial.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('partial', require('../partial')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/partialRight.js b/node_modules/lodash/fp/partialRight.js new file mode 100644 index 0000000..7f05fed --- /dev/null +++ b/node_modules/lodash/fp/partialRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('partialRight', require('../partialRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/partition.js b/node_modules/lodash/fp/partition.js new file mode 100644 index 0000000..2ebcacc --- /dev/null +++ b/node_modules/lodash/fp/partition.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('partition', require('../partition')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/path.js b/node_modules/lodash/fp/path.js new file mode 100644 index 0000000..b29cfb2 --- /dev/null +++ b/node_modules/lodash/fp/path.js @@ -0,0 +1 @@ +module.exports = require('./get'); diff --git a/node_modules/lodash/fp/pathEq.js b/node_modules/lodash/fp/pathEq.js new file mode 100644 index 0000000..36c027a --- /dev/null +++ b/node_modules/lodash/fp/pathEq.js @@ -0,0 +1 @@ +module.exports = require('./matchesProperty'); diff --git a/node_modules/lodash/fp/pathOr.js b/node_modules/lodash/fp/pathOr.js new file mode 100644 index 0000000..4ab5820 --- /dev/null +++ b/node_modules/lodash/fp/pathOr.js @@ -0,0 +1 @@ +module.exports = require('./getOr'); diff --git a/node_modules/lodash/fp/paths.js b/node_modules/lodash/fp/paths.js new file mode 100644 index 0000000..1eb7950 --- /dev/null +++ b/node_modules/lodash/fp/paths.js @@ -0,0 +1 @@ +module.exports = require('./at'); diff --git a/node_modules/lodash/fp/pick.js b/node_modules/lodash/fp/pick.js new file mode 100644 index 0000000..197393d --- /dev/null +++ b/node_modules/lodash/fp/pick.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pick', require('../pick')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pickAll.js b/node_modules/lodash/fp/pickAll.js new file mode 100644 index 0000000..a8ecd46 --- /dev/null +++ b/node_modules/lodash/fp/pickAll.js @@ -0,0 +1 @@ +module.exports = require('./pick'); diff --git a/node_modules/lodash/fp/pickBy.js b/node_modules/lodash/fp/pickBy.js new file mode 100644 index 0000000..d832d16 --- /dev/null +++ b/node_modules/lodash/fp/pickBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pickBy', require('../pickBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pipe.js b/node_modules/lodash/fp/pipe.js new file mode 100644 index 0000000..b2e1e2c --- /dev/null +++ b/node_modules/lodash/fp/pipe.js @@ -0,0 +1 @@ +module.exports = require('./flow'); diff --git a/node_modules/lodash/fp/placeholder.js b/node_modules/lodash/fp/placeholder.js new file mode 100644 index 0000000..1ce1739 --- /dev/null +++ b/node_modules/lodash/fp/placeholder.js @@ -0,0 +1,6 @@ +/** + * The default argument placeholder value for methods. + * + * @type {Object} + */ +module.exports = {}; diff --git a/node_modules/lodash/fp/plant.js b/node_modules/lodash/fp/plant.js new file mode 100644 index 0000000..eca8f32 --- /dev/null +++ b/node_modules/lodash/fp/plant.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('plant', require('../plant'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pluck.js b/node_modules/lodash/fp/pluck.js new file mode 100644 index 0000000..0d1e1ab --- /dev/null +++ b/node_modules/lodash/fp/pluck.js @@ -0,0 +1 @@ +module.exports = require('./map'); diff --git a/node_modules/lodash/fp/prop.js b/node_modules/lodash/fp/prop.js new file mode 100644 index 0000000..b29cfb2 --- /dev/null +++ b/node_modules/lodash/fp/prop.js @@ -0,0 +1 @@ +module.exports = require('./get'); diff --git a/node_modules/lodash/fp/propEq.js b/node_modules/lodash/fp/propEq.js new file mode 100644 index 0000000..36c027a --- /dev/null +++ b/node_modules/lodash/fp/propEq.js @@ -0,0 +1 @@ +module.exports = require('./matchesProperty'); diff --git a/node_modules/lodash/fp/propOr.js b/node_modules/lodash/fp/propOr.js new file mode 100644 index 0000000..4ab5820 --- /dev/null +++ b/node_modules/lodash/fp/propOr.js @@ -0,0 +1 @@ +module.exports = require('./getOr'); diff --git a/node_modules/lodash/fp/property.js b/node_modules/lodash/fp/property.js new file mode 100644 index 0000000..b29cfb2 --- /dev/null +++ b/node_modules/lodash/fp/property.js @@ -0,0 +1 @@ +module.exports = require('./get'); diff --git a/node_modules/lodash/fp/propertyOf.js b/node_modules/lodash/fp/propertyOf.js new file mode 100644 index 0000000..f6273ee --- /dev/null +++ b/node_modules/lodash/fp/propertyOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('propertyOf', require('../get')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/props.js b/node_modules/lodash/fp/props.js new file mode 100644 index 0000000..1eb7950 --- /dev/null +++ b/node_modules/lodash/fp/props.js @@ -0,0 +1 @@ +module.exports = require('./at'); diff --git a/node_modules/lodash/fp/pull.js b/node_modules/lodash/fp/pull.js new file mode 100644 index 0000000..8d7084f --- /dev/null +++ b/node_modules/lodash/fp/pull.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pull', require('../pull')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pullAll.js b/node_modules/lodash/fp/pullAll.js new file mode 100644 index 0000000..98d5c9a --- /dev/null +++ b/node_modules/lodash/fp/pullAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pullAll', require('../pullAll')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pullAllBy.js b/node_modules/lodash/fp/pullAllBy.js new file mode 100644 index 0000000..876bc3b --- /dev/null +++ b/node_modules/lodash/fp/pullAllBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pullAllBy', require('../pullAllBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pullAllWith.js b/node_modules/lodash/fp/pullAllWith.js new file mode 100644 index 0000000..f71ba4d --- /dev/null +++ b/node_modules/lodash/fp/pullAllWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pullAllWith', require('../pullAllWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/pullAt.js b/node_modules/lodash/fp/pullAt.js new file mode 100644 index 0000000..e8b3bb6 --- /dev/null +++ b/node_modules/lodash/fp/pullAt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('pullAt', require('../pullAt')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/random.js b/node_modules/lodash/fp/random.js new file mode 100644 index 0000000..99d852e --- /dev/null +++ b/node_modules/lodash/fp/random.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('random', require('../random')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/range.js b/node_modules/lodash/fp/range.js new file mode 100644 index 0000000..a6bb591 --- /dev/null +++ b/node_modules/lodash/fp/range.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('range', require('../range')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/rangeRight.js b/node_modules/lodash/fp/rangeRight.js new file mode 100644 index 0000000..fdb712f --- /dev/null +++ b/node_modules/lodash/fp/rangeRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rangeRight', require('../rangeRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/rangeStep.js b/node_modules/lodash/fp/rangeStep.js new file mode 100644 index 0000000..d72dfc2 --- /dev/null +++ b/node_modules/lodash/fp/rangeStep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rangeStep', require('../range')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/rangeStepRight.js b/node_modules/lodash/fp/rangeStepRight.js new file mode 100644 index 0000000..8b2a67b --- /dev/null +++ b/node_modules/lodash/fp/rangeStepRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rangeStepRight', require('../rangeRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/rearg.js b/node_modules/lodash/fp/rearg.js new file mode 100644 index 0000000..678e02a --- /dev/null +++ b/node_modules/lodash/fp/rearg.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rearg', require('../rearg')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/reduce.js b/node_modules/lodash/fp/reduce.js new file mode 100644 index 0000000..4cef0a0 --- /dev/null +++ b/node_modules/lodash/fp/reduce.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('reduce', require('../reduce')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/reduceRight.js b/node_modules/lodash/fp/reduceRight.js new file mode 100644 index 0000000..caf5bb5 --- /dev/null +++ b/node_modules/lodash/fp/reduceRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('reduceRight', require('../reduceRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/reject.js b/node_modules/lodash/fp/reject.js new file mode 100644 index 0000000..c163273 --- /dev/null +++ b/node_modules/lodash/fp/reject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('reject', require('../reject')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/remove.js b/node_modules/lodash/fp/remove.js new file mode 100644 index 0000000..e9d1327 --- /dev/null +++ b/node_modules/lodash/fp/remove.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('remove', require('../remove')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/repeat.js b/node_modules/lodash/fp/repeat.js new file mode 100644 index 0000000..08470f2 --- /dev/null +++ b/node_modules/lodash/fp/repeat.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('repeat', require('../repeat')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/replace.js b/node_modules/lodash/fp/replace.js new file mode 100644 index 0000000..2227db6 --- /dev/null +++ b/node_modules/lodash/fp/replace.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('replace', require('../replace')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/rest.js b/node_modules/lodash/fp/rest.js new file mode 100644 index 0000000..c1f3d64 --- /dev/null +++ b/node_modules/lodash/fp/rest.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('rest', require('../rest')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/restFrom.js b/node_modules/lodash/fp/restFrom.js new file mode 100644 index 0000000..714e42b --- /dev/null +++ b/node_modules/lodash/fp/restFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('restFrom', require('../rest')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/result.js b/node_modules/lodash/fp/result.js new file mode 100644 index 0000000..f86ce07 --- /dev/null +++ b/node_modules/lodash/fp/result.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('result', require('../result')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/reverse.js b/node_modules/lodash/fp/reverse.js new file mode 100644 index 0000000..07c9f5e --- /dev/null +++ b/node_modules/lodash/fp/reverse.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('reverse', require('../reverse')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/round.js b/node_modules/lodash/fp/round.js new file mode 100644 index 0000000..4c0e5c8 --- /dev/null +++ b/node_modules/lodash/fp/round.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('round', require('../round')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sample.js b/node_modules/lodash/fp/sample.js new file mode 100644 index 0000000..6bea125 --- /dev/null +++ b/node_modules/lodash/fp/sample.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sample', require('../sample'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sampleSize.js b/node_modules/lodash/fp/sampleSize.js new file mode 100644 index 0000000..359ed6f --- /dev/null +++ b/node_modules/lodash/fp/sampleSize.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sampleSize', require('../sampleSize')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/seq.js b/node_modules/lodash/fp/seq.js new file mode 100644 index 0000000..d8f42b0 --- /dev/null +++ b/node_modules/lodash/fp/seq.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../seq')); diff --git a/node_modules/lodash/fp/set.js b/node_modules/lodash/fp/set.js new file mode 100644 index 0000000..0b56a56 --- /dev/null +++ b/node_modules/lodash/fp/set.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('set', require('../set')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/setWith.js b/node_modules/lodash/fp/setWith.js new file mode 100644 index 0000000..0b58495 --- /dev/null +++ b/node_modules/lodash/fp/setWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('setWith', require('../setWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/shuffle.js b/node_modules/lodash/fp/shuffle.js new file mode 100644 index 0000000..aa3a1ca --- /dev/null +++ b/node_modules/lodash/fp/shuffle.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('shuffle', require('../shuffle'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/size.js b/node_modules/lodash/fp/size.js new file mode 100644 index 0000000..7490136 --- /dev/null +++ b/node_modules/lodash/fp/size.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('size', require('../size'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/slice.js b/node_modules/lodash/fp/slice.js new file mode 100644 index 0000000..15945d3 --- /dev/null +++ b/node_modules/lodash/fp/slice.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('slice', require('../slice')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/snakeCase.js b/node_modules/lodash/fp/snakeCase.js new file mode 100644 index 0000000..a0ff780 --- /dev/null +++ b/node_modules/lodash/fp/snakeCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('snakeCase', require('../snakeCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/some.js b/node_modules/lodash/fp/some.js new file mode 100644 index 0000000..a4fa2d0 --- /dev/null +++ b/node_modules/lodash/fp/some.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('some', require('../some')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortBy.js b/node_modules/lodash/fp/sortBy.js new file mode 100644 index 0000000..e0790ad --- /dev/null +++ b/node_modules/lodash/fp/sortBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortBy', require('../sortBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedIndex.js b/node_modules/lodash/fp/sortedIndex.js new file mode 100644 index 0000000..364a054 --- /dev/null +++ b/node_modules/lodash/fp/sortedIndex.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedIndex', require('../sortedIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedIndexBy.js b/node_modules/lodash/fp/sortedIndexBy.js new file mode 100644 index 0000000..9593dbd --- /dev/null +++ b/node_modules/lodash/fp/sortedIndexBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedIndexBy', require('../sortedIndexBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedIndexOf.js b/node_modules/lodash/fp/sortedIndexOf.js new file mode 100644 index 0000000..c9084ca --- /dev/null +++ b/node_modules/lodash/fp/sortedIndexOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedIndexOf', require('../sortedIndexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedLastIndex.js b/node_modules/lodash/fp/sortedLastIndex.js new file mode 100644 index 0000000..47fe241 --- /dev/null +++ b/node_modules/lodash/fp/sortedLastIndex.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedLastIndex', require('../sortedLastIndex')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedLastIndexBy.js b/node_modules/lodash/fp/sortedLastIndexBy.js new file mode 100644 index 0000000..0f9a347 --- /dev/null +++ b/node_modules/lodash/fp/sortedLastIndexBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedLastIndexBy', require('../sortedLastIndexBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedLastIndexOf.js b/node_modules/lodash/fp/sortedLastIndexOf.js new file mode 100644 index 0000000..0d4d932 --- /dev/null +++ b/node_modules/lodash/fp/sortedLastIndexOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedLastIndexOf', require('../sortedLastIndexOf')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedUniq.js b/node_modules/lodash/fp/sortedUniq.js new file mode 100644 index 0000000..882d283 --- /dev/null +++ b/node_modules/lodash/fp/sortedUniq.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedUniq', require('../sortedUniq'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sortedUniqBy.js b/node_modules/lodash/fp/sortedUniqBy.js new file mode 100644 index 0000000..033db91 --- /dev/null +++ b/node_modules/lodash/fp/sortedUniqBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sortedUniqBy', require('../sortedUniqBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/split.js b/node_modules/lodash/fp/split.js new file mode 100644 index 0000000..14de1a7 --- /dev/null +++ b/node_modules/lodash/fp/split.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('split', require('../split')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/spread.js b/node_modules/lodash/fp/spread.js new file mode 100644 index 0000000..2d11b70 --- /dev/null +++ b/node_modules/lodash/fp/spread.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('spread', require('../spread')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/spreadFrom.js b/node_modules/lodash/fp/spreadFrom.js new file mode 100644 index 0000000..0b630df --- /dev/null +++ b/node_modules/lodash/fp/spreadFrom.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('spreadFrom', require('../spread')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/startCase.js b/node_modules/lodash/fp/startCase.js new file mode 100644 index 0000000..ada98c9 --- /dev/null +++ b/node_modules/lodash/fp/startCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('startCase', require('../startCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/startsWith.js b/node_modules/lodash/fp/startsWith.js new file mode 100644 index 0000000..985e2f2 --- /dev/null +++ b/node_modules/lodash/fp/startsWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('startsWith', require('../startsWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/string.js b/node_modules/lodash/fp/string.js new file mode 100644 index 0000000..773b037 --- /dev/null +++ b/node_modules/lodash/fp/string.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../string')); diff --git a/node_modules/lodash/fp/stubArray.js b/node_modules/lodash/fp/stubArray.js new file mode 100644 index 0000000..cd604cb --- /dev/null +++ b/node_modules/lodash/fp/stubArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubArray', require('../stubArray'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/stubFalse.js b/node_modules/lodash/fp/stubFalse.js new file mode 100644 index 0000000..3296664 --- /dev/null +++ b/node_modules/lodash/fp/stubFalse.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubFalse', require('../stubFalse'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/stubObject.js b/node_modules/lodash/fp/stubObject.js new file mode 100644 index 0000000..c6c8ec4 --- /dev/null +++ b/node_modules/lodash/fp/stubObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubObject', require('../stubObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/stubString.js b/node_modules/lodash/fp/stubString.js new file mode 100644 index 0000000..701051e --- /dev/null +++ b/node_modules/lodash/fp/stubString.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubString', require('../stubString'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/stubTrue.js b/node_modules/lodash/fp/stubTrue.js new file mode 100644 index 0000000..9249082 --- /dev/null +++ b/node_modules/lodash/fp/stubTrue.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('stubTrue', require('../stubTrue'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/subtract.js b/node_modules/lodash/fp/subtract.js new file mode 100644 index 0000000..d32b16d --- /dev/null +++ b/node_modules/lodash/fp/subtract.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('subtract', require('../subtract')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sum.js b/node_modules/lodash/fp/sum.js new file mode 100644 index 0000000..5cce12b --- /dev/null +++ b/node_modules/lodash/fp/sum.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sum', require('../sum'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/sumBy.js b/node_modules/lodash/fp/sumBy.js new file mode 100644 index 0000000..c882656 --- /dev/null +++ b/node_modules/lodash/fp/sumBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('sumBy', require('../sumBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/symmetricDifference.js b/node_modules/lodash/fp/symmetricDifference.js new file mode 100644 index 0000000..78c16ad --- /dev/null +++ b/node_modules/lodash/fp/symmetricDifference.js @@ -0,0 +1 @@ +module.exports = require('./xor'); diff --git a/node_modules/lodash/fp/symmetricDifferenceBy.js b/node_modules/lodash/fp/symmetricDifferenceBy.js new file mode 100644 index 0000000..298fc7f --- /dev/null +++ b/node_modules/lodash/fp/symmetricDifferenceBy.js @@ -0,0 +1 @@ +module.exports = require('./xorBy'); diff --git a/node_modules/lodash/fp/symmetricDifferenceWith.js b/node_modules/lodash/fp/symmetricDifferenceWith.js new file mode 100644 index 0000000..70bc6fa --- /dev/null +++ b/node_modules/lodash/fp/symmetricDifferenceWith.js @@ -0,0 +1 @@ +module.exports = require('./xorWith'); diff --git a/node_modules/lodash/fp/tail.js b/node_modules/lodash/fp/tail.js new file mode 100644 index 0000000..f122f0a --- /dev/null +++ b/node_modules/lodash/fp/tail.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('tail', require('../tail'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/take.js b/node_modules/lodash/fp/take.js new file mode 100644 index 0000000..9af98a7 --- /dev/null +++ b/node_modules/lodash/fp/take.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('take', require('../take')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/takeLast.js b/node_modules/lodash/fp/takeLast.js new file mode 100644 index 0000000..e98c84a --- /dev/null +++ b/node_modules/lodash/fp/takeLast.js @@ -0,0 +1 @@ +module.exports = require('./takeRight'); diff --git a/node_modules/lodash/fp/takeLastWhile.js b/node_modules/lodash/fp/takeLastWhile.js new file mode 100644 index 0000000..5367968 --- /dev/null +++ b/node_modules/lodash/fp/takeLastWhile.js @@ -0,0 +1 @@ +module.exports = require('./takeRightWhile'); diff --git a/node_modules/lodash/fp/takeRight.js b/node_modules/lodash/fp/takeRight.js new file mode 100644 index 0000000..b82950a --- /dev/null +++ b/node_modules/lodash/fp/takeRight.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('takeRight', require('../takeRight')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/takeRightWhile.js b/node_modules/lodash/fp/takeRightWhile.js new file mode 100644 index 0000000..8ffb0a2 --- /dev/null +++ b/node_modules/lodash/fp/takeRightWhile.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('takeRightWhile', require('../takeRightWhile')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/takeWhile.js b/node_modules/lodash/fp/takeWhile.js new file mode 100644 index 0000000..2813664 --- /dev/null +++ b/node_modules/lodash/fp/takeWhile.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('takeWhile', require('../takeWhile')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/tap.js b/node_modules/lodash/fp/tap.js new file mode 100644 index 0000000..d33ad6e --- /dev/null +++ b/node_modules/lodash/fp/tap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('tap', require('../tap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/template.js b/node_modules/lodash/fp/template.js new file mode 100644 index 0000000..74857e1 --- /dev/null +++ b/node_modules/lodash/fp/template.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('template', require('../template')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/templateSettings.js b/node_modules/lodash/fp/templateSettings.js new file mode 100644 index 0000000..7bcc0a8 --- /dev/null +++ b/node_modules/lodash/fp/templateSettings.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('templateSettings', require('../templateSettings'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/throttle.js b/node_modules/lodash/fp/throttle.js new file mode 100644 index 0000000..77fff14 --- /dev/null +++ b/node_modules/lodash/fp/throttle.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('throttle', require('../throttle')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/thru.js b/node_modules/lodash/fp/thru.js new file mode 100644 index 0000000..d42b3b1 --- /dev/null +++ b/node_modules/lodash/fp/thru.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('thru', require('../thru')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/times.js b/node_modules/lodash/fp/times.js new file mode 100644 index 0000000..0dab06d --- /dev/null +++ b/node_modules/lodash/fp/times.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('times', require('../times')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toArray.js b/node_modules/lodash/fp/toArray.js new file mode 100644 index 0000000..f0c360a --- /dev/null +++ b/node_modules/lodash/fp/toArray.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toArray', require('../toArray'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toFinite.js b/node_modules/lodash/fp/toFinite.js new file mode 100644 index 0000000..3a47687 --- /dev/null +++ b/node_modules/lodash/fp/toFinite.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toFinite', require('../toFinite'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toInteger.js b/node_modules/lodash/fp/toInteger.js new file mode 100644 index 0000000..e0af6a7 --- /dev/null +++ b/node_modules/lodash/fp/toInteger.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toInteger', require('../toInteger'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toIterator.js b/node_modules/lodash/fp/toIterator.js new file mode 100644 index 0000000..65e6baa --- /dev/null +++ b/node_modules/lodash/fp/toIterator.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toIterator', require('../toIterator'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toJSON.js b/node_modules/lodash/fp/toJSON.js new file mode 100644 index 0000000..2d718d0 --- /dev/null +++ b/node_modules/lodash/fp/toJSON.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toJSON', require('../toJSON'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toLength.js b/node_modules/lodash/fp/toLength.js new file mode 100644 index 0000000..b97cdd9 --- /dev/null +++ b/node_modules/lodash/fp/toLength.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toLength', require('../toLength'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toLower.js b/node_modules/lodash/fp/toLower.js new file mode 100644 index 0000000..616ef36 --- /dev/null +++ b/node_modules/lodash/fp/toLower.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toLower', require('../toLower'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toNumber.js b/node_modules/lodash/fp/toNumber.js new file mode 100644 index 0000000..d0c6f4d --- /dev/null +++ b/node_modules/lodash/fp/toNumber.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toNumber', require('../toNumber'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toPairs.js b/node_modules/lodash/fp/toPairs.js new file mode 100644 index 0000000..af78378 --- /dev/null +++ b/node_modules/lodash/fp/toPairs.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toPairs', require('../toPairs'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toPairsIn.js b/node_modules/lodash/fp/toPairsIn.js new file mode 100644 index 0000000..66504ab --- /dev/null +++ b/node_modules/lodash/fp/toPairsIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toPairsIn', require('../toPairsIn'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toPath.js b/node_modules/lodash/fp/toPath.js new file mode 100644 index 0000000..b4d5e50 --- /dev/null +++ b/node_modules/lodash/fp/toPath.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toPath', require('../toPath'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toPlainObject.js b/node_modules/lodash/fp/toPlainObject.js new file mode 100644 index 0000000..278bb86 --- /dev/null +++ b/node_modules/lodash/fp/toPlainObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toPlainObject', require('../toPlainObject'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toSafeInteger.js b/node_modules/lodash/fp/toSafeInteger.js new file mode 100644 index 0000000..367a26f --- /dev/null +++ b/node_modules/lodash/fp/toSafeInteger.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toSafeInteger', require('../toSafeInteger'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toString.js b/node_modules/lodash/fp/toString.js new file mode 100644 index 0000000..cec4f8e --- /dev/null +++ b/node_modules/lodash/fp/toString.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toString', require('../toString'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/toUpper.js b/node_modules/lodash/fp/toUpper.js new file mode 100644 index 0000000..54f9a56 --- /dev/null +++ b/node_modules/lodash/fp/toUpper.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('toUpper', require('../toUpper'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/transform.js b/node_modules/lodash/fp/transform.js new file mode 100644 index 0000000..759d088 --- /dev/null +++ b/node_modules/lodash/fp/transform.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('transform', require('../transform')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/trim.js b/node_modules/lodash/fp/trim.js new file mode 100644 index 0000000..e6319a7 --- /dev/null +++ b/node_modules/lodash/fp/trim.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trim', require('../trim')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/trimChars.js b/node_modules/lodash/fp/trimChars.js new file mode 100644 index 0000000..c9294de --- /dev/null +++ b/node_modules/lodash/fp/trimChars.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimChars', require('../trim')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/trimCharsEnd.js b/node_modules/lodash/fp/trimCharsEnd.js new file mode 100644 index 0000000..284bc2f --- /dev/null +++ b/node_modules/lodash/fp/trimCharsEnd.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimCharsEnd', require('../trimEnd')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/trimCharsStart.js b/node_modules/lodash/fp/trimCharsStart.js new file mode 100644 index 0000000..ff0ee65 --- /dev/null +++ b/node_modules/lodash/fp/trimCharsStart.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimCharsStart', require('../trimStart')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/trimEnd.js b/node_modules/lodash/fp/trimEnd.js new file mode 100644 index 0000000..7190880 --- /dev/null +++ b/node_modules/lodash/fp/trimEnd.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimEnd', require('../trimEnd')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/trimStart.js b/node_modules/lodash/fp/trimStart.js new file mode 100644 index 0000000..fda902c --- /dev/null +++ b/node_modules/lodash/fp/trimStart.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('trimStart', require('../trimStart')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/truncate.js b/node_modules/lodash/fp/truncate.js new file mode 100644 index 0000000..d265c1d --- /dev/null +++ b/node_modules/lodash/fp/truncate.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('truncate', require('../truncate')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/unapply.js b/node_modules/lodash/fp/unapply.js new file mode 100644 index 0000000..c5dfe77 --- /dev/null +++ b/node_modules/lodash/fp/unapply.js @@ -0,0 +1 @@ +module.exports = require('./rest'); diff --git a/node_modules/lodash/fp/unary.js b/node_modules/lodash/fp/unary.js new file mode 100644 index 0000000..286c945 --- /dev/null +++ b/node_modules/lodash/fp/unary.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unary', require('../unary'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/unescape.js b/node_modules/lodash/fp/unescape.js new file mode 100644 index 0000000..fddcb46 --- /dev/null +++ b/node_modules/lodash/fp/unescape.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unescape', require('../unescape'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/union.js b/node_modules/lodash/fp/union.js new file mode 100644 index 0000000..ef8228d --- /dev/null +++ b/node_modules/lodash/fp/union.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('union', require('../union')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/unionBy.js b/node_modules/lodash/fp/unionBy.js new file mode 100644 index 0000000..603687a --- /dev/null +++ b/node_modules/lodash/fp/unionBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unionBy', require('../unionBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/unionWith.js b/node_modules/lodash/fp/unionWith.js new file mode 100644 index 0000000..65bb3a7 --- /dev/null +++ b/node_modules/lodash/fp/unionWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unionWith', require('../unionWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/uniq.js b/node_modules/lodash/fp/uniq.js new file mode 100644 index 0000000..bc18524 --- /dev/null +++ b/node_modules/lodash/fp/uniq.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('uniq', require('../uniq'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/uniqBy.js b/node_modules/lodash/fp/uniqBy.js new file mode 100644 index 0000000..634c6a8 --- /dev/null +++ b/node_modules/lodash/fp/uniqBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('uniqBy', require('../uniqBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/uniqWith.js b/node_modules/lodash/fp/uniqWith.js new file mode 100644 index 0000000..0ec601a --- /dev/null +++ b/node_modules/lodash/fp/uniqWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('uniqWith', require('../uniqWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/uniqueId.js b/node_modules/lodash/fp/uniqueId.js new file mode 100644 index 0000000..aa8fc2f --- /dev/null +++ b/node_modules/lodash/fp/uniqueId.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('uniqueId', require('../uniqueId')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/unnest.js b/node_modules/lodash/fp/unnest.js new file mode 100644 index 0000000..5d34060 --- /dev/null +++ b/node_modules/lodash/fp/unnest.js @@ -0,0 +1 @@ +module.exports = require('./flatten'); diff --git a/node_modules/lodash/fp/unset.js b/node_modules/lodash/fp/unset.js new file mode 100644 index 0000000..ea203a0 --- /dev/null +++ b/node_modules/lodash/fp/unset.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unset', require('../unset')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/unzip.js b/node_modules/lodash/fp/unzip.js new file mode 100644 index 0000000..cc364b3 --- /dev/null +++ b/node_modules/lodash/fp/unzip.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unzip', require('../unzip'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/unzipWith.js b/node_modules/lodash/fp/unzipWith.js new file mode 100644 index 0000000..182eaa1 --- /dev/null +++ b/node_modules/lodash/fp/unzipWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('unzipWith', require('../unzipWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/update.js b/node_modules/lodash/fp/update.js new file mode 100644 index 0000000..b8ce2cc --- /dev/null +++ b/node_modules/lodash/fp/update.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('update', require('../update')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/updateWith.js b/node_modules/lodash/fp/updateWith.js new file mode 100644 index 0000000..d5e8282 --- /dev/null +++ b/node_modules/lodash/fp/updateWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('updateWith', require('../updateWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/upperCase.js b/node_modules/lodash/fp/upperCase.js new file mode 100644 index 0000000..c886f20 --- /dev/null +++ b/node_modules/lodash/fp/upperCase.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('upperCase', require('../upperCase'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/upperFirst.js b/node_modules/lodash/fp/upperFirst.js new file mode 100644 index 0000000..d8c04df --- /dev/null +++ b/node_modules/lodash/fp/upperFirst.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('upperFirst', require('../upperFirst'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/useWith.js b/node_modules/lodash/fp/useWith.js new file mode 100644 index 0000000..d8b3df5 --- /dev/null +++ b/node_modules/lodash/fp/useWith.js @@ -0,0 +1 @@ +module.exports = require('./overArgs'); diff --git a/node_modules/lodash/fp/util.js b/node_modules/lodash/fp/util.js new file mode 100644 index 0000000..18c00ba --- /dev/null +++ b/node_modules/lodash/fp/util.js @@ -0,0 +1,2 @@ +var convert = require('./convert'); +module.exports = convert(require('../util')); diff --git a/node_modules/lodash/fp/value.js b/node_modules/lodash/fp/value.js new file mode 100644 index 0000000..555eec7 --- /dev/null +++ b/node_modules/lodash/fp/value.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('value', require('../value'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/valueOf.js b/node_modules/lodash/fp/valueOf.js new file mode 100644 index 0000000..f968807 --- /dev/null +++ b/node_modules/lodash/fp/valueOf.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('valueOf', require('../valueOf'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/values.js b/node_modules/lodash/fp/values.js new file mode 100644 index 0000000..2dfc561 --- /dev/null +++ b/node_modules/lodash/fp/values.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('values', require('../values'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/valuesIn.js b/node_modules/lodash/fp/valuesIn.js new file mode 100644 index 0000000..a1b2bb8 --- /dev/null +++ b/node_modules/lodash/fp/valuesIn.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('valuesIn', require('../valuesIn'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/where.js b/node_modules/lodash/fp/where.js new file mode 100644 index 0000000..3247f64 --- /dev/null +++ b/node_modules/lodash/fp/where.js @@ -0,0 +1 @@ +module.exports = require('./conformsTo'); diff --git a/node_modules/lodash/fp/whereEq.js b/node_modules/lodash/fp/whereEq.js new file mode 100644 index 0000000..29d1e1e --- /dev/null +++ b/node_modules/lodash/fp/whereEq.js @@ -0,0 +1 @@ +module.exports = require('./isMatch'); diff --git a/node_modules/lodash/fp/without.js b/node_modules/lodash/fp/without.js new file mode 100644 index 0000000..bad9e12 --- /dev/null +++ b/node_modules/lodash/fp/without.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('without', require('../without')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/words.js b/node_modules/lodash/fp/words.js new file mode 100644 index 0000000..4a90141 --- /dev/null +++ b/node_modules/lodash/fp/words.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('words', require('../words')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/wrap.js b/node_modules/lodash/fp/wrap.js new file mode 100644 index 0000000..e93bd8a --- /dev/null +++ b/node_modules/lodash/fp/wrap.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrap', require('../wrap')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/wrapperAt.js b/node_modules/lodash/fp/wrapperAt.js new file mode 100644 index 0000000..8f0a310 --- /dev/null +++ b/node_modules/lodash/fp/wrapperAt.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperAt', require('../wrapperAt'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/wrapperChain.js b/node_modules/lodash/fp/wrapperChain.js new file mode 100644 index 0000000..2a48ea2 --- /dev/null +++ b/node_modules/lodash/fp/wrapperChain.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperChain', require('../wrapperChain'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/wrapperLodash.js b/node_modules/lodash/fp/wrapperLodash.js new file mode 100644 index 0000000..a7162d0 --- /dev/null +++ b/node_modules/lodash/fp/wrapperLodash.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperLodash', require('../wrapperLodash'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/wrapperReverse.js b/node_modules/lodash/fp/wrapperReverse.js new file mode 100644 index 0000000..e1481aa --- /dev/null +++ b/node_modules/lodash/fp/wrapperReverse.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperReverse', require('../wrapperReverse'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/wrapperValue.js b/node_modules/lodash/fp/wrapperValue.js new file mode 100644 index 0000000..8eb9112 --- /dev/null +++ b/node_modules/lodash/fp/wrapperValue.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('wrapperValue', require('../wrapperValue'), require('./_falseOptions')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/xor.js b/node_modules/lodash/fp/xor.js new file mode 100644 index 0000000..29e2819 --- /dev/null +++ b/node_modules/lodash/fp/xor.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('xor', require('../xor')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/xorBy.js b/node_modules/lodash/fp/xorBy.js new file mode 100644 index 0000000..b355686 --- /dev/null +++ b/node_modules/lodash/fp/xorBy.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('xorBy', require('../xorBy')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/xorWith.js b/node_modules/lodash/fp/xorWith.js new file mode 100644 index 0000000..8e05739 --- /dev/null +++ b/node_modules/lodash/fp/xorWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('xorWith', require('../xorWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/zip.js b/node_modules/lodash/fp/zip.js new file mode 100644 index 0000000..69e147a --- /dev/null +++ b/node_modules/lodash/fp/zip.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zip', require('../zip')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/zipAll.js b/node_modules/lodash/fp/zipAll.js new file mode 100644 index 0000000..efa8ccb --- /dev/null +++ b/node_modules/lodash/fp/zipAll.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zipAll', require('../zip')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/zipObj.js b/node_modules/lodash/fp/zipObj.js new file mode 100644 index 0000000..f4a3453 --- /dev/null +++ b/node_modules/lodash/fp/zipObj.js @@ -0,0 +1 @@ +module.exports = require('./zipObject'); diff --git a/node_modules/lodash/fp/zipObject.js b/node_modules/lodash/fp/zipObject.js new file mode 100644 index 0000000..462dbb6 --- /dev/null +++ b/node_modules/lodash/fp/zipObject.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zipObject', require('../zipObject')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/zipObjectDeep.js b/node_modules/lodash/fp/zipObjectDeep.js new file mode 100644 index 0000000..53a5d33 --- /dev/null +++ b/node_modules/lodash/fp/zipObjectDeep.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zipObjectDeep', require('../zipObjectDeep')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fp/zipWith.js b/node_modules/lodash/fp/zipWith.js new file mode 100644 index 0000000..c5cf9e2 --- /dev/null +++ b/node_modules/lodash/fp/zipWith.js @@ -0,0 +1,5 @@ +var convert = require('./convert'), + func = convert('zipWith', require('../zipWith')); + +func.placeholder = require('./placeholder'); +module.exports = func; diff --git a/node_modules/lodash/fromPairs.js b/node_modules/lodash/fromPairs.js new file mode 100644 index 0000000..ee7940d --- /dev/null +++ b/node_modules/lodash/fromPairs.js @@ -0,0 +1,28 @@ +/** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ +function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; +} + +module.exports = fromPairs; diff --git a/node_modules/lodash/function.js b/node_modules/lodash/function.js new file mode 100644 index 0000000..b0fc6d9 --- /dev/null +++ b/node_modules/lodash/function.js @@ -0,0 +1,25 @@ +module.exports = { + 'after': require('./after'), + 'ary': require('./ary'), + 'before': require('./before'), + 'bind': require('./bind'), + 'bindKey': require('./bindKey'), + 'curry': require('./curry'), + 'curryRight': require('./curryRight'), + 'debounce': require('./debounce'), + 'defer': require('./defer'), + 'delay': require('./delay'), + 'flip': require('./flip'), + 'memoize': require('./memoize'), + 'negate': require('./negate'), + 'once': require('./once'), + 'overArgs': require('./overArgs'), + 'partial': require('./partial'), + 'partialRight': require('./partialRight'), + 'rearg': require('./rearg'), + 'rest': require('./rest'), + 'spread': require('./spread'), + 'throttle': require('./throttle'), + 'unary': require('./unary'), + 'wrap': require('./wrap') +}; diff --git a/node_modules/lodash/functions.js b/node_modules/lodash/functions.js new file mode 100644 index 0000000..9722928 --- /dev/null +++ b/node_modules/lodash/functions.js @@ -0,0 +1,31 @@ +var baseFunctions = require('./_baseFunctions'), + keys = require('./keys'); + +/** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ +function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); +} + +module.exports = functions; diff --git a/node_modules/lodash/functionsIn.js b/node_modules/lodash/functionsIn.js new file mode 100644 index 0000000..f00345d --- /dev/null +++ b/node_modules/lodash/functionsIn.js @@ -0,0 +1,31 @@ +var baseFunctions = require('./_baseFunctions'), + keysIn = require('./keysIn'); + +/** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ +function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); +} + +module.exports = functionsIn; diff --git a/node_modules/lodash/get.js b/node_modules/lodash/get.js new file mode 100644 index 0000000..8805ff9 --- /dev/null +++ b/node_modules/lodash/get.js @@ -0,0 +1,33 @@ +var baseGet = require('./_baseGet'); + +/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ +function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; +} + +module.exports = get; diff --git a/node_modules/lodash/groupBy.js b/node_modules/lodash/groupBy.js new file mode 100644 index 0000000..babf4f6 --- /dev/null +++ b/node_modules/lodash/groupBy.js @@ -0,0 +1,41 @@ +var baseAssignValue = require('./_baseAssignValue'), + createAggregator = require('./_createAggregator'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ +var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } +}); + +module.exports = groupBy; diff --git a/node_modules/lodash/gt.js b/node_modules/lodash/gt.js new file mode 100644 index 0000000..3a66282 --- /dev/null +++ b/node_modules/lodash/gt.js @@ -0,0 +1,29 @@ +var baseGt = require('./_baseGt'), + createRelationalOperation = require('./_createRelationalOperation'); + +/** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @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`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ +var gt = createRelationalOperation(baseGt); + +module.exports = gt; diff --git a/node_modules/lodash/gte.js b/node_modules/lodash/gte.js new file mode 100644 index 0000000..4180a68 --- /dev/null +++ b/node_modules/lodash/gte.js @@ -0,0 +1,30 @@ +var createRelationalOperation = require('./_createRelationalOperation'); + +/** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ +var gte = createRelationalOperation(function(value, other) { + return value >= other; +}); + +module.exports = gte; diff --git a/node_modules/lodash/has.js b/node_modules/lodash/has.js new file mode 100644 index 0000000..34df55e --- /dev/null +++ b/node_modules/lodash/has.js @@ -0,0 +1,35 @@ +var baseHas = require('./_baseHas'), + hasPath = require('./_hasPath'); + +/** + * 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 && hasPath(object, path, baseHas); +} + +module.exports = has; diff --git a/node_modules/lodash/hasIn.js b/node_modules/lodash/hasIn.js new file mode 100644 index 0000000..06a3686 --- /dev/null +++ b/node_modules/lodash/hasIn.js @@ -0,0 +1,34 @@ +var baseHasIn = require('./_baseHasIn'), + hasPath = require('./_hasPath'); + +/** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @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 = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ +function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); +} + +module.exports = hasIn; diff --git a/node_modules/lodash/head.js b/node_modules/lodash/head.js new file mode 100644 index 0000000..dee9d1f --- /dev/null +++ b/node_modules/lodash/head.js @@ -0,0 +1,23 @@ +/** + * 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; +} + +module.exports = head; diff --git a/node_modules/lodash/identity.js b/node_modules/lodash/identity.js new file mode 100644 index 0000000..2d5d963 --- /dev/null +++ b/node_modules/lodash/identity.js @@ -0,0 +1,21 @@ +/** + * 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; +} + +module.exports = identity; diff --git a/node_modules/lodash/inRange.js b/node_modules/lodash/inRange.js new file mode 100644 index 0000000..f20728d --- /dev/null +++ b/node_modules/lodash/inRange.js @@ -0,0 +1,55 @@ +var baseInRange = require('./_baseInRange'), + toFinite = require('./toFinite'), + toNumber = require('./toNumber'); + +/** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] 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`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ +function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); +} + +module.exports = inRange; diff --git a/node_modules/lodash/includes.js b/node_modules/lodash/includes.js new file mode 100644 index 0000000..ae0deed --- /dev/null +++ b/node_modules/lodash/includes.js @@ -0,0 +1,53 @@ +var baseIndexOf = require('./_baseIndexOf'), + isArrayLike = require('./isArrayLike'), + isString = require('./isString'), + toInteger = require('./toInteger'), + values = require('./values'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ +function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); +} + +module.exports = includes; diff --git a/node_modules/lodash/index.js b/node_modules/lodash/index.js new file mode 100644 index 0000000..5d063e2 --- /dev/null +++ b/node_modules/lodash/index.js @@ -0,0 +1 @@ +module.exports = require('./lodash'); \ No newline at end of file diff --git a/node_modules/lodash/indexOf.js b/node_modules/lodash/indexOf.js new file mode 100644 index 0000000..3c644af --- /dev/null +++ b/node_modules/lodash/indexOf.js @@ -0,0 +1,42 @@ +var baseIndexOf = require('./_baseIndexOf'), + toInteger = require('./toInteger'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * 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 (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); +} + +module.exports = indexOf; diff --git a/node_modules/lodash/initial.js b/node_modules/lodash/initial.js new file mode 100644 index 0000000..f47fc50 --- /dev/null +++ b/node_modules/lodash/initial.js @@ -0,0 +1,22 @@ +var baseSlice = require('./_baseSlice'); + +/** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ +function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; +} + +module.exports = initial; diff --git a/node_modules/lodash/intersection.js b/node_modules/lodash/intersection.js new file mode 100644 index 0000000..a94c135 --- /dev/null +++ b/node_modules/lodash/intersection.js @@ -0,0 +1,30 @@ +var arrayMap = require('./_arrayMap'), + baseIntersection = require('./_baseIntersection'), + baseRest = require('./_baseRest'), + castArrayLikeObject = require('./_castArrayLikeObject'); + +/** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ +var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; +}); + +module.exports = intersection; diff --git a/node_modules/lodash/intersectionBy.js b/node_modules/lodash/intersectionBy.js new file mode 100644 index 0000000..31461aa --- /dev/null +++ b/node_modules/lodash/intersectionBy.js @@ -0,0 +1,45 @@ +var arrayMap = require('./_arrayMap'), + baseIntersection = require('./_baseIntersection'), + baseIteratee = require('./_baseIteratee'), + baseRest = require('./_baseRest'), + castArrayLikeObject = require('./_castArrayLikeObject'), + last = require('./last'); + +/** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ +var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, baseIteratee(iteratee, 2)) + : []; +}); + +module.exports = intersectionBy; diff --git a/node_modules/lodash/intersectionWith.js b/node_modules/lodash/intersectionWith.js new file mode 100644 index 0000000..63cabfa --- /dev/null +++ b/node_modules/lodash/intersectionWith.js @@ -0,0 +1,41 @@ +var arrayMap = require('./_arrayMap'), + baseIntersection = require('./_baseIntersection'), + baseRest = require('./_baseRest'), + castArrayLikeObject = require('./_castArrayLikeObject'), + last = require('./last'); + +/** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ +var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; +}); + +module.exports = intersectionWith; diff --git a/node_modules/lodash/invert.js b/node_modules/lodash/invert.js new file mode 100644 index 0000000..8c47950 --- /dev/null +++ b/node_modules/lodash/invert.js @@ -0,0 +1,42 @@ +var constant = require('./constant'), + createInverter = require('./_createInverter'), + identity = require('./identity'); + +/** 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; + +/** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ +var invert = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + result[value] = key; +}, constant(identity)); + +module.exports = invert; diff --git a/node_modules/lodash/invertBy.js b/node_modules/lodash/invertBy.js new file mode 100644 index 0000000..3f4f7e5 --- /dev/null +++ b/node_modules/lodash/invertBy.js @@ -0,0 +1,56 @@ +var baseIteratee = require('./_baseIteratee'), + createInverter = require('./_createInverter'); + +/** 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; + +/** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ +var invertBy = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } +}, baseIteratee); + +module.exports = invertBy; diff --git a/node_modules/lodash/invoke.js b/node_modules/lodash/invoke.js new file mode 100644 index 0000000..97d51eb --- /dev/null +++ b/node_modules/lodash/invoke.js @@ -0,0 +1,24 @@ +var baseInvoke = require('./_baseInvoke'), + baseRest = require('./_baseRest'); + +/** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ +var invoke = baseRest(baseInvoke); + +module.exports = invoke; diff --git a/node_modules/lodash/invokeMap.js b/node_modules/lodash/invokeMap.js new file mode 100644 index 0000000..8da5126 --- /dev/null +++ b/node_modules/lodash/invokeMap.js @@ -0,0 +1,41 @@ +var apply = require('./_apply'), + baseEach = require('./_baseEach'), + baseInvoke = require('./_baseInvoke'), + baseRest = require('./_baseRest'), + isArrayLike = require('./isArrayLike'); + +/** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ +var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result; +}); + +module.exports = invokeMap; diff --git a/node_modules/lodash/isArguments.js b/node_modules/lodash/isArguments.js new file mode 100644 index 0000000..8b9ed66 --- /dev/null +++ b/node_modules/lodash/isArguments.js @@ -0,0 +1,36 @@ +var baseIsArguments = require('./_baseIsArguments'), + isObjectLike = require('./isObjectLike'); + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; + +/** + * 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'); +}; + +module.exports = isArguments; diff --git a/node_modules/lodash/isArray.js b/node_modules/lodash/isArray.js new file mode 100644 index 0000000..88ab55f --- /dev/null +++ b/node_modules/lodash/isArray.js @@ -0,0 +1,26 @@ +/** + * 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; + +module.exports = isArray; diff --git a/node_modules/lodash/isArrayBuffer.js b/node_modules/lodash/isArrayBuffer.js new file mode 100644 index 0000000..12904a6 --- /dev/null +++ b/node_modules/lodash/isArrayBuffer.js @@ -0,0 +1,27 @@ +var baseIsArrayBuffer = require('./_baseIsArrayBuffer'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer; + +/** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ +var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + +module.exports = isArrayBuffer; diff --git a/node_modules/lodash/isArrayLike.js b/node_modules/lodash/isArrayLike.js new file mode 100644 index 0000000..0f96680 --- /dev/null +++ b/node_modules/lodash/isArrayLike.js @@ -0,0 +1,33 @@ +var isFunction = require('./isFunction'), + isLength = require('./isLength'); + +/** + * 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); +} + +module.exports = isArrayLike; diff --git a/node_modules/lodash/isArrayLikeObject.js b/node_modules/lodash/isArrayLikeObject.js new file mode 100644 index 0000000..6c4812a --- /dev/null +++ b/node_modules/lodash/isArrayLikeObject.js @@ -0,0 +1,33 @@ +var isArrayLike = require('./isArrayLike'), + isObjectLike = require('./isObjectLike'); + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +module.exports = isArrayLikeObject; diff --git a/node_modules/lodash/isBoolean.js b/node_modules/lodash/isBoolean.js new file mode 100644 index 0000000..a43ed4b --- /dev/null +++ b/node_modules/lodash/isBoolean.js @@ -0,0 +1,29 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]'; + +/** + * 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); +} + +module.exports = isBoolean; diff --git a/node_modules/lodash/isBuffer.js b/node_modules/lodash/isBuffer.js new file mode 100644 index 0000000..c103cc7 --- /dev/null +++ b/node_modules/lodash/isBuffer.js @@ -0,0 +1,38 @@ +var root = require('./_root'), + stubFalse = require('./stubFalse'); + +/** 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; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; + +module.exports = isBuffer; diff --git a/node_modules/lodash/isDate.js b/node_modules/lodash/isDate.js new file mode 100644 index 0000000..7f0209f --- /dev/null +++ b/node_modules/lodash/isDate.js @@ -0,0 +1,27 @@ +var baseIsDate = require('./_baseIsDate'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsDate = nodeUtil && nodeUtil.isDate; + +/** + * 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 = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + +module.exports = isDate; diff --git a/node_modules/lodash/isElement.js b/node_modules/lodash/isElement.js new file mode 100644 index 0000000..76ae29c --- /dev/null +++ b/node_modules/lodash/isElement.js @@ -0,0 +1,25 @@ +var isObjectLike = require('./isObjectLike'), + isPlainObject = require('./isPlainObject'); + +/** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ +function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); +} + +module.exports = isElement; diff --git a/node_modules/lodash/isEmpty.js b/node_modules/lodash/isEmpty.js new file mode 100644 index 0000000..3597294 --- /dev/null +++ b/node_modules/lodash/isEmpty.js @@ -0,0 +1,77 @@ +var baseKeys = require('./_baseKeys'), + getTag = require('./_getTag'), + isArguments = require('./isArguments'), + isArray = require('./isArray'), + isArrayLike = require('./isArrayLike'), + isBuffer = require('./isBuffer'), + isPrototype = require('./_isPrototype'), + isTypedArray = require('./isTypedArray'); + +/** `Object#toString` result references. */ +var mapTag = '[object Map]', + setTag = '[object Set]'; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * 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 (value == null) { + return true; + } + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; +} + +module.exports = isEmpty; diff --git a/node_modules/lodash/isEqual.js b/node_modules/lodash/isEqual.js new file mode 100644 index 0000000..5e23e76 --- /dev/null +++ b/node_modules/lodash/isEqual.js @@ -0,0 +1,35 @@ +var baseIsEqual = require('./_baseIsEqual'); + +/** + * 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); +} + +module.exports = isEqual; diff --git a/node_modules/lodash/isEqualWith.js b/node_modules/lodash/isEqualWith.js new file mode 100644 index 0000000..21bdc7f --- /dev/null +++ b/node_modules/lodash/isEqualWith.js @@ -0,0 +1,41 @@ +var baseIsEqual = require('./_baseIsEqual'); + +/** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ +function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; +} + +module.exports = isEqualWith; diff --git a/node_modules/lodash/isError.js b/node_modules/lodash/isError.js new file mode 100644 index 0000000..b4f41e0 --- /dev/null +++ b/node_modules/lodash/isError.js @@ -0,0 +1,36 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'), + isPlainObject = require('./isPlainObject'); + +/** `Object#toString` result references. */ +var domExcTag = '[object DOMException]', + errorTag = '[object Error]'; + +/** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ +function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag || tag == domExcTag || + (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); +} + +module.exports = isError; diff --git a/node_modules/lodash/isFinite.js b/node_modules/lodash/isFinite.js new file mode 100644 index 0000000..601842b --- /dev/null +++ b/node_modules/lodash/isFinite.js @@ -0,0 +1,36 @@ +var root = require('./_root'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = root.isFinite; + +/** + * 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); +} + +module.exports = isFinite; diff --git a/node_modules/lodash/isFunction.js b/node_modules/lodash/isFunction.js new file mode 100644 index 0000000..907a8cd --- /dev/null +++ b/node_modules/lodash/isFunction.js @@ -0,0 +1,37 @@ +var baseGetTag = require('./_baseGetTag'), + isObject = require('./isObject'); + +/** `Object#toString` result references. */ +var asyncTag = '[object AsyncFunction]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; + +/** + * 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; +} + +module.exports = isFunction; diff --git a/node_modules/lodash/isInteger.js b/node_modules/lodash/isInteger.js new file mode 100644 index 0000000..66aa87d --- /dev/null +++ b/node_modules/lodash/isInteger.js @@ -0,0 +1,33 @@ +var toInteger = require('./toInteger'); + +/** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ +function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); +} + +module.exports = isInteger; diff --git a/node_modules/lodash/isLength.js b/node_modules/lodash/isLength.js new file mode 100644 index 0000000..3a95caa --- /dev/null +++ b/node_modules/lodash/isLength.js @@ -0,0 +1,35 @@ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** + * 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; +} + +module.exports = isLength; diff --git a/node_modules/lodash/isMap.js b/node_modules/lodash/isMap.js new file mode 100644 index 0000000..44f8517 --- /dev/null +++ b/node_modules/lodash/isMap.js @@ -0,0 +1,27 @@ +var baseIsMap = require('./_baseIsMap'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsMap = nodeUtil && nodeUtil.isMap; + +/** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ +var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + +module.exports = isMap; diff --git a/node_modules/lodash/isMatch.js b/node_modules/lodash/isMatch.js new file mode 100644 index 0000000..9773a18 --- /dev/null +++ b/node_modules/lodash/isMatch.js @@ -0,0 +1,36 @@ +var baseIsMatch = require('./_baseIsMatch'), + getMatchData = require('./_getMatchData'); + +/** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * 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. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ +function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); +} + +module.exports = isMatch; diff --git a/node_modules/lodash/isMatchWith.js b/node_modules/lodash/isMatchWith.js new file mode 100644 index 0000000..187b6a6 --- /dev/null +++ b/node_modules/lodash/isMatchWith.js @@ -0,0 +1,41 @@ +var baseIsMatch = require('./_baseIsMatch'), + getMatchData = require('./_getMatchData'); + +/** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ +function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); +} + +module.exports = isMatchWith; diff --git a/node_modules/lodash/isNaN.js b/node_modules/lodash/isNaN.js new file mode 100644 index 0000000..7d0d783 --- /dev/null +++ b/node_modules/lodash/isNaN.js @@ -0,0 +1,38 @@ +var isNumber = require('./isNumber'); + +/** + * 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; +} + +module.exports = isNaN; diff --git a/node_modules/lodash/isNative.js b/node_modules/lodash/isNative.js new file mode 100644 index 0000000..f0cb8d5 --- /dev/null +++ b/node_modules/lodash/isNative.js @@ -0,0 +1,40 @@ +var baseIsNative = require('./_baseIsNative'), + isMaskable = require('./_isMaskable'); + +/** Error message constants. */ +var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.'; + +/** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ +function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); +} + +module.exports = isNative; diff --git a/node_modules/lodash/isNil.js b/node_modules/lodash/isNil.js new file mode 100644 index 0000000..79f0505 --- /dev/null +++ b/node_modules/lodash/isNil.js @@ -0,0 +1,25 @@ +/** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ +function isNil(value) { + return value == null; +} + +module.exports = isNil; diff --git a/node_modules/lodash/isNull.js b/node_modules/lodash/isNull.js new file mode 100644 index 0000000..c0a374d --- /dev/null +++ b/node_modules/lodash/isNull.js @@ -0,0 +1,22 @@ +/** + * 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; +} + +module.exports = isNull; diff --git a/node_modules/lodash/isNumber.js b/node_modules/lodash/isNumber.js new file mode 100644 index 0000000..cd34ee4 --- /dev/null +++ b/node_modules/lodash/isNumber.js @@ -0,0 +1,38 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var numberTag = '[object Number]'; + +/** + * 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); +} + +module.exports = isNumber; diff --git a/node_modules/lodash/isObject.js b/node_modules/lodash/isObject.js new file mode 100644 index 0000000..1dc8939 --- /dev/null +++ b/node_modules/lodash/isObject.js @@ -0,0 +1,31 @@ +/** + * 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'); +} + +module.exports = isObject; diff --git a/node_modules/lodash/isObjectLike.js b/node_modules/lodash/isObjectLike.js new file mode 100644 index 0000000..301716b --- /dev/null +++ b/node_modules/lodash/isObjectLike.js @@ -0,0 +1,29 @@ +/** + * 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'; +} + +module.exports = isObjectLike; diff --git a/node_modules/lodash/isPlainObject.js b/node_modules/lodash/isPlainObject.js new file mode 100644 index 0000000..2387373 --- /dev/null +++ b/node_modules/lodash/isPlainObject.js @@ -0,0 +1,62 @@ +var baseGetTag = require('./_baseGetTag'), + getPrototype = require('./_getPrototype'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var objectTag = '[object Object]'; + +/** 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 infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); + +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; +} + +module.exports = isPlainObject; diff --git a/node_modules/lodash/isRegExp.js b/node_modules/lodash/isRegExp.js new file mode 100644 index 0000000..76c9b6e --- /dev/null +++ b/node_modules/lodash/isRegExp.js @@ -0,0 +1,27 @@ +var baseIsRegExp = require('./_baseIsRegExp'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp; + +/** + * 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 = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + +module.exports = isRegExp; diff --git a/node_modules/lodash/isSafeInteger.js b/node_modules/lodash/isSafeInteger.js new file mode 100644 index 0000000..2a48526 --- /dev/null +++ b/node_modules/lodash/isSafeInteger.js @@ -0,0 +1,37 @@ +var isInteger = require('./isInteger'); + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ +function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; +} + +module.exports = isSafeInteger; diff --git a/node_modules/lodash/isSet.js b/node_modules/lodash/isSet.js new file mode 100644 index 0000000..ab88bdf --- /dev/null +++ b/node_modules/lodash/isSet.js @@ -0,0 +1,27 @@ +var baseIsSet = require('./_baseIsSet'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsSet = nodeUtil && nodeUtil.isSet; + +/** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ +var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + +module.exports = isSet; diff --git a/node_modules/lodash/isString.js b/node_modules/lodash/isString.js new file mode 100644 index 0000000..627eb9c --- /dev/null +++ b/node_modules/lodash/isString.js @@ -0,0 +1,30 @@ +var baseGetTag = require('./_baseGetTag'), + isArray = require('./isArray'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var stringTag = '[object String]'; + +/** + * 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); +} + +module.exports = isString; diff --git a/node_modules/lodash/isSymbol.js b/node_modules/lodash/isSymbol.js new file mode 100644 index 0000000..dfb60b9 --- /dev/null +++ b/node_modules/lodash/isSymbol.js @@ -0,0 +1,29 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); +} + +module.exports = isSymbol; diff --git a/node_modules/lodash/isTypedArray.js b/node_modules/lodash/isTypedArray.js new file mode 100644 index 0000000..da3f8dd --- /dev/null +++ b/node_modules/lodash/isTypedArray.js @@ -0,0 +1,27 @@ +var baseIsTypedArray = require('./_baseIsTypedArray'), + baseUnary = require('./_baseUnary'), + nodeUtil = require('./_nodeUtil'); + +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + +module.exports = isTypedArray; diff --git a/node_modules/lodash/isUndefined.js b/node_modules/lodash/isUndefined.js new file mode 100644 index 0000000..377d121 --- /dev/null +++ b/node_modules/lodash/isUndefined.js @@ -0,0 +1,22 @@ +/** + * 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; +} + +module.exports = isUndefined; diff --git a/node_modules/lodash/isWeakMap.js b/node_modules/lodash/isWeakMap.js new file mode 100644 index 0000000..8d36f66 --- /dev/null +++ b/node_modules/lodash/isWeakMap.js @@ -0,0 +1,28 @@ +var getTag = require('./_getTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var weakMapTag = '[object WeakMap]'; + +/** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ +function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; +} + +module.exports = isWeakMap; diff --git a/node_modules/lodash/isWeakSet.js b/node_modules/lodash/isWeakSet.js new file mode 100644 index 0000000..e628b26 --- /dev/null +++ b/node_modules/lodash/isWeakSet.js @@ -0,0 +1,28 @@ +var baseGetTag = require('./_baseGetTag'), + isObjectLike = require('./isObjectLike'); + +/** `Object#toString` result references. */ +var weakSetTag = '[object WeakSet]'; + +/** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ +function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; +} + +module.exports = isWeakSet; diff --git a/node_modules/lodash/iteratee.js b/node_modules/lodash/iteratee.js new file mode 100644 index 0000000..61b73a8 --- /dev/null +++ b/node_modules/lodash/iteratee.js @@ -0,0 +1,53 @@ +var baseClone = require('./_baseClone'), + baseIteratee = require('./_baseIteratee'); + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1; + +/** + * 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'] + */ +function iteratee(func) { + return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); +} + +module.exports = iteratee; diff --git a/node_modules/lodash/join.js b/node_modules/lodash/join.js new file mode 100644 index 0000000..45de079 --- /dev/null +++ b/node_modules/lodash/join.js @@ -0,0 +1,26 @@ +/** Used for built-in method references. */ +var arrayProto = Array.prototype; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeJoin = arrayProto.join; + +/** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ +function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); +} + +module.exports = join; diff --git a/node_modules/lodash/kebabCase.js b/node_modules/lodash/kebabCase.js new file mode 100644 index 0000000..8a52be6 --- /dev/null +++ b/node_modules/lodash/kebabCase.js @@ -0,0 +1,28 @@ +var createCompounder = require('./_createCompounder'); + +/** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ +var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); +}); + +module.exports = kebabCase; diff --git a/node_modules/lodash/keyBy.js b/node_modules/lodash/keyBy.js new file mode 100644 index 0000000..acc007a --- /dev/null +++ b/node_modules/lodash/keyBy.js @@ -0,0 +1,36 @@ +var baseAssignValue = require('./_baseAssignValue'), + createAggregator = require('./_createAggregator'); + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ +var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); +}); + +module.exports = keyBy; diff --git a/node_modules/lodash/keys.js b/node_modules/lodash/keys.js new file mode 100644 index 0000000..d143c71 --- /dev/null +++ b/node_modules/lodash/keys.js @@ -0,0 +1,37 @@ +var arrayLikeKeys = require('./_arrayLikeKeys'), + baseKeys = require('./_baseKeys'), + isArrayLike = require('./isArrayLike'); + +/** + * 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'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +module.exports = keys; diff --git a/node_modules/lodash/keysIn.js b/node_modules/lodash/keysIn.js new file mode 100644 index 0000000..a62308f --- /dev/null +++ b/node_modules/lodash/keysIn.js @@ -0,0 +1,32 @@ +var arrayLikeKeys = require('./_arrayLikeKeys'), + baseKeysIn = require('./_baseKeysIn'), + isArrayLike = require('./isArrayLike'); + +/** + * 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) + */ +function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); +} + +module.exports = keysIn; diff --git a/node_modules/lodash/lang.js b/node_modules/lodash/lang.js new file mode 100644 index 0000000..a396216 --- /dev/null +++ b/node_modules/lodash/lang.js @@ -0,0 +1,58 @@ +module.exports = { + 'castArray': require('./castArray'), + 'clone': require('./clone'), + 'cloneDeep': require('./cloneDeep'), + 'cloneDeepWith': require('./cloneDeepWith'), + 'cloneWith': require('./cloneWith'), + 'conformsTo': require('./conformsTo'), + 'eq': require('./eq'), + 'gt': require('./gt'), + 'gte': require('./gte'), + 'isArguments': require('./isArguments'), + 'isArray': require('./isArray'), + 'isArrayBuffer': require('./isArrayBuffer'), + 'isArrayLike': require('./isArrayLike'), + 'isArrayLikeObject': require('./isArrayLikeObject'), + 'isBoolean': require('./isBoolean'), + 'isBuffer': require('./isBuffer'), + 'isDate': require('./isDate'), + 'isElement': require('./isElement'), + 'isEmpty': require('./isEmpty'), + 'isEqual': require('./isEqual'), + 'isEqualWith': require('./isEqualWith'), + 'isError': require('./isError'), + 'isFinite': require('./isFinite'), + 'isFunction': require('./isFunction'), + 'isInteger': require('./isInteger'), + 'isLength': require('./isLength'), + 'isMap': require('./isMap'), + 'isMatch': require('./isMatch'), + 'isMatchWith': require('./isMatchWith'), + 'isNaN': require('./isNaN'), + 'isNative': require('./isNative'), + 'isNil': require('./isNil'), + 'isNull': require('./isNull'), + 'isNumber': require('./isNumber'), + 'isObject': require('./isObject'), + 'isObjectLike': require('./isObjectLike'), + 'isPlainObject': require('./isPlainObject'), + 'isRegExp': require('./isRegExp'), + 'isSafeInteger': require('./isSafeInteger'), + 'isSet': require('./isSet'), + 'isString': require('./isString'), + 'isSymbol': require('./isSymbol'), + 'isTypedArray': require('./isTypedArray'), + 'isUndefined': require('./isUndefined'), + 'isWeakMap': require('./isWeakMap'), + 'isWeakSet': require('./isWeakSet'), + 'lt': require('./lt'), + 'lte': require('./lte'), + 'toArray': require('./toArray'), + 'toFinite': require('./toFinite'), + 'toInteger': require('./toInteger'), + 'toLength': require('./toLength'), + 'toNumber': require('./toNumber'), + 'toPlainObject': require('./toPlainObject'), + 'toSafeInteger': require('./toSafeInteger'), + 'toString': require('./toString') +}; diff --git a/node_modules/lodash/last.js b/node_modules/lodash/last.js new file mode 100644 index 0000000..cad1eaf --- /dev/null +++ b/node_modules/lodash/last.js @@ -0,0 +1,20 @@ +/** + * 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; +} + +module.exports = last; diff --git a/node_modules/lodash/lastIndexOf.js b/node_modules/lodash/lastIndexOf.js new file mode 100644 index 0000000..dabfb61 --- /dev/null +++ b/node_modules/lodash/lastIndexOf.js @@ -0,0 +1,46 @@ +var baseFindIndex = require('./_baseFindIndex'), + baseIsNaN = require('./_baseIsNaN'), + strictLastIndexOf = require('./_strictLastIndexOf'), + toInteger = require('./toInteger'); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max, + nativeMin = Math.min; + +/** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @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=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ +function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); +} + +module.exports = lastIndexOf; diff --git a/node_modules/lodash/lodash.js b/node_modules/lodash/lodash.js new file mode 100644 index 0000000..4131e93 --- /dev/null +++ b/node_modules/lodash/lodash.js @@ -0,0 +1,17209 @@ +/** + * @license + * Lodash + * 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'; + + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Error message constants. */ + var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', + FUNC_ERROR_TEXT = 'Expected a function', + INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; + + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; + + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; + + /** 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_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + 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 as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; + + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; + + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; + + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; + + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + + /** 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] + ]; + + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + domExcTag = '[object DOMException]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; + + 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 match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, + reUnescapedHtml = /[&<>"']/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; + + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + + /** Used to match leading whitespace. */ + var reTrimStart = /^\s+/; + + /** Used to match a single whitespace character. */ + var reWhitespace = /\s/; + + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; + + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + + /** + * Used to validate the `validate` option in `_.template` variable. + * + * Forbids characters which could potentially change the meaning of the function argument definition: + * - "()," (modification of function parameters) + * - "=" (default value) + * - "[]{}" (destructuring of function parameters) + * - "/" (beginning of a comment) + * - whitespace + */ + var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; + + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; + + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; + + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; + + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; + + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; + + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; + + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; + + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + + /** 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]", + rsAstral = '[' + rsAstralRange + ']', + 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, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); + + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); + + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + + /** 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'); + + /** 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 + ']'); + + /** 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 ]/; + + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', + 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' + ]; + + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; + + /** 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; + + /** 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; + + /** 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 to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; + + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; + + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; + + /** 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; + + /** 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) {} + }()); + + /* Node.js helper references. */ + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, + nodeIsDate = nodeUtil && nodeUtil.isDate, + nodeIsMap = nodeUtil && nodeUtil.isMap, + nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, + nodeIsSet = nodeUtil && nodeUtil.isSet, + nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /*--------------------------------------------------------------------------*/ + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); + + /** + * 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(''); + } + + /** + * 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) || []; + } + + /** + * 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; + } + + /** + * 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 `_.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); + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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 `_.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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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]]; + }); + } + + /** + * 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; + } + + /** + * 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); + }; + } + + /** + * 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]; + }); + } + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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); + + /** + * 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); + + /** + * 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]; + } + + /** + * 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]; + } + + /** + * 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); + } + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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)); + }; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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); + } + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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); + + /** + * 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; + } + + /** + * 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) || []; + } + + /** + * 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) || []; + } + + /*--------------------------------------------------------------------------*/ + + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + var runInContext = (function runInContext(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); + + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; + + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; + + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; + + /** 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 generate unique IDs. */ + var idCounter = 0; + + /** 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) : ''; + }()); + + /** + * 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 infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); + + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; + + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); + + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, + symIterator = Symbol ? Symbol.iterator : undefined, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; + + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); + + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; + + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); + + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; + + /** Used to lookup unminified function names. */ + var realNames = {}; + + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); + + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + + /*------------------------------------------------------------------------*/ + + /** + * 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) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return 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 function whose prototype chain sequence wrappers inherit from. + * + * @private + */ + function baseLodash() { + // No operation performed. + } + + /** + * 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; + } + + /** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. + * + * @static + * @memberOf _ + * @type {Object} + */ + lodash.templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': lodash + } + }; + + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; + + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * 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__ = []; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + + /** + * 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]); + } + } + + /** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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); + } + + /** + * 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; + } + + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + + /** + * 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]); + } + } + + /** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + + /** + * 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; + } + + /** + * 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]; + } + + /** + * 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; + } + + /** + * 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; + } + + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * 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]); + } + } + + /** + * 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 + }; + } + + /** + * 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; + } + + /** + * 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); + } + + /** + * 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); + } + + /** + * 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; + } + + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + + /*------------------------------------------------------------------------*/ + + /** + * + * 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]); + } + } + + /** + * 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; + } + + /** + * 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); + } + + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + + /*------------------------------------------------------------------------*/ + + /** + * 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; + } + + /** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; + } + + /** + * 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; + } + + /** + * 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); + } + + /** + * 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); + } + + /** + * 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; + } + + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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)); + } + + /** + * 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)); + } + + /** + * 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); + } + } + + /** + * 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); + } + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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); + } + + /** + * 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); + } + + /** + * 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; + } + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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); + }; + } + + /** + * 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; + } + + /** + * 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 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; + } + + /** + * 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 `_.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); + + /** + * 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 && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; + } + + /** + * 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; + } + + /** + * 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(); + + /** + * 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); + + /** + * 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 `_.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); + } + + /** + * 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]); + }); + } + + /** + * 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; + } + + /** + * 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)); + } + + /** + * 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); + } + + /** + * 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 `_.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); + } + + /** + * 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); + } + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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 : 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); + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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)); + } + + /** + * 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 `_.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; + } + + /** + * 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)]; + } + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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 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); + }; + } + + /** + * 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); + }; + } + + /** + * 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); + } + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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(getIteratee())); + + 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); + }); + } + + /** + * 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); + }); + } + + /** + * 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; + } + + /** + * 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); + }; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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)); + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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 `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ + function baseSample(collection) { + return arraySample(values(collection)); + } + + /** + * 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)); + } + + /** + * 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; + } + + /** + * 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; + }; + + /** + * 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 + }); + }; + + /** + * 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)); + } + + /** + * 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; + } + + /** + * 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 `_.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); + } + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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))]; + } + + /** + * 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); + } + + /** + * 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)); + } + + /** + * 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); + } + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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 : []; + } + + /** + * 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; + } + + /** + * 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)); + } + + /** + * 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; + + /** + * 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); + } + + /** + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). + * + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */ + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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)) : {}; + } + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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); + } + + /** + * 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); + } + + /** + * 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, getIteratee(iteratee, 2), accumulator); + }; + } + + /** + * 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; + }); + } + + /** + * 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 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; + } + + /** + * 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; + }; + } + + /** + * 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, ''); + }; + } + + /** + * 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; + }; + } + + /** + * 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; + } + + /** + * 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 = getIteratee(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 `_.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; + }; + }); + } + + /** + * 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; + } + + /** + * 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), {}); + }; + } + + /** + * 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; + }; + } + + /** + * 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(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); + } + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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); + }; + } + + /** + * 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); + }; + } + + /** + * 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); + } + + /** + * 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); + }; + } + + /** + * 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); + }; + + /** + * 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)); + }; + } + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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 + ''); + } + + /** + * 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); + } + + /** + * 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); + } + + /** + * 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); + }; + + /** + * 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; + } + + /** + * 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 = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; + } + + /** + * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, + * this function returns the custom method, otherwise it returns `baseIteratee`. + * If arguments are provided, the chosen function is invoked with them and + * its result is returned. + * + * @private + * @param {*} [value] The value to convert to an iteratee. + * @param {number} [arity] The arity of the created iteratee. + * @returns {Function} Returns the chosen function or its result. + */ + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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); + }); + }; + + /** + * 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; + }; + + /** + * 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; + }; + } + + /** + * 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 }; + } + + /** + * 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) : []; + } + + /** + * 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)); + } + + /** + * 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; + } + + /** + * 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)) + : {}; + } + + /** + * 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); + } + } + + /** + * 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'); + } + + /** + * 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]); + } + + /** + * 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; + } + + /** + * 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)); + } + + /** + * 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); + } + + /** + * 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]; + } + + /** + * 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); + } + + /** + * 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; + + /** + * 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; + } + + /** + * 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); + } + + /** + * 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))); + }; + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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 apply(func, this, otherArgs); + }; + } + + /** + * 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)); + } + + /** + * 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; + } + + /** + * 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]; + } + + /** + * 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); + + /** + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. + */ + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + + /** + * 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); + + /** + * 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))); + } + + /** + * 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); + }; + } + + /** + * 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; + } + + /** + * 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; + }); + + /** + * 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; + } + + /** + * 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 ''; + } + + /** + * 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(); + } + + /** + * 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; + } + + /*------------------------------------------------------------------------*/ + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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)); + } + + /** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; + }); + + /** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ + function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; + } + + /** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; + } + + /** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @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`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ + function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); + } + + /** + * 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, getIteratee(predicate, 3), index); + } + + /** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } + + /** + * 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) : []; + } + + /** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); + } + + /** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ + function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; + } + + /** + * 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 (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); + } + + /** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; + } + + /** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); + + /** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; + }); + + /** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ + function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); + } + + /** + * 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; + } + + /** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @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=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ + function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); + } + + /** + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. + * + * @static + * @memberOf _ + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; + */ + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + } + + /** + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] + */ + var pull = baseRest(pullAll); + + /** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */ + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; + } + + /** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */ + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; + } + + /** + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); + * + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] + */ + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; + }); + + /** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; + } + + /** + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function reverse(array) { + return array == null ? array : nativeReverse.call(array); + } + + /** + * 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; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + */ + function sortedIndex(array, value) { + return baseSortedIndex(array, value); + } + + /** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 + */ + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + } + + /** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */ + function sortedIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 + */ + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); + } + + /** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 + * + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 + */ + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + } + + /** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 + */ + function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; + } + + /** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */ + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; + } + + /** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] + */ + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; + } + + /** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.tail([1, 2, 3]); + * // => [2, 3] + */ + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; + } + + /** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ + function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); + } + + /** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ + function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); + } + + /** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */ + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; + } + + /** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] + */ + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; + } + + /** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + + /** + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); + + /** + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniq([2, 1, 2]); + * // => [2, 1] + */ + function uniq(array) { + return (array && array.length) ? baseUniq(array) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] + */ + function uniqBy(array, iteratee) { + return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + } + + /** + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + */ + function uniqWith(array, comparator) { + comparator = typeof comparator == 'function' ? comparator : undefined; + return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + } + + /** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + * + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] + */ + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } + + /** + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] + * + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] + */ + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); + } + + /** + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor + * @example + * + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */ + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; + }); + + /** + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without + * @example + * + * _.xor([2, 1], [2, 3]); + * // => [1, 3] + */ + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); + + /** + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] + * + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); + + /** + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + */ + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); + + /** + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + */ + var zip = baseRest(unzip); + + /** + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. + * + * @static + * @memberOf _ + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } + */ + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); + } + + /** + * This method is like `_.zipObject` except that it supports property paths. + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. + * @example + * + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + */ + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); + } + + /** + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine + * grouped values. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] + */ + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); + }); + + /*------------------------------------------------------------------------*/ + + /** + * 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); + } + + /** + * This method is the wrapper version of `_.at`. + * + * @name at + * @memberOf _ + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _(object).at(['a[0].b.c', 'a[1]']).value(); + * // => [3, 4] + */ + var wrapperAt = flatRest(function(paths) { + var length = paths.length, + start = length ? paths[0] : 0, + value = this.__wrapped__, + interceptor = function(object) { return baseAt(object, paths); }; + + if (length > 1 || this.__actions__.length || + !(value instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value = value.slice(start, +start + (length ? 1 : 0)); + value.__actions__.push({ + 'func': thru, + 'args': [interceptor], + 'thisArg': undefined + }); + return new LodashWrapper(value, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined); + } + return array; + }); + }); + + /** + * 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 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__); + } + + /** + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * + * @name next + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } + */ + function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; + } + + /** + * Enables the wrapper to be iterable. + * + * @name Symbol.iterator + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the wrapper object. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped[Symbol.iterator]() === wrapped; + * // => true + * + * Array.from(wrapped); + * // => [1, 2] + */ + function wrapperToIterator() { + return this; + } + + /** + * Creates a clone of the chain sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */ + function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; + } + + /** + * This method is the wrapper version of `_.reverse`. + * + * **Note:** This method mutates the wrapped array. + * + * @name reverse + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2, 3]; + * + * _(array).reverse().value() + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ + function wrapperReverse() { + var value = this.__wrapped__; + if (value instanceof LazyWrapper) { + var wrapped = value; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + 'func': thru, + 'args': [reverse], + 'thisArg': undefined + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + + /** + * 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__); + } + + /*------------------------------------------------------------------------*/ + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ + var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } + }); + + /** + * 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) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * 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) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); + } + + /** + * 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); + + /** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ + var findLast = createFind(findLastIndex); + + /** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.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 flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.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 flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ + function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY); + } + + /** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ + function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); + } + + /** + * 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) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @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 _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ + function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ + var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } + }); + + /** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ + function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + } + + /** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result; + }); + + /** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ + var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); + }); + + /** + * 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) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. 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. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */ + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); + } + + /** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.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 array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */ + var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); + }, function() { return [[], []]; }); + + /** + * 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) { + var func = isArray(collection) ? arrayReduce : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + } + + /** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @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 _.reduce + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ + function reduceRight(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + } + + /** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @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 _.filter + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] + */ + function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); + } + + /** + * Gets a random element from `collection`. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + */ + function sample(collection) { + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); + } + + /** + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. + * @example + * + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] + * + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] + */ + function sampleSize(collection, n, guard) { + if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); + } + + /** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ + function shuffle(collection) { + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); + } + + /** + * 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; + } + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(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) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, getIteratee(predicate, 3)); + } + + /** + * 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]] + */ + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + + /*------------------------------------------------------------------------*/ + + /** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ + var now = ctxNow || function() { + return root.Date.now(); + }; + + /*------------------------------------------------------------------------*/ + + /** + * 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); + } + }; + } + + /** + * 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); + } + + /** + * 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) { + 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); + }); + + /** + * 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); + }); + + /** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ + function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; + } + + /** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ + function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; + } + + /** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ + function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + timeWaiting = wait - timeSinceLastCall; + + return maxing + ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) + : timeWaiting; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + clearTimeout(timerId); + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + } + + /** + * 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 invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ + function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); + } + + /** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ + function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; + } + + // Expose `MapCache`. + memoize.Cache = MapCache; + + /** + * 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; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + 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 function that invokes `func` with its arguments transformed. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); + * + * func(9, 3); + * // => [81, 6] + * + * func(10, 5); + * // => [100, 10] + */ + var overArgs = castRest(function(func, transforms) { + transforms = (transforms.length == 1 && isArray(transforms[0])) + ? arrayMap(transforms[0], baseUnary(getIteratee())) + : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, + length = nativeMin(args.length, funcsLength); + + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); + }); + + /** + * Creates a function that invokes `func` with `partials` prepended to the + * arguments it receives. This method is like `_.bind` except it does **not** + * alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 0.2.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); + }); + + /** + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); + }); + + /** + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + */ + var rearg = flatRest(function(func, indexes) { + return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); + }); + + /** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @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. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ + function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); + } + + /** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ + function spread(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + start = start == null ? 0 : nativeMax(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], + otherArgs = castSlice(args, 0, start); + + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); + } + + /** + * Creates a throttled function that only invokes `func` at most once per + * every `wait` milliseconds. The throttled function comes with a `cancel` + * method to cancel delayed `func` invocations and a `flush` method to + * immediately invoke them. Provide `options` to indicate whether `func` + * should be invoked on the leading and/or trailing edge of the `wait` + * timeout. The `func` is invoked with the last arguments provided to the + * throttled function. Subsequent calls to the throttled function return the + * result of the last `func` invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the throttled function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.throttle` and `_.debounce`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to throttle. + * @param {number} [wait=0] The number of milliseconds to throttle invocations to. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=true] + * Specify invoking on the leading edge of the timeout. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new throttled function. + * @example + * + * // Avoid excessively updating the position while scrolling. + * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * + * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. + * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); + * jQuery(element).on('click', throttled); + * + * // Cancel the trailing throttled invocation. + * jQuery(window).on('popstate', throttled.cancel); + */ + function throttle(func, wait, options) { + var leading = true, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (isObject(options)) { + leading = 'leading' in options ? !!options.leading : leading; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + 'leading': leading, + 'maxWait': wait, + 'trailing': trailing + }); + } + + /** + * Creates a function that accepts up to one argument, ignoring any + * additional arguments. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.unary(parseInt)); + * // => [6, 8, 10] + */ + function unary(func) { + return ary(func, 1); + } + + /** + * Creates a function that provides `value` to `wrapper` as its first + * argument. Any additional arguments provided to the function are appended + * to those provided to the `wrapper`. The wrapper is invoked with the `this` + * binding of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {*} value The value to wrap. + * @param {Function} [wrapper=identity] The wrapper function. + * @returns {Function} Returns the new function. + * @example + * + * var p = _.wrap(_.escape, function(func, text) { + * return '

' + func(text) + '

'; + * }); + * + * p('fred, barney, & pebbles'); + * // => '

fred, barney, & pebbles

' + */ + function wrap(value, wrapper) { + return partial(castFunction(wrapper), value); + } + + /*------------------------------------------------------------------------*/ + + /** + * 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]; + } + + /** + * 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); + } + + /** + * 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); + } + + /** + * 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); + } + + /** + * 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); + } + + /** + * 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)); + } + + /** + * 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 greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @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`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ + var gt = createRelationalOperation(baseGt); + + /** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ + var gte = createRelationalOperation(function(value, other) { + return value >= 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 classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + + /** + * 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); + } + + /** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ + function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(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 a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ + var isBuffer = nativeIsBuffer || stubFalse; + + /** + * 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 = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + + /** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ + function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + } + + /** + * 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 (value == null) { + return true; + } + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag(value); + if (tag == mapTag || tag == setTag) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty.call(value, key)) { + return false; + } + } + return true; + } + + /** + * 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); + } + + /** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ + function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; + } + + /** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ + function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag || tag == domExcTag || + (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); + } + + /** + * 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 an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ + function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); + } + + /** + * 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 classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + + /** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * 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. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); + } + + /** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + + /** + * 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 a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ + function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(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 `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ + function isNil(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 a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ + function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; + } + + /** + * 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 = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + + /** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ + function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + } + + /** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + + /** + * 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 classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ + function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag); + } + + /** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + + /** + * 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; + } + + /** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ + function isWeakMap(value) { + return isObjectLike(value) && getTag(value) == weakMapTag; + } + + /** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ + function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; + } + + /** + * Checks if `value` is less than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @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`. + * @see _.gt + * @example + * + * _.lt(1, 3); + * // => true + * + * _.lt(3, 3); + * // => false + * + * _.lt(3, 1); + * // => false + */ + var lt = createRelationalOperation(baseLt); + + /** + * Checks if `value` is less than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte + * @example + * + * _.lte(1, 3); + * // => true + * + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */ + var lte = createRelationalOperation(function(value, other) { + return value <= other; + }); + + /** + * 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 (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (symIterator && value[symIterator]) { + return iteratorToArray(value[symIterator]()); + } + var tag = getTag(value), + func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); + + return func(value); + } + + /** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ + function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; + } + + /** + * 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 + */ + function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; + } + + /** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is 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 convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toLength(3.2); + * // => 3 + * + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 + */ + function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + } + + /** + * 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 + */ + function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = baseTrim(value); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); + } + + /** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ + function toPlainObject(value) { + return copyObject(value, keysIn(value)); + } + + /** + * Converts `value` to a safe integer. A safe integer can be compared and + * represented correctly. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toSafeInteger(3.2); + * // => 3 + * + * _.toSafeInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toSafeInteger(Infinity); + * // => 9007199254740991 + * + * _.toSafeInteger('3.2'); + * // => 3 + */ + function toSafeInteger(value) { + return value + ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) + : (value === 0 ? value : 0); + } + + /** + * 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) { + return value == null ? '' : baseToString(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) { + 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]); + } + } + }); + + /** + * 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); + }); + + /** + * 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); + }); + + /** + * 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); + }); + + /** + * 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); + + /** + * 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 : baseAssign(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; + }); + + /** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ + var defaultsDeep = baseRest(function(args) { + args.push(undefined, customDefaultsMerge); + return apply(mergeWith, undefined, args); + }); + + /** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + } + + /** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + } + + /** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ + function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ + function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, getIteratee(iteratee, 3), keysIn); + } + + /** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ + function forOwn(object, iteratee) { + return object && baseForOwn(object, getIteratee(iteratee, 3)); + } + + /** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ + function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + } + + /** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ + function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); + } + + /** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); + } + + /** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ + function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; + } + + /** + * 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 && hasPath(object, path, baseHas); + } + + /** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @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 = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + + /** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ + var invert = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + result[value] = key; + }, constant(identity)); + + /** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ + var invertBy = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + if (hasOwnProperty.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } + }, getIteratee); + + /** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ + var invoke = baseRest(baseInvoke); + + /** + * 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'] + */ + function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + + /** + * 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) + */ + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + + /** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ + function mapKeys(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; + } + + /** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ + function mapValues(object, iteratee) { + var result = {}; + iteratee = getIteratee(iteratee, 3); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; + } + + /** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + + /** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **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`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */ + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); + + /** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable property paths of `object` that are not omitted. + * + * **Note:** This method is considerably slower than `_.pick`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to omit. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */ + var omit = flatRest(function(object, paths) { + var result = {}; + if (object == null) { + return result; + } + var isDeep = false; + paths = arrayMap(paths, function(path) { + path = castPath(path, object); + isDeep || (isDeep = path.length > 1); + return path; + }); + copyObject(object, getAllKeysIn(object), result); + if (isDeep) { + result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); + } + var length = paths.length; + while (length--) { + baseUnset(result, paths[length]); + } + return result; + }); + + /** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); + } + + /** + * 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); + }); + + /** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = getIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); + } + + /** + * 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) { + path = castPath(path, object); + + var index = -1, + length = path.length; + + // Ensure the loop is entered when path is empty. + if (!length) { + length = 1; + object = undefined; + } + while (++index < length) { + var value = object == null ? undefined : object[toKey(path[index])]; + if (value === undefined) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; + } + + /** + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */ + function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); + } + + /** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @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 assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */ + function setWith(object, path, value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); + } + + /** + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */ + var toPairs = createToPairs(keys); + + /** + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + */ + var toPairsIn = createToPairs(keysIn); + + /** + * An alternative to `_.reduce`; this method transforms `object` to a new + * `accumulator` object which is the result of running each of its own + * enumerable string keyed properties thru `iteratee`, with each invocation + * potentially mutating the `accumulator` object. If `accumulator` is not + * provided, a new object with the same `[[Prototype]]` will be used. The + * iteratee is invoked with four arguments: (accumulator, value, key, object). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The custom accumulator value. + * @returns {*} Returns the accumulated value. + * @example + * + * _.transform([2, 3, 4], function(result, n) { + * result.push(n *= n); + * return n % 2 == 0; + * }, []); + * // => [4, 9] + * + * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } + */ + function transform(object, iteratee, accumulator) { + var isArr = isArray(object), + isArrLike = isArr || isBuffer(object) || isTypedArray(object); + + iteratee = getIteratee(iteratee, 4); + if (accumulator == null) { + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor : []; + } + else if (isObject(object)) { + accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; + } + else { + accumulator = {}; + } + } + (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { + return iteratee(accumulator, value, index, object); + }); + return accumulator; + } + + /** + * Removes the property at `path` of `object`. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 7 } }] }; + * _.unset(object, 'a[0].b.c'); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + * + * _.unset(object, ['a', '0', 'b', 'c']); + * // => true + * + * console.log(object); + * // => { 'a': [{ 'b': {} }] }; + */ + function unset(object, path) { + return object == null ? true : baseUnset(object, path); + } + + /** + * This method is like `_.set` except that accepts `updater` to produce the + * value to set. Use `_.updateWith` to customize `path` creation. The `updater` + * is invoked with one argument: (value). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.update(object, 'a[0].b.c', function(n) { return n * n; }); + * console.log(object.a[0].b.c); + * // => 9 + * + * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); + * console.log(object.x[0].y.z); + * // => 0 + */ + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); + } + + /** + * This method is like `_.update` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.updateWith(object, '[0][1]', _.constant('a'), Object); + * // => { '0': { '1': 'a' } } + */ + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } + + /** + * 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)); + } + + /** + * Creates an array of the own and inherited enumerable string keyed property + * values 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 values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.valuesIn(new Foo); + * // => [1, 2, 3] (iteration order is not guaranteed) + */ + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + + /*------------------------------------------------------------------------*/ + + /** + * 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); + } + + /** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] 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`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); + } + + /** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ + function random(lower, upper, floating) { + if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined; + } + if (floating === undefined) { + if (typeof upper == 'boolean') { + floating = upper; + upper = undefined; + } + else if (typeof lower == 'boolean') { + floating = lower; + lower = undefined; + } + } + if (lower === undefined && upper === undefined) { + lower = 0; + upper = 1; + } + else { + lower = toFinite(lower); + if (upper === undefined) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); + } + return baseRandom(lower, upper); + } + + /*------------------------------------------------------------------------*/ + + /** + * 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); + }); + + /** + * 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()); + } + + /** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); + } + + /** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } + + /** + * 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; + } + + /** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ + function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; + } + + /** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ + var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); + }); + + /** + * Converts `string`, as space separated words, to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' + * + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */ + var lowerCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + word.toLowerCase(); + }); + + /** + * Converts the first character of `string` to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.lowerFirst('Fred'); + * // => 'fred' + * + * _.lowerFirst('FRED'); + * // => 'fRED' + */ + var lowerFirst = createCaseFirst('toLowerCase'); + + /** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ + function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return ( + createPadding(nativeFloor(mid), chars) + + string + + createPadding(nativeCeil(mid), chars) + ); + } + + /** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padEnd('abc', 6); + * // => 'abc ' + * + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */ + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (string + createPadding(length - strLength, chars)) + : string; + } + + /** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padStart('abc', 6); + * // => ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */ + function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (createPadding(length - strLength, chars) + string) + : string; + } + + /** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a + * hexadecimal, in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the + * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category String + * @param {string} string The string to convert. + * @param {number} [radix=10] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ + function parseInt(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); + } + + /** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ + function repeat(string, n, guard) { + if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); + } + + /** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. + * @example + * + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */ + function replace() { + var args = arguments, + string = toString(args[0]); + + return args.length < 3 ? string : string.replace(args[1], args[2]); + } + + /** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */ + var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); + }); + + /** + * Splits `string` by `separator`. + * + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. + * @example + * + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */ + function split(string, separator, limit) { + if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { + separator = limit = undefined; + } + limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && ( + typeof separator == 'string' || + (separator != null && !isRegExp(separator)) + )) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); + } + + /** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */ + var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + upperFirst(word); + }); + + /** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ + function startsWith(string, target, position) { + string = toString(string); + position = position == null + ? 0 + : baseClamp(toInteger(position), 0, string.length); + + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } + + /** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='lodash.templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. + * @example + * + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': '`; + // If the inner JS formatter removes the parens, the expression might change its meaning: + // f((a + b) / 2) vs f(a + b / 2) + if (node.extra && node.extra.parenthesized && /^PRETTIER_HTML_PLACEHOLDER_\d+_\d+_IN_JS$/.test(node.name)) { + return true; + } // `for (async of []);` is invalid + + + if (name === "left" && node.name === "async" && parent.type === "ForOfStatement" && !parent.await) { + return true; + } + + return false; + } + + switch (parent.type) { + case "ParenthesizedExpression": + return false; + + case "ClassDeclaration": + case "ClassExpression": + { + // Add parens around the extends clause of a class. It is needed for almost + // all expressions. + if (name === "superClass" && (node.type === "ArrowFunctionExpression" || node.type === "AssignmentExpression" || node.type === "AwaitExpression" || node.type === "BinaryExpression" || node.type === "ConditionalExpression" || node.type === "LogicalExpression" || node.type === "NewExpression" || node.type === "ObjectExpression" || node.type === "ParenthesizedExpression" || node.type === "SequenceExpression" || node.type === "TaggedTemplateExpression" || node.type === "UnaryExpression" || node.type === "UpdateExpression" || node.type === "YieldExpression" || node.type === "TSNonNullExpression")) { + return true; + } + + break; + } + + case "ExportDefaultDeclaration": + { + return (// `export default function` or `export default class` can't be followed by + // anything after. So an expression like `export default (function(){}).toString()` + // needs to be followed by a parentheses + shouldWrapFunctionForExportDefault(path, options) || // `export default (foo, bar)` also needs parentheses + node.type === "SequenceExpression" + ); + } + + case "Decorator": + { + if (name === "expression") { + let hasCallExpression = false; + let hasMemberExpression = false; + let current = node; + + while (current) { + switch (current.type) { + case "MemberExpression": + hasMemberExpression = true; + current = current.object; + break; + + case "CallExpression": + if ( + /** @(x().y) */ + hasMemberExpression || + /** @(x().y()) */ + hasCallExpression) { + return true; + } + + hasCallExpression = true; + current = current.callee; + break; + + case "Identifier": + return false; + + default: + return true; + } + } + + return true; + } + + break; + } + + case "ExpressionStatement": + { + if (startsWithNoLookaheadToken$1(node, + /* forbidFunctionClassAndDoExpr */ + true)) { + return true; + } + + break; + } + + case "ArrowFunctionExpression": + { + if (name === "body" && node.type !== "SequenceExpression" && // these have parens added anyway + startsWithNoLookaheadToken$1(node, + /* forbidFunctionClassAndDoExpr */ + false)) { + return true; + } + + break; + } + } + + switch (node.type) { + case "UpdateExpression": + if (parent.type === "UnaryExpression") { + return node.prefix && (node.operator === "++" && parent.operator === "+" || node.operator === "--" && parent.operator === "-"); + } + + // else fallthrough + + case "UnaryExpression": + switch (parent.type) { + case "UnaryExpression": + return node.operator === parent.operator && (node.operator === "+" || node.operator === "-"); + + case "BindExpression": + return true; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + case "TaggedTemplateExpression": + return true; + + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "BinaryExpression": + return name === "left" && parent.operator === "**"; + + case "TSNonNullExpression": + return true; + + default: + return false; + } + + case "BinaryExpression": + { + if (parent.type === "UpdateExpression" || parent.type === "PipelineTopicExpression" && node.operator === "|>") { + return true; + } // We add parentheses to any `a in b` inside `ForStatement` initializer + // https://github.com/prettier/prettier/issues/907#issuecomment-284304321 + + + if (node.operator === "in" && isPathInForStatementInitializer(path)) { + return true; + } + + if (node.operator === "|>" && node.extra && node.extra.parenthesized) { + const grandParent = path.getParentNode(1); + + if (grandParent.type === "BinaryExpression" && grandParent.operator === "|>") { + return true; + } + } + } + // fallthrough + + case "TSTypeAssertion": + case "TSAsExpression": + case "LogicalExpression": + switch (parent.type) { + case "TSAsExpression": + // example: foo as unknown as Bar + return node.type !== "TSAsExpression"; + + case "ConditionalExpression": + return node.type === "TSAsExpression"; + + case "CallExpression": + case "NewExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "ClassExpression": + case "ClassDeclaration": + return name === "superClass"; + + case "TSTypeAssertion": + case "TaggedTemplateExpression": + case "UnaryExpression": + case "JSXSpreadAttribute": + case "SpreadElement": + case "SpreadProperty": + case "BindExpression": + case "AwaitExpression": + case "TSNonNullExpression": + case "UpdateExpression": + return true; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + case "AssignmentExpression": + case "AssignmentPattern": + return name === "left" && (node.type === "TSTypeAssertion" || node.type === "TSAsExpression"); + + case "LogicalExpression": + if (node.type === "LogicalExpression") { + return parent.operator !== node.operator; + } + + // else fallthrough + + case "BinaryExpression": + { + const { + operator, + type + } = node; + + if (!operator && type !== "TSTypeAssertion") { + return true; + } + + const precedence = getPrecedence(operator); + const parentOperator = parent.operator; + const parentPrecedence = getPrecedence(parentOperator); + + if (parentPrecedence > precedence) { + return true; + } + + if (name === "right" && parentPrecedence === precedence) { + return true; + } + + if (parentPrecedence === precedence && !shouldFlatten$1(parentOperator, operator)) { + return true; + } + + if (parentPrecedence < precedence && operator === "%") { + return parentOperator === "+" || parentOperator === "-"; + } // Add parenthesis when working with bitwise operators + // It's not strictly needed but helps with code understanding + + + if (isBitwiseOperator(parentOperator)) { + return true; + } + + return false; + } + + default: + return false; + } + + case "SequenceExpression": + switch (parent.type) { + case "ReturnStatement": + return false; + + case "ForStatement": + // Although parentheses wouldn't hurt around sequence + // expressions in the head of for loops, traditional style + // dictates that e.g. i++, j++ should not be wrapped with + // parentheses. + return false; + + case "ExpressionStatement": + return name !== "expression"; + + case "ArrowFunctionExpression": + // We do need parentheses, but SequenceExpressions are handled + // specially when printing bodies of arrow functions. + return name !== "body"; + + default: + // Otherwise err on the side of overparenthesization, adding + // explicit exceptions above if this proves overzealous. + return true; + } + + case "YieldExpression": + if (parent.type === "UnaryExpression" || parent.type === "AwaitExpression" || parent.type === "TSAsExpression" || parent.type === "TSNonNullExpression") { + return true; + } + + if (name === "expression" && node.argument && node.argument.type === "PipelinePrimaryTopicReference" && parent.type === "PipelineTopicExpression") { + return true; + } + + // else fallthrough + + case "AwaitExpression": + switch (parent.type) { + case "TaggedTemplateExpression": + case "UnaryExpression": + case "LogicalExpression": + case "SpreadElement": + case "SpreadProperty": + case "TSAsExpression": + case "TSNonNullExpression": + case "BindExpression": + return true; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "ConditionalExpression": + return name === "test"; + + case "BinaryExpression": + { + if (!node.argument && parent.operator === "|>") { + return false; + } + + return true; + } + + default: + return false; + } + + case "TSConditionalType": + if (name === "extendsType" && parent.type === "TSConditionalType") { + return true; + } + + // fallthrough + + case "TSFunctionType": + case "TSConstructorType": + if (name === "checkType" && parent.type === "TSConditionalType") { + return true; + } + + // fallthrough + + case "TSUnionType": + case "TSIntersectionType": + if ((parent.type === "TSUnionType" || parent.type === "TSIntersectionType") && parent.types.length > 1 && (!node.types || node.types.length > 1)) { + return true; + } + + // fallthrough + + case "TSInferType": + if (node.type === "TSInferType" && parent.type === "TSRestType") { + return false; + } + + // fallthrough + + case "TSTypeOperator": + return parent.type === "TSArrayType" || parent.type === "TSOptionalType" || parent.type === "TSRestType" || name === "objectType" && parent.type === "TSIndexedAccessType" || parent.type === "TSTypeOperator" || parent.type === "TSTypeAnnotation" && /^TSJSDoc/.test(path.getParentNode(1).type); + + case "ArrayTypeAnnotation": + return parent.type === "NullableTypeAnnotation"; + + case "IntersectionTypeAnnotation": + case "UnionTypeAnnotation": + return parent.type === "ArrayTypeAnnotation" || parent.type === "NullableTypeAnnotation" || parent.type === "IntersectionTypeAnnotation" || parent.type === "UnionTypeAnnotation"; + + case "NullableTypeAnnotation": + return parent.type === "ArrayTypeAnnotation"; + + case "FunctionTypeAnnotation": + { + const ancestor = parent.type === "NullableTypeAnnotation" ? path.getParentNode(1) : parent; + return ancestor.type === "UnionTypeAnnotation" || ancestor.type === "IntersectionTypeAnnotation" || ancestor.type === "ArrayTypeAnnotation" || // We should check ancestor's parent to know whether the parentheses + // are really needed, but since ??T doesn't make sense this check + // will almost never be true. + ancestor.type === "NullableTypeAnnotation" || // See #5283 + parent.type === "FunctionTypeParam" && parent.name === null && getFunctionParameters$4(node).some(param => param.typeAnnotation && param.typeAnnotation.type === "NullableTypeAnnotation"); + } + + case "OptionalIndexedAccessType": + return name === "objectType" && parent.type === "IndexedAccessType"; + + case "StringLiteral": + case "NumericLiteral": + case "Literal": + if (typeof node.value === "string" && parent.type === "ExpressionStatement" && !parent.directive) { + // To avoid becoming a directive + const grandParent = path.getParentNode(1); + return grandParent.type === "Program" || grandParent.type === "BlockStatement"; + } + + return name === "object" && parent.type === "MemberExpression" && typeof node.value === "number"; + + case "AssignmentExpression": + { + const grandParent = path.getParentNode(1); + + if (name === "body" && parent.type === "ArrowFunctionExpression") { + return true; + } + + if (name === "key" && (parent.type === "ClassProperty" || parent.type === "PropertyDefinition") && parent.computed) { + return false; + } + + if ((name === "init" || name === "update") && parent.type === "ForStatement") { + return false; + } + + if (parent.type === "ExpressionStatement") { + return node.left.type === "ObjectPattern"; + } + + if (name === "key" && parent.type === "TSPropertySignature") { + return false; + } + + if (parent.type === "AssignmentExpression") { + return false; + } + + if (parent.type === "SequenceExpression" && grandParent && grandParent.type === "ForStatement" && (grandParent.init === parent || grandParent.update === parent)) { + return false; + } + + if (name === "value" && parent.type === "Property" && grandParent && grandParent.type === "ObjectPattern" && grandParent.properties.includes(parent)) { + return false; + } + + if (parent.type === "NGChainedExpression") { + return false; + } + + return true; + } + + case "ConditionalExpression": + switch (parent.type) { + case "TaggedTemplateExpression": + case "UnaryExpression": + case "SpreadElement": + case "SpreadProperty": + case "BinaryExpression": + case "LogicalExpression": + case "NGPipeExpression": + case "ExportDefaultDeclaration": + case "AwaitExpression": + case "JSXSpreadAttribute": + case "TSTypeAssertion": + case "TypeCastExpression": + case "TSAsExpression": + case "TSNonNullExpression": + return true; + + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "ConditionalExpression": + return name === "test"; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + default: + return false; + } + + case "FunctionExpression": + switch (parent.type) { + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + // Not always necessary, but it's clearer to the reader if IIFEs are wrapped in parentheses. + // Is necessary if it is `expression` of `ExpressionStatement`. + return name === "callee"; + + case "TaggedTemplateExpression": + return true; + // This is basically a kind of IIFE. + + default: + return false; + } + + case "ArrowFunctionExpression": + switch (parent.type) { + case "PipelineTopicExpression": + return Boolean(node.extra && node.extra.parenthesized); + + case "BinaryExpression": + return parent.operator !== "|>" || node.extra && node.extra.parenthesized; + + case "NewExpression": + case "CallExpression": + case "OptionalCallExpression": + return name === "callee"; + + case "MemberExpression": + case "OptionalMemberExpression": + return name === "object"; + + case "TSAsExpression": + case "TSNonNullExpression": + case "BindExpression": + case "TaggedTemplateExpression": + case "UnaryExpression": + case "LogicalExpression": + case "AwaitExpression": + case "TSTypeAssertion": + return true; + + case "ConditionalExpression": + return name === "test"; + + default: + return false; + } + + case "ClassExpression": + switch (parent.type) { + case "NewExpression": + return name === "callee"; + + default: + return false; + } + + case "OptionalMemberExpression": + case "OptionalCallExpression": + { + const parentParent = path.getParentNode(1); + + if (name === "object" && parent.type === "MemberExpression" || name === "callee" && (parent.type === "CallExpression" || parent.type === "NewExpression") || parent.type === "TSNonNullExpression" && parentParent.type === "MemberExpression" && parentParent.object === parent) { + return true; + } + } + // fallthrough + + case "CallExpression": + case "MemberExpression": + case "TaggedTemplateExpression": + case "TSNonNullExpression": + if (name === "callee" && (parent.type === "BindExpression" || parent.type === "NewExpression")) { + let object = node; + + while (object) { + switch (object.type) { + case "CallExpression": + case "OptionalCallExpression": + return true; + + case "MemberExpression": + case "OptionalMemberExpression": + case "BindExpression": + object = object.object; + break; + // tagged templates are basically member expressions from a grammar perspective + // see https://tc39.github.io/ecma262/#prod-MemberExpression + + case "TaggedTemplateExpression": + object = object.tag; + break; + + case "TSNonNullExpression": + object = object.expression; + break; + + default: + return false; + } + } + } + + return false; + + case "BindExpression": + return name === "callee" && (parent.type === "BindExpression" || parent.type === "NewExpression") || name === "object" && isMemberExpression$7(parent); + + case "NGPipeExpression": + if (parent.type === "NGRoot" || parent.type === "NGMicrosyntaxExpression" || parent.type === "ObjectProperty" && // Preserve parens for compatibility with AngularJS expressions + !(node.extra && node.extra.parenthesized) || parent.type === "ArrayExpression" || isCallExpression$b(parent) && parent.arguments[name] === node || name === "right" && parent.type === "NGPipeExpression" || name === "property" && parent.type === "MemberExpression" || parent.type === "AssignmentExpression") { + return false; + } + + return true; + + case "JSXFragment": + case "JSXElement": + return name === "callee" || name === "left" && parent.type === "BinaryExpression" && parent.operator === "<" || parent.type !== "ArrayExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "AssignmentExpression" && parent.type !== "AssignmentPattern" && parent.type !== "BinaryExpression" && parent.type !== "NewExpression" && parent.type !== "ConditionalExpression" && parent.type !== "ExpressionStatement" && parent.type !== "JsExpressionRoot" && parent.type !== "JSXAttribute" && parent.type !== "JSXElement" && parent.type !== "JSXExpressionContainer" && parent.type !== "JSXFragment" && parent.type !== "LogicalExpression" && !isCallExpression$b(parent) && !isObjectProperty$3(parent) && parent.type !== "ReturnStatement" && parent.type !== "ThrowStatement" && parent.type !== "TypeCastExpression" && parent.type !== "VariableDeclarator" && parent.type !== "YieldExpression"; + + case "TypeAnnotation": + return name === "returnType" && parent.type === "ArrowFunctionExpression" && includesFunctionTypeInObjectType(node); + } + + return false; +} + +function isStatement(node) { + return node.type === "BlockStatement" || node.type === "BreakStatement" || node.type === "ClassBody" || node.type === "ClassDeclaration" || node.type === "ClassMethod" || node.type === "ClassProperty" || node.type === "PropertyDefinition" || node.type === "ClassPrivateProperty" || node.type === "ContinueStatement" || node.type === "DebuggerStatement" || node.type === "DeclareClass" || node.type === "DeclareExportAllDeclaration" || node.type === "DeclareExportDeclaration" || node.type === "DeclareFunction" || node.type === "DeclareInterface" || node.type === "DeclareModule" || node.type === "DeclareModuleExports" || node.type === "DeclareVariable" || node.type === "DoWhileStatement" || node.type === "EnumDeclaration" || node.type === "ExportAllDeclaration" || node.type === "ExportDefaultDeclaration" || node.type === "ExportNamedDeclaration" || node.type === "ExpressionStatement" || node.type === "ForInStatement" || node.type === "ForOfStatement" || node.type === "ForStatement" || node.type === "FunctionDeclaration" || node.type === "IfStatement" || node.type === "ImportDeclaration" || node.type === "InterfaceDeclaration" || node.type === "LabeledStatement" || node.type === "MethodDefinition" || node.type === "ReturnStatement" || node.type === "SwitchStatement" || node.type === "ThrowStatement" || node.type === "TryStatement" || node.type === "TSDeclareFunction" || node.type === "TSEnumDeclaration" || node.type === "TSImportEqualsDeclaration" || node.type === "TSInterfaceDeclaration" || node.type === "TSModuleDeclaration" || node.type === "TSNamespaceExportDeclaration" || node.type === "TypeAlias" || node.type === "VariableDeclaration" || node.type === "WhileStatement" || node.type === "WithStatement"; +} + +function isPathInForStatementInitializer(path) { + let i = 0; + let node = path.getValue(); + + while (node) { + const parent = path.getParentNode(i++); + + if (parent && parent.type === "ForStatement" && parent.init === node) { + return true; + } + + node = parent; + } + + return false; +} + +function includesFunctionTypeInObjectType(node) { + return hasNode$1(node, n1 => n1.type === "ObjectTypeAnnotation" && hasNode$1(n1, n2 => n2.type === "FunctionTypeAnnotation" || undefined) || undefined); +} + +function endsWithRightBracket(node) { + switch (node.type) { + case "ObjectExpression": + return true; + + default: + return false; + } +} + +function isFollowedByRightBracket(path) { + const node = path.getValue(); + const parent = path.getParentNode(); + const name = path.getName(); + + switch (parent.type) { + case "NGPipeExpression": + if (typeof name === "number" && parent.arguments[name] === node && parent.arguments.length - 1 === name) { + return path.callParent(isFollowedByRightBracket); + } + + break; + + case "ObjectProperty": + if (name === "value") { + const parentParent = path.getParentNode(1); + return getLast_1(parentParent.properties) === parent; + } + + break; + + case "BinaryExpression": + case "LogicalExpression": + if (name === "right") { + return path.callParent(isFollowedByRightBracket); + } + + break; + + case "ConditionalExpression": + if (name === "alternate") { + return path.callParent(isFollowedByRightBracket); + } + + break; + + case "UnaryExpression": + if (parent.prefix) { + return path.callParent(isFollowedByRightBracket); + } + + break; + } + + return false; +} + +function shouldWrapFunctionForExportDefault(path, options) { + const node = path.getValue(); + const parent = path.getParentNode(); + + if (node.type === "FunctionExpression" || node.type === "ClassExpression") { + return parent.type === "ExportDefaultDeclaration" || // in some cases the function is already wrapped + // (e.g. `export default (function() {})();`) + // in this case we don't need to add extra parens + !needsParens(path, options); + } + + if (!hasNakedLeftSide$2(node) || parent.type !== "ExportDefaultDeclaration" && needsParens(path, options)) { + return false; + } + + return path.call(childPath => shouldWrapFunctionForExportDefault(childPath, options), ...getLeftSidePathName$1(path, node)); +} + +var needsParens_1 = needsParens; + +function preprocess$3(ast, options) { + switch (options.parser) { + case "json": + case "json5": + case "json-stringify": + case "__js_expression": + case "__vue_expression": + return Object.assign(Object.assign({}, ast), {}, { + type: options.parser.startsWith("__") ? "JsExpressionRoot" : "JsonRoot", + node: ast, + comments: [], + rootMarker: options.rootMarker + }); + + default: + return ast; + } +} + +var printPreprocess$3 = preprocess$3; + +const { + builders: { + join: join$r, + line: line$t, + group: group$y, + softline: softline$o, + indent: indent$s + } +} = doc; + +function printHtmlBinding$1(path, options, print) { + const node = path.getValue(); + + if (options.__onHtmlBindingRoot && path.getName() === null) { + options.__onHtmlBindingRoot(node, options); + } + + if (node.type !== "File") { + return; + } + + if (options.__isVueForBindingLeft) { + return path.call(functionDeclarationPath => { + const printed = join$r([",", line$t], functionDeclarationPath.map(print, "params")); + const { + params + } = functionDeclarationPath.getValue(); + + if (params.length === 1) { + return printed; + } + + return ["(", indent$s([softline$o, group$y(printed)]), softline$o, ")"]; + }, "program", "body", 0); + } + + if (options.__isVueBindings) { + return path.call(functionDeclarationPath => join$r([",", line$t], functionDeclarationPath.map(print, "params")), "program", "body", 0); + } +} // based on https://github.com/prettier/prettier/blob/main/src/language-html/syntax-vue.js isVueEventBindingExpression() + + +function isVueEventBindingExpression$3(node) { + switch (node.type) { + case "MemberExpression": + switch (node.property.type) { + case "Identifier": + case "NumericLiteral": + case "StringLiteral": + return isVueEventBindingExpression$3(node.object); + } + + return false; + + case "Identifier": + return true; + + default: + return false; + } +} + +var htmlBinding = { + isVueEventBindingExpression: isVueEventBindingExpression$3, + printHtmlBinding: printHtmlBinding$1 +}; + +const { + printComments: printComments$5 +} = comments$1; +const { + getLast: getLast$b +} = util$5; +const { + builders: { + join: join$q, + line: line$s, + softline: softline$n, + group: group$x, + indent: indent$r, + align: align$4, + ifBreak: ifBreak$l, + indentIfBreak: indentIfBreak$3 + }, + utils: { + cleanDoc: cleanDoc$2, + getDocParts: getDocParts$5, + isConcat: isConcat$1 + } +} = doc; +const { + hasLeadingOwnLineComment: hasLeadingOwnLineComment$3, + isBinaryish: isBinaryish$3, + isJsxNode: isJsxNode$5, + shouldFlatten, + hasComment: hasComment$g, + CommentCheckFlags: CommentCheckFlags$d, + isCallExpression: isCallExpression$a, + isMemberExpression: isMemberExpression$6, + isObjectProperty: isObjectProperty$2 +} = utils$5; +/** @typedef {import("../../document").Doc} Doc */ + +let uid = 0; + +function printBinaryishExpression$2(path, options, print) { + const node = path.getValue(); + const parent = path.getParentNode(); + const parentParent = path.getParentNode(1); + const isInsideParenthesis = node !== parent.body && (parent.type === "IfStatement" || parent.type === "WhileStatement" || parent.type === "SwitchStatement" || parent.type === "DoWhileStatement"); + const parts = printBinaryishExpressions(path, print, options, + /* isNested */ + false, isInsideParenthesis); // if ( + // this.hasPlugin("dynamicImports") && this.lookahead().type === tt.parenLeft + // ) { + // + // looks super weird, we want to break the children if the parent breaks + // + // if ( + // this.hasPlugin("dynamicImports") && + // this.lookahead().type === tt.parenLeft + // ) { + + if (isInsideParenthesis) { + return parts; + } // Break between the parens in + // unaries or in a member or specific call expression, i.e. + // + // ( + // a && + // b && + // c + // ).call() + + + if (isCallExpression$a(parent) && parent.callee === node || parent.type === "UnaryExpression" || isMemberExpression$6(parent) && !parent.computed) { + return group$x([indent$r([softline$n, ...parts]), softline$n]); + } // Avoid indenting sub-expressions in some cases where the first sub-expression is already + // indented accordingly. We should indent sub-expressions where the first case isn't indented. + + + const shouldNotIndent = parent.type === "ReturnStatement" || parent.type === "ThrowStatement" || parent.type === "JSXExpressionContainer" && parentParent.type === "JSXAttribute" || node.operator !== "|" && parent.type === "JsExpressionRoot" || node.type !== "NGPipeExpression" && (parent.type === "NGRoot" && options.parser === "__ng_binding" || parent.type === "NGMicrosyntaxExpression" && parentParent.type === "NGMicrosyntax" && parentParent.body.length === 1) || node === parent.body && parent.type === "ArrowFunctionExpression" || node !== parent.body && parent.type === "ForStatement" || parent.type === "ConditionalExpression" && parentParent.type !== "ReturnStatement" && parentParent.type !== "ThrowStatement" && !isCallExpression$a(parentParent) || parent.type === "TemplateLiteral"; + const shouldIndentIfInlining = parent.type === "AssignmentExpression" || parent.type === "VariableDeclarator" || parent.type === "ClassProperty" || parent.type === "PropertyDefinition" || parent.type === "TSAbstractClassProperty" || parent.type === "ClassPrivateProperty" || isObjectProperty$2(parent); + const samePrecedenceSubExpression = isBinaryish$3(node.left) && shouldFlatten(node.operator, node.left.operator); + + if (shouldNotIndent || shouldInlineLogicalExpression$1(node) && !samePrecedenceSubExpression || !shouldInlineLogicalExpression$1(node) && shouldIndentIfInlining) { + return group$x(parts); + } + + if (parts.length === 0) { + return ""; + } // If the right part is a JSX node, we include it in a separate group to + // prevent it breaking the whole chain, so we can print the expression like: + // + // foo && bar && ( + // + // + // + // ) + + + const hasJsx = isJsxNode$5(node.right); + const firstGroupIndex = parts.findIndex(part => typeof part !== "string" && !Array.isArray(part) && part.type === "group"); // Separate the leftmost expression, possibly with its leading comments. + + const headParts = parts.slice(0, firstGroupIndex === -1 ? 1 : firstGroupIndex + 1); + const rest = parts.slice(headParts.length, hasJsx ? -1 : undefined); + const groupId = Symbol("logicalChain-" + ++uid); + const chain = group$x([// Don't include the initial expression in the indentation + // level. The first item is guaranteed to be the first + // left-most expression. + ...headParts, indent$r(rest)], { + id: groupId + }); + + if (!hasJsx) { + return chain; + } + + const jsxPart = getLast$b(parts); + return group$x([chain, indentIfBreak$3(jsxPart, { + groupId + })]); +} // For binary expressions to be consistent, we need to group +// subsequent operators with the same precedence level under a single +// group. Otherwise they will be nested such that some of them break +// onto new lines but not all. Operators with the same precedence +// level should either all break or not. Because we group them by +// precedence level and the AST is structured based on precedence +// level, things are naturally broken up correctly, i.e. `&&` is +// broken before `+`. + + +function printBinaryishExpressions(path, print, options, isNested, isInsideParenthesis) { + /** @type{Doc[]} */ + let parts = []; + const node = path.getValue(); // We treat BinaryExpression and LogicalExpression nodes the same. + + if (isBinaryish$3(node)) { + // Put all operators with the same precedence level in the same + // group. The reason we only need to do this with the `left` + // expression is because given an expression like `1 + 2 - 3`, it + // is always parsed like `((1 + 2) - 3)`, meaning the `left` side + // is where the rest of the expression will exist. Binary + // expressions on the right side mean they have a difference + // precedence level and should be treated as a separate group, so + // print them normally. (This doesn't hold for the `**` operator, + // which is unique in that it is right-associative.) + if (shouldFlatten(node.operator, node.left.operator)) { + // Flatten them out by recursively calling this function. + parts = [...parts, ...path.call(left => printBinaryishExpressions(left, print, options, + /* isNested */ + true, isInsideParenthesis), "left")]; + } else { + parts.push(group$x(print("left"))); + } + + const shouldInline = shouldInlineLogicalExpression$1(node); + const lineBeforeOperator = (node.operator === "|>" || node.type === "NGPipeExpression" || node.operator === "|" && options.parser === "__vue_expression") && !hasLeadingOwnLineComment$3(options.originalText, node.right); + const operator = node.type === "NGPipeExpression" ? "|" : node.operator; + const rightSuffix = node.type === "NGPipeExpression" && node.arguments.length > 0 ? group$x(indent$r([softline$n, ": ", join$q([softline$n, ":", ifBreak$l(" ")], path.map(print, "arguments").map(arg => align$4(2, group$x(arg))))])) : ""; + const right = shouldInline ? [operator, " ", print("right"), rightSuffix] : [lineBeforeOperator ? line$s : "", operator, lineBeforeOperator ? " " : line$s, print("right"), rightSuffix]; // If there's only a single binary expression, we want to create a group + // in order to avoid having a small right part like -1 be on its own line. + + const parent = path.getParentNode(); + const shouldBreak = hasComment$g(node.left, CommentCheckFlags$d.Trailing | CommentCheckFlags$d.Line); + const shouldGroup = shouldBreak || !(isInsideParenthesis && node.type === "LogicalExpression") && parent.type !== node.type && node.left.type !== node.type && node.right.type !== node.type; + parts.push(lineBeforeOperator ? "" : " ", shouldGroup ? group$x(right, { + shouldBreak + }) : right); // The root comments are already printed, but we need to manually print + // the other ones since we don't call the normal print on BinaryExpression, + // only for the left and right parts + + if (isNested && hasComment$g(node)) { + const printed = cleanDoc$2(printComments$5(path, parts, options)); + /* istanbul ignore else */ + + if (isConcat$1(printed) || printed.type === "fill") { + parts = getDocParts$5(printed); + } else { + parts = [printed]; + } + } + } else { + // Our stopping case. Simply print the node normally. + parts.push(group$x(print())); + } + + return parts; +} + +function shouldInlineLogicalExpression$1(node) { + if (node.type !== "LogicalExpression") { + return false; + } + + if (node.right.type === "ObjectExpression" && node.right.properties.length > 0) { + return true; + } + + if (node.right.type === "ArrayExpression" && node.right.elements.length > 0) { + return true; + } + + if (isJsxNode$5(node.right)) { + return true; + } + + return false; +} + +var binaryish = { + printBinaryishExpression: printBinaryishExpression$2, + shouldInlineLogicalExpression: shouldInlineLogicalExpression$1 +}; + +const { + builders: { + join: join$p, + line: line$r, + group: group$w + } +} = doc; +const { + hasNode, + hasComment: hasComment$f, + getComments: getComments$3 +} = utils$5; +const { + printBinaryishExpression: printBinaryishExpression$1 +} = binaryish; +/** @typedef {import("../../common/ast-path")} AstPath */ + +function printAngular$1(path, options, print) { + const node = path.getValue(); // Angular nodes always starts with `NG` + + if (!node.type.startsWith("NG")) { + return; + } + + switch (node.type) { + case "NGRoot": + return [print("node"), !hasComment$f(node.node) ? "" : " //" + getComments$3(node.node)[0].value.trimEnd()]; + + case "NGPipeExpression": + return printBinaryishExpression$1(path, options, print); + + case "NGChainedExpression": + return group$w(join$p([";", line$r], path.map(childPath => hasNgSideEffect(childPath) ? print() : ["(", print(), ")"], "expressions"))); + + case "NGEmptyExpression": + return ""; + + case "NGQuotedExpression": + return [node.prefix, ": ", node.value.trim()]; + + case "NGMicrosyntax": + return path.map((childPath, index) => [index === 0 ? "" : isNgForOf(childPath.getValue(), index, node) ? " " : [";", line$r], print()], "body"); + + case "NGMicrosyntaxKey": + return /^[$_a-z][\w$]*(-[$_a-z][\w$])*$/i.test(node.name) ? node.name : JSON.stringify(node.name); + + case "NGMicrosyntaxExpression": + return [print("expression"), node.alias === null ? "" : [" as ", print("alias")]]; + + case "NGMicrosyntaxKeyedExpression": + { + const index = path.getName(); + const parentNode = path.getParentNode(); + const shouldNotPrintColon = isNgForOf(node, index, parentNode) || (index === 1 && (node.key.name === "then" || node.key.name === "else") || index === 2 && node.key.name === "else" && parentNode.body[index - 1].type === "NGMicrosyntaxKeyedExpression" && parentNode.body[index - 1].key.name === "then") && parentNode.body[0].type === "NGMicrosyntaxExpression"; + return [print("key"), shouldNotPrintColon ? " " : ": ", print("expression")]; + } + + case "NGMicrosyntaxLet": + return ["let ", print("key"), node.value === null ? "" : [" = ", print("value")]]; + + case "NGMicrosyntaxAs": + return [print("key"), " as ", print("alias")]; + + default: + /* istanbul ignore next */ + throw new Error(`Unknown Angular node type: ${JSON.stringify(node.type)}.`); + } +} + +function isNgForOf(node, index, parentNode) { + return node.type === "NGMicrosyntaxKeyedExpression" && node.key.name === "of" && index === 1 && parentNode.body[0].type === "NGMicrosyntaxLet" && parentNode.body[0].value === null; +} +/** identify if an angular expression seems to have side effects */ + +/** + * @param {AstPath} path + * @returns {boolean} + */ + + +function hasNgSideEffect(path) { + return hasNode(path.getValue(), node => { + switch (node.type) { + case undefined: + return false; + + case "CallExpression": + case "OptionalCallExpression": + case "AssignmentExpression": + return true; + } + }); +} + +var angular = { + printAngular: printAngular$1 +}; + +const { + printComments: printComments$4, + printDanglingComments: printDanglingComments$d +} = comments$1; +const { + builders: { + line: line$q, + hardline: hardline$t, + softline: softline$m, + group: group$v, + indent: indent$q, + conditionalGroup: conditionalGroup$4, + fill: fill$7, + ifBreak: ifBreak$k, + lineSuffixBoundary, + join: join$o + }, + utils: { + willBreak: willBreak$5 + } +} = doc; +const { + getLast: getLast$a, + getPreferredQuote +} = util$5; +const { + isJsxNode: isJsxNode$4, + rawText: rawText$4, + isLiteral: isLiteral$2, + isCallExpression: isCallExpression$9, + isStringLiteral: isStringLiteral$4, + isBinaryish: isBinaryish$2, + hasComment: hasComment$e, + CommentCheckFlags: CommentCheckFlags$c, + hasNodeIgnoreComment +} = utils$5; +const { + willPrintOwnComments +} = comments; + +const isEmptyStringOrAnyLine = doc => doc === "" || doc === line$q || doc === hardline$t || doc === softline$m; +/** + * @typedef {import("../../common/ast-path")} AstPath + * @typedef {import("../types/estree").Node} Node + * @typedef {import("../types/estree").JSXElement} JSXElement + */ +// JSX expands children from the inside-out, instead of the outside-in. +// This is both to break children before attributes, +// and to ensure that when children break, their parents do as well. +// +// Any element that is written without any newlines and fits on a single line +// is left that way. +// Not only that, any user-written-line containing multiple JSX siblings +// should also be kept on one line if possible, +// so each user-written-line is wrapped in its own group. +// +// Elements that contain newlines or don't fit on a single line (recursively) +// are fully-split, using hardline and shouldBreak: true. +// +// To support that case properly, all leading and trailing spaces +// are stripped from the list of children, and replaced with a single hardline. + + +function printJsxElementInternal(path, options, print) { + const node = path.getValue(); + + if (node.type === "JSXElement" && isEmptyJsxElement(node)) { + return [print("openingElement"), print("closingElement")]; + } + + const openingLines = node.type === "JSXElement" ? print("openingElement") : print("openingFragment"); + const closingLines = node.type === "JSXElement" ? print("closingElement") : print("closingFragment"); + + if (node.children.length === 1 && node.children[0].type === "JSXExpressionContainer" && (node.children[0].expression.type === "TemplateLiteral" || node.children[0].expression.type === "TaggedTemplateExpression")) { + return [openingLines, ...path.map(print, "children"), closingLines]; + } // Convert `{" "}` to text nodes containing a space. + // This makes it easy to turn them into `jsxWhitespace` which + // can then print as either a space or `{" "}` when breaking. + + + node.children = node.children.map(child => { + if (isJsxWhitespaceExpression(child)) { + return { + type: "JSXText", + value: " ", + raw: " " + }; + } + + return child; + }); + const containsTag = node.children.filter(isJsxNode$4).length > 0; + const containsMultipleExpressions = node.children.filter(child => child.type === "JSXExpressionContainer").length > 1; + const containsMultipleAttributes = node.type === "JSXElement" && node.openingElement.attributes.length > 1; // Record any breaks. Should never go from true to false, only false to true. + + let forcedBreak = willBreak$5(openingLines) || containsTag || containsMultipleAttributes || containsMultipleExpressions; + const isMdxBlock = path.getParentNode().rootMarker === "mdx"; + const rawJsxWhitespace = options.singleQuote ? "{' '}" : '{" "}'; + const jsxWhitespace = isMdxBlock ? " " : ifBreak$k([rawJsxWhitespace, softline$m], " "); + const isFacebookTranslationTag = node.openingElement && node.openingElement.name && node.openingElement.name.name === "fbt"; + const children = printJsxChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag); + const containsText = node.children.some(child => isMeaningfulJsxText(child)); // We can end up we multiple whitespace elements with empty string + // content between them. + // We need to remove empty whitespace and softlines before JSX whitespace + // to get the correct output. + + for (let i = children.length - 2; i >= 0; i--) { + const isPairOfEmptyStrings = children[i] === "" && children[i + 1] === ""; + const isPairOfHardlines = children[i] === hardline$t && children[i + 1] === "" && children[i + 2] === hardline$t; + const isLineFollowedByJsxWhitespace = (children[i] === softline$m || children[i] === hardline$t) && children[i + 1] === "" && children[i + 2] === jsxWhitespace; + const isJsxWhitespaceFollowedByLine = children[i] === jsxWhitespace && children[i + 1] === "" && (children[i + 2] === softline$m || children[i + 2] === hardline$t); + const isDoubleJsxWhitespace = children[i] === jsxWhitespace && children[i + 1] === "" && children[i + 2] === jsxWhitespace; + const isPairOfHardOrSoftLines = children[i] === softline$m && children[i + 1] === "" && children[i + 2] === hardline$t || children[i] === hardline$t && children[i + 1] === "" && children[i + 2] === softline$m; + + if (isPairOfHardlines && containsText || isPairOfEmptyStrings || isLineFollowedByJsxWhitespace || isDoubleJsxWhitespace || isPairOfHardOrSoftLines) { + children.splice(i, 2); + } else if (isJsxWhitespaceFollowedByLine) { + children.splice(i + 1, 2); + } + } // Trim trailing lines (or empty strings) + + + while (children.length > 0 && isEmptyStringOrAnyLine(getLast$a(children))) { + children.pop(); + } // Trim leading lines (or empty strings) + + + while (children.length > 1 && isEmptyStringOrAnyLine(children[0]) && isEmptyStringOrAnyLine(children[1])) { + children.shift(); + children.shift(); + } // Tweak how we format children if outputting this element over multiple lines. + // Also detect whether we will force this element to output over multiple lines. + + + const multilineChildren = []; + + for (const [i, child] of children.entries()) { + // There are a number of situations where we need to ensure we display + // whitespace as `{" "}` when outputting this element over multiple lines. + if (child === jsxWhitespace) { + if (i === 1 && children[i - 1] === "") { + if (children.length === 2) { + // Solitary whitespace + multilineChildren.push(rawJsxWhitespace); + continue; + } // Leading whitespace + + + multilineChildren.push([rawJsxWhitespace, hardline$t]); + continue; + } else if (i === children.length - 1) { + // Trailing whitespace + multilineChildren.push(rawJsxWhitespace); + continue; + } else if (children[i - 1] === "" && children[i - 2] === hardline$t) { + // Whitespace after line break + multilineChildren.push(rawJsxWhitespace); + continue; + } + } + + multilineChildren.push(child); + + if (willBreak$5(child)) { + forcedBreak = true; + } + } // If there is text we use `fill` to fit as much onto each line as possible. + // When there is no text (just tags and expressions) we use `group` + // to output each on a separate line. + + + const content = containsText ? fill$7(multilineChildren) : group$v(multilineChildren, { + shouldBreak: true + }); + + if (isMdxBlock) { + return content; + } + + const multiLineElem = group$v([openingLines, indent$q([hardline$t, content]), hardline$t, closingLines]); + + if (forcedBreak) { + return multiLineElem; + } + + return conditionalGroup$4([group$v([openingLines, ...children, closingLines]), multiLineElem]); +} // JSX Children are strange, mostly for two reasons: +// 1. JSX reads newlines into string values, instead of skipping them like JS +// 2. up to one whitespace between elements within a line is significant, +// but not between lines. +// +// Leading, trailing, and lone whitespace all need to +// turn themselves into the rather ugly `{' '}` when breaking. +// +// We print JSX using the `fill` doc primitive. +// This requires that we give it an array of alternating +// content and whitespace elements. +// To ensure this we add dummy `""` content elements as needed. + + +function printJsxChildren(path, options, print, jsxWhitespace, isFacebookTranslationTag) { + const parts = []; + path.each((childPath, i, children) => { + const child = childPath.getValue(); + + if (isLiteral$2(child)) { + const text = rawText$4(child); // Contains a non-whitespace character + + if (isMeaningfulJsxText(child)) { + const words = text.split(matchJsxWhitespaceRegex); // Starts with whitespace + + if (words[0] === "") { + parts.push(""); + words.shift(); + + if (/\n/.test(words[0])) { + const next = children[i + 1]; + parts.push(separatorWithWhitespace(isFacebookTranslationTag, words[1], child, next)); + } else { + parts.push(jsxWhitespace); + } + + words.shift(); + } + + let endWhitespace; // Ends with whitespace + + if (getLast$a(words) === "") { + words.pop(); + endWhitespace = words.pop(); + } // This was whitespace only without a new line. + + + if (words.length === 0) { + return; + } + + for (const [i, word] of words.entries()) { + if (i % 2 === 1) { + parts.push(line$q); + } else { + parts.push(word); + } + } + + if (endWhitespace !== undefined) { + if (/\n/.test(endWhitespace)) { + const next = children[i + 1]; + parts.push(separatorWithWhitespace(isFacebookTranslationTag, getLast$a(parts), child, next)); + } else { + parts.push(jsxWhitespace); + } + } else { + const next = children[i + 1]; + parts.push(separatorNoWhitespace(isFacebookTranslationTag, getLast$a(parts), child, next)); + } + } else if (/\n/.test(text)) { + // Keep (up to one) blank line between tags/expressions/text. + // Note: We don't keep blank lines between text elements. + if (text.match(/\n/g).length > 1) { + parts.push("", hardline$t); + } + } else { + parts.push("", jsxWhitespace); + } + } else { + const printedChild = print(); + parts.push(printedChild); + const next = children[i + 1]; + const directlyFollowedByMeaningfulText = next && isMeaningfulJsxText(next); + + if (directlyFollowedByMeaningfulText) { + const firstWord = trimJsxWhitespace(rawText$4(next)).split(matchJsxWhitespaceRegex)[0]; + parts.push(separatorNoWhitespace(isFacebookTranslationTag, firstWord, child, next)); + } else { + parts.push(hardline$t); + } + } + }, "children"); + return parts; +} + +function separatorNoWhitespace(isFacebookTranslationTag, child, childNode, nextNode) { + if (isFacebookTranslationTag) { + return ""; + } + + if (childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement) { + return child.length === 1 ? softline$m : hardline$t; + } + + return softline$m; +} + +function separatorWithWhitespace(isFacebookTranslationTag, child, childNode, nextNode) { + if (isFacebookTranslationTag) { + return hardline$t; + } + + if (child.length === 1) { + return childNode.type === "JSXElement" && !childNode.closingElement || nextNode && nextNode.type === "JSXElement" && !nextNode.closingElement ? hardline$t : softline$m; + } + + return hardline$t; +} + +function maybeWrapJsxElementInParens(path, elem, options) { + const parent = path.getParentNode(); + /* istanbul ignore next */ + + if (!parent) { + return elem; + } + + const NO_WRAP_PARENTS = { + ArrayExpression: true, + JSXAttribute: true, + JSXElement: true, + JSXExpressionContainer: true, + JSXFragment: true, + ExpressionStatement: true, + CallExpression: true, + OptionalCallExpression: true, + ConditionalExpression: true, + JsExpressionRoot: true + }; + + if (NO_WRAP_PARENTS[parent.type]) { + return elem; + } + + const shouldBreak = path.match(undefined, node => node.type === "ArrowFunctionExpression", isCallExpression$9, node => node.type === "JSXExpressionContainer"); + const needsParens = needsParens_1(path, options); + return group$v([needsParens ? "" : ifBreak$k("("), indent$q([softline$m, elem]), softline$m, needsParens ? "" : ifBreak$k(")")], { + shouldBreak + }); +} + +function printJsxAttribute(path, options, print) { + const node = path.getValue(); + const parts = []; + parts.push(print("name")); + + if (node.value) { + let res; + + if (isStringLiteral$4(node.value)) { + const raw = rawText$4(node.value); // Unescape all quotes so we get an accurate preferred quote + + let final = raw.replace(/'/g, "'").replace(/"/g, '"'); + const quote = getPreferredQuote(final, options.jsxSingleQuote ? "'" : '"'); + const escape = quote === "'" ? "'" : """; + final = final.slice(1, -1).replace(new RegExp(quote, "g"), escape); + res = [quote, final, quote]; + } else { + res = print("value"); + } + + parts.push("=", res); + } + + return parts; +} + +function printJsxExpressionContainer(path, options, print) { + const node = path.getValue(); + const parent = path.getParentNode(0); + const shouldInline = node.expression.type === "JSXEmptyExpression" || !hasComment$e(node.expression) && (node.expression.type === "ArrayExpression" || node.expression.type === "ObjectExpression" || node.expression.type === "ArrowFunctionExpression" || isCallExpression$9(node.expression) || node.expression.type === "FunctionExpression" || node.expression.type === "TemplateLiteral" || node.expression.type === "TaggedTemplateExpression" || node.expression.type === "DoExpression" || isJsxNode$4(parent) && (node.expression.type === "ConditionalExpression" || isBinaryish$2(node.expression))); + + if (shouldInline) { + return group$v(["{", print("expression"), lineSuffixBoundary, "}"]); + } + + return group$v(["{", indent$q([softline$m, print("expression")]), softline$m, lineSuffixBoundary, "}"]); +} + +function printJsxOpeningElement(path, options, print) { + const node = path.getValue(); + const nameHasComments = node.name && hasComment$e(node.name) || node.typeParameters && hasComment$e(node.typeParameters); // Don't break self-closing elements with no attributes and no comments + + if (node.selfClosing && node.attributes.length === 0 && !nameHasComments) { + return ["<", print("name"), print("typeParameters"), " />"]; + } // don't break up opening elements with a single long text attribute + + + if (node.attributes && node.attributes.length === 1 && node.attributes[0].value && isStringLiteral$4(node.attributes[0].value) && !node.attributes[0].value.value.includes("\n") && // We should break for the following cases: + //
+ //
+ !nameHasComments && !hasComment$e(node.attributes[0])) { + return group$v(["<", print("name"), print("typeParameters"), " ", ...path.map(print, "attributes"), node.selfClosing ? " />" : ">"]); + } + + const lastAttrHasTrailingComments = node.attributes.length > 0 && hasComment$e(getLast$a(node.attributes), CommentCheckFlags$c.Trailing); + const bracketSameLine = // Simple tags (no attributes and no comment in tag name) should be + // kept unbroken regardless of `jsxBracketSameLine` + node.attributes.length === 0 && !nameHasComments || options.jsxBracketSameLine && ( // We should print the bracket in a new line for the following cases: + //
+ //
+ !nameHasComments || node.attributes.length > 0) && !lastAttrHasTrailingComments; // We should print the opening element expanded if any prop value is a + // string literal with newlines + + const shouldBreak = node.attributes && node.attributes.some(attr => attr.value && isStringLiteral$4(attr.value) && attr.value.value.includes("\n")); + return group$v(["<", print("name"), print("typeParameters"), indent$q(path.map(() => [line$q, print()], "attributes")), node.selfClosing ? line$q : bracketSameLine ? ">" : softline$m, node.selfClosing ? "/>" : bracketSameLine ? "" : ">"], { + shouldBreak + }); +} + +function printJsxClosingElement(path, options, print) { + const node = path.getValue(); + const parts = []; + parts.push(""); + return parts; +} + +function printJsxOpeningClosingFragment(path, options +/*, print*/ +) { + const node = path.getValue(); + const nodeHasComment = hasComment$e(node); + const hasOwnLineComment = hasComment$e(node, CommentCheckFlags$c.Line); + const isOpeningFragment = node.type === "JSXOpeningFragment"; + return [isOpeningFragment ? "<" : ""]; +} + +function printJsxElement(path, options, print) { + const elem = printComments$4(path, printJsxElementInternal(path, options, print), options); + return maybeWrapJsxElementInParens(path, elem, options); +} + +function printJsxEmptyExpression(path, options +/*, print*/ +) { + const node = path.getValue(); + const requiresHardline = hasComment$e(node, CommentCheckFlags$c.Line); + return [printDanglingComments$d(path, options, + /* sameIndent */ + !requiresHardline), requiresHardline ? hardline$t : ""]; +} // `JSXSpreadAttribute` and `JSXSpreadChild` + + +function printJsxSpreadAttribute(path, options, print) { + const node = path.getValue(); + return ["{", path.call(p => { + const printed = ["...", print()]; + const node = p.getValue(); + + if (!hasComment$e(node) || !willPrintOwnComments(p)) { + return printed; + } + + return [indent$q([softline$m, printComments$4(p, printed, options)]), softline$m]; + }, node.type === "JSXSpreadAttribute" ? "argument" : "expression"), "}"]; +} + +function printJsx$1(path, options, print) { + const node = path.getValue(); // JSX nodes always starts with `JSX` + + if (!node.type.startsWith("JSX")) { + return; + } + + switch (node.type) { + case "JSXAttribute": + return printJsxAttribute(path, options, print); + + case "JSXIdentifier": + return String(node.name); + + case "JSXNamespacedName": + return join$o(":", [print("namespace"), print("name")]); + + case "JSXMemberExpression": + return join$o(".", [print("object"), print("property")]); + + case "JSXSpreadAttribute": + return printJsxSpreadAttribute(path, options, print); + + case "JSXSpreadChild": + { + // Same as `printJsxSpreadAttribute` + const printJsxSpreadChild = printJsxSpreadAttribute; + return printJsxSpreadChild(path, options, print); + } + + case "JSXExpressionContainer": + return printJsxExpressionContainer(path, options, print); + + case "JSXFragment": + case "JSXElement": + return printJsxElement(path, options, print); + + case "JSXOpeningElement": + return printJsxOpeningElement(path, options, print); + + case "JSXClosingElement": + return printJsxClosingElement(path, options, print); + + case "JSXOpeningFragment": + case "JSXClosingFragment": + return printJsxOpeningClosingFragment(path, options + /*, print*/ + ); + + case "JSXEmptyExpression": + return printJsxEmptyExpression(path, options + /*, print*/ + ); + + case "JSXText": + /* istanbul ignore next */ + throw new Error("JSXTest should be handled by JSXElement"); + + default: + /* istanbul ignore next */ + throw new Error(`Unknown JSX node type: ${JSON.stringify(node.type)}.`); + } +} // Only space, newline, carriage return, and tab are treated as whitespace +// inside JSX. + + +const jsxWhitespaceChars = " \n\r\t"; +const matchJsxWhitespaceRegex = new RegExp("([" + jsxWhitespaceChars + "]+)"); +const containsNonJsxWhitespaceRegex = new RegExp("[^" + jsxWhitespaceChars + "]"); + +const trimJsxWhitespace = text => text.replace(new RegExp("(?:^" + matchJsxWhitespaceRegex.source + "|" + matchJsxWhitespaceRegex.source + "$)"), ""); +/** + * @param {JSXElement} node + * @returns {boolean} + */ + + +function isEmptyJsxElement(node) { + if (node.children.length === 0) { + return true; + } + + if (node.children.length > 1) { + return false; + } // if there is one text child and does not contain any meaningful text + // we can treat the element as empty. + + + const child = node.children[0]; + return isLiteral$2(child) && !isMeaningfulJsxText(child); +} // Meaningful if it contains non-whitespace characters, +// or it contains whitespace without a new line. + +/** + * @param {Node} node + * @returns {boolean} + */ + + +function isMeaningfulJsxText(node) { + return isLiteral$2(node) && (containsNonJsxWhitespaceRegex.test(rawText$4(node)) || !/\n/.test(rawText$4(node))); +} // Detect an expression node representing `{" "}` + + +function isJsxWhitespaceExpression(node) { + return node.type === "JSXExpressionContainer" && isLiteral$2(node.expression) && node.expression.value === " " && !hasComment$e(node.expression); +} +/** + * @param {AstPath} path + * @returns {boolean} + */ + + +function hasJsxIgnoreComment$1(path) { + const node = path.getValue(); + const parent = path.getParentNode(); + + if (!parent || !node || !isJsxNode$4(node) || !isJsxNode$4(parent)) { + return false; + } // Lookup the previous sibling, ignoring any empty JSXText elements + + + const index = parent.children.indexOf(node); + let prevSibling = null; + + for (let i = index; i > 0; i--) { + const candidate = parent.children[i - 1]; + + if (candidate.type === "JSXText" && !isMeaningfulJsxText(candidate)) { + continue; + } + + prevSibling = candidate; + break; + } + + return prevSibling && prevSibling.type === "JSXExpressionContainer" && prevSibling.expression.type === "JSXEmptyExpression" && hasNodeIgnoreComment(prevSibling.expression); +} + +var jsx = { + hasJsxIgnoreComment: hasJsxIgnoreComment$1, + printJsx: printJsx$1 +}; + +// `Array.prototype.flat` method +// https://tc39.es/ecma262/#sec-array.prototype.flat +_export({ target: 'Array', proto: true }, { + flat: function flat(/* depthArg = 1 */) { + var depthArg = arguments.length ? arguments[0] : undefined; + var O = toObject(this); + var sourceLen = toLength(O.length); + var A = arraySpeciesCreate(O, 0); + A.length = flattenIntoArray_1(A, O, O, sourceLen, 0, depthArg === undefined ? 1 : toInteger(depthArg)); + return A; + } +}); + +const { + isNonEmptyArray: isNonEmptyArray$e +} = util$5; +const { + builders: { + indent: indent$p, + join: join$n, + line: line$p + } +} = doc; +const { + isFlowAnnotationComment: isFlowAnnotationComment$1 +} = utils$5; + +function printOptionalToken$9(path) { + const node = path.getValue(); + + if (!node.optional || // It's an optional computed method parsed by typescript-estree. + // "?" is printed in `printMethod`. + node.type === "Identifier" && node === path.getParentNode().key) { + return ""; + } + + if (node.type === "OptionalCallExpression" || node.type === "OptionalMemberExpression" && node.computed) { + return "?."; + } + + return "?"; +} + +function printFunctionTypeParameters$4(path, options, print) { + const fun = path.getValue(); + + if (fun.typeArguments) { + return print("typeArguments"); + } + + if (fun.typeParameters) { + return print("typeParameters"); + } + + return ""; +} + +function printTypeAnnotation$5(path, options, print) { + const node = path.getValue(); + + if (!node.typeAnnotation) { + return ""; + } + + const parentNode = path.getParentNode(); + const isDefinite = node.definite || parentNode && parentNode.type === "VariableDeclarator" && parentNode.definite; + const isFunctionDeclarationIdentifier = parentNode.type === "DeclareFunction" && parentNode.id === node; + + if (isFlowAnnotationComment$1(options.originalText, node.typeAnnotation)) { + return [" /*: ", print("typeAnnotation"), " */"]; + } + + return [isFunctionDeclarationIdentifier ? "" : isDefinite ? "!: " : ": ", print("typeAnnotation")]; +} + +function printBindExpressionCallee$2(path, options, print) { + return ["::", print("callee")]; +} + +function printTypeScriptModifiers$2(path, options, print) { + const node = path.getValue(); + + if (!isNonEmptyArray$e(node.modifiers)) { + return ""; + } + + return [join$n(" ", path.map(print, "modifiers")), " "]; +} + +function adjustClause$1(node, clause, forceSpace) { + if (node.type === "EmptyStatement") { + return ";"; + } + + if (node.type === "BlockStatement" || forceSpace) { + return [" ", clause]; + } + + return indent$p([line$p, clause]); +} + +function printRestSpread$2(path, options, print) { + return ["...", print("argument"), printTypeAnnotation$5(path, options, print)]; +} + +var misc$1 = { + printOptionalToken: printOptionalToken$9, + printFunctionTypeParameters: printFunctionTypeParameters$4, + printBindExpressionCallee: printBindExpressionCallee$2, + printTypeScriptModifiers: printTypeScriptModifiers$2, + printTypeAnnotation: printTypeAnnotation$5, + printRestSpread: printRestSpread$2, + adjustClause: adjustClause$1 +}; + +const { + printDanglingComments: printDanglingComments$c +} = comments$1; +const { + builders: { + line: line$o, + softline: softline$l, + hardline: hardline$s, + group: group$u, + indent: indent$o, + ifBreak: ifBreak$j, + fill: fill$6 + } +} = doc; +const { + getLast: getLast$9, + hasNewline: hasNewline$5 +} = util$5; +const { + shouldPrintComma: shouldPrintComma$a, + hasComment: hasComment$d, + CommentCheckFlags: CommentCheckFlags$b, + isNextLineEmpty: isNextLineEmpty$b, + isNumericLiteral: isNumericLiteral$4, + isSignedNumericLiteral: isSignedNumericLiteral$1 +} = utils$5; +const { + locStart: locStart$m +} = loc$6; +const { + printOptionalToken: printOptionalToken$8, + printTypeAnnotation: printTypeAnnotation$4 +} = misc$1; +/** @typedef {import("../../document").Doc} Doc */ + +function printArray$1(path, options, print) { + const node = path.getValue(); + /** @type{Doc[]} */ + + const parts = []; + const openBracket = node.type === "TupleExpression" ? "#[" : "["; + const closeBracket = "]"; + + if (node.elements.length === 0) { + if (!hasComment$d(node, CommentCheckFlags$b.Dangling)) { + parts.push(openBracket, closeBracket); + } else { + parts.push(group$u([openBracket, printDanglingComments$c(path, options), softline$l, closeBracket])); + } + } else { + const lastElem = getLast$9(node.elements); + const canHaveTrailingComma = !(lastElem && lastElem.type === "RestElement"); // JavaScript allows you to have empty elements in an array which + // changes its length based on the number of commas. The algorithm + // is that if the last argument is null, we need to force insert + // a comma to ensure JavaScript recognizes it. + // [,].length === 1 + // [1,].length === 1 + // [1,,].length === 2 + // + // Note that getLast returns null if the array is empty, but + // we already check for an empty array just above so we are safe + + const needsForcedTrailingComma = lastElem === null; + const groupId = Symbol("array"); + const shouldBreak = !options.__inJestEach && node.elements.length > 1 && node.elements.every((element, i, elements) => { + const elementType = element && element.type; + + if (elementType !== "ArrayExpression" && elementType !== "ObjectExpression") { + return false; + } + + const nextElement = elements[i + 1]; + + if (nextElement && elementType !== nextElement.type) { + return false; + } + + const itemsKey = elementType === "ArrayExpression" ? "elements" : "properties"; + return element[itemsKey] && element[itemsKey].length > 1; + }); + const shouldUseConciseFormatting = isConciselyPrintedArray$1(node, options); + const trailingComma = !canHaveTrailingComma ? "" : needsForcedTrailingComma ? "," : !shouldPrintComma$a(options) ? "" : shouldUseConciseFormatting ? ifBreak$j(",", "", { + groupId + }) : ifBreak$j(","); + parts.push(group$u([openBracket, indent$o([softline$l, shouldUseConciseFormatting ? printArrayItemsConcisely(path, options, print, trailingComma) : [printArrayItems$3(path, options, "elements", print), trailingComma], printDanglingComments$c(path, options, + /* sameIndent */ + true)]), softline$l, closeBracket], { + shouldBreak, + id: groupId + })); + } + + parts.push(printOptionalToken$8(path), printTypeAnnotation$4(path, options, print)); + return parts; +} + +function isConciselyPrintedArray$1(node, options) { + return node.elements.length > 1 && node.elements.every(element => element && (isNumericLiteral$4(element) || isSignedNumericLiteral$1(element) && !hasComment$d(element.argument)) && !hasComment$d(element, CommentCheckFlags$b.Trailing | CommentCheckFlags$b.Line, comment => !hasNewline$5(options.originalText, locStart$m(comment), { + backwards: true + }))); +} + +function printArrayItems$3(path, options, printPath, print) { + const printedElements = []; + let separatorParts = []; + path.each(childPath => { + printedElements.push(separatorParts, group$u(print())); + separatorParts = [",", line$o]; + + if (childPath.getValue() && isNextLineEmpty$b(childPath.getValue(), options)) { + separatorParts.push(softline$l); + } + }, printPath); + return printedElements; +} + +function printArrayItemsConcisely(path, options, print, trailingComma) { + const parts = []; + path.each((childPath, i, elements) => { + const isLast = i === elements.length - 1; + parts.push([print(), isLast ? trailingComma : ","]); + + if (!isLast) { + parts.push(isNextLineEmpty$b(childPath.getValue(), options) ? [hardline$s, hardline$s] : hasComment$d(elements[i + 1], CommentCheckFlags$b.Leading | CommentCheckFlags$b.Line) ? hardline$s : line$o); + } + }, "elements"); + return fill$6(parts); +} + +var array = { + printArray: printArray$1, + printArrayItems: printArrayItems$3, + isConciselyPrintedArray: isConciselyPrintedArray$1 +}; + +const { + printDanglingComments: printDanglingComments$b +} = comments$1; +const { + getLast: getLast$8, + getPenultimate +} = util$5; +const { + getFunctionParameters: getFunctionParameters$3, + hasComment: hasComment$c, + CommentCheckFlags: CommentCheckFlags$a, + isFunctionCompositionArgs, + isJsxNode: isJsxNode$3, + isLongCurriedCallExpression: isLongCurriedCallExpression$1, + shouldPrintComma: shouldPrintComma$9, + getCallArguments: getCallArguments$3, + iterateCallArgumentsPath: iterateCallArgumentsPath$1, + isNextLineEmpty: isNextLineEmpty$a, + isCallExpression: isCallExpression$8, + isStringLiteral: isStringLiteral$3, + isObjectProperty: isObjectProperty$1 +} = utils$5; +const { + builders: { + line: line$n, + hardline: hardline$r, + softline: softline$k, + group: group$t, + indent: indent$n, + conditionalGroup: conditionalGroup$3, + ifBreak: ifBreak$i, + breakParent: breakParent$7 + }, + utils: { + willBreak: willBreak$4 + } +} = doc; +const { + ArgExpansionBailout: ArgExpansionBailout$2 +} = errors; +const { + isConciselyPrintedArray +} = array; + +function printCallArguments(path, options, print) { + const node = path.getValue(); + const isDynamicImport = node.type === "ImportExpression"; + const args = getCallArguments$3(node); + + if (args.length === 0) { + return ["(", printDanglingComments$b(path, options, + /* sameIndent */ + true), ")"]; + } // useEffect(() => { ... }, [foo, bar, baz]) + + + if (isReactHookCallWithDepsArray(args)) { + return ["(", print(["arguments", 0]), ", ", print(["arguments", 1]), ")"]; + } + + let anyArgEmptyLine = false; + let hasEmptyLineFollowingFirstArg = false; + const lastArgIndex = args.length - 1; + const printedArguments = []; + iterateCallArgumentsPath$1(path, (argPath, index) => { + const arg = argPath.getNode(); + const parts = [print()]; + + if (index === lastArgIndex) ; else if (isNextLineEmpty$a(arg, options)) { + if (index === 0) { + hasEmptyLineFollowingFirstArg = true; + } + + anyArgEmptyLine = true; + parts.push(",", hardline$r, hardline$r); + } else { + parts.push(",", line$n); + } + + printedArguments.push(parts); + }); + const maybeTrailingComma = // Dynamic imports cannot have trailing commas + !(isDynamicImport || node.callee && node.callee.type === "Import") && shouldPrintComma$9(options, "all") ? "," : ""; + + function allArgsBrokenOut() { + return group$t(["(", indent$n([line$n, ...printedArguments]), maybeTrailingComma, line$n, ")"], { + shouldBreak: true + }); + } + + if (anyArgEmptyLine || path.getParentNode().type !== "Decorator" && isFunctionCompositionArgs(args)) { + return allArgsBrokenOut(); + } + + const shouldGroupFirst = shouldGroupFirstArg(args); + const shouldGroupLast = shouldGroupLastArg(args, options); + + if (shouldGroupFirst || shouldGroupLast) { + if (shouldGroupFirst ? printedArguments.slice(1).some(willBreak$4) : printedArguments.slice(0, -1).some(willBreak$4)) { + return allArgsBrokenOut(); + } // We want to print the last argument with a special flag + + + let printedExpanded = []; + + try { + path.try(() => { + iterateCallArgumentsPath$1(path, (argPath, i) => { + if (shouldGroupFirst && i === 0) { + printedExpanded = [[print([], { + expandFirstArg: true + }), printedArguments.length > 1 ? "," : "", hasEmptyLineFollowingFirstArg ? hardline$r : line$n, hasEmptyLineFollowingFirstArg ? hardline$r : ""], ...printedArguments.slice(1)]; + } + + if (shouldGroupLast && i === lastArgIndex) { + printedExpanded = [...printedArguments.slice(0, -1), print([], { + expandLastArg: true + })]; + } + }); + }); + } catch (caught) { + if (caught instanceof ArgExpansionBailout$2) { + return allArgsBrokenOut(); + } + /* istanbul ignore next */ + + + throw caught; + } + + return [printedArguments.some(willBreak$4) ? breakParent$7 : "", conditionalGroup$3([["(", ...printedExpanded, ")"], shouldGroupFirst ? ["(", group$t(printedExpanded[0], { + shouldBreak: true + }), ...printedExpanded.slice(1), ")"] : ["(", ...printedArguments.slice(0, -1), group$t(getLast$8(printedExpanded), { + shouldBreak: true + }), ")"], allArgsBrokenOut()])]; + } + + const contents = ["(", indent$n([softline$k, ...printedArguments]), ifBreak$i(maybeTrailingComma), softline$k, ")"]; + + if (isLongCurriedCallExpression$1(path)) { + // By not wrapping the arguments in a group, the printer prioritizes + // breaking up these arguments rather than the args of the parent call. + return contents; + } + + return group$t(contents, { + shouldBreak: printedArguments.some(willBreak$4) || anyArgEmptyLine + }); +} + +function couldGroupArg(arg, arrowChainRecursion = false) { + return arg.type === "ObjectExpression" && (arg.properties.length > 0 || hasComment$c(arg)) || arg.type === "ArrayExpression" && (arg.elements.length > 0 || hasComment$c(arg)) || arg.type === "TSTypeAssertion" && couldGroupArg(arg.expression) || arg.type === "TSAsExpression" && couldGroupArg(arg.expression) || arg.type === "FunctionExpression" || arg.type === "ArrowFunctionExpression" && ( // we want to avoid breaking inside composite return types but not simple keywords + // https://github.com/prettier/prettier/issues/4070 + // export class Thing implements OtherThing { + // do: (type: Type) => Provider = memoize( + // (type: ObjectType): Provider => {} + // ); + // } + // https://github.com/prettier/prettier/issues/6099 + // app.get("/", (req, res): void => { + // res.send("Hello World!"); + // }); + !arg.returnType || !arg.returnType.typeAnnotation || arg.returnType.typeAnnotation.type !== "TSTypeReference" || // https://github.com/prettier/prettier/issues/7542 + isNonEmptyBlockStatement(arg.body)) && (arg.body.type === "BlockStatement" || arg.body.type === "ArrowFunctionExpression" && couldGroupArg(arg.body, true) || arg.body.type === "ObjectExpression" || arg.body.type === "ArrayExpression" || !arrowChainRecursion && (isCallExpression$8(arg.body) || arg.body.type === "ConditionalExpression") || isJsxNode$3(arg.body)) || arg.type === "DoExpression" || arg.type === "ModuleExpression"; +} + +function shouldGroupLastArg(args, options) { + const lastArg = getLast$8(args); + const penultimateArg = getPenultimate(args); + return !hasComment$c(lastArg, CommentCheckFlags$a.Leading) && !hasComment$c(lastArg, CommentCheckFlags$a.Trailing) && couldGroupArg(lastArg) && ( // If the last two arguments are of the same type, + // disable last element expansion. + !penultimateArg || penultimateArg.type !== lastArg.type) && ( // useMemo(() => func(), [foo, bar, baz]) + args.length !== 2 || penultimateArg.type !== "ArrowFunctionExpression" || lastArg.type !== "ArrayExpression") && !(args.length > 1 && lastArg.type === "ArrayExpression" && isConciselyPrintedArray(lastArg, options)); +} + +function shouldGroupFirstArg(args) { + if (args.length !== 2) { + return false; + } + + const [firstArg, secondArg] = args; + + if (firstArg.type === "ModuleExpression" && isTypeModuleObjectExpression(secondArg)) { + return true; + } + + return !hasComment$c(firstArg) && (firstArg.type === "FunctionExpression" || firstArg.type === "ArrowFunctionExpression" && firstArg.body.type === "BlockStatement") && secondArg.type !== "FunctionExpression" && secondArg.type !== "ArrowFunctionExpression" && secondArg.type !== "ConditionalExpression" && !couldGroupArg(secondArg); +} + +function isReactHookCallWithDepsArray(args) { + return args.length === 2 && args[0].type === "ArrowFunctionExpression" && getFunctionParameters$3(args[0]).length === 0 && args[0].body.type === "BlockStatement" && args[1].type === "ArrayExpression" && !args.some(arg => hasComment$c(arg)); +} + +function isNonEmptyBlockStatement(node) { + return node.type === "BlockStatement" && (node.body.some(node => node.type !== "EmptyStatement") || hasComment$c(node, CommentCheckFlags$a.Dangling)); +} // { type: "module" } + + +function isTypeModuleObjectExpression(node) { + return node.type === "ObjectExpression" && node.properties.length === 1 && isObjectProperty$1(node.properties[0]) && node.properties[0].key.type === "Identifier" && node.properties[0].key.name === "type" && isStringLiteral$3(node.properties[0].value) && node.properties[0].value.value === "module"; +} + +var callArguments = printCallArguments; + +const { + builders: { + softline: softline$j, + group: group$s, + indent: indent$m, + label: label$2 + } +} = doc; +const { + isNumericLiteral: isNumericLiteral$3, + isMemberExpression: isMemberExpression$5, + isCallExpression: isCallExpression$7 +} = utils$5; +const { + printOptionalToken: printOptionalToken$7 +} = misc$1; + +function printMemberExpression$1(path, options, print) { + const node = path.getValue(); + const parent = path.getParentNode(); + let firstNonMemberParent; + let i = 0; + + do { + firstNonMemberParent = path.getParentNode(i); + i++; + } while (firstNonMemberParent && (isMemberExpression$5(firstNonMemberParent) || firstNonMemberParent.type === "TSNonNullExpression")); + + const objectDoc = print("object"); + const lookupDoc = printMemberLookup$1(path, options, print); + const shouldInline = firstNonMemberParent && (firstNonMemberParent.type === "NewExpression" || firstNonMemberParent.type === "BindExpression" || firstNonMemberParent.type === "AssignmentExpression" && firstNonMemberParent.left.type !== "Identifier") || node.computed || node.object.type === "Identifier" && node.property.type === "Identifier" && !isMemberExpression$5(parent) || (parent.type === "AssignmentExpression" || parent.type === "VariableDeclarator") && (isCallExpression$7(node.object) && node.object.arguments.length > 0 || node.object.type === "TSNonNullExpression" && isCallExpression$7(node.object.expression) && node.object.expression.arguments.length > 0 || objectDoc.label === "member-chain"); + return label$2(objectDoc.label === "member-chain" ? "member-chain" : "member", [objectDoc, shouldInline ? lookupDoc : group$s(indent$m([softline$j, lookupDoc]))]); +} + +function printMemberLookup$1(path, options, print) { + const property = print("property"); + const node = path.getValue(); + const optional = printOptionalToken$7(path); + + if (!node.computed) { + return [optional, ".", property]; + } + + if (!node.property || isNumericLiteral$3(node.property)) { + return [optional, "[", property, "]"]; + } + + return group$s([optional, "[", indent$m([softline$j, property]), softline$j, "]"]); +} + +var member = { + printMemberExpression: printMemberExpression$1, + printMemberLookup: printMemberLookup$1 +}; + +const { + printComments: printComments$3 +} = comments$1; +const { + getLast: getLast$7, + isNextLineEmptyAfterIndex, + getNextNonSpaceNonCommentCharacterIndex: getNextNonSpaceNonCommentCharacterIndex$1 +} = util$5; +const { + isCallExpression: isCallExpression$6, + isMemberExpression: isMemberExpression$4, + isFunctionOrArrowExpression, + isLongCurriedCallExpression, + isMemberish: isMemberish$1, + isNumericLiteral: isNumericLiteral$2, + isSimpleCallArgument, + hasComment: hasComment$b, + CommentCheckFlags: CommentCheckFlags$9, + isNextLineEmpty: isNextLineEmpty$9 +} = utils$5; +const { + locEnd: locEnd$l +} = loc$6; +const { + builders: { + join: join$m, + hardline: hardline$q, + group: group$r, + indent: indent$l, + conditionalGroup: conditionalGroup$2, + breakParent: breakParent$6, + label: label$1 + }, + utils: { + willBreak: willBreak$3 + } +} = doc; +const { + printMemberLookup +} = member; +const { + printOptionalToken: printOptionalToken$6, + printFunctionTypeParameters: printFunctionTypeParameters$3, + printBindExpressionCallee: printBindExpressionCallee$1 +} = misc$1; // We detect calls on member expressions specially to format a +// common pattern better. The pattern we are looking for is this: +// +// arr +// .map(x => x + 1) +// .filter(x => x > 10) +// .some(x => x % 2) +// +// The way it is structured in the AST is via a nested sequence of +// MemberExpression and CallExpression. We need to traverse the AST +// and make groups out of it to print it in the desired way. + +function printMemberChain(path, options, print) { + const parent = path.getParentNode(); + const isExpressionStatement = !parent || parent.type === "ExpressionStatement"; // The first phase is to linearize the AST by traversing it down. + // + // a().b() + // has the following AST structure: + // CallExpression(MemberExpression(CallExpression(Identifier))) + // and we transform it into + // [Identifier, CallExpression, MemberExpression, CallExpression] + + const printedNodes = []; // Here we try to retain one typed empty line after each call expression or + // the first group whether it is in parentheses or not + + function shouldInsertEmptyLineAfter(node) { + const { + originalText + } = options; + const nextCharIndex = getNextNonSpaceNonCommentCharacterIndex$1(originalText, node, locEnd$l); + const nextChar = originalText.charAt(nextCharIndex); // if it is cut off by a parenthesis, we only account for one typed empty + // line after that parenthesis + + if (nextChar === ")") { + return nextCharIndex !== false && isNextLineEmptyAfterIndex(originalText, nextCharIndex + 1); + } + + return isNextLineEmpty$9(node, options); + } + + function rec(path) { + const node = path.getValue(); + + if (isCallExpression$6(node) && (isMemberish$1(node.callee) || isCallExpression$6(node.callee))) { + printedNodes.unshift({ + node, + printed: [printComments$3(path, [printOptionalToken$6(path), printFunctionTypeParameters$3(path, options, print), callArguments(path, options, print)], options), shouldInsertEmptyLineAfter(node) ? hardline$q : ""] + }); + path.call(callee => rec(callee), "callee"); + } else if (isMemberish$1(node)) { + printedNodes.unshift({ + node, + needsParens: needsParens_1(path, options), + printed: printComments$3(path, isMemberExpression$4(node) ? printMemberLookup(path, options, print) : printBindExpressionCallee$1(path, options, print), options) + }); + path.call(object => rec(object), "object"); + } else if (node.type === "TSNonNullExpression") { + printedNodes.unshift({ + node, + printed: printComments$3(path, "!", options) + }); + path.call(expression => rec(expression), "expression"); + } else { + printedNodes.unshift({ + node, + printed: print() + }); + } + } // Note: the comments of the root node have already been printed, so we + // need to extract this first call without printing them as they would + // if handled inside of the recursive call. + + + const node = path.getValue(); + printedNodes.unshift({ + node, + printed: [printOptionalToken$6(path), printFunctionTypeParameters$3(path, options, print), callArguments(path, options, print)] + }); + + if (node.callee) { + path.call(callee => rec(callee), "callee"); + } // Once we have a linear list of printed nodes, we want to create groups out + // of it. + // + // a().b.c().d().e + // will be grouped as + // [ + // [Identifier, CallExpression], + // [MemberExpression, MemberExpression, CallExpression], + // [MemberExpression, CallExpression], + // [MemberExpression], + // ] + // so that we can print it as + // a() + // .b.c() + // .d() + // .e + // The first group is the first node followed by + // - as many CallExpression as possible + // < fn()()() >.something() + // - as many array accessors as possible + // < fn()[0][1][2] >.something() + // - then, as many MemberExpression as possible but the last one + // < this.items >.something() + + + const groups = []; + let currentGroup = [printedNodes[0]]; + let i = 1; + + for (; i < printedNodes.length; ++i) { + if (printedNodes[i].node.type === "TSNonNullExpression" || isCallExpression$6(printedNodes[i].node) || isMemberExpression$4(printedNodes[i].node) && printedNodes[i].node.computed && isNumericLiteral$2(printedNodes[i].node.property)) { + currentGroup.push(printedNodes[i]); + } else { + break; + } + } + + if (!isCallExpression$6(printedNodes[0].node)) { + for (; i + 1 < printedNodes.length; ++i) { + if (isMemberish$1(printedNodes[i].node) && isMemberish$1(printedNodes[i + 1].node)) { + currentGroup.push(printedNodes[i]); + } else { + break; + } + } + } + + groups.push(currentGroup); + currentGroup = []; // Then, each following group is a sequence of MemberExpression followed by + // a sequence of CallExpression. To compute it, we keep adding things to the + // group until we has seen a CallExpression in the past and reach a + // MemberExpression + + let hasSeenCallExpression = false; + + for (; i < printedNodes.length; ++i) { + if (hasSeenCallExpression && isMemberish$1(printedNodes[i].node)) { + // [0] should be appended at the end of the group instead of the + // beginning of the next one + if (printedNodes[i].node.computed && isNumericLiteral$2(printedNodes[i].node.property)) { + currentGroup.push(printedNodes[i]); + continue; + } + + groups.push(currentGroup); + currentGroup = []; + hasSeenCallExpression = false; + } + + if (isCallExpression$6(printedNodes[i].node) || printedNodes[i].node.type === "ImportExpression") { + hasSeenCallExpression = true; + } + + currentGroup.push(printedNodes[i]); + + if (hasComment$b(printedNodes[i].node, CommentCheckFlags$9.Trailing)) { + groups.push(currentGroup); + currentGroup = []; + hasSeenCallExpression = false; + } + } + + if (currentGroup.length > 0) { + groups.push(currentGroup); + } // There are cases like Object.keys(), Observable.of(), _.values() where + // they are the subject of all the chained calls and therefore should + // be kept on the same line: + // + // Object.keys(items) + // .filter(x => x) + // .map(x => x) + // + // In order to detect those cases, we use an heuristic: if the first + // node is an identifier with the name starting with a capital + // letter or just a sequence of _$. The rationale is that they are + // likely to be factories. + + + function isFactory(name) { + return /^[A-Z]|^[$_]+$/.test(name); + } // In case the Identifier is shorter than tab width, we can keep the + // first call in a single line, if it's an ExpressionStatement. + // + // d3.scaleLinear() + // .domain([0, 100]) + // .range([0, width]); + // + + + function isShort(name) { + return name.length <= options.tabWidth; + } + + function shouldNotWrap(groups) { + const hasComputed = groups[1].length > 0 && groups[1][0].node.computed; + + if (groups[0].length === 1) { + const firstNode = groups[0][0].node; + return firstNode.type === "ThisExpression" || firstNode.type === "Identifier" && (isFactory(firstNode.name) || isExpressionStatement && isShort(firstNode.name) || hasComputed); + } + + const lastNode = getLast$7(groups[0]).node; + return isMemberExpression$4(lastNode) && lastNode.property.type === "Identifier" && (isFactory(lastNode.property.name) || hasComputed); + } + + const shouldMerge = groups.length >= 2 && !hasComment$b(groups[1][0].node) && shouldNotWrap(groups); + + function printGroup(printedGroup) { + const printed = printedGroup.map(tuple => tuple.printed); // Checks if the last node (i.e. the parent node) needs parens and print + // accordingly + + if (printedGroup.length > 0 && getLast$7(printedGroup).needsParens) { + return ["(", ...printed, ")"]; + } + + return printed; + } + + function printIndentedGroup(groups) { + /* istanbul ignore next */ + if (groups.length === 0) { + return ""; + } + + return indent$l(group$r([hardline$q, join$m(hardline$q, groups.map(printGroup))])); + } + + const printedGroups = groups.map(printGroup); + const oneLine = printedGroups; + const cutoff = shouldMerge ? 3 : 2; + const flatGroups = groups.flat(); + const nodeHasComment = flatGroups.slice(1, -1).some(node => hasComment$b(node.node, CommentCheckFlags$9.Leading)) || flatGroups.slice(0, -1).some(node => hasComment$b(node.node, CommentCheckFlags$9.Trailing)) || groups[cutoff] && hasComment$b(groups[cutoff][0].node, CommentCheckFlags$9.Leading); // If we only have a single `.`, we shouldn't do anything fancy and just + // render everything concatenated together. + + if (groups.length <= cutoff && !nodeHasComment) { + if (isLongCurriedCallExpression(path)) { + return oneLine; + } + + return group$r(oneLine); + } // Find out the last node in the first group and check if it has an + // empty line after + + + const lastNodeBeforeIndent = getLast$7(groups[shouldMerge ? 1 : 0]).node; + const shouldHaveEmptyLineBeforeIndent = !isCallExpression$6(lastNodeBeforeIndent) && shouldInsertEmptyLineAfter(lastNodeBeforeIndent); + const expanded = [printGroup(groups[0]), shouldMerge ? groups.slice(1, 2).map(printGroup) : "", shouldHaveEmptyLineBeforeIndent ? hardline$q : "", printIndentedGroup(groups.slice(shouldMerge ? 2 : 1))]; + const callExpressions = printedNodes.map(({ + node + }) => node).filter(isCallExpression$6); + + function lastGroupWillBreakAndOtherCallsHaveFunctionArguments() { + const lastGroupNode = getLast$7(getLast$7(groups)).node; + const lastGroupDoc = getLast$7(printedGroups); + return isCallExpression$6(lastGroupNode) && willBreak$3(lastGroupDoc) && callExpressions.slice(0, -1).some(node => node.arguments.some(isFunctionOrArrowExpression)); + } + + let result; // We don't want to print in one line if at least one of these conditions occurs: + // * the chain has comments, + // * the chain is an expression statement and all the arguments are literal-like ("fluent configuration" pattern), + // * the chain is longer than 2 calls and has non-trivial arguments or more than 2 arguments in any call but the first one, + // * any group but the last one has a hard line, + // * the last call's arguments have a hard line and other calls have non-trivial arguments. + + if (nodeHasComment || callExpressions.length > 2 && callExpressions.some(expr => !expr.arguments.every(arg => isSimpleCallArgument(arg, 0))) || printedGroups.slice(0, -1).some(willBreak$3) || lastGroupWillBreakAndOtherCallsHaveFunctionArguments()) { + result = group$r(expanded); + } else { + result = [// We only need to check `oneLine` because if `expanded` is chosen + // that means that the parent group has already been broken + // naturally + willBreak$3(oneLine) || shouldHaveEmptyLineBeforeIndent ? breakParent$6 : "", conditionalGroup$2([oneLine, expanded])]; + } + + return label$1("member-chain", result); +} + +var memberChain = printMemberChain; + +const { + builders: { + join: join$l, + group: group$q + } +} = doc; +const { + getCallArguments: getCallArguments$2, + hasFlowAnnotationComment, + isCallExpression: isCallExpression$5, + isMemberish, + isStringLiteral: isStringLiteral$2, + isTemplateOnItsOwnLine: isTemplateOnItsOwnLine$1, + isTestCall: isTestCall$2, + iterateCallArgumentsPath +} = utils$5; +const { + printOptionalToken: printOptionalToken$5, + printFunctionTypeParameters: printFunctionTypeParameters$2 +} = misc$1; + +function printCallExpression$2(path, options, print) { + const node = path.getValue(); + const parentNode = path.getParentNode(); + const isNew = node.type === "NewExpression"; + const isDynamicImport = node.type === "ImportExpression"; + const optional = printOptionalToken$5(path); + const args = getCallArguments$2(node); + + if ( // Dangling comments are not handled, all these special cases should have arguments #9668 + args.length > 0 && ( // We want to keep CommonJS- and AMD-style require calls, and AMD-style + // define calls, as a unit. + // e.g. `define(["some/lib"], (lib) => {` + !isDynamicImport && !isNew && isCommonsJsOrAmdCall(node, parentNode) || // Template literals as single arguments + args.length === 1 && isTemplateOnItsOwnLine$1(args[0], options.originalText) || // Keep test declarations on a single line + // e.g. `it('long name', () => {` + !isNew && isTestCall$2(node, parentNode))) { + const printed = []; + iterateCallArgumentsPath(path, () => { + printed.push(print()); + }); + return [isNew ? "new " : "", print("callee"), optional, printFunctionTypeParameters$2(path, options, print), "(", join$l(", ", printed), ")"]; + } // Inline Flow annotation comments following Identifiers in Call nodes need to + // stay with the Identifier. For example: + // + // foo /*:: */(bar); + // + // Here, we ensure that such comments stay between the Identifier and the Callee. + + + const isIdentifierWithFlowAnnotation = (options.parser === "babel" || options.parser === "babel-flow") && node.callee && node.callee.type === "Identifier" && hasFlowAnnotationComment(node.callee.trailingComments); + + if (isIdentifierWithFlowAnnotation) { + node.callee.trailingComments[0].printed = true; + } // We detect calls on member lookups and possibly print them in a + // special chain format. See `printMemberChain` for more info. + + + if (!isDynamicImport && !isNew && isMemberish(node.callee) && !path.call(path => needsParens_1(path, options), "callee")) { + return memberChain(path, options, print); + } + + const contents = [isNew ? "new " : "", isDynamicImport ? "import" : print("callee"), optional, isIdentifierWithFlowAnnotation ? `/*:: ${node.callee.trailingComments[0].value.slice(2).trim()} */` : "", printFunctionTypeParameters$2(path, options, print), callArguments(path, options, print)]; // We group here when the callee is itself a call expression. + // See `isLongCurriedCallExpression` for more info. + + if (isDynamicImport || isCallExpression$5(node.callee)) { + return group$q(contents); + } + + return contents; +} + +function isCommonsJsOrAmdCall(node, parentNode) { + if (node.callee.type !== "Identifier") { + return false; + } + + if (node.callee.name === "require") { + return true; + } + + if (node.callee.name === "define") { + const args = getCallArguments$2(node); + return parentNode.type === "ExpressionStatement" && (args.length === 1 || args.length === 2 && args[0].type === "ArrayExpression" || args.length === 3 && isStringLiteral$2(args[0]) && args[1].type === "ArrayExpression"); + } + + return false; +} + +var callExpression = { + printCallExpression: printCallExpression$2 +}; + +const { + isNonEmptyArray: isNonEmptyArray$d, + getStringWidth: getStringWidth$1 +} = util$5; +const { + builders: { + line: line$m, + group: group$p, + indent: indent$k, + indentIfBreak: indentIfBreak$2 + }, + utils: { + cleanDoc: cleanDoc$1, + willBreak: willBreak$2 + } +} = doc; +const { + hasLeadingOwnLineComment: hasLeadingOwnLineComment$2, + isBinaryish: isBinaryish$1, + isStringLiteral: isStringLiteral$1, + isLiteral: isLiteral$1, + isNumericLiteral: isNumericLiteral$1, + isCallExpression: isCallExpression$4, + isMemberExpression: isMemberExpression$3, + getCallArguments: getCallArguments$1, + rawText: rawText$3, + hasComment: hasComment$a, + isSignedNumericLiteral, + isObjectProperty +} = utils$5; +const { + shouldInlineLogicalExpression +} = binaryish; +const { + printCallExpression: printCallExpression$1 +} = callExpression; + +function printAssignment$3(path, options, print, leftDoc, operator, rightPropertyName) { + const layout = chooseLayout(path, options, print, leftDoc, rightPropertyName); + const rightDoc = print(rightPropertyName, { + assignmentLayout: layout + }); + + switch (layout) { + // First break after operator, then the sides are broken independently on their own lines + case "break-after-operator": + return group$p([group$p(leftDoc), operator, group$p(indent$k([line$m, rightDoc]))]); + // First break right-hand side, then left-hand side + + case "never-break-after-operator": + return group$p([group$p(leftDoc), operator, " ", rightDoc]); + // First break right-hand side, then after operator + + case "fluid": + { + const groupId = Symbol("assignment"); + return group$p([group$p(leftDoc), operator, group$p(indent$k(line$m), { + id: groupId + }), indentIfBreak$2(rightDoc, { + groupId + })]); + } + + case "break-lhs": + return group$p([leftDoc, operator, " ", group$p(rightDoc)]); + // Parts of assignment chains aren't wrapped in groups. + // Once one of them breaks, the chain breaks too. + + case "chain": + return [group$p(leftDoc), operator, line$m, rightDoc]; + + case "chain-tail": + return [group$p(leftDoc), operator, indent$k([line$m, rightDoc])]; + + case "chain-tail-arrow-chain": + return [group$p(leftDoc), operator, rightDoc]; + + case "only-left": + return leftDoc; + } +} + +function printAssignmentExpression$1(path, options, print) { + const node = path.getValue(); + return printAssignment$3(path, options, print, print("left"), [" ", node.operator], "right"); +} + +function printVariableDeclarator$1(path, options, print) { + return printAssignment$3(path, options, print, print("id"), " =", "init"); +} + +function chooseLayout(path, options, print, leftDoc, rightPropertyName) { + const node = path.getValue(); + const rightNode = node[rightPropertyName]; + + if (!rightNode) { + return "only-left"; + } // Short assignment chains (only 2 segments) are NOT formatted as chains. + // 1) a = b = c; (expression statements) + // 2) var/let/const a = b = c; + + + const isTail = !isAssignment(rightNode); + const shouldUseChainFormatting = path.match(isAssignment, isAssignmentOrVariableDeclarator, node => !isTail || node.type !== "ExpressionStatement" && node.type !== "VariableDeclaration"); + + if (shouldUseChainFormatting) { + return !isTail ? "chain" : rightNode.type === "ArrowFunctionExpression" && rightNode.body.type === "ArrowFunctionExpression" ? "chain-tail-arrow-chain" : "chain-tail"; + } + + const isHeadOfLongChain = !isTail && isAssignment(rightNode.right); + + if (isHeadOfLongChain || hasLeadingOwnLineComment$2(options.originalText, rightNode)) { + return "break-after-operator"; + } + + if (rightNode.type === "CallExpression" && rightNode.callee.name === "require" || // do not put values on a separate line from the key in json + options.parser === "json5" || options.parser === "json") { + return "never-break-after-operator"; + } + + if (isComplexDestructuring(node) || isComplexTypeAliasParams(node) || hasComplexTypeAnnotation(node)) { + return "break-lhs"; + } // wrapping object properties with very short keys usually doesn't add much value + + + const hasShortKey = isObjectPropertyWithShortKey(node, leftDoc, options); + + if (path.call(() => shouldBreakAfterOperator(path, options, print, hasShortKey), rightPropertyName)) { + return "break-after-operator"; + } + + if (hasShortKey || rightNode.type === "TemplateLiteral" || rightNode.type === "TaggedTemplateExpression" || rightNode.type === "BooleanLiteral" || isNumericLiteral$1(rightNode) || rightNode.type === "ClassExpression") { + return "never-break-after-operator"; + } + + return "fluid"; +} + +function shouldBreakAfterOperator(path, options, print, hasShortKey) { + const rightNode = path.getValue(); + + if (isBinaryish$1(rightNode) && !shouldInlineLogicalExpression(rightNode)) { + return true; + } + + switch (rightNode.type) { + case "StringLiteralTypeAnnotation": + case "SequenceExpression": + return true; + + case "ConditionalExpression": + { + const { + test + } = rightNode; + return isBinaryish$1(test) && !shouldInlineLogicalExpression(test); + } + + case "ClassExpression": + return isNonEmptyArray$d(rightNode.decorators); + } + + if (hasShortKey) { + return false; + } + + let node = rightNode; + const propertiesForPath = []; + + for (;;) { + if (node.type === "UnaryExpression") { + node = node.argument; + propertiesForPath.push("argument"); + } else if (node.type === "TSNonNullExpression") { + node = node.expression; + propertiesForPath.push("expression"); + } else { + break; + } + } + + if (isStringLiteral$1(node) || path.call(() => isPoorlyBreakableMemberOrCallChain(path, options, print), ...propertiesForPath)) { + return true; + } + + return false; +} // prefer to break destructuring assignment +// if it includes default values or non-shorthand properties + + +function isComplexDestructuring(node) { + if (isAssignmentOrVariableDeclarator(node)) { + const leftNode = node.left || node.id; + return leftNode.type === "ObjectPattern" && leftNode.properties.length > 2 && leftNode.properties.some(property => isObjectProperty(property) && (!property.shorthand || property.value && property.value.type === "AssignmentPattern")); + } + + return false; +} + +function isAssignment(node) { + return node.type === "AssignmentExpression"; +} + +function isAssignmentOrVariableDeclarator(node) { + return isAssignment(node) || node.type === "VariableDeclarator"; +} + +function isComplexTypeAliasParams(node) { + const typeParams = getTypeParametersFromTypeAlias(node); + + if (isNonEmptyArray$d(typeParams)) { + const constraintPropertyName = node.type === "TSTypeAliasDeclaration" ? "constraint" : "bound"; + + if (typeParams.length > 1 && typeParams.some(param => param[constraintPropertyName] || param.default)) { + return true; + } + } + + return false; +} + +function getTypeParametersFromTypeAlias(node) { + if (isTypeAlias(node) && node.typeParameters && node.typeParameters.params) { + return node.typeParameters.params; + } + + return null; +} + +function isTypeAlias(node) { + return node.type === "TSTypeAliasDeclaration" || node.type === "TypeAlias"; +} + +function hasComplexTypeAnnotation(node) { + if (node.type !== "VariableDeclarator") { + return false; + } + + const { + typeAnnotation + } = node.id; + + if (!typeAnnotation || !typeAnnotation.typeAnnotation) { + return false; + } + + const typeParams = getTypeParametersFromTypeReference(typeAnnotation.typeAnnotation); + return isNonEmptyArray$d(typeParams) && typeParams.length > 1 && typeParams.some(param => isNonEmptyArray$d(getTypeParametersFromTypeReference(param)) || param.type === "TSConditionalType"); +} + +function getTypeParametersFromTypeReference(node) { + if (isTypeReference(node) && node.typeParameters && node.typeParameters.params) { + return node.typeParameters.params; + } + + return null; +} + +function isTypeReference(node) { + return node.type === "TSTypeReference" || node.type === "GenericTypeAnnotation"; +} +/** + * A chain with no calls at all or whose calls are all without arguments or with lone short arguments, + * excluding chains printed by `printMemberChain` + */ + + +function isPoorlyBreakableMemberOrCallChain(path, options, print, deep = false) { + const node = path.getValue(); + + const goDeeper = () => isPoorlyBreakableMemberOrCallChain(path, options, print, true); + + if (node.type === "TSNonNullExpression") { + return path.call(goDeeper, "expression"); + } + + if (isCallExpression$4(node)) { + /** @type {any} TODO */ + const doc = printCallExpression$1(path, options, print); + + if (doc.label === "member-chain") { + return false; + } + + const args = getCallArguments$1(node); + const isPoorlyBreakableCall = args.length === 0 || args.length === 1 && isLoneShortArgument(args[0], options); + + if (!isPoorlyBreakableCall) { + return false; + } + + if (isCallExpressionWithComplexTypeArguments(node, print)) { + return false; + } + + return path.call(goDeeper, "callee"); + } + + if (isMemberExpression$3(node)) { + return path.call(goDeeper, "object"); + } + + return deep && (node.type === "Identifier" || node.type === "ThisExpression"); +} + +const LONE_SHORT_ARGUMENT_THRESHOLD_RATE = 0.25; + +function isLoneShortArgument(node, { + printWidth +}) { + if (hasComment$a(node)) { + return false; + } + + const threshold = printWidth * LONE_SHORT_ARGUMENT_THRESHOLD_RATE; + + if (node.type === "ThisExpression" || node.type === "Identifier" && node.name.length <= threshold || isSignedNumericLiteral(node) && !hasComment$a(node.argument)) { + return true; + } + + const regexpPattern = node.type === "Literal" && "regex" in node && node.regex.pattern || node.type === "RegExpLiteral" && node.pattern; + + if (regexpPattern) { + return regexpPattern.length <= threshold; + } + + if (isStringLiteral$1(node)) { + return rawText$3(node).length <= threshold; + } + + if (node.type === "TemplateLiteral") { + return node.expressions.length === 0 && node.quasis[0].value.raw.length <= threshold && !node.quasis[0].value.raw.includes("\n"); + } + + return isLiteral$1(node); +} + +function isObjectPropertyWithShortKey(node, keyDoc, options) { + if (!isObjectProperty(node)) { + return false; + } // TODO: for performance, it might make sense to use a more lightweight + // version of cleanDoc, such that it would stop once it detects that + // the doc can't be reduced to a string. + + + keyDoc = cleanDoc$1(keyDoc); + const MIN_OVERLAP_FOR_BREAK = 3; // ↓↓ - insufficient overlap for a line break + // key1: longValue1, + // ↓↓↓↓↓↓ - overlap is long enough to break + // key2abcd: + // longValue2 + + return typeof keyDoc === "string" && getStringWidth$1(keyDoc) < options.tabWidth + MIN_OVERLAP_FOR_BREAK; +} + +function isCallExpressionWithComplexTypeArguments(node, print) { + const typeArgs = getTypeArgumentsFromCallExpression(node); + + if (isNonEmptyArray$d(typeArgs)) { + if (typeArgs.length > 1) { + return true; + } + + if (typeArgs.length === 1) { + const firstArg = typeArgs[0]; + + if (firstArg.type === "TSUnionType" || firstArg.type === "UnionTypeAnnotation" || firstArg.type === "TSIntersectionType" || firstArg.type === "IntersectionTypeAnnotation") { + return true; + } + } + + const typeArgsKeyName = node.typeParameters ? "typeParameters" : "typeArguments"; + + if (willBreak$2(print(typeArgsKeyName))) { + return true; + } + } + + return false; +} + +function getTypeArgumentsFromCallExpression(node) { + return node.typeParameters && node.typeParameters.params || node.typeArguments && node.typeArguments.params; +} + +var assignment = { + printVariableDeclarator: printVariableDeclarator$1, + printAssignmentExpression: printAssignmentExpression$1, + printAssignment: printAssignment$3 +}; + +const { + getNextNonSpaceNonCommentCharacter +} = util$5; +const { + printDanglingComments: printDanglingComments$a +} = comments$1; +const { + builders: { + line: line$l, + hardline: hardline$p, + softline: softline$i, + group: group$o, + indent: indent$j, + ifBreak: ifBreak$h + }, + utils: { + removeLines: removeLines$2, + willBreak: willBreak$1 + } +} = doc; +const { + getFunctionParameters: getFunctionParameters$2, + iterateFunctionParametersPath, + isSimpleType: isSimpleType$1, + isTestCall: isTestCall$1, + isTypeAnnotationAFunction, + isObjectType: isObjectType$1, + isObjectTypePropertyAFunction: isObjectTypePropertyAFunction$1, + hasRestParameter, + shouldPrintComma: shouldPrintComma$8, + hasComment: hasComment$9, + isNextLineEmpty: isNextLineEmpty$8 +} = utils$5; +const { + locEnd: locEnd$k +} = loc$6; +const { + ArgExpansionBailout: ArgExpansionBailout$1 +} = errors; +const { + printFunctionTypeParameters: printFunctionTypeParameters$1 +} = misc$1; + +function printFunctionParameters$3(path, print, options, expandArg, printTypeParams) { + const functionNode = path.getValue(); + const parameters = getFunctionParameters$2(functionNode); + const typeParams = printTypeParams ? printFunctionTypeParameters$1(path, options, print) : ""; + + if (parameters.length === 0) { + return [typeParams, "(", printDanglingComments$a(path, options, + /* sameIndent */ + true, comment => getNextNonSpaceNonCommentCharacter(options.originalText, comment, locEnd$k) === ")"), ")"]; + } + + const parent = path.getParentNode(); + const isParametersInTestCall = isTestCall$1(parent); + const shouldHugParameters = shouldHugFunctionParameters$1(functionNode); + const printed = []; + iterateFunctionParametersPath(path, (parameterPath, index) => { + const isLastParameter = index === parameters.length - 1; + + if (isLastParameter && functionNode.rest) { + printed.push("..."); + } + + printed.push(print()); + + if (isLastParameter) { + return; + } + + printed.push(","); + + if (isParametersInTestCall || shouldHugParameters) { + printed.push(" "); + } else if (isNextLineEmpty$8(parameters[index], options)) { + printed.push(hardline$p, hardline$p); + } else { + printed.push(line$l); + } + }); // If the parent is a call with the first/last argument expansion and this is the + // params of the first/last argument, we don't want the arguments to break and instead + // want the whole expression to be on a new line. + // + // Good: Bad: + // verylongcall( verylongcall(( + // (a, b) => { a, + // } b, + // ) ) => { + // }) + + if (expandArg) { + if (willBreak$1(typeParams) || willBreak$1(printed)) { + // Removing lines in this case leads to broken or ugly output + throw new ArgExpansionBailout$1(); + } + + return group$o([removeLines$2(typeParams), "(", removeLines$2(printed), ")"]); + } // Single object destructuring should hug + // + // function({ + // a, + // b, + // c + // }) {} + + + const hasNotParameterDecorator = parameters.every(node => !node.decorators); + + if (shouldHugParameters && hasNotParameterDecorator) { + return [typeParams, "(", ...printed, ")"]; + } // don't break in specs, eg; `it("should maintain parens around done even when long", (done) => {})` + + + if (isParametersInTestCall) { + return [typeParams, "(", ...printed, ")"]; + } + + const isFlowShorthandWithOneArg = (isObjectTypePropertyAFunction$1(parent) || isTypeAnnotationAFunction(parent) || parent.type === "TypeAlias" || parent.type === "UnionTypeAnnotation" || parent.type === "TSUnionType" || parent.type === "IntersectionTypeAnnotation" || parent.type === "FunctionTypeAnnotation" && parent.returnType === functionNode) && parameters.length === 1 && parameters[0].name === null && // `type q = (this: string) => void;` + functionNode.this !== parameters[0] && parameters[0].typeAnnotation && functionNode.typeParameters === null && isSimpleType$1(parameters[0].typeAnnotation) && !functionNode.rest; + + if (isFlowShorthandWithOneArg) { + if (options.arrowParens === "always") { + return ["(", ...printed, ")"]; + } + + return printed; + } + + return [typeParams, "(", indent$j([softline$i, ...printed]), ifBreak$h(!hasRestParameter(functionNode) && shouldPrintComma$8(options, "all") ? "," : ""), softline$i, ")"]; +} + +function shouldHugFunctionParameters$1(node) { + if (!node) { + return false; + } + + const parameters = getFunctionParameters$2(node); + + if (parameters.length !== 1) { + return false; + } + + const [parameter] = parameters; + return !hasComment$9(parameter) && (parameter.type === "ObjectPattern" || parameter.type === "ArrayPattern" || parameter.type === "Identifier" && parameter.typeAnnotation && (parameter.typeAnnotation.type === "TypeAnnotation" || parameter.typeAnnotation.type === "TSTypeAnnotation") && isObjectType$1(parameter.typeAnnotation.typeAnnotation) || parameter.type === "FunctionTypeParam" && isObjectType$1(parameter.typeAnnotation) || parameter.type === "AssignmentPattern" && (parameter.left.type === "ObjectPattern" || parameter.left.type === "ArrayPattern") && (parameter.right.type === "Identifier" || parameter.right.type === "ObjectExpression" && parameter.right.properties.length === 0 || parameter.right.type === "ArrayExpression" && parameter.right.elements.length === 0)); +} + +function getReturnTypeNode(functionNode) { + let returnTypeNode; + + if (functionNode.returnType) { + returnTypeNode = functionNode.returnType; + + if (returnTypeNode.typeAnnotation) { + returnTypeNode = returnTypeNode.typeAnnotation; + } + } else if (functionNode.typeAnnotation) { + returnTypeNode = functionNode.typeAnnotation; + } + + return returnTypeNode; +} // When parameters are grouped, the return type annotation breaks first. + + +function shouldGroupFunctionParameters$3(functionNode, returnTypeDoc) { + const returnTypeNode = getReturnTypeNode(functionNode); + + if (!returnTypeNode) { + return false; + } + + const typeParameters = functionNode.typeParameters && functionNode.typeParameters.params; + + if (typeParameters) { + if (typeParameters.length > 1) { + return false; + } + + if (typeParameters.length === 1) { + const typeParameter = typeParameters[0]; + + if (typeParameter.constraint || typeParameter.default) { + return false; + } + } + } + + return getFunctionParameters$2(functionNode).length === 1 && (isObjectType$1(returnTypeNode) || willBreak$1(returnTypeDoc)); +} + +var functionParameters = { + printFunctionParameters: printFunctionParameters$3, + shouldHugFunctionParameters: shouldHugFunctionParameters$1, + shouldGroupFunctionParameters: shouldGroupFunctionParameters$3 +}; + +const { + printComments: printComments$2, + printDanglingComments: printDanglingComments$9 +} = comments$1; +const { + getLast: getLast$6 +} = util$5; +const { + builders: { + group: group$n, + join: join$k, + line: line$k, + softline: softline$h, + indent: indent$i, + align: align$3, + ifBreak: ifBreak$g + } +} = doc; +const { + locStart: locStart$l +} = loc$6; +const { + isSimpleType, + isObjectType, + hasLeadingOwnLineComment: hasLeadingOwnLineComment$1, + isObjectTypePropertyAFunction, + shouldPrintComma: shouldPrintComma$7 +} = utils$5; +const { + printAssignment: printAssignment$2 +} = assignment; +const { + printFunctionParameters: printFunctionParameters$2, + shouldGroupFunctionParameters: shouldGroupFunctionParameters$2 +} = functionParameters; +const { + printArrayItems: printArrayItems$2 +} = array; + +function shouldHugType$2(node) { + if (isSimpleType(node) || isObjectType(node)) { + return true; + } + + if (node.type === "UnionTypeAnnotation" || node.type === "TSUnionType") { + const voidCount = node.types.filter(node => node.type === "VoidTypeAnnotation" || node.type === "TSVoidKeyword" || node.type === "NullLiteralTypeAnnotation" || node.type === "TSNullKeyword").length; + const hasObject = node.types.some(node => node.type === "ObjectTypeAnnotation" || node.type === "TSTypeLiteral" || // This is a bit aggressive but captures Array<{x}> + node.type === "GenericTypeAnnotation" || node.type === "TSTypeReference"); + + if (node.types.length - 1 === voidCount && hasObject) { + return true; + } + } + + return false; +} + +function printOpaqueType$1(path, options, print) { + const semi = options.semi ? ";" : ""; + const node = path.getValue(); + const parts = []; + parts.push("opaque type ", print("id"), print("typeParameters")); + + if (node.supertype) { + parts.push(": ", print("supertype")); + } + + if (node.impltype) { + parts.push(" = ", print("impltype")); + } + + parts.push(semi); + return parts; +} + +function printTypeAlias$2(path, options, print) { + const semi = options.semi ? ";" : ""; + const node = path.getValue(); + const parts = []; + + if (node.declare) { + parts.push("declare "); + } + + parts.push("type ", print("id"), print("typeParameters")); + const rightPropertyName = node.type === "TSTypeAliasDeclaration" ? "typeAnnotation" : "right"; + return [printAssignment$2(path, options, print, parts, " =", rightPropertyName), semi]; +} // `TSIntersectionType` and `IntersectionTypeAnnotation` + + +function printIntersectionType$2(path, options, print) { + const node = path.getValue(); + const types = path.map(print, "types"); + const result = []; + let wasIndented = false; + + for (let i = 0; i < types.length; ++i) { + if (i === 0) { + result.push(types[i]); + } else if (isObjectType(node.types[i - 1]) && isObjectType(node.types[i])) { + // If both are objects, don't indent + result.push([" & ", wasIndented ? indent$i(types[i]) : types[i]]); + } else if (!isObjectType(node.types[i - 1]) && !isObjectType(node.types[i])) { + // If no object is involved, go to the next line if it breaks + result.push(indent$i([" &", line$k, types[i]])); + } else { + // If you go from object to non-object or vis-versa, then inline it + if (i > 1) { + wasIndented = true; + } + + result.push(" & ", i > 1 ? indent$i(types[i]) : types[i]); + } + } + + return group$n(result); +} // `TSUnionType` and `UnionTypeAnnotation` + + +function printUnionType$2(path, options, print) { + const node = path.getValue(); // single-line variation + // A | B | C + // multi-line variation + // | A + // | B + // | C + + const parent = path.getParentNode(); // If there's a leading comment, the parent is doing the indentation + + const shouldIndent = parent.type !== "TypeParameterInstantiation" && parent.type !== "TSTypeParameterInstantiation" && parent.type !== "GenericTypeAnnotation" && parent.type !== "TSTypeReference" && parent.type !== "TSTypeAssertion" && parent.type !== "TupleTypeAnnotation" && parent.type !== "TSTupleType" && !(parent.type === "FunctionTypeParam" && !parent.name && path.getParentNode(1).this !== parent) && !((parent.type === "TypeAlias" || parent.type === "VariableDeclarator" || parent.type === "TSTypeAliasDeclaration") && hasLeadingOwnLineComment$1(options.originalText, node)); // { + // a: string + // } | null | void + // should be inlined and not be printed in the multi-line variant + + const shouldHug = shouldHugType$2(node); // We want to align the children but without its comment, so it looks like + // | child1 + // // comment + // | child2 + + const printed = path.map(typePath => { + let printedType = print(); + + if (!shouldHug) { + printedType = align$3(2, printedType); + } + + return printComments$2(typePath, printedType, options); + }, "types"); + + if (shouldHug) { + return join$k(" | ", printed); + } + + const shouldAddStartLine = shouldIndent && !hasLeadingOwnLineComment$1(options.originalText, node); + const code = [ifBreak$g([shouldAddStartLine ? line$k : "", "| "]), join$k([line$k, "| "], printed)]; + + if (needsParens_1(path, options)) { + return group$n([indent$i(code), softline$h]); + } + + if (parent.type === "TupleTypeAnnotation" && parent.types.length > 1 || parent.type === "TSTupleType" && parent.elementTypes.length > 1) { + return group$n([indent$i([ifBreak$g(["(", softline$h]), code]), softline$h, ifBreak$g(")")]); + } + + return group$n(shouldIndent ? indent$i(code) : code); +} // `TSFunctionType` and `FunctionTypeAnnotation` + + +function printFunctionType$2(path, options, print) { + const node = path.getValue(); + const parts = []; // FunctionTypeAnnotation is ambiguous: + // declare function foo(a: B): void; OR + // var A: (a: B) => void; + + const parent = path.getParentNode(0); + const parentParent = path.getParentNode(1); + const parentParentParent = path.getParentNode(2); + let isArrowFunctionTypeAnnotation = node.type === "TSFunctionType" || !((parent.type === "ObjectTypeProperty" || parent.type === "ObjectTypeInternalSlot") && !parent.variance && !parent.optional && locStart$l(parent) === locStart$l(node) || parent.type === "ObjectTypeCallProperty" || parentParentParent && parentParentParent.type === "DeclareFunction"); + let needsColon = isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation"); // Sadly we can't put it inside of AstPath::needsColon because we are + // printing ":" as part of the expression and it would put parenthesis + // around :( + + const needsParens = needsColon && isArrowFunctionTypeAnnotation && (parent.type === "TypeAnnotation" || parent.type === "TSTypeAnnotation") && parentParent.type === "ArrowFunctionExpression"; + + if (isObjectTypePropertyAFunction(parent)) { + isArrowFunctionTypeAnnotation = true; + needsColon = true; + } + + if (needsParens) { + parts.push("("); + } + + const parametersDoc = printFunctionParameters$2(path, print, options, + /* expandArg */ + false, + /* printTypeParams */ + true); // The returnType is not wrapped in a TypeAnnotation, so the colon + // needs to be added separately. + + const returnTypeDoc = node.returnType || node.predicate || node.typeAnnotation ? [isArrowFunctionTypeAnnotation ? " => " : ": ", print("returnType"), print("predicate"), print("typeAnnotation")] : ""; + const shouldGroupParameters = shouldGroupFunctionParameters$2(node, returnTypeDoc); + parts.push(shouldGroupParameters ? group$n(parametersDoc) : parametersDoc); + + if (returnTypeDoc) { + parts.push(returnTypeDoc); + } + + if (needsParens) { + parts.push(")"); + } + + return group$n(parts); +} // `TSTupleType` and `TupleTypeAnnotation` + + +function printTupleType$2(path, options, print) { + const node = path.getValue(); + const typesField = node.type === "TSTupleType" ? "elementTypes" : "types"; + const hasRest = node[typesField].length > 0 && getLast$6(node[typesField]).type === "TSRestType"; + return group$n(["[", indent$i([softline$h, printArrayItems$2(path, options, typesField, print)]), ifBreak$g(shouldPrintComma$7(options, "all") && !hasRest ? "," : ""), printDanglingComments$9(path, options, + /* sameIndent */ + true), softline$h, "]"]); +} // `TSIndexedAccessType`, `IndexedAccessType`, and `OptionalIndexedAccessType` + + +function printIndexedAccessType$2(path, options, print) { + const node = path.getValue(); + const leftDelimiter = node.type === "OptionalIndexedAccessType" && node.optional ? "?.[" : "["; + return [print("objectType"), leftDelimiter, print("indexType"), "]"]; +} + +var typeAnnotation = { + printOpaqueType: printOpaqueType$1, + printTypeAlias: printTypeAlias$2, + printIntersectionType: printIntersectionType$2, + printUnionType: printUnionType$2, + printFunctionType: printFunctionType$2, + printTupleType: printTupleType$2, + printIndexedAccessType: printIndexedAccessType$2, + shouldHugType: shouldHugType$2 +}; + +const { + printDanglingComments: printDanglingComments$8 +} = comments$1; +const { + builders: { + join: join$j, + line: line$j, + hardline: hardline$o, + softline: softline$g, + group: group$m, + indent: indent$h, + ifBreak: ifBreak$f + } +} = doc; +const { + isTestCall, + hasComment: hasComment$8, + CommentCheckFlags: CommentCheckFlags$8, + isTSXFile, + shouldPrintComma: shouldPrintComma$6, + getFunctionParameters: getFunctionParameters$1 +} = utils$5; +const { + createGroupIdMapper: createGroupIdMapper$1 +} = util$5; +const { + shouldHugType: shouldHugType$1 +} = typeAnnotation; +const getTypeParametersGroupId$2 = createGroupIdMapper$1("typeParameters"); + +function printTypeParameters$2(path, options, print, paramsKey) { + const node = path.getValue(); + + if (!node[paramsKey]) { + return ""; + } // for TypeParameterDeclaration typeParameters is a single node + + + if (!Array.isArray(node[paramsKey])) { + return print(paramsKey); + } + + const grandparent = path.getNode(2); + const isParameterInTestCall = grandparent && isTestCall(grandparent); + const shouldInline = isParameterInTestCall || node[paramsKey].length === 0 || node[paramsKey].length === 1 && (shouldHugType$1(node[paramsKey][0]) || node[paramsKey][0].type === "NullableTypeAnnotation"); + + if (shouldInline) { + return ["<", join$j(", ", path.map(print, paramsKey)), printDanglingCommentsForInline(path, options), ">"]; + } // Keep comma if the file extension is .tsx and + // has one type parameter that isn't extend with any types. + // Because, otherwise formatted result will be invalid as tsx. + + + const trailingComma = node.type === "TSTypeParameterInstantiation" // https://github.com/microsoft/TypeScript/issues/21984 + ? "" : getFunctionParameters$1(node).length === 1 && isTSXFile(options) && !node[paramsKey][0].constraint && path.getParentNode().type === "ArrowFunctionExpression" ? "," : shouldPrintComma$6(options, "all") ? ifBreak$f(",") : ""; + return group$m(["<", indent$h([softline$g, join$j([",", line$j], path.map(print, paramsKey))]), trailingComma, softline$g, ">"], { + id: getTypeParametersGroupId$2(node) + }); +} + +function printDanglingCommentsForInline(path, options) { + const node = path.getValue(); + + if (!hasComment$8(node, CommentCheckFlags$8.Dangling)) { + return ""; + } + + const hasOnlyBlockComments = !hasComment$8(node, CommentCheckFlags$8.Line); + const printed = printDanglingComments$8(path, options, + /* sameIndent */ + hasOnlyBlockComments); + + if (hasOnlyBlockComments) { + return printed; + } + + return [printed, hardline$o]; +} + +function printTypeParameter$2(path, options, print) { + const node = path.getValue(); + const parts = []; + const parent = path.getParentNode(); + + if (parent.type === "TSMappedType") { + parts.push("[", print("name")); + + if (node.constraint) { + parts.push(" in ", print("constraint")); + } + + if (parent.nameType) { + parts.push(" as ", path.callParent(() => print("nameType"))); + } + + parts.push("]"); + return parts; + } + + if (node.variance) { + parts.push(print("variance")); + } + + parts.push(print("name")); + + if (node.bound) { + parts.push(": ", print("bound")); + } + + if (node.constraint) { + parts.push(" extends ", print("constraint")); + } + + if (node.default) { + parts.push(" = ", print("default")); + } + + return parts; +} + +var typeParameters = { + printTypeParameter: printTypeParameter$2, + printTypeParameters: printTypeParameters$2, + getTypeParametersGroupId: getTypeParametersGroupId$2 +}; + +const { + printComments: printComments$1 +} = comments$1; +const { + printString: printString$3, + printNumber: printNumber$3 +} = util$5; +const { + isNumericLiteral, + isSimpleNumber, + isStringLiteral, + isStringPropSafeToUnquote, + rawText: rawText$2 +} = utils$5; +const { + printAssignment: printAssignment$1 +} = assignment; +const needsQuoteProps = new WeakMap(); + +function printPropertyKey$4(path, options, print) { + const node = path.getNode(); + + if (node.computed) { + return ["[", print("key"), "]"]; + } + + const parent = path.getParentNode(); + const { + key + } = node; // flow has `Identifier` key, other parsers use `PrivateIdentifier` (ESTree) or `PrivateName` + + if (node.type === "ClassPrivateProperty" && key.type === "Identifier") { + return ["#", print("key")]; + } + + if (options.quoteProps === "consistent" && !needsQuoteProps.has(parent)) { + const objectHasStringProp = (parent.properties || parent.body || parent.members).some(prop => !prop.computed && prop.key && isStringLiteral(prop.key) && !isStringPropSafeToUnquote(prop, options)); + needsQuoteProps.set(parent, objectHasStringProp); + } + + if ((key.type === "Identifier" || isNumericLiteral(key) && isSimpleNumber(printNumber$3(rawText$2(key))) && // Avoid converting 999999999999999999999 to 1e+21, 0.99999999999999999 to 1 and 1.0 to 1. + String(key.value) === printNumber$3(rawText$2(key)) && // Quoting number keys is safe in JS and Flow, but not in TypeScript (as + // mentioned in `isStringPropSafeToUnquote`). + !(options.parser === "typescript" || options.parser === "babel-ts")) && (options.parser === "json" || options.quoteProps === "consistent" && needsQuoteProps.get(parent))) { + // a -> "a" + // 1 -> "1" + // 1.5 -> "1.5" + const prop = printString$3(JSON.stringify(key.type === "Identifier" ? key.name : key.value.toString()), options); + return path.call(keyPath => printComments$1(keyPath, prop, options), "key"); + } + + if (isStringPropSafeToUnquote(node, options) && (options.quoteProps === "as-needed" || options.quoteProps === "consistent" && !needsQuoteProps.get(parent))) { + // 'a' -> a + // '1' -> 1 + // '1.5' -> 1.5 + return path.call(keyPath => printComments$1(keyPath, /^\d/.test(key.value) ? printNumber$3(key.value) : key.value, options), "key"); + } + + return print("key"); +} + +function printProperty$1(path, options, print) { + const node = path.getValue(); + + if (node.shorthand) { + return print("value"); + } + + return printAssignment$1(path, options, print, printPropertyKey$4(path, options, print), ":", "value"); +} + +var property = { + printProperty: printProperty$1, + printPropertyKey: printPropertyKey$4 +}; + +/** @typedef {import("../../document/doc-builders").Doc} Doc */ + + +const { + printDanglingComments: printDanglingComments$7, + printCommentsSeparately +} = comments$1; +const { + getNextNonSpaceNonCommentCharacterIndex +} = util$5; +const { + builders: { + line: line$i, + softline: softline$f, + group: group$l, + indent: indent$g, + ifBreak: ifBreak$e, + hardline: hardline$n, + join: join$i, + indentIfBreak: indentIfBreak$1 + }, + utils: { + removeLines: removeLines$1, + willBreak + } +} = doc; +const { + ArgExpansionBailout +} = errors; +const { + getFunctionParameters, + hasLeadingOwnLineComment, + isFlowAnnotationComment, + isJsxNode: isJsxNode$2, + isTemplateOnItsOwnLine, + shouldPrintComma: shouldPrintComma$5, + startsWithNoLookaheadToken, + isBinaryish, + isLineComment: isLineComment$2, + hasComment: hasComment$7, + getComments: getComments$2, + CommentCheckFlags: CommentCheckFlags$7, + isCallLikeExpression, + isCallExpression: isCallExpression$3, + getCallArguments, + hasNakedLeftSide: hasNakedLeftSide$1, + getLeftSide +} = utils$5; +const { + locEnd: locEnd$j +} = loc$6; +const { + printFunctionParameters: printFunctionParameters$1, + shouldGroupFunctionParameters: shouldGroupFunctionParameters$1 +} = functionParameters; +const { + printPropertyKey: printPropertyKey$3 +} = property; +const { + printFunctionTypeParameters +} = misc$1; + +function printFunction$2(path, print, options, args) { + const node = path.getValue(); + let expandArg = false; + + if ((node.type === "FunctionDeclaration" || node.type === "FunctionExpression") && args && args.expandLastArg) { + const parent = path.getParentNode(); + + if (isCallExpression$3(parent) && getCallArguments(parent).length > 1) { + expandArg = true; + } + } + + const parts = []; // For TypeScript the TSDeclareFunction node shares the AST + // structure with FunctionDeclaration + + if (node.type === "TSDeclareFunction" && node.declare) { + parts.push("declare "); + } + + if (node.async) { + parts.push("async "); + } + + if (node.generator) { + parts.push("function* "); + } else { + parts.push("function "); + } + + if (node.id) { + parts.push(print("id")); + } + + const parametersDoc = printFunctionParameters$1(path, print, options, expandArg); + const returnTypeDoc = printReturnType(path, print, options); + const shouldGroupParameters = shouldGroupFunctionParameters$1(node, returnTypeDoc); + parts.push(printFunctionTypeParameters(path, options, print), group$l([shouldGroupParameters ? group$l(parametersDoc) : parametersDoc, returnTypeDoc]), node.body ? " " : "", print("body")); + + if (options.semi && (node.declare || !node.body)) { + parts.push(";"); + } + + return parts; +} + +function printMethod$2(path, options, print) { + const node = path.getNode(); + const { + kind + } = node; + const value = node.value || node; + const parts = []; + + if (!kind || kind === "init" || kind === "method" || kind === "constructor") { + if (value.async) { + parts.push("async "); + } + } else { + assert__default['default'].ok(kind === "get" || kind === "set"); + parts.push(kind, " "); + } // A `getter`/`setter` can't be a generator, but it's recoverable + + + if (value.generator) { + parts.push("*"); + } + + parts.push(printPropertyKey$3(path, options, print), node.optional || node.key.optional ? "?" : ""); + + if (node === value) { + parts.push(printMethodInternal$1(path, options, print)); + } else if (value.type === "FunctionExpression") { + parts.push(path.call(path => printMethodInternal$1(path, options, print), "value")); + } else { + parts.push(print("value")); + } + + return parts; +} + +function printMethodInternal$1(path, options, print) { + const node = path.getNode(); + const parametersDoc = printFunctionParameters$1(path, print, options); + const returnTypeDoc = printReturnType(path, print, options); + const shouldGroupParameters = shouldGroupFunctionParameters$1(node, returnTypeDoc); + const parts = [printFunctionTypeParameters(path, options, print), group$l([shouldGroupParameters ? group$l(parametersDoc) : parametersDoc, returnTypeDoc])]; + + if (node.body) { + parts.push(" ", print("body")); + } else { + parts.push(options.semi ? ";" : ""); + } + + return parts; +} + +function printArrowFunctionSignature(path, options, print, args) { + const node = path.getValue(); + const parts = []; + + if (node.async) { + parts.push("async "); + } + + if (shouldPrintParamsWithoutParens$1(path, options)) { + parts.push(print(["params", 0])); + } else { + const expandArg = args && (args.expandLastArg || args.expandFirstArg); + let returnTypeDoc = printReturnType(path, print, options); + + if (expandArg) { + if (willBreak(returnTypeDoc)) { + throw new ArgExpansionBailout(); + } + + returnTypeDoc = group$l(removeLines$1(returnTypeDoc)); + } + + parts.push(group$l([printFunctionParameters$1(path, print, options, expandArg, + /* printTypeParams */ + true), returnTypeDoc])); + } + + const dangling = printDanglingComments$7(path, options, + /* sameIndent */ + true, comment => { + const nextCharacter = getNextNonSpaceNonCommentCharacterIndex(options.originalText, comment, locEnd$j); + return nextCharacter !== false && options.originalText.slice(nextCharacter, nextCharacter + 2) === "=>"; + }); + + if (dangling) { + parts.push(" ", dangling); + } + + return parts; +} + +function printArrowChain(path, args, signatures, shouldBreak, bodyDoc, tailNode) { + const name = path.getName(); + const parent = path.getParentNode(); + const isCallee = isCallLikeExpression(parent) && name === "callee"; + const isAssignmentRhs = Boolean(args && args.assignmentLayout); + const shouldPutBodyOnSeparateLine = tailNode.body.type !== "BlockStatement" && tailNode.body.type !== "ObjectExpression"; + const shouldBreakBeforeChain = isCallee && shouldPutBodyOnSeparateLine || args && args.assignmentLayout === "chain-tail-arrow-chain"; + const groupId = Symbol("arrow-chain"); + return group$l([group$l(indent$g([isCallee || isAssignmentRhs ? softline$f : "", group$l(join$i([" =>", line$i], signatures), { + shouldBreak + })]), { + id: groupId, + shouldBreak: shouldBreakBeforeChain + }), " =>", indentIfBreak$1(shouldPutBodyOnSeparateLine ? indent$g([line$i, bodyDoc]) : [" ", bodyDoc], { + groupId + }), isCallee ? ifBreak$e(softline$f, "", { + groupId + }) : ""]); +} + +function printArrowFunction$1(path, options, print, args) { + let node = path.getValue(); + /** @type {Doc[]} */ + + const signatures = []; + const body = []; + let chainShouldBreak = false; + + (function rec() { + const doc = printArrowFunctionSignature(path, options, print, args); + + if (signatures.length === 0) { + signatures.push(doc); + } else { + const { + leading, + trailing + } = printCommentsSeparately(path, options); + signatures.push([leading, doc]); + body.unshift(trailing); + } + + chainShouldBreak = chainShouldBreak || // Always break the chain if: + node.returnType && getFunctionParameters(node).length > 0 || node.typeParameters || getFunctionParameters(node).some(param => param.type !== "Identifier"); + + if (node.body.type !== "ArrowFunctionExpression" || args && args.expandLastArg) { + body.unshift(print("body", args)); + } else { + node = node.body; + path.call(rec, "body"); + } + })(); + + if (signatures.length > 1) { + return printArrowChain(path, args, signatures, chainShouldBreak, body, node); + } + + const parts = signatures; + parts.push(" =>"); // We want to always keep these types of nodes on the same line + // as the arrow. + + if (!hasLeadingOwnLineComment(options.originalText, node.body) && (node.body.type === "ArrayExpression" || node.body.type === "ObjectExpression" || node.body.type === "BlockStatement" || isJsxNode$2(node.body) || isTemplateOnItsOwnLine(node.body, options.originalText) || node.body.type === "ArrowFunctionExpression" || node.body.type === "DoExpression")) { + return group$l([...parts, " ", body]); + } // We handle sequence expressions as the body of arrows specially, + // so that the required parentheses end up on their own lines. + + + if (node.body.type === "SequenceExpression") { + return group$l([...parts, group$l([" (", indent$g([softline$f, body]), softline$f, ")"])]); + } // if the arrow function is expanded as last argument, we are adding a + // level of indentation and need to add a softline to align the closing ) + // with the opening (, or if it's inside a JSXExpression (e.g. an attribute) + // we should align the expression's closing } with the line with the opening {. + + + const shouldAddSoftLine = (args && args.expandLastArg || path.getParentNode().type === "JSXExpressionContainer") && !hasComment$7(node); + const printTrailingComma = args && args.expandLastArg && shouldPrintComma$5(options, "all"); // In order to avoid confusion between + // a => a ? a : a + // a <= a ? a : a + + const shouldAddParens = node.body.type === "ConditionalExpression" && !startsWithNoLookaheadToken(node.body, + /* forbidFunctionAndClass */ + false); + return group$l([...parts, group$l([indent$g([line$i, shouldAddParens ? ifBreak$e("", "(") : "", body, shouldAddParens ? ifBreak$e("", ")") : ""]), shouldAddSoftLine ? [ifBreak$e(printTrailingComma ? "," : ""), softline$f] : ""])]); +} + +function canPrintParamsWithoutParens(node) { + const parameters = getFunctionParameters(node); + return parameters.length === 1 && !node.typeParameters && !hasComment$7(node, CommentCheckFlags$7.Dangling) && parameters[0].type === "Identifier" && !parameters[0].typeAnnotation && !hasComment$7(parameters[0]) && !parameters[0].optional && !node.predicate && !node.returnType; +} + +function shouldPrintParamsWithoutParens$1(path, options) { + if (options.arrowParens === "always") { + return false; + } + + if (options.arrowParens === "avoid") { + const node = path.getValue(); + return canPrintParamsWithoutParens(node); + } // Fallback default; should be unreachable + + /* istanbul ignore next */ + + + return false; +} +/** @returns {Doc} */ + + +function printReturnType(path, print, options) { + const node = path.getValue(); + const returnType = print("returnType"); + + if (node.returnType && isFlowAnnotationComment(options.originalText, node.returnType)) { + return [" /*: ", returnType, " */"]; + } + + const parts = [returnType]; // prepend colon to TypeScript type annotation + + if (node.returnType && node.returnType.typeAnnotation) { + parts.unshift(": "); + } + + if (node.predicate) { + // The return type will already add the colon, but otherwise we + // need to do it ourselves + parts.push(node.returnType ? " " : ": ", print("predicate")); + } + + return parts; +} // `ReturnStatement` and `ThrowStatement` + + +function printReturnOrThrowArgument(path, options, print) { + const node = path.getValue(); + const semi = options.semi ? ";" : ""; + const parts = []; + + if (node.argument) { + if (returnArgumentHasLeadingComment(options, node.argument)) { + parts.push([" (", indent$g([hardline$n, print("argument")]), hardline$n, ")"]); + } else if (isBinaryish(node.argument) || node.argument.type === "SequenceExpression") { + parts.push(group$l([ifBreak$e(" (", " "), indent$g([softline$f, print("argument")]), softline$f, ifBreak$e(")")])); + } else { + parts.push(" ", print("argument")); + } + } + + const comments = getComments$2(node); + const lastComment = getLast_1(comments); + const isLastCommentLine = lastComment && isLineComment$2(lastComment); + + if (isLastCommentLine) { + parts.push(semi); + } + + if (hasComment$7(node, CommentCheckFlags$7.Dangling)) { + parts.push(" ", printDanglingComments$7(path, options, + /* sameIndent */ + true)); + } + + if (!isLastCommentLine) { + parts.push(semi); + } + + return parts; +} + +function printReturnStatement$1(path, options, print) { + return ["return", printReturnOrThrowArgument(path, options, print)]; +} + +function printThrowStatement$1(path, options, print) { + return ["throw", printReturnOrThrowArgument(path, options, print)]; +} // This recurses the return argument, looking for the first token +// (the leftmost leaf node) and, if it (or its parents) has any +// leadingComments, returns true (so it can be wrapped in parens). + + +function returnArgumentHasLeadingComment(options, argument) { + if (hasLeadingOwnLineComment(options.originalText, argument)) { + return true; + } + + if (hasNakedLeftSide$1(argument)) { + let leftMost = argument; + let newLeftMost; + + while (newLeftMost = getLeftSide(leftMost)) { + leftMost = newLeftMost; + + if (hasLeadingOwnLineComment(options.originalText, leftMost)) { + return true; + } + } + } + + return false; +} + +var _function = { + printFunction: printFunction$2, + printArrowFunction: printArrowFunction$1, + printMethod: printMethod$2, + printReturnStatement: printReturnStatement$1, + printThrowStatement: printThrowStatement$1, + printMethodInternal: printMethodInternal$1, + shouldPrintParamsWithoutParens: shouldPrintParamsWithoutParens$1 +}; + +const { + isNonEmptyArray: isNonEmptyArray$c, + hasNewline: hasNewline$4 +} = util$5; +const { + builders: { + line: line$h, + hardline: hardline$m, + join: join$h, + breakParent: breakParent$5, + group: group$k + } +} = doc; +const { + locStart: locStart$k, + locEnd: locEnd$i +} = loc$6; +const { + getParentExportDeclaration: getParentExportDeclaration$1 +} = utils$5; + +function printClassMemberDecorators$1(path, options, print) { + const node = path.getValue(); + return group$k([join$h(line$h, path.map(print, "decorators")), hasNewlineBetweenOrAfterDecorators(node, options) ? hardline$m : line$h]); +} + +function printDecoratorsBeforeExport$1(path, options, print) { + // Export declarations are responsible for printing any decorators + // that logically apply to node.declaration. + return [join$h(hardline$m, path.map(print, "declaration", "decorators")), hardline$m]; +} + +function printDecorators$1(path, options, print) { + const node = path.getValue(); + const { + decorators + } = node; + + if (!isNonEmptyArray$c(decorators) || // If the parent node is an export declaration and the decorator + // was written before the export, the export will be responsible + // for printing the decorators. + hasDecoratorsBeforeExport$1(path.getParentNode())) { + return; + } + + const shouldBreak = node.type === "ClassExpression" || node.type === "ClassDeclaration" || hasNewlineBetweenOrAfterDecorators(node, options); + return [getParentExportDeclaration$1(path) ? hardline$m : shouldBreak ? breakParent$5 : "", join$h(line$h, path.map(print, "decorators")), line$h]; +} + +function hasNewlineBetweenOrAfterDecorators(node, options) { + return node.decorators.some(decorator => hasNewline$4(options.originalText, locEnd$i(decorator))); +} + +function hasDecoratorsBeforeExport$1(node) { + if (node.type !== "ExportDefaultDeclaration" && node.type !== "ExportNamedDeclaration" && node.type !== "DeclareExportDeclaration") { + return false; + } + + const decorators = node.declaration && node.declaration.decorators; + return isNonEmptyArray$c(decorators) && locStart$k(node, { + ignoreDecorators: true + }) > locStart$k(decorators[0]); +} + +var decorators = { + printDecorators: printDecorators$1, + printClassMemberDecorators: printClassMemberDecorators$1, + printDecoratorsBeforeExport: printDecoratorsBeforeExport$1, + hasDecoratorsBeforeExport: hasDecoratorsBeforeExport$1 +}; + +const { + isNonEmptyArray: isNonEmptyArray$b, + createGroupIdMapper +} = util$5; +const { + printComments, + printDanglingComments: printDanglingComments$6 +} = comments$1; +const { + builders: { + join: join$g, + line: line$g, + hardline: hardline$l, + softline: softline$e, + group: group$j, + indent: indent$f, + ifBreak: ifBreak$d + } +} = doc; +const { + hasComment: hasComment$6, + CommentCheckFlags: CommentCheckFlags$6 +} = utils$5; +const { + getTypeParametersGroupId: getTypeParametersGroupId$1 +} = typeParameters; +const { + printMethod: printMethod$1 +} = _function; +const { + printOptionalToken: printOptionalToken$4, + printTypeAnnotation: printTypeAnnotation$3 +} = misc$1; +const { + printPropertyKey: printPropertyKey$2 +} = property; +const { + printAssignment +} = assignment; +const { + printClassMemberDecorators +} = decorators; + +function printClass$2(path, options, print) { + const node = path.getValue(); + const parts = []; + + if (node.declare) { + parts.push("declare "); + } + + if (node.abstract) { + parts.push("abstract "); + } + + parts.push("class"); // Keep old behaviour of extends in same line + // If there is only on extends and there are not comments + + const groupMode = node.id && hasComment$6(node.id, CommentCheckFlags$6.Trailing) || node.superClass && hasComment$6(node.superClass) || isNonEmptyArray$b(node.extends) || // DeclareClass + isNonEmptyArray$b(node.mixins) || isNonEmptyArray$b(node.implements); + const partsGroup = []; + const extendsParts = []; + + if (node.id) { + partsGroup.push(" ", print("id")); + } + + partsGroup.push(print("typeParameters")); + + if (node.superClass) { + const printed = ["extends ", printSuperClass(path, options, print), print("superTypeParameters")]; + const printedWithComments = path.call(superClass => printComments(superClass, printed, options), "superClass"); + + if (groupMode) { + extendsParts.push(line$g, group$j(printedWithComments)); + } else { + extendsParts.push(" ", printedWithComments); + } + } else { + extendsParts.push(printList(path, options, print, "extends")); + } + + extendsParts.push(printList(path, options, print, "mixins"), printList(path, options, print, "implements")); + + if (groupMode) { + let printedPartsGroup; + + if (shouldIndentOnlyHeritageClauses(node)) { + printedPartsGroup = [...partsGroup, indent$f(extendsParts)]; + } else { + printedPartsGroup = indent$f([...partsGroup, extendsParts]); + } + + parts.push(group$j(printedPartsGroup, { + id: getHeritageGroupId(node) + })); + } else { + parts.push(...partsGroup, ...extendsParts); + } + + parts.push(" ", print("body")); + return parts; +} + +const getHeritageGroupId = createGroupIdMapper("heritageGroup"); + +function printHardlineAfterHeritage$2(node) { + return ifBreak$d(hardline$l, "", { + groupId: getHeritageGroupId(node) + }); +} + +function hasMultipleHeritage(node) { + return ["superClass", "extends", "mixins", "implements"].filter(key => Boolean(node[key])).length > 1; +} + +function shouldIndentOnlyHeritageClauses(node) { + return node.typeParameters && !hasComment$6(node.typeParameters, CommentCheckFlags$6.Trailing | CommentCheckFlags$6.Line) && !hasMultipleHeritage(node); +} + +function printList(path, options, print, listName) { + const node = path.getValue(); + + if (!isNonEmptyArray$b(node[listName])) { + return ""; + } + + const printedLeadingComments = printDanglingComments$6(path, options, + /* sameIndent */ + true, ({ + marker + }) => marker === listName); + return [shouldIndentOnlyHeritageClauses(node) ? ifBreak$d(" ", line$g, { + groupId: getTypeParametersGroupId$1(node.typeParameters) + }) : line$g, printedLeadingComments, printedLeadingComments && hardline$l, listName, group$j(indent$f([line$g, join$g([",", line$g], path.map(print, listName))]))]; +} + +function printSuperClass(path, options, print) { + const printed = print("superClass"); + const parent = path.getParentNode(); + + if (parent.type === "AssignmentExpression") { + return group$j(ifBreak$d(["(", indent$f([softline$e, printed]), softline$e, ")"], printed)); + } + + return printed; +} + +function printClassMethod$2(path, options, print) { + const node = path.getValue(); + const parts = []; + + if (isNonEmptyArray$b(node.decorators)) { + parts.push(printClassMemberDecorators(path, options, print)); + } + + if (node.accessibility) { + parts.push(node.accessibility + " "); + } // "readonly" and "declare" are supported by only "babel-ts" + // https://github.com/prettier/prettier/issues/9760 + + + if (node.readonly) { + parts.push("readonly "); + } + + if (node.declare) { + parts.push("declare "); + } + + if (node.static) { + parts.push("static "); + } + + if (node.type === "TSAbstractMethodDefinition" || node.abstract) { + parts.push("abstract "); + } + + if (node.override) { + parts.push("override "); + } + + parts.push(printMethod$1(path, options, print)); + return parts; +} + +function printClassProperty$2(path, options, print) { + const node = path.getValue(); + const parts = []; + const semi = options.semi ? ";" : ""; + + if (isNonEmptyArray$b(node.decorators)) { + parts.push(printClassMemberDecorators(path, options, print)); + } + + if (node.accessibility) { + parts.push(node.accessibility + " "); + } + + if (node.declare) { + parts.push("declare "); + } + + if (node.static) { + parts.push("static "); + } + + if (node.type === "TSAbstractClassProperty" || node.abstract) { + parts.push("abstract "); + } + + if (node.override) { + parts.push("override "); + } + + if (node.readonly) { + parts.push("readonly "); + } + + if (node.variance) { + parts.push(print("variance")); + } + + parts.push(printPropertyKey$2(path, options, print), printOptionalToken$4(path), printTypeAnnotation$3(path, options, print)); + return [printAssignment(path, options, print, parts, " =", "value"), semi]; +} + +var _class = { + printClass: printClass$2, + printClassMethod: printClassMethod$2, + printClassProperty: printClassProperty$2, + printHardlineAfterHeritage: printHardlineAfterHeritage$2 +}; + +const { + isNonEmptyArray: isNonEmptyArray$a +} = util$5; +const { + builders: { + join: join$f, + line: line$f, + group: group$i, + indent: indent$e, + ifBreak: ifBreak$c + } +} = doc; +const { + hasComment: hasComment$5, + identity, + CommentCheckFlags: CommentCheckFlags$5 +} = utils$5; +const { + getTypeParametersGroupId +} = typeParameters; +const { + printTypeScriptModifiers: printTypeScriptModifiers$1 +} = misc$1; + +function printInterface$2(path, options, print) { + const node = path.getValue(); + const parts = []; + + if (node.declare) { + parts.push("declare "); + } + + if (node.type === "TSInterfaceDeclaration") { + parts.push(node.abstract ? "abstract " : "", printTypeScriptModifiers$1(path, options, print)); + } + + parts.push("interface"); + const partsGroup = []; + const extendsParts = []; + + if (node.type !== "InterfaceTypeAnnotation") { + partsGroup.push(" ", print("id"), print("typeParameters")); + } + + const shouldIndentOnlyHeritageClauses = node.typeParameters && !hasComment$5(node.typeParameters, CommentCheckFlags$5.Trailing | CommentCheckFlags$5.Line); + + if (isNonEmptyArray$a(node.extends)) { + extendsParts.push(shouldIndentOnlyHeritageClauses ? ifBreak$c(" ", line$f, { + groupId: getTypeParametersGroupId(node.typeParameters) + }) : line$f, "extends ", (node.extends.length === 1 ? identity : indent$e)(join$f([",", line$f], path.map(print, "extends")))); + } + + if (node.id && hasComment$5(node.id, CommentCheckFlags$5.Trailing) || isNonEmptyArray$a(node.extends)) { + if (shouldIndentOnlyHeritageClauses) { + parts.push(group$i([...partsGroup, indent$e(extendsParts)])); + } else { + parts.push(group$i(indent$e([...partsGroup, ...extendsParts]))); + } + } else { + parts.push(...partsGroup, ...extendsParts); + } + + parts.push(" ", print("body")); + return group$i(parts); +} + +var _interface = { + printInterface: printInterface$2 +}; + +const { + isNonEmptyArray: isNonEmptyArray$9 +} = util$5; +const { + builders: { + softline: softline$d, + group: group$h, + indent: indent$d, + join: join$e, + line: line$e, + ifBreak: ifBreak$b, + hardline: hardline$k + } +} = doc; +const { + printDanglingComments: printDanglingComments$5 +} = comments$1; +const { + hasComment: hasComment$4, + CommentCheckFlags: CommentCheckFlags$4, + shouldPrintComma: shouldPrintComma$4, + needsHardlineAfterDanglingComment: needsHardlineAfterDanglingComment$1 +} = utils$5; +const { + locStart: locStart$j, + hasSameLoc +} = loc$6; +const { + hasDecoratorsBeforeExport, + printDecoratorsBeforeExport +} = decorators; +/** + * @typedef {import("../../document").Doc} Doc + */ + +function printImportDeclaration$1(path, options, print) { + const node = path.getValue(); + const semi = options.semi ? ";" : ""; + /** @type{Doc[]} */ + + const parts = []; + const { + importKind + } = node; + parts.push("import"); + + if (importKind && importKind !== "value") { + parts.push(" ", importKind); + } + + parts.push(printModuleSpecifiers(path, options, print), printModuleSource(path, options, print), printImportAssertions(path, options, print), semi); + return parts; +} + +function printExportDeclaration$2(path, options, print) { + const node = path.getValue(); + /** @type{Doc[]} */ + + const parts = []; // Only print decorators here if they were written before the export, + // otherwise they are printed by the node.declaration + + if (hasDecoratorsBeforeExport(node)) { + parts.push(printDecoratorsBeforeExport(path, options, print)); + } + + const { + type, + exportKind, + declaration + } = node; + parts.push("export"); + const isDefaultExport = node.default || type === "ExportDefaultDeclaration"; + + if (isDefaultExport) { + parts.push(" default"); + } + + if (hasComment$4(node, CommentCheckFlags$4.Dangling)) { + parts.push(" ", printDanglingComments$5(path, options, + /* sameIndent */ + true)); + + if (needsHardlineAfterDanglingComment$1(node)) { + parts.push(hardline$k); + } + } + + if (declaration) { + parts.push(" ", print("declaration")); + } else { + parts.push(exportKind === "type" ? " type" : "", printModuleSpecifiers(path, options, print), printModuleSource(path, options, print), printImportAssertions(path, options, print)); + } + + if (shouldExportDeclarationPrintSemi(node, options)) { + parts.push(";"); + } + + return parts; +} + +function printExportAllDeclaration$2(path, options, print) { + const node = path.getValue(); + const semi = options.semi ? ";" : ""; + /** @type{Doc[]} */ + + const parts = []; + const { + exportKind, + exported + } = node; + parts.push("export"); + + if (exportKind === "type") { + parts.push(" type"); + } + + parts.push(" *"); + + if (exported) { + parts.push(" as ", print("exported")); + } + + parts.push(printModuleSource(path, options, print), printImportAssertions(path, options, print), semi); + return parts; +} + +function shouldExportDeclarationPrintSemi(node, options) { + if (!options.semi) { + return false; + } + + const { + type, + declaration + } = node; + const isDefaultExport = node.default || type === "ExportDefaultDeclaration"; + + if (!declaration) { + return true; + } + + const { + type: declarationType + } = declaration; + + if (isDefaultExport && declarationType !== "ClassDeclaration" && declarationType !== "FunctionDeclaration" && declarationType !== "TSInterfaceDeclaration" && declarationType !== "DeclareClass" && declarationType !== "DeclareFunction" && declarationType !== "TSDeclareFunction" && declarationType !== "EnumDeclaration") { + return true; + } + + return false; +} + +function printModuleSource(path, options, print) { + const node = path.getValue(); + + if (!node.source) { + return ""; + } + /** @type{Doc[]} */ + + + const parts = []; + + if (!shouldNotPrintSpecifiers(node, options)) { + parts.push(" from"); + } + + parts.push(" ", print("source")); + return parts; +} + +function printModuleSpecifiers(path, options, print) { + const node = path.getValue(); + + if (shouldNotPrintSpecifiers(node, options)) { + return ""; + } + /** @type{Doc[]} */ + + + const parts = [" "]; + + if (isNonEmptyArray$9(node.specifiers)) { + const standaloneSpecifiers = []; + const groupedSpecifiers = []; + path.each(() => { + const specifierType = path.getValue().type; + + if (specifierType === "ExportNamespaceSpecifier" || specifierType === "ExportDefaultSpecifier" || specifierType === "ImportNamespaceSpecifier" || specifierType === "ImportDefaultSpecifier") { + standaloneSpecifiers.push(print()); + } else if (specifierType === "ExportSpecifier" || specifierType === "ImportSpecifier") { + groupedSpecifiers.push(print()); + } else { + /* istanbul ignore next */ + throw new Error(`Unknown specifier type ${JSON.stringify(specifierType)}`); + } + }, "specifiers"); + parts.push(join$e(", ", standaloneSpecifiers)); + + if (groupedSpecifiers.length > 0) { + if (standaloneSpecifiers.length > 0) { + parts.push(", "); + } + + const canBreak = groupedSpecifiers.length > 1 || standaloneSpecifiers.length > 0 || node.specifiers.some(node => hasComment$4(node)); + + if (canBreak) { + parts.push(group$h(["{", indent$d([options.bracketSpacing ? line$e : softline$d, join$e([",", line$e], groupedSpecifiers)]), ifBreak$b(shouldPrintComma$4(options) ? "," : ""), options.bracketSpacing ? line$e : softline$d, "}"])); + } else { + parts.push(["{", options.bracketSpacing ? " " : "", ...groupedSpecifiers, options.bracketSpacing ? " " : "", "}"]); + } + } + } else { + parts.push("{}"); + } + + return parts; +} + +function shouldNotPrintSpecifiers(node, options) { + const { + type, + importKind, + source, + specifiers + } = node; + + if (type !== "ImportDeclaration" || isNonEmptyArray$9(specifiers) || importKind === "type") { + return false; + } // TODO: check tokens + + + return !/{\s*}/.test(options.originalText.slice(locStart$j(node), locStart$j(source))); +} + +function printImportAssertions(path, options, print) { + const node = path.getNode(); + + if (isNonEmptyArray$9(node.assertions)) { + return [" assert {", options.bracketSpacing ? " " : "", join$e(", ", path.map(print, "assertions")), options.bracketSpacing ? " " : "", "}"]; + } + + return ""; +} + +function printModuleSpecifier$1(path, options, print) { + const node = path.getNode(); + const { + type, + importKind + } = node; + /** @type{Doc[]} */ + + const parts = []; + + if (type === "ImportSpecifier" && importKind) { + parts.push(importKind, " "); + } + + const isImport = type.startsWith("Import"); + const leftSideProperty = isImport ? "imported" : "local"; + const rightSideProperty = isImport ? "local" : "exported"; + let left = ""; + let right = ""; + + if (type === "ExportNamespaceSpecifier" || type === "ImportNamespaceSpecifier") { + left = "*"; + } else if (node[leftSideProperty]) { + left = print(leftSideProperty); + } + + if (node[rightSideProperty] && (!node[leftSideProperty] || // import {a as a} from '.' + !hasSameLoc(node[leftSideProperty], node[rightSideProperty]))) { + right = print(rightSideProperty); + } + + parts.push(left, left && right ? " as " : "", right); + return parts; +} + +var module$1 = { + printImportDeclaration: printImportDeclaration$1, + printExportDeclaration: printExportDeclaration$2, + printExportAllDeclaration: printExportAllDeclaration$2, + printModuleSpecifier: printModuleSpecifier$1 +}; + +const { + printDanglingComments: printDanglingComments$4 +} = comments$1; +const { + builders: { + line: line$d, + softline: softline$c, + group: group$g, + indent: indent$c, + ifBreak: ifBreak$a, + hardline: hardline$j + } +} = doc; +const { + getLast: getLast$5, + hasNewlineInRange: hasNewlineInRange$2, + hasNewline: hasNewline$3, + isNonEmptyArray: isNonEmptyArray$8 +} = util$5; +const { + shouldPrintComma: shouldPrintComma$3, + hasComment: hasComment$3, + getComments: getComments$1, + CommentCheckFlags: CommentCheckFlags$3, + isNextLineEmpty: isNextLineEmpty$7 +} = utils$5; +const { + locStart: locStart$i, + locEnd: locEnd$h +} = loc$6; +const { + printOptionalToken: printOptionalToken$3, + printTypeAnnotation: printTypeAnnotation$2 +} = misc$1; +const { + shouldHugFunctionParameters +} = functionParameters; +const { + shouldHugType +} = typeAnnotation; +const { + printHardlineAfterHeritage: printHardlineAfterHeritage$1 +} = _class; +/** @typedef {import("../../document").Doc} Doc */ + +function printObject$3(path, options, print) { + const semi = options.semi ? ";" : ""; + const node = path.getValue(); + let propertiesField; + + if (node.type === "TSTypeLiteral") { + propertiesField = "members"; + } else if (node.type === "TSInterfaceBody") { + propertiesField = "body"; + } else { + propertiesField = "properties"; + } + + const isTypeAnnotation = node.type === "ObjectTypeAnnotation"; + const fields = [propertiesField]; + + if (isTypeAnnotation) { + fields.push("indexers", "callProperties", "internalSlots"); + } + + const firstProperty = fields.map(field => node[field][0]).sort((a, b) => locStart$i(a) - locStart$i(b))[0]; + const parent = path.getParentNode(0); + const isFlowInterfaceLikeBody = isTypeAnnotation && parent && (parent.type === "InterfaceDeclaration" || parent.type === "DeclareInterface" || parent.type === "DeclareClass") && path.getName() === "body"; + const shouldBreak = node.type === "TSInterfaceBody" || isFlowInterfaceLikeBody || node.type === "ObjectPattern" && parent.type !== "FunctionDeclaration" && parent.type !== "FunctionExpression" && parent.type !== "ArrowFunctionExpression" && parent.type !== "ObjectMethod" && parent.type !== "ClassMethod" && parent.type !== "ClassPrivateMethod" && parent.type !== "AssignmentPattern" && parent.type !== "CatchClause" && node.properties.some(property => property.value && (property.value.type === "ObjectPattern" || property.value.type === "ArrayPattern")) || node.type !== "ObjectPattern" && firstProperty && hasNewlineInRange$2(options.originalText, locStart$i(node), locStart$i(firstProperty)); + const separator = isFlowInterfaceLikeBody ? ";" : node.type === "TSInterfaceBody" || node.type === "TSTypeLiteral" ? ifBreak$a(semi, ";") : ","; + const leftBrace = node.type === "RecordExpression" ? "#{" : node.exact ? "{|" : "{"; + const rightBrace = node.exact ? "|}" : "}"; // Unfortunately, things are grouped together in the ast can be + // interleaved in the source code. So we need to reorder them before + // printing them. + + const propsAndLoc = []; + + for (const field of fields) { + path.each(childPath => { + const node = childPath.getValue(); + propsAndLoc.push({ + node, + printed: print(), + loc: locStart$i(node) + }); + }, field); + } + + if (fields.length > 1) { + propsAndLoc.sort((a, b) => a.loc - b.loc); + } + /** @type {Doc[]} */ + + + let separatorParts = []; + const props = propsAndLoc.map(prop => { + const result = [...separatorParts, group$g(prop.printed)]; + separatorParts = [separator, line$d]; + + if ((prop.node.type === "TSPropertySignature" || prop.node.type === "TSMethodSignature" || prop.node.type === "TSConstructSignatureDeclaration") && hasComment$3(prop.node, CommentCheckFlags$3.PrettierIgnore)) { + separatorParts.shift(); + } + + if (isNextLineEmpty$7(prop.node, options)) { + separatorParts.push(hardline$j); + } + + return result; + }); + + if (node.inexact) { + let printed; + + if (hasComment$3(node, CommentCheckFlags$3.Dangling)) { + const hasLineComments = hasComment$3(node, CommentCheckFlags$3.Line); + const printedDanglingComments = printDanglingComments$4(path, options, + /* sameIndent */ + true); + printed = [printedDanglingComments, hasLineComments || hasNewline$3(options.originalText, locEnd$h(getLast$5(getComments$1(node)))) ? hardline$j : line$d, "..."]; + } else { + printed = ["..."]; + } + + props.push([...separatorParts, ...printed]); + } + + const lastElem = getLast$5(node[propertiesField]); + const canHaveTrailingSeparator = !(node.inexact || lastElem && lastElem.type === "RestElement" || lastElem && (lastElem.type === "TSPropertySignature" || lastElem.type === "TSCallSignatureDeclaration" || lastElem.type === "TSMethodSignature" || lastElem.type === "TSConstructSignatureDeclaration") && hasComment$3(lastElem, CommentCheckFlags$3.PrettierIgnore)); + let content; + + if (props.length === 0) { + if (!hasComment$3(node, CommentCheckFlags$3.Dangling)) { + return [leftBrace, rightBrace, printTypeAnnotation$2(path, options, print)]; + } + + content = group$g([leftBrace, printDanglingComments$4(path, options), softline$c, rightBrace, printOptionalToken$3(path), printTypeAnnotation$2(path, options, print)]); + } else { + content = [isFlowInterfaceLikeBody && isNonEmptyArray$8(node.properties) ? printHardlineAfterHeritage$1(parent) : "", leftBrace, indent$c([options.bracketSpacing ? line$d : softline$c, ...props]), ifBreak$a(canHaveTrailingSeparator && (separator !== "," || shouldPrintComma$3(options)) ? separator : ""), options.bracketSpacing ? line$d : softline$c, rightBrace, printOptionalToken$3(path), printTypeAnnotation$2(path, options, print)]; + } // If we inline the object as first argument of the parent, we don't want + // to create another group so that the object breaks before the return + // type + + + if (path.match(node => node.type === "ObjectPattern" && !node.decorators, (node, name, number) => shouldHugFunctionParameters(node) && (name === "params" || name === "parameters" || name === "this" || name === "rest") && number === 0) || path.match(shouldHugType, (node, name) => name === "typeAnnotation", (node, name) => name === "typeAnnotation", (node, name, number) => shouldHugFunctionParameters(node) && (name === "params" || name === "parameters" || name === "this" || name === "rest") && number === 0) || // Assignment printing logic (printAssignment) is responsible + // for adding a group if needed + !shouldBreak && path.match(node => node.type === "ObjectPattern", node => node.type === "AssignmentExpression" || node.type === "VariableDeclarator")) { + return content; + } + + return group$g(content, { + shouldBreak + }); +} + +var object$1 = { + printObject: printObject$3 +}; + +/** @typedef {import("../../document").Doc} Doc */ + + +const { + printDanglingComments: printDanglingComments$3 +} = comments$1; +const { + printString: printString$2, + printNumber: printNumber$2 +} = util$5; +const { + builders: { + hardline: hardline$i, + softline: softline$b, + group: group$f, + indent: indent$b + } +} = doc; +const { + getParentExportDeclaration, + isFunctionNotation, + isGetterOrSetter, + rawText: rawText$1, + shouldPrintComma: shouldPrintComma$2 +} = utils$5; +const { + locStart: locStart$h, + locEnd: locEnd$g +} = loc$6; +const { + printClass: printClass$1 +} = _class; +const { + printOpaqueType, + printTypeAlias: printTypeAlias$1, + printIntersectionType: printIntersectionType$1, + printUnionType: printUnionType$1, + printFunctionType: printFunctionType$1, + printTupleType: printTupleType$1, + printIndexedAccessType: printIndexedAccessType$1 +} = typeAnnotation; +const { + printInterface: printInterface$1 +} = _interface; +const { + printTypeParameter: printTypeParameter$1, + printTypeParameters: printTypeParameters$1 +} = typeParameters; +const { + printExportDeclaration: printExportDeclaration$1, + printExportAllDeclaration: printExportAllDeclaration$1 +} = module$1; +const { + printArrayItems: printArrayItems$1 +} = array; +const { + printObject: printObject$2 +} = object$1; +const { + printPropertyKey: printPropertyKey$1 +} = property; +const { + printOptionalToken: printOptionalToken$2, + printTypeAnnotation: printTypeAnnotation$1, + printRestSpread: printRestSpread$1 +} = misc$1; + +function printFlow$1(path, options, print) { + const node = path.getValue(); + const semi = options.semi ? ";" : ""; + /** @type{Doc[]} */ + + const parts = []; + + switch (node.type) { + case "DeclareClass": + return printFlowDeclaration(path, printClass$1(path, options, print)); + + case "DeclareFunction": + return printFlowDeclaration(path, ["function ", print("id"), node.predicate ? " " : "", print("predicate"), semi]); + + case "DeclareModule": + return printFlowDeclaration(path, ["module ", print("id"), " ", print("body")]); + + case "DeclareModuleExports": + return printFlowDeclaration(path, ["module.exports", ": ", print("typeAnnotation"), semi]); + + case "DeclareVariable": + return printFlowDeclaration(path, ["var ", print("id"), semi]); + + case "DeclareOpaqueType": + return printFlowDeclaration(path, printOpaqueType(path, options, print)); + + case "DeclareInterface": + return printFlowDeclaration(path, printInterface$1(path, options, print)); + + case "DeclareTypeAlias": + return printFlowDeclaration(path, printTypeAlias$1(path, options, print)); + + case "DeclareExportDeclaration": + return printFlowDeclaration(path, printExportDeclaration$1(path, options, print)); + + case "DeclareExportAllDeclaration": + return printFlowDeclaration(path, printExportAllDeclaration$1(path, options, print)); + + case "OpaqueType": + return printOpaqueType(path, options, print); + + case "TypeAlias": + return printTypeAlias$1(path, options, print); + + case "IntersectionTypeAnnotation": + return printIntersectionType$1(path, options, print); + + case "UnionTypeAnnotation": + return printUnionType$1(path, options, print); + + case "FunctionTypeAnnotation": + return printFunctionType$1(path, options, print); + + case "TupleTypeAnnotation": + return printTupleType$1(path, options, print); + + case "GenericTypeAnnotation": + return [print("id"), printTypeParameters$1(path, options, print, "typeParameters")]; + + case "IndexedAccessType": + case "OptionalIndexedAccessType": + return printIndexedAccessType$1(path, options, print); + // Type Annotations for Facebook Flow, typically stripped out or + // transformed away before printing. + + case "TypeAnnotation": + return print("typeAnnotation"); + + case "TypeParameter": + return printTypeParameter$1(path, options, print); + + case "TypeofTypeAnnotation": + return ["typeof ", print("argument")]; + + case "ExistsTypeAnnotation": + return "*"; + + case "EmptyTypeAnnotation": + return "empty"; + + case "MixedTypeAnnotation": + return "mixed"; + + case "ArrayTypeAnnotation": + return [print("elementType"), "[]"]; + + case "BooleanLiteralTypeAnnotation": + return String(node.value); + + case "EnumDeclaration": + return ["enum ", print("id"), " ", print("body")]; + + case "EnumBooleanBody": + case "EnumNumberBody": + case "EnumStringBody": + case "EnumSymbolBody": + { + if (node.type === "EnumSymbolBody" || node.explicitType) { + let type = null; + + switch (node.type) { + case "EnumBooleanBody": + type = "boolean"; + break; + + case "EnumNumberBody": + type = "number"; + break; + + case "EnumStringBody": + type = "string"; + break; + + case "EnumSymbolBody": + type = "symbol"; + break; + } + + parts.push("of ", type, " "); + } + + if (node.members.length === 0 && !node.hasUnknownMembers) { + parts.push(group$f(["{", printDanglingComments$3(path, options), softline$b, "}"])); + } else { + const members = node.members.length > 0 ? [hardline$i, printArrayItems$1(path, options, "members", print), node.hasUnknownMembers || shouldPrintComma$2(options) ? "," : ""] : []; + parts.push(group$f(["{", indent$b([...members, ...(node.hasUnknownMembers ? [hardline$i, "..."] : [])]), printDanglingComments$3(path, options, + /* sameIndent */ + true), hardline$i, "}"])); + } + + return parts; + } + + case "EnumBooleanMember": + case "EnumNumberMember": + case "EnumStringMember": + return [print("id"), " = ", typeof node.init === "object" ? print("init") : String(node.init)]; + + case "EnumDefaultedMember": + return print("id"); + + case "FunctionTypeParam": + { + const name = node.name ? print("name") : path.getParentNode().this === node ? "this" : ""; + return [name, printOptionalToken$2(path), name ? ": " : "", print("typeAnnotation")]; + } + + case "InterfaceDeclaration": + case "InterfaceTypeAnnotation": + return printInterface$1(path, options, print); + + case "ClassImplements": + case "InterfaceExtends": + return [print("id"), print("typeParameters")]; + + case "NullableTypeAnnotation": + return ["?", print("typeAnnotation")]; + + case "Variance": + { + const { + kind + } = node; + assert__default['default'].ok(kind === "plus" || kind === "minus"); + return kind === "plus" ? "+" : "-"; + } + + case "ObjectTypeCallProperty": + if (node.static) { + parts.push("static "); + } + + parts.push(print("value")); + return parts; + + case "ObjectTypeIndexer": + { + return [node.variance ? print("variance") : "", "[", print("id"), node.id ? ": " : "", print("key"), "]: ", print("value")]; + } + + case "ObjectTypeProperty": + { + let modifier = ""; + + if (node.proto) { + modifier = "proto "; + } else if (node.static) { + modifier = "static "; + } + + return [modifier, isGetterOrSetter(node) ? node.kind + " " : "", node.variance ? print("variance") : "", printPropertyKey$1(path, options, print), printOptionalToken$2(path), isFunctionNotation(node) ? "" : ": ", print("value")]; + } + + case "ObjectTypeAnnotation": + return printObject$2(path, options, print); + + case "ObjectTypeInternalSlot": + return [node.static ? "static " : "", "[[", print("id"), "]]", printOptionalToken$2(path), node.method ? "" : ": ", print("value")]; + // Same as `RestElement` + + case "ObjectTypeSpreadProperty": + return printRestSpread$1(path, options, print); + + case "QualifiedTypeIdentifier": + return [print("qualification"), ".", print("id")]; + + case "StringLiteralTypeAnnotation": + return printString$2(rawText$1(node), options); + + case "NumberLiteralTypeAnnotation": + assert__default['default'].strictEqual(typeof node.value, "number"); + // fall through + + case "BigIntLiteralTypeAnnotation": + if (node.extra) { + return printNumber$2(node.extra.raw); + } + + return printNumber$2(node.raw); + + case "TypeCastExpression": + { + return ["(", print("expression"), printTypeAnnotation$1(path, options, print), ")"]; + } + + case "TypeParameterDeclaration": + case "TypeParameterInstantiation": + { + const printed = printTypeParameters$1(path, options, print, "params"); + + if (options.parser === "flow") { + const start = locStart$h(node); + const end = locEnd$g(node); + const commentStartIndex = options.originalText.lastIndexOf("/*", start); + const commentEndIndex = options.originalText.indexOf("*/", end); + + if (commentStartIndex !== -1 && commentEndIndex !== -1) { + const comment = options.originalText.slice(commentStartIndex + 2, commentEndIndex).trim(); + + if (comment.startsWith("::") && !comment.includes("/*") && !comment.includes("*/")) { + return ["/*:: ", printed, " */"]; + } + } + } + + return printed; + } + + case "InferredPredicate": + return "%checks"; + // Unhandled types below. If encountered, nodes of these types should + // be either left alone or desugared into AST types that are fully + // supported by the pretty-printer. + + case "DeclaredPredicate": + return ["%checks(", print("value"), ")"]; + + case "AnyTypeAnnotation": + return "any"; + + case "BooleanTypeAnnotation": + return "boolean"; + + case "BigIntTypeAnnotation": + return "bigint"; + + case "NullLiteralTypeAnnotation": + return "null"; + + case "NumberTypeAnnotation": + return "number"; + + case "SymbolTypeAnnotation": + return "symbol"; + + case "StringTypeAnnotation": + return "string"; + + case "VoidTypeAnnotation": + return "void"; + + case "ThisTypeAnnotation": + return "this"; + // These types are unprintable because they serve as abstract + // supertypes for other (printable) types. + + case "Node": + case "Printable": + case "SourceLocation": + case "Position": + case "Statement": + case "Function": + case "Pattern": + case "Expression": + case "Declaration": + case "Specifier": + case "NamedSpecifier": + case "Comment": + case "MemberTypeAnnotation": // Flow + + case "Type": + /* istanbul ignore next */ + throw new Error("unprintable type: " + JSON.stringify(node.type)); + } +} + +function printFlowDeclaration(path, printed) { + const parentExportDecl = getParentExportDeclaration(path); + + if (parentExportDecl) { + assert__default['default'].strictEqual(parentExportDecl.type, "DeclareExportDeclaration"); + return printed; + } // If the parent node has type DeclareExportDeclaration, then it + // will be responsible for printing the "declare" token. Otherwise + // it needs to be printed with this non-exported declaration node. + + + return ["declare ", printed]; +} + +var flow = { + printFlow: printFlow$1 +}; + +const { + hasNewlineInRange: hasNewlineInRange$1 +} = util$5; +const { + isJsxNode: isJsxNode$1, + isBlockComment: isBlockComment$2, + getComments, + isCallExpression: isCallExpression$2, + isMemberExpression: isMemberExpression$2 +} = utils$5; +const { + locStart: locStart$g, + locEnd: locEnd$f +} = loc$6; +const { + builders: { + line: line$c, + softline: softline$a, + group: group$e, + indent: indent$a, + align: align$2, + ifBreak: ifBreak$9, + dedent: dedent$3, + breakParent: breakParent$4 + } +} = doc; +/** + * @typedef {import("../../document").Doc} Doc + * @typedef {import("../../common/ast-path")} AstPath + * + * @typedef {any} Options - Prettier options (TBD ...) + */ +// If we have nested conditional expressions, we want to print them in JSX mode +// if there's at least one JSXElement somewhere in the tree. +// +// A conditional expression chain like this should be printed in normal mode, +// because there aren't JSXElements anywhere in it: +// +// isA ? "A" : isB ? "B" : isC ? "C" : "Unknown"; +// +// But a conditional expression chain like this should be printed in JSX mode, +// because there is a JSXElement in the last ConditionalExpression: +// +// isA ? "A" : isB ? "B" : isC ? "C" : Unknown; +// +// This type of ConditionalExpression chain is structured like this in the AST: +// +// ConditionalExpression { +// test: ..., +// consequent: ..., +// alternate: ConditionalExpression { +// test: ..., +// consequent: ..., +// alternate: ConditionalExpression { +// test: ..., +// consequent: ..., +// alternate: ..., +// } +// } +// } + +function conditionalExpressionChainContainsJsx(node) { + // Given this code: + // + // // Using a ConditionalExpression as the consequent is uncommon, but should + // // be handled. + // A ? B : C ? D : E ? F ? G : H : I + // + // which has this AST: + // + // ConditionalExpression { + // test: Identifier(A), + // consequent: Identifier(B), + // alternate: ConditionalExpression { + // test: Identifier(C), + // consequent: Identifier(D), + // alternate: ConditionalExpression { + // test: Identifier(E), + // consequent: ConditionalExpression { + // test: Identifier(F), + // consequent: Identifier(G), + // alternate: Identifier(H), + // }, + // alternate: Identifier(I), + // } + // } + // } + // + // We don't care about whether each node was the test, consequent, or alternate + // We are only checking if there's any JSXElements inside. + const conditionalExpressions = [node]; + + for (let index = 0; index < conditionalExpressions.length; index++) { + const conditionalExpression = conditionalExpressions[index]; + + for (const property of ["test", "consequent", "alternate"]) { + const node = conditionalExpression[property]; + + if (isJsxNode$1(node)) { + return true; + } + + if (node.type === "ConditionalExpression") { + conditionalExpressions.push(node); + } + } + } + + return false; +} + +function printTernaryTest(path, options, print) { + const node = path.getValue(); + const isConditionalExpression = node.type === "ConditionalExpression"; + const alternateNodePropertyName = isConditionalExpression ? "alternate" : "falseType"; + const parent = path.getParentNode(); + const printed = isConditionalExpression ? print("test") : [print("checkType"), " ", "extends", " ", print("extendsType")]; + /** + * a + * ? b + * : multiline + * test + * node + * ^^ align(2) + * ? d + * : e + */ + + if (parent.type === node.type && parent[alternateNodePropertyName] === node) { + return align$2(2, printed); + } + + return printed; +} + +const ancestorNameMap = new Map([["AssignmentExpression", "right"], ["VariableDeclarator", "init"], ["ReturnStatement", "argument"], ["ThrowStatement", "argument"], ["UnaryExpression", "argument"], ["YieldExpression", "argument"]]); + +function shouldExtraIndentForConditionalExpression(path) { + const node = path.getValue(); + + if (node.type !== "ConditionalExpression") { + return false; + } + + let parent; + let child = node; + + for (let ancestorCount = 0; !parent; ancestorCount++) { + const node = path.getParentNode(ancestorCount); + + if (isCallExpression$2(node) && node.callee === child || isMemberExpression$2(node) && node.object === child || node.type === "TSNonNullExpression" && node.expression === child) { + child = node; + continue; + } // Reached chain root + + + if (node.type === "NewExpression" && node.callee === child || node.type === "TSAsExpression" && node.expression === child) { + parent = path.getParentNode(ancestorCount + 1); + child = node; + } else { + parent = node; + } + } // Do not add indent to direct `ConditionalExpression` + + + if (child === node) { + return false; + } + + return parent[ancestorNameMap.get(parent.type)] === child; +} +/** + * The following is the shared logic for + * ternary operators, namely ConditionalExpression + * and TSConditionalType + * @param {AstPath} path - The path to the ConditionalExpression/TSConditionalType node. + * @param {Options} options - Prettier options + * @param {Function} print - Print function to call recursively + * @returns {Doc} + */ + + +function printTernary$2(path, options, print) { + const node = path.getValue(); + const isConditionalExpression = node.type === "ConditionalExpression"; + const consequentNodePropertyName = isConditionalExpression ? "consequent" : "trueType"; + const alternateNodePropertyName = isConditionalExpression ? "alternate" : "falseType"; + const testNodePropertyNames = isConditionalExpression ? ["test"] : ["checkType", "extendsType"]; + const consequentNode = node[consequentNodePropertyName]; + const alternateNode = node[alternateNodePropertyName]; + const parts = []; // We print a ConditionalExpression in either "JSX mode" or "normal mode". + // See tests/jsx/conditional-expression.js for more info. + + let jsxMode = false; + const parent = path.getParentNode(); + const isParentTest = parent.type === node.type && testNodePropertyNames.some(prop => parent[prop] === node); + let forceNoIndent = parent.type === node.type && !isParentTest; // Find the outermost non-ConditionalExpression parent, and the outermost + // ConditionalExpression parent. We'll use these to determine if we should + // print in JSX mode. + + let currentParent; + let previousParent; + let i = 0; + + do { + previousParent = currentParent || node; + currentParent = path.getParentNode(i); + i++; + } while (currentParent && currentParent.type === node.type && testNodePropertyNames.every(prop => currentParent[prop] !== previousParent)); + + const firstNonConditionalParent = currentParent || parent; + const lastConditionalParent = previousParent; + + if (isConditionalExpression && (isJsxNode$1(node[testNodePropertyNames[0]]) || isJsxNode$1(consequentNode) || isJsxNode$1(alternateNode) || conditionalExpressionChainContainsJsx(lastConditionalParent))) { + jsxMode = true; + forceNoIndent = true; // Even though they don't need parens, we wrap (almost) everything in + // parens when using ?: within JSX, because the parens are analogous to + // curly braces in an if statement. + + const wrap = doc => [ifBreak$9("("), indent$a([softline$a, doc]), softline$a, ifBreak$9(")")]; // The only things we don't wrap are: + // * Nested conditional expressions in alternates + // * null + // * undefined + + + const isNil = node => node.type === "NullLiteral" || node.type === "Literal" && node.value === null || node.type === "Identifier" && node.name === "undefined"; + + parts.push(" ? ", isNil(consequentNode) ? print(consequentNodePropertyName) : wrap(print(consequentNodePropertyName)), " : ", alternateNode.type === node.type || isNil(alternateNode) ? print(alternateNodePropertyName) : wrap(print(alternateNodePropertyName))); + } else { + // normal mode + const part = [line$c, "? ", consequentNode.type === node.type ? ifBreak$9("", "(") : "", align$2(2, print(consequentNodePropertyName)), consequentNode.type === node.type ? ifBreak$9("", ")") : "", line$c, ": ", alternateNode.type === node.type ? print(alternateNodePropertyName) : align$2(2, print(alternateNodePropertyName))]; + parts.push(parent.type !== node.type || parent[alternateNodePropertyName] === node || isParentTest ? part : options.useTabs ? dedent$3(indent$a(part)) : align$2(Math.max(0, options.tabWidth - 2), part)); + } // We want a whole chain of ConditionalExpressions to all + // break if any of them break. That means we should only group around the + // outer-most ConditionalExpression. + + + const comments = [...testNodePropertyNames.map(propertyName => getComments(node[propertyName])), getComments(consequentNode), getComments(alternateNode)].flat(); + const shouldBreak = comments.some(comment => isBlockComment$2(comment) && hasNewlineInRange$1(options.originalText, locStart$g(comment), locEnd$f(comment))); + + const maybeGroup = doc => parent === firstNonConditionalParent ? group$e(doc, { + shouldBreak + }) : shouldBreak ? [doc, breakParent$4] : doc; // Break the closing paren to keep the chain right after it: + // (a + // ? b + // : c + // ).call() + + + const breakClosingParen = !jsxMode && (isMemberExpression$2(parent) || parent.type === "NGPipeExpression" && parent.left === node) && !parent.computed; + const shouldExtraIndent = shouldExtraIndentForConditionalExpression(path); + const result = maybeGroup([printTernaryTest(path, options, print), forceNoIndent ? parts : indent$a(parts), isConditionalExpression && breakClosingParen && !shouldExtraIndent ? softline$a : ""]); + return isParentTest || shouldExtraIndent ? group$e([indent$a([softline$a, result]), softline$a]) : result; +} + +var ternary = { + printTernary: printTernary$2 +}; + +const { + builders: { + hardline: hardline$h + } +} = doc; +const { + getLeftSidePathName, + hasNakedLeftSide, + isJsxNode, + isTheOnlyJsxElementInMarkdown: isTheOnlyJsxElementInMarkdown$1, + hasComment: hasComment$2, + CommentCheckFlags: CommentCheckFlags$2, + isNextLineEmpty: isNextLineEmpty$6 +} = utils$5; +const { + shouldPrintParamsWithoutParens +} = _function; +/** + * @typedef {import("../../document").Doc} Doc + * @typedef {import("../../common/ast-path")} AstPath + */ + +function printStatementSequence(path, options, print, property) { + const node = path.getValue(); + const parts = []; + const isClassBody = node.type === "ClassBody"; + const lastStatement = getLastStatement(node[property]); + path.each((path, index, statements) => { + const node = path.getValue(); // Skip printing EmptyStatement nodes to avoid leaving stray + // semicolons lying around. + + if (node.type === "EmptyStatement") { + return; + } + + const printed = print(); // in no-semi mode, prepend statement with semicolon if it might break ASI + // don't prepend the only JSX element in a program with semicolon + + if (!options.semi && !isClassBody && !isTheOnlyJsxElementInMarkdown$1(options, path) && statementNeedsASIProtection(path, options)) { + if (hasComment$2(node, CommentCheckFlags$2.Leading)) { + parts.push(print([], { + needsSemi: true + })); + } else { + parts.push(";", printed); + } + } else { + parts.push(printed); + } + + if (!options.semi && isClassBody && isClassProperty(node) && // `ClassBody` don't allow `EmptyStatement`, + // so we can use `statements` to get next node + shouldPrintSemicolonAfterClassProperty(node, statements[index + 1])) { + parts.push(";"); + } + + if (node !== lastStatement) { + parts.push(hardline$h); + + if (isNextLineEmpty$6(node, options)) { + parts.push(hardline$h); + } + } + }, property); + return parts; +} + +function getLastStatement(statements) { + for (let i = statements.length - 1; i >= 0; i--) { + const statement = statements[i]; + + if (statement.type !== "EmptyStatement") { + return statement; + } + } +} + +function statementNeedsASIProtection(path, options) { + const node = path.getNode(); + + if (node.type !== "ExpressionStatement") { + return false; + } + + return path.call(childPath => expressionNeedsASIProtection(childPath, options), "expression"); +} + +function expressionNeedsASIProtection(path, options) { + const node = path.getValue(); + + switch (node.type) { + case "ParenthesizedExpression": + case "TypeCastExpression": + case "ArrayExpression": + case "ArrayPattern": + case "TemplateLiteral": + case "TemplateElement": + case "RegExpLiteral": + return true; + + case "ArrowFunctionExpression": + { + if (!shouldPrintParamsWithoutParens(path, options)) { + return true; + } + + break; + } + + case "UnaryExpression": + { + const { + prefix, + operator + } = node; + + if (prefix && (operator === "+" || operator === "-")) { + return true; + } + + break; + } + + case "BindExpression": + { + if (!node.object) { + return true; + } + + break; + } + + case "Literal": + { + if (node.regex) { + return true; + } + + break; + } + + default: + { + if (isJsxNode(node)) { + return true; + } + } + } + + if (needsParens_1(path, options)) { + return true; + } + + if (!hasNakedLeftSide(node)) { + return false; + } + + return path.call(childPath => expressionNeedsASIProtection(childPath, options), ...getLeftSidePathName(path, node)); +} + +function printBody$1(path, options, print) { + return printStatementSequence(path, options, print, "body"); +} + +function printSwitchCaseConsequent$1(path, options, print) { + return printStatementSequence(path, options, print, "consequent"); +} + +const isClassProperty = ({ + type +}) => type === "ClassProperty" || type === "PropertyDefinition" || type === "ClassPrivateProperty"; +/** + * @returns {boolean} + */ + + +function shouldPrintSemicolonAfterClassProperty(node, nextNode) { + const name = node.key && node.key.name; // this isn't actually possible yet with most parsers available today + // so isn't properly tested yet. + + if ((name === "static" || name === "get" || name === "set") && !node.value && !node.typeAnnotation) { + return true; + } + + if (!nextNode) { + return false; + } + + if (nextNode.static || nextNode.accessibility // TypeScript + ) { + return false; + } + + if (!nextNode.computed) { + const name = nextNode.key && nextNode.key.name; + + if (name === "in" || name === "instanceof") { + return true; + } + } + + switch (nextNode.type) { + case "ClassProperty": + case "PropertyDefinition": + case "TSAbstractClassProperty": + return nextNode.computed; + + case "MethodDefinition": // Flow + + case "TSAbstractMethodDefinition": // TypeScript + + case "ClassMethod": + case "ClassPrivateMethod": + { + // Babel + const isAsync = nextNode.value ? nextNode.value.async : nextNode.async; + + if (isAsync || nextNode.kind === "get" || nextNode.kind === "set") { + return false; + } + + const isGenerator = nextNode.value ? nextNode.value.generator : nextNode.generator; + + if (nextNode.computed || isGenerator) { + return true; + } + + return false; + } + + case "TSIndexSignature": + return true; + } + /* istanbul ignore next */ + + + return false; +} + +var statement = { + printBody: printBody$1, + printSwitchCaseConsequent: printSwitchCaseConsequent$1 +}; + +const { + printDanglingComments: printDanglingComments$2 +} = comments$1; +const { + isNonEmptyArray: isNonEmptyArray$7 +} = util$5; +const { + builders: { + hardline: hardline$g, + indent: indent$9 + } +} = doc; +const { + hasComment: hasComment$1, + CommentCheckFlags: CommentCheckFlags$1, + isNextLineEmpty: isNextLineEmpty$5 +} = utils$5; +const { + printHardlineAfterHeritage +} = _class; +const { + printBody +} = statement; +/** @typedef {import("../../document").Doc} Doc */ + +function printBlock$3(path, options, print) { + const node = path.getValue(); + const parts = []; + + if (node.type === "StaticBlock") { + parts.push("static "); + } + + if (node.type === "ClassBody" && isNonEmptyArray$7(node.body)) { + const parent = path.getParentNode(); + parts.push(printHardlineAfterHeritage(parent)); + } + + parts.push("{"); + const printed = printBlockBody$1(path, options, print); + + if (printed) { + parts.push(indent$9([hardline$g, printed]), hardline$g); + } else { + const parent = path.getParentNode(); + const parentParent = path.getParentNode(1); + + if (!(parent.type === "ArrowFunctionExpression" || parent.type === "FunctionExpression" || parent.type === "FunctionDeclaration" || parent.type === "ObjectMethod" || parent.type === "ClassMethod" || parent.type === "ClassPrivateMethod" || parent.type === "ForStatement" || parent.type === "WhileStatement" || parent.type === "DoWhileStatement" || parent.type === "DoExpression" || parent.type === "CatchClause" && !parentParent.finalizer || parent.type === "TSModuleDeclaration" || parent.type === "TSDeclareFunction" || node.type === "StaticBlock" || node.type === "ClassBody")) { + parts.push(hardline$g); + } + } + + parts.push("}"); + return parts; +} + +function printBlockBody$1(path, options, print) { + const node = path.getValue(); + const nodeHasDirectives = isNonEmptyArray$7(node.directives); + const nodeHasBody = node.body.some(node => node.type !== "EmptyStatement"); + const nodeHasComment = hasComment$1(node, CommentCheckFlags$1.Dangling); + + if (!nodeHasDirectives && !nodeHasBody && !nodeHasComment) { + return ""; + } + + const parts = []; // Babel 6 + + if (nodeHasDirectives) { + path.each((childPath, index, directives) => { + parts.push(print()); + + if (index < directives.length - 1 || nodeHasBody || nodeHasComment) { + parts.push(hardline$g); + + if (isNextLineEmpty$5(childPath.getValue(), options)) { + parts.push(hardline$g); + } + } + }, "directives"); + } + + if (nodeHasBody) { + parts.push(printBody(path, options, print)); + } + + if (nodeHasComment) { + parts.push(printDanglingComments$2(path, options, + /* sameIndent */ + true)); + } + + if (node.type === "Program") { + const parent = path.getParentNode(); + + if (!parent || parent.type !== "ModuleExpression") { + parts.push(hardline$g); + } + } + + return parts; +} + +var block$1 = { + printBlock: printBlock$3, + printBlockBody: printBlockBody$1 +}; + +const { + printDanglingComments: printDanglingComments$1 +} = comments$1; +const { + hasNewlineInRange +} = util$5; +const { + builders: { + join: join$d, + line: line$b, + hardline: hardline$f, + softline: softline$9, + group: group$d, + indent: indent$8, + conditionalGroup: conditionalGroup$1, + ifBreak: ifBreak$8 + } +} = doc; +const { + isLiteral, + getTypeScriptMappedTypeModifier, + shouldPrintComma: shouldPrintComma$1, + isCallExpression: isCallExpression$1, + isMemberExpression: isMemberExpression$1 +} = utils$5; +const { + locStart: locStart$f, + locEnd: locEnd$e +} = loc$6; +const { + printOptionalToken: printOptionalToken$1, + printTypeScriptModifiers +} = misc$1; +const { + printTernary: printTernary$1 +} = ternary; +const { + printFunctionParameters, + shouldGroupFunctionParameters +} = functionParameters; +const { + printTemplateLiteral: printTemplateLiteral$1 +} = templateLiteral; +const { + printArrayItems +} = array; +const { + printObject: printObject$1 +} = object$1; +const { + printClassProperty: printClassProperty$1, + printClassMethod: printClassMethod$1 +} = _class; +const { + printTypeParameter, + printTypeParameters +} = typeParameters; +const { + printPropertyKey +} = property; +const { + printFunction: printFunction$1, + printMethodInternal +} = _function; +const { + printInterface +} = _interface; +const { + printBlock: printBlock$2 +} = block$1; +const { + printTypeAlias, + printIntersectionType, + printUnionType, + printFunctionType, + printTupleType, + printIndexedAccessType +} = typeAnnotation; + +function printTypescript$1(path, options, print) { + const node = path.getValue(); // TypeScript nodes always starts with `TS` + + if (!node.type.startsWith("TS")) { + return; + } + + if (node.type.endsWith("Keyword")) { + return node.type.slice(2, -7).toLowerCase(); + } + + const semi = options.semi ? ";" : ""; + const parts = []; + + switch (node.type) { + case "TSThisType": + return "this"; + + case "TSTypeAssertion": + { + const shouldBreakAfterCast = !(node.expression.type === "ArrayExpression" || node.expression.type === "ObjectExpression"); + const castGroup = group$d(["<", indent$8([softline$9, print("typeAnnotation")]), softline$9, ">"]); + const exprContents = [ifBreak$8("("), indent$8([softline$9, print("expression")]), softline$9, ifBreak$8(")")]; + + if (shouldBreakAfterCast) { + return conditionalGroup$1([[castGroup, print("expression")], [castGroup, group$d(exprContents, { + shouldBreak: true + })], [castGroup, print("expression")]]); + } + + return group$d([castGroup, print("expression")]); + } + + case "TSDeclareFunction": + return printFunction$1(path, print, options); + + case "TSExportAssignment": + return ["export = ", print("expression"), semi]; + + case "TSModuleBlock": + return printBlock$2(path, options, print); + + case "TSInterfaceBody": + case "TSTypeLiteral": + return printObject$1(path, options, print); + + case "TSTypeAliasDeclaration": + return printTypeAlias(path, options, print); + + case "TSQualifiedName": + return join$d(".", [print("left"), print("right")]); + + case "TSAbstractMethodDefinition": + case "TSDeclareMethod": + return printClassMethod$1(path, options, print); + + case "TSAbstractClassProperty": + return printClassProperty$1(path, options, print); + + case "TSInterfaceHeritage": + case "TSExpressionWithTypeArguments": + // Babel AST + parts.push(print("expression")); + + if (node.typeParameters) { + parts.push(print("typeParameters")); + } + + return parts; + + case "TSTemplateLiteralType": + return printTemplateLiteral$1(path, print, options); + + case "TSNamedTupleMember": + return [print("label"), node.optional ? "?" : "", ": ", print("elementType")]; + + case "TSRestType": + return ["...", print("typeAnnotation")]; + + case "TSOptionalType": + return [print("typeAnnotation"), "?"]; + + case "TSInterfaceDeclaration": + return printInterface(path, options, print); + + case "TSClassImplements": + return [print("expression"), print("typeParameters")]; + + case "TSTypeParameterDeclaration": + case "TSTypeParameterInstantiation": + return printTypeParameters(path, options, print, "params"); + + case "TSTypeParameter": + return printTypeParameter(path, options, print); + + case "TSAsExpression": + { + parts.push(print("expression"), " as ", print("typeAnnotation")); + const parent = path.getParentNode(); + + if (isCallExpression$1(parent) && parent.callee === node || isMemberExpression$1(parent) && parent.object === node) { + return group$d([indent$8([softline$9, ...parts]), softline$9]); + } + + return parts; + } + + case "TSArrayType": + return [print("elementType"), "[]"]; + + case "TSPropertySignature": + { + if (node.readonly) { + parts.push("readonly "); + } + + parts.push(printPropertyKey(path, options, print), printOptionalToken$1(path)); + + if (node.typeAnnotation) { + parts.push(": ", print("typeAnnotation")); + } // This isn't valid semantically, but it's in the AST so we can print it. + + + if (node.initializer) { + parts.push(" = ", print("initializer")); + } + + return parts; + } + + case "TSParameterProperty": + if (node.accessibility) { + parts.push(node.accessibility + " "); + } + + if (node.export) { + parts.push("export "); + } + + if (node.static) { + parts.push("static "); + } + + if (node.readonly) { + parts.push("readonly "); + } + + parts.push(print("parameter")); + return parts; + + case "TSTypeQuery": + return ["typeof ", print("exprName")]; + + case "TSIndexSignature": + { + const parent = path.getParentNode(); // The typescript parser accepts multiple parameters here. If you're + // using them, it makes sense to have a trailing comma. But if you + // aren't, this is more like a computed property name than an array. + // So we leave off the trailing comma when there's just one parameter. + + const trailingComma = node.parameters.length > 1 ? ifBreak$8(shouldPrintComma$1(options) ? "," : "") : ""; + const parametersGroup = group$d([indent$8([softline$9, join$d([", ", softline$9], path.map(print, "parameters"))]), trailingComma, softline$9]); + return [node.export ? "export " : "", node.accessibility ? [node.accessibility, " "] : "", node.static ? "static " : "", node.readonly ? "readonly " : "", node.declare ? "declare " : "", "[", node.parameters ? parametersGroup : "", node.typeAnnotation ? "]: " : "]", node.typeAnnotation ? print("typeAnnotation") : "", parent.type === "ClassBody" ? semi : ""]; + } + + case "TSTypePredicate": + return [node.asserts ? "asserts " : "", print("parameterName"), node.typeAnnotation ? [" is ", print("typeAnnotation")] : ""]; + + case "TSNonNullExpression": + return [print("expression"), "!"]; + + case "TSImportType": + return [!node.isTypeOf ? "" : "typeof ", "import(", print(node.parameter ? "parameter" : "argument"), ")", !node.qualifier ? "" : [".", print("qualifier")], printTypeParameters(path, options, print, "typeParameters")]; + + case "TSLiteralType": + return print("literal"); + + case "TSIndexedAccessType": + return printIndexedAccessType(path, options, print); + + case "TSConstructSignatureDeclaration": + case "TSCallSignatureDeclaration": + case "TSConstructorType": + { + if (node.type === "TSConstructorType" && node.abstract) { + parts.push("abstract "); + } + + if (node.type !== "TSCallSignatureDeclaration") { + parts.push("new "); + } + + parts.push(group$d(printFunctionParameters(path, print, options, + /* expandArg */ + false, + /* printTypeParams */ + true))); + + if (node.returnType || node.typeAnnotation) { + const isType = node.type === "TSConstructorType"; + parts.push(isType ? " => " : ": ", print("returnType"), print("typeAnnotation")); + } + + return parts; + } + + case "TSTypeOperator": + return [node.operator, " ", print("typeAnnotation")]; + + case "TSMappedType": + { + const shouldBreak = hasNewlineInRange(options.originalText, locStart$f(node), locEnd$e(node)); + return group$d(["{", indent$8([options.bracketSpacing ? line$b : softline$9, node.readonly ? [getTypeScriptMappedTypeModifier(node.readonly, "readonly"), " "] : "", printTypeScriptModifiers(path, options, print), print("typeParameter"), node.optional ? getTypeScriptMappedTypeModifier(node.optional, "?") : "", node.typeAnnotation ? ": " : "", print("typeAnnotation"), ifBreak$8(semi)]), printDanglingComments$1(path, options, + /* sameIndent */ + true), options.bracketSpacing ? line$b : softline$9, "}"], { + shouldBreak + }); + } + + case "TSMethodSignature": + { + const kind = node.kind && node.kind !== "method" ? `${node.kind} ` : ""; + parts.push(node.accessibility ? [node.accessibility, " "] : "", kind, node.export ? "export " : "", node.static ? "static " : "", node.readonly ? "readonly " : "", // "abstract" and "declare" are supported by only "babel-ts" + // https://github.com/prettier/prettier/issues/9760 + node.abstract ? "abstract " : "", node.declare ? "declare " : "", node.computed ? "[" : "", print("key"), node.computed ? "]" : "", printOptionalToken$1(path)); + const parametersDoc = printFunctionParameters(path, print, options, + /* expandArg */ + false, + /* printTypeParams */ + true); + const returnTypePropertyName = node.returnType ? "returnType" : "typeAnnotation"; + const returnTypeNode = node[returnTypePropertyName]; + const returnTypeDoc = returnTypeNode ? print(returnTypePropertyName) : ""; + const shouldGroupParameters = shouldGroupFunctionParameters(node, returnTypeDoc); + parts.push(shouldGroupParameters ? group$d(parametersDoc) : parametersDoc); + + if (returnTypeNode) { + parts.push(": ", group$d(returnTypeDoc)); + } + + return group$d(parts); + } + + case "TSNamespaceExportDeclaration": + parts.push("export as namespace ", print("id")); + + if (options.semi) { + parts.push(";"); + } + + return group$d(parts); + + case "TSEnumDeclaration": + if (node.declare) { + parts.push("declare "); + } + + if (node.modifiers) { + parts.push(printTypeScriptModifiers(path, options, print)); + } + + if (node.const) { + parts.push("const "); + } + + parts.push("enum ", print("id"), " "); + + if (node.members.length === 0) { + parts.push(group$d(["{", printDanglingComments$1(path, options), softline$9, "}"])); + } else { + parts.push(group$d(["{", indent$8([hardline$f, printArrayItems(path, options, "members", print), shouldPrintComma$1(options, "es5") ? "," : ""]), printDanglingComments$1(path, options, + /* sameIndent */ + true), hardline$f, "}"])); + } + + return parts; + + case "TSEnumMember": + parts.push(print("id")); + + if (node.initializer) { + parts.push(" = ", print("initializer")); + } + + return parts; + + case "TSImportEqualsDeclaration": + if (node.isExport) { + parts.push("export "); + } + + parts.push("import "); + + if (node.importKind && node.importKind !== "value") { + parts.push(node.importKind, " "); + } + + parts.push(print("id"), " = ", print("moduleReference")); + + if (options.semi) { + parts.push(";"); + } + + return group$d(parts); + + case "TSExternalModuleReference": + return ["require(", print("expression"), ")"]; + + case "TSModuleDeclaration": + { + const parent = path.getParentNode(); + const isExternalModule = isLiteral(node.id); + const parentIsDeclaration = parent.type === "TSModuleDeclaration"; + const bodyIsDeclaration = node.body && node.body.type === "TSModuleDeclaration"; + + if (parentIsDeclaration) { + parts.push("."); + } else { + if (node.declare) { + parts.push("declare "); + } + + parts.push(printTypeScriptModifiers(path, options, print)); + const textBetweenNodeAndItsId = options.originalText.slice(locStart$f(node), locStart$f(node.id)); // Global declaration looks like this: + // (declare)? global { ... } + + const isGlobalDeclaration = node.id.type === "Identifier" && node.id.name === "global" && !/namespace|module/.test(textBetweenNodeAndItsId); + + if (!isGlobalDeclaration) { + parts.push(isExternalModule || /(^|\s)module(\s|$)/.test(textBetweenNodeAndItsId) ? "module " : "namespace "); + } + } + + parts.push(print("id")); + + if (bodyIsDeclaration) { + parts.push(print("body")); + } else if (node.body) { + parts.push(" ", group$d(print("body"))); + } else { + parts.push(semi); + } + + return parts; + } + // TODO: Temporary auto-generated node type. To remove when typescript-estree has proper support for private fields. + + case "TSPrivateIdentifier": + return node.escapedText; + + case "TSConditionalType": + return printTernary$1(path, options, print); + + case "TSInferType": + return ["infer", " ", print("typeParameter")]; + + case "TSIntersectionType": + return printIntersectionType(path, options, print); + + case "TSUnionType": + return printUnionType(path, options, print); + + case "TSFunctionType": + return printFunctionType(path, options, print); + + case "TSTupleType": + return printTupleType(path, options, print); + + case "TSTypeReference": + return [print("typeName"), printTypeParameters(path, options, print, "typeParameters")]; + + case "TSTypeAnnotation": + return print("typeAnnotation"); + + case "TSEmptyBodyFunctionExpression": + return printMethodInternal(path, options, print); + // These are not valid TypeScript. Printing them just for the sake of error recovery. + + case "TSJSDocAllType": + return "*"; + + case "TSJSDocUnknownType": + return "?"; + + case "TSJSDocNullableType": + return ["?", print("typeAnnotation")]; + + case "TSJSDocNonNullableType": + return ["!", print("typeAnnotation")]; + + default: + /* istanbul ignore next */ + throw new Error(`Unknown TypeScript node type: ${JSON.stringify(node.type)}.`); + } +} + +var typescript = { + printTypescript: printTypescript$1 +}; + +const { + hasNewline: hasNewline$2 +} = util$5; +const { + builders: { + join: join$c, + hardline: hardline$e + }, + utils: { + replaceNewlinesWithLiterallines: replaceNewlinesWithLiterallines$2 + } +} = doc; +const { + isLineComment: isLineComment$1, + isBlockComment: isBlockComment$1 +} = utils$5; +const { + locStart: locStart$e, + locEnd: locEnd$d +} = loc$6; + +function printComment$2(commentPath, options) { + const comment = commentPath.getValue(); + + if (isLineComment$1(comment)) { + // Supports `//`, `#!`, `` + return options.originalText.slice(locStart$e(comment), locEnd$d(comment)).trimEnd(); + } + + if (isBlockComment$1(comment)) { + if (isIndentableBlockComment(comment)) { + const printed = printIndentableBlockComment(comment); // We need to prevent an edge case of a previous trailing comment + // printed as a `lineSuffix` which causes the comments to be + // interleaved. See https://github.com/prettier/prettier/issues/4412 + + if (comment.trailing && !hasNewline$2(options.originalText, locStart$e(comment), { + backwards: true + })) { + return [hardline$e, printed]; + } + + return printed; + } + + const commentEnd = locEnd$d(comment); + const isInsideFlowComment = options.originalText.slice(commentEnd - 3, commentEnd) === "*-/"; + return ["/*", replaceNewlinesWithLiterallines$2(comment.value), isInsideFlowComment ? "*-/" : "*/"]; + } + /* istanbul ignore next */ + + + throw new Error("Not a comment: " + JSON.stringify(comment)); +} + +function isIndentableBlockComment(comment) { + // If the comment has multiple lines and every line starts with a star + // we can fix the indentation of each line. The stars in the `/*` and + // `*/` delimiters are not included in the comment value, so add them + // back first. + const lines = `*${comment.value}*`.split("\n"); + return lines.length > 1 && lines.every(line => line.trim()[0] === "*"); +} + +function printIndentableBlockComment(comment) { + const lines = comment.value.split("\n"); + return ["/*", join$c(hardline$e, lines.map((line, index) => index === 0 ? line.trimEnd() : " " + (index < lines.length - 1 ? line.trim() : line.trimStart()))), "*/"]; +} + +var comment = { + printComment: printComment$2 +}; + +const { + printString: printString$1, + printNumber: printNumber$1 +} = util$5; + +function printLiteral$1(path, options +/*, print*/ +) { + const node = path.getNode(); + + switch (node.type) { + case "RegExpLiteral": + // Babel 6 Literal split + return printRegex(node); + + case "BigIntLiteral": + // babel: node.extra.raw, flow: node.bigint + return printBigInt(node.bigint || node.extra.raw); + + case "NumericLiteral": + // Babel 6 Literal split + return printNumber$1(node.extra.raw); + + case "StringLiteral": + // Babel 6 Literal split + return printString$1(node.extra.raw, options); + + case "NullLiteral": + // Babel 6 Literal split + return "null"; + + case "BooleanLiteral": + // Babel 6 Literal split + return String(node.value); + + case "DecimalLiteral": + return printNumber$1(node.value) + "m"; + + case "Literal": + { + if (node.regex) { + return printRegex(node.regex); + } + + if (node.bigint) { + return printBigInt(node.raw); + } + + if (node.decimal) { + return printNumber$1(node.decimal) + "m"; + } + + const { + value + } = node; + + if (typeof value === "number") { + return printNumber$1(node.raw); + } + + if (typeof value === "string") { + return printString$1(node.raw, options); + } + + return String(value); + } + } +} + +function printBigInt(raw) { + return raw.toLowerCase(); +} + +function printRegex({ + pattern, + flags +}) { + flags = flags.split("").sort().join(""); + return `/${pattern}/${flags}`; +} + +var literal = { + printLiteral: printLiteral$1 +}; + +/** @typedef {import("../document").Doc} Doc */ +// TODO(azz): anything that imports from main shouldn't be in a `language-*` dir. + + +const { + printDanglingComments +} = comments$1; +const { + hasNewline: hasNewline$1 +} = util$5; +const { + builders: { + join: join$b, + line: line$a, + hardline: hardline$d, + softline: softline$8, + group: group$c, + indent: indent$7 + }, + utils: { + replaceNewlinesWithLiterallines: replaceNewlinesWithLiterallines$1 + } +} = doc; +const { + insertPragma: insertPragma$9 +} = pragma$5; +const { + hasFlowShorthandAnnotationComment, + hasComment, + CommentCheckFlags, + isTheOnlyJsxElementInMarkdown, + isBlockComment, + isLineComment, + isNextLineEmpty: isNextLineEmpty$4, + needsHardlineAfterDanglingComment, + rawText, + hasIgnoreComment, + isCallExpression, + isMemberExpression +} = utils$5; +const { + locStart: locStart$d, + locEnd: locEnd$c +} = loc$6; +const { + printHtmlBinding, + isVueEventBindingExpression: isVueEventBindingExpression$2 +} = htmlBinding; +const { + printAngular +} = angular; +const { + printJsx, + hasJsxIgnoreComment +} = jsx; +const { + printFlow +} = flow; +const { + printTypescript +} = typescript; +const { + printOptionalToken, + printBindExpressionCallee, + printTypeAnnotation, + adjustClause, + printRestSpread +} = misc$1; +const { + printImportDeclaration, + printExportDeclaration, + printExportAllDeclaration, + printModuleSpecifier +} = module$1; +const { + printTernary +} = ternary; +const { + printTemplateLiteral +} = templateLiteral; +const { + printArray +} = array; +const { + printObject +} = object$1; +const { + printClass, + printClassMethod, + printClassProperty +} = _class; +const { + printProperty +} = property; +const { + printFunction, + printArrowFunction, + printMethod, + printReturnStatement, + printThrowStatement +} = _function; +const { + printCallExpression +} = callExpression; +const { + printVariableDeclarator, + printAssignmentExpression +} = assignment; +const { + printBinaryishExpression +} = binaryish; +const { + printSwitchCaseConsequent +} = statement; +const { + printMemberExpression +} = member; +const { + printBlock: printBlock$1, + printBlockBody +} = block$1; +const { + printComment: printComment$1 +} = comment; +const { + printLiteral +} = literal; +const { + printDecorators +} = decorators; + +function genericPrint$6(path, options, print, args) { + const printed = printPathNoParens(path, options, print, args); + + if (!printed) { + return ""; + } + + const node = path.getValue(); + const { + type + } = node; // Their decorators are handled themselves, and they can't have parentheses + + if (type === "ClassMethod" || type === "ClassPrivateMethod" || type === "ClassProperty" || type === "PropertyDefinition" || type === "TSAbstractClassProperty" || type === "ClassPrivateProperty" || type === "MethodDefinition" || type === "TSAbstractMethodDefinition" || type === "TSDeclareMethod") { + return printed; + } + + const printedDecorators = printDecorators(path, options, print); // Nodes with decorators can't have parentheses and don't need leading semicolons + + if (printedDecorators) { + return group$c([...printedDecorators, printed]); + } + + const needsParens = needsParens_1(path, options); + + if (!needsParens) { + return args && args.needsSemi ? [";", printed] : printed; + } + + const parts = [args && args.needsSemi ? ";(" : "(", printed]; + + if (hasFlowShorthandAnnotationComment(node)) { + const [comment] = node.trailingComments; + parts.push(" /*", comment.value.trimStart(), "*/"); + comment.printed = true; + } + + parts.push(")"); + return parts; +} + +function printPathNoParens(path, options, print, args) { + const node = path.getValue(); + const semi = options.semi ? ";" : ""; + + if (!node) { + return ""; + } + + if (typeof node === "string") { + return node; + } + + for (const printer of [printLiteral, printHtmlBinding, printAngular, printJsx, printFlow, printTypescript]) { + const printed = printer(path, options, print); + + if (typeof printed !== "undefined") { + return printed; + } + } + /** @type{Doc[]} */ + + + let parts = []; + + switch (node.type) { + case "JsExpressionRoot": + return print("node"); + + case "JsonRoot": + return [print("node"), hardline$d]; + + case "File": + // Print @babel/parser's InterpreterDirective here so that + // leading comments on the `Program` node get printed after the hashbang. + if (node.program && node.program.interpreter) { + parts.push(print(["program", "interpreter"])); + } + + parts.push(print("program")); + return parts; + + case "Program": + return printBlockBody(path, options, print); + // Babel extension. + + case "EmptyStatement": + return ""; + + case "ExpressionStatement": + // Detect Flow and TypeScript directives + if (node.directive) { + return [printDirective(node.expression, options), semi]; + } + + if (options.parser === "__vue_event_binding") { + const parent = path.getParentNode(); + + if (parent.type === "Program" && parent.body.length === 1 && parent.body[0] === node) { + return [print("expression"), isVueEventBindingExpression$2(node.expression) ? ";" : ""]; + } + } // Do not append semicolon after the only JSX element in a program + + + return [print("expression"), isTheOnlyJsxElementInMarkdown(options, path) ? "" : semi]; + // Babel non-standard node. Used for Closure-style type casts. See postprocess.js. + + case "ParenthesizedExpression": + { + const shouldHug = !hasComment(node.expression) && (node.expression.type === "ObjectExpression" || node.expression.type === "ArrayExpression"); + + if (shouldHug) { + return ["(", print("expression"), ")"]; + } + + return group$c(["(", indent$7([softline$8, print("expression")]), softline$8, ")"]); + } + + case "AssignmentExpression": + return printAssignmentExpression(path, options, print); + + case "VariableDeclarator": + return printVariableDeclarator(path, options, print); + + case "BinaryExpression": + case "LogicalExpression": + return printBinaryishExpression(path, options, print); + + case "AssignmentPattern": + return [print("left"), " = ", print("right")]; + + case "OptionalMemberExpression": + case "MemberExpression": + { + return printMemberExpression(path, options, print); + } + + case "MetaProperty": + return [print("meta"), ".", print("property")]; + + case "BindExpression": + if (node.object) { + parts.push(print("object")); + } + + parts.push(group$c(indent$7([softline$8, printBindExpressionCallee(path, options, print)]))); + return parts; + + case "Identifier": + { + return [node.name, printOptionalToken(path), printTypeAnnotation(path, options, print)]; + } + + case "V8IntrinsicIdentifier": + return ["%", node.name]; + + case "SpreadElement": + case "SpreadElementPattern": + case "SpreadProperty": + case "SpreadPropertyPattern": + case "RestElement": + return printRestSpread(path, options, print); + + case "FunctionDeclaration": + case "FunctionExpression": + return printFunction(path, print, options, args); + + case "ArrowFunctionExpression": + return printArrowFunction(path, options, print, args); + + case "YieldExpression": + parts.push("yield"); + + if (node.delegate) { + parts.push("*"); + } + + if (node.argument) { + parts.push(" ", print("argument")); + } + + return parts; + + case "AwaitExpression": + { + parts.push("await"); + + if (node.argument) { + parts.push(" ", print("argument")); + const parent = path.getParentNode(); + + if (isCallExpression(parent) && parent.callee === node || isMemberExpression(parent) && parent.object === node) { + parts = [indent$7([softline$8, ...parts]), softline$8]; + const parentAwaitOrBlock = path.findAncestor(node => node.type === "AwaitExpression" || node.type === "BlockStatement"); + + if (!parentAwaitOrBlock || parentAwaitOrBlock.type !== "AwaitExpression") { + return group$c(parts); + } + } + } + + return parts; + } + + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + return printExportDeclaration(path, options, print); + + case "ExportAllDeclaration": + return printExportAllDeclaration(path, options, print); + + case "ImportDeclaration": + return printImportDeclaration(path, options, print); + + case "ImportSpecifier": + case "ExportSpecifier": + case "ImportNamespaceSpecifier": + case "ExportNamespaceSpecifier": + case "ImportDefaultSpecifier": + case "ExportDefaultSpecifier": + return printModuleSpecifier(path, options, print); + + case "ImportAttribute": + return [print("key"), ": ", print("value")]; + + case "Import": + return "import"; + + case "BlockStatement": + case "StaticBlock": + case "ClassBody": + return printBlock$1(path, options, print); + + case "ThrowStatement": + return printThrowStatement(path, options, print); + + case "ReturnStatement": + return printReturnStatement(path, options, print); + + case "NewExpression": + case "ImportExpression": + case "OptionalCallExpression": + case "CallExpression": + return printCallExpression(path, options, print); + + case "ObjectExpression": + case "ObjectPattern": + case "RecordExpression": + return printObject(path, options, print); + // Babel 6 + + case "ObjectProperty": // Non-standard AST node type. + + case "Property": + if (node.method || node.kind === "get" || node.kind === "set") { + return printMethod(path, options, print); + } + + return printProperty(path, options, print); + + case "ObjectMethod": + return printMethod(path, options, print); + + case "Decorator": + return ["@", print("expression")]; + + case "ArrayExpression": + case "ArrayPattern": + case "TupleExpression": + return printArray(path, options, print); + + case "SequenceExpression": + { + const parent = path.getParentNode(0); + + if (parent.type === "ExpressionStatement" || parent.type === "ForStatement") { + // For ExpressionStatements and for-loop heads, which are among + // the few places a SequenceExpression appears unparenthesized, we want + // to indent expressions after the first. + const parts = []; + path.each((expressionPath, index) => { + if (index === 0) { + parts.push(print()); + } else { + parts.push(",", indent$7([line$a, print()])); + } + }, "expressions"); + return group$c(parts); + } + + return group$c(join$b([",", line$a], path.map(print, "expressions"))); + } + + case "ThisExpression": + return "this"; + + case "Super": + return "super"; + + case "Directive": + return [print("value"), semi]; + // Babel 6 + + case "DirectiveLiteral": + return printDirective(node, options); + + case "UnaryExpression": + parts.push(node.operator); + + if (/[a-z]$/.test(node.operator)) { + parts.push(" "); + } + + if (hasComment(node.argument)) { + parts.push(group$c(["(", indent$7([softline$8, print("argument")]), softline$8, ")"])); + } else { + parts.push(print("argument")); + } + + return parts; + + case "UpdateExpression": + parts.push(print("argument"), node.operator); + + if (node.prefix) { + parts.reverse(); + } + + return parts; + + case "ConditionalExpression": + return printTernary(path, options, print); + + case "VariableDeclaration": + { + const printed = path.map(print, "declarations"); // We generally want to terminate all variable declarations with a + // semicolon, except when they in the () part of for loops. + + const parentNode = path.getParentNode(); + const isParentForLoop = parentNode.type === "ForStatement" || parentNode.type === "ForInStatement" || parentNode.type === "ForOfStatement"; + const hasValue = node.declarations.some(decl => decl.init); + let firstVariable; + + if (printed.length === 1 && !hasComment(node.declarations[0])) { + firstVariable = printed[0]; + } else if (printed.length > 0) { + // Indent first var to comply with eslint one-var rule + firstVariable = indent$7(printed[0]); + } + + parts = [node.declare ? "declare " : "", node.kind, firstVariable ? [" ", firstVariable] : "", indent$7(printed.slice(1).map(p => [",", hasValue && !isParentForLoop ? hardline$d : line$a, p]))]; + + if (!(isParentForLoop && parentNode.body !== node)) { + parts.push(semi); + } + + return group$c(parts); + } + + case "WithStatement": + return group$c(["with (", print("object"), ")", adjustClause(node.body, print("body"))]); + + case "IfStatement": + { + const con = adjustClause(node.consequent, print("consequent")); + const opening = group$c(["if (", group$c([indent$7([softline$8, print("test")]), softline$8]), ")", con]); + parts.push(opening); + + if (node.alternate) { + const commentOnOwnLine = hasComment(node.consequent, CommentCheckFlags.Trailing | CommentCheckFlags.Line) || needsHardlineAfterDanglingComment(node); + const elseOnSameLine = node.consequent.type === "BlockStatement" && !commentOnOwnLine; + parts.push(elseOnSameLine ? " " : hardline$d); + + if (hasComment(node, CommentCheckFlags.Dangling)) { + parts.push(printDanglingComments(path, options, true), commentOnOwnLine ? hardline$d : " "); + } + + parts.push("else", group$c(adjustClause(node.alternate, print("alternate"), node.alternate.type === "IfStatement"))); + } + + return parts; + } + + case "ForStatement": + { + const body = adjustClause(node.body, print("body")); // We want to keep dangling comments above the loop to stay consistent. + // Any comment positioned between the for statement and the parentheses + // is going to be printed before the statement. + + const dangling = printDanglingComments(path, options, + /* sameLine */ + true); + const printedComments = dangling ? [dangling, softline$8] : ""; + + if (!node.init && !node.test && !node.update) { + return [printedComments, group$c(["for (;;)", body])]; + } + + return [printedComments, group$c(["for (", group$c([indent$7([softline$8, print("init"), ";", line$a, print("test"), ";", line$a, print("update")]), softline$8]), ")", body])]; + } + + case "WhileStatement": + return group$c(["while (", group$c([indent$7([softline$8, print("test")]), softline$8]), ")", adjustClause(node.body, print("body"))]); + + case "ForInStatement": + return group$c(["for (", print("left"), " in ", print("right"), ")", adjustClause(node.body, print("body"))]); + + case "ForOfStatement": + return group$c(["for", node.await ? " await" : "", " (", print("left"), " of ", print("right"), ")", adjustClause(node.body, print("body"))]); + + case "DoWhileStatement": + { + const clause = adjustClause(node.body, print("body")); + const doBody = group$c(["do", clause]); + parts = [doBody]; + + if (node.body.type === "BlockStatement") { + parts.push(" "); + } else { + parts.push(hardline$d); + } + + parts.push("while (", group$c([indent$7([softline$8, print("test")]), softline$8]), ")", semi); + return parts; + } + + case "DoExpression": + return [node.async ? "async " : "", "do ", print("body")]; + + case "BreakStatement": + parts.push("break"); + + if (node.label) { + parts.push(" ", print("label")); + } + + parts.push(semi); + return parts; + + case "ContinueStatement": + parts.push("continue"); + + if (node.label) { + parts.push(" ", print("label")); + } + + parts.push(semi); + return parts; + + case "LabeledStatement": + if (node.body.type === "EmptyStatement") { + return [print("label"), ":;"]; + } + + return [print("label"), ": ", print("body")]; + + case "TryStatement": + return ["try ", print("block"), node.handler ? [" ", print("handler")] : "", node.finalizer ? [" finally ", print("finalizer")] : ""]; + + case "CatchClause": + if (node.param) { + const parameterHasComments = hasComment(node.param, comment => !isBlockComment(comment) || comment.leading && hasNewline$1(options.originalText, locEnd$c(comment)) || comment.trailing && hasNewline$1(options.originalText, locStart$d(comment), { + backwards: true + })); + const param = print("param"); + return ["catch ", parameterHasComments ? ["(", indent$7([softline$8, param]), softline$8, ") "] : ["(", param, ") "], print("body")]; + } + + return ["catch ", print("body")]; + // Note: ignoring n.lexical because it has no printing consequences. + + case "SwitchStatement": + return [group$c(["switch (", indent$7([softline$8, print("discriminant")]), softline$8, ")"]), " {", node.cases.length > 0 ? indent$7([hardline$d, join$b(hardline$d, path.map((casePath, index, cases) => { + const caseNode = casePath.getValue(); + return [print(), index !== cases.length - 1 && isNextLineEmpty$4(caseNode, options) ? hardline$d : ""]; + }, "cases"))]) : "", hardline$d, "}"]; + + case "SwitchCase": + { + if (node.test) { + parts.push("case ", print("test"), ":"); + } else { + parts.push("default:"); + } + + const consequent = node.consequent.filter(node => node.type !== "EmptyStatement"); + + if (consequent.length > 0) { + const cons = printSwitchCaseConsequent(path, options, print); + parts.push(consequent.length === 1 && consequent[0].type === "BlockStatement" ? [" ", cons] : indent$7([hardline$d, cons])); + } + + return parts; + } + // JSX extensions below. + + case "DebuggerStatement": + return ["debugger", semi]; + + case "ClassDeclaration": + case "ClassExpression": + return printClass(path, options, print); + + case "ClassMethod": + case "ClassPrivateMethod": + case "MethodDefinition": + return printClassMethod(path, options, print); + + case "ClassProperty": + case "PropertyDefinition": + case "ClassPrivateProperty": + return printClassProperty(path, options, print); + + case "TemplateElement": + return replaceNewlinesWithLiterallines$1(node.value.raw); + + case "TemplateLiteral": + return printTemplateLiteral(path, print, options); + + case "TaggedTemplateExpression": + return [print("tag"), print("typeParameters"), print("quasi")]; + + case "PrivateIdentifier": + return ["#", print("name")]; + + case "PrivateName": + return ["#", print("id")]; + + case "InterpreterDirective": + parts.push("#!", node.value, hardline$d); + + if (isNextLineEmpty$4(node, options)) { + parts.push(hardline$d); + } + + return parts; + + case "PipelineBareFunction": + return print("callee"); + + case "PipelineTopicExpression": + return print("expression"); + + case "PipelinePrimaryTopicReference": + return "#"; + + case "ArgumentPlaceholder": + return "?"; + + case "ModuleExpression": + { + parts.push("module {"); + const printed = print("body"); + + if (printed) { + parts.push(indent$7([hardline$d, printed]), hardline$d); + } + + parts.push("}"); + return parts; + } + + default: + /* istanbul ignore next */ + throw new Error("unknown type: " + JSON.stringify(node.type)); + } +} + +function printDirective(node, options) { + const raw = rawText(node); + const rawContent = raw.slice(1, -1); // Check for the alternate quote, to determine if we're allowed to swap + // the quotes on a DirectiveLiteral. + + if (rawContent.includes('"') || rawContent.includes("'")) { + return raw; + } + + const enclosingQuote = options.singleQuote ? "'" : '"'; // Directives are exact code unit sequences, which means that you can't + // change the escape sequences they use. + // See https://github.com/prettier/prettier/issues/1555 + // and https://tc39.github.io/ecma262/#directive-prologue + + return enclosingQuote + rawContent + enclosingQuote; +} + +function canAttachComment$1(node) { + return node.type && !isBlockComment(node) && !isLineComment(node) && node.type !== "EmptyStatement" && node.type !== "TemplateElement" && node.type !== "Import" && // `babel-ts` don't have similar node for `class Foo { bar() /* bat */; }` + node.type !== "TSEmptyBodyFunctionExpression"; +} + +var printerEstree = { + preprocess: printPreprocess$3, + print: genericPrint$6, + embed: embed_1$3, + insertPragma: insertPragma$9, + massageAstNode: clean_1$4, + + hasPrettierIgnore(path) { + return hasIgnoreComment(path) || hasJsxIgnoreComment(path); + }, + + willPrintOwnComments: comments.willPrintOwnComments, + canAttachComment: canAttachComment$1, + printComment: printComment$1, + isBlockComment, + handleComments: { + // TODO: Make this as default behavior + avoidAstMutation: true, + ownLine: comments.handleOwnLineComment, + endOfLine: comments.handleEndOfLineComment, + remaining: comments.handleRemainingComment + }, + getCommentChildNodes: comments.getCommentChildNodes +}; + +const { + builders: { + hardline: hardline$c, + indent: indent$6, + join: join$a + } +} = doc; + +function genericPrint$5(path, options, print) { + const node = path.getValue(); + + switch (node.type) { + case "JsonRoot": + return [print("node"), hardline$c]; + + case "ArrayExpression": + { + if (node.elements.length === 0) { + return "[]"; + } + + const printed = path.map(() => path.getValue() === null ? "null" : print(), "elements"); + return ["[", indent$6([hardline$c, join$a([",", hardline$c], printed)]), hardline$c, "]"]; + } + + case "ObjectExpression": + return node.properties.length === 0 ? "{}" : ["{", indent$6([hardline$c, join$a([",", hardline$c], path.map(print, "properties"))]), hardline$c, "}"]; + + case "ObjectProperty": + return [print("key"), ": ", print("value")]; + + case "UnaryExpression": + return [node.operator === "+" ? "" : node.operator, print("argument")]; + + case "NullLiteral": + return "null"; + + case "BooleanLiteral": + return node.value ? "true" : "false"; + + case "StringLiteral": + case "NumericLiteral": + return JSON.stringify(node.value); + + case "Identifier": + { + const parent = path.getParentNode(); + + if (parent && parent.type === "ObjectProperty" && parent.key === node) { + return JSON.stringify(node.name); + } + + return node.name; + } + + case "TemplateLiteral": + // There is only one `TemplateElement` + return print(["quasis", 0]); + + case "TemplateElement": + return JSON.stringify(node.value.cooked); + + default: + /* istanbul ignore next */ + throw new Error("unknown type: " + JSON.stringify(node.type)); + } +} + +const ignoredProperties$3 = new Set(["start", "end", "extra", "loc", "comments", "leadingComments", "trailingComments", "innerComments", "errors", "range", "tokens"]); + +function clean$6(node, newNode +/*, parent*/ +) { + const { + type + } = node; // We print quoted key + + if (type === "ObjectProperty" && node.key.type === "Identifier") { + newNode.key = { + type: "StringLiteral", + value: node.key.name + }; + return; + } + + if (type === "UnaryExpression" && node.operator === "+") { + return newNode.argument; + } // We print holes in array as `null` + + + if (type === "ArrayExpression") { + for (const [index, element] of node.elements.entries()) { + if (element === null) { + newNode.elements.splice(index, 0, { + type: "NullLiteral" + }); + } + } + + return; + } // We print `TemplateLiteral` as string + + + if (type === "TemplateLiteral") { + return { + type: "StringLiteral", + value: node.quasis[0].value.cooked + }; + } +} + +clean$6.ignoredProperties = ignoredProperties$3; +var printerEstreeJson = { + preprocess: printPreprocess$3, + print: genericPrint$5, + massageAstNode: clean$6 +}; + +const CATEGORY_COMMON = "Common"; // format based on https://github.com/prettier/prettier/blob/main/src/main/core-options.js + +var commonOptions = { + bracketSpacing: { + since: "0.0.0", + category: CATEGORY_COMMON, + type: "boolean", + default: true, + description: "Print spaces between brackets.", + oppositeDescription: "Do not print spaces between brackets." + }, + singleQuote: { + since: "0.0.0", + category: CATEGORY_COMMON, + type: "boolean", + default: false, + description: "Use single quotes instead of double quotes." + }, + proseWrap: { + since: "1.8.2", + category: CATEGORY_COMMON, + type: "choice", + default: [{ + since: "1.8.2", + value: true + }, { + since: "1.9.0", + value: "preserve" + }], + description: "How to wrap prose.", + choices: [{ + since: "1.9.0", + value: "always", + description: "Wrap prose if it exceeds the print width." + }, { + since: "1.9.0", + value: "never", + description: "Do not wrap prose." + }, { + since: "1.9.0", + value: "preserve", + description: "Wrap prose as-is." + }] + } +}; + +const CATEGORY_JAVASCRIPT = "JavaScript"; // format based on https://github.com/prettier/prettier/blob/main/src/main/core-options.js + +var options$5 = { + arrowParens: { + since: "1.9.0", + category: CATEGORY_JAVASCRIPT, + type: "choice", + default: [{ + since: "1.9.0", + value: "avoid" + }, { + since: "2.0.0", + value: "always" + }], + description: "Include parentheses around a sole arrow function parameter.", + choices: [{ + value: "always", + description: "Always include parens. Example: `(x) => x`" + }, { + value: "avoid", + description: "Omit parens when possible. Example: `x => x`" + }] + }, + bracketSpacing: commonOptions.bracketSpacing, + jsxBracketSameLine: { + since: "0.17.0", + category: CATEGORY_JAVASCRIPT, + type: "boolean", + default: false, + description: "Put > on the last line instead of at a new line." + }, + semi: { + since: "1.0.0", + category: CATEGORY_JAVASCRIPT, + type: "boolean", + default: true, + description: "Print semicolons.", + oppositeDescription: "Do not print semicolons, except at the beginning of lines which may need them." + }, + singleQuote: commonOptions.singleQuote, + jsxSingleQuote: { + since: "1.15.0", + category: CATEGORY_JAVASCRIPT, + type: "boolean", + default: false, + description: "Use single quotes in JSX." + }, + quoteProps: { + since: "1.17.0", + category: CATEGORY_JAVASCRIPT, + type: "choice", + default: "as-needed", + description: "Change when properties in objects are quoted.", + choices: [{ + value: "as-needed", + description: "Only add quotes around object properties where required." + }, { + value: "consistent", + description: "If at least one property in an object requires quotes, quote all properties." + }, { + value: "preserve", + description: "Respect the input use of quotes in object properties." + }] + }, + trailingComma: { + since: "0.0.0", + category: CATEGORY_JAVASCRIPT, + type: "choice", + default: [{ + since: "0.0.0", + value: false + }, { + since: "0.19.0", + value: "none" + }, { + since: "2.0.0", + value: "es5" + }], + description: "Print trailing commas wherever possible when multi-line.", + choices: [{ + value: "es5", + description: "Trailing commas where valid in ES5 (objects, arrays, etc.)" + }, { + value: "none", + description: "No trailing commas." + }, { + value: "all", + description: "Trailing commas wherever possible (including function arguments)." + }] + } +}; + +var name$f = "JavaScript"; +var type$f = "programming"; +var tmScope$f = "source.js"; +var aceMode$f = "javascript"; +var codemirrorMode$b = "javascript"; +var codemirrorMimeType$b = "text/javascript"; +var color$a = "#f1e05a"; +var aliases$6 = [ + "js", + "node" +]; +var extensions$f = [ + ".js", + "._js", + ".bones", + ".cjs", + ".es", + ".es6", + ".frag", + ".gs", + ".jake", + ".jsb", + ".jscad", + ".jsfl", + ".jsm", + ".jss", + ".jsx", + ".mjs", + ".njs", + ".pac", + ".sjs", + ".ssjs", + ".xsjs", + ".xsjslib" +]; +var filenames$4 = [ + "Jakefile" +]; +var interpreters$1 = [ + "chakra", + "d8", + "gjs", + "js", + "node", + "nodejs", + "qjs", + "rhino", + "v8", + "v8-shell" +]; +var languageId$f = 183; +var require$$0$6 = { + name: name$f, + type: type$f, + tmScope: tmScope$f, + aceMode: aceMode$f, + codemirrorMode: codemirrorMode$b, + codemirrorMimeType: codemirrorMimeType$b, + color: color$a, + aliases: aliases$6, + extensions: extensions$f, + filenames: filenames$4, + interpreters: interpreters$1, + languageId: languageId$f +}; + +var name$e = "TypeScript"; +var type$e = "programming"; +var color$9 = "#2b7489"; +var aliases$5 = [ + "ts" +]; +var interpreters = [ + "deno", + "ts-node" +]; +var extensions$e = [ + ".ts" +]; +var tmScope$e = "source.ts"; +var aceMode$e = "typescript"; +var codemirrorMode$a = "javascript"; +var codemirrorMimeType$a = "application/typescript"; +var languageId$e = 378; +var require$$1$3 = { + name: name$e, + type: type$e, + color: color$9, + aliases: aliases$5, + interpreters: interpreters, + extensions: extensions$e, + tmScope: tmScope$e, + aceMode: aceMode$e, + codemirrorMode: codemirrorMode$a, + codemirrorMimeType: codemirrorMimeType$a, + languageId: languageId$e +}; + +var name$d = "TSX"; +var type$d = "programming"; +var group$b = "TypeScript"; +var extensions$d = [ + ".tsx" +]; +var tmScope$d = "source.tsx"; +var aceMode$d = "javascript"; +var codemirrorMode$9 = "jsx"; +var codemirrorMimeType$9 = "text/jsx"; +var languageId$d = 94901924; +var require$$2$2 = { + name: name$d, + type: type$d, + group: group$b, + extensions: extensions$d, + tmScope: tmScope$d, + aceMode: aceMode$d, + codemirrorMode: codemirrorMode$9, + codemirrorMimeType: codemirrorMimeType$9, + languageId: languageId$d +}; + +var name$c = "JSON"; +var type$c = "data"; +var tmScope$c = "source.json"; +var aceMode$c = "json"; +var codemirrorMode$8 = "javascript"; +var codemirrorMimeType$8 = "application/json"; +var extensions$c = [ + ".json", + ".avsc", + ".geojson", + ".gltf", + ".har", + ".ice", + ".JSON-tmLanguage", + ".jsonl", + ".mcmeta", + ".tfstate", + ".tfstate.backup", + ".topojson", + ".webapp", + ".webmanifest", + ".yy", + ".yyp" +]; +var filenames$3 = [ + ".arcconfig", + ".htmlhintrc", + ".imgbotconfig", + ".tern-config", + ".tern-project", + ".watchmanconfig", + "Pipfile.lock", + "composer.lock", + "mcmod.info" +]; +var languageId$c = 174; +var require$$3$1 = { + name: name$c, + type: type$c, + tmScope: tmScope$c, + aceMode: aceMode$c, + codemirrorMode: codemirrorMode$8, + codemirrorMimeType: codemirrorMimeType$8, + extensions: extensions$c, + filenames: filenames$3, + languageId: languageId$c +}; + +var name$b = "JSON with Comments"; +var type$b = "data"; +var group$a = "JSON"; +var tmScope$b = "source.js"; +var aceMode$b = "javascript"; +var codemirrorMode$7 = "javascript"; +var codemirrorMimeType$7 = "text/javascript"; +var aliases$4 = [ + "jsonc" +]; +var extensions$b = [ + ".jsonc", + ".sublime-build", + ".sublime-commands", + ".sublime-completions", + ".sublime-keymap", + ".sublime-macro", + ".sublime-menu", + ".sublime-mousemap", + ".sublime-project", + ".sublime-settings", + ".sublime-theme", + ".sublime-workspace", + ".sublime_metrics", + ".sublime_session" +]; +var filenames$2 = [ + ".babelrc", + ".eslintrc.json", + ".jscsrc", + ".jshintrc", + ".jslintrc", + "api-extractor.json", + "devcontainer.json", + "jsconfig.json", + "language-configuration.json", + "tsconfig.json", + "tslint.json" +]; +var languageId$b = 423; +var require$$4 = { + name: name$b, + type: type$b, + group: group$a, + tmScope: tmScope$b, + aceMode: aceMode$b, + codemirrorMode: codemirrorMode$7, + codemirrorMimeType: codemirrorMimeType$7, + aliases: aliases$4, + extensions: extensions$b, + filenames: filenames$2, + languageId: languageId$b +}; + +var name$a = "JSON5"; +var type$a = "data"; +var extensions$a = [ + ".json5" +]; +var tmScope$a = "source.js"; +var aceMode$a = "javascript"; +var codemirrorMode$6 = "javascript"; +var codemirrorMimeType$6 = "application/json"; +var languageId$a = 175; +var require$$5 = { + name: name$a, + type: type$a, + extensions: extensions$a, + tmScope: tmScope$a, + aceMode: aceMode$a, + codemirrorMode: codemirrorMode$6, + codemirrorMimeType: codemirrorMimeType$6, + languageId: languageId$a +}; + +const languages$7 = [createLanguage(require$$0$6, data => ({ + since: "0.0.0", + parsers: ["babel", "espree", "meriyah", "babel-flow", "babel-ts", "flow", "typescript"], + vscodeLanguageIds: ["javascript", "mongo"], + extensions: [...data.extensions.filter(extension => extension !== ".jsx"), // WeiXin Script (Weixin Mini Programs) + // https://developers.weixin.qq.com/miniprogram/en/dev/framework/view/wxs/ + ".wxs"] +})), createLanguage(require$$0$6, () => ({ + name: "Flow", + since: "0.0.0", + parsers: ["flow", "babel-flow"], + vscodeLanguageIds: ["javascript"], + aliases: [], + filenames: [], + extensions: [".js.flow"] +})), createLanguage(require$$0$6, () => ({ + name: "JSX", + since: "0.0.0", + parsers: ["babel", "babel-flow", "babel-ts", "flow", "typescript", "espree", "meriyah"], + vscodeLanguageIds: ["javascriptreact"], + aliases: undefined, + filenames: undefined, + extensions: [".jsx"], + group: "JavaScript", + interpreters: undefined, + tmScope: "source.js.jsx", + aceMode: "javascript", + codemirrorMode: "jsx", + codemirrorMimeType: "text/jsx", + color: undefined +})), createLanguage(require$$1$3, () => ({ + since: "1.4.0", + parsers: ["typescript", "babel-ts"], + vscodeLanguageIds: ["typescript"] +})), createLanguage(require$$2$2, () => ({ + since: "1.4.0", + parsers: ["typescript", "babel-ts"], + vscodeLanguageIds: ["typescriptreact"] +})), createLanguage(require$$3$1, () => ({ + name: "JSON.stringify", + since: "1.13.0", + parsers: ["json-stringify"], + vscodeLanguageIds: ["json"], + extensions: [], + // .json file defaults to json instead of json-stringify + filenames: ["package.json", "package-lock.json", "composer.json"] +})), createLanguage(require$$3$1, data => ({ + since: "1.5.0", + parsers: ["json"], + vscodeLanguageIds: ["json"], + extensions: data.extensions.filter(extension => extension !== ".jsonl") +})), createLanguage(require$$4, data => ({ + since: "1.5.0", + parsers: ["json"], + vscodeLanguageIds: ["jsonc"], + filenames: [...data.filenames, ".eslintrc"] +})), createLanguage(require$$5, () => ({ + since: "1.13.0", + parsers: ["json5"], + vscodeLanguageIds: ["json5"] +}))]; +const printers$5 = { + estree: printerEstree, + "estree-json": printerEstreeJson +}; +const parsers$6 = { + // JS - Babel + get babel() { + return require("./parser-babel").parsers.babel; + }, + + get "babel-flow"() { + return require("./parser-babel").parsers["babel-flow"]; + }, + + get "babel-ts"() { + return require("./parser-babel").parsers["babel-ts"]; + }, + + get json() { + return require("./parser-babel").parsers.json; + }, + + get json5() { + return require("./parser-babel").parsers.json5; + }, + + get "json-stringify"() { + return require("./parser-babel").parsers["json-stringify"]; + }, + + get __js_expression() { + return require("./parser-babel").parsers.__js_expression; + }, + + get __vue_expression() { + return require("./parser-babel").parsers.__vue_expression; + }, + + get __vue_event_binding() { + return require("./parser-babel").parsers.__vue_event_binding; + }, + + // JS - Flow + get flow() { + return require("./parser-flow").parsers.flow; + }, + + // JS - TypeScript + get typescript() { + return require("./parser-typescript").parsers.typescript; + }, + + // JS - Angular Action + get __ng_action() { + return require("./parser-angular").parsers.__ng_action; + }, + + // JS - Angular Binding + get __ng_binding() { + return require("./parser-angular").parsers.__ng_binding; + }, + + // JS - Angular Interpolation + get __ng_interpolation() { + return require("./parser-angular").parsers.__ng_interpolation; + }, + + // JS - Angular Directive + get __ng_directive() { + return require("./parser-angular").parsers.__ng_directive; + }, + + // JS - espree + get espree() { + return require("./parser-espree").parsers.espree; + }, + + // JS - meriyah + get meriyah() { + return require("./parser-meriyah").parsers.meriyah; + }, + + // JS - Babel Estree + get __babel_estree() { + return require("./parser-babel").parsers.__babel_estree; + } + +}; +var languageJs = { + languages: languages$7, + options: options$5, + printers: printers$5, + parsers: parsers$6 +}; + +const { + isFrontMatterNode: isFrontMatterNode$4 +} = util$5; +const ignoredProperties$2 = new Set(["raw", // front-matter +"raws", "sourceIndex", "source", "before", "after", "trailingComma"]); + +function clean$5(ast, newObj, parent) { + if (isFrontMatterNode$4(ast) && ast.lang === "yaml") { + delete newObj.value; + } + + if (ast.type === "css-comment" && parent.type === "css-root" && parent.nodes.length > 0) { + // --insert-pragma + // first non-front-matter comment + if (parent.nodes[0] === ast || isFrontMatterNode$4(parent.nodes[0]) && parent.nodes[1] === ast) { + /** + * something + * + * @format + */ + delete newObj.text; // standalone pragma + + if (/^\*\s*@(format|prettier)\s*$/.test(ast.text)) { + return null; + } + } // Last comment is not parsed, when omitting semicolon, #8675 + + + if (parent.type === "css-root" && getLast_1(parent.nodes) === ast) { + return null; + } + } + + if (ast.type === "value-root") { + delete newObj.text; + } + + if (ast.type === "media-query" || ast.type === "media-query-list" || ast.type === "media-feature-expression") { + delete newObj.value; + } + + if (ast.type === "css-rule") { + delete newObj.params; + } + + if (ast.type === "selector-combinator") { + newObj.value = newObj.value.replace(/\s+/g, " "); + } + + if (ast.type === "media-feature") { + newObj.value = newObj.value.replace(/ /g, ""); + } + + if (ast.type === "value-word" && (ast.isColor && ast.isHex || ["initial", "inherit", "unset", "revert"].includes(newObj.value.replace().toLowerCase())) || ast.type === "media-feature" || ast.type === "selector-root-invalid" || ast.type === "selector-pseudo") { + newObj.value = newObj.value.toLowerCase(); + } + + if (ast.type === "css-decl") { + newObj.prop = newObj.prop.toLowerCase(); + } + + if (ast.type === "css-atrule" || ast.type === "css-import") { + newObj.name = newObj.name.toLowerCase(); + } + + if (ast.type === "value-number") { + newObj.unit = newObj.unit.toLowerCase(); + } + + if ((ast.type === "media-feature" || ast.type === "media-keyword" || ast.type === "media-type" || ast.type === "media-unknown" || ast.type === "media-url" || ast.type === "media-value" || ast.type === "selector-attribute" || ast.type === "selector-string" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "value-string") && newObj.value) { + newObj.value = cleanCSSStrings(newObj.value); + } + + if (ast.type === "selector-attribute") { + newObj.attribute = newObj.attribute.trim(); + + if (newObj.namespace) { + if (typeof newObj.namespace === "string") { + newObj.namespace = newObj.namespace.trim(); + + if (newObj.namespace.length === 0) { + newObj.namespace = true; + } + } + } + + if (newObj.value) { + newObj.value = newObj.value.trim().replace(/^["']|["']$/g, ""); + delete newObj.quoted; + } + } + + if ((ast.type === "media-value" || ast.type === "media-type" || ast.type === "value-number" || ast.type === "selector-root-invalid" || ast.type === "selector-class" || ast.type === "selector-combinator" || ast.type === "selector-tag") && newObj.value) { + newObj.value = newObj.value.replace(/([\d+.Ee-]+)([A-Za-z]*)/g, (match, numStr, unit) => { + const num = Number(numStr); + return Number.isNaN(num) ? match : num + unit.toLowerCase(); + }); + } + + if (ast.type === "selector-tag") { + const lowercasedValue = ast.value.toLowerCase(); + + if (["from", "to"].includes(lowercasedValue)) { + newObj.value = lowercasedValue; + } + } // Workaround when `postcss-values-parser` parse `not`, `and` or `or` keywords as `value-func` + + + if (ast.type === "css-atrule" && ast.name.toLowerCase() === "supports") { + delete newObj.value; + } // Workaround for SCSS nested properties + + + if (ast.type === "selector-unknown") { + delete newObj.value; + } +} + +clean$5.ignoredProperties = ignoredProperties$2; + +function cleanCSSStrings(value) { + return value.replace(/'/g, '"').replace(/\\([^\dA-Fa-f])/g, "$1"); +} + +var clean_1$3 = clean$5; + +const { + builders: { + hardline: hardline$b, + markAsRoot: markAsRoot$3 + } +} = doc; + +function print$1(node, textToDoc) { + if (node.lang === "yaml") { + const value = node.value.trim(); + const doc = value ? textToDoc(value, { + parser: "yaml" + }, { + stripTrailingHardline: true + }) : ""; + return markAsRoot$3([node.startDelimiter, hardline$b, doc, doc ? hardline$b : "", node.endDelimiter]); + } +} + +var print_1 = print$1; + +const { + builders: { + hardline: hardline$a + } +} = doc; + +function embed$4(path, print, textToDoc +/*, options */ +) { + const node = path.getValue(); + + if (node.type === "front-matter") { + const doc = print_1(node, textToDoc); + return doc ? [doc, hardline$a] : ""; + } +} + +var embed_1$2 = embed$4; + +const frontMatterRegex = new RegExp("^(?-{3}|\\+{3})" + // trailing spaces after delimiters are allowed +"(?[^\\n]*)" + "\\n(?:|(?.*?)\\n)" + // In some markdown processors such as pandoc, +// "..." can be used as the end delimiter for YAML front-matter. +// Adding `\.{3}` make the regex matches `+++\n...`, but we'll exclude it later +"(?\\k|\\.{3})" + "[^\\S\\n]*(?:\\n|$)", "s"); + +function parse(text) { + const match = text.match(frontMatterRegex); + + if (!match) { + return { + content: text + }; + } + + const { + startDelimiter, + language, + value = "", + endDelimiter + } = match.groups; + let lang = language.trim() || "yaml"; + + if (startDelimiter === "+++") { + lang = "toml"; + } // Only allow yaml to parse with a different end delimiter + + + if (lang !== "yaml" && startDelimiter !== endDelimiter) { + return { + content: text + }; + } + + const [raw] = match; + const frontMatter = { + type: "front-matter", + lang, + value, + startDelimiter, + endDelimiter, + raw: raw.replace(/\n$/, "") + }; + return { + frontMatter, + content: raw.replace(/[^\n]/g, " ") + text.slice(raw.length) + }; +} + +var parse_1 = parse; + +function hasPragma$3(text) { + return pragma$5.hasPragma(parse_1(text).content); +} + +function insertPragma$8(text) { + const { + frontMatter, + content + } = parse_1(text); + return (frontMatter ? frontMatter.raw + "\n\n" : "") + pragma$5.insertPragma(content); +} + +var pragma$4 = { + hasPragma: hasPragma$3, + insertPragma: insertPragma$8 +}; + +const { + isNonEmptyArray: isNonEmptyArray$6 +} = util$5; +const colorAdjusterFunctions = new Set(["red", "green", "blue", "alpha", "a", "rgb", "hue", "h", "saturation", "s", "lightness", "l", "whiteness", "w", "blackness", "b", "tint", "shade", "blend", "blenda", "contrast", "hsl", "hsla", "hwb", "hwba"]); + +function getAncestorCounter$1(path, typeOrTypes) { + const types = Array.isArray(typeOrTypes) ? typeOrTypes : [typeOrTypes]; + let counter = -1; + let ancestorNode; + + while (ancestorNode = path.getParentNode(++counter)) { + if (types.includes(ancestorNode.type)) { + return counter; + } + } + + return -1; +} + +function getAncestorNode$2(path, typeOrTypes) { + const counter = getAncestorCounter$1(path, typeOrTypes); + return counter === -1 ? null : path.getParentNode(counter); +} + +function getPropOfDeclNode$1(path) { + const declAncestorNode = getAncestorNode$2(path, "css-decl"); + return declAncestorNode && declAncestorNode.prop && declAncestorNode.prop.toLowerCase(); +} + +function hasSCSSInterpolation(groupList) { + if (isNonEmptyArray$6(groupList)) { + for (let i = groupList.length - 1; i > 0; i--) { + // If we find `#{`, return true. + if (groupList[i].type === "word" && groupList[i].value === "{" && groupList[i - 1].type === "word" && groupList[i - 1].value.endsWith("#")) { + return true; + } + } + } + + return false; +} + +function hasStringOrFunction(groupList) { + if (isNonEmptyArray$6(groupList)) { + for (let i = 0; i < groupList.length; i++) { + if (groupList[i].type === "string" || groupList[i].type === "func") { + return true; + } + } + } + + return false; +} + +function isSCSS$1(parser, text) { + const hasExplicitParserChoice = parser === "less" || parser === "scss"; + const IS_POSSIBLY_SCSS = /(\w\s*:\s*[^:}]+|#){|@import[^\n]+(?:url|,)/; + return hasExplicitParserChoice ? parser === "scss" : IS_POSSIBLY_SCSS.test(text); +} + +function isSCSSVariable(node) { + return Boolean(node && node.type === "word" && node.value.startsWith("$")); +} + +function isWideKeywords$1(value) { + return ["initial", "inherit", "unset", "revert"].includes(value.toLowerCase()); +} + +function isKeyframeAtRuleKeywords$1(path, value) { + const atRuleAncestorNode = getAncestorNode$2(path, "css-atrule"); + return atRuleAncestorNode && atRuleAncestorNode.name && atRuleAncestorNode.name.toLowerCase().endsWith("keyframes") && ["from", "to"].includes(value.toLowerCase()); +} + +function maybeToLowerCase$1(value) { + return value.includes("$") || value.includes("@") || value.includes("#") || value.startsWith("%") || value.startsWith("--") || value.startsWith(":--") || value.includes("(") && value.includes(")") ? value : value.toLowerCase(); +} + +function insideValueFunctionNode$1(path, functionName) { + const funcAncestorNode = getAncestorNode$2(path, "value-func"); + return funcAncestorNode && funcAncestorNode.value && funcAncestorNode.value.toLowerCase() === functionName; +} + +function insideICSSRuleNode$1(path) { + const ruleAncestorNode = getAncestorNode$2(path, "css-rule"); + return ruleAncestorNode && ruleAncestorNode.raws && ruleAncestorNode.raws.selector && (ruleAncestorNode.raws.selector.startsWith(":import") || ruleAncestorNode.raws.selector.startsWith(":export")); +} + +function insideAtRuleNode$1(path, atRuleNameOrAtRuleNames) { + const atRuleNames = Array.isArray(atRuleNameOrAtRuleNames) ? atRuleNameOrAtRuleNames : [atRuleNameOrAtRuleNames]; + const atRuleAncestorNode = getAncestorNode$2(path, "css-atrule"); + return atRuleAncestorNode && atRuleNames.includes(atRuleAncestorNode.name.toLowerCase()); +} + +function insideURLFunctionInImportAtRuleNode$1(path) { + const node = path.getValue(); + const atRuleAncestorNode = getAncestorNode$2(path, "css-atrule"); + return atRuleAncestorNode && atRuleAncestorNode.name === "import" && node.groups[0].value === "url" && node.groups.length === 2; +} + +function isURLFunctionNode$1(node) { + return node.type === "value-func" && node.value.toLowerCase() === "url"; +} + +function isLastNode$1(path, node) { + const parentNode = path.getParentNode(); + /* istanbul ignore next */ + + if (!parentNode) { + return false; + } + + const { + nodes + } = parentNode; + return nodes && nodes.indexOf(node) === nodes.length - 1; +} + +function isDetachedRulesetDeclarationNode$1(node) { + // If a Less file ends up being parsed with the SCSS parser, Less + // variable declarations will be parsed as atrules with names ending + // with a colon, so keep the original case then. + + /* istanbul ignore next */ + if (!node.selector) { + return false; + } + + return typeof node.selector === "string" && /^@.+:.*$/.test(node.selector) || node.selector.value && /^@.+:.*$/.test(node.selector.value); +} + +function isForKeywordNode$1(node) { + return node.type === "value-word" && ["from", "through", "end"].includes(node.value); +} + +function isIfElseKeywordNode$1(node) { + return node.type === "value-word" && ["and", "or", "not"].includes(node.value); +} + +function isEachKeywordNode$1(node) { + return node.type === "value-word" && node.value === "in"; +} + +function isMultiplicationNode$1(node) { + return node.type === "value-operator" && node.value === "*"; +} + +function isDivisionNode$1(node) { + return node.type === "value-operator" && node.value === "/"; +} + +function isAdditionNode$1(node) { + return node.type === "value-operator" && node.value === "+"; +} + +function isSubtractionNode$1(node) { + return node.type === "value-operator" && node.value === "-"; +} + +function isModuloNode(node) { + return node.type === "value-operator" && node.value === "%"; +} + +function isMathOperatorNode$1(node) { + return isMultiplicationNode$1(node) || isDivisionNode$1(node) || isAdditionNode$1(node) || isSubtractionNode$1(node) || isModuloNode(node); +} + +function isEqualityOperatorNode$1(node) { + return node.type === "value-word" && ["==", "!="].includes(node.value); +} + +function isRelationalOperatorNode$1(node) { + return node.type === "value-word" && ["<", ">", "<=", ">="].includes(node.value); +} + +function isSCSSControlDirectiveNode$1(node) { + return node.type === "css-atrule" && ["if", "else", "for", "each", "while"].includes(node.name); +} + +function isSCSSNestedPropertyNode(node) { + /* istanbul ignore next */ + if (!node.selector) { + return false; + } + + return node.selector.replace(/\/\*.*?\*\//, "").replace(/\/\/.*?\n/, "").trim().endsWith(":"); +} + +function isDetachedRulesetCallNode$1(node) { + return node.raws && node.raws.params && /^\(\s*\)$/.test(node.raws.params); +} + +function isTemplatePlaceholderNode$1(node) { + return node.name.startsWith("prettier-placeholder"); +} + +function isTemplatePropNode$1(node) { + return node.prop.startsWith("@prettier-placeholder"); +} + +function isPostcssSimpleVarNode$1(currentNode, nextNode) { + return currentNode.value === "$$" && currentNode.type === "value-func" && nextNode && nextNode.type === "value-word" && !nextNode.raws.before; +} + +function hasComposesNode$1(node) { + return node.value && node.value.type === "value-root" && node.value.group && node.value.group.type === "value-value" && node.prop.toLowerCase() === "composes"; +} + +function hasParensAroundNode$1(node) { + return node.value && node.value.group && node.value.group.group && node.value.group.group.type === "value-paren_group" && node.value.group.group.open !== null && node.value.group.group.close !== null; +} + +function hasEmptyRawBefore$1(node) { + return node.raws && node.raws.before === ""; +} + +function isKeyValuePairNode$1(node) { + return node.type === "value-comma_group" && node.groups && node.groups[1] && node.groups[1].type === "value-colon"; +} + +function isKeyValuePairInParenGroupNode(node) { + return node.type === "value-paren_group" && node.groups && node.groups[0] && isKeyValuePairNode$1(node.groups[0]); +} + +function isSCSSMapItemNode$1(path) { + const node = path.getValue(); // Ignore empty item (i.e. `$key: ()`) + + if (node.groups.length === 0) { + return false; + } + + const parentParentNode = path.getParentNode(1); // Check open parens contain key/value pair (i.e. `(key: value)` and `(key: (value, other-value)`) + + if (!isKeyValuePairInParenGroupNode(node) && !(parentParentNode && isKeyValuePairInParenGroupNode(parentParentNode))) { + return false; + } + + const declNode = getAncestorNode$2(path, "css-decl"); // SCSS map declaration (i.e. `$map: (key: value, other-key: other-value)`) + + if (declNode && declNode.prop && declNode.prop.startsWith("$")) { + return true; + } // List as value of key inside SCSS map (i.e. `$map: (key: (value other-value other-other-value))`) + + + if (isKeyValuePairInParenGroupNode(parentParentNode)) { + return true; + } // SCSS Map is argument of function (i.e. `func((key: value, other-key: other-value))`) + + + if (parentParentNode.type === "value-func") { + return true; + } + + return false; +} + +function isInlineValueCommentNode$1(node) { + return node.type === "value-comment" && node.inline; +} + +function isHashNode$1(node) { + return node.type === "value-word" && node.value === "#"; +} + +function isLeftCurlyBraceNode$1(node) { + return node.type === "value-word" && node.value === "{"; +} + +function isRightCurlyBraceNode$1(node) { + return node.type === "value-word" && node.value === "}"; +} + +function isWordNode$1(node) { + return ["value-word", "value-atword"].includes(node.type); +} + +function isColonNode$1(node) { + return node && node.type === "value-colon"; +} + +function isKeyInValuePairNode$1(node, parentNode) { + if (!isKeyValuePairNode$1(parentNode)) { + return false; + } + + const { + groups + } = parentNode; + const index = groups.indexOf(node); + + if (index === -1) { + return false; + } + + return isColonNode$1(groups[index + 1]); +} + +function isMediaAndSupportsKeywords$1(node) { + return node.value && ["not", "and", "or"].includes(node.value.toLowerCase()); +} + +function isColorAdjusterFuncNode$1(node) { + if (node.type !== "value-func") { + return false; + } + + return colorAdjusterFunctions.has(node.value.toLowerCase()); +} // TODO: only check `less` when we don't use `less` to parse `css` + + +function isLessParser$1(options) { + return options.parser === "css" || options.parser === "less"; +} + +function lastLineHasInlineComment$1(text) { + return /\/\//.test(text.split(/[\n\r]/).pop()); +} + +function stringifyNode(node) { + if (node.groups) { + const open = node.open && node.open.value ? node.open.value : ""; + const groups = node.groups.reduce((previousValue, currentValue, index) => previousValue + stringifyNode(currentValue) + (node.groups[0].type === "comma_group" && index !== node.groups.length - 1 ? "," : ""), ""); + const close = node.close && node.close.value ? node.close.value : ""; + return open + groups + close; + } + + const before = node.raws && node.raws.before ? node.raws.before : ""; + const quote = node.raws && node.raws.quote ? node.raws.quote : ""; + const atword = node.type === "atword" ? "@" : ""; + const value = node.value ? node.value : ""; + const unit = node.unit ? node.unit : ""; + const group = node.group ? stringifyNode(node.group) : ""; + const after = node.raws && node.raws.after ? node.raws.after : ""; + return before + quote + atword + value + quote + unit + group + after; +} + +function isAtWordPlaceholderNode$1(node) { + return node && node.type === "value-atword" && node.value.startsWith("prettier-placeholder-"); +} + +var utils$4 = { + getAncestorCounter: getAncestorCounter$1, + getAncestorNode: getAncestorNode$2, + getPropOfDeclNode: getPropOfDeclNode$1, + hasSCSSInterpolation, + hasStringOrFunction, + maybeToLowerCase: maybeToLowerCase$1, + insideValueFunctionNode: insideValueFunctionNode$1, + insideICSSRuleNode: insideICSSRuleNode$1, + insideAtRuleNode: insideAtRuleNode$1, + insideURLFunctionInImportAtRuleNode: insideURLFunctionInImportAtRuleNode$1, + isKeyframeAtRuleKeywords: isKeyframeAtRuleKeywords$1, + isWideKeywords: isWideKeywords$1, + isSCSS: isSCSS$1, + isSCSSVariable, + isLastNode: isLastNode$1, + isLessParser: isLessParser$1, + isSCSSControlDirectiveNode: isSCSSControlDirectiveNode$1, + isDetachedRulesetDeclarationNode: isDetachedRulesetDeclarationNode$1, + isRelationalOperatorNode: isRelationalOperatorNode$1, + isEqualityOperatorNode: isEqualityOperatorNode$1, + isMultiplicationNode: isMultiplicationNode$1, + isDivisionNode: isDivisionNode$1, + isAdditionNode: isAdditionNode$1, + isSubtractionNode: isSubtractionNode$1, + isModuloNode, + isMathOperatorNode: isMathOperatorNode$1, + isEachKeywordNode: isEachKeywordNode$1, + isForKeywordNode: isForKeywordNode$1, + isURLFunctionNode: isURLFunctionNode$1, + isIfElseKeywordNode: isIfElseKeywordNode$1, + hasComposesNode: hasComposesNode$1, + hasParensAroundNode: hasParensAroundNode$1, + hasEmptyRawBefore: hasEmptyRawBefore$1, + isSCSSNestedPropertyNode, + isDetachedRulesetCallNode: isDetachedRulesetCallNode$1, + isTemplatePlaceholderNode: isTemplatePlaceholderNode$1, + isTemplatePropNode: isTemplatePropNode$1, + isPostcssSimpleVarNode: isPostcssSimpleVarNode$1, + isKeyValuePairNode: isKeyValuePairNode$1, + isKeyValuePairInParenGroupNode, + isKeyInValuePairNode: isKeyInValuePairNode$1, + isSCSSMapItemNode: isSCSSMapItemNode$1, + isInlineValueCommentNode: isInlineValueCommentNode$1, + isHashNode: isHashNode$1, + isLeftCurlyBraceNode: isLeftCurlyBraceNode$1, + isRightCurlyBraceNode: isRightCurlyBraceNode$1, + isWordNode: isWordNode$1, + isColonNode: isColonNode$1, + isMediaAndSupportsKeywords: isMediaAndSupportsKeywords$1, + isColorAdjusterFuncNode: isColorAdjusterFuncNode$1, + lastLineHasInlineComment: lastLineHasInlineComment$1, + stringifyNode, + isAtWordPlaceholderNode: isAtWordPlaceholderNode$1 +}; + +var lineColumnToIndex = function (lineColumn, text) { + let index = 0; + + for (let i = 0; i < lineColumn.line - 1; ++i) { + index = text.indexOf("\n", index) + 1; + } + + return index + lineColumn.column; +}; + +const { + getLast: getLast$4, + skipEverythingButNewLine +} = util$5; + +function calculateLocStart(node, text) { + // value-* nodes have this + if (typeof node.sourceIndex === "number") { + return node.sourceIndex; + } + + return node.source ? lineColumnToIndex(node.source.start, text) - 1 : null; +} + +function calculateLocEnd(node, text) { + if (node.type === "css-comment" && node.inline) { + return skipEverythingButNewLine(text, node.source.startOffset); + } + + const endNode = node.nodes && getLast$4(node.nodes); + + if (endNode && node.source && !node.source.end) { + node = endNode; + } + + if (node.source && node.source.end) { + return lineColumnToIndex(node.source.end, text); + } + + return null; +} + +function calculateLoc(node, text) { + if (node.source) { + node.source.startOffset = calculateLocStart(node, text); + node.source.endOffset = calculateLocEnd(node, text); + } + + for (const key in node) { + const child = node[key]; + + if (key === "source" || !child || typeof child !== "object") { + continue; + } + + if (child.type === "value-root" || child.type === "value-unknown") { + calculateValueNodeLoc(child, getValueRootOffset(node), child.text || child.value); + } else { + calculateLoc(child, text); + } + } +} + +function calculateValueNodeLoc(node, rootOffset, text) { + if (node.source) { + node.source.startOffset = calculateLocStart(node, text) + rootOffset; + node.source.endOffset = calculateLocEnd(node, text) + rootOffset; + } + + for (const key in node) { + const child = node[key]; + + if (key === "source" || !child || typeof child !== "object") { + continue; + } + + calculateValueNodeLoc(child, rootOffset, text); + } +} + +function getValueRootOffset(node) { + let result = node.source.startOffset; + + if (typeof node.prop === "string") { + result += node.prop.length; + } + + if (node.type === "css-atrule" && typeof node.name === "string") { + result += 1 + node.name.length + node.raws.afterName.match(/^\s*:?\s*/)[0].length; + } + + if (node.type !== "css-atrule" && node.raws && typeof node.raws.between === "string") { + result += node.raws.between.length; + } + + return result; +} +/** + * Workaround for a bug: quotes and asterisks in inline comments corrupt loc data of subsequent nodes. + * This function replaces the quotes and asterisks with spaces. Later, when the comments are printed, + * their content is extracted from the original text. + * - https://github.com/prettier/prettier/issues/7780 + * - https://github.com/shellscape/postcss-less/issues/145 + * - https://github.com/prettier/prettier/issues/8130 + * @param text {string} + */ + + +function replaceQuotesInInlineComments(text) { + /** @typedef { 'initial' | 'single-quotes' | 'double-quotes' | 'url' | 'comment-block' | 'comment-inline' } State */ + + /** @type {State} */ + let state = "initial"; + /** @type {State} */ + + let stateToReturnFromQuotes = "initial"; + let inlineCommentStartIndex; + let inlineCommentContainsQuotes = false; + const inlineCommentsToReplace = []; + + for (let i = 0; i < text.length; i++) { + const c = text[i]; + + switch (state) { + case "initial": + if (c === "'") { + state = "single-quotes"; + continue; + } + + if (c === '"') { + state = "double-quotes"; + continue; + } + + if ((c === "u" || c === "U") && text.slice(i, i + 4).toLowerCase() === "url(") { + state = "url"; + i += 3; + continue; + } + + if (c === "*" && text[i - 1] === "/") { + state = "comment-block"; + continue; + } + + if (c === "/" && text[i - 1] === "/") { + state = "comment-inline"; + inlineCommentStartIndex = i - 1; + continue; + } + + continue; + + case "single-quotes": + if (c === "'" && text[i - 1] !== "\\") { + state = stateToReturnFromQuotes; + stateToReturnFromQuotes = "initial"; + } + + if (c === "\n" || c === "\r") { + return text; // invalid input + } + + continue; + + case "double-quotes": + if (c === '"' && text[i - 1] !== "\\") { + state = stateToReturnFromQuotes; + stateToReturnFromQuotes = "initial"; + } + + if (c === "\n" || c === "\r") { + return text; // invalid input + } + + continue; + + case "url": + if (c === ")") { + state = "initial"; + } + + if (c === "\n" || c === "\r") { + return text; // invalid input + } + + if (c === "'") { + state = "single-quotes"; + stateToReturnFromQuotes = "url"; + continue; + } + + if (c === '"') { + state = "double-quotes"; + stateToReturnFromQuotes = "url"; + continue; + } + + continue; + + case "comment-block": + if (c === "/" && text[i - 1] === "*") { + state = "initial"; + } + + continue; + + case "comment-inline": + if (c === '"' || c === "'" || c === "*") { + inlineCommentContainsQuotes = true; + } + + if (c === "\n" || c === "\r") { + if (inlineCommentContainsQuotes) { + inlineCommentsToReplace.push([inlineCommentStartIndex, i]); + } + + state = "initial"; + inlineCommentContainsQuotes = false; + } + + continue; + } + } + + for (const [start, end] of inlineCommentsToReplace) { + text = text.slice(0, start) + text.slice(start, end).replace(/["'*]/g, " ") + text.slice(end); + } + + return text; +} + +function locStart$c(node) { + return node.source.startOffset; +} + +function locEnd$b(node) { + return node.source.endOffset; +} + +var loc$5 = { + locStart: locStart$c, + locEnd: locEnd$b, + calculateLoc, + replaceQuotesInInlineComments +}; + +const { + printNumber, + printString, + hasNewline, + isFrontMatterNode: isFrontMatterNode$3, + isNextLineEmpty: isNextLineEmpty$3, + isNonEmptyArray: isNonEmptyArray$5 +} = util$5; +const { + builders: { + join: join$9, + line: line$9, + hardline: hardline$9, + softline: softline$7, + group: group$9, + fill: fill$5, + indent: indent$5, + dedent: dedent$2, + ifBreak: ifBreak$7, + breakParent: breakParent$3 + }, + utils: { + removeLines, + getDocParts: getDocParts$4 + } +} = doc; +const { + insertPragma: insertPragma$7 +} = pragma$4; +const { + getAncestorNode: getAncestorNode$1, + getPropOfDeclNode, + maybeToLowerCase, + insideValueFunctionNode, + insideICSSRuleNode, + insideAtRuleNode, + insideURLFunctionInImportAtRuleNode, + isKeyframeAtRuleKeywords, + isWideKeywords, + isSCSS, + isLastNode, + isLessParser, + isSCSSControlDirectiveNode, + isDetachedRulesetDeclarationNode, + isRelationalOperatorNode, + isEqualityOperatorNode, + isMultiplicationNode, + isDivisionNode, + isAdditionNode, + isSubtractionNode, + isMathOperatorNode, + isEachKeywordNode, + isForKeywordNode, + isURLFunctionNode, + isIfElseKeywordNode, + hasComposesNode, + hasParensAroundNode, + hasEmptyRawBefore, + isKeyValuePairNode, + isKeyInValuePairNode, + isDetachedRulesetCallNode, + isTemplatePlaceholderNode, + isTemplatePropNode, + isPostcssSimpleVarNode, + isSCSSMapItemNode, + isInlineValueCommentNode, + isHashNode, + isLeftCurlyBraceNode, + isRightCurlyBraceNode, + isWordNode, + isColonNode, + isMediaAndSupportsKeywords, + isColorAdjusterFuncNode, + lastLineHasInlineComment, + isAtWordPlaceholderNode +} = utils$4; +const { + locStart: locStart$b, + locEnd: locEnd$a +} = loc$5; + +function shouldPrintComma(options) { + return options.trailingComma === "es5" || options.trailingComma === "all"; +} + +function genericPrint$4(path, options, print) { + const node = path.getValue(); + /* istanbul ignore if */ + + if (!node) { + return ""; + } + + if (typeof node === "string") { + return node; + } + + switch (node.type) { + case "front-matter": + return [node.raw, hardline$9]; + + case "css-root": + { + const nodes = printNodeSequence(path, options, print); + const after = node.raws.after.trim(); + return [nodes, after ? ` ${after}` : "", getDocParts$4(nodes).length > 0 ? hardline$9 : ""]; + } + + case "css-comment": + { + const isInlineComment = node.inline || node.raws.inline; + const text = options.originalText.slice(locStart$b(node), locEnd$a(node)); + return isInlineComment ? text.trimEnd() : text; + } + + case "css-rule": + { + return [print("selector"), node.important ? " !important" : "", node.nodes ? [node.selector && node.selector.type === "selector-unknown" && lastLineHasInlineComment(node.selector.value) ? line$9 : " ", "{", node.nodes.length > 0 ? indent$5([hardline$9, printNodeSequence(path, options, print)]) : "", hardline$9, "}", isDetachedRulesetDeclarationNode(node) ? ";" : ""] : ";"]; + } + + case "css-decl": + { + const parentNode = path.getParentNode(); + const { + between: rawBetween + } = node.raws; + const trimmedBetween = rawBetween.trim(); + const isColon = trimmedBetween === ":"; + let value = hasComposesNode(node) ? removeLines(print("value")) : print("value"); + + if (!isColon && lastLineHasInlineComment(trimmedBetween)) { + value = indent$5([hardline$9, dedent$2(value)]); + } + + return [node.raws.before.replace(/[\s;]/g, ""), insideICSSRuleNode(path) ? node.prop : maybeToLowerCase(node.prop), trimmedBetween.startsWith("//") ? " " : "", trimmedBetween, node.extend ? "" : " ", isLessParser(options) && node.extend && node.selector ? ["extend(", print("selector"), ")"] : "", value, node.raws.important ? node.raws.important.replace(/\s*!\s*important/i, " !important") : node.important ? " !important" : "", node.raws.scssDefault ? node.raws.scssDefault.replace(/\s*!default/i, " !default") : node.scssDefault ? " !default" : "", node.raws.scssGlobal ? node.raws.scssGlobal.replace(/\s*!global/i, " !global") : node.scssGlobal ? " !global" : "", node.nodes ? [" {", indent$5([softline$7, printNodeSequence(path, options, print)]), softline$7, "}"] : isTemplatePropNode(node) && !parentNode.raws.semicolon && options.originalText[locEnd$a(node) - 1] !== ";" ? "" : options.__isHTMLStyleAttribute && isLastNode(path, node) ? ifBreak$7(";") : ";"]; + } + + case "css-atrule": + { + const parentNode = path.getParentNode(); + const isTemplatePlaceholderNodeWithoutSemiColon = isTemplatePlaceholderNode(node) && !parentNode.raws.semicolon && options.originalText[locEnd$a(node) - 1] !== ";"; + + if (isLessParser(options)) { + if (node.mixin) { + return [print("selector"), node.important ? " !important" : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]; + } + + if (node.function) { + return [node.name, print("params"), isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]; + } + + if (node.variable) { + return ["@", node.name, ": ", node.value ? print("value") : "", node.raws.between.trim() ? node.raws.between.trim() + " " : "", node.nodes ? ["{", indent$5([node.nodes.length > 0 ? softline$7 : "", printNodeSequence(path, options, print)]), softline$7, "}"] : "", isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]; + } + } + + return ["@", // If a Less file ends up being parsed with the SCSS parser, Less + // variable declarations will be parsed as at-rules with names ending + // with a colon, so keep the original case then. + isDetachedRulesetCallNode(node) || node.name.endsWith(":") ? node.name : maybeToLowerCase(node.name), node.params ? [isDetachedRulesetCallNode(node) ? "" : isTemplatePlaceholderNode(node) ? node.raws.afterName === "" ? "" : node.name.endsWith(":") ? " " : /^\s*\n\s*\n/.test(node.raws.afterName) ? [hardline$9, hardline$9] : /^\s*\n/.test(node.raws.afterName) ? hardline$9 : " " : " ", print("params")] : "", node.selector ? indent$5([" ", print("selector")]) : "", node.value ? group$9([" ", print("value"), isSCSSControlDirectiveNode(node) ? hasParensAroundNode(node) ? " " : line$9 : ""]) : node.name === "else" ? " " : "", node.nodes ? [isSCSSControlDirectiveNode(node) ? "" : node.selector && !node.selector.nodes && typeof node.selector.value === "string" && lastLineHasInlineComment(node.selector.value) || !node.selector && typeof node.params === "string" && lastLineHasInlineComment(node.params) ? line$9 : " ", "{", indent$5([node.nodes.length > 0 ? softline$7 : "", printNodeSequence(path, options, print)]), softline$7, "}"] : isTemplatePlaceholderNodeWithoutSemiColon ? "" : ";"]; + } + // postcss-media-query-parser + + case "media-query-list": + { + const parts = []; + path.each(childPath => { + const node = childPath.getValue(); + + if (node.type === "media-query" && node.value === "") { + return; + } + + parts.push(print()); + }, "nodes"); + return group$9(indent$5(join$9(line$9, parts))); + } + + case "media-query": + { + return [join$9(" ", path.map(print, "nodes")), isLastNode(path, node) ? "" : ","]; + } + + case "media-type": + { + return adjustNumbers(adjustStrings(node.value, options)); + } + + case "media-feature-expression": + { + if (!node.nodes) { + return node.value; + } + + return ["(", ...path.map(print, "nodes"), ")"]; + } + + case "media-feature": + { + return maybeToLowerCase(adjustStrings(node.value.replace(/ +/g, " "), options)); + } + + case "media-colon": + { + return [node.value, " "]; + } + + case "media-value": + { + return adjustNumbers(adjustStrings(node.value, options)); + } + + case "media-keyword": + { + return adjustStrings(node.value, options); + } + + case "media-url": + { + return adjustStrings(node.value.replace(/^url\(\s+/gi, "url(").replace(/\s+\)$/g, ")"), options); + } + + case "media-unknown": + { + return node.value; + } + // postcss-selector-parser + + case "selector-root": + { + return group$9([insideAtRuleNode(path, "custom-selector") ? [getAncestorNode$1(path, "css-atrule").customSelector, line$9] : "", join$9([",", insideAtRuleNode(path, ["extend", "custom-selector", "nest"]) ? line$9 : hardline$9], path.map(print, "nodes"))]); + } + + case "selector-selector": + { + return group$9(indent$5(path.map(print, "nodes"))); + } + + case "selector-comment": + { + return node.value; + } + + case "selector-string": + { + return adjustStrings(node.value, options); + } + + case "selector-tag": + { + const parentNode = path.getParentNode(); + const index = parentNode && parentNode.nodes.indexOf(node); + const prevNode = index && parentNode.nodes[index - 1]; + return [node.namespace ? [node.namespace === true ? "" : node.namespace.trim(), "|"] : "", prevNode.type === "selector-nesting" ? node.value : adjustNumbers(isKeyframeAtRuleKeywords(path, node.value) ? node.value.toLowerCase() : node.value)]; + } + + case "selector-id": + { + return ["#", node.value]; + } + + case "selector-class": + { + return [".", adjustNumbers(adjustStrings(node.value, options))]; + } + + case "selector-attribute": + { + return ["[", node.namespace ? [node.namespace === true ? "" : node.namespace.trim(), "|"] : "", node.attribute.trim(), node.operator ? node.operator : "", node.value ? quoteAttributeValue(adjustStrings(node.value.trim(), options), options) : "", node.insensitive ? " i" : "", "]"]; + } + + case "selector-combinator": + { + if (node.value === "+" || node.value === ">" || node.value === "~" || node.value === ">>>") { + const parentNode = path.getParentNode(); + const leading = parentNode.type === "selector-selector" && parentNode.nodes[0] === node ? "" : line$9; + return [leading, node.value, isLastNode(path, node) ? "" : " "]; + } + + const leading = node.value.trim().startsWith("(") ? line$9 : ""; + const value = adjustNumbers(adjustStrings(node.value.trim(), options)) || line$9; + return [leading, value]; + } + + case "selector-universal": + { + return [node.namespace ? [node.namespace === true ? "" : node.namespace.trim(), "|"] : "", node.value]; + } + + case "selector-pseudo": + { + return [maybeToLowerCase(node.value), isNonEmptyArray$5(node.nodes) ? ["(", join$9(", ", path.map(print, "nodes")), ")"] : ""]; + } + + case "selector-nesting": + { + return node.value; + } + + case "selector-unknown": + { + const ruleAncestorNode = getAncestorNode$1(path, "css-rule"); // Nested SCSS property + + if (ruleAncestorNode && ruleAncestorNode.isSCSSNesterProperty) { + return adjustNumbers(adjustStrings(maybeToLowerCase(node.value), options)); + } // originalText has to be used for Less, see replaceQuotesInInlineComments in loc.js + + + const parentNode = path.getParentNode(); + + if (parentNode.raws && parentNode.raws.selector) { + const start = locStart$b(parentNode); + const end = start + parentNode.raws.selector.length; + return options.originalText.slice(start, end).trim(); + } // Same reason above + + + const grandParent = path.getParentNode(1); + + if (parentNode.type === "value-paren_group" && grandParent && grandParent.type === "value-func" && grandParent.value === "selector") { + const start = locStart$b(parentNode.open) + 1; + const end = locEnd$a(parentNode.close) - 1; + const selector = options.originalText.slice(start, end).trim(); + return lastLineHasInlineComment(selector) ? [breakParent$3, selector] : selector; + } + + return node.value; + } + // postcss-values-parser + + case "value-value": + case "value-root": + { + return print("group"); + } + + case "value-comment": + { + return options.originalText.slice(locStart$b(node), locEnd$a(node)); + } + + case "value-comma_group": + { + const parentNode = path.getParentNode(); + const parentParentNode = path.getParentNode(1); + const declAncestorProp = getPropOfDeclNode(path); + const isGridValue = declAncestorProp && parentNode.type === "value-value" && (declAncestorProp === "grid" || declAncestorProp.startsWith("grid-template")); + const atRuleAncestorNode = getAncestorNode$1(path, "css-atrule"); + const isControlDirective = atRuleAncestorNode && isSCSSControlDirectiveNode(atRuleAncestorNode); + const hasInlineComment = node.groups.some(node => isInlineValueCommentNode(node)); + const printed = path.map(print, "groups"); + const parts = []; + const insideURLFunction = insideValueFunctionNode(path, "url"); + let insideSCSSInterpolationInString = false; + let didBreak = false; + + for (let i = 0; i < node.groups.length; ++i) { + parts.push(printed[i]); + const iPrevNode = node.groups[i - 1]; + const iNode = node.groups[i]; + const iNextNode = node.groups[i + 1]; + const iNextNextNode = node.groups[i + 2]; + + if (insideURLFunction) { + if (iNextNode && isAdditionNode(iNextNode) || isAdditionNode(iNode)) { + parts.push(" "); + } + + continue; + } // Ignore after latest node (i.e. before semicolon) + + + if (!iNextNode) { + continue; + } // styled.div` background: var(--${one}); ` + + + if (iNode.type === "value-word" && iNode.value.endsWith("-") && isAtWordPlaceholderNode(iNextNode)) { + continue; + } // Ignore spaces before/after string interpolation (i.e. `"#{my-fn("_")}"`) + + + const isStartSCSSInterpolationInString = iNode.type === "value-string" && iNode.value.startsWith("#{"); + const isEndingSCSSInterpolationInString = insideSCSSInterpolationInString && iNextNode.type === "value-string" && iNextNode.value.endsWith("}"); + + if (isStartSCSSInterpolationInString || isEndingSCSSInterpolationInString) { + insideSCSSInterpolationInString = !insideSCSSInterpolationInString; + continue; + } + + if (insideSCSSInterpolationInString) { + continue; + } // Ignore colon (i.e. `:`) + + + if (isColonNode(iNode) || isColonNode(iNextNode)) { + continue; + } // Ignore `@` in Less (i.e. `@@var;`) + + + if (iNode.type === "value-atword" && iNode.value === "") { + continue; + } // Ignore `~` in Less (i.e. `content: ~"^//* some horrible but needed css hack";`) + + + if (iNode.value === "~") { + continue; + } // Ignore escape `\` + + + if (iNode.value && iNode.value.includes("\\") && iNextNode && iNextNode.type !== "value-comment") { + continue; + } // Ignore escaped `/` + + + if (iPrevNode && iPrevNode.value && iPrevNode.value.indexOf("\\") === iPrevNode.value.length - 1 && iNode.type === "value-operator" && iNode.value === "/") { + continue; + } // Ignore `\` (i.e. `$variable: \@small;`) + + + if (iNode.value === "\\") { + continue; + } // Ignore `$$` (i.e. `background-color: $$(style)Color;`) + + + if (isPostcssSimpleVarNode(iNode, iNextNode)) { + continue; + } // Ignore spaces after `#` and after `{` and before `}` in SCSS interpolation (i.e. `#{variable}`) + + + if (isHashNode(iNode) || isLeftCurlyBraceNode(iNode) || isRightCurlyBraceNode(iNextNode) || isLeftCurlyBraceNode(iNextNode) && hasEmptyRawBefore(iNextNode) || isRightCurlyBraceNode(iNode) && hasEmptyRawBefore(iNextNode)) { + continue; + } // Ignore css variables and interpolation in SCSS (i.e. `--#{$var}`) + + + if (iNode.value === "--" && isHashNode(iNextNode)) { + continue; + } // Formatting math operations + + + const isMathOperator = isMathOperatorNode(iNode); + const isNextMathOperator = isMathOperatorNode(iNextNode); // Print spaces before and after math operators beside SCSS interpolation as is + // (i.e. `#{$var}+5`, `#{$var} +5`, `#{$var}+ 5`, `#{$var} + 5`) + // (i.e. `5+#{$var}`, `5 +#{$var}`, `5+ #{$var}`, `5 + #{$var}`) + + if ((isMathOperator && isHashNode(iNextNode) || isNextMathOperator && isRightCurlyBraceNode(iNode)) && hasEmptyRawBefore(iNextNode)) { + continue; + } // absolute paths are only parsed as one token if they are part of url(/abs/path) call + // but if you have custom -fb-url(/abs/path/) then it is parsed as "division /" and rest + // of the path. We don't want to put a space after that first division in this case. + + + if (!iPrevNode && isDivisionNode(iNode)) { + continue; + } // Print spaces before and after addition and subtraction math operators as is in `calc` function + // due to the fact that it is not valid syntax + // (i.e. `calc(1px+1px)`, `calc(1px+ 1px)`, `calc(1px +1px)`, `calc(1px + 1px)`) + + + if (insideValueFunctionNode(path, "calc") && (isAdditionNode(iNode) || isAdditionNode(iNextNode) || isSubtractionNode(iNode) || isSubtractionNode(iNextNode)) && hasEmptyRawBefore(iNextNode)) { + continue; + } // Print spaces after `+` and `-` in color adjuster functions as is (e.g. `color(red l(+ 20%))`) + // Adjusters with signed numbers (e.g. `color(red l(+20%))`) output as-is. + + + const isColorAdjusterNode = (isAdditionNode(iNode) || isSubtractionNode(iNode)) && i === 0 && (iNextNode.type === "value-number" || iNextNode.isHex) && parentParentNode && isColorAdjusterFuncNode(parentParentNode) && !hasEmptyRawBefore(iNextNode); + const requireSpaceBeforeOperator = iNextNextNode && iNextNextNode.type === "value-func" || iNextNextNode && isWordNode(iNextNextNode) || iNode.type === "value-func" || isWordNode(iNode); + const requireSpaceAfterOperator = iNextNode.type === "value-func" || isWordNode(iNextNode) || iPrevNode && iPrevNode.type === "value-func" || iPrevNode && isWordNode(iPrevNode); // Formatting `/`, `+`, `-` sign + + if (!(isMultiplicationNode(iNextNode) || isMultiplicationNode(iNode)) && !insideValueFunctionNode(path, "calc") && !isColorAdjusterNode && (isDivisionNode(iNextNode) && !requireSpaceBeforeOperator || isDivisionNode(iNode) && !requireSpaceAfterOperator || isAdditionNode(iNextNode) && !requireSpaceBeforeOperator || isAdditionNode(iNode) && !requireSpaceAfterOperator || isSubtractionNode(iNextNode) || isSubtractionNode(iNode)) && (hasEmptyRawBefore(iNextNode) || isMathOperator && (!iPrevNode || iPrevNode && isMathOperatorNode(iPrevNode)))) { + continue; + } // Add `hardline` after inline comment (i.e. `// comment\n foo: bar;`) + + + if (isInlineValueCommentNode(iNode)) { + if (parentNode.type === "value-paren_group") { + parts.push(dedent$2(hardline$9)); + continue; + } + + parts.push(hardline$9); + continue; + } // Handle keywords in SCSS control directive + + + if (isControlDirective && (isEqualityOperatorNode(iNextNode) || isRelationalOperatorNode(iNextNode) || isIfElseKeywordNode(iNextNode) || isEachKeywordNode(iNode) || isForKeywordNode(iNode))) { + parts.push(" "); + continue; + } // At-rule `namespace` should be in one line + + + if (atRuleAncestorNode && atRuleAncestorNode.name.toLowerCase() === "namespace") { + parts.push(" "); + continue; + } // Formatting `grid` property + + + if (isGridValue) { + if (iNode.source && iNextNode.source && iNode.source.start.line !== iNextNode.source.start.line) { + parts.push(hardline$9); + didBreak = true; + } else { + parts.push(" "); + } + + continue; + } // Add `space` before next math operation + // Note: `grip` property have `/` delimiter and it is not math operation, so + // `grid` property handles above + + + if (isNextMathOperator) { + parts.push(" "); + continue; + } // allow function(returns-list($list)...) + + + if (iNextNode && iNextNode.value === "...") { + continue; + } + + if (isAtWordPlaceholderNode(iNode) && isAtWordPlaceholderNode(iNextNode) && locEnd$a(iNode) === locStart$b(iNextNode)) { + continue; + } // Be default all values go through `line` + + + parts.push(line$9); + } + + if (hasInlineComment) { + parts.push(breakParent$3); + } + + if (didBreak) { + parts.unshift(hardline$9); + } + + if (isControlDirective) { + return group$9(indent$5(parts)); + } // Indent is not needed for import url when url is very long + // and node has two groups + // when type is value-comma_group + // example @import url("verylongurl") projection,tv + + + if (insideURLFunctionInImportAtRuleNode(path)) { + return group$9(fill$5(parts)); + } + + return group$9(indent$5(fill$5(parts))); + } + + case "value-paren_group": + { + const parentNode = path.getParentNode(); + + if (parentNode && isURLFunctionNode(parentNode) && (node.groups.length === 1 || node.groups.length > 0 && node.groups[0].type === "value-comma_group" && node.groups[0].groups.length > 0 && node.groups[0].groups[0].type === "value-word" && node.groups[0].groups[0].value.startsWith("data:"))) { + return [node.open ? print("open") : "", join$9(",", path.map(print, "groups")), node.close ? print("close") : ""]; + } + + if (!node.open) { + const printed = path.map(print, "groups"); + const res = []; + + for (let i = 0; i < printed.length; i++) { + if (i !== 0) { + res.push([",", line$9]); + } + + res.push(printed[i]); + } + + return group$9(indent$5(fill$5(res))); + } + + const isSCSSMapItem = isSCSSMapItemNode(path); + const lastItem = getLast_1(node.groups); + const isLastItemComment = lastItem && lastItem.type === "value-comment"; + const isKey = isKeyInValuePairNode(node, parentNode); + const printed = group$9([node.open ? print("open") : "", indent$5([softline$7, join$9([",", line$9], path.map(childPath => { + const node = childPath.getValue(); + const printed = print(); // Key/Value pair in open paren already indented + + if (isKeyValuePairNode(node) && node.type === "value-comma_group" && node.groups && node.groups[0].type !== "value-paren_group" && node.groups[2] && node.groups[2].type === "value-paren_group") { + const parts = getDocParts$4(printed.contents.contents); + parts[1] = group$9(parts[1]); + return group$9(dedent$2(printed)); + } + + return printed; + }, "groups"))]), ifBreak$7(!isLastItemComment && isSCSS(options.parser, options.originalText) && isSCSSMapItem && shouldPrintComma(options) ? "," : ""), softline$7, node.close ? print("close") : ""], { + shouldBreak: isSCSSMapItem && !isKey + }); + return isKey ? dedent$2(printed) : printed; + } + + case "value-func": + { + return [node.value, insideAtRuleNode(path, "supports") && isMediaAndSupportsKeywords(node) ? " " : "", print("group")]; + } + + case "value-paren": + { + return node.value; + } + + case "value-number": + { + return [printCssNumber(node.value), maybeToLowerCase(node.unit)]; + } + + case "value-operator": + { + return node.value; + } + + case "value-word": + { + if (node.isColor && node.isHex || isWideKeywords(node.value)) { + return node.value.toLowerCase(); + } + + return node.value; + } + + case "value-colon": + { + const parentNode = path.getParentNode(); + const index = parentNode && parentNode.groups.indexOf(node); + const prevNode = index && parentNode.groups[index - 1]; + return [node.value, // Don't add spaces on escaped colon `:`, e.g: grid-template-rows: [row-1-00\:00] auto; + prevNode && typeof prevNode.value === "string" && getLast_1(prevNode.value) === "\\" || // Don't add spaces on `:` in `url` function (i.e. `url(fbglyph: cross-outline, fig-white)`) + insideValueFunctionNode(path, "url") ? "" : line$9]; + } + // TODO: confirm this code is dead + + /* istanbul ignore next */ + + case "value-comma": + { + return [node.value, " "]; + } + + case "value-string": + { + return printString(node.raws.quote + node.value + node.raws.quote, options); + } + + case "value-atword": + { + return ["@", node.value]; + } + + case "value-unicode-range": + { + return node.value; + } + + case "value-unknown": + { + return node.value; + } + + default: + /* istanbul ignore next */ + throw new Error(`Unknown postcss type ${JSON.stringify(node.type)}`); + } +} + +function printNodeSequence(path, options, print) { + const parts = []; + path.each((pathChild, i, nodes) => { + const prevNode = nodes[i - 1]; + + if (prevNode && prevNode.type === "css-comment" && prevNode.text.trim() === "prettier-ignore") { + const childNode = pathChild.getValue(); + parts.push(options.originalText.slice(locStart$b(childNode), locEnd$a(childNode))); + } else { + parts.push(print()); + } + + if (i !== nodes.length - 1) { + if (nodes[i + 1].type === "css-comment" && !hasNewline(options.originalText, locStart$b(nodes[i + 1]), { + backwards: true + }) && !isFrontMatterNode$3(nodes[i]) || nodes[i + 1].type === "css-atrule" && nodes[i + 1].name === "else" && nodes[i].type !== "css-comment") { + parts.push(" "); + } else { + parts.push(options.__isHTMLStyleAttribute ? line$9 : hardline$9); + + if (isNextLineEmpty$3(options.originalText, pathChild.getValue(), locEnd$a) && !isFrontMatterNode$3(nodes[i])) { + parts.push(hardline$9); + } + } + } + }, "nodes"); + return parts; +} + +const STRING_REGEX = /(["'])(?:(?!\1)[^\\]|\\.)*\1/gs; +const NUMBER_REGEX = /(?:\d*\.\d+|\d+\.?)(?:[Ee][+-]?\d+)?/g; +const STANDARD_UNIT_REGEX = /[A-Za-z]+/g; +const WORD_PART_REGEX = /[$@]?[A-Z_a-z\u0080-\uFFFF][\w\u0080-\uFFFF-]*/g; +const ADJUST_NUMBERS_REGEX = new RegExp(STRING_REGEX.source + "|" + `(${WORD_PART_REGEX.source})?` + `(${NUMBER_REGEX.source})` + `(${STANDARD_UNIT_REGEX.source})?`, "g"); + +function adjustStrings(value, options) { + return value.replace(STRING_REGEX, match => printString(match, options)); +} + +function quoteAttributeValue(value, options) { + const quote = options.singleQuote ? "'" : '"'; + return value.includes('"') || value.includes("'") ? value : quote + value + quote; +} + +function adjustNumbers(value) { + return value.replace(ADJUST_NUMBERS_REGEX, (match, quote, wordPart, number, unit) => !wordPart && number ? printCssNumber(number) + maybeToLowerCase(unit || "") : match); +} + +function printCssNumber(rawNumber) { + return printNumber(rawNumber) // Remove trailing `.0`. + .replace(/\.0(?=$|e)/, ""); +} + +var printerPostcss = { + print: genericPrint$4, + embed: embed_1$2, + insertPragma: insertPragma$7, + massageAstNode: clean_1$3 +}; + +var options$4 = { + singleQuote: commonOptions.singleQuote +}; + +var name$9 = "CSS"; +var type$9 = "markup"; +var tmScope$9 = "source.css"; +var aceMode$9 = "css"; +var codemirrorMode$5 = "css"; +var codemirrorMimeType$5 = "text/css"; +var color$8 = "#563d7c"; +var extensions$9 = [ + ".css" +]; +var languageId$9 = 50; +var require$$0$5 = { + name: name$9, + type: type$9, + tmScope: tmScope$9, + aceMode: aceMode$9, + codemirrorMode: codemirrorMode$5, + codemirrorMimeType: codemirrorMimeType$5, + color: color$8, + extensions: extensions$9, + languageId: languageId$9 +}; + +var name$8 = "PostCSS"; +var type$8 = "markup"; +var tmScope$8 = "source.postcss"; +var group$8 = "CSS"; +var extensions$8 = [ + ".pcss", + ".postcss" +]; +var aceMode$8 = "text"; +var languageId$8 = 262764437; +var require$$1$2 = { + name: name$8, + type: type$8, + tmScope: tmScope$8, + group: group$8, + extensions: extensions$8, + aceMode: aceMode$8, + languageId: languageId$8 +}; + +var name$7 = "Less"; +var type$7 = "markup"; +var color$7 = "#1d365d"; +var extensions$7 = [ + ".less" +]; +var tmScope$7 = "source.css.less"; +var aceMode$7 = "less"; +var codemirrorMode$4 = "css"; +var codemirrorMimeType$4 = "text/css"; +var languageId$7 = 198; +var require$$2$1 = { + name: name$7, + type: type$7, + color: color$7, + extensions: extensions$7, + tmScope: tmScope$7, + aceMode: aceMode$7, + codemirrorMode: codemirrorMode$4, + codemirrorMimeType: codemirrorMimeType$4, + languageId: languageId$7 +}; + +var name$6 = "SCSS"; +var type$6 = "markup"; +var color$6 = "#c6538c"; +var tmScope$6 = "source.css.scss"; +var aceMode$6 = "scss"; +var codemirrorMode$3 = "css"; +var codemirrorMimeType$3 = "text/x-scss"; +var extensions$6 = [ + ".scss" +]; +var languageId$6 = 329; +var require$$3 = { + name: name$6, + type: type$6, + color: color$6, + tmScope: tmScope$6, + aceMode: aceMode$6, + codemirrorMode: codemirrorMode$3, + codemirrorMimeType: codemirrorMimeType$3, + extensions: extensions$6, + languageId: languageId$6 +}; + +const languages$6 = [createLanguage(require$$0$5, data => ({ + since: "1.4.0", + parsers: ["css"], + vscodeLanguageIds: ["css"], + extensions: [...data.extensions, // `WeiXin Style Sheets`(Weixin Mini Programs) + // https://developers.weixin.qq.com/miniprogram/en/dev/framework/view/wxs/ + ".wxss"] +})), createLanguage(require$$1$2, () => ({ + since: "1.4.0", + parsers: ["css"], + vscodeLanguageIds: ["postcss"] +})), createLanguage(require$$2$1, () => ({ + since: "1.4.0", + parsers: ["less"], + vscodeLanguageIds: ["less"] +})), createLanguage(require$$3, () => ({ + since: "1.4.0", + parsers: ["scss"], + vscodeLanguageIds: ["scss"] +}))]; +const printers$4 = { + postcss: printerPostcss +}; +const parsers$5 = { + // TODO: switch these to just `postcss` and use `language` instead. + get css() { + return require("./parser-postcss").parsers.css; + }, + + get less() { + return require("./parser-postcss").parsers.less; + }, + + get scss() { + return require("./parser-postcss").parsers.scss; + } + +}; +var languageCss = { + languages: languages$6, + options: options$4, + printers: printers$4, + parsers: parsers$5 +}; + +function locStart$a(node) { + return node.loc.start.offset; +} + +function locEnd$9(node) { + return node.loc.end.offset; +} + +var loc$4 = { + locStart: locStart$a, + locEnd: locEnd$9 +}; + +function clean$4(ast, newNode +/*, parent*/ +) { + // (Glimmer/HTML) ignore TextNode + if (ast.type === "TextNode") { + const trimmed = ast.chars.trim(); + + if (!trimmed) { + return null; + } + + newNode.chars = trimmed.replace(/[\t\n\f\r ]+/g, " "); + } // `class` is reformatted + + + if (ast.type === "AttrNode" && ast.name.toLowerCase() === "class") { + delete newNode.value; + } +} + +clean$4.ignoredProperties = new Set(["loc", "selfClosing"]); +var clean_1$2 = clean$4; + +var htmlVoidElements = [ + "area", + "base", + "basefont", + "bgsound", + "br", + "col", + "command", + "embed", + "frame", + "hr", + "image", + "img", + "input", + "isindex", + "keygen", + "link", + "menuitem", + "meta", + "nextid", + "param", + "source", + "track", + "wbr" +]; + +function isLastNodeOfSiblings$1(path) { + const node = path.getValue(); + const parentNode = path.getParentNode(0); + + if (isParentOfSomeType$1(path, ["ElementNode"]) && getLast_1(parentNode.children) === node) { + return true; + } + + if (isParentOfSomeType$1(path, ["Block"]) && getLast_1(parentNode.body) === node) { + return true; + } + + return false; +} + +function isUppercase(string) { + return string.toUpperCase() === string; +} + +function isGlimmerComponent(node) { + return isNodeOfSomeType$1(node, ["ElementNode"]) && typeof node.tag === "string" && (isUppercase(node.tag[0]) || node.tag.includes(".")); +} + +const voidTags = new Set(htmlVoidElements); + +function isVoid$1(node) { + return isGlimmerComponent(node) && node.children.every(node => isWhitespaceNode$1(node)) || voidTags.has(node.tag); +} + +function isWhitespaceNode$1(node) { + return isNodeOfSomeType$1(node, ["TextNode"]) && !/\S/.test(node.chars); +} + +function isNodeOfSomeType$1(node, types) { + return node && types.includes(node.type); +} + +function isParentOfSomeType$1(path, types) { + const parentNode = path.getParentNode(0); + return isNodeOfSomeType$1(parentNode, types); +} + +function isPreviousNodeOfSomeType$1(path, types) { + const previousNode = getPreviousNode$1(path); + return isNodeOfSomeType$1(previousNode, types); +} + +function isNextNodeOfSomeType$1(path, types) { + const nextNode = getNextNode$1(path); + return isNodeOfSomeType$1(nextNode, types); +} + +function getSiblingNode(path, offset) { + const node = path.getValue(); + const parentNode = path.getParentNode(0) || {}; + const children = parentNode.children || parentNode.body || parentNode.parts || []; + const index = children.indexOf(node); + return index !== -1 && children[index + offset]; +} + +function getPreviousNode$1(path, lookBack = 1) { + return getSiblingNode(path, -lookBack); +} + +function getNextNode$1(path) { + return getSiblingNode(path, 1); +} + +function isPrettierIgnoreNode(node) { + return isNodeOfSomeType$1(node, ["MustacheCommentStatement"]) && typeof node.value === "string" && node.value.trim() === "prettier-ignore"; +} + +function hasPrettierIgnore$7(path) { + const node = path.getValue(); + const previousPreviousNode = getPreviousNode$1(path, 2); + return isPrettierIgnoreNode(node) || isPrettierIgnoreNode(previousPreviousNode); +} + +var utils$3 = { + getNextNode: getNextNode$1, + getPreviousNode: getPreviousNode$1, + hasPrettierIgnore: hasPrettierIgnore$7, + isLastNodeOfSiblings: isLastNodeOfSiblings$1, + isNextNodeOfSomeType: isNextNodeOfSomeType$1, + isNodeOfSomeType: isNodeOfSomeType$1, + isParentOfSomeType: isParentOfSomeType$1, + isPreviousNodeOfSomeType: isPreviousNodeOfSomeType$1, + isVoid: isVoid$1, + isWhitespaceNode: isWhitespaceNode$1 +}; + +const { + builders: { + dedent: dedent$1, + fill: fill$4, + group: group$7, + hardline: hardline$8, + ifBreak: ifBreak$6, + indent: indent$4, + join: join$8, + line: line$8, + softline: softline$6, + literalline: literalline$4 + }, + utils: { + getDocParts: getDocParts$3, + replaceEndOfLineWith: replaceEndOfLineWith$3 + } +} = doc; +const { + isNonEmptyArray: isNonEmptyArray$4 +} = util$5; +const { + locStart: locStart$9, + locEnd: locEnd$8 +} = loc$4; +const { + getNextNode, + getPreviousNode, + hasPrettierIgnore: hasPrettierIgnore$6, + isLastNodeOfSiblings, + isNextNodeOfSomeType, + isNodeOfSomeType, + isParentOfSomeType, + isPreviousNodeOfSomeType, + isVoid, + isWhitespaceNode +} = utils$3; +const NEWLINES_TO_PRESERVE_MAX = 2; // Formatter based on @glimmerjs/syntax's built-in test formatter: +// https://github.com/glimmerjs/glimmer-vm/blob/master/packages/%40glimmer/syntax/lib/generation/print.ts + +function print(path, options, print) { + const node = path.getValue(); + /* istanbul ignore if*/ + + if (!node) { + return ""; + } + + if (hasPrettierIgnore$6(path)) { + return options.originalText.slice(locStart$9(node), locEnd$8(node)); + } + + switch (node.type) { + case "Block": + case "Program": + case "Template": + { + return group$7(path.map(print, "body")); + } + + case "ElementNode": + { + const startingTag = group$7(printStartingTag(path, print)); + const escapeNextElementNode = options.htmlWhitespaceSensitivity === "ignore" && isNextNodeOfSomeType(path, ["ElementNode"]) ? softline$6 : ""; + + if (isVoid(node)) { + return [startingTag, escapeNextElementNode]; + } + + const endingTag = [""]; + + if (node.children.length === 0) { + return [startingTag, indent$4(endingTag), escapeNextElementNode]; + } + + if (options.htmlWhitespaceSensitivity === "ignore") { + return [startingTag, indent$4(printChildren$3(path, options, print)), hardline$8, indent$4(endingTag), escapeNextElementNode]; + } + + return [startingTag, indent$4(group$7(printChildren$3(path, options, print))), indent$4(endingTag), escapeNextElementNode]; + } + + case "BlockStatement": + { + const pp = path.getParentNode(1); + const isElseIf = pp && pp.inverse && pp.inverse.body.length === 1 && pp.inverse.body[0] === node && pp.inverse.body[0].path.parts[0] === "if"; + + if (isElseIf) { + return [printElseIfBlock(path, print), printProgram(path, print, options), printInverse(path, print, options)]; + } + + return [printOpenBlock(path, print), group$7([printProgram(path, print, options), printInverse(path, print, options), printCloseBlock(path, print, options)])]; + } + + case "ElementModifierStatement": + { + return group$7(["{{", printPathAndParams(path, print), "}}"]); + } + + case "MustacheStatement": + { + return group$7([printOpeningMustache(node), printPathAndParams(path, print), printClosingMustache(node)]); + } + + case "SubExpression": + { + return group$7(["(", printSubExpressionPathAndParams(path, print), softline$6, ")"]); + } + + case "AttrNode": + { + const isText = node.value.type === "TextNode"; + const isEmptyText = isText && node.value.chars === ""; // If the text is empty and the value's loc start and end offsets are the + // same, there is no value for this AttrNode and it should be printed + // without the `=""`. Example: `` -> `` + + if (isEmptyText && locStart$9(node.value) === locEnd$8(node.value)) { + return node.name; + } // Let's assume quotes inside the content of text nodes are already + // properly escaped with entities, otherwise the parse wouldn't have parsed them. + + + const quote = isText ? chooseEnclosingQuote(options, node.value.chars).quote : node.value.type === "ConcatStatement" ? chooseEnclosingQuote(options, node.value.parts.filter(part => part.type === "TextNode").map(part => part.chars).join("")).quote : ""; + const valueDoc = print("value"); + return [node.name, "=", quote, node.name === "class" && quote ? group$7(indent$4(valueDoc)) : valueDoc, quote]; + } + + case "ConcatStatement": + { + return path.map(print, "parts"); + } + + case "Hash": + { + return join$8(line$8, path.map(print, "pairs")); + } + + case "HashPair": + { + return [node.key, "=", print("value")]; + } + + case "TextNode": + { + /* if `{{my-component}}` (or any text containing "{{") + * makes it to the TextNode, it means it was escaped, + * so let's print it escaped, ie.; `\{{my-component}}` */ + let text = node.chars.replace(/{{/g, "\\{{"); + const attrName = getCurrentAttributeName(path); + + if (attrName) { + // TODO: format style and srcset attributes + if (attrName === "class") { + const formattedClasses = text.trim().split(/\s+/).join(" "); + let leadingSpace = false; + let trailingSpace = false; + + if (isParentOfSomeType(path, ["ConcatStatement"])) { + if (isPreviousNodeOfSomeType(path, ["MustacheStatement"]) && /^\s/.test(text)) { + leadingSpace = true; + } + + if (isNextNodeOfSomeType(path, ["MustacheStatement"]) && /\s$/.test(text) && formattedClasses !== "") { + trailingSpace = true; + } + } + + return [leadingSpace ? line$8 : "", formattedClasses, trailingSpace ? line$8 : ""]; + } + + return replaceEndOfLineWith$3(text, literalline$4); + } + + const whitespacesOnlyRE = /^[\t\n\f\r ]*$/; + const isWhitespaceOnly = whitespacesOnlyRE.test(text); + const isFirstElement = !getPreviousNode(path); + const isLastElement = !getNextNode(path); + + if (options.htmlWhitespaceSensitivity !== "ignore") { + // https://infra.spec.whatwg.org/#ascii-whitespace + const leadingWhitespacesRE = /^[\t\n\f\r ]*/; + const trailingWhitespacesRE = /[\t\n\f\r ]*$/; // let's remove the file's final newline + // https://github.com/ember-cli/ember-new-output/blob/1a04c67ddd02ccb35e0ff41bb5cbce34b31173ef/.editorconfig#L16 + + const shouldTrimTrailingNewlines = isLastElement && isParentOfSomeType(path, ["Template"]); + const shouldTrimLeadingNewlines = isFirstElement && isParentOfSomeType(path, ["Template"]); + + if (isWhitespaceOnly) { + if (shouldTrimLeadingNewlines || shouldTrimTrailingNewlines) { + return ""; + } + + let breaks = [line$8]; + const newlines = countNewLines(text); + + if (newlines) { + breaks = generateHardlines(newlines); + } + + if (isLastNodeOfSiblings(path)) { + breaks = breaks.map(newline => dedent$1(newline)); + } + + return breaks; + } + + const [lead] = text.match(leadingWhitespacesRE); + const [tail] = text.match(trailingWhitespacesRE); + let leadBreaks = []; + + if (lead) { + leadBreaks = [line$8]; + const leadingNewlines = countNewLines(lead); + + if (leadingNewlines) { + leadBreaks = generateHardlines(leadingNewlines); + } + + text = text.replace(leadingWhitespacesRE, ""); + } + + let trailBreaks = []; + + if (tail) { + if (!shouldTrimTrailingNewlines) { + trailBreaks = [line$8]; + const trailingNewlines = countNewLines(tail); + + if (trailingNewlines) { + trailBreaks = generateHardlines(trailingNewlines); + } + + if (isLastNodeOfSiblings(path)) { + trailBreaks = trailBreaks.map(hardline => dedent$1(hardline)); + } + } + + text = text.replace(trailingWhitespacesRE, ""); + } + + return [...leadBreaks, fill$4(getTextValueParts$1(text)), ...trailBreaks]; + } + + const lineBreaksCount = countNewLines(text); + let leadingLineBreaksCount = countLeadingNewLines(text); + let trailingLineBreaksCount = countTrailingNewLines(text); + + if ((isFirstElement || isLastElement) && isWhitespaceOnly && isParentOfSomeType(path, ["Block", "ElementNode", "Template"])) { + return ""; + } + + if (isWhitespaceOnly && lineBreaksCount) { + leadingLineBreaksCount = Math.min(lineBreaksCount, NEWLINES_TO_PRESERVE_MAX); + trailingLineBreaksCount = 0; + } else { + if (isNextNodeOfSomeType(path, ["BlockStatement", "ElementNode"])) { + trailingLineBreaksCount = Math.max(trailingLineBreaksCount, 1); + } + + if (isPreviousNodeOfSomeType(path, ["BlockStatement", "ElementNode"])) { + leadingLineBreaksCount = Math.max(leadingLineBreaksCount, 1); + } + } + + let leadingSpace = ""; + let trailingSpace = ""; + + if (trailingLineBreaksCount === 0 && isNextNodeOfSomeType(path, ["MustacheStatement"])) { + trailingSpace = " "; + } + + if (leadingLineBreaksCount === 0 && isPreviousNodeOfSomeType(path, ["MustacheStatement"])) { + leadingSpace = " "; + } + + if (isFirstElement) { + leadingLineBreaksCount = 0; + leadingSpace = ""; + } + + if (isLastElement) { + trailingLineBreaksCount = 0; + trailingSpace = ""; + } + + text = text.replace(/^[\t\n\f\r ]+/g, leadingSpace).replace(/[\t\n\f\r ]+$/, trailingSpace); + return [...generateHardlines(leadingLineBreaksCount), fill$4(getTextValueParts$1(text)), ...generateHardlines(trailingLineBreaksCount)]; + } + + case "MustacheCommentStatement": + { + const start = locStart$9(node); + const end = locEnd$8(node); // Starts with `{{~` + + const isLeftWhiteSpaceSensitive = options.originalText.charAt(start + 2) === "~"; // Ends with `{{~` + + const isRightWhitespaceSensitive = options.originalText.charAt(end - 3) === "~"; + const dashes = node.value.includes("}}") ? "--" : ""; + return ["{{", isLeftWhiteSpaceSensitive ? "~" : "", "!", dashes, node.value, dashes, isRightWhitespaceSensitive ? "~" : "", "}}"]; + } + + case "PathExpression": + { + return node.original; + } + + case "BooleanLiteral": + { + return String(node.value); + } + + case "CommentStatement": + { + return [""]; + } + + case "StringLiteral": + { + return printStringLiteral(node.value, options); + } + + case "NumberLiteral": + { + return String(node.value); + } + + case "UndefinedLiteral": + { + return "undefined"; + } + + case "NullLiteral": + { + return "null"; + } + + /* istanbul ignore next */ + + default: + throw new Error("unknown glimmer type: " + JSON.stringify(node.type)); + } +} +/* ElementNode print helpers */ + + +function sortByLoc(a, b) { + return locStart$9(a) - locStart$9(b); +} + +function printStartingTag(path, print) { + const node = path.getValue(); + const types = ["attributes", "modifiers", "comments"].filter(property => isNonEmptyArray$4(node[property])); + const attributes = types.flatMap(type => node[type]).sort(sortByLoc); + + for (const attributeType of types) { + path.each(attributePath => { + const index = attributes.indexOf(attributePath.getValue()); + attributes.splice(index, 1, [line$8, print()]); + }, attributeType); + } + + if (isNonEmptyArray$4(node.blockParams)) { + attributes.push(line$8, printBlockParams(node)); + } + + return ["<", node.tag, indent$4(attributes), printStartingTagEndMarker(node)]; +} + +function printChildren$3(path, options, print) { + const node = path.getValue(); + const isEmpty = node.children.every(node => isWhitespaceNode(node)); + + if (options.htmlWhitespaceSensitivity === "ignore" && isEmpty) { + return ""; + } + + return path.map((childPath, childIndex) => { + const printedChild = print(); + + if (childIndex === 0 && options.htmlWhitespaceSensitivity === "ignore") { + return [softline$6, printedChild]; + } + + return printedChild; + }, "children"); +} + +function printStartingTagEndMarker(node) { + if (isVoid(node)) { + return ifBreak$6([softline$6, "/>"], [" />", softline$6]); + } + + return ifBreak$6([softline$6, ">"], ">"); +} +/* MustacheStatement print helpers */ + + +function printOpeningMustache(node) { + const mustache = node.escaped === false ? "{{{" : "{{"; + const strip = node.strip && node.strip.open ? "~" : ""; + return [mustache, strip]; +} + +function printClosingMustache(node) { + const mustache = node.escaped === false ? "}}}" : "}}"; + const strip = node.strip && node.strip.close ? "~" : ""; + return [strip, mustache]; +} +/* BlockStatement print helpers */ + + +function printOpeningBlockOpeningMustache(node) { + const opening = printOpeningMustache(node); + const strip = node.openStrip.open ? "~" : ""; + return [opening, strip, "#"]; +} + +function printOpeningBlockClosingMustache(node) { + const closing = printClosingMustache(node); + const strip = node.openStrip.close ? "~" : ""; + return [strip, closing]; +} + +function printClosingBlockOpeningMustache(node) { + const opening = printOpeningMustache(node); + const strip = node.closeStrip.open ? "~" : ""; + return [opening, strip, "/"]; +} + +function printClosingBlockClosingMustache(node) { + const closing = printClosingMustache(node); + const strip = node.closeStrip.close ? "~" : ""; + return [strip, closing]; +} + +function printInverseBlockOpeningMustache(node) { + const opening = printOpeningMustache(node); + const strip = node.inverseStrip.open ? "~" : ""; + return [opening, strip]; +} + +function printInverseBlockClosingMustache(node) { + const closing = printClosingMustache(node); + const strip = node.inverseStrip.close ? "~" : ""; + return [strip, closing]; +} + +function printOpenBlock(path, print) { + const node = path.getValue(); + const openingMustache = printOpeningBlockOpeningMustache(node); + const closingMustache = printOpeningBlockClosingMustache(node); + const attributes = [printPath(path, print)]; + const params = printParams(path, print); + + if (params) { + attributes.push(line$8, params); + } + + if (isNonEmptyArray$4(node.program.blockParams)) { + const block = printBlockParams(node.program); + attributes.push(line$8, block); + } + + return group$7([openingMustache, indent$4(attributes), softline$6, closingMustache]); +} + +function printElseBlock(node, options) { + return [options.htmlWhitespaceSensitivity === "ignore" ? hardline$8 : "", printInverseBlockOpeningMustache(node), "else", printInverseBlockClosingMustache(node)]; +} + +function printElseIfBlock(path, print) { + const parentNode = path.getParentNode(1); + return [printInverseBlockOpeningMustache(parentNode), "else if ", printParams(path, print), printInverseBlockClosingMustache(parentNode)]; +} + +function printCloseBlock(path, print, options) { + const node = path.getValue(); + + if (options.htmlWhitespaceSensitivity === "ignore") { + const escape = blockStatementHasOnlyWhitespaceInProgram(node) ? softline$6 : hardline$8; + return [escape, printClosingBlockOpeningMustache(node), print("path"), printClosingBlockClosingMustache(node)]; + } + + return [printClosingBlockOpeningMustache(node), print("path"), printClosingBlockClosingMustache(node)]; +} + +function blockStatementHasOnlyWhitespaceInProgram(node) { + return isNodeOfSomeType(node, ["BlockStatement"]) && node.program.body.every(node => isWhitespaceNode(node)); +} + +function blockStatementHasElseIf(node) { + return blockStatementHasElse(node) && node.inverse.body.length === 1 && isNodeOfSomeType(node.inverse.body[0], ["BlockStatement"]) && node.inverse.body[0].path.parts[0] === "if"; +} + +function blockStatementHasElse(node) { + return isNodeOfSomeType(node, ["BlockStatement"]) && node.inverse; +} + +function printProgram(path, print, options) { + const node = path.getValue(); + + if (blockStatementHasOnlyWhitespaceInProgram(node)) { + return ""; + } + + const program = print("program"); + + if (options.htmlWhitespaceSensitivity === "ignore") { + return indent$4([hardline$8, program]); + } + + return indent$4(program); +} + +function printInverse(path, print, options) { + const node = path.getValue(); + const inverse = print("inverse"); + const printed = options.htmlWhitespaceSensitivity === "ignore" ? [hardline$8, inverse] : inverse; + + if (blockStatementHasElseIf(node)) { + return printed; + } + + if (blockStatementHasElse(node)) { + return [printElseBlock(node, options), indent$4(printed)]; + } + + return ""; +} +/* TextNode print helpers */ + + +function getTextValueParts$1(value) { + return getDocParts$3(join$8(line$8, splitByHtmlWhitespace$2(value))); +} + +function splitByHtmlWhitespace$2(string) { + return string.split(/[\t\n\f\r ]+/); +} + +function getCurrentAttributeName(path) { + for (let depth = 0; depth < 2; depth++) { + const parentNode = path.getParentNode(depth); + + if (parentNode && parentNode.type === "AttrNode") { + return parentNode.name.toLowerCase(); + } + } +} + +function countNewLines(string) { + /* istanbul ignore next */ + string = typeof string === "string" ? string : ""; + return string.split("\n").length - 1; +} + +function countLeadingNewLines(string) { + /* istanbul ignore next */ + string = typeof string === "string" ? string : ""; + const newLines = (string.match(/^([^\S\n\r]*[\n\r])+/g) || [])[0] || ""; + return countNewLines(newLines); +} + +function countTrailingNewLines(string) { + /* istanbul ignore next */ + string = typeof string === "string" ? string : ""; + const newLines = (string.match(/([\n\r][^\S\n\r]*)+$/g) || [])[0] || ""; + return countNewLines(newLines); +} + +function generateHardlines(number = 0) { + return new Array(Math.min(number, NEWLINES_TO_PRESERVE_MAX)).fill(hardline$8); +} +/* StringLiteral print helpers */ + +/** + * Prints a string literal with the correct surrounding quotes based on + * `options.singleQuote` and the number of escaped quotes contained in + * the string literal. This function is the glimmer equivalent of `printString` + * in `common/util`, but has differences because of the way escaped characters + * are treated in hbs string literals. + * @param {string} stringLiteral - the string literal value + * @param {object} options - the prettier options object + */ + + +function printStringLiteral(stringLiteral, options) { + const { + quote, + regex + } = chooseEnclosingQuote(options, stringLiteral); + return [quote, stringLiteral.replace(regex, `\\${quote}`), quote]; +} + +function chooseEnclosingQuote(options, stringLiteral) { + const double = { + quote: '"', + regex: /"/g + }; + const single = { + quote: "'", + regex: /'/g + }; + const preferred = options.singleQuote ? single : double; + const alternate = preferred === single ? double : single; + let shouldUseAlternateQuote = false; // If `stringLiteral` contains at least one of the quote preferred for + // enclosing the string, we might want to enclose with the alternate quote + // instead, to minimize the number of escaped quotes. + + if (stringLiteral.includes(preferred.quote) || stringLiteral.includes(alternate.quote)) { + const numPreferredQuotes = (stringLiteral.match(preferred.regex) || []).length; + const numAlternateQuotes = (stringLiteral.match(alternate.regex) || []).length; + shouldUseAlternateQuote = numPreferredQuotes > numAlternateQuotes; + } + + return shouldUseAlternateQuote ? alternate : preferred; +} +/* SubExpression print helpers */ + + +function printSubExpressionPathAndParams(path, print) { + const p = printPath(path, print); + const params = printParams(path, print); + + if (!params) { + return p; + } + + return indent$4([p, line$8, group$7(params)]); +} +/* misc. print helpers */ + + +function printPathAndParams(path, print) { + const p = printPath(path, print); + const params = printParams(path, print); + + if (!params) { + return p; + } + + return [indent$4([p, line$8, params]), softline$6]; +} + +function printPath(path, print) { + return print("path"); +} + +function printParams(path, print) { + const node = path.getValue(); + const parts = []; + + if (node.params.length > 0) { + const params = path.map(print, "params"); + parts.push(...params); + } + + if (node.hash && node.hash.pairs.length > 0) { + const hash = print("hash"); + parts.push(hash); + } + + if (parts.length === 0) { + return ""; + } + + return join$8(line$8, parts); +} + +function printBlockParams(node) { + return ["as |", node.blockParams.join(" "), "|"]; +} + +var printerGlimmer = { + print, + massageAstNode: clean_1$2 +}; + +var name$5 = "Handlebars"; +var type$5 = "markup"; +var color$5 = "#f7931e"; +var aliases$3 = [ + "hbs", + "htmlbars" +]; +var extensions$5 = [ + ".handlebars", + ".hbs" +]; +var tmScope$5 = "text.html.handlebars"; +var aceMode$5 = "handlebars"; +var languageId$5 = 155; +var require$$0$4 = { + name: name$5, + type: type$5, + color: color$5, + aliases: aliases$3, + extensions: extensions$5, + tmScope: tmScope$5, + aceMode: aceMode$5, + languageId: languageId$5 +}; + +const languages$5 = [createLanguage(require$$0$4, () => ({ + since: "2.3.0", + parsers: ["glimmer"], + vscodeLanguageIds: ["handlebars"] +}))]; +const printers$3 = { + glimmer: printerGlimmer +}; +const parsers$4 = { + get glimmer() { + return require("./parser-glimmer").parsers.glimmer; + } + +}; +var languageHandlebars = { + languages: languages$5, + printers: printers$3, + parsers: parsers$4 +}; + +function hasPragma$2(text) { + return /^\s*#[^\S\n]*@(format|prettier)\s*(\n|$)/.test(text); +} + +function insertPragma$6(text) { + return "# @format\n\n" + text; +} + +var pragma$3 = { + hasPragma: hasPragma$2, + insertPragma: insertPragma$6 +}; + +function locStart$8(node) { + if (typeof node.start === "number") { + return node.start; + } + + return node.loc && node.loc.start; +} + +function locEnd$7(node) { + if (typeof node.end === "number") { + return node.end; + } + + return node.loc && node.loc.end; +} + +var loc$3 = { + locStart: locStart$8, + locEnd: locEnd$7 +}; + +const { + builders: { + join: join$7, + hardline: hardline$7, + line: line$7, + softline: softline$5, + group: group$6, + indent: indent$3, + ifBreak: ifBreak$5 + } +} = doc; +const { + isNextLineEmpty: isNextLineEmpty$2, + isNonEmptyArray: isNonEmptyArray$3 +} = util$5; +const { + insertPragma: insertPragma$5 +} = pragma$3; +const { + locStart: locStart$7, + locEnd: locEnd$6 +} = loc$3; + +function genericPrint$3(path, options, print) { + const node = path.getValue(); + + if (!node) { + return ""; + } + + if (typeof node === "string") { + return node; + } + + switch (node.kind) { + case "Document": + { + const parts = []; + path.each((pathChild, index, definitions) => { + parts.push(print()); + + if (index !== definitions.length - 1) { + parts.push(hardline$7); + + if (isNextLineEmpty$2(options.originalText, pathChild.getValue(), locEnd$6)) { + parts.push(hardline$7); + } + } + }, "definitions"); + return [...parts, hardline$7]; + } + + case "OperationDefinition": + { + const hasOperation = options.originalText[locStart$7(node)] !== "{"; + const hasName = Boolean(node.name); + return [hasOperation ? node.operation : "", hasOperation && hasName ? [" ", print("name")] : "", hasOperation && !hasName && isNonEmptyArray$3(node.variableDefinitions) ? " " : "", isNonEmptyArray$3(node.variableDefinitions) ? group$6(["(", indent$3([softline$5, join$7([ifBreak$5("", ", "), softline$5], path.map(print, "variableDefinitions"))]), softline$5, ")"]) : "", printDirectives(path, print, node), node.selectionSet ? !hasOperation && !hasName ? "" : " " : "", print("selectionSet")]; + } + + case "FragmentDefinition": + { + return ["fragment ", print("name"), isNonEmptyArray$3(node.variableDefinitions) ? group$6(["(", indent$3([softline$5, join$7([ifBreak$5("", ", "), softline$5], path.map(print, "variableDefinitions"))]), softline$5, ")"]) : "", " on ", print("typeCondition"), printDirectives(path, print, node), " ", print("selectionSet")]; + } + + case "SelectionSet": + { + return ["{", indent$3([hardline$7, join$7(hardline$7, path.call(selectionsPath => printSequence(selectionsPath, options, print), "selections"))]), hardline$7, "}"]; + } + + case "Field": + { + return group$6([node.alias ? [print("alias"), ": "] : "", print("name"), node.arguments.length > 0 ? group$6(["(", indent$3([softline$5, join$7([ifBreak$5("", ", "), softline$5], path.call(argsPath => printSequence(argsPath, options, print), "arguments"))]), softline$5, ")"]) : "", printDirectives(path, print, node), node.selectionSet ? " " : "", print("selectionSet")]); + } + + case "Name": + { + return node.value; + } + + case "StringValue": + { + if (node.block) { + return ['"""', hardline$7, join$7(hardline$7, node.value.replace(/"""/g, "\\$&").split("\n")), hardline$7, '"""']; + } + + return ['"', node.value.replace(/["\\]/g, "\\$&").replace(/\n/g, "\\n"), '"']; + } + + case "IntValue": + case "FloatValue": + case "EnumValue": + { + return node.value; + } + + case "BooleanValue": + { + return node.value ? "true" : "false"; + } + + case "NullValue": + { + return "null"; + } + + case "Variable": + { + return ["$", print("name")]; + } + + case "ListValue": + { + return group$6(["[", indent$3([softline$5, join$7([ifBreak$5("", ", "), softline$5], path.map(print, "values"))]), softline$5, "]"]); + } + + case "ObjectValue": + { + return group$6(["{", options.bracketSpacing && node.fields.length > 0 ? " " : "", indent$3([softline$5, join$7([ifBreak$5("", ", "), softline$5], path.map(print, "fields"))]), softline$5, ifBreak$5("", options.bracketSpacing && node.fields.length > 0 ? " " : ""), "}"]); + } + + case "ObjectField": + case "Argument": + { + return [print("name"), ": ", print("value")]; + } + + case "Directive": + { + return ["@", print("name"), node.arguments.length > 0 ? group$6(["(", indent$3([softline$5, join$7([ifBreak$5("", ", "), softline$5], path.call(argsPath => printSequence(argsPath, options, print), "arguments"))]), softline$5, ")"]) : ""]; + } + + case "NamedType": + { + return print("name"); + } + + case "VariableDefinition": + { + return [print("variable"), ": ", print("type"), node.defaultValue ? [" = ", print("defaultValue")] : "", printDirectives(path, print, node)]; + } + + case "ObjectTypeExtension": + case "ObjectTypeDefinition": + { + return [print("description"), node.description ? hardline$7 : "", node.kind === "ObjectTypeExtension" ? "extend " : "", "type ", print("name"), node.interfaces.length > 0 ? [" implements ", ...printInterfaces(path, options, print)] : "", printDirectives(path, print, node), node.fields.length > 0 ? [" {", indent$3([hardline$7, join$7(hardline$7, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))]), hardline$7, "}"] : ""]; + } + + case "FieldDefinition": + { + return [print("description"), node.description ? hardline$7 : "", print("name"), node.arguments.length > 0 ? group$6(["(", indent$3([softline$5, join$7([ifBreak$5("", ", "), softline$5], path.call(argsPath => printSequence(argsPath, options, print), "arguments"))]), softline$5, ")"]) : "", ": ", print("type"), printDirectives(path, print, node)]; + } + + case "DirectiveDefinition": + { + return [print("description"), node.description ? hardline$7 : "", "directive ", "@", print("name"), node.arguments.length > 0 ? group$6(["(", indent$3([softline$5, join$7([ifBreak$5("", ", "), softline$5], path.call(argsPath => printSequence(argsPath, options, print), "arguments"))]), softline$5, ")"]) : "", node.repeatable ? " repeatable" : "", " on ", join$7(" | ", path.map(print, "locations"))]; + } + + case "EnumTypeExtension": + case "EnumTypeDefinition": + { + return [print("description"), node.description ? hardline$7 : "", node.kind === "EnumTypeExtension" ? "extend " : "", "enum ", print("name"), printDirectives(path, print, node), node.values.length > 0 ? [" {", indent$3([hardline$7, join$7(hardline$7, path.call(valuesPath => printSequence(valuesPath, options, print), "values"))]), hardline$7, "}"] : ""]; + } + + case "EnumValueDefinition": + { + return [print("description"), node.description ? hardline$7 : "", print("name"), printDirectives(path, print, node)]; + } + + case "InputValueDefinition": + { + return [print("description"), node.description ? node.description.block ? hardline$7 : line$7 : "", print("name"), ": ", print("type"), node.defaultValue ? [" = ", print("defaultValue")] : "", printDirectives(path, print, node)]; + } + + case "InputObjectTypeExtension": + case "InputObjectTypeDefinition": + { + return [print("description"), node.description ? hardline$7 : "", node.kind === "InputObjectTypeExtension" ? "extend " : "", "input ", print("name"), printDirectives(path, print, node), node.fields.length > 0 ? [" {", indent$3([hardline$7, join$7(hardline$7, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))]), hardline$7, "}"] : ""]; + } + + case "SchemaDefinition": + { + return ["schema", printDirectives(path, print, node), " {", node.operationTypes.length > 0 ? indent$3([hardline$7, join$7(hardline$7, path.call(opsPath => printSequence(opsPath, options, print), "operationTypes"))]) : "", hardline$7, "}"]; + } + + case "OperationTypeDefinition": + { + return [print("operation"), ": ", print("type")]; + } + + case "InterfaceTypeExtension": + case "InterfaceTypeDefinition": + { + return [print("description"), node.description ? hardline$7 : "", node.kind === "InterfaceTypeExtension" ? "extend " : "", "interface ", print("name"), node.interfaces.length > 0 ? [" implements ", ...printInterfaces(path, options, print)] : "", printDirectives(path, print, node), node.fields.length > 0 ? [" {", indent$3([hardline$7, join$7(hardline$7, path.call(fieldsPath => printSequence(fieldsPath, options, print), "fields"))]), hardline$7, "}"] : ""]; + } + + case "FragmentSpread": + { + return ["...", print("name"), printDirectives(path, print, node)]; + } + + case "InlineFragment": + { + return ["...", node.typeCondition ? [" on ", print("typeCondition")] : "", printDirectives(path, print, node), " ", print("selectionSet")]; + } + + case "UnionTypeExtension": + case "UnionTypeDefinition": + { + return group$6([print("description"), node.description ? hardline$7 : "", group$6([node.kind === "UnionTypeExtension" ? "extend " : "", "union ", print("name"), printDirectives(path, print, node), node.types.length > 0 ? [" =", ifBreak$5("", " "), indent$3([ifBreak$5([line$7, " "]), join$7([line$7, "| "], path.map(print, "types"))])] : ""])]); + } + + case "ScalarTypeExtension": + case "ScalarTypeDefinition": + { + return [print("description"), node.description ? hardline$7 : "", node.kind === "ScalarTypeExtension" ? "extend " : "", "scalar ", print("name"), printDirectives(path, print, node)]; + } + + case "NonNullType": + { + return [print("type"), "!"]; + } + + case "ListType": + { + return ["[", print("type"), "]"]; + } + + default: + /* istanbul ignore next */ + throw new Error("unknown graphql type: " + JSON.stringify(node.kind)); + } +} + +function printDirectives(path, print, node) { + if (node.directives.length === 0) { + return ""; + } + + const printed = join$7(line$7, path.map(print, "directives")); + + if (node.kind === "FragmentDefinition" || node.kind === "OperationDefinition") { + return group$6([line$7, printed]); + } + + return [" ", group$6(indent$3([softline$5, printed]))]; +} + +function printSequence(sequencePath, options, print) { + const count = sequencePath.getValue().length; + return sequencePath.map((path, i) => { + const printed = print(); + + if (isNextLineEmpty$2(options.originalText, path.getValue(), locEnd$6) && i < count - 1) { + return [printed, hardline$7]; + } + + return printed; + }); +} + +function canAttachComment(node) { + return node.kind && node.kind !== "Comment"; +} + +function printComment(commentPath) { + const comment = commentPath.getValue(); + + if (comment.kind === "Comment") { + return "#" + comment.value.trimEnd(); + } + /* istanbul ignore next */ + + + throw new Error("Not a comment: " + JSON.stringify(comment)); +} + +function printInterfaces(path, options, print) { + const node = path.getNode(); + const parts = []; + const { + interfaces + } = node; + const printed = path.map(node => print(node), "interfaces"); + + for (let index = 0; index < interfaces.length; index++) { + const interfaceNode = interfaces[index]; + parts.push(printed[index]); + const nextInterfaceNode = interfaces[index + 1]; + + if (nextInterfaceNode) { + const textBetween = options.originalText.slice(interfaceNode.loc.end, nextInterfaceNode.loc.start); + const hasComment = textBetween.includes("#"); + const separator = textBetween.replace(/#.*/g, "").trim(); + parts.push(separator === "," ? "," : " &", hasComment ? line$7 : " "); + } + } + + return parts; +} + +function clean$3() +/*node, newNode , parent*/ +{} + +clean$3.ignoredProperties = new Set(["loc", "comments"]); + +function hasPrettierIgnore$5(path) { + const node = path.getValue(); + return node && Array.isArray(node.comments) && node.comments.some(comment => comment.value.trim() === "prettier-ignore"); +} + +var printerGraphql = { + print: genericPrint$3, + massageAstNode: clean$3, + hasPrettierIgnore: hasPrettierIgnore$5, + insertPragma: insertPragma$5, + printComment, + canAttachComment +}; + +var options$3 = { + bracketSpacing: commonOptions.bracketSpacing +}; + +var name$4 = "GraphQL"; +var type$4 = "data"; +var color$4 = "#e10098"; +var extensions$4 = [ + ".graphql", + ".gql", + ".graphqls" +]; +var tmScope$4 = "source.graphql"; +var aceMode$4 = "text"; +var languageId$4 = 139; +var require$$0$3 = { + name: name$4, + type: type$4, + color: color$4, + extensions: extensions$4, + tmScope: tmScope$4, + aceMode: aceMode$4, + languageId: languageId$4 +}; + +const languages$4 = [createLanguage(require$$0$3, () => ({ + since: "1.5.0", + parsers: ["graphql"], + vscodeLanguageIds: ["graphql"] +}))]; +const printers$2 = { + graphql: printerGraphql +}; +const parsers$3 = { + get graphql() { + return require("./parser-graphql").parsers.graphql; + } + +}; +var languageGraphql = { + languages: languages$4, + options: options$3, + printers: printers$2, + parsers: parsers$3 +}; + +function locStart$6(node) { + return node.position.start.offset; +} + +function locEnd$5(node) { + return node.position.end.offset; +} + +var loc$2 = { + locStart: locStart$6, + locEnd: locEnd$5 +}; + +var require$$2 = { + "cjkPattern": "(?:[\\u02ea-\\u02eb\\u1100-\\u11ff\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u2ff0-\\u303f\\u3041-\\u3096\\u3099-\\u309f\\u30a1-\\u30fa\\u30fc-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u3191\\u3196-\\u31ba\\u31c0-\\u31e3\\u31f0-\\u321e\\u322a-\\u3247\\u3260-\\u327e\\u328a-\\u32b0\\u32c0-\\u32cb\\u32d0-\\u3370\\u337b-\\u337f\\u33e0-\\u33fe\\u3400-\\u4db5\\u4e00-\\u9fef\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufa6d\\ufa70-\\ufad9\\ufe10-\\ufe1f\\ufe30-\\ufe6f\\uff00-\\uffef]|[\\ud840-\\ud868\\ud86a-\\ud86c\\ud86f-\\ud872\\ud874-\\ud879][\\udc00-\\udfff]|\\ud82c[\\udc00-\\udd1e\\udd50-\\udd52\\udd64-\\udd67]|\\ud83c[\\ude00\\ude50-\\ude51]|\\ud869[\\udc00-\\uded6\\udf00-\\udfff]|\\ud86d[\\udc00-\\udf34\\udf40-\\udfff]|\\ud86e[\\udc00-\\udc1d\\udc20-\\udfff]|\\ud873[\\udc00-\\udea1\\udeb0-\\udfff]|\\ud87a[\\udc00-\\udfe0]|\\ud87e[\\udc00-\\ude1d])(?:[\\ufe00-\\ufe0f]|\\udb40[\\udd00-\\uddef])?", + "kPattern": "[\\u1100-\\u11ff\\u3001-\\u3003\\u3008-\\u3011\\u3013-\\u301f\\u302e-\\u3030\\u3037\\u30fb\\u3131-\\u318e\\u3200-\\u321e\\u3260-\\u327e\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\ufe45-\\ufe46\\uff61-\\uff65\\uffa0-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc]", + "punctuationPattern": "[\\u0021-\\u002f\\u003a-\\u0040\\u005b-\\u0060\\u007b-\\u007e\\u00a1\\u00a7\\u00ab\\u00b6-\\u00b7\\u00bb\\u00bf\\u037e\\u0387\\u055a-\\u055f\\u0589-\\u058a\\u05be\\u05c0\\u05c3\\u05c6\\u05f3-\\u05f4\\u0609-\\u060a\\u060c-\\u060d\\u061b\\u061e-\\u061f\\u066a-\\u066d\\u06d4\\u0700-\\u070d\\u07f7-\\u07f9\\u0830-\\u083e\\u085e\\u0964-\\u0965\\u0970\\u09fd\\u0a76\\u0af0\\u0c77\\u0c84\\u0df4\\u0e4f\\u0e5a-\\u0e5b\\u0f04-\\u0f12\\u0f14\\u0f3a-\\u0f3d\\u0f85\\u0fd0-\\u0fd4\\u0fd9-\\u0fda\\u104a-\\u104f\\u10fb\\u1360-\\u1368\\u1400\\u166e\\u169b-\\u169c\\u16eb-\\u16ed\\u1735-\\u1736\\u17d4-\\u17d6\\u17d8-\\u17da\\u1800-\\u180a\\u1944-\\u1945\\u1a1e-\\u1a1f\\u1aa0-\\u1aa6\\u1aa8-\\u1aad\\u1b5a-\\u1b60\\u1bfc-\\u1bff\\u1c3b-\\u1c3f\\u1c7e-\\u1c7f\\u1cc0-\\u1cc7\\u1cd3\\u2010-\\u2027\\u2030-\\u2043\\u2045-\\u2051\\u2053-\\u205e\\u207d-\\u207e\\u208d-\\u208e\\u2308-\\u230b\\u2329-\\u232a\\u2768-\\u2775\\u27c5-\\u27c6\\u27e6-\\u27ef\\u2983-\\u2998\\u29d8-\\u29db\\u29fc-\\u29fd\\u2cf9-\\u2cfc\\u2cfe-\\u2cff\\u2d70\\u2e00-\\u2e2e\\u2e30-\\u2e4f\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301f\\u3030\\u303d\\u30a0\\u30fb\\ua4fe-\\ua4ff\\ua60d-\\ua60f\\ua673\\ua67e\\ua6f2-\\ua6f7\\ua874-\\ua877\\ua8ce-\\ua8cf\\ua8f8-\\ua8fa\\ua8fc\\ua92e-\\ua92f\\ua95f\\ua9c1-\\ua9cd\\ua9de-\\ua9df\\uaa5c-\\uaa5f\\uaade-\\uaadf\\uaaf0-\\uaaf1\\uabeb\\ufd3e-\\ufd3f\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe61\\ufe63\\ufe68\\ufe6a-\\ufe6b\\uff01-\\uff03\\uff05-\\uff0a\\uff0c-\\uff0f\\uff1a-\\uff1b\\uff1f-\\uff20\\uff3b-\\uff3d\\uff3f\\uff5b\\uff5d\\uff5f-\\uff65]|\\ud800[\\udd00-\\udd02\\udf9f\\udfd0]|\\ud801[\\udd6f]|\\ud802[\\udc57\\udd1f\\udd3f\\ude50-\\ude58\\ude7f\\udef0-\\udef6\\udf39-\\udf3f\\udf99-\\udf9c]|\\ud803[\\udf55-\\udf59]|\\ud804[\\udc47-\\udc4d\\udcbb-\\udcbc\\udcbe-\\udcc1\\udd40-\\udd43\\udd74-\\udd75\\uddc5-\\uddc8\\uddcd\\udddb\\udddd-\\udddf\\ude38-\\ude3d\\udea9]|\\ud805[\\udc4b-\\udc4f\\udc5b\\udc5d\\udcc6\\uddc1-\\uddd7\\ude41-\\ude43\\ude60-\\ude6c\\udf3c-\\udf3e]|\\ud806[\\udc3b\\udde2\\ude3f-\\ude46\\ude9a-\\ude9c\\ude9e-\\udea2]|\\ud807[\\udc41-\\udc45\\udc70-\\udc71\\udef7-\\udef8\\udfff]|\\ud809[\\udc70-\\udc74]|\\ud81a[\\ude6e-\\ude6f\\udef5\\udf37-\\udf3b\\udf44]|\\ud81b[\\ude97-\\ude9a\\udfe2]|\\ud82f[\\udc9f]|\\ud836[\\ude87-\\ude8b]|\\ud83a[\\udd5e-\\udd5f]" +}; + +const { + getLast: getLast$3 +} = util$5; +const { + locStart: locStart$5, + locEnd: locEnd$4 +} = loc$2; +const { + cjkPattern, + kPattern, + punctuationPattern: punctuationPattern$1 +} = require$$2; +const INLINE_NODE_TYPES$1 = ["liquidNode", "inlineCode", "emphasis", "strong", "delete", "wikiLink", "link", "linkReference", "image", "imageReference", "footnote", "footnoteReference", "sentence", "whitespace", "word", "break", "inlineMath"]; +const INLINE_NODE_WRAPPER_TYPES$1 = [...INLINE_NODE_TYPES$1, "tableCell", "paragraph", "heading"]; +const kRegex = new RegExp(kPattern); +const punctuationRegex = new RegExp(punctuationPattern$1); +/** + * split text into whitespaces and words + * @param {string} text + */ + +function splitText$2(text, options) { + const KIND_NON_CJK = "non-cjk"; + const KIND_CJ_LETTER = "cj-letter"; + const KIND_K_LETTER = "k-letter"; + const KIND_CJK_PUNCTUATION = "cjk-punctuation"; + /** @type {Array<{ type: "whitespace", value: " " | "\n" | "" } | { type: "word", value: string }>} */ + + const nodes = []; + const tokens = (options.proseWrap === "preserve" ? text : text.replace(new RegExp(`(${cjkPattern})\n(${cjkPattern})`, "g"), "$1$2")).split(/([\t\n ]+)/); + + for (const [index, token] of tokens.entries()) { + // whitespace + if (index % 2 === 1) { + nodes.push({ + type: "whitespace", + value: /\n/.test(token) ? "\n" : " " + }); + continue; + } // word separated by whitespace + + + if ((index === 0 || index === tokens.length - 1) && token === "") { + continue; + } + + const innerTokens = token.split(new RegExp(`(${cjkPattern})`)); + + for (const [innerIndex, innerToken] of innerTokens.entries()) { + if ((innerIndex === 0 || innerIndex === innerTokens.length - 1) && innerToken === "") { + continue; + } // non-CJK word + + + if (innerIndex % 2 === 0) { + if (innerToken !== "") { + appendNode({ + type: "word", + value: innerToken, + kind: KIND_NON_CJK, + hasLeadingPunctuation: punctuationRegex.test(innerToken[0]), + hasTrailingPunctuation: punctuationRegex.test(getLast$3(innerToken)) + }); + } + + continue; + } // CJK character + + + appendNode(punctuationRegex.test(innerToken) ? { + type: "word", + value: innerToken, + kind: KIND_CJK_PUNCTUATION, + hasLeadingPunctuation: true, + hasTrailingPunctuation: true + } : { + type: "word", + value: innerToken, + kind: kRegex.test(innerToken) ? KIND_K_LETTER : KIND_CJ_LETTER, + hasLeadingPunctuation: false, + hasTrailingPunctuation: false + }); + } + } + + return nodes; + + function appendNode(node) { + const lastNode = getLast$3(nodes); + + if (lastNode && lastNode.type === "word") { + if (lastNode.kind === KIND_NON_CJK && node.kind === KIND_CJ_LETTER && !lastNode.hasTrailingPunctuation || lastNode.kind === KIND_CJ_LETTER && node.kind === KIND_NON_CJK && !node.hasLeadingPunctuation) { + nodes.push({ + type: "whitespace", + value: " " + }); + } else if (!isBetween(KIND_NON_CJK, KIND_CJK_PUNCTUATION) && // disallow leading/trailing full-width whitespace + ![lastNode.value, node.value].some(value => /\u3000/.test(value))) { + nodes.push({ + type: "whitespace", + value: "" + }); + } + } + + nodes.push(node); + + function isBetween(kind1, kind2) { + return lastNode.kind === kind1 && node.kind === kind2 || lastNode.kind === kind2 && node.kind === kind1; + } + } +} + +function getOrderedListItemInfo$1(orderListItem, originalText) { + const [, numberText, marker, leadingSpaces] = originalText.slice(orderListItem.position.start.offset, orderListItem.position.end.offset).match(/^\s*(\d+)(\.|\))(\s*)/); + return { + numberText, + marker, + leadingSpaces + }; +} + +function hasGitDiffFriendlyOrderedList$1(node, options) { + if (!node.ordered) { + return false; + } + + if (node.children.length < 2) { + return false; + } + + const firstNumber = Number(getOrderedListItemInfo$1(node.children[0], options.originalText).numberText); + const secondNumber = Number(getOrderedListItemInfo$1(node.children[1], options.originalText).numberText); + + if (firstNumber === 0 && node.children.length > 2) { + const thirdNumber = Number(getOrderedListItemInfo$1(node.children[2], options.originalText).numberText); + return secondNumber === 1 && thirdNumber === 1; + } + + return secondNumber === 1; +} // The final new line should not include in value +// https://github.com/remarkjs/remark/issues/512 + + +function getFencedCodeBlockValue$2(node, originalText) { + const { + value + } = node; + + if (node.position.end.offset === originalText.length && value.endsWith("\n") && // Code block has no end mark + originalText.endsWith("\n")) { + return value.slice(0, -1); + } + + return value; +} + +function mapAst$1(ast, handler) { + return function preorder(node, index, parentStack) { + const newNode = Object.assign({}, handler(node, index, parentStack)); + + if (newNode.children) { + newNode.children = newNode.children.map((child, index) => preorder(child, index, [newNode, ...parentStack])); + } + + return newNode; + }(ast, null, []); +} + +function isAutolink$1(node) { + if (!node || node.type !== "link" || node.children.length !== 1) { + return false; + } + + const child = node.children[0]; + return child && locStart$5(node) === locStart$5(child) && locEnd$4(node) === locEnd$4(child); +} + +var utils$2 = { + mapAst: mapAst$1, + splitText: splitText$2, + punctuationPattern: punctuationPattern$1, + getFencedCodeBlockValue: getFencedCodeBlockValue$2, + getOrderedListItemInfo: getOrderedListItemInfo$1, + hasGitDiffFriendlyOrderedList: hasGitDiffFriendlyOrderedList$1, + INLINE_NODE_TYPES: INLINE_NODE_TYPES$1, + INLINE_NODE_WRAPPER_TYPES: INLINE_NODE_WRAPPER_TYPES$1, + isAutolink: isAutolink$1 +}; + +const { + inferParserByLanguage: inferParserByLanguage$1, + getMaxContinuousCount: getMaxContinuousCount$1 +} = util$5; +const { + builders: { + hardline: hardline$6, + markAsRoot: markAsRoot$2 + }, + utils: { + replaceNewlinesWithLiterallines + } +} = doc; +const { + getFencedCodeBlockValue: getFencedCodeBlockValue$1 +} = utils$2; + +function embed$3(path, print, textToDoc, options) { + const node = path.getValue(); + + if (node.type === "code" && node.lang !== null) { + const parser = inferParserByLanguage$1(node.lang, options); + + if (parser) { + const styleUnit = options.__inJsTemplate ? "~" : "`"; + const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount$1(node.value, styleUnit) + 1)); + const doc = textToDoc(getFencedCodeBlockValue$1(node, options.originalText), { + parser + }, { + stripTrailingHardline: true + }); + return markAsRoot$2([style, node.lang, node.meta ? " " + node.meta : "", hardline$6, replaceNewlinesWithLiterallines(doc), hardline$6, style]); + } + } + + switch (node.type) { + case "front-matter": + return print_1(node, textToDoc); + // MDX + + case "importExport": + return [textToDoc(node.value, { + parser: "babel" + }, { + stripTrailingHardline: true + }), hardline$6]; + + case "jsx": + return textToDoc(`<$>${node.value}`, { + parser: "__js_expression", + rootMarker: "mdx" + }, { + stripTrailingHardline: true + }); + } + + return null; +} + +var embed_1$1 = embed$3; + +const pragmas = ["format", "prettier"]; + +function startWithPragma$1(text) { + const pragma = `@(${pragmas.join("|")})`; + const regex = new RegExp([``, ``].join("|"), "m"); + const matched = text.match(regex); + return matched && matched.index === 0; +} + +var pragma$2 = { + startWithPragma: startWithPragma$1, + hasPragma: text => startWithPragma$1(parse_1(text).content.trimStart()), + insertPragma: text => { + const extracted = parse_1(text); + const pragma = ``; + return extracted.frontMatter ? `${extracted.frontMatter.raw}\n\n${pragma}\n\n${extracted.content}` : `${pragma}\n\n${extracted.content}`; + } +}; + +const { + getOrderedListItemInfo, + mapAst, + splitText: splitText$1 +} = utils$2; // 0x0 ~ 0x10ffff + +const isSingleCharRegex = /^.$/su; + +function preprocess$2(ast, options) { + ast = restoreUnescapedCharacter(ast, options); + ast = mergeContinuousTexts(ast); + ast = transformInlineCode(ast); + ast = transformIndentedCodeblockAndMarkItsParentList(ast, options); + ast = markAlignedList(ast, options); + ast = splitTextIntoSentences(ast, options); + ast = transformImportExport(ast); + ast = mergeContinuousImportExport(ast); + return ast; +} + +function transformImportExport(ast) { + return mapAst(ast, node => { + if (node.type !== "import" && node.type !== "export") { + return node; + } + + return Object.assign(Object.assign({}, node), {}, { + type: "importExport" + }); + }); +} + +function transformInlineCode(ast) { + return mapAst(ast, node => { + if (node.type !== "inlineCode") { + return node; + } + + return Object.assign(Object.assign({}, node), {}, { + value: node.value.replace(/\s+/g, " ") + }); + }); +} + +function restoreUnescapedCharacter(ast, options) { + return mapAst(ast, node => node.type !== "text" || node.value === "*" || node.value === "_" || // handle these cases in printer + !isSingleCharRegex.test(node.value) || node.position.end.offset - node.position.start.offset === node.value.length ? node : Object.assign(Object.assign({}, node), {}, { + value: options.originalText.slice(node.position.start.offset, node.position.end.offset) + })); +} + +function mergeContinuousImportExport(ast) { + return mergeChildren(ast, (prevNode, node) => prevNode.type === "importExport" && node.type === "importExport", (prevNode, node) => ({ + type: "importExport", + value: prevNode.value + "\n\n" + node.value, + position: { + start: prevNode.position.start, + end: node.position.end + } + })); +} + +function mergeChildren(ast, shouldMerge, mergeNode) { + return mapAst(ast, node => { + if (!node.children) { + return node; + } + + const children = node.children.reduce((current, child) => { + const lastChild = getLast_1(current); + + if (lastChild && shouldMerge(lastChild, child)) { + current.splice(-1, 1, mergeNode(lastChild, child)); + } else { + current.push(child); + } + + return current; + }, []); + return Object.assign(Object.assign({}, node), {}, { + children + }); + }); +} + +function mergeContinuousTexts(ast) { + return mergeChildren(ast, (prevNode, node) => prevNode.type === "text" && node.type === "text", (prevNode, node) => ({ + type: "text", + value: prevNode.value + node.value, + position: { + start: prevNode.position.start, + end: node.position.end + } + })); +} + +function splitTextIntoSentences(ast, options) { + return mapAst(ast, (node, index, [parentNode]) => { + if (node.type !== "text") { + return node; + } + + let { + value + } = node; + + if (parentNode.type === "paragraph") { + if (index === 0) { + value = value.trimStart(); + } + + if (index === parentNode.children.length - 1) { + value = value.trimEnd(); + } + } + + return { + type: "sentence", + position: node.position, + children: splitText$1(value, options) + }; + }); +} + +function transformIndentedCodeblockAndMarkItsParentList(ast, options) { + return mapAst(ast, (node, index, parentStack) => { + if (node.type === "code") { + // the first char may point to `\n`, e.g. `\n\t\tbar`, just ignore it + const isIndented = /^\n?( {4,}|\t)/.test(options.originalText.slice(node.position.start.offset, node.position.end.offset)); + node.isIndented = isIndented; + + if (isIndented) { + for (let i = 0; i < parentStack.length; i++) { + const parent = parentStack[i]; // no need to check checked items + + if (parent.hasIndentedCodeblock) { + break; + } + + if (parent.type === "list") { + parent.hasIndentedCodeblock = true; + } + } + } + } + + return node; + }); +} + +function markAlignedList(ast, options) { + return mapAst(ast, (node, index, parentStack) => { + if (node.type === "list" && node.children.length > 0) { + // if one of its parents is not aligned, it's not possible to be aligned in sub-lists + for (let i = 0; i < parentStack.length; i++) { + const parent = parentStack[i]; + + if (parent.type === "list" && !parent.isAligned) { + node.isAligned = false; + return node; + } + } + + node.isAligned = isAligned(node); + } + + return node; + }); + + function getListItemStart(listItem) { + return listItem.children.length === 0 ? -1 : listItem.children[0].position.start.column - 1; + } + + function isAligned(list) { + if (!list.ordered) { + /** + * - 123 + * - 123 + */ + return true; + } + + const [firstItem, secondItem] = list.children; + const firstInfo = getOrderedListItemInfo(firstItem, options.originalText); + + if (firstInfo.leadingSpaces.length > 1) { + /** + * 1. 123 + * + * 1. 123 + * 1. 123 + */ + return true; + } + + const firstStart = getListItemStart(firstItem); + + if (firstStart === -1) { + /** + * 1. + * + * 1. + * 1. + */ + return false; + } + + if (list.children.length === 1) { + /** + * aligned: + * + * 11. 123 + * + * not aligned: + * + * 1. 123 + */ + return firstStart % options.tabWidth === 0; + } + + const secondStart = getListItemStart(secondItem); + + if (firstStart !== secondStart) { + /** + * 11. 123 + * 1. 123 + * + * 1. 123 + * 11. 123 + */ + return false; + } + + if (firstStart % options.tabWidth === 0) { + /** + * 11. 123 + * 12. 123 + */ + return true; + } + /** + * aligned: + * + * 11. 123 + * 1. 123 + * + * not aligned: + * + * 1. 123 + * 2. 123 + */ + + + const secondInfo = getOrderedListItemInfo(secondItem, options.originalText); + return secondInfo.leadingSpaces.length > 1; + } +} + +var printPreprocess$2 = preprocess$2; + +const { + isFrontMatterNode: isFrontMatterNode$2 +} = util$5; +const { + startWithPragma +} = pragma$2; +const ignoredProperties$1 = new Set(["position", "raw" // front-matter +]); + +function clean$2(ast, newObj, parent) { + // for codeblock + if (ast.type === "front-matter" || ast.type === "code" || ast.type === "yaml" || ast.type === "import" || ast.type === "export" || ast.type === "jsx") { + delete newObj.value; + } + + if (ast.type === "list") { + delete newObj.isAligned; + } + + if (ast.type === "list" || ast.type === "listItem") { + delete newObj.spread; + delete newObj.loose; + } // texts can be splitted or merged + + + if (ast.type === "text") { + return null; + } + + if (ast.type === "inlineCode") { + newObj.value = ast.value.replace(/[\t\n ]+/g, " "); + } + + if (ast.type === "wikiLink") { + newObj.value = ast.value.trim().replace(/[\t\n]+/g, " "); + } + + if (ast.type === "definition" || ast.type === "linkReference") { + newObj.label = ast.label.trim().replace(/[\t\n ]+/g, " ").toLowerCase(); + } + + if ((ast.type === "definition" || ast.type === "link" || ast.type === "image") && ast.title) { + newObj.title = ast.title.replace(/\\(["')])/g, "$1"); + } // for insert pragma + + + if (parent && parent.type === "root" && parent.children.length > 0 && (parent.children[0] === ast || isFrontMatterNode$2(parent.children[0]) && parent.children[1] === ast) && ast.type === "html" && startWithPragma(ast.value)) { + return null; + } +} + +clean$2.ignoredProperties = ignoredProperties$1; +var clean_1$1 = clean$2; + +const { + getLast: getLast$2, + getMinNotPresentContinuousCount, + getMaxContinuousCount, + getStringWidth, + isNonEmptyArray: isNonEmptyArray$2 +} = util$5; +const { + builders: { + breakParent: breakParent$2, + join: join$6, + line: line$6, + literalline: literalline$3, + markAsRoot: markAsRoot$1, + hardline: hardline$5, + softline: softline$4, + ifBreak: ifBreak$4, + fill: fill$3, + align: align$1, + indent: indent$2, + group: group$5, + hardlineWithoutBreakParent + }, + utils: { + normalizeDoc, + replaceEndOfLineWith: replaceEndOfLineWith$2 + }, + printer: { + printDocToString + } +} = doc; +const { + insertPragma: insertPragma$4 +} = pragma$2; +const { + locStart: locStart$4, + locEnd: locEnd$3 +} = loc$2; +const { + getFencedCodeBlockValue, + hasGitDiffFriendlyOrderedList, + splitText, + punctuationPattern, + INLINE_NODE_TYPES, + INLINE_NODE_WRAPPER_TYPES, + isAutolink +} = utils$2; +/** + * @typedef {import("../document").Doc} Doc + */ + +const TRAILING_HARDLINE_NODES = new Set(["importExport"]); +const SINGLE_LINE_NODE_TYPES = ["heading", "tableCell", "link", "wikiLink"]; +const SIBLING_NODE_TYPES = new Set(["listItem", "definition", "footnoteDefinition"]); + +function genericPrint$2(path, options, print) { + const node = path.getValue(); + + if (shouldRemainTheSameContent(path)) { + return splitText(options.originalText.slice(node.position.start.offset, node.position.end.offset), options).map(node => node.type === "word" ? node.value : node.value === "" ? "" : printLine(path, node.value, options)); + } + + switch (node.type) { + case "front-matter": + return options.originalText.slice(node.position.start.offset, node.position.end.offset); + + case "root": + if (node.children.length === 0) { + return ""; + } + + return [normalizeDoc(printRoot(path, options, print)), !TRAILING_HARDLINE_NODES.has(getLastDescendantNode$2(node).type) ? hardline$5 : ""]; + + case "paragraph": + return printChildren$2(path, options, print, { + postprocessor: fill$3 + }); + + case "sentence": + return printChildren$2(path, options, print); + + case "word": + { + let escapedValue = node.value.replace(/\*/g, "\\$&") // escape all `*` + .replace(new RegExp([`(^|${punctuationPattern})(_+)`, `(_+)(${punctuationPattern}|$)`].join("|"), "g"), (_, text1, underscore1, underscore2, text2) => (underscore1 ? `${text1}${underscore1}` : `${underscore2}${text2}`).replace(/_/g, "\\_")); // escape all `_` except concating with non-punctuation, e.g. `1_2_3` is not considered emphasis + + const isFirstSentence = (node, name, index) => node.type === "sentence" && index === 0; + + const isLastChildAutolink = (node, name, index) => isAutolink(node.children[index - 1]); + + if (escapedValue !== node.value && (path.match(undefined, isFirstSentence, isLastChildAutolink) || path.match(undefined, isFirstSentence, (node, name, index) => node.type === "emphasis" && index === 0, isLastChildAutolink))) { + // backslash is parsed as part of autolinks, so we need to remove it + escapedValue = escapedValue.replace(/^(\\?[*_])+/, prefix => prefix.replace(/\\/g, "")); + } + + return escapedValue; + } + + case "whitespace": + { + const parentNode = path.getParentNode(); + const index = parentNode.children.indexOf(node); + const nextNode = parentNode.children[index + 1]; + const proseWrap = // leading char that may cause different syntax + nextNode && /^>|^([*+-]|#{1,6}|\d+[).])$/.test(nextNode.value) ? "never" : options.proseWrap; + return printLine(path, node.value, { + proseWrap + }); + } + + case "emphasis": + { + let style; + + if (isAutolink(node.children[0])) { + style = options.originalText[node.position.start.offset]; + } else { + const parentNode = path.getParentNode(); + const index = parentNode.children.indexOf(node); + const prevNode = parentNode.children[index - 1]; + const nextNode = parentNode.children[index + 1]; + const hasPrevOrNextWord = // `1*2*3` is considered emphasis but `1_2_3` is not + prevNode && prevNode.type === "sentence" && prevNode.children.length > 0 && getLast$2(prevNode.children).type === "word" && !getLast$2(prevNode.children).hasTrailingPunctuation || nextNode && nextNode.type === "sentence" && nextNode.children.length > 0 && nextNode.children[0].type === "word" && !nextNode.children[0].hasLeadingPunctuation; + style = hasPrevOrNextWord || getAncestorNode(path, "emphasis") ? "*" : "_"; + } + + return [style, printChildren$2(path, options, print), style]; + } + + case "strong": + return ["**", printChildren$2(path, options, print), "**"]; + + case "delete": + return ["~~", printChildren$2(path, options, print), "~~"]; + + case "inlineCode": + { + const backtickCount = getMinNotPresentContinuousCount(node.value, "`"); + const style = "`".repeat(backtickCount || 1); + const gap = backtickCount && !/^\s/.test(node.value) ? " " : ""; + return [style, gap, node.value, gap, style]; + } + + case "wikiLink": + { + let contents = ""; + + if (options.proseWrap === "preserve") { + contents = node.value; + } else { + contents = node.value.replace(/[\t\n]+/g, " "); + } + + return ["[[", contents, "]]"]; + } + + case "link": + switch (options.originalText[node.position.start.offset]) { + case "<": + { + const mailto = "mailto:"; + const url = // is parsed as { url: "mailto:hello@example.com" } + node.url.startsWith(mailto) && options.originalText.slice(node.position.start.offset + 1, node.position.start.offset + 1 + mailto.length) !== mailto ? node.url.slice(mailto.length) : node.url; + return ["<", url, ">"]; + } + + case "[": + return ["[", printChildren$2(path, options, print), "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]; + + default: + return options.originalText.slice(node.position.start.offset, node.position.end.offset); + } + + case "image": + return ["![", node.alt || "", "](", printUrl(node.url, ")"), printTitle(node.title, options), ")"]; + + case "blockquote": + return ["> ", align$1("> ", printChildren$2(path, options, print))]; + + case "heading": + return ["#".repeat(node.depth) + " ", printChildren$2(path, options, print)]; + + case "code": + { + if (node.isIndented) { + // indented code block + const alignment = " ".repeat(4); + return align$1(alignment, [alignment, ...replaceEndOfLineWith$2(node.value, hardline$5)]); + } // fenced code block + + + const styleUnit = options.__inJsTemplate ? "~" : "`"; + const style = styleUnit.repeat(Math.max(3, getMaxContinuousCount(node.value, styleUnit) + 1)); + return [style, node.lang || "", node.meta ? " " + node.meta : "", hardline$5, ...replaceEndOfLineWith$2(getFencedCodeBlockValue(node, options.originalText), hardline$5), hardline$5, style]; + } + + case "html": + { + const parentNode = path.getParentNode(); + const value = parentNode.type === "root" && getLast$2(parentNode.children) === node ? node.value.trimEnd() : node.value; + const isHtmlComment = /^$/s.test(value); + return replaceEndOfLineWith$2(value, isHtmlComment ? hardline$5 : markAsRoot$1(literalline$3)); + } + + case "list": + { + const nthSiblingIndex = getNthListSiblingIndex(node, path.getParentNode()); + const isGitDiffFriendlyOrderedList = hasGitDiffFriendlyOrderedList(node, options); + return printChildren$2(path, options, print, { + processor: (childPath, index) => { + const prefix = getPrefix(); + const childNode = childPath.getValue(); + + if (childNode.children.length === 2 && childNode.children[1].type === "html" && childNode.children[0].position.start.column !== childNode.children[1].position.start.column) { + return [prefix, printListItem(childPath, options, print, prefix)]; + } + + return [prefix, align$1(" ".repeat(prefix.length), printListItem(childPath, options, print, prefix))]; + + function getPrefix() { + const rawPrefix = node.ordered ? (index === 0 ? node.start : isGitDiffFriendlyOrderedList ? 1 : node.start + index) + (nthSiblingIndex % 2 === 0 ? ". " : ") ") : nthSiblingIndex % 2 === 0 ? "- " : "* "; + return node.isAligned || + /* workaround for https://github.com/remarkjs/remark/issues/315 */ + node.hasIndentedCodeblock ? alignListPrefix(rawPrefix, options) : rawPrefix; + } + } + }); + } + + case "thematicBreak": + { + const counter = getAncestorCounter(path, "list"); + + if (counter === -1) { + return "---"; + } + + const nthSiblingIndex = getNthListSiblingIndex(path.getParentNode(counter), path.getParentNode(counter + 1)); + return nthSiblingIndex % 2 === 0 ? "***" : "---"; + } + + case "linkReference": + return ["[", printChildren$2(path, options, print), "]", node.referenceType === "full" ? ["[", node.identifier, "]"] : node.referenceType === "collapsed" ? "[]" : ""]; + + case "imageReference": + switch (node.referenceType) { + case "full": + return ["![", node.alt || "", "][", node.identifier, "]"]; + + default: + return ["![", node.alt, "]", node.referenceType === "collapsed" ? "[]" : ""]; + } + + case "definition": + { + const lineOrSpace = options.proseWrap === "always" ? line$6 : " "; + return group$5(["[", node.identifier, "]:", indent$2([lineOrSpace, printUrl(node.url), node.title === null ? "" : [lineOrSpace, printTitle(node.title, options, false)]])]); + } + // `footnote` requires `.use(footnotes, {inlineNotes: true})`, we are not using this option + // https://github.com/remarkjs/remark-footnotes#optionsinlinenotes + + /* istanbul ignore next */ + + case "footnote": + return ["[^", printChildren$2(path, options, print), "]"]; + + case "footnoteReference": + return ["[^", node.identifier, "]"]; + + case "footnoteDefinition": + { + const nextNode = path.getParentNode().children[path.getName() + 1]; + const shouldInlineFootnote = node.children.length === 1 && node.children[0].type === "paragraph" && (options.proseWrap === "never" || options.proseWrap === "preserve" && node.children[0].position.start.line === node.children[0].position.end.line); + return ["[^", node.identifier, "]: ", shouldInlineFootnote ? printChildren$2(path, options, print) : group$5([align$1(" ".repeat(4), printChildren$2(path, options, print, { + processor: (childPath, index) => index === 0 ? group$5([softline$4, print()]) : print() + })), nextNode && nextNode.type === "footnoteDefinition" ? softline$4 : ""])]; + } + + case "table": + return printTable(path, options, print); + + case "tableCell": + return printChildren$2(path, options, print); + + case "break": + return /\s/.test(options.originalText[node.position.start.offset]) ? [" ", markAsRoot$1(literalline$3)] : ["\\", hardline$5]; + + case "liquidNode": + return replaceEndOfLineWith$2(node.value, hardline$5); + // MDX + // fallback to the original text if multiparser failed + // or `embeddedLanguageFormatting: "off"` + + case "importExport": + return [node.value, hardline$5]; + + case "jsx": + return node.value; + + case "math": + return ["$$", hardline$5, node.value ? [...replaceEndOfLineWith$2(node.value, hardline$5), hardline$5] : "", "$$"]; + + case "inlineMath": + { + // remark-math trims content but we don't want to remove whitespaces + // since it's very possible that it's recognized as math accidentally + return options.originalText.slice(locStart$4(node), locEnd$3(node)); + } + + case "tableRow": // handled in "table" + + case "listItem": // handled in "list" + + default: + /* istanbul ignore next */ + throw new Error(`Unknown markdown type ${JSON.stringify(node.type)}`); + } +} + +function printListItem(path, options, print, listPrefix) { + const node = path.getValue(); + const prefix = node.checked === null ? "" : node.checked ? "[x] " : "[ ] "; + return [prefix, printChildren$2(path, options, print, { + processor: (childPath, index) => { + if (index === 0 && childPath.getValue().type !== "list") { + return align$1(" ".repeat(prefix.length), print()); + } + + const alignment = " ".repeat(clamp(options.tabWidth - listPrefix.length, 0, 3) // 4+ will cause indented code block + ); + return [alignment, align$1(alignment, print())]; + } + })]; +} + +function alignListPrefix(prefix, options) { + const additionalSpaces = getAdditionalSpaces(); + return prefix + " ".repeat(additionalSpaces >= 4 ? 0 : additionalSpaces // 4+ will cause indented code block + ); + + function getAdditionalSpaces() { + const restSpaces = prefix.length % options.tabWidth; + return restSpaces === 0 ? 0 : options.tabWidth - restSpaces; + } +} + +function getNthListSiblingIndex(node, parentNode) { + return getNthSiblingIndex(node, parentNode, siblingNode => siblingNode.ordered === node.ordered); +} + +function getNthSiblingIndex(node, parentNode, condition) { + let index = -1; + + for (const childNode of parentNode.children) { + if (childNode.type === node.type && condition(childNode)) { + index++; + } else { + index = -1; + } + + if (childNode === node) { + return index; + } + } +} + +function getAncestorCounter(path, typeOrTypes) { + const types = Array.isArray(typeOrTypes) ? typeOrTypes : [typeOrTypes]; + let counter = -1; + let ancestorNode; + + while (ancestorNode = path.getParentNode(++counter)) { + if (types.includes(ancestorNode.type)) { + return counter; + } + } + + return -1; +} + +function getAncestorNode(path, typeOrTypes) { + const counter = getAncestorCounter(path, typeOrTypes); + return counter === -1 ? null : path.getParentNode(counter); +} + +function printLine(path, value, options) { + if (options.proseWrap === "preserve" && value === "\n") { + return hardline$5; + } + + const isBreakable = options.proseWrap === "always" && !getAncestorNode(path, SINGLE_LINE_NODE_TYPES); + return value !== "" ? isBreakable ? line$6 : " " : isBreakable ? softline$4 : ""; +} + +function printTable(path, options, print) { + const node = path.getValue(); + const columnMaxWidths = []; // { [rowIndex: number]: { [columnIndex: number]: {text: string, width: number} } } + + const contents = path.map(rowPath => rowPath.map((cellPath, columnIndex) => { + const text = printDocToString(print(), options).formatted; + const width = getStringWidth(text); + columnMaxWidths[columnIndex] = Math.max(columnMaxWidths[columnIndex] || 3, // minimum width = 3 (---, :--, :-:, --:) + width); + return { + text, + width + }; + }, "children"), "children"); + const alignedTable = printTableContents( + /* isCompact */ + false); + + if (options.proseWrap !== "never") { + return [breakParent$2, alignedTable]; + } // Only if the --prose-wrap never is set and it exceeds the print width. + + + const compactTable = printTableContents( + /* isCompact */ + true); + return [breakParent$2, group$5(ifBreak$4(compactTable, alignedTable))]; + + function printTableContents(isCompact) { + /** @type{Doc[]} */ + const parts = [printRow(contents[0], isCompact), printAlign(isCompact)]; + + if (contents.length > 1) { + parts.push(join$6(hardlineWithoutBreakParent, contents.slice(1).map(rowContents => printRow(rowContents, isCompact)))); + } + + return join$6(hardlineWithoutBreakParent, parts); + } + + function printAlign(isCompact) { + const align = columnMaxWidths.map((width, index) => { + const align = node.align[index]; + const first = align === "center" || align === "left" ? ":" : "-"; + const last = align === "center" || align === "right" ? ":" : "-"; + const middle = isCompact ? "-" : "-".repeat(width - 2); + return `${first}${middle}${last}`; + }); + return `| ${align.join(" | ")} |`; + } + + function printRow(rowContents, isCompact) { + const columns = rowContents.map(({ + text, + width + }, columnIndex) => { + if (isCompact) { + return text; + } + + const spaces = columnMaxWidths[columnIndex] - width; + const align = node.align[columnIndex]; + let before = 0; + + if (align === "right") { + before = spaces; + } else if (align === "center") { + before = Math.floor(spaces / 2); + } + + const after = spaces - before; + return `${" ".repeat(before)}${text}${" ".repeat(after)}`; + }); + return `| ${columns.join(" | ")} |`; + } +} + +function printRoot(path, options, print) { + /** @typedef {{ index: number, offset: number }} IgnorePosition */ + + /** @type {Array<{start: IgnorePosition, end: IgnorePosition}>} */ + const ignoreRanges = []; + /** @type {IgnorePosition | null} */ + + let ignoreStart = null; + const { + children + } = path.getValue(); + + for (const [index, childNode] of children.entries()) { + switch (isPrettierIgnore$2(childNode)) { + case "start": + if (ignoreStart === null) { + ignoreStart = { + index, + offset: childNode.position.end.offset + }; + } + + break; + + case "end": + if (ignoreStart !== null) { + ignoreRanges.push({ + start: ignoreStart, + end: { + index, + offset: childNode.position.start.offset + } + }); + ignoreStart = null; + } + + break; + } + } + + return printChildren$2(path, options, print, { + processor: (childPath, index) => { + if (ignoreRanges.length > 0) { + const ignoreRange = ignoreRanges[0]; + + if (index === ignoreRange.start.index) { + return [children[ignoreRange.start.index].value, options.originalText.slice(ignoreRange.start.offset, ignoreRange.end.offset), children[ignoreRange.end.index].value]; + } + + if (ignoreRange.start.index < index && index < ignoreRange.end.index) { + return false; + } + + if (index === ignoreRange.end.index) { + ignoreRanges.shift(); + return false; + } + } + + return print(); + } + }); +} + +function printChildren$2(path, options, print, events = {}) { + const { + postprocessor + } = events; + + const processor = events.processor || (() => print()); + + const node = path.getValue(); + const parts = []; + let lastChildNode; + path.each((childPath, index) => { + const childNode = childPath.getValue(); + const result = processor(childPath, index); + + if (result !== false) { + const data = { + parts, + prevNode: lastChildNode, + parentNode: node, + options + }; + + if (shouldPrePrintHardline(childNode, data)) { + parts.push(hardline$5); // Can't find a case to pass `shouldPrePrintTripleHardline` + + /* istanbul ignore next */ + + if (lastChildNode && TRAILING_HARDLINE_NODES.has(lastChildNode.type)) { + if (shouldPrePrintTripleHardline(childNode, data)) { + parts.push(hardline$5); + } + } else { + if (shouldPrePrintDoubleHardline(childNode, data) || shouldPrePrintTripleHardline(childNode, data)) { + parts.push(hardline$5); + } + + if (shouldPrePrintTripleHardline(childNode, data)) { + parts.push(hardline$5); + } + } + } + + parts.push(result); + lastChildNode = childNode; + } + }, "children"); + return postprocessor ? postprocessor(parts) : parts; +} + +function getLastDescendantNode$2(node) { + let current = node; + + while (isNonEmptyArray$2(current.children)) { + current = getLast$2(current.children); + } + + return current; +} +/** @return {false | 'next' | 'start' | 'end'} */ + + +function isPrettierIgnore$2(node) { + if (node.type !== "html") { + return false; + } + + const match = node.value.match(/^$/); + return match === null ? false : match[1] ? match[1] : "next"; +} + +function shouldPrePrintHardline(node, data) { + const isFirstNode = data.parts.length === 0; + const isInlineNode = INLINE_NODE_TYPES.includes(node.type); + const isInlineHTML = node.type === "html" && INLINE_NODE_WRAPPER_TYPES.includes(data.parentNode.type); + return !isFirstNode && !isInlineNode && !isInlineHTML; +} + +function shouldPrePrintDoubleHardline(node, data) { + const isSequence = (data.prevNode && data.prevNode.type) === node.type; + const isSiblingNode = isSequence && SIBLING_NODE_TYPES.has(node.type); + const isInTightListItem = data.parentNode.type === "listItem" && !data.parentNode.loose; + const isPrevNodeLooseListItem = data.prevNode && data.prevNode.type === "listItem" && data.prevNode.loose; + const isPrevNodePrettierIgnore = isPrettierIgnore$2(data.prevNode) === "next"; + const isBlockHtmlWithoutBlankLineBetweenPrevHtml = node.type === "html" && data.prevNode && data.prevNode.type === "html" && data.prevNode.position.end.line + 1 === node.position.start.line; + const isHtmlDirectAfterListItem = node.type === "html" && data.parentNode.type === "listItem" && data.prevNode && data.prevNode.type === "paragraph" && data.prevNode.position.end.line + 1 === node.position.start.line; + return isPrevNodeLooseListItem || !(isSiblingNode || isInTightListItem || isPrevNodePrettierIgnore || isBlockHtmlWithoutBlankLineBetweenPrevHtml || isHtmlDirectAfterListItem); +} + +function shouldPrePrintTripleHardline(node, data) { + const isPrevNodeList = data.prevNode && data.prevNode.type === "list"; + const isIndentedCode = node.type === "code" && node.isIndented; + return isPrevNodeList && isIndentedCode; +} + +function shouldRemainTheSameContent(path) { + const ancestorNode = getAncestorNode(path, ["linkReference", "imageReference"]); + return ancestorNode && (ancestorNode.type !== "linkReference" || ancestorNode.referenceType !== "full"); +} +/** + * @param {string} url + * @param {string[] | string} [dangerousCharOrChars] + * @returns {string} + */ + + +function printUrl(url, dangerousCharOrChars = []) { + const dangerousChars = [" ", ...(Array.isArray(dangerousCharOrChars) ? dangerousCharOrChars : [dangerousCharOrChars])]; + return new RegExp(dangerousChars.map(x => `\\${x}`).join("|")).test(url) ? `<${url}>` : url; +} + +function printTitle(title, options, printSpace = true) { + if (!title) { + return ""; + } + + if (printSpace) { + return " " + printTitle(title, options, false); + } // title is escaped after `remark-parse` v7 + + + title = title.replace(/\\(["')])/g, "$1"); + + if (title.includes('"') && title.includes("'") && !title.includes(")")) { + return `(${title})`; // avoid escaped quotes + } // faster than using RegExps: https://jsperf.com/performance-of-match-vs-split + + + const singleCount = title.split("'").length - 1; + const doubleCount = title.split('"').length - 1; + const quote = singleCount > doubleCount ? '"' : doubleCount > singleCount ? "'" : options.singleQuote ? "'" : '"'; + title = title.replace(/\\/, "\\\\"); + title = title.replace(new RegExp(`(${quote})`, "g"), "\\$1"); + return `${quote}${title}${quote}`; +} + +function clamp(value, min, max) { + return value < min ? min : value > max ? max : value; +} + +function hasPrettierIgnore$4(path) { + const index = Number(path.getName()); + + if (index === 0) { + return false; + } + + const prevNode = path.getParentNode().children[index - 1]; + return isPrettierIgnore$2(prevNode) === "next"; +} + +var printerMarkdown = { + preprocess: printPreprocess$2, + print: genericPrint$2, + embed: embed_1$1, + massageAstNode: clean_1$1, + hasPrettierIgnore: hasPrettierIgnore$4, + insertPragma: insertPragma$4 +}; + +var options$2 = { + proseWrap: commonOptions.proseWrap, + singleQuote: commonOptions.singleQuote +}; + +var name$3 = "Markdown"; +var type$3 = "prose"; +var color$3 = "#083fa1"; +var aliases$2 = [ + "pandoc" +]; +var aceMode$3 = "markdown"; +var codemirrorMode$2 = "gfm"; +var codemirrorMimeType$2 = "text/x-gfm"; +var wrap = true; +var extensions$3 = [ + ".md", + ".markdown", + ".mdown", + ".mdwn", + ".mdx", + ".mkd", + ".mkdn", + ".mkdown", + ".ronn", + ".scd", + ".workbook" +]; +var filenames$1 = [ + "contents.lr" +]; +var tmScope$3 = "source.gfm"; +var languageId$3 = 222; +var require$$0$2 = { + name: name$3, + type: type$3, + color: color$3, + aliases: aliases$2, + aceMode: aceMode$3, + codemirrorMode: codemirrorMode$2, + codemirrorMimeType: codemirrorMimeType$2, + wrap: wrap, + extensions: extensions$3, + filenames: filenames$1, + tmScope: tmScope$3, + languageId: languageId$3 +}; + +const languages$3 = [createLanguage(require$$0$2, data => ({ + since: "1.8.0", + parsers: ["markdown"], + vscodeLanguageIds: ["markdown"], + filenames: [...data.filenames, "README"], + extensions: data.extensions.filter(extension => extension !== ".mdx") +})), createLanguage(require$$0$2, () => ({ + name: "MDX", + since: "1.15.0", + parsers: ["mdx"], + vscodeLanguageIds: ["mdx"], + filenames: [], + extensions: [".mdx"] +}))]; +const printers$1 = { + mdast: printerMarkdown +}; +const parsers$2 = { + /* istanbul ignore next */ + get remark() { + return require("./parser-markdown").parsers.remark; + }, + + get markdown() { + return require("./parser-markdown").parsers.remark; + }, + + get mdx() { + return require("./parser-markdown").parsers.mdx; + } + +}; +var languageMarkdown = { + languages: languages$3, + options: options$2, + printers: printers$1, + parsers: parsers$2 +}; + +const { + isFrontMatterNode: isFrontMatterNode$1 +} = util$5; +const ignoredProperties = new Set(["sourceSpan", "startSourceSpan", "endSourceSpan", "nameSpan", "valueSpan"]); + +function clean$1(ast, newNode) { + if (ast.type === "text" || ast.type === "comment") { + return null; + } // may be formatted by multiparser + + + if (isFrontMatterNode$1(ast) || ast.type === "yaml" || ast.type === "toml") { + return null; + } + + if (ast.type === "attribute") { + delete newNode.value; + } + + if (ast.type === "docType") { + delete newNode.value; + } +} + +clean$1.ignoredProperties = ignoredProperties; +var clean_1 = clean$1; + +var htmlTagNames = [ + "a", + "abbr", + "acronym", + "address", + "applet", + "area", + "article", + "aside", + "audio", + "b", + "base", + "basefont", + "bdi", + "bdo", + "bgsound", + "big", + "blink", + "blockquote", + "body", + "br", + "button", + "canvas", + "caption", + "center", + "cite", + "code", + "col", + "colgroup", + "command", + "content", + "data", + "datalist", + "dd", + "del", + "details", + "dfn", + "dialog", + "dir", + "div", + "dl", + "dt", + "element", + "em", + "embed", + "fieldset", + "figcaption", + "figure", + "font", + "footer", + "form", + "frame", + "frameset", + "h1", + "h2", + "h3", + "h4", + "h5", + "h6", + "head", + "header", + "hgroup", + "hr", + "html", + "i", + "iframe", + "image", + "img", + "input", + "ins", + "isindex", + "kbd", + "keygen", + "label", + "legend", + "li", + "link", + "listing", + "main", + "map", + "mark", + "marquee", + "math", + "menu", + "menuitem", + "meta", + "meter", + "multicol", + "nav", + "nextid", + "nobr", + "noembed", + "noframes", + "noscript", + "object", + "ol", + "optgroup", + "option", + "output", + "p", + "param", + "picture", + "plaintext", + "pre", + "progress", + "q", + "rb", + "rbc", + "rp", + "rt", + "rtc", + "ruby", + "s", + "samp", + "script", + "section", + "select", + "shadow", + "slot", + "small", + "source", + "spacer", + "span", + "strike", + "strong", + "style", + "sub", + "summary", + "sup", + "svg", + "table", + "tbody", + "td", + "template", + "textarea", + "tfoot", + "th", + "thead", + "time", + "title", + "tr", + "track", + "tt", + "u", + "ul", + "var", + "video", + "wbr", + "xmp" +]; + +var a = [ + "accesskey", + "charset", + "coords", + "download", + "href", + "hreflang", + "name", + "ping", + "referrerpolicy", + "rel", + "rev", + "shape", + "tabindex", + "target", + "type" +]; +var abbr = [ + "title" +]; +var applet = [ + "align", + "alt", + "archive", + "code", + "codebase", + "height", + "hspace", + "name", + "object", + "vspace", + "width" +]; +var area = [ + "accesskey", + "alt", + "coords", + "download", + "href", + "hreflang", + "nohref", + "ping", + "referrerpolicy", + "rel", + "shape", + "tabindex", + "target", + "type" +]; +var audio = [ + "autoplay", + "controls", + "crossorigin", + "loop", + "muted", + "preload", + "src" +]; +var base = [ + "href", + "target" +]; +var basefont = [ + "color", + "face", + "size" +]; +var bdo = [ + "dir" +]; +var blockquote = [ + "cite" +]; +var body = [ + "alink", + "background", + "bgcolor", + "link", + "text", + "vlink" +]; +var br = [ + "clear" +]; +var button = [ + "accesskey", + "autofocus", + "disabled", + "form", + "formaction", + "formenctype", + "formmethod", + "formnovalidate", + "formtarget", + "name", + "tabindex", + "type", + "value" +]; +var canvas = [ + "height", + "width" +]; +var caption = [ + "align" +]; +var col = [ + "align", + "char", + "charoff", + "span", + "valign", + "width" +]; +var colgroup = [ + "align", + "char", + "charoff", + "span", + "valign", + "width" +]; +var data = [ + "value" +]; +var del = [ + "cite", + "datetime" +]; +var details = [ + "open" +]; +var dfn = [ + "title" +]; +var dialog = [ + "open" +]; +var dir = [ + "compact" +]; +var div = [ + "align" +]; +var dl = [ + "compact" +]; +var embed$2 = [ + "height", + "src", + "type", + "width" +]; +var fieldset = [ + "disabled", + "form", + "name" +]; +var font = [ + "color", + "face", + "size" +]; +var form = [ + "accept", + "accept-charset", + "action", + "autocomplete", + "enctype", + "method", + "name", + "novalidate", + "target" +]; +var frame = [ + "frameborder", + "longdesc", + "marginheight", + "marginwidth", + "name", + "noresize", + "scrolling", + "src" +]; +var frameset = [ + "cols", + "rows" +]; +var h1 = [ + "align" +]; +var h2 = [ + "align" +]; +var h3 = [ + "align" +]; +var h4 = [ + "align" +]; +var h5 = [ + "align" +]; +var h6 = [ + "align" +]; +var head = [ + "profile" +]; +var hr = [ + "align", + "noshade", + "size", + "width" +]; +var html = [ + "manifest", + "version" +]; +var iframe = [ + "align", + "allow", + "allowfullscreen", + "allowpaymentrequest", + "allowusermedia", + "frameborder", + "height", + "loading", + "longdesc", + "marginheight", + "marginwidth", + "name", + "referrerpolicy", + "sandbox", + "scrolling", + "src", + "srcdoc", + "width" +]; +var img = [ + "align", + "alt", + "border", + "crossorigin", + "decoding", + "height", + "hspace", + "ismap", + "loading", + "longdesc", + "name", + "referrerpolicy", + "sizes", + "src", + "srcset", + "usemap", + "vspace", + "width" +]; +var input = [ + "accept", + "accesskey", + "align", + "alt", + "autocomplete", + "autofocus", + "checked", + "dirname", + "disabled", + "form", + "formaction", + "formenctype", + "formmethod", + "formnovalidate", + "formtarget", + "height", + "ismap", + "list", + "max", + "maxlength", + "min", + "minlength", + "multiple", + "name", + "pattern", + "placeholder", + "readonly", + "required", + "size", + "src", + "step", + "tabindex", + "title", + "type", + "usemap", + "value", + "width" +]; +var ins = [ + "cite", + "datetime" +]; +var isindex = [ + "prompt" +]; +var label = [ + "accesskey", + "for", + "form" +]; +var legend = [ + "accesskey", + "align" +]; +var li = [ + "type", + "value" +]; +var link = [ + "as", + "charset", + "color", + "crossorigin", + "disabled", + "href", + "hreflang", + "imagesizes", + "imagesrcset", + "integrity", + "media", + "nonce", + "referrerpolicy", + "rel", + "rev", + "sizes", + "target", + "title", + "type" +]; +var map = [ + "name" +]; +var menu = [ + "compact" +]; +var meta = [ + "charset", + "content", + "http-equiv", + "name", + "scheme" +]; +var meter = [ + "high", + "low", + "max", + "min", + "optimum", + "value" +]; +var object = [ + "align", + "archive", + "border", + "classid", + "codebase", + "codetype", + "data", + "declare", + "form", + "height", + "hspace", + "name", + "standby", + "tabindex", + "type", + "typemustmatch", + "usemap", + "vspace", + "width" +]; +var ol = [ + "compact", + "reversed", + "start", + "type" +]; +var optgroup = [ + "disabled", + "label" +]; +var option = [ + "disabled", + "label", + "selected", + "value" +]; +var output = [ + "for", + "form", + "name" +]; +var p = [ + "align" +]; +var param = [ + "name", + "type", + "value", + "valuetype" +]; +var pre = [ + "width" +]; +var progress = [ + "max", + "value" +]; +var q = [ + "cite" +]; +var script = [ + "async", + "charset", + "crossorigin", + "defer", + "integrity", + "language", + "nomodule", + "nonce", + "referrerpolicy", + "src", + "type" +]; +var select = [ + "autocomplete", + "autofocus", + "disabled", + "form", + "multiple", + "name", + "required", + "size", + "tabindex" +]; +var slot = [ + "name" +]; +var source = [ + "media", + "sizes", + "src", + "srcset", + "type" +]; +var style = [ + "media", + "nonce", + "title", + "type" +]; +var table = [ + "align", + "bgcolor", + "border", + "cellpadding", + "cellspacing", + "frame", + "rules", + "summary", + "width" +]; +var tbody = [ + "align", + "char", + "charoff", + "valign" +]; +var td = [ + "abbr", + "align", + "axis", + "bgcolor", + "char", + "charoff", + "colspan", + "headers", + "height", + "nowrap", + "rowspan", + "scope", + "valign", + "width" +]; +var textarea = [ + "accesskey", + "autocomplete", + "autofocus", + "cols", + "dirname", + "disabled", + "form", + "maxlength", + "minlength", + "name", + "placeholder", + "readonly", + "required", + "rows", + "tabindex", + "wrap" +]; +var tfoot = [ + "align", + "char", + "charoff", + "valign" +]; +var th = [ + "abbr", + "align", + "axis", + "bgcolor", + "char", + "charoff", + "colspan", + "headers", + "height", + "nowrap", + "rowspan", + "scope", + "valign", + "width" +]; +var thead = [ + "align", + "char", + "charoff", + "valign" +]; +var time = [ + "datetime" +]; +var tr = [ + "align", + "bgcolor", + "char", + "charoff", + "valign" +]; +var track = [ + "default", + "kind", + "label", + "src", + "srclang" +]; +var ul = [ + "compact", + "type" +]; +var video = [ + "autoplay", + "controls", + "crossorigin", + "height", + "loop", + "muted", + "playsinline", + "poster", + "preload", + "src", + "width" +]; +var htmlElementAttributes = { + "*": [ + "accesskey", + "autocapitalize", + "autofocus", + "class", + "contenteditable", + "dir", + "draggable", + "enterkeyhint", + "hidden", + "id", + "inputmode", + "is", + "itemid", + "itemprop", + "itemref", + "itemscope", + "itemtype", + "lang", + "nonce", + "slot", + "spellcheck", + "style", + "tabindex", + "title", + "translate" +], + a: a, + abbr: abbr, + applet: applet, + area: area, + audio: audio, + base: base, + basefont: basefont, + bdo: bdo, + blockquote: blockquote, + body: body, + br: br, + button: button, + canvas: canvas, + caption: caption, + col: col, + colgroup: colgroup, + data: data, + del: del, + details: details, + dfn: dfn, + dialog: dialog, + dir: dir, + div: div, + dl: dl, + embed: embed$2, + fieldset: fieldset, + font: font, + form: form, + frame: frame, + frameset: frameset, + h1: h1, + h2: h2, + h3: h3, + h4: h4, + h5: h5, + h6: h6, + head: head, + hr: hr, + html: html, + iframe: iframe, + img: img, + input: input, + ins: ins, + isindex: isindex, + label: label, + legend: legend, + li: li, + link: link, + map: map, + menu: menu, + meta: meta, + meter: meter, + object: object, + ol: ol, + optgroup: optgroup, + option: option, + output: output, + p: p, + param: param, + pre: pre, + progress: progress, + q: q, + script: script, + select: select, + slot: slot, + source: source, + style: style, + table: table, + tbody: tbody, + td: td, + textarea: textarea, + tfoot: tfoot, + th: th, + thead: thead, + time: time, + tr: tr, + track: track, + ul: ul, + video: video +}; + +var require$$1$1 = { + "CSS_DISPLAY_TAGS": { + "area": "none", + "base": "none", + "basefont": "none", + "datalist": "none", + "head": "none", + "link": "none", + "meta": "none", + "noembed": "none", + "noframes": "none", + "param": "block", + "rp": "none", + "script": "block", + "source": "block", + "style": "none", + "template": "inline", + "track": "block", + "title": "none", + "html": "block", + "body": "block", + "address": "block", + "blockquote": "block", + "center": "block", + "div": "block", + "figure": "block", + "figcaption": "block", + "footer": "block", + "form": "block", + "header": "block", + "hr": "block", + "legend": "block", + "listing": "block", + "main": "block", + "p": "block", + "plaintext": "block", + "pre": "block", + "xmp": "block", + "slot": "contents", + "ruby": "ruby", + "rt": "ruby-text", + "article": "block", + "aside": "block", + "h1": "block", + "h2": "block", + "h3": "block", + "h4": "block", + "h5": "block", + "h6": "block", + "hgroup": "block", + "nav": "block", + "section": "block", + "dir": "block", + "dd": "block", + "dl": "block", + "dt": "block", + "ol": "block", + "ul": "block", + "li": "list-item", + "table": "table", + "caption": "table-caption", + "colgroup": "table-column-group", + "col": "table-column", + "thead": "table-header-group", + "tbody": "table-row-group", + "tfoot": "table-footer-group", + "tr": "table-row", + "td": "table-cell", + "th": "table-cell", + "fieldset": "block", + "button": "inline-block", + "details": "block", + "summary": "block", + "dialog": "block", + "meter": "inline-block", + "progress": "inline-block", + "object": "inline-block", + "video": "inline-block", + "audio": "inline-block", + "select": "inline-block", + "option": "block", + "optgroup": "block" + }, + "CSS_DISPLAY_DEFAULT": "inline", + "CSS_WHITE_SPACE_TAGS": { + "listing": "pre", + "plaintext": "pre", + "pre": "pre", + "xmp": "pre", + "nobr": "nowrap", + "table": "initial", + "textarea": "pre-wrap" + }, + "CSS_WHITE_SPACE_DEFAULT": "normal" +}; + +/** + * @typedef {import("../common/ast-path")} AstPath + */ + + +const { + inferParserByLanguage, + isFrontMatterNode +} = util$5; +const { + CSS_DISPLAY_TAGS, + CSS_DISPLAY_DEFAULT, + CSS_WHITE_SPACE_TAGS, + CSS_WHITE_SPACE_DEFAULT +} = require$$1$1; +const HTML_TAGS = arrayToMap(htmlTagNames); +const HTML_ELEMENT_ATTRIBUTES = mapObject(htmlElementAttributes, arrayToMap); // https://infra.spec.whatwg.org/#ascii-whitespace + +const HTML_WHITESPACE = new Set(["\t", "\n", "\f", "\r", " "]); + +const htmlTrimStart = string => string.replace(/^[\t\n\f\r ]+/, ""); + +const htmlTrimEnd = string => string.replace(/[\t\n\f\r ]+$/, ""); + +const htmlTrim$1 = string => htmlTrimStart(htmlTrimEnd(string)); + +const htmlTrimLeadingBlankLines = string => string.replace(/^[\t\f\r ]*?\n/g, ""); + +const htmlTrimPreserveIndentation$1 = string => htmlTrimLeadingBlankLines(htmlTrimEnd(string)); + +const splitByHtmlWhitespace$1 = string => string.split(/[\t\n\f\r ]+/); + +const getLeadingHtmlWhitespace = string => string.match(/^[\t\n\f\r ]*/)[0]; + +const getLeadingAndTrailingHtmlWhitespace$1 = string => { + const [, leadingWhitespace, text, trailingWhitespace] = string.match(/^([\t\n\f\r ]*)(.*?)([\t\n\f\r ]*)$/s); + return { + leadingWhitespace, + trailingWhitespace, + text + }; +}; + +const hasHtmlWhitespace$1 = string => /[\t\n\f\r ]/.test(string); + +function arrayToMap(array) { + const map = Object.create(null); + + for (const value of array) { + map[value] = true; + } + + return map; +} + +function mapObject(object, fn) { + const newObject = Object.create(null); + + for (const [key, value] of Object.entries(object)) { + newObject[key] = fn(value, key); + } + + return newObject; +} + +function shouldPreserveContent$1(node, options) { + // unterminated node in ie conditional comment + // e.g. + if (node.type === "ieConditionalComment" && node.lastChild && !node.lastChild.isSelfClosing && !node.lastChild.endSourceSpan) { + return true; + } // incomplete html in ie conditional comment + // e.g. + + + if (node.type === "ieConditionalComment" && !node.complete) { + return true; + } // TODO: handle non-text children in
+
+
+  if (isPreLikeNode$1(node) && node.children.some(child => child.type !== "text" && child.type !== "interpolation")) {
+    return true;
+  }
+
+  if (isVueNonHtmlBlock$1(node, options) && !isScriptLikeTag$1(node) && node.type !== "interpolation") {
+    return true;
+  }
+
+  return false;
+}
+
+function hasPrettierIgnore$3(node) {
+  /* istanbul ignore next */
+  if (node.type === "attribute") {
+    return false;
+  }
+  /* istanbul ignore next */
+
+
+  if (!node.parent) {
+    return false;
+  }
+
+  if (typeof node.index !== "number" || node.index === 0) {
+    return false;
+  }
+
+  const prevNode = node.parent.children[node.index - 1];
+  return isPrettierIgnore$1(prevNode);
+}
+
+function isPrettierIgnore$1(node) {
+  return node.type === "comment" && node.value.trim() === "prettier-ignore";
+}
+
+function getPrettierIgnoreAttributeCommentData$1(value) {
+  const match = value.trim().match(/^prettier-ignore-attribute(?:\s+(.+))?$/s);
+
+  if (!match) {
+    return false;
+  }
+
+  if (!match[1]) {
+    return true;
+  }
+
+  return match[1].split(/\s+/);
+}
+/** there's no opening/closing tag or it's considered not breakable */
+
+
+function isTextLikeNode$1(node) {
+  return node.type === "text" || node.type === "comment";
+}
+
+function isScriptLikeTag$1(node) {
+  return node.type === "element" && (node.fullName === "script" || node.fullName === "style" || node.fullName === "svg:style" || isUnknownNamespace(node) && (node.name === "script" || node.name === "style"));
+}
+
+function canHaveInterpolation$1(node) {
+  return node.children && !isScriptLikeTag$1(node);
+}
+
+function isWhitespaceSensitiveNode$1(node) {
+  return isScriptLikeTag$1(node) || node.type === "interpolation" || isIndentationSensitiveNode$1(node);
+}
+
+function isIndentationSensitiveNode$1(node) {
+  return getNodeCssStyleWhiteSpace(node).startsWith("pre");
+}
+
+function isLeadingSpaceSensitiveNode$1(node, options) {
+  const isLeadingSpaceSensitive = _isLeadingSpaceSensitiveNode();
+
+  if (isLeadingSpaceSensitive && !node.prev && node.parent && node.parent.tagDefinition && node.parent.tagDefinition.ignoreFirstLf) {
+    return node.type === "interpolation";
+  }
+
+  return isLeadingSpaceSensitive;
+
+  function _isLeadingSpaceSensitiveNode() {
+    if (isFrontMatterNode(node)) {
+      return false;
+    }
+
+    if ((node.type === "text" || node.type === "interpolation") && node.prev && (node.prev.type === "text" || node.prev.type === "interpolation")) {
+      return true;
+    }
+
+    if (!node.parent || node.parent.cssDisplay === "none") {
+      return false;
+    }
+
+    if (isPreLikeNode$1(node.parent)) {
+      return true;
+    }
+
+    if (!node.prev && (node.parent.type === "root" || isPreLikeNode$1(node) && node.parent || isScriptLikeTag$1(node.parent) || isVueCustomBlock$1(node.parent, options) || !isFirstChildLeadingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
+      return false;
+    }
+
+    if (node.prev && !isNextLeadingSpaceSensitiveCssDisplay(node.prev.cssDisplay)) {
+      return false;
+    }
+
+    return true;
+  }
+}
+
+function isTrailingSpaceSensitiveNode$1(node, options) {
+  if (isFrontMatterNode(node)) {
+    return false;
+  }
+
+  if ((node.type === "text" || node.type === "interpolation") && node.next && (node.next.type === "text" || node.next.type === "interpolation")) {
+    return true;
+  }
+
+  if (!node.parent || node.parent.cssDisplay === "none") {
+    return false;
+  }
+
+  if (isPreLikeNode$1(node.parent)) {
+    return true;
+  }
+
+  if (!node.next && (node.parent.type === "root" || isPreLikeNode$1(node) && node.parent || isScriptLikeTag$1(node.parent) || isVueCustomBlock$1(node.parent, options) || !isLastChildTrailingSpaceSensitiveCssDisplay(node.parent.cssDisplay))) {
+    return false;
+  }
+
+  if (node.next && !isPrevTrailingSpaceSensitiveCssDisplay(node.next.cssDisplay)) {
+    return false;
+  }
+
+  return true;
+}
+
+function isDanglingSpaceSensitiveNode$1(node) {
+  return isDanglingSpaceSensitiveCssDisplay(node.cssDisplay) && !isScriptLikeTag$1(node);
+}
+
+function forceNextEmptyLine$1(node) {
+  return isFrontMatterNode(node) || node.next && node.sourceSpan.end && node.sourceSpan.end.line + 1 < node.next.sourceSpan.start.line;
+}
+/** firstChild leadingSpaces and lastChild trailingSpaces */
+
+
+function forceBreakContent$1(node) {
+  return forceBreakChildren$1(node) || node.type === "element" && node.children.length > 0 && (["body", "script", "style"].includes(node.name) || node.children.some(child => hasNonTextChild(child))) || node.firstChild && node.firstChild === node.lastChild && node.firstChild.type !== "text" && hasLeadingLineBreak(node.firstChild) && (!node.lastChild.isTrailingSpaceSensitive || hasTrailingLineBreak(node.lastChild));
+}
+/** spaces between children */
+
+
+function forceBreakChildren$1(node) {
+  return node.type === "element" && node.children.length > 0 && (["html", "head", "ul", "ol", "select"].includes(node.name) || node.cssDisplay.startsWith("table") && node.cssDisplay !== "table-cell");
+}
+
+function preferHardlineAsLeadingSpaces$1(node) {
+  return preferHardlineAsSurroundingSpaces(node) || node.prev && preferHardlineAsTrailingSpaces(node.prev) || hasSurroundingLineBreak(node);
+}
+
+function preferHardlineAsTrailingSpaces(node) {
+  return preferHardlineAsSurroundingSpaces(node) || node.type === "element" && node.fullName === "br" || hasSurroundingLineBreak(node);
+}
+
+function hasSurroundingLineBreak(node) {
+  return hasLeadingLineBreak(node) && hasTrailingLineBreak(node);
+}
+
+function hasLeadingLineBreak(node) {
+  return node.hasLeadingSpaces && (node.prev ? node.prev.sourceSpan.end.line < node.sourceSpan.start.line : node.parent.type === "root" || node.parent.startSourceSpan.end.line < node.sourceSpan.start.line);
+}
+
+function hasTrailingLineBreak(node) {
+  return node.hasTrailingSpaces && (node.next ? node.next.sourceSpan.start.line > node.sourceSpan.end.line : node.parent.type === "root" || node.parent.endSourceSpan && node.parent.endSourceSpan.start.line > node.sourceSpan.end.line);
+}
+
+function preferHardlineAsSurroundingSpaces(node) {
+  switch (node.type) {
+    case "ieConditionalComment":
+    case "comment":
+    case "directive":
+      return true;
+
+    case "element":
+      return ["script", "select"].includes(node.name);
+  }
+
+  return false;
+}
+
+function getLastDescendant$1(node) {
+  return node.lastChild ? getLastDescendant$1(node.lastChild) : node;
+}
+
+function hasNonTextChild(node) {
+  return node.children && node.children.some(child => child.type !== "text");
+}
+
+function _inferScriptParser(node) {
+  const {
+    type,
+    lang
+  } = node.attrMap;
+
+  if (type === "module" || type === "text/javascript" || type === "text/babel" || type === "application/javascript" || lang === "jsx") {
+    return "babel";
+  }
+
+  if (type === "application/x-typescript" || lang === "ts" || lang === "tsx") {
+    return "typescript";
+  }
+
+  if (type === "text/markdown") {
+    return "markdown";
+  }
+
+  if (type === "text/html") {
+    return "html";
+  }
+
+  if (type && (type.endsWith("json") || type.endsWith("importmap"))) {
+    return "json";
+  }
+
+  if (type === "text/x-handlebars-template") {
+    return "glimmer";
+  }
+}
+
+function inferStyleParser(node) {
+  const {
+    lang
+  } = node.attrMap;
+
+  if (!lang || lang === "postcss" || lang === "css") {
+    return "css";
+  }
+
+  if (lang === "scss") {
+    return "scss";
+  }
+
+  if (lang === "less") {
+    return "less";
+  }
+}
+
+function inferScriptParser$1(node, options) {
+  if (node.name === "script" && !node.attrMap.src) {
+    if (!node.attrMap.lang && !node.attrMap.type) {
+      return "babel";
+    }
+
+    return _inferScriptParser(node);
+  }
+
+  if (node.name === "style") {
+    return inferStyleParser(node);
+  }
+
+  if (options && isVueNonHtmlBlock$1(node, options)) {
+    return _inferScriptParser(node) || !("src" in node.attrMap) && inferParserByLanguage(node.attrMap.lang, options);
+  }
+}
+
+function isBlockLikeCssDisplay(cssDisplay) {
+  return cssDisplay === "block" || cssDisplay === "list-item" || cssDisplay.startsWith("table");
+}
+
+function isFirstChildLeadingSpaceSensitiveCssDisplay(cssDisplay) {
+  return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
+}
+
+function isLastChildTrailingSpaceSensitiveCssDisplay(cssDisplay) {
+  return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
+}
+
+function isPrevTrailingSpaceSensitiveCssDisplay(cssDisplay) {
+  return !isBlockLikeCssDisplay(cssDisplay);
+}
+
+function isNextLeadingSpaceSensitiveCssDisplay(cssDisplay) {
+  return !isBlockLikeCssDisplay(cssDisplay);
+}
+
+function isDanglingSpaceSensitiveCssDisplay(cssDisplay) {
+  return !isBlockLikeCssDisplay(cssDisplay) && cssDisplay !== "inline-block";
+}
+
+function isPreLikeNode$1(node) {
+  return getNodeCssStyleWhiteSpace(node).startsWith("pre");
+}
+/**
+ * @param {AstPath} path
+ * @param {(any) => boolean} predicate
+ */
+
+
+function countParents$1(path, predicate) {
+  let counter = 0;
+
+  for (let i = path.stack.length - 1; i >= 0; i--) {
+    const value = path.stack[i];
+
+    if (value && typeof value === "object" && !Array.isArray(value) && predicate(value)) {
+      counter++;
+    }
+  }
+
+  return counter;
+}
+
+function hasParent(node, fn) {
+  let current = node;
+
+  while (current) {
+    if (fn(current)) {
+      return true;
+    }
+
+    current = current.parent;
+  }
+
+  return false;
+}
+
+function getNodeCssStyleDisplay$1(node, options) {
+  if (node.prev && node.prev.type === "comment") {
+    // 
+    const match = node.prev.value.match(/^\s*display:\s*([a-z]+)\s*$/);
+
+    if (match) {
+      return match[1];
+    }
+  }
+
+  let isInSvgForeignObject = false;
+
+  if (node.type === "element" && node.namespace === "svg") {
+    if (hasParent(node, parent => parent.fullName === "svg:foreignObject")) {
+      isInSvgForeignObject = true;
+    } else {
+      return node.name === "svg" ? "inline-block" : "block";
+    }
+  }
+
+  switch (options.htmlWhitespaceSensitivity) {
+    case "strict":
+      return "inline";
+
+    case "ignore":
+      return "block";
+
+    default:
+      {
+        // See https://github.com/prettier/prettier/issues/8151
+        if (options.parser === "vue" && node.parent && node.parent.type === "root") {
+          return "block";
+        }
+
+        return node.type === "element" && (!node.namespace || isInSvgForeignObject || isUnknownNamespace(node)) && CSS_DISPLAY_TAGS[node.name] || CSS_DISPLAY_DEFAULT;
+      }
+  }
+}
+
+function isUnknownNamespace(node) {
+  return node.type === "element" && !node.hasExplicitNamespace && !["html", "svg"].includes(node.namespace);
+}
+
+function getNodeCssStyleWhiteSpace(node) {
+  return node.type === "element" && (!node.namespace || isUnknownNamespace(node)) && CSS_WHITE_SPACE_TAGS[node.name] || CSS_WHITE_SPACE_DEFAULT;
+}
+
+function getMinIndentation(text) {
+  let minIndentation = Number.POSITIVE_INFINITY;
+
+  for (const lineText of text.split("\n")) {
+    if (lineText.length === 0) {
+      continue;
+    }
+
+    if (!HTML_WHITESPACE.has(lineText[0])) {
+      return 0;
+    }
+
+    const indentation = getLeadingHtmlWhitespace(lineText).length;
+
+    if (lineText.length === indentation) {
+      continue;
+    }
+
+    if (indentation < minIndentation) {
+      minIndentation = indentation;
+    }
+  }
+
+  return minIndentation === Number.POSITIVE_INFINITY ? 0 : minIndentation;
+}
+
+function dedentString$1(text, minIndent = getMinIndentation(text)) {
+  return minIndent === 0 ? text : text.split("\n").map(lineText => lineText.slice(minIndent)).join("\n");
+}
+
+function shouldNotPrintClosingTag$1(node, options) {
+  return !node.isSelfClosing && !node.endSourceSpan && (hasPrettierIgnore$3(node) || shouldPreserveContent$1(node.parent, options));
+}
+
+function countChars$1(text, char) {
+  let counter = 0;
+
+  for (let i = 0; i < text.length; i++) {
+    if (text[i] === char) {
+      counter++;
+    }
+  }
+
+  return counter;
+}
+
+function unescapeQuoteEntities$1(text) {
+  return text.replace(/'/g, "'").replace(/"/g, '"');
+} // top-level elements (excluding