diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml index a634d86..b43a356 100644 --- a/.github/workflows/format.yml +++ b/.github/workflows/format.yml @@ -30,17 +30,19 @@ jobs: git pull origin "${GITHUB_REF#refs/heads/}" fi - - name: Setup Node - uses: actions/setup-node@v3 - with: - node-version: "16" + # - name: Setup Node + # uses: actions/setup-node@v3 + # with: + # node-version: "16" - - name: Clean Install - run: | - if [ -d "node_modules" ]; then - rm -rf node_modules - fi - npm install + # - name: Clean Install + # run: | + # if [ -d "node_modules" ]; then + # rm -rf node_modules + # fi + # npm install + - name: Install Prettier + run: npm install -g prettier - name: Apply Prettier Foramtting run: npx prettier --write "**/*.java" diff --git a/node_modules/.bin/prettier b/node_modules/.bin/prettier new file mode 120000 index 0000000..92267ed --- /dev/null +++ b/node_modules/.bin/prettier @@ -0,0 +1 @@ +../prettier/bin/prettier.cjs \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..7d092c0 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,137 @@ +{ + "name": "2024-rewrite", + "version": "1.0.0", + "lockfileVersion": 2, + "requires": true, + "packages": { + "node_modules/@chevrotain/cst-dts-gen": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/cst-dts-gen/-/cst-dts-gen-11.0.3.tgz", + "integrity": "sha512-BvIKpRLeS/8UbfxXxgC33xOumsacaeCKAjAeLyOn7Pcp95HiRbrpl14S+9vaZLolnbssPIUuiUd8IvgkRyt6NQ==", + "dev": true, + "dependencies": { + "@chevrotain/gast": "11.0.3", + "@chevrotain/types": "11.0.3", + "lodash-es": "4.17.21" + } + }, + "node_modules/@chevrotain/gast": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/gast/-/gast-11.0.3.tgz", + "integrity": "sha512-+qNfcoNk70PyS/uxmj3li5NiECO+2YKZZQMbmjTqRI3Qchu8Hig/Q9vgkHpI3alNjr7M+a2St5pw5w5F6NL5/Q==", + "dev": true, + "dependencies": { + "@chevrotain/types": "11.0.3", + "lodash-es": "4.17.21" + } + }, + "node_modules/@chevrotain/regexp-to-ast": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/regexp-to-ast/-/regexp-to-ast-11.0.3.tgz", + "integrity": "sha512-1fMHaBZxLFvWI067AVbGJav1eRY7N8DDvYCTwGBiE/ytKBgP8azTdgyrKyWZ9Mfh09eHWb5PgTSO8wi7U824RA==", + "dev": true + }, + "node_modules/@chevrotain/types": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/types/-/types-11.0.3.tgz", + "integrity": "sha512-gsiM3G8b58kZC2HaWR50gu6Y1440cHiJ+i3JUvcp/35JchYejb2+5MVeJK0iKThYpAa/P2PYFV4hoi44HD+aHQ==", + "dev": true + }, + "node_modules/@chevrotain/utils": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/@chevrotain/utils/-/utils-11.0.3.tgz", + "integrity": "sha512-YslZMgtJUyuMbZ+aKvfF3x1f5liK4mWNxghFRv7jqRR9C3R3fAOGTTKvxXDa2Y1s9zSbcpuO0cAxDYsc9SrXoQ==", + "dev": true + }, + "node_modules/chevrotain": { + "version": "11.0.3", + "resolved": "https://registry.npmjs.org/chevrotain/-/chevrotain-11.0.3.tgz", + "integrity": "sha512-ci2iJH6LeIkvP9eJW6gpueU8cnZhv85ELY8w8WiFtNjMHA5ad6pQLaJo9mEly/9qUyCpvqX8/POVUTf18/HFdw==", + "dev": true, + "dependencies": { + "@chevrotain/cst-dts-gen": "11.0.3", + "@chevrotain/gast": "11.0.3", + "@chevrotain/regexp-to-ast": "11.0.3", + "@chevrotain/types": "11.0.3", + "@chevrotain/utils": "11.0.3", + "lodash-es": "4.17.21" + } + }, + "node_modules/chevrotain-allstar": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/chevrotain-allstar/-/chevrotain-allstar-0.3.1.tgz", + "integrity": "sha512-b7g+y9A0v4mxCW1qUhf3BSVPg+/NvGErk/dOkrDaHA0nQIQGAtrOjlX//9OQtRlSCy+x9rfB5N8yC71lH1nvMw==", + "dev": true, + "dependencies": { + "lodash-es": "^4.17.21" + }, + "peerDependencies": { + "chevrotain": "^11.0.0" + } + }, + "node_modules/java-parser": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/java-parser/-/java-parser-2.3.2.tgz", + "integrity": "sha512-/O42UbEHy3VVJw8W0ruHkQjW75oWvQx4QisoUDRIGir6q3/IZ4JslDMPMYEqp7LU56PYJkH5uXdQiBaCXt/Opw==", + "dev": true, + "dependencies": { + "chevrotain": "11.0.3", + "chevrotain-allstar": "0.3.1", + "lodash": "4.17.21" + } + }, + "node_modules/lodash": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", + "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", + "dev": true + }, + "node_modules/lodash-es": { + "version": "4.17.21", + "resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.17.21.tgz", + "integrity": "sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==", + "dev": true + }, + "node_modules/prettier": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.4.2.tgz", + "integrity": "sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ==", + "dev": true, + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + }, + "node_modules/prettier-plugin-java": { + "version": "2.6.5", + "resolved": "https://registry.npmjs.org/prettier-plugin-java/-/prettier-plugin-java-2.6.5.tgz", + "integrity": "sha512-2RkPNXyYpP5dRhr04pz45n+e5LXwYWTh1JXrztiCkZTGGokIGYrfwUuGa8csnDoGbP6CDPgVm8zZSIm/9I0SRQ==", + "dev": true, + "dependencies": { + "java-parser": "2.3.2", + "lodash": "4.17.21", + "prettier": "3.2.5" + } + }, + "node_modules/prettier-plugin-java/node_modules/prettier": { + "version": "3.2.5", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz", + "integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==", + "dev": true, + "bin": { + "prettier": "bin/prettier.cjs" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/prettier/prettier?sponsor=1" + } + } + } +} diff --git a/node_modules/@chevrotain/cst-dts-gen/LICENSE.txt b/node_modules/@chevrotain/cst-dts-gen/LICENSE.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@chevrotain/cst-dts-gen/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/cst-dts-gen/lib/src/api.d.ts b/node_modules/@chevrotain/cst-dts-gen/lib/src/api.d.ts new file mode 100644 index 0000000..2ff0320 --- /dev/null +++ b/node_modules/@chevrotain/cst-dts-gen/lib/src/api.d.ts @@ -0,0 +1,2 @@ +import { GenerateDtsOptions, Rule } from "@chevrotain/types"; +export declare function generateCstDts(productions: Record, options?: GenerateDtsOptions): string; diff --git a/node_modules/@chevrotain/cst-dts-gen/lib/src/api.js b/node_modules/@chevrotain/cst-dts-gen/lib/src/api.js new file mode 100644 index 0000000..9df31a6 --- /dev/null +++ b/node_modules/@chevrotain/cst-dts-gen/lib/src/api.js @@ -0,0 +1,12 @@ +import { buildModel } from "./model.js"; +import { genDts } from "./generate.js"; +const defaultOptions = { + includeVisitorInterface: true, + visitorInterfaceName: "ICstNodeVisitor", +}; +export function generateCstDts(productions, options) { + const effectiveOptions = Object.assign(Object.assign({}, defaultOptions), options); + const model = buildModel(productions); + return genDts(model, effectiveOptions); +} +//# sourceMappingURL=api.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/cst-dts-gen/lib/src/api.js.map b/node_modules/@chevrotain/cst-dts-gen/lib/src/api.js.map new file mode 100644 index 0000000..d0a2b9b --- /dev/null +++ b/node_modules/@chevrotain/cst-dts-gen/lib/src/api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/api.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAEvC,MAAM,cAAc,GAAiC;IACnD,uBAAuB,EAAE,IAAI;IAC7B,oBAAoB,EAAE,iBAAiB;CACxC,CAAC;AAEF,MAAM,UAAU,cAAc,CAC5B,WAAiC,EACjC,OAA4B;IAE5B,MAAM,gBAAgB,mCACjB,cAAc,GACd,OAAO,CACX,CAAC;IAEF,MAAM,KAAK,GAAG,UAAU,CAAC,WAAW,CAAC,CAAC;IAEtC,OAAO,MAAM,CAAC,KAAK,EAAE,gBAAgB,CAAC,CAAC;AACzC,CAAC"} \ No newline at end of file diff --git a/node_modules/@chevrotain/cst-dts-gen/lib/src/generate.d.ts b/node_modules/@chevrotain/cst-dts-gen/lib/src/generate.d.ts new file mode 100644 index 0000000..59b01c9 --- /dev/null +++ b/node_modules/@chevrotain/cst-dts-gen/lib/src/generate.d.ts @@ -0,0 +1,3 @@ +import { GenerateDtsOptions } from "@chevrotain/types"; +import { CstNodeTypeDefinition } from "./model.js"; +export declare function genDts(model: CstNodeTypeDefinition[], options: Required): string; diff --git a/node_modules/@chevrotain/cst-dts-gen/lib/src/generate.js b/node_modules/@chevrotain/cst-dts-gen/lib/src/generate.js new file mode 100644 index 0000000..e39b23e --- /dev/null +++ b/node_modules/@chevrotain/cst-dts-gen/lib/src/generate.js @@ -0,0 +1,65 @@ +import { flatten, isArray, map, reduce, uniq, upperFirst } from "lodash-es"; +export function genDts(model, options) { + let contentParts = []; + contentParts = contentParts.concat(`import type { CstNode, ICstVisitor, IToken } from "chevrotain";`); + contentParts = contentParts.concat(flatten(map(model, (node) => genCstNodeTypes(node)))); + if (options.includeVisitorInterface) { + contentParts = contentParts.concat(genVisitor(options.visitorInterfaceName, model)); + } + return contentParts.join("\n\n") + "\n"; +} +function genCstNodeTypes(node) { + const nodeCstInterface = genNodeInterface(node); + const nodeChildrenInterface = genNodeChildrenType(node); + return [nodeCstInterface, nodeChildrenInterface]; +} +function genNodeInterface(node) { + const nodeInterfaceName = getNodeInterfaceName(node.name); + const childrenTypeName = getNodeChildrenTypeName(node.name); + return `export interface ${nodeInterfaceName} extends CstNode { + name: "${node.name}"; + children: ${childrenTypeName}; +}`; +} +function genNodeChildrenType(node) { + const typeName = getNodeChildrenTypeName(node.name); + return `export type ${typeName} = { + ${map(node.properties, (property) => genChildProperty(property)).join("\n ")} +};`; +} +function genChildProperty(prop) { + const typeName = buildTypeString(prop.type); + return `${prop.name}${prop.optional ? "?" : ""}: ${typeName}[];`; +} +function genVisitor(name, nodes) { + return `export interface ${name} extends ICstVisitor { + ${map(nodes, (node) => genVisitorFunction(node)).join("\n ")} +}`; +} +function genVisitorFunction(node) { + const childrenTypeName = getNodeChildrenTypeName(node.name); + return `${node.name}(children: ${childrenTypeName}, param?: IN): OUT;`; +} +function buildTypeString(type) { + if (isArray(type)) { + const typeNames = uniq(map(type, (t) => getTypeString(t))); + const typeString = reduce(typeNames, (sum, t) => sum + " | " + t); + return "(" + typeString + ")"; + } + else { + return getTypeString(type); + } +} +function getTypeString(type) { + if (type.kind === "token") { + return "IToken"; + } + return getNodeInterfaceName(type.name); +} +function getNodeInterfaceName(ruleName) { + return upperFirst(ruleName) + "CstNode"; +} +function getNodeChildrenTypeName(ruleName) { + return upperFirst(ruleName) + "CstChildren"; +} +//# sourceMappingURL=generate.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/cst-dts-gen/lib/src/generate.js.map b/node_modules/@chevrotain/cst-dts-gen/lib/src/generate.js.map new file mode 100644 index 0000000..8bcce3d --- /dev/null +++ b/node_modules/@chevrotain/cst-dts-gen/lib/src/generate.js.map @@ -0,0 +1 @@ +{"version":3,"file":"generate.js","sourceRoot":"","sources":["../../src/generate.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAU5E,MAAM,UAAU,MAAM,CACpB,KAA8B,EAC9B,OAAqC;IAErC,IAAI,YAAY,GAAa,EAAE,CAAC;IAEhC,YAAY,GAAG,YAAY,CAAC,MAAM,CAChC,iEAAiE,CAClE,CAAC;IAEF,YAAY,GAAG,YAAY,CAAC,MAAM,CAChC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CACrD,CAAC;IAEF,IAAI,OAAO,CAAC,uBAAuB,EAAE;QACnC,YAAY,GAAG,YAAY,CAAC,MAAM,CAChC,UAAU,CAAC,OAAO,CAAC,oBAAoB,EAAE,KAAK,CAAC,CAChD,CAAC;KACH;IAED,OAAO,YAAY,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC;AAC1C,CAAC;AA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AC;AAED,SAAS,kBAAkB,CAAC,IAA2B;IACrD,MAAM,gBAAgB,GAAG,uBAAuB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC5D,OAAO,GAAG,IAAI,CAAC,IAAI,cAAc,gBAAgB,qBAAqB,CAAC;AACzE,CAAC;AAED,SAAS,eAAe,CAAC,IAAuB;IAC9C,IAAI,OAAO,CAAC,IAAI,CAAC,EAAE;QACjB,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;QAC3D,MAAM,UAAU,GAAG,MAAM,CAAC,SAAS,EAAE,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,KAAK,GAAG,CAAC,CAAC,CAAC;QAClE,OAAO,GAAG,GAAG,UAAU,GAAG,GAAG,CAAC;KAC/B;SAAM;QACL,OAAO,aAAa,CAAC,IAAI,CAAC,CAAC;KAC5B;AACH,CAAC;AAED,SAAS,aAAa,CAAC,IAAoC;IACzD,IAAI,IAAI,CAAC,IAAI,KAAK,OAAO,EAAE;QACzB,OAAO,QAAQ,CAAC;KACjB;IACD,OAAO,oBAAoB,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzC,CAAC;AAED,SAAS,oBAAoB,CAAC,QAAgB;IAC5C,OAAO,UAAU,CAAC,QAAQ,CAAC,GAAG,SAAS,CAAC;AAC1C,CAAC;AAED,SAAS,uBAAuB,CAAC,QAAgB;IAC/C,OAAO,UAAU,CAAC,QAAQ,CAAC,GAAG,aAAa,CAAC;AAC9C,CAAC"} \ No newline at end of file diff --git a/node_modules/@chevrotain/cst-dts-gen/lib/src/model.d.ts b/node_modules/@chevrotain/cst-dts-gen/lib/src/model.d.ts new file mode 100644 index 0000000..a1f3389 --- /dev/null +++ b/node_modules/@chevrotain/cst-dts-gen/lib/src/model.d.ts @@ -0,0 +1,19 @@ +import type { Rule } from "@chevrotain/types"; +export declare function buildModel(productions: Record): CstNodeTypeDefinition[]; +export type CstNodeTypeDefinition = { + name: string; + properties: PropertyTypeDefinition[]; +}; +export type PropertyTypeDefinition = { + name: string; + type: PropertyArrayType; + optional: boolean; +}; +export type PropertyArrayType = TokenArrayType | RuleArrayType | (TokenArrayType | RuleArrayType)[]; +export type TokenArrayType = { + kind: "token"; +}; +export type RuleArrayType = { + kind: "rule"; + name: string; +}; diff --git a/node_modules/@chevrotain/cst-dts-gen/lib/src/model.js b/node_modules/@chevrotain/cst-dts-gen/lib/src/model.js new file mode 100644 index 0000000..406ed50 --- /dev/null +++ b/node_modules/@chevrotain/cst-dts-gen/lib/src/model.js @@ -0,0 +1,96 @@ +import { GAstVisitor, NonTerminal } from "@chevrotain/gast"; +import { assign, flatten, groupBy, map, some, values } from "lodash-es"; +export function buildModel(productions) { + const generator = new CstNodeDefinitionGenerator(); + const allRules = values(productions); + return map(allRules, (rule) => generator.visitRule(rule)); +} +class CstNodeDefinitionGenerator extends GAstVisitor { + visitRule(node) { + const rawElements = this.visitEach(node.definition); + const grouped = groupBy(rawElements, (el) => el.propertyName); + const properties = map(grouped, (group, propertyName) => { + const allNullable = !some(group, (el) => !el.canBeNull); + // In an alternation with a label a property name can have + // multiple types. + let propertyType = group[0].type; + if (group.length > 1) { + propertyType = map(group, (g) => g.type); + } + return { + name: propertyName, + type: propertyType, + optional: allNullable, + }; + }); + return { + name: node.name, + properties: properties, + }; + } + visitAlternative(node) { + return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); + } + visitOption(node) { + return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); + } + visitRepetition(node) { + return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); + } + visitRepetitionMandatory(node) { + return this.visitEach(node.definition); + } + visitRepetitionMandatoryWithSeparator(node) { + return this.visitEach(node.definition).concat({ + propertyName: node.separator.name, + canBeNull: true, + type: getType(node.separator), + }); + } + visitRepetitionWithSeparator(node) { + return this.visitEachAndOverrideWith(node.definition, { + canBeNull: true, + }).concat({ + propertyName: node.separator.name, + canBeNull: true, + type: getType(node.separator), + }); + } + visitAlternation(node) { + return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); + } + visitTerminal(node) { + return [ + { + propertyName: node.label || node.terminalType.name, + canBeNull: false, + type: getType(node), + }, + ]; + } + visitNonTerminal(node) { + return [ + { + propertyName: node.label || node.nonTerminalName, + canBeNull: false, + type: getType(node), + }, + ]; + } + visitEachAndOverrideWith(definition, override) { + return map(this.visitEach(definition), (definition) => assign({}, definition, override)); + } + visitEach(definition) { + return flatten(map(definition, (definition) => this.visit(definition))); + } +} +function getType(production) { + if (production instanceof NonTerminal) { + return { + kind: "rule", + name: production.referencedRule.name, + }; + } + return { kind: "token" }; +} +//# sourceMappingURL=model.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/cst-dts-gen/lib/src/model.js.map b/node_modules/@chevrotain/cst-dts-gen/lib/src/model.js.map new file mode 100644 index 0000000..72886ad --- /dev/null +++ b/node_modules/@chevrotain/cst-dts-gen/lib/src/model.js.map @@ -0,0 +1 @@ +{"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/model.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC5D,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,WAAW,CAAC;AAExE,MAAM,UAAU,UAAU,CACxB,WAAiC;IAEjC,MAAM,SAAS,GAAG,IAAI,0BAA0B,EAAE,CAAC;IACnD,MAAM,QAAQ,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;IACrC,OAAO,GAAG,CAAC,QAAQ,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;AAC5D,CAAC;AAwBD,MAAM,0BAA2B,SAAQ,WAAW;IAClD,SAA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IAAI,EAAE,OAAO,CAAC,IAAI,CAAC;aACpB;SACF,CAAC;IACJ,CAAC;IAEO,wBAAwB,CAC9B,UAAyB,EACzB,QAAuC;QAEvC,OAAO,GAAG,CACR,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,EAC1B,CAAC,UAAU,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,EAAE,UAAU,EAAE,QAAQ,CAAyB,CACzE,CAAC;IACJ,CAAC;IAEO,SAAS,CAAC,UAAyB;QACzC,OAAO,OAAO,CACZ,GAAG,CACD,UAAU,EACV,CAAC,UAAU,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,UAAU,CAA2B,CACjE,CACF,CAAC;IACJ,CAAC;CACF;AAQD,SAAS,OAAO,CACd,UAA8C;IAE9C,IAAI,UAAU,YAAY,WAAW,EAAE;QACrC,OAAO;YACL,IAAI,EAAE,MAAM;YACZ,IAAI,EAAE,UAAU,CAAC,cAAc,CAAC,IAAI;SACrC,CAAC;KACH;IAED,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;AAC3B,CAAC"} \ No newline at end of file diff --git a/node_modules/@chevrotain/cst-dts-gen/package.json b/node_modules/@chevrotain/cst-dts-gen/package.json new file mode 100644 index 0000000..205b4e5 --- /dev/null +++ b/node_modules/@chevrotain/cst-dts-gen/package.json @@ -0,0 +1,50 @@ +{ + "name": "@chevrotain/cst-dts-gen", + "version": "11.0.3", + "description": "Generates type definitions for Chevrotain CST nodes", + "keywords": [], + "bugs": { + "url": "https://github.com/Chevrotain/chevrotain/issues" + }, + "license": "Apache-2.0", + "type": "module", + "types": "./lib/src/api.d.ts", + "exports": { + ".": { + "import": "./lib/src/api.js", + "types": "./lib/src/api.d.ts" + } + }, + "files": [ + "lib/src/**/*.js", + "lib/src/**/*.map", + "lib/src/**/*.d.ts", + "src/**/*.ts" + ], + "repository": { + "type": "git", + "url": "git://github.com/Chevrotain/chevrotain.git" + }, + "scripts": { + "---------- CI FLOWS --------": "", + "ci": "pnpm run build test", + "build": "npm-run-all clean compile", + "test": "echo \"tests are in a different package\"", + "---------- BUILD STEPS --------": "", + "clean": "shx rm -rf lib", + "compile:watch": "tsc -w", + "compile": "tsc" + }, + "dependencies": { + "@chevrotain/gast": "11.0.3", + "@chevrotain/types": "11.0.3", + "lodash-es": "4.17.21" + }, + "devDependencies": { + "@types/lodash-es": "4.17.7" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "ac5806631779035c2c1955744a47d8ed4f25a175" +} diff --git a/node_modules/@chevrotain/cst-dts-gen/src/api.ts b/node_modules/@chevrotain/cst-dts-gen/src/api.ts new file mode 100644 index 0000000..c5023cc --- /dev/null +++ b/node_modules/@chevrotain/cst-dts-gen/src/api.ts @@ -0,0 +1,22 @@ +import { GenerateDtsOptions, Rule } from "@chevrotain/types"; +import { buildModel } from "./model.js"; +import { genDts } from "./generate.js"; + +const defaultOptions: Required = { + includeVisitorInterface: true, + visitorInterfaceName: "ICstNodeVisitor", +}; + +export function generateCstDts( + productions: Record, + options?: GenerateDtsOptions, +): string { + const effectiveOptions = { + ...defaultOptions, + ...options, + }; + + const model = buildModel(productions); + + return genDts(model, effectiveOptions); +} diff --git a/node_modules/@chevrotain/cst-dts-gen/src/generate.ts b/node_modules/@chevrotain/cst-dts-gen/src/generate.ts new file mode 100644 index 0000000..f7dc206 --- /dev/null +++ b/node_modules/@chevrotain/cst-dts-gen/src/generate.ts @@ -0,0 +1,98 @@ +import { flatten, isArray, map, reduce, uniq, upperFirst } from "lodash-es"; +import { GenerateDtsOptions } from "@chevrotain/types"; +import { + CstNodeTypeDefinition, + PropertyArrayType, + PropertyTypeDefinition, + RuleArrayType, + TokenArrayType, +} from "./model.js"; + +export function genDts( + model: CstNodeTypeDefinition[], + options: Required, +): string { + let contentParts: string[] = []; + + contentParts = contentParts.concat( + `import type { CstNode, ICstVisitor, IToken } from "chevrotain";`, + ); + + contentParts = contentParts.concat( + flatten(map(model, (node) => genCstNodeTypes(node))), + ); + + if (options.includeVisitorInterface) { + contentParts = contentParts.concat( + genVisitor(options.visitorInterfaceName, model), + ); + } + + return contentParts.join("\n\n") + "\n"; +} + +function genCstNodeTypes(node: CstNodeTypeDefinition) { + const nodeCstInterface = genNodeInterface(node); + const nodeChildrenInterface = genNodeChildrenType(node); + + return [nodeCstInterface, nodeChildrenInterface]; +} + +function genNodeInterface(node: CstNodeTypeDefinition) { + const nodeInterfaceName = getNodeInterfaceName(node.name); + const childrenTypeName = getNodeChildrenTypeName(node.name); + + return `export interface ${nodeInterfaceName} extends CstNode { + name: "${node.name}"; + children: ${childrenTypeName}; +}`; +} + +function genNodeChildrenType(node: CstNodeTypeDefinition) { + const typeName = getNodeChildrenTypeName(node.name); + + return `export type ${typeName} = { + ${map(node.properties, (property) => genChildProperty(property)).join("\n ")} +};`; +} + +function genChildProperty(prop: PropertyTypeDefinition) { + const typeName = buildTypeString(prop.type); + return `${prop.name}${prop.optional ? "?" : ""}: ${typeName}[];`; +} + +function genVisitor(name: string, nodes: CstNodeTypeDefinition[]) { + return `export interface ${name} extends ICstVisitor { + ${map(nodes, (node) => genVisitorFunction(node)).join("\n ")} +}`; +} + +function genVisitorFunction(node: CstNodeTypeDefinition) { + const childrenTypeName = getNodeChildrenTypeName(node.name); + return `${node.name}(children: ${childrenTypeName}, param?: IN): OUT;`; +} + +function buildTypeString(type: PropertyArrayType) { + if (isArray(type)) { + const typeNames = uniq(map(type, (t) => getTypeString(t))); + const typeString = reduce(typeNames, (sum, t) => sum + " | " + t); + return "(" + typeString + ")"; + } else { + return getTypeString(type); + } +} + +function getTypeString(type: TokenArrayType | RuleArrayType) { + if (type.kind === "token") { + return "IToken"; + } + return getNodeInterfaceName(type.name); +} + +function getNodeInterfaceName(ruleName: string) { + return upperFirst(ruleName) + "CstNode"; +} + +function getNodeChildrenTypeName(ruleName: string) { + return upperFirst(ruleName) + "CstChildren"; +} diff --git a/node_modules/@chevrotain/cst-dts-gen/src/model.ts b/node_modules/@chevrotain/cst-dts-gen/src/model.ts new file mode 100644 index 0000000..47f48e9 --- /dev/null +++ b/node_modules/@chevrotain/cst-dts-gen/src/model.ts @@ -0,0 +1,172 @@ +import type { + Alternation, + Alternative, + IProduction, + Option, + Repetition, + RepetitionMandatory, + RepetitionMandatoryWithSeparator, + RepetitionWithSeparator, + Rule, + Terminal, + TokenType, +} from "@chevrotain/types"; +import { GAstVisitor, NonTerminal } from "@chevrotain/gast"; +import { assign, flatten, groupBy, map, some, values } from "lodash-es"; + +export function buildModel( + productions: Record, +): CstNodeTypeDefinition[] { + const generator = new CstNodeDefinitionGenerator(); + const allRules = values(productions); + return map(allRules, (rule) => generator.visitRule(rule)); +} + +export type CstNodeTypeDefinition = { + name: string; + properties: PropertyTypeDefinition[]; +}; + +export type PropertyTypeDefinition = { + name: string; + type: PropertyArrayType; + optional: boolean; +}; + +export type PropertyArrayType = + | TokenArrayType + | RuleArrayType + | (TokenArrayType | RuleArrayType)[]; + +export type TokenArrayType = { kind: "token" }; +export type RuleArrayType = { + kind: "rule"; + name: string; +}; + +class CstNodeDefinitionGenerator extends GAstVisitor { + visitRule(node: Rule): CstNodeTypeDefinition { + const rawElements = this.visitEach(node.definition); + + const grouped = groupBy(rawElements, (el) => el.propertyName); + const properties = map(grouped, (group, propertyName) => { + const allNullable = !some(group, (el) => !el.canBeNull); + + // In an alternation with a label a property name can have + // multiple types. + let propertyType: PropertyArrayType = group[0].type; + if (group.length > 1) { + propertyType = map(group, (g) => g.type); + } + + return { + name: propertyName, + type: propertyType, + optional: allNullable, + } as PropertyTypeDefinition; + }); + + return { + name: node.name, + properties: properties, + }; + } + + visitAlternative(node: Alternative) { + return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); + } + + visitOption(node: Option) { + return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); + } + + visitRepetition(node: Repetition) { + return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); + } + + visitRepetitionMandatory(node: RepetitionMandatory) { + return this.visitEach(node.definition); + } + + visitRepetitionMandatoryWithSeparator( + node: RepetitionMandatoryWithSeparator, + ) { + return this.visitEach(node.definition).concat({ + propertyName: node.separator.name, + canBeNull: true, + type: getType(node.separator), + }); + } + + visitRepetitionWithSeparator(node: RepetitionWithSeparator) { + return this.visitEachAndOverrideWith(node.definition, { + canBeNull: true, + }).concat({ + propertyName: node.separator.name, + canBeNull: true, + type: getType(node.separator), + }); + } + + visitAlternation(node: Alternation) { + return this.visitEachAndOverrideWith(node.definition, { canBeNull: true }); + } + + visitTerminal(node: Terminal): PropertyTupleElement[] { + return [ + { + propertyName: node.label || node.terminalType.name, + canBeNull: false, + type: getType(node), + }, + ]; + } + + visitNonTerminal(node: NonTerminal): PropertyTupleElement[] { + return [ + { + propertyName: node.label || node.nonTerminalName, + canBeNull: false, + type: getType(node), + }, + ]; + } + + private visitEachAndOverrideWith( + definition: IProduction[], + override: Partial, + ) { + return map( + this.visitEach(definition), + (definition) => assign({}, definition, override) as PropertyTupleElement, + ); + } + + private visitEach(definition: IProduction[]) { + return flatten( + map( + definition, + (definition) => this.visit(definition) as PropertyTupleElement[], + ), + ); + } +} + +type PropertyTupleElement = { + propertyName: string; + canBeNull: boolean; + type: TokenArrayType | RuleArrayType; +}; + +function getType( + production: Terminal | NonTerminal | TokenType, +): TokenArrayType | RuleArrayType { + if (production instanceof NonTerminal) { + return { + kind: "rule", + name: production.referencedRule.name, + }; + } + + return { kind: "token" }; +} diff --git a/node_modules/@chevrotain/gast/LICENSE.txt b/node_modules/@chevrotain/gast/LICENSE.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@chevrotain/gast/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/gast/lib/src/api.d.ts b/node_modules/@chevrotain/gast/lib/src/api.d.ts new file mode 100644 index 0000000..7b6631f --- /dev/null +++ b/node_modules/@chevrotain/gast/lib/src/api.d.ts @@ -0,0 +1,3 @@ +export { Rule, Terminal, NonTerminal, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Alternation, Alternative, serializeGrammar, serializeProduction, } from "./model.js"; +export { GAstVisitor } from "./visitor.js"; +export { getProductionDslName, isOptionalProd, isBranchingProd, isSequenceProd, } from "./helpers.js"; diff --git a/node_modules/@chevrotain/gast/lib/src/api.js b/node_modules/@chevrotain/gast/lib/src/api.js new file mode 100644 index 0000000..ef6232b --- /dev/null +++ b/node_modules/@chevrotain/gast/lib/src/api.js @@ -0,0 +1,4 @@ +export { Rule, Terminal, NonTerminal, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Alternation, Alternative, serializeGrammar, serializeProduction, } from "./model.js"; +export { GAstVisitor } from "./visitor.js"; +export { getProductionDslName, isOptionalProd, isBranchingProd, isSequenceProd, } from "./helpers.js"; +//# sourceMappingURL=api.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/gast/lib/src/api.js.map b/node_modules/@chevrotain/gast/lib/src/api.js.map new file mode 100644 index 0000000..d2187ae --- /dev/null +++ b/node_modules/@chevrotain/gast/lib/src/api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,IAAI,EACJ,QAAQ,EACR,WAAW,EACX,MAAM,EACN,UAAU,EACV,mBAAmB,EACnB,gCAAgC,EAChC,uBAAuB,EACvB,WAAW,EACX,WAAW,EACX,gBAAgB,EAChB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,OAAO,EACL,oBAAoB,EACpB,cAAc,EACd,eAAe,EACf,cAAc,GACf,MAAM,cAAc,CAAC"} \ No newline at end of file diff --git a/node_modules/@chevrotain/gast/lib/src/helpers.d.ts b/node_modules/@chevrotain/gast/lib/src/helpers.d.ts new file mode 100644 index 0000000..f0e70ed --- /dev/null +++ b/node_modules/@chevrotain/gast/lib/src/helpers.d.ts @@ -0,0 +1,10 @@ +import { NonTerminal } from "./model.js"; +import type { IProduction, IProductionWithOccurrence } from "@chevrotain/types"; +export declare function isSequenceProd(prod: IProduction): prod is { + definition: IProduction[]; +} & IProduction; +export declare function isOptionalProd(prod: IProduction, alreadyVisited?: NonTerminal[]): boolean; +export declare function isBranchingProd(prod: IProduction): prod is { + definition: IProduction[]; +} & IProduction; +export declare function getProductionDslName(prod: IProductionWithOccurrence): string; diff --git a/node_modules/@chevrotain/gast/lib/src/helpers.js b/node_modules/@chevrotain/gast/lib/src/helpers.js new file mode 100644 index 0000000..62d1e4d --- /dev/null +++ b/node_modules/@chevrotain/gast/lib/src/helpers.js @@ -0,0 +1,79 @@ +import { every, includes, some } from "lodash-es"; +import { AbstractProduction, Alternation, Alternative, NonTerminal, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Rule, Terminal, } from "./model.js"; +export function isSequenceProd(prod) { + return (prod instanceof Alternative || + 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 = []) { + const 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, (subProd) => { + return isOptionalProd(subProd, alreadyVisited); + }); + } + else if (prod instanceof NonTerminal && includes(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, (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"; + /* c8 ignore next 3 */ + } + else { + throw Error("non exhaustive match"); + } +} +//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/gast/lib/src/helpers.js.map b/node_modules/@chevrotain/gast/lib/src/helpers.js.map new file mode 100644 index 0000000..c270325 --- /dev/null +++ b/node_modules/@chevrotain/gast/lib/src/helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"helpers.js","sourceRoot":"","sources":["../../src/helpers.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAClD,OAAO,EACL,kBAAkB,EAClB,WAAW,EACX,WAAW,EACX,WAAW,EACX,MAAM,EACN,UAAU,EACV,mBAAmB,EACnB,gCAAgC,EAChC,uBAAuB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C;KACd;AACH,CAAC;AAED,MAAM,UAAU,eAAe,CAC7B,IAAiB;IAEjB,OAAO,IAAI,YAAY,WAAW,CAAC;AACrC,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,IAA+B;IAClE,0BAA0B;IAC1B,IAAI,IAAI,YAAY,WAAW,EAAE;QAC/B,OAAO,SAAS,CAAC;KAClB;SAAM,IAAI,IAAI,YAAY,MAAM,EAAE;QACjC,OAAO,QAAQ,CAAC;KACjB;SAAM,IAAI,IAAI,YAAY,WAAW,EAAE;QACtC,OAAO,IAAI,CAAC;KACb;SAAM,IAAI,IAAI,YAAY,mBAAmB,EAAE;QAC9C,OAAO,cAAc,CAAC;KACvB;SAAM,IAAI,IAAI,YAAY,gCAAgC,EAAE;QAC3D,OAAO,kBAAkB,CAAC;KAC3B;SAAM,IAAI,IAAI,YAAY,uBAAuB,EAAE;QAClD,OAAO,UAAU,CAAC;KACnB;SAAM,IAAI,IAAI,YAAY,UAAU,EAAE;QACrC,OAAO,MAAM,CAAC;KACf;SAAM,IAAI,IAAI,YAAY,QAAQ,EAAE;QACnC,OAAO,SAAS,CAAC;QACjB,sBAAsB;KACvB;SAAM;QACL,MAAM,KAAK,CAAC,sBAAsB,CAAC,CAAC;KACrC;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/@chevrotain/gast/lib/src/model.d.ts b/node_modules/@chevrotain/gast/lib/src/model.d.ts new file mode 100644 index 0000000..80cd068 --- /dev/null +++ b/node_modules/@chevrotain/gast/lib/src/model.d.ts @@ -0,0 +1,144 @@ +import type { IGASTVisitor, IProduction, IProductionWithOccurrence, ISerializedGast, TokenType } from "@chevrotain/types"; +export declare abstract class AbstractProduction implements IProduction { + protected _definition: T[]; + get definition(): T[]; + set definition(value: T[]); + constructor(_definition: T[]); + accept(visitor: IGASTVisitor): void; +} +export declare class NonTerminal extends AbstractProduction implements IProductionWithOccurrence { + nonTerminalName: string; + label?: string; + referencedRule: Rule; + idx: number; + constructor(options: { + nonTerminalName: string; + label?: string; + referencedRule?: Rule; + idx?: number; + }); + set definition(definition: IProduction[]); + get definition(): IProduction[]; + accept(visitor: IGASTVisitor): void; +} +export declare class Rule extends AbstractProduction { + name: string; + orgText: string; + constructor(options: { + name: string; + definition: IProduction[]; + orgText?: string; + }); +} +export declare class Alternative extends AbstractProduction { + ignoreAmbiguities: boolean; + constructor(options: { + definition: IProduction[]; + ignoreAmbiguities?: boolean; + }); +} +export declare class Option extends AbstractProduction implements IProductionWithOccurrence { + idx: number; + maxLookahead?: number; + constructor(options: { + definition: IProduction[]; + idx?: number; + maxLookahead?: number; + }); +} +export declare class RepetitionMandatory extends AbstractProduction implements IProductionWithOccurrence { + idx: number; + maxLookahead?: number; + constructor(options: { + definition: IProduction[]; + idx?: number; + maxLookahead?: number; + }); +} +export declare class RepetitionMandatoryWithSeparator extends AbstractProduction implements IProductionWithOccurrence { + separator: TokenType; + idx: number; + maxLookahead?: number; + constructor(options: { + definition: IProduction[]; + separator: TokenType; + idx?: number; + }); +} +export declare class Repetition extends AbstractProduction implements IProductionWithOccurrence { + separator: TokenType; + idx: number; + maxLookahead?: number; + constructor(options: { + definition: IProduction[]; + idx?: number; + maxLookahead?: number; + }); +} +export declare class RepetitionWithSeparator extends AbstractProduction implements IProductionWithOccurrence { + separator: TokenType; + idx: number; + maxLookahead?: number; + constructor(options: { + definition: IProduction[]; + separator: TokenType; + idx?: number; + }); +} +export declare class Alternation extends AbstractProduction implements IProductionWithOccurrence { + idx: number; + ignoreAmbiguities: boolean; + hasPredicates: boolean; + maxLookahead?: number; + get definition(): Alternative[]; + set definition(value: Alternative[]); + constructor(options: { + definition: Alternative[]; + idx?: number; + ignoreAmbiguities?: boolean; + hasPredicates?: boolean; + maxLookahead?: number; + }); +} +export declare class Terminal implements IProductionWithOccurrence { + terminalType: TokenType; + label?: string; + idx: number; + constructor(options: { + terminalType: TokenType; + label?: string; + idx?: number; + }); + accept(visitor: IGASTVisitor): void; +} +export interface ISerializedBasic extends ISerializedGast { + type: "Alternative" | "Option" | "RepetitionMandatory" | "Repetition" | "Alternation"; + idx?: number; +} +export interface ISerializedGastRule extends ISerializedGast { + type: "Rule"; + name: string; + orgText: string; +} +export interface ISerializedNonTerminal extends ISerializedGast { + type: "NonTerminal"; + name: string; + label?: string; + idx: number; +} +export interface ISerializedTerminal extends ISerializedGast { + type: "Terminal"; + name: string; + terminalLabel?: string; + label?: string; + pattern?: string; + idx: number; +} +export interface ISerializedTerminalWithSeparator extends ISerializedGast { + type: "RepetitionMandatoryWithSeparator" | "RepetitionWithSeparator"; + idx: number; + separator: ISerializedTerminal; +} +export type ISerializedGastAny = ISerializedBasic | ISerializedGastRule | ISerializedNonTerminal | ISerializedTerminal | ISerializedTerminalWithSeparator; +export declare function serializeGrammar(topRules: Rule[]): ISerializedGast[]; +export declare function serializeProduction(node: IProduction): ISerializedGast; diff --git a/node_modules/@chevrotain/gast/lib/src/model.js b/node_modules/@chevrotain/gast/lib/src/model.js new file mode 100644 index 0000000..856c42a --- /dev/null +++ b/node_modules/@chevrotain/gast/lib/src/model.js @@ -0,0 +1,225 @@ +import { assign, forEach, isRegExp, isString, map, pickBy } from "lodash-es"; +// TODO: duplicated code to avoid extracting another sub-package -- how to avoid? +function tokenLabel(tokType) { + if (hasTokenLabel(tokType)) { + return tokType.LABEL; + } + else { + return tokType.name; + } +} +// TODO: duplicated code to avoid extracting another sub-package -- how to avoid? +function hasTokenLabel(obj) { + return isString(obj.LABEL) && obj.LABEL !== ""; +} +export class AbstractProduction { + get definition() { + return this._definition; + } + set definition(value) { + this._definition = value; + } + constructor(_definition) { + this._definition = _definition; + } + accept(visitor) { + visitor.visit(this); + forEach(this.definition, (prod) => { + prod.accept(visitor); + }); + } +} +export class NonTerminal extends AbstractProduction { + constructor(options) { + super([]); + this.idx = 1; + assign(this, pickBy(options, (v) => v !== undefined)); + } + set definition(definition) { + // immutable + } + get definition() { + if (this.referencedRule !== undefined) { + return this.referencedRule.definition; + } + return []; + } + accept(visitor) { + visitor.visit(this); + // don't visit children of a reference, we will get cyclic infinite loops if we do so + } +} +export class Rule extends AbstractProduction { + constructor(options) { + super(options.definition); + this.orgText = ""; + assign(this, pickBy(options, (v) => v !== undefined)); + } +} +export class Alternative extends AbstractProduction { + constructor(options) { + super(options.definition); + this.ignoreAmbiguities = false; + assign(this, pickBy(options, (v) => v !== undefined)); + } +} +export class Option extends AbstractProduction { + constructor(options) { + super(options.definition); + this.idx = 1; + assign(this, pickBy(options, (v) => v !== undefined)); + } +} +export class RepetitionMandatory extends AbstractProduction { + constructor(options) { + super(options.definition); + this.idx = 1; + assign(this, pickBy(options, (v) => v !== undefined)); + } +} +export class RepetitionMandatoryWithSeparator extends AbstractProduction { + constructor(options) { + super(options.definition); + this.idx = 1; + assign(this, pickBy(options, (v) => v !== undefined)); + } +} +export class Repetition extends AbstractProduction { + constructor(options) { + super(options.definition); + this.idx = 1; + assign(this, pickBy(options, (v) => v !== undefined)); + } +} +export class RepetitionWithSeparator extends AbstractProduction { + constructor(options) { + super(options.definition); + this.idx = 1; + assign(this, pickBy(options, (v) => v !== undefined)); + } +} +export class Alternation extends AbstractProduction { + get definition() { + return this._definition; + } + set definition(value) { + this._definition = value; + } + constructor(options) { + super(options.definition); + this.idx = 1; + this.ignoreAmbiguities = false; + this.hasPredicates = false; + assign(this, pickBy(options, (v) => v !== undefined)); + } +} +export class Terminal { + constructor(options) { + this.idx = 1; + assign(this, pickBy(options, (v) => v !== undefined)); + } + accept(visitor) { + visitor.visit(this); + } +} +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) { + const serializedNonTerminal = { + type: "NonTerminal", + name: node.nonTerminalName, + idx: node.idx, + }; + if (isString(node.label)) { + serializedNonTerminal.label = node.label; + } + return serializedNonTerminal; + } + else if (node instanceof Alternative) { + return { + type: "Alternative", + 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", + idx: node.idx, + definition: convertDefinition(node.definition), + }; + } + else if (node instanceof RepetitionMandatoryWithSeparator) { + return { + type: "RepetitionMandatoryWithSeparator", + idx: node.idx, + separator: (serializeProduction(new Terminal({ terminalType: node.separator }))), + definition: convertDefinition(node.definition), + }; + } + else if (node instanceof RepetitionWithSeparator) { + return { + type: "RepetitionWithSeparator", + idx: node.idx, + separator: (serializeProduction(new Terminal({ terminalType: node.separator }))), + definition: convertDefinition(node.definition), + }; + } + else if (node instanceof Repetition) { + return { + type: "Repetition", + idx: node.idx, + definition: convertDefinition(node.definition), + }; + } + else if (node instanceof Alternation) { + return { + type: "Alternation", + idx: node.idx, + definition: convertDefinition(node.definition), + }; + } + else if (node instanceof Terminal) { + const serializedTerminal = { + type: "Terminal", + name: node.terminalType.name, + label: tokenLabel(node.terminalType), + idx: node.idx, + }; + if (isString(node.label)) { + serializedTerminal.terminalLabel = node.label; + } + const 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), + }; + /* c8 ignore next 3 */ + } + else { + throw Error("non exhaustive match"); + } +} +//# sourceMappingURL=model.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/gast/lib/src/model.js.map b/node_modules/@chevrotain/gast/lib/src/model.js.map new file mode 100644 index 0000000..47e6fee --- /dev/null +++ b/node_modules/@chevrotain/gast/lib/src/model.js.map @@ -0,0 +1 @@ +{"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/model.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,WAAW,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/C,CAAC;KACH;SAAM,IAAI,IAAI,YAAY,QAAQ,EAAE;QACnC,MAAM,kBAAkB,GAAwB;YAC9C,IAAI,EAAE,UAAU;YAChB,IAAI,EAAE,IAAI,CAAC,YAAY,CAAC,IAAI;YAC5B,KAAK,EAAE,UAAU,CAAC,IAAI,CAAC,YAAY,CAAC;YACpC,GAAG,EAAE,IAAI,CAAC,GAAG;SACd,CAAC;QAEF,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;YACxB,kBAAkB,CAAC,aAAa,GAAG,IAAI,CAAC,KAAK,CAAC;SAC/C;QAED,MAAM,OAAO,GAAG,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC;QAC1C,IAAI,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE;YAC7B,kBAAkB,CAAC,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC;gBAC5C,CAAC,CAAO,OAAQ,CAAC,MAAM;gBACvB,CAAC,CAAC,OAAO,CAAC;SACb;QAED,OAAO,kBAAkB,CAAC;KAC3B;SAAM,IAAI,IAAI,YAAY,IAAI,EAAE;QAC/B,OAA4B;YAC1B,IAAI,EAAE,MAAM;YACZ,IAAI,EAAE,IAAI,CAAC,IAAI;YACf,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,UAAU,EAAE,iBAAiB,CAAC,IAAI,CAAC,UAAU,CAAC;SAC/C,CAAC;QACF,sBAAsB;KACvB;SAAM;QACL,MAAM,KAAK,CAAC,sBAAsB,CAAC,CAAC;KACrC;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/@chevrotain/gast/lib/src/visitor.d.ts b/node_modules/@chevrotain/gast/lib/src/visitor.d.ts new file mode 100644 index 0000000..41ec7d4 --- /dev/null +++ b/node_modules/@chevrotain/gast/lib/src/visitor.d.ts @@ -0,0 +1,15 @@ +import { Alternation, Alternative, NonTerminal, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Rule, Terminal } from "./model.js"; +import type { IProduction } from "@chevrotain/types"; +export declare abstract class GAstVisitor { + visit(node: IProduction): any; + visitNonTerminal(node: NonTerminal): any; + visitAlternative(node: Alternative): any; + visitOption(node: Option): any; + visitRepetition(node: Repetition): any; + visitRepetitionMandatory(node: RepetitionMandatory): any; + visitRepetitionMandatoryWithSeparator(node: RepetitionMandatoryWithSeparator): any; + visitRepetitionWithSeparator(node: RepetitionWithSeparator): any; + visitAlternation(node: Alternation): any; + visitTerminal(node: Terminal): any; + visitRule(node: Rule): any; +} diff --git a/node_modules/@chevrotain/gast/lib/src/visitor.js b/node_modules/@chevrotain/gast/lib/src/visitor.js new file mode 100644 index 0000000..1e95d89 --- /dev/null +++ b/node_modules/@chevrotain/gast/lib/src/visitor.js @@ -0,0 +1,52 @@ +import { Alternation, Alternative, NonTerminal, Option, Repetition, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Rule, Terminal, } from "./model.js"; +export class GAstVisitor { + visit(node) { + const nodeAny = node; + switch (nodeAny.constructor) { + case NonTerminal: + return this.visitNonTerminal(nodeAny); + case Alternative: + return this.visitAlternative(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); + /* c8 ignore next 2 */ + default: + throw Error("non exhaustive match"); + } + } + /* c8 ignore next */ + visitNonTerminal(node) { } + /* c8 ignore next */ + visitAlternative(node) { } + /* c8 ignore next */ + visitOption(node) { } + /* c8 ignore next */ + visitRepetition(node) { } + /* c8 ignore next */ + visitRepetitionMandatory(node) { } + /* c8 ignore next 3 */ + visitRepetitionMandatoryWithSeparator(node) { } + /* c8 ignore next */ + visitRepetitionWithSeparator(node) { } + /* c8 ignore next */ + visitAlternation(node) { } + /* c8 ignore next */ + visitTerminal(node) { } + /* c8 ignore next */ + visitRule(node) { } +} +//# sourceMappingURL=visitor.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/gast/lib/src/visitor.js.map b/node_modules/@chevrotain/gast/lib/src/visitor.js.map new file mode 100644 index 0000000..3256517 --- /dev/null +++ b/node_modules/@chevrotain/gast/lib/src/visitor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"visitor.js","sourceRoot":"","sources":["../../src/visitor.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,EACX,WAAW,EACX,WAAW,EACX,MAAM,EACN,UAAU,EACV,mBAAmB,EACnB,gCAAgC,EAChC,uBAAuB,EACvB,IAAI,EACJ,QAAQ,GACT,MAAM,YAAY,CAAC;AAGpB,MAAM,OAAgB,WAAW;IACxB,KAAK,CAAC,IAAiB;QAC5B,MAAM,OAAO,GAAQ,IAAI,CAAC;QAC1B,QAAQ,OAAO,CAAC,WAAW,EAAE;YAC3B,KAAK,WAAW;gBACd,OAAO,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;YACxC,KAAK,WAAW;gBACd,OAAO,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;YACxC,KAAK,MAAM;gBACT,OAAO,IAAI,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC;YACnC,KAAK,mBAAmB;gBACtB,OAAO,IAAI,CAAC,wBAAwB,CAAC,OAAO,CAAC,CAAC;YAChD,KAAK,gCAAgC;gBACnC,OAAO,IAAI,CAAC,qCAAqC,CAAC,OAAO,CAAC,CAAC;YAC7D,KAAK,uBAAuB;gBAC1B,OAAO,IAAI,CAAC,4BAA4B,CAAC,OAAO,CAAC,CAAC;YACpD,KAAK,UAAU;gBACb,OAAO,IAAI,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;YACvC,KAAK,WAAW;gBACd,OAAO,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,CAAC;YACxC,KAAK,QAAQ;gBACX,OAAO,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,CAAC;YACrC,KAAK,IAAI;gBACP,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;YACjC,sBAAsB;YACtB;gBACE,MAAM,KAAK,CAAC,sBAAsB,CAAC,CAAC;SACvC;IACH,CAAC;IAED,oBAAoB;IACb,gBAAgB,CAAC,IAAiB,IAAQ,CAAC;IAElD,oBAAoB;IACb,gBAAgB,CAAC,IAAiB,IAAQ,CAAC;IAElD,oBAAoB;IACb,WAAW,CAAC,IAAY,IAAQ,CAAC;IAExC,oBAAoB;IACb,eAAe,CAAC,IAAgB,IAAQ,CAAC;IAEhD,oBAAoB;IACb,wBAAwB,CAAC,IAAyB,IAAQ,CAAC;IAElE,sBAAsB;IACf,qCAAqC,CAC1C,IAAsC,IAChC,CAAC;IAET,oBAAoB;IACb,4BAA4B,CAAC,IAA6B,IAAQ,CAAC;IAE1E,oBAAoB;IACb,gBAAgB,CAAC,IAAiB,IAAQ,CAAC;IAElD,oBAAoB;IACb,aAAa,CAAC,IAAc,IAAQ,CAAC;IAE5C,oBAAoB;IACb,SAAS,CAAC,IAAU,IAAQ,CAAC;CACrC"} \ No newline at end of file diff --git a/node_modules/@chevrotain/gast/package.json b/node_modules/@chevrotain/gast/package.json new file mode 100644 index 0000000..fe5c1cd --- /dev/null +++ b/node_modules/@chevrotain/gast/package.json @@ -0,0 +1,52 @@ +{ + "name": "@chevrotain/gast", + "version": "11.0.3", + "description": "Grammar AST structure for Chevrotain Parsers", + "keywords": [], + "bugs": { + "url": "https://github.com/Chevrotain/chevrotain/issues" + }, + "license": "Apache-2.0", + "type": "module", + "types": "./lib/src/api.d.ts", + "exports": { + ".": { + "import": "./lib/src/api.js", + "types": "./lib/src/api.d.ts" + } + }, + "files": [ + "lib/src/**/*.js", + "lib/src/**/*.map", + "lib/src/**/*.d.ts", + "src/**/*.ts" + ], + "repository": { + "type": "git", + "url": "git://github.com/Chevrotain/chevrotain.git" + }, + "scripts": { + "---------- CI FLOWS --------": "", + "ci": "pnpm run build test", + "build": "npm-run-all clean compile", + "test": "npm-run-all coverage", + "---------- DEV FLOWS --------": "", + "update-snapshots": "node ./scripts/update-snapshots.js", + "---------- BUILD STEPS --------": "", + "clean": "shx rm -rf lib coverage", + "compile:watch": "tsc -w", + "compile": "tsc", + "coverage": "c8 mocha --enable-source-maps" + }, + "dependencies": { + "@chevrotain/types": "11.0.3", + "lodash-es": "4.17.21" + }, + "devDependencies": { + "@types/lodash-es": "4.17.7" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "ac5806631779035c2c1955744a47d8ed4f25a175" +} diff --git a/node_modules/@chevrotain/gast/src/api.ts b/node_modules/@chevrotain/gast/src/api.ts new file mode 100644 index 0000000..1ca9f36 --- /dev/null +++ b/node_modules/@chevrotain/gast/src/api.ts @@ -0,0 +1,23 @@ +export { + Rule, + Terminal, + NonTerminal, + Option, + Repetition, + RepetitionMandatory, + RepetitionMandatoryWithSeparator, + RepetitionWithSeparator, + Alternation, + Alternative, + serializeGrammar, + serializeProduction, +} from "./model.js"; + +export { GAstVisitor } from "./visitor.js"; + +export { + getProductionDslName, + isOptionalProd, + isBranchingProd, + isSequenceProd, +} from "./helpers.js"; diff --git a/node_modules/@chevrotain/gast/src/helpers.ts b/node_modules/@chevrotain/gast/src/helpers.ts new file mode 100644 index 0000000..f395aee --- /dev/null +++ b/node_modules/@chevrotain/gast/src/helpers.ts @@ -0,0 +1,98 @@ +import { every, includes, some } from "lodash-es"; +import { + AbstractProduction, + Alternation, + Alternative, + NonTerminal, + Option, + Repetition, + RepetitionMandatory, + RepetitionMandatoryWithSeparator, + RepetitionWithSeparator, + Rule, + Terminal, +} from "./model.js"; +import type { IProduction, IProductionWithOccurrence } from "@chevrotain/types"; + +export function isSequenceProd( + prod: IProduction, +): prod is { definition: IProduction[] } & IProduction { + return ( + prod instanceof Alternative || + 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: IProduction, + alreadyVisited: NonTerminal[] = [], +): boolean { + const 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, (subProd: IProduction) => { + return isOptionalProd(subProd, alreadyVisited); + }); + } else if (prod instanceof NonTerminal && includes(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, + (subProd: IProduction) => { + return isOptionalProd(subProd, alreadyVisited); + }, + ); + } else { + return false; + } +} + +export function isBranchingProd( + prod: IProduction, +): prod is { definition: IProduction[] } & IProduction { + return prod instanceof Alternation; +} + +export function getProductionDslName(prod: IProductionWithOccurrence): string { + /* 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"; + /* c8 ignore next 3 */ + } else { + throw Error("non exhaustive match"); + } +} diff --git a/node_modules/@chevrotain/gast/src/model.ts b/node_modules/@chevrotain/gast/src/model.ts new file mode 100644 index 0000000..fc0cb0f --- /dev/null +++ b/node_modules/@chevrotain/gast/src/model.ts @@ -0,0 +1,416 @@ +import { assign, forEach, isRegExp, isString, map, pickBy } from "lodash-es"; +import type { + IGASTVisitor, + IProduction, + IProductionWithOccurrence, + ISerializedGast, + TokenType, +} from "@chevrotain/types"; + +// TODO: duplicated code to avoid extracting another sub-package -- how to avoid? +function tokenLabel(tokType: TokenType): string { + if (hasTokenLabel(tokType)) { + return tokType.LABEL; + } else { + return tokType.name; + } +} + +// TODO: duplicated code to avoid extracting another sub-package -- how to avoid? +function hasTokenLabel( + obj: TokenType, +): obj is TokenType & Pick, "LABEL"> { + return isString(obj.LABEL) && obj.LABEL !== ""; +} + +export abstract class AbstractProduction + implements IProduction +{ + public get definition(): T[] { + return this._definition; + } + public set definition(value: T[]) { + this._definition = value; + } + + constructor(protected _definition: T[]) {} + + accept(visitor: IGASTVisitor): void { + visitor.visit(this); + forEach(this.definition, (prod) => { + prod.accept(visitor); + }); + } +} + +export class NonTerminal + extends AbstractProduction + implements IProductionWithOccurrence +{ + public nonTerminalName!: string; + public label?: string; + public referencedRule!: Rule; + public idx: number = 1; + + constructor(options: { + nonTerminalName: string; + label?: string; + referencedRule?: Rule; + idx?: number; + }) { + super([]); + assign( + this, + pickBy(options, (v) => v !== undefined), + ); + } + + set definition(definition: IProduction[]) { + // immutable + } + + get definition(): IProduction[] { + if (this.referencedRule !== undefined) { + return this.referencedRule.definition; + } + return []; + } + + accept(visitor: IGASTVisitor): void { + visitor.visit(this); + // don't visit children of a reference, we will get cyclic infinite loops if we do so + } +} + +export class Rule extends AbstractProduction { + public name!: string; + public orgText: string = ""; + + constructor(options: { + name: string; + definition: IProduction[]; + orgText?: string; + }) { + super(options.definition); + assign( + this, + pickBy(options, (v) => v !== undefined), + ); + } +} + +export class Alternative extends AbstractProduction { + public ignoreAmbiguities: boolean = false; + + constructor(options: { + definition: IProduction[]; + ignoreAmbiguities?: boolean; + }) { + super(options.definition); + assign( + this, + pickBy(options, (v) => v !== undefined), + ); + } +} + +export class Option + extends AbstractProduction + implements IProductionWithOccurrence +{ + public idx: number = 1; + public maxLookahead?: number; + + constructor(options: { + definition: IProduction[]; + idx?: number; + maxLookahead?: number; + }) { + super(options.definition); + assign( + this, + pickBy(options, (v) => v !== undefined), + ); + } +} + +export class RepetitionMandatory + extends AbstractProduction + implements IProductionWithOccurrence +{ + public idx: number = 1; + public maxLookahead?: number; + + constructor(options: { + definition: IProduction[]; + idx?: number; + maxLookahead?: number; + }) { + super(options.definition); + assign( + this, + pickBy(options, (v) => v !== undefined), + ); + } +} + +export class RepetitionMandatoryWithSeparator + extends AbstractProduction + implements IProductionWithOccurrence +{ + public separator!: TokenType; + public idx: number = 1; + public maxLookahead?: number; + + constructor(options: { + definition: IProduction[]; + separator: TokenType; + idx?: number; + }) { + super(options.definition); + assign( + this, + pickBy(options, (v) => v !== undefined), + ); + } +} + +export class Repetition + extends AbstractProduction + implements IProductionWithOccurrence +{ + public separator!: TokenType; + public idx: number = 1; + public maxLookahead?: number; + + constructor(options: { + definition: IProduction[]; + idx?: number; + maxLookahead?: number; + }) { + super(options.definition); + assign( + this, + pickBy(options, (v) => v !== undefined), + ); + } +} + +export class RepetitionWithSeparator + extends AbstractProduction + implements IProductionWithOccurrence +{ + public separator!: TokenType; + public idx: number = 1; + public maxLookahead?: number; + + constructor(options: { + definition: IProduction[]; + separator: TokenType; + idx?: number; + }) { + super(options.definition); + assign( + this, + pickBy(options, (v) => v !== undefined), + ); + } +} + +export class Alternation + extends AbstractProduction + implements IProductionWithOccurrence +{ + public idx: number = 1; + public ignoreAmbiguities: boolean = false; + public hasPredicates: boolean = false; + public maxLookahead?: number; + + public get definition(): Alternative[] { + return this._definition; + } + public set definition(value: Alternative[]) { + this._definition = value; + } + + constructor(options: { + definition: Alternative[]; + idx?: number; + ignoreAmbiguities?: boolean; + hasPredicates?: boolean; + maxLookahead?: number; + }) { + super(options.definition); + assign( + this, + pickBy(options, (v) => v !== undefined), + ); + } +} + +export class Terminal implements IProductionWithOccurrence { + public terminalType!: TokenType; + public label?: string; + public idx: number = 1; + + constructor(options: { + terminalType: TokenType; + label?: string; + idx?: number; + }) { + assign( + this, + pickBy(options, (v) => v !== undefined), + ); + } + + accept(visitor: IGASTVisitor): void { + visitor.visit(this); + } +} + +export interface ISerializedBasic extends ISerializedGast { + type: + | "Alternative" + | "Option" + | "RepetitionMandatory" + | "Repetition" + | "Alternation"; + idx?: number; +} + +export interface ISerializedGastRule extends ISerializedGast { + type: "Rule"; + name: string; + orgText: string; +} + +export interface ISerializedNonTerminal extends ISerializedGast { + type: "NonTerminal"; + name: string; + label?: string; + idx: number; +} + +export interface ISerializedTerminal extends ISerializedGast { + type: "Terminal"; + name: string; + terminalLabel?: string; + label?: string; + pattern?: string; + idx: number; +} + +export interface ISerializedTerminalWithSeparator extends ISerializedGast { + type: "RepetitionMandatoryWithSeparator" | "RepetitionWithSeparator"; + idx: number; + separator: ISerializedTerminal; +} + +export type ISerializedGastAny = + | ISerializedBasic + | ISerializedGastRule + | ISerializedNonTerminal + | ISerializedTerminal + | ISerializedTerminalWithSeparator; + +export function serializeGrammar(topRules: Rule[]): ISerializedGast[] { + return map(topRules, serializeProduction); +} + +export function serializeProduction(node: IProduction): ISerializedGast { + function convertDefinition(definition: IProduction[]): ISerializedGast[] { + return map(definition, serializeProduction); + } + /* istanbul ignore else */ + if (node instanceof NonTerminal) { + const serializedNonTerminal: ISerializedNonTerminal = { + type: "NonTerminal", + name: node.nonTerminalName, + idx: node.idx, + }; + + if (isString(node.label)) { + serializedNonTerminal.label = node.label; + } + + return serializedNonTerminal; + } else if (node instanceof Alternative) { + return { + type: "Alternative", + 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", + idx: node.idx, + definition: convertDefinition(node.definition), + }; + } else if (node instanceof RepetitionMandatoryWithSeparator) { + return { + type: "RepetitionMandatoryWithSeparator", + idx: node.idx, + separator: ( + serializeProduction(new Terminal({ terminalType: node.separator })) + ), + definition: convertDefinition(node.definition), + }; + } else if (node instanceof RepetitionWithSeparator) { + return { + type: "RepetitionWithSeparator", + idx: node.idx, + separator: ( + serializeProduction(new Terminal({ terminalType: node.separator })) + ), + definition: convertDefinition(node.definition), + }; + } else if (node instanceof Repetition) { + return { + type: "Repetition", + idx: node.idx, + definition: convertDefinition(node.definition), + }; + } else if (node instanceof Alternation) { + return { + type: "Alternation", + idx: node.idx, + definition: convertDefinition(node.definition), + }; + } else if (node instanceof Terminal) { + const serializedTerminal = { + type: "Terminal", + name: node.terminalType.name, + label: tokenLabel(node.terminalType), + idx: node.idx, + }; + + if (isString(node.label)) { + serializedTerminal.terminalLabel = node.label; + } + + const 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), + }; + /* c8 ignore next 3 */ + } else { + throw Error("non exhaustive match"); + } +} diff --git a/node_modules/@chevrotain/gast/src/visitor.ts b/node_modules/@chevrotain/gast/src/visitor.ts new file mode 100644 index 0000000..bf54d22 --- /dev/null +++ b/node_modules/@chevrotain/gast/src/visitor.ts @@ -0,0 +1,76 @@ +import { + Alternation, + Alternative, + NonTerminal, + Option, + Repetition, + RepetitionMandatory, + RepetitionMandatoryWithSeparator, + RepetitionWithSeparator, + Rule, + Terminal, +} from "./model.js"; +import type { IProduction } from "@chevrotain/types"; + +export abstract class GAstVisitor { + public visit(node: IProduction): any { + const nodeAny: any = node; + switch (nodeAny.constructor) { + case NonTerminal: + return this.visitNonTerminal(nodeAny); + case Alternative: + return this.visitAlternative(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); + /* c8 ignore next 2 */ + default: + throw Error("non exhaustive match"); + } + } + + /* c8 ignore next */ + public visitNonTerminal(node: NonTerminal): any {} + + /* c8 ignore next */ + public visitAlternative(node: Alternative): any {} + + /* c8 ignore next */ + public visitOption(node: Option): any {} + + /* c8 ignore next */ + public visitRepetition(node: Repetition): any {} + + /* c8 ignore next */ + public visitRepetitionMandatory(node: RepetitionMandatory): any {} + + /* c8 ignore next 3 */ + public visitRepetitionMandatoryWithSeparator( + node: RepetitionMandatoryWithSeparator, + ): any {} + + /* c8 ignore next */ + public visitRepetitionWithSeparator(node: RepetitionWithSeparator): any {} + + /* c8 ignore next */ + public visitAlternation(node: Alternation): any {} + + /* c8 ignore next */ + public visitTerminal(node: Terminal): any {} + + /* c8 ignore next */ + public visitRule(node: Rule): any {} +} diff --git a/node_modules/@chevrotain/regexp-to-ast/LICENSE.txt b/node_modules/@chevrotain/regexp-to-ast/LICENSE.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/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/regexp-to-ast/lib/src/api.js b/node_modules/@chevrotain/regexp-to-ast/lib/src/api.js new file mode 100644 index 0000000..121891b --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/lib/src/api.js @@ -0,0 +1,3 @@ +export { RegExpParser } from "./regexp-parser.js"; +export { BaseRegExpVisitor } from "./base-regexp-visitor.js"; +//# sourceMappingURL=api.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/regexp-to-ast/lib/src/api.js.map b/node_modules/@chevrotain/regexp-to-ast/lib/src/api.js.map new file mode 100644 index 0000000..93c8992 --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/lib/src/api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC"} \ No newline at end of file diff --git a/node_modules/@chevrotain/regexp-to-ast/lib/src/base-regexp-visitor.js b/node_modules/@chevrotain/regexp-to-ast/lib/src/base-regexp-visitor.js new file mode 100644 index 0000000..a678c89 --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/lib/src/base-regexp-visitor.js @@ -0,0 +1,86 @@ +export class BaseRegExpVisitor { + visitChildren(node) { + for (const key in node) { + const child = node[key]; + /* istanbul ignore else */ + if (node.hasOwnProperty(key)) { + if (child.type !== undefined) { + this.visit(child); + } + else if (Array.isArray(child)) { + child.forEach((subChild) => { + this.visit(subChild); + }, this); + } + } + } + } + visit(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); + } + visitPattern(node) { } + visitFlags(node) { } + visitDisjunction(node) { } + visitAlternative(node) { } + // Assertion + visitStartAnchor(node) { } + visitEndAnchor(node) { } + visitWordBoundary(node) { } + visitNonWordBoundary(node) { } + visitLookahead(node) { } + visitNegativeLookahead(node) { } + // atoms + visitCharacter(node) { } + visitSet(node) { } + visitGroup(node) { } + visitGroupBackReference(node) { } + visitQuantifier(node) { } +} +//# sourceMappingURL=base-regexp-visitor.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/regexp-to-ast/lib/src/base-regexp-visitor.js.map b/node_modules/@chevrotain/regexp-to-ast/lib/src/base-regexp-visitor.js.map new file mode 100644 index 0000000..e455c97 --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/lib/src/base-regexp-visitor.js.map @@ -0,0 +1 @@ +{"version":3,"file":"base-regexp-visitor.js","sourceRoot":"","sources":["../../src/base-regexp-visitor.ts"],"names":[],"mappings":"AAeA,MAAM,OAAO,iBAAiB;IACrB,aAAa,CAAC,IAAgB;QACnC,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE;YACtB,MAAM,KAAK,GAAI,IAAY,CAAC,GAAG,CAAC,CAAC;YACjC,0BAA0B;YAC1B,IAAI,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;gBAC5B,IAAI,KAAK,CAAC,IAAI,KAAK,SAAS,EAAE;oBAC5B,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;iBACnB;qBAAM,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE;oBAC/B,KAAK,CAAC,OAAO,CAAC,CAAC,QAAQ,EAAE,EAAE;wBACz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,KAAK,oBAAoB;gBACvB,IAAI,CAAC,uBAAuB,CAAC,IAAI,CAAC,CAAC;gBACnC,MAAM;YACR,KAAK,YAAY;gBACf,IAAI,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;gBAC3B,MAAM;SACT;QAED,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAC3B,CAAC;IAEM,YAAY,CAAC,IAAmB,IAAS,CAAC;IAE1C,UAAU,CAAC,IAAiB,IAAS,CAAC;IAEtC,gBAAgB,CAAC,IAAiB,IAAS,CAAC;IAE5C,gBAAgB,CAAC,IAAiB,IAAS,CAAC;IAEnD,YAAY;IACL,gBAAgB,CAAC,IAAe,IAAS,CAAC;IAE1C,cAAc,CAAC,IAAe,IAAS,CAAC;IAExC,iBAAiB,CAAC,IAAe,IAAS,CAAC;IAE3C,oBAAoB,CAAC,IAAe,IAAS,CAAC;IAE9C,cAAc,CAAC,IAAe,IAAS,CAAC;IAExC,sBAAsB,CAAC,IAAe,IAAS,CAAC;IAEvD,QAAQ;IACD,cAAc,CAAC,IAAe,IAAS,CAAC;IAExC,QAAQ,CAAC,IAAS,IAAS,CAAC;IAE5B,UAAU,CAAC,IAAW,IAAS,CAAC;IAEhC,uBAAuB,CAAC,IAAwB,IAAS,CAAC;IAE1D,eAAe,CAAC,IAAgB,IAAS,CAAC;CAClD"} \ No newline at end of file diff --git a/node_modules/@chevrotain/regexp-to-ast/lib/src/character-classes.js b/node_modules/@chevrotain/regexp-to-ast/lib/src/character-classes.js new file mode 100644 index 0000000..a589ec4 --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/lib/src/character-classes.js @@ -0,0 +1,42 @@ +import { cc } from "./utils.js"; +export const digitsCharCodes = []; +for (let i = cc("0"); i <= cc("9"); i++) { + digitsCharCodes.push(i); +} +export const wordCharCodes = [cc("_")].concat(digitsCharCodes); +for (let i = cc("a"); i <= cc("z"); i++) { + wordCharCodes.push(i); +} +for (let 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 +export const 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"), +]; +//# sourceMappingURL=character-classes.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/regexp-to-ast/lib/src/character-classes.js.map b/node_modules/@chevrotain/regexp-to-ast/lib/src/character-classes.js.map new file mode 100644 index 0000000..4ca48c9 --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/lib/src/character-classes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"character-classes.js","sourceRoot":"","sources":["../../src/character-classes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,EAAE,EAAE,MAAM,YAAY,CAAC;AAEhC,MAAM,CAAC,MAAM,eAAe,GAAa,EAAE,CAAC;AAC5C,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;IACvC,eAAe,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;CACzB;AAED,MAAM,CAAC,MAAM,aAAa,GAAa,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC;AACzE,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;IACvC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;CACvB;AAED,KAAK,IAAI,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE;IACvC,aAAa,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;CACvB;AAED,4GAA4G;AAC5G,MAAM,CAAC,MAAM,eAAe,GAAa;IACvC,EAAE,CAAC,GAAG,CAAC;IACP,EAAE,CAAC,IAAI,CAAC;IACR,EAAE,CAAC,IAAI,CAAC;IACR,EAAE,CAAC,IAAI,CAAC;IACR,EAAE,CAAC,IAAI,CAAC;IACR,EAAE,CAAC,IAAI,CAAC;IACR,EAAE,CAAC,IAAI,CAAC;IACR,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;IACZ,EAAE,CAAC,QAAQ,CAAC;CACb,CAAC"} \ No newline at end of file diff --git a/node_modules/@chevrotain/regexp-to-ast/lib/src/regexp-parser.js b/node_modules/@chevrotain/regexp-to-ast/lib/src/regexp-parser.js new file mode 100644 index 0000000..70165dd --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/lib/src/regexp-parser.js @@ -0,0 +1,731 @@ +import { addFlag, ASSERT_EXISTS, ASSERT_NEVER_REACH_HERE, cc, insertToSet, isCharacter, } from "./utils.js"; +import { digitsCharCodes, whitespaceCodes, wordCharCodes, } from "./character-classes.js"; +// consts and utilities +const hexDigitPattern = /[0-9a-fA-F]/; +const decimalPattern = /[0-9]/; +const decimalPatternNoZero = /[1-9]/; +// 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 +export class RegExpParser { + constructor() { + this.idx = 0; + this.input = ""; + this.groupIdx = 0; + } + saveState() { + return { + idx: this.idx, + input: this.input, + groupIdx: this.groupIdx, + }; + } + restoreState(newState) { + this.idx = newState.idx; + this.input = newState.input; + this.groupIdx = newState.groupIdx; + } + pattern(input) { + // parser state + this.idx = 0; + this.input = input; + this.groupIdx = 0; + this.consumeChar("/"); + const value = this.disjunction(); + this.consumeChar("/"); + const flags = { + type: "Flags", + loc: { begin: this.idx, end: input.length }, + global: false, + ignoreCase: false, + multiLine: false, + unicode: false, + sticky: false, + }; + while (this.isRegExpFlag()) { + switch (this.popChar()) { + case "g": + addFlag(flags, "global"); + break; + case "i": + addFlag(flags, "ignoreCase"); + break; + case "m": + addFlag(flags, "multiLine"); + break; + case "u": + addFlag(flags, "unicode"); + break; + case "y": + addFlag(flags, "sticky"); + break; + } + } + if (this.idx !== this.input.length) { + throw Error("Redundant input: " + this.input.substring(this.idx)); + } + return { + type: "Pattern", + flags: flags, + value: value, + loc: this.loc(0), + }; + } + disjunction() { + const alts = []; + const begin = this.idx; + alts.push(this.alternative()); + while (this.peekChar() === "|") { + this.consumeChar("|"); + alts.push(this.alternative()); + } + return { type: "Disjunction", value: alts, loc: this.loc(begin) }; + } + alternative() { + const terms = []; + const begin = this.idx; + while (this.isTerm()) { + terms.push(this.term()); + } + return { type: "Alternative", value: terms, loc: this.loc(begin) }; + } + term() { + if (this.isAssertion()) { + return this.assertion(); + } + else { + return this.atom(); + } + } + assertion() { + const begin = this.idx; + switch (this.popChar()) { + case "^": + return { + type: "StartAnchor", + loc: this.loc(begin), + }; + case "$": + return { type: "EndAnchor", loc: this.loc(begin) }; + // '\b' or '\B' + case "\\": + switch (this.popChar()) { + case "b": + return { + type: "WordBoundary", + loc: this.loc(begin), + }; + case "B": + return { + type: "NonWordBoundary", + loc: this.loc(begin), + }; + } + // istanbul ignore next + throw Error("Invalid Assertion Escape"); + // '(?=' or '(?!' + case "(": + this.consumeChar("?"); + let type; + switch (this.popChar()) { + case "=": + type = "Lookahead"; + break; + case "!": + type = "NegativeLookahead"; + break; + } + ASSERT_EXISTS(type); + const disjunction = this.disjunction(); + this.consumeChar(")"); + return { + type: type, + value: disjunction, + loc: this.loc(begin), + }; + } + // istanbul ignore next + return ASSERT_NEVER_REACH_HERE(); + } + quantifier(isBacktracking = false) { + let range = undefined; + const begin = this.idx; + switch (this.popChar()) { + case "*": + range = { + atLeast: 0, + atMost: Infinity, + }; + break; + case "+": + range = { + atLeast: 1, + atMost: Infinity, + }; + break; + case "?": + range = { + atLeast: 0, + atMost: 1, + }; + break; + case "{": + const atLeast = this.integerIncludingZero(); + switch (this.popChar()) { + case "}": + range = { + atLeast: atLeast, + atMost: atLeast, + }; + break; + case ",": + let 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; + } + // istanbul ignore else + if (ASSERT_EXISTS(range)) { + if (this.peekChar(0) === "?") { + this.consumeChar("?"); + range.greedy = false; + } + else { + range.greedy = true; + } + range.type = "Quantifier"; + range.loc = this.loc(begin); + return range; + } + } + atom() { + let atom; + const begin = this.idx; + switch (this.peekChar()) { + case ".": + atom = this.dotAll(); + break; + case "\\": + atom = this.atomEscape(); + break; + case "[": + atom = this.characterClass(); + break; + case "(": + atom = this.group(); + break; + } + if (atom === undefined && this.isPatternCharacter()) { + atom = this.patternCharacter(); + } + // istanbul ignore else + if (ASSERT_EXISTS(atom)) { + atom.loc = this.loc(begin); + if (this.isQuantifier()) { + atom.quantifier = this.quantifier(); + } + return atom; + } + // istanbul ignore next + return ASSERT_NEVER_REACH_HERE(); + } + dotAll() { + this.consumeChar("."); + return { + type: "Set", + complement: true, + value: [cc("\n"), cc("\r"), cc("\u2028"), cc("\u2029")], + }; + } + atomEscape() { + 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(); + } + } + decimalEscapeAtom() { + const value = this.positiveInteger(); + return { type: "GroupBackReference", value: value }; + } + characterClassEscape() { + let set; + let 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; + } + // istanbul ignore else + if (ASSERT_EXISTS(set)) { + return { type: "Set", value: set, complement: complement }; + } + // istanbul ignore next + return ASSERT_NEVER_REACH_HERE(); + } + controlEscapeAtom() { + let 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; + } + // istanbul ignore else + if (ASSERT_EXISTS(escapeCode)) { + return { type: "Character", value: escapeCode }; + } + // istanbul ignore next + return ASSERT_NEVER_REACH_HERE(); + } + controlLetterEscapeAtom() { + this.consumeChar("c"); + const letter = this.popChar(); + if (/[a-zA-Z]/.test(letter) === false) { + throw Error("Invalid "); + } + const letterCode = letter.toUpperCase().charCodeAt(0) - 64; + return { type: "Character", value: letterCode }; + } + nulCharacterAtom() { + // TODO implement '[lookahead ∉ DecimalDigit]' + // TODO: for the deprecated octal escape sequence + this.consumeChar("0"); + return { type: "Character", value: cc("\0") }; + } + hexEscapeSequenceAtom() { + this.consumeChar("x"); + return this.parseHexDigits(2); + } + regExpUnicodeEscapeSequenceAtom() { + this.consumeChar("u"); + return this.parseHexDigits(4); + } + identityEscapeAtom() { + // TODO: implement "SourceCharacter but not UnicodeIDContinue" + // // http://unicode.org/reports/tr31/#Specific_Character_Adjustments + const escapedChar = this.popChar(); + return { type: "Character", value: cc(escapedChar) }; + } + classPatternCharacterAtom() { + 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: + const nextChar = this.popChar(); + return { type: "Character", value: cc(nextChar) }; + } + } + characterClass() { + const set = []; + let complement = false; + this.consumeChar("["); + if (this.peekChar(0) === "^") { + this.consumeChar("^"); + complement = true; + } + while (this.isClassAtom()) { + const from = this.classAtom(); + const isFromSingleChar = from.type === "Character"; + if (isCharacter(from) && this.isRangeDash()) { + this.consumeChar("-"); + const to = this.classAtom(); + const isToSingleChar = to.type === "Character"; + // a range can only be used when both sides are single characters + if (isCharacter(to)) { + 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 }; + } + classAtom() { + 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(); + } + } + classEscape() { + 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(); + } + } + group() { + let capturing = true; + this.consumeChar("("); + switch (this.peekChar(0)) { + case "?": + this.consumeChar("?"); + this.consumeChar(":"); + capturing = false; + break; + default: + this.groupIdx++; + break; + } + const value = this.disjunction(); + this.consumeChar(")"); + const groupAst = { + type: "Group", + capturing: capturing, + value: value, + }; + if (capturing) { + groupAst["idx"] = this.groupIdx; + } + return groupAst; + } + positiveInteger() { + let 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); + } + integerIncludingZero() { + let 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); + } + patternCharacter() { + const 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) }; + } + } + isRegExpFlag() { + switch (this.peekChar(0)) { + case "g": + case "i": + case "m": + case "u": + case "y": + return true; + default: + return false; + } + } + isRangeDash() { + return this.peekChar() === "-" && this.isClassAtom(1); + } + isDigit() { + return decimalPattern.test(this.peekChar(0)); + } + isClassAtom(howMuch = 0) { + switch (this.peekChar(howMuch)) { + case "]": + case "\n": + case "\r": + case "\u2028": + case "\u2029": + return false; + default: + return true; + } + } + isTerm() { + return this.isAtom() || this.isAssertion(); + } + isAtom() { + 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; + } + } + isAssertion() { + 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; + } + } + isQuantifier() { + const prevState = this.saveState(); + try { + return this.quantifier(true) !== undefined; + } + catch (e) { + return false; + } + finally { + this.restoreState(prevState); + } + } + isPatternCharacter() { + 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; + } + } + parseHexDigits(howMany) { + let hexString = ""; + for (let i = 0; i < howMany; i++) { + const hexChar = this.popChar(); + if (hexDigitPattern.test(hexChar) === false) { + throw Error("Expecting a HexDecimal digits"); + } + hexString += hexChar; + } + const charCode = parseInt(hexString, 16); + return { type: "Character", value: charCode }; + } + peekChar(howMuch = 0) { + return this.input[this.idx + howMuch]; + } + popChar() { + const nextChar = this.peekChar(0); + this.consumeChar(undefined); + return nextChar; + } + consumeChar(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++; + } + loc(begin) { + return { begin: begin, end: this.idx }; + } +} +//# sourceMappingURL=regexp-parser.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/regexp-to-ast/lib/src/regexp-parser.js.map b/node_modules/@chevrotain/regexp-to-ast/lib/src/regexp-parser.js.map new file mode 100644 index 0000000..150760b --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/lib/src/regexp-parser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"regexp-parser.js","sourceRoot":"","sources":["../../src/regexp-parser.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,OAAO,EACP,aAAa,EACb,uBAAuB,EACvB,EAAE,EACF,WAAW,EACX,WAAW,GACZ,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,eAAe,EACf,eAAe,EACf,aAAa,GACd,MAAM,wBAAwB,CAAC;AAEhC,uBAAuB;AACvB,MAAM,eAAe,GAAG,aAAa,CAAC;AACtC,MAAM,cAAc,GAAG,OAAO,CAAC;AAC/B,MAAM,oBAAoB,GAAG,OAAO,CAAC;AAErC,2FAA2F;AAC3F,0EAA0E;AAC1E,MAAM,OAAO,YAAY;IAAzB;QACY,QAAG,GAAW,CAAC,CAAC;QAChB,UAAK,GAAW,EAAE,CAAC;QACnB,aAAQ,GAAW,CAAC,CAAC;IA+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OAAO;QACf,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC;QAClC,IAAI,CAAC,WAAW,CAAC,SAAS,CAAC,CAAC;QAC5B,OAAO,QAAQ,CAAC;IAClB,CAAC;IAES,WAAW,CAAC,IAAwB;QAC5C,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,IAAI,EAAE;YACvD,MAAM,KAAK,CACT,aAAa;gBACX,IAAI;gBACJ,gBAAgB;gBAChB,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC;gBACpB,eAAe;gBACf,IAAI,CAAC,GAAG,CACX,CAAC;SACH;QAED,IAAI,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE;YACjC,MAAM,KAAK,CAAC,yBAAyB,CAAC,CAAC;SACxC;QACD,IAAI,CAAC,GAAG,EAAE,CAAC;IACb,CAAC;IAES,GAAG,CAAC,KAAa;QACzB,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC;IACzC,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@chevrotain/regexp-to-ast/lib/src/utils.js b/node_modules/@chevrotain/regexp-to-ast/lib/src/utils.js new file mode 100644 index 0000000..7a35e28 --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/lib/src/utils.js @@ -0,0 +1,35 @@ +export function cc(char) { + return char.charCodeAt(0); +} +export function insertToSet(item, set) { + if (Array.isArray(item)) { + item.forEach(function (subItem) { + set.push(subItem); + }); + } + else { + set.push(item); + } +} +export function addFlag(flagObj, flagKey) { + if (flagObj[flagKey] === true) { + throw "duplicate flag " + flagKey; + } + const x = flagObj[flagKey]; + flagObj[flagKey] = true; +} +export function ASSERT_EXISTS(obj) { + // istanbul ignore next + if (obj === undefined) { + throw Error("Internal Error - Should never get here!"); + } + return true; +} +// istanbul ignore next +export function ASSERT_NEVER_REACH_HERE() { + throw Error("Internal Error - Should never get here!"); +} +export function isCharacter(obj) { + return obj["type"] === "Character"; +} +//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/regexp-to-ast/lib/src/utils.js.map b/node_modules/@chevrotain/regexp-to-ast/lib/src/utils.js.map new file mode 100644 index 0000000..103962e --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/lib/src/utils.js.map @@ -0,0 +1 @@ +{"version":3,"file":"utils.js","sourceRoot":"","sources":["../../src/utils.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,EAAE,CAAC,IAAY;IAC7B,OAAO,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;AAC5B,CAAC;AAED,MAAM,UAAU,WAAW,CAAI,IAAa,EAAE,GAAQ;IACpD,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;QACvB,IAAI,CAAC,OAAO,CAAC,UAAU,OAAO;YAC5B,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpB,CAAC,CAAC,CAAC;KACJ;SAAM;QACL,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;KAChB;AACH,CAAC;AAED,MAAM,UAAU,OAAO,CACrB,OAAoB,EACpB,OAAkD;IAElD,IAAI,OAAO,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE;QAC7B,MAAM,iBAAiB,GAAG,OAAO,CAAC;KACnC;IAED,MAAM,CAAC,GAAY,OAAO,CAAC,OAAO,CAAC,CAAC;IACpC,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;AAC1B,CAAC;AAED,MAAM,UAAU,aAAa,CAAa,GAAQ;IAChD,uBAAuB;IACvB,IAAI,GAAG,KAAK,SAAS,EAAE;QACrB,MAAM,KAAK,CAAC,yCAAyC,CAAC,CAAC;KACxD;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,uBAAuB;AACvB,MAAM,UAAU,uBAAuB;IACrC,MAAM,KAAK,CAAC,yCAAyC,CAAC,CAAC;AACzD,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,GAAqB;IAC/C,OAAO,GAAG,CAAC,MAAM,CAAC,KAAK,WAAW,CAAC;AACrC,CAAC"} \ No newline at end of file diff --git a/node_modules/@chevrotain/regexp-to-ast/package.json b/node_modules/@chevrotain/regexp-to-ast/package.json new file mode 100644 index 0000000..f8f2896 --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/package.json @@ -0,0 +1,47 @@ +{ + "name": "@chevrotain/regexp-to-ast", + "version": "11.0.3", + "description": "Parses a Regular Expression and outputs an AST", + "keywords": [ + "regExp", + "parser", + "regular expression" + ], + "bugs": { + "url": "https://github.com/Chevrotain/chevrotain/issues" + }, + "license": "Apache-2.0", + "type": "module", + "types": "./types.d.ts", + "exports": { + ".": { + "import": "./lib/src/api.js", + "types": "./types.d.ts" + } + }, + "files": [ + "lib/src/**/*.js", + "lib/src/**/*.map", + "src/**/*.ts", + "types.d.ts" + ], + "repository": { + "type": "git", + "url": "git://github.com/Chevrotain/chevrotain.git" + }, + "scripts": { + "---------- CI FLOWS --------": "", + "ci": "pnpm run build test", + "build": "npm-run-all clean compile", + "test": "npm-run-all coverage", + "---------- BUILD STEPS --------": "", + "clean": "shx rm -rf lib coverage", + "compile:watch": "tsc -w", + "compile": "tsc", + "coverage": "c8 mocha" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "ac5806631779035c2c1955744a47d8ed4f25a175" +} diff --git a/node_modules/@chevrotain/regexp-to-ast/src/api.ts b/node_modules/@chevrotain/regexp-to-ast/src/api.ts new file mode 100644 index 0000000..926bb0b --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/src/api.ts @@ -0,0 +1,2 @@ +export { RegExpParser } from "./regexp-parser.js"; +export { BaseRegExpVisitor } from "./base-regexp-visitor.js"; diff --git a/node_modules/@chevrotain/regexp-to-ast/src/base-regexp-visitor.ts b/node_modules/@chevrotain/regexp-to-ast/src/base-regexp-visitor.ts new file mode 100644 index 0000000..2da3118 --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/src/base-regexp-visitor.ts @@ -0,0 +1,116 @@ +import type { + Alternative, + Assertion, + Character, + Disjunction, + Group, + GroupBackReference, + IRegExpAST, + Quantifier, + RegExpAstPart, + RegExpFlags, + RegExpPattern, + Set, +} from "../types"; + +export class BaseRegExpVisitor { + public visitChildren(node: IRegExpAST) { + for (const key in node) { + const child = (node as any)[key]; + /* istanbul ignore else */ + if (node.hasOwnProperty(key)) { + if (child.type !== undefined) { + this.visit(child); + } else if (Array.isArray(child)) { + child.forEach((subChild) => { + this.visit(subChild); + }, this); + } + } + } + } + + public visit(node: RegExpAstPart): void { + 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); + } + + public visitPattern(node: RegExpPattern): void {} + + public visitFlags(node: RegExpFlags): void {} + + public visitDisjunction(node: Disjunction): void {} + + public visitAlternative(node: Alternative): void {} + + // Assertion + public visitStartAnchor(node: Assertion): void {} + + public visitEndAnchor(node: Assertion): void {} + + public visitWordBoundary(node: Assertion): void {} + + public visitNonWordBoundary(node: Assertion): void {} + + public visitLookahead(node: Assertion): void {} + + public visitNegativeLookahead(node: Assertion): void {} + + // atoms + public visitCharacter(node: Character): void {} + + public visitSet(node: Set): void {} + + public visitGroup(node: Group): void {} + + public visitGroupBackReference(node: GroupBackReference): void {} + + public visitQuantifier(node: Quantifier): void {} +} diff --git a/node_modules/@chevrotain/regexp-to-ast/src/character-classes.ts b/node_modules/@chevrotain/regexp-to-ast/src/character-classes.ts new file mode 100644 index 0000000..05fc148 --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/src/character-classes.ts @@ -0,0 +1,45 @@ +import { cc } from "./utils.js"; + +export const digitsCharCodes: number[] = []; +for (let i = cc("0"); i <= cc("9"); i++) { + digitsCharCodes.push(i); +} + +export const wordCharCodes: number[] = [cc("_")].concat(digitsCharCodes); +for (let i = cc("a"); i <= cc("z"); i++) { + wordCharCodes.push(i); +} + +for (let 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 +export const whitespaceCodes: number[] = [ + 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"), +]; diff --git a/node_modules/@chevrotain/regexp-to-ast/src/regexp-parser.ts b/node_modules/@chevrotain/regexp-to-ast/src/regexp-parser.ts new file mode 100644 index 0000000..3250a96 --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/src/regexp-parser.ts @@ -0,0 +1,840 @@ +import type { + Alternative, + Assertion, + Atom, + Character, + Disjunction, + Group, + GroupBackReference, + Location, + Quantifier, + Range, + RegExpFlags, + RegExpPattern, + Set, + Term, +} from "../types"; +import { + addFlag, + ASSERT_EXISTS, + ASSERT_NEVER_REACH_HERE, + cc, + insertToSet, + isCharacter, +} from "./utils.js"; +import { + digitsCharCodes, + whitespaceCodes, + wordCharCodes, +} from "./character-classes.js"; + +// consts and utilities +const hexDigitPattern = /[0-9a-fA-F]/; +const decimalPattern = /[0-9]/; +const decimalPatternNoZero = /[1-9]/; + +// 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 +export class RegExpParser { + protected idx: number = 0; + protected input: string = ""; + protected groupIdx: number = 0; + + protected saveState() { + return { + idx: this.idx, + input: this.input, + groupIdx: this.groupIdx, + }; + } + + protected restoreState(newState: { + idx: number; + input: string; + groupIdx: number; + }) { + this.idx = newState.idx; + this.input = newState.input; + this.groupIdx = newState.groupIdx; + } + + public pattern(input: string): RegExpPattern { + // parser state + this.idx = 0; + this.input = input; + this.groupIdx = 0; + + this.consumeChar("/"); + const value = this.disjunction(); + this.consumeChar("/"); + + const flags: RegExpFlags = { + type: "Flags", + loc: { begin: this.idx, end: input.length }, + global: false, + ignoreCase: false, + multiLine: false, + unicode: false, + sticky: false, + }; + + while (this.isRegExpFlag()) { + switch (this.popChar()) { + case "g": + addFlag(flags, "global"); + break; + case "i": + addFlag(flags, "ignoreCase"); + break; + case "m": + addFlag(flags, "multiLine"); + break; + case "u": + addFlag(flags, "unicode"); + break; + case "y": + addFlag(flags, "sticky"); + break; + } + } + + if (this.idx !== this.input.length) { + throw Error("Redundant input: " + this.input.substring(this.idx)); + } + return { + type: "Pattern", + flags: flags, + value: value, + loc: this.loc(0), + }; + } + + protected disjunction(): Disjunction { + const alts = []; + const begin = this.idx; + + alts.push(this.alternative()); + + while (this.peekChar() === "|") { + this.consumeChar("|"); + alts.push(this.alternative()); + } + + return { type: "Disjunction", value: alts, loc: this.loc(begin) }; + } + + protected alternative(): Alternative { + const terms = []; + const begin = this.idx; + + while (this.isTerm()) { + terms.push(this.term()); + } + + return { type: "Alternative", value: terms, loc: this.loc(begin) }; + } + + protected term(): Term { + if (this.isAssertion()) { + return this.assertion(); + } else { + return this.atom(); + } + } + + protected assertion(): Assertion { + const begin = this.idx; + switch (this.popChar()) { + case "^": + return { + type: "StartAnchor", + loc: this.loc(begin), + }; + case "$": + return { type: "EndAnchor", loc: this.loc(begin) }; + // '\b' or '\B' + case "\\": + switch (this.popChar()) { + case "b": + return { + type: "WordBoundary", + loc: this.loc(begin), + }; + case "B": + return { + type: "NonWordBoundary", + loc: this.loc(begin), + }; + } + // istanbul ignore next + throw Error("Invalid Assertion Escape"); + // '(?=' or '(?!' + case "(": + this.consumeChar("?"); + + let type: "Lookahead" | "NegativeLookahead" | undefined; + switch (this.popChar()) { + case "=": + type = "Lookahead"; + break; + case "!": + type = "NegativeLookahead"; + break; + } + ASSERT_EXISTS(type); + + const disjunction = this.disjunction(); + + this.consumeChar(")"); + + return { + type: type!, + value: disjunction, + loc: this.loc(begin), + }; + } + // istanbul ignore next + return ASSERT_NEVER_REACH_HERE(); + } + + protected quantifier( + isBacktracking: boolean = false, + ): Quantifier | undefined { + let range: Partial | undefined = undefined; + const begin = this.idx; + switch (this.popChar()) { + case "*": + range = { + atLeast: 0, + atMost: Infinity, + }; + break; + case "+": + range = { + atLeast: 1, + atMost: Infinity, + }; + break; + case "?": + range = { + atLeast: 0, + atMost: 1, + }; + break; + case "{": + const atLeast = this.integerIncludingZero(); + switch (this.popChar()) { + case "}": + range = { + atLeast: atLeast, + atMost: atLeast, + }; + break; + case ",": + let 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; + } + + // istanbul ignore else + if (ASSERT_EXISTS(range)) { + if (this.peekChar(0) === "?") { + this.consumeChar("?"); + range.greedy = false; + } else { + range.greedy = true; + } + + range.type = "Quantifier"; + range.loc = this.loc(begin); + return range as Quantifier; + } + } + + protected atom(): Atom { + let atom: Omit | undefined; + const begin = this.idx; + switch (this.peekChar()) { + case ".": + atom = this.dotAll(); + break; + case "\\": + atom = this.atomEscape(); + break; + case "[": + atom = this.characterClass(); + break; + case "(": + atom = this.group(); + break; + } + + if (atom === undefined && this.isPatternCharacter()) { + atom = this.patternCharacter(); + } + + // istanbul ignore else + if (ASSERT_EXISTS(atom)) { + atom.loc = this.loc(begin); + + if (this.isQuantifier()) { + atom.quantifier = this.quantifier(); + } + + return atom; + } + + // istanbul ignore next + return ASSERT_NEVER_REACH_HERE(); + } + + protected dotAll(): Omit { + this.consumeChar("."); + return { + type: "Set", + complement: true, + value: [cc("\n"), cc("\r"), cc("\u2028"), cc("\u2029")], + }; + } + + protected atomEscape(): Omit { + 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(); + } + } + + protected decimalEscapeAtom(): Omit { + const value = this.positiveInteger(); + + return { type: "GroupBackReference", value: value }; + } + + protected characterClassEscape(): Omit { + let set: (number | Range)[] | undefined; + let 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; + } + + // istanbul ignore else + if (ASSERT_EXISTS(set)) { + return { type: "Set", value: set, complement: complement }; + } + // istanbul ignore next + return ASSERT_NEVER_REACH_HERE(); + } + + protected controlEscapeAtom(): Omit { + let 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; + } + + // istanbul ignore else + if (ASSERT_EXISTS(escapeCode)) { + return { type: "Character", value: escapeCode }; + } + // istanbul ignore next + return ASSERT_NEVER_REACH_HERE(); + } + + protected controlLetterEscapeAtom(): Omit { + this.consumeChar("c"); + const letter = this.popChar(); + if (/[a-zA-Z]/.test(letter) === false) { + throw Error("Invalid "); + } + + const letterCode = letter.toUpperCase().charCodeAt(0) - 64; + return { type: "Character", value: letterCode }; + } + + protected nulCharacterAtom(): Omit { + // TODO implement '[lookahead ∉ DecimalDigit]' + // TODO: for the deprecated octal escape sequence + this.consumeChar("0"); + return { type: "Character", value: cc("\0") }; + } + + protected hexEscapeSequenceAtom(): Omit { + this.consumeChar("x"); + return this.parseHexDigits(2); + } + + protected regExpUnicodeEscapeSequenceAtom(): Omit { + this.consumeChar("u"); + return this.parseHexDigits(4); + } + + protected identityEscapeAtom(): Omit { + // TODO: implement "SourceCharacter but not UnicodeIDContinue" + // // http://unicode.org/reports/tr31/#Specific_Character_Adjustments + const escapedChar = this.popChar(); + return { type: "Character", value: cc(escapedChar) }; + } + + protected classPatternCharacterAtom(): Omit { + 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: + const nextChar = this.popChar(); + return { type: "Character", value: cc(nextChar) }; + } + } + + protected characterClass(): Omit { + const set: (number | Range)[] = []; + let complement = false; + this.consumeChar("["); + if (this.peekChar(0) === "^") { + this.consumeChar("^"); + complement = true; + } + + while (this.isClassAtom()) { + const from = this.classAtom(); + const isFromSingleChar = from.type === "Character"; + if (isCharacter(from) && this.isRangeDash()) { + this.consumeChar("-"); + const to = this.classAtom(); + const isToSingleChar = to.type === "Character"; + + // a range can only be used when both sides are single characters + if (isCharacter(to)) { + 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 }; + } + + protected classAtom(): Omit { + 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(); + } + } + + protected classEscape(): Omit { + 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(); + } + } + + protected group(): Omit { + let capturing = true; + this.consumeChar("("); + switch (this.peekChar(0)) { + case "?": + this.consumeChar("?"); + this.consumeChar(":"); + capturing = false; + break; + default: + this.groupIdx++; + break; + } + const value = this.disjunction(); + this.consumeChar(")"); + + const groupAst: Omit = { + type: "Group", + capturing: capturing, + value: value, + }; + + if (capturing) { + groupAst["idx"] = this.groupIdx; + } + + return groupAst; + } + + protected positiveInteger(): number { + let 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); + } + + protected integerIncludingZero(): number { + let 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); + } + + protected patternCharacter(): Omit { + const 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) }; + } + } + protected isRegExpFlag(): boolean { + switch (this.peekChar(0)) { + case "g": + case "i": + case "m": + case "u": + case "y": + return true; + default: + return false; + } + } + + protected isRangeDash(): boolean { + return this.peekChar() === "-" && this.isClassAtom(1); + } + + protected isDigit(): boolean { + return decimalPattern.test(this.peekChar(0)); + } + + protected isClassAtom(howMuch = 0): boolean { + switch (this.peekChar(howMuch)) { + case "]": + case "\n": + case "\r": + case "\u2028": + case "\u2029": + return false; + default: + return true; + } + } + + protected isTerm() { + return this.isAtom() || this.isAssertion(); + } + + protected isAtom(): boolean { + 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; + } + } + + protected isAssertion(): boolean { + 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; + } + } + + protected isQuantifier(): boolean { + const prevState = this.saveState(); + try { + return this.quantifier(true) !== undefined; + } catch (e) { + return false; + } finally { + this.restoreState(prevState); + } + } + + protected isPatternCharacter(): boolean { + 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; + } + } + + protected parseHexDigits(howMany: number): Omit { + let hexString = ""; + for (let i = 0; i < howMany; i++) { + const hexChar = this.popChar(); + if (hexDigitPattern.test(hexChar) === false) { + throw Error("Expecting a HexDecimal digits"); + } + hexString += hexChar; + } + const charCode = parseInt(hexString, 16); + return { type: "Character", value: charCode }; + } + + protected peekChar(howMuch = 0): string { + return this.input[this.idx + howMuch]; + } + + protected popChar(): string { + const nextChar = this.peekChar(0); + this.consumeChar(undefined); + return nextChar; + } + + protected consumeChar(char: string | undefined): void { + 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++; + } + + protected loc(begin: number): Location { + return { begin: begin, end: this.idx }; + } +} diff --git a/node_modules/@chevrotain/regexp-to-ast/src/utils.ts b/node_modules/@chevrotain/regexp-to-ast/src/utils.ts new file mode 100644 index 0000000..d59d22b --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/src/utils.ts @@ -0,0 +1,44 @@ +import type { Character, IRegExpAST, RegExpFlags } from "../types"; + +export function cc(char: string): number { + return char.charCodeAt(0); +} + +export function insertToSet(item: T | T[], set: T[]) { + if (Array.isArray(item)) { + item.forEach(function (subItem) { + set.push(subItem); + }); + } else { + set.push(item); + } +} + +export function addFlag( + flagObj: RegExpFlags, + flagKey: keyof Omit, +) { + if (flagObj[flagKey] === true) { + throw "duplicate flag " + flagKey; + } + + const x: boolean = flagObj[flagKey]; + flagObj[flagKey] = true; +} + +export function ASSERT_EXISTS(obj: any): obj is T { + // istanbul ignore next + if (obj === undefined) { + throw Error("Internal Error - Should never get here!"); + } + return true; +} + +// istanbul ignore next +export function ASSERT_NEVER_REACH_HERE(): any { + throw Error("Internal Error - Should never get here!"); +} + +export function isCharacter(obj: { type: string }): obj is Character { + return obj["type"] === "Character"; +} diff --git a/node_modules/@chevrotain/regexp-to-ast/types.d.ts b/node_modules/@chevrotain/regexp-to-ast/types.d.ts new file mode 100644 index 0000000..7432450 --- /dev/null +++ b/node_modules/@chevrotain/regexp-to-ast/types.d.ts @@ -0,0 +1,134 @@ +export class RegExpParser { + pattern: (input: string) => RegExpPattern; +} + +export interface IRegExpAST { + type: string; + loc: Location; +} + +export interface Location { + begin: number; + end: number; +} + +export type RegExpAstPart = + | RegExpPattern + | RegExpFlags + | Disjunction + | Alternative + | Atom + | Assertion + | Quantifier; + +export interface RegExpPattern extends IRegExpAST { + type: "Pattern"; + flags: RegExpFlags; + value: Disjunction; +} + +export interface RegExpFlags extends IRegExpAST { + type: "Flags"; + global: boolean; + ignoreCase: boolean; + multiLine: boolean; + unicode: boolean; + sticky: boolean; +} + +export interface Disjunction extends IRegExpAST { + type: "Disjunction"; + value: Alternative[]; +} + +export interface Alternative extends IRegExpAST { + type: "Alternative"; + value: Term[]; +} + +export type Term = Atom | Assertion; + +export interface Assertion extends IRegExpAST { + type: + | "StartAnchor" + | "EndAnchor" + | "WordBoundary" + | "NonWordBoundary" + | "Lookahead" + | "NegativeLookahead"; + + value?: Disjunction; +} + +export type Atom = Character | Set | Group | GroupBackReference; + +export interface Character extends IRegExpAST { + type: "Character"; + value: number; + quantifier?: Quantifier; +} + +export type Range = { from: number; to: number }; + +export interface Set extends IRegExpAST { + type: "Set"; + complement: boolean; + value: (number | Range)[]; + quantifier?: Quantifier; +} + +export interface Group extends IRegExpAST { + type: "Group"; + value: Disjunction; + capturing: boolean; + idx?: number; + quantifier?: Quantifier; +} + +export interface GroupBackReference extends IRegExpAST { + type: "GroupBackReference"; + value: number; + quantifier?: Quantifier; +} + +export interface Quantifier extends IRegExpAST { + type: "Quantifier"; + atLeast: number; + atMost: number; + greedy: boolean; +} + +export class BaseRegExpVisitor { + /** + * The entry point visitor method. + * This will dispatch to the specific visitor method. + */ + visit(node: IRegExpAST): void; + + /** + * The entry point for visiting the children of a node. + * Override this to filter the types of children visited + * or to support new types of children in extended ASTs. + */ + visitChildren(node: IRegExpAST): void; + + /** + * The specific visitor methods + * Override some of these of create custom visitors. + */ + visitPattern(node: RegExpPattern): void; + visitFlags(node: RegExpFlags): void; + visitDisjunction(node: Disjunction): void; + visitAlternative(node: Alternative): void; + visitStartAnchor(node: Assertion): void; + visitEndAnchor(node: Assertion): void; + visitWordBoundary(node: Assertion): void; + visitNonWordBoundary(node: Assertion): void; + visitLookahead(node: Assertion): void; + visitNegativeLookahead(node: Assertion): void; + visitCharacter(node: Character): void; + visitSet(node: Set): void; + visitGroup(Node: Group): void; + visitGroupBackReference(Node: GroupBackReference): void; + visitQuantifier(Node: Quantifier): void; +} diff --git a/node_modules/@chevrotain/types/LICENSE.txt b/node_modules/@chevrotain/types/LICENSE.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@chevrotain/types/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/types/api.d.ts b/node_modules/@chevrotain/types/api.d.ts new file mode 100644 index 0000000..20e11dc --- /dev/null +++ b/node_modules/@chevrotain/types/api.d.ts @@ -0,0 +1,2790 @@ +export declare const VERSION: string; + +export type ParserMethod = (...args: ARGS) => R; + +/** + * This class does not actually exist 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://chevrotain.io/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://chevrotain.io/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://chevrotain.io/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 - argument 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://chevrotain.io/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 OPTION + */ + protected option( + idx: number, + actionORMethodDef: GrammarAction | DSLMethodOpts, + ): OUT | undefined; + + /** + * 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; + protected or(idx: number, altsOrOpts: IOrAlt[] | OrMethodOpts): T; + + /** + * 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 `tokType`. + * 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://chevrotain.io/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. + * + * @returns The `GrammarAction` return value (OUT) if the optional syntax is encountered + * or `undefined` if not. + */ + protected OPTION( + actionORMethodDef: GrammarAction | DSLMethodOpts, + ): OUT | undefined; + + /** + * @see OPTION + * @hidden + */ + protected OPTION1( + actionORMethodDef: GrammarAction | DSLMethodOpts, + ): OUT | undefined; + + /** + * @see OPTION + * @hidden + */ + protected OPTION2( + actionORMethodDef: GrammarAction | DSLMethodOpts, + ): OUT | undefined; + + /** + * @see OPTION + * @hidden + */ + protected OPTION3( + actionORMethodDef: GrammarAction | DSLMethodOpts, + ): OUT | undefined; + + /** + * @see OPTION + * @hidden + */ + protected OPTION4( + actionORMethodDef: GrammarAction | DSLMethodOpts, + ): OUT | undefined; + + /** + * @see OPTION + * @hidden + */ + protected OPTION5( + actionORMethodDef: GrammarAction | DSLMethodOpts, + ): OUT | undefined; + + /** + * @see OPTION + * @hidden + */ + protected OPTION6( + actionORMethodDef: GrammarAction | DSLMethodOpts, + ): OUT | undefined; + + /** + * @see OPTION + * @hidden + */ + protected OPTION7( + actionORMethodDef: GrammarAction | DSLMethodOpts, + ): OUT | undefined; + + /** + * @see OPTION + * @hidden + */ + protected OPTION8( + actionORMethodDef: GrammarAction | DSLMethodOpts, + ): OUT | undefined; + + /** + * @see OPTION + * @hidden + */ + protected OPTION9( + actionORMethodDef: GrammarAction | DSLMethodOpts, + ): OUT | undefined; + + /** + * 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): T; + protected OR(altsOrOpts: IOrAlt[] | OrMethodOpts): any; + + /** + * @see OR + * @hidden + */ + protected OR1(altsOrOpts: IOrAlt[] | OrMethodOpts): T; + protected OR1(altsOrOpts: IOrAlt[] | OrMethodOpts): any; + + /** + * @see OR + * @hidden + */ + protected OR2(altsOrOpts: IOrAlt[] | OrMethodOpts): T; + protected OR2(altsOrOpts: IOrAlt[] | OrMethodOpts): any; + + /** + * @see OR + * @hidden + */ + protected OR3(altsOrOpts: IOrAlt[] | OrMethodOpts): T; + protected OR3(altsOrOpts: IOrAlt[] | OrMethodOpts): any; + + /** + * @see OR + * @hidden + */ + protected OR4(altsOrOpts: IOrAlt[] | OrMethodOpts): T; + protected OR4(altsOrOpts: IOrAlt[] | OrMethodOpts): any; + + /** + * @see OR + * @hidden + */ + protected OR5(altsOrOpts: IOrAlt[] | OrMethodOpts): T; + protected OR5(altsOrOpts: IOrAlt[] | OrMethodOpts): any; + + /** + * @see OR + * @hidden + */ + protected OR6(altsOrOpts: IOrAlt[] | OrMethodOpts): T; + protected OR6(altsOrOpts: IOrAlt[] | OrMethodOpts): any; + + /** + * @see OR + * @hidden + */ + protected OR7(altsOrOpts: IOrAlt[] | OrMethodOpts): T; + protected OR7(altsOrOpts: IOrAlt[] | OrMethodOpts): any; + + /** + * @see OR + * @hidden + */ + protected OR8(altsOrOpts: IOrAlt[] | OrMethodOpts): T; + protected OR8(altsOrOpts: IOrAlt[] | OrMethodOpts): any; + + /** + * @see OR + * @hidden + */ + protected OR9(altsOrOpts: IOrAlt[] | OrMethodOpts): T; + 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; + + /** + * By default, all token types may be deleted. This behavior may be overridden in inheriting parsers. + * The method receives the expected token type. The token that would be deleted can be received with {@link LA}. + */ + protected canTokenTypeBeDeletedInRecovery(tokType: TokenType): boolean; + + /** + * @deprecated - will be removed in the future + */ + protected getNextPossibleTokenTypes( + grammarPath: ITokenGrammarPath, + ): TokenType[]; + + input: IToken[]; + + /** + * Will consume a single token and return the **next** token, meaning + * the token **after** the skipped token. + */ + 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://chevrotain.io/docs/features/gates.html + */ + protected LA(howMuch: number): IToken; +} + +/** + * A Parser that outputs a Concrete Syntax Tree. + * See: + * - https://chevrotain.io/docs/tutorial/step3_adding_actions_root.html#alternatives + * - https://chevrotain.io/docs/guide/concrete_syntax_tree.html + * For in depth docs. + */ +export declare class CstParser extends BaseParser { + /** + * Creates a Grammar Rule + * + * Note that any parameters of your implementation must be optional as it will + * be called without parameters during the grammar recording phase. + */ + protected RULE void>( + name: string, + implementation: F, + config?: IRuleConfig, + ): ParserMethod, CstNode>; + + /** + * Overrides a Grammar Rule + * See usage example in: https://github.com/chevrotain/chevrotain/blob/master/examples/parser/versioning/versioning.js + */ + protected OVERRIDE_RULE void>( + name: string, + implementation: F, + config?: IRuleConfig, + ): ParserMethod, 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: ParserMethod, + 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: ParserMethod, + options?: SubruleMethodOpts, + ): CstNode; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE1( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): CstNode; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE2( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): CstNode; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE3( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): CstNode; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE4( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): CstNode; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE5( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): CstNode; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE6( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): CstNode; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE7( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): CstNode; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE8( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): CstNode; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE9( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): CstNode; +} + +/** + * A Parser that relies on end user's embedded actions to control its output. + * For more details see: + * - https://chevrotain.io/docs/tutorial/step3_adding_actions_root.html#alternatives + * - https://chevrotain.io/docs/tutorial/step3b_adding_actions_embedded.html#simple-example + */ +export declare class EmbeddedActionsParser extends BaseParser { + /** + * Creates a Grammar Rule + * + * Note that any parameters of your implementation must be optional as it will + * be called without parameters during the grammar recording phase. + */ + protected RULE any>( + name: string, + implementation: F, + config?: IRuleConfig>, + ): ParserMethod, ReturnType>; + + /** + * Overrides a Grammar Rule + * See usage example in: https://github.com/chevrotain/chevrotain/blob/master/examples/parser/versioning/versioning.js + */ + protected OVERRIDE_RULE any>( + name: string, + implementation: F, + config?: IRuleConfig>, + ): ParserMethod, ReturnType>; + + /** + * 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: ParserMethod, + options?: SubruleMethodOpts, + ): R; + + /** + * 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: ParserMethod, + options?: SubruleMethodOpts, + ): R; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE1( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): R; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE2( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): R; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE3( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): R; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE4( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): R; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE5( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): R; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE6( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): R; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE7( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): R; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE8( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): R; + + /** + * @see SUBRULE + * @hidden + */ + protected SUBRULE9( + ruleToCall: ParserMethod, + options?: SubruleMethodOpts, + ): R; +} + +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 ITokenConfig.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" properties + * of the {@link ITokenConfig} config properties. + * + * - 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/chevrotain/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 | undefined; + column: number | undefined; + 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; + + /** + * Should the lexer halt on the **first** error, or continue attempting to tokenize by dropping characters + * until a match is found or the end of input is reached. + * + * Setting `recoveryEnabled` to `false` is useful when you want to **halt quickly** on faulty inputs, + * particularly when dealing with **large** faulty inputs. + * + * By default, `recoveryEnabled` is `true` + */ + recoveryEnabled?: 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 occurred. (optional) + * Will not be provided when lexer is not defined to track lines/columns + * + * @param column - Column number where the error occurred. (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://chevrotain.io/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/chevrotain/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/chevrotain/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/chevrotain/chevrotain/tree/master/examples/lexer/multi_mode_lexer + */ + pop_mode?: boolean; + + /** + * The "longer_alt" property will cause the Lexer to attempt matching against other Token Types + * every time this Token Type has been matched. + * + * This feature can be useful when two or more Token Types have common prefixes which + * cannot be resolved (only) by the ordering of the Tokens in the lexer definition. + * + * - Note that the `longer_alt` capability **cannot be chained**. + * - Note that the **first** matched `longer_alt` takes precendence. + * + * For example see: https://github.com/chevrotain/chevrotain/tree/master/examples/lexer/keywords_vs_identifiers + * For resolving the keywords vs Identifier ambiguity. + */ + longer_alt?: TokenType | 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://chevrotain.io/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 | 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://chevrotain.io/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. 0-indexed. */ + startOffset: number; + /** Line of the first character of the Token. 1-indexed. */ + startLine?: number; + /** + * Column of the first character of the Token. 1-indexed. + * + * For token foo in the following line, startColumn will be 3 and endColumn will be 5. + * ``` + * a foo + * 123456 + * ``` + */ + startColumn?: number; + /** + * Offset of the last character of the Token. 0-indexed. + * Note that this points at the last character, not the end of the token, so the original image would be + * `input.substring(token.startOffset, token.endOffset + 1)`. + */ + endOffset?: number; + /** Line of the last character of the Token. 1-indexed. Will be the same as startLine for single-line tokens.*/ + endLine?: number; + /** Column of the last character of the Token. 1-indexed. See also startColumn. */ + 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://chevrotain.io/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?: (e: IRecognitionException) => T; + /** + * Enable/Disable re-sync error recovery for this specific production. + */ + resyncEnabled?: boolean; +} + +export interface DSLMethodOpts { + /** + * The Grammar to process in this method. + */ + DEF: GrammarAction; + /** + * A semantic constraint on this DSL method + * @see https://github.com/chevrotain/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 { + /** + * The set of alternatives, + * See detailed description in {@link BaseParser.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 { + /** + * 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/chevrotain/chevrotain/blob/master/examples/parser/parametrized_rules/parametrized.js + */ + ARGS?: ARGS; + /** + * A label to be used instead of the subrule's name in the created CST. + */ + LABEL?: string; +} + +export declare type GrammarAction = () => OUT; + +export interface IOrAlt { + GATE?: () => boolean; + ALT: () => T; + /** + * 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; + + /** + * Will throw an error if the visitor is missing any required methods + * - `visitXYZ` for each `XYZ` grammar rule. + */ + validateVisitor(): void; +} + +/** + * A [Concrete Syntax Tree](http://chevrotain.io/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; + /** + * A flag indicating the whole CSTNode has been recovered during **re-sync** error recovery. + * This means that some of the node's children may be missing. + * - Note that single token insertion/deletion recovery would not activate this flag. + * This flag would only be activated in **re-sync** recovery when the rule's + * grammar cannot be fully parsed. + * - See: https://chevrotain.io/docs/tutorial/step4_fault_tolerance.html + * for more info on error recovery and fault tolerance. + */ + readonly recoveredNode?: boolean; + + /** + * Will only be present if the {@link IParserConfig.nodeLocationTracking} is + * **not** set to "none". + * See: https://chevrotain.io/docs/guide/concrete_syntax_tree.html#cstnodes-location + * For more details. + */ + readonly location?: CstNodeLocation; +} + +/** + * 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; + /** + * 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/chevrotain/chevrotain/tree/master/examples/parser/dynamic_tokens) + */ + dynamicTokensEnabled?: boolean; + /** + * Enable computation of CST nodes location. + * By default this is set to "none", meaning this feature is disabled. + * See: http://chevrotain.io/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; + /** + * @experimental + * + * A custom lookahead strategy. + * Can be used to override the default LL(*k*) lookahead behavior. + * + * Note that the default lookahead strategy is very well optimized and using a custom lookahead + * strategy might lead to massively reduced performance. + */ + lookaheadStrategy?: ILookaheadStrategy; +} + +/** + * A set of methods used to customize parsing error messages. + * Call {@link defaultParserErrorProvider} to implement the default behavior + */ +export interface IParserErrorMessageProvider { + /** + * Mismatched Token Error happens when the parser attempted to consume a terminal and failed. + * It corresponds to a failed {@link BaseParser.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 BaseParser.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 BaseParser.AT_LEAST_ONE_SEP} 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 BaseParser.AT_LEAST_ONE_SEP} or {@link BaseParser.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 BaseParser.AT_LEAST_ONE_SEP} 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; +} + +/** + * @experimental + */ +export interface ILLkLookaheadValidator { + validateNoLeftRecursion(rules: Rule[]): ILookaheadValidationError[]; + + validateEmptyOrAlternatives(rules: Rule[]): ILookaheadValidationError[]; + + validateAmbiguousAlternationAlternatives( + rules: Rule[], + maxLookahead: number, + ): ILookaheadValidationError[]; + + validateSomeNonEmptyLookaheadPath( + rules: Rule[], + maxLookahead: number, + ): ILookaheadValidationError[]; +} + +/** + * @experimental + */ +export interface ILLkLookaheadStrategyConstructor { + new (options?: { + maxLookahead?: number; + }): ILookaheadStrategy & ILLkLookaheadValidator; +} + +/** + * @experimental + */ +export const LLkLookaheadStrategy: ILLkLookaheadStrategyConstructor; + +/** + * @experimental + */ +export interface ILookaheadStrategy { + /** + * Performs validations on the grammar specific to this lookahead strategy. + * This method is not called if parser validations are disabled. + * + * @param options.rules All parser rules of the grammar. + * + * @param options.tokenTypes All token types of the grammar. + * + * @param options.grammarName The name of the grammar. + */ + validate(options: { + rules: Rule[]; + tokenTypes: TokenType[]; + grammarName: string; + }): ILookaheadValidationError[]; + + /** + * Initializes the lookahead for a grammar. + * + * Note that this method does not build the lookahead functions. + * It only initializes the internal state of the strategy based on all grammar rules. + * + * @param options.rules All parser rules of the grammar. + */ + initialize?(options: { rules: Rule[] }): void; + + /** + * Builds a lookahead function for alternations/`OR` parser methods. + * + * @param options.prodOccurrence The occurrence number of this `OR` within its rule. + * + * @param options.rule The rule that contains this `OR`. + * + * @param options.maxLookahead The maximum amount of lookahead for this `OR`. + * + * @param options.hasPredicates Whether any of the alternatives contain a predicate. + * + * @param options.dynamicTokensEnabled Whether dynamic tokens are enabled for this parser. + * + * @returns A function that is able to compute which of the alternatives to choose while parsing. + */ + buildLookaheadForAlternation(options: { + prodOccurrence: number; + rule: Rule; + maxLookahead: number; + hasPredicates: boolean; + dynamicTokensEnabled: boolean; + }): (orAlts?: IOrAlt[] | undefined) => number | undefined; + + /** + * Builds a lookahead function for optional productions. + * + * @param options.prodOccurrence The occurrence number of this production within its rule. + * + * @param options.prodType The type of this production. + * + * @param options.rule The rule that contains this production. + * + * @param options.maxLookahead The maximum amount of lookahead for this production. + * + * @param options.dynamicTokensEnabled Whether dynamic tokens are enabled for this parser. + * + * @returns A function is able to compute whether to parse the production or to continue with the rest of the parser rule. + */ + buildLookaheadForOptional(options: { + prodOccurrence: number; + prodType: OptionalProductionType; + rule: Rule; + maxLookahead: number; + dynamicTokensEnabled: boolean; + }): () => boolean; +} + +export interface ILookaheadValidationError { + message: string; + ruleName?: string; +} + +export type LookaheadSequence = TokenType[][]; + +export type OptionalProductionType = + | "Option" + | "RepetitionMandatory" + | "RepetitionMandatoryWithSeparator" + | "Repetition" + | "RepetitionWithSeparator"; + +export type LookaheadProductionType = OptionalProductionType | "Alternation"; + +/** + * Computes all lookahead paths for a given production. + * + * The result is a three-dimensional array of token types. + * Accessing this array with the index of an alternative of the given production returns a two-dimensional array. + * Each entry of this array represents a list of the token types which can occur in this alternative. + * + * @param options.occurrence The occurrence number of this production within its rule. + * + * @param options.rule The rule which contains this production. + * + * @param options.prodType The type of this production. + * + * @param options.maxLookahead The maximum amount of lookahead for this production. + */ +export declare function getLookaheadPaths(options: { + occurrence: number; + rule: Rule; + prodType: LookaheadProductionType; + maxLookahead: number; +}): LookaheadSequence[]; + +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: ProductionType; + definition?: ISerializedGast[]; +} + +export type ProductionType = + | LookaheadProductionType + | "NonTerminal" + | "Alternative" + | "Terminal" + | "Rule"; + +/** + * 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, + MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE = 17, +} + +/** + * 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(): () => undefined; +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 extends Error { + 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; + +/** + * An exception of this type will be saved in {@link BaseParser.errors} when {@link BaseParser.CONSUME} + * was called but failed to match the expected Token Type. + */ +export declare class MismatchedTokenException + extends Error + implements IRecognitionException +{ + context: IRecognizerContext; + resyncedTokens: IToken[]; + token: IToken; + previousToken: IToken; + + constructor(message: string, token: IToken, previousToken: IToken); +} + +/** + * An exception of this type will be saved in {@link BaseParser.errors} when {@link BaseParser.OR} + * was called yet none of the possible alternatives could be matched. + */ +export declare class NoViableAltException + extends Error + implements IRecognitionException +{ + context: IRecognizerContext; + resyncedTokens: IToken[]; + token: IToken; + previousToken: IToken; + + constructor(message: string, token: IToken, previousToken: IToken); +} + +/** + * An exception of this type will be saved in {@link BaseParser.errors} when + * the parser has finished yet there exists remaining input (tokens) that has not processed. + */ +export declare class NotAllInputParsedException + extends Error + implements IRecognitionException +{ + context: IRecognizerContext; + resyncedTokens: IToken[]; + token: IToken; + + constructor(message: string, token: IToken); +} + +/** + * An exception of this type will be saved in {@link BaseParser.errors} when {@link BaseParser.AT_LEAST_ONE_SEP} + * or {@link BaseParser.AT_LEAST_ONE_SEP} was called but failed to match even a single iteration. + */ +export declare class EarlyExitException + extends Error + implements IRecognitionException +{ + context: IRecognizerContext; + resyncedTokens: IToken[]; + token: IToken; + previousToken: IToken; + + constructor(message: string, token: IToken, previousToken: IToken); +} + +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 visitAlternative(node: Alternative): 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 CstParser.RULE} or {@link EmbeddedActionsParser.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 CstParser.SUBRULE} or {@link EmbeddedActionsParser.SUBRULE} call. + */ +export declare class NonTerminal implements IProductionWithOccurrence { + nonTerminalName: string; + label?: string; + referencedRule: Rule; + idx: number; + constructor(options: { + nonTerminalName: string; + label?: string; + referencedRule?: Rule; + idx?: number; + }); + definition: IProduction[]; + accept(visitor: IGASTVisitor): void; +} + +/** + * The Grammar AST class used to represent a single alternative in an {@link Alternation}. + */ +export declare class Alternative { + definition: IProduction[]; + ignoreAmbiguities: boolean; + + constructor(options: { + definition: IProduction[]; + ignoreAmbiguities?: boolean; + }); + + accept(visitor: IGASTVisitor): void; +} + +/** + * The Grammar AST class representing a {@link BaseParser.OPTION} call. + */ +export declare class Option implements IProductionWithOccurrence { + idx: number; + definition: IProduction[]; + + constructor(options: { + definition: IProduction[]; + idx?: number; + name?: string; + }); + + accept(visitor: IGASTVisitor): void; +} + +/** + * The Grammar AST class representing a {@link BaseParser.AT_LEAST_ONE_SEP} call. + */ +export declare class RepetitionMandatory implements IProductionWithOccurrence { + idx: number; + definition: IProduction[]; + + constructor(options: { + definition: IProduction[]; + idx?: number; + name?: string; + }); + + accept(visitor: IGASTVisitor): void; +} + +/** + * The Grammar AST class representing a {@link BaseParser.AT_LEAST_ONE_SEP} call. + */ +export declare class RepetitionMandatoryWithSeparator + implements IProductionWithOccurrence +{ + separator: TokenType; + idx: number; + definition: IProduction[]; + + constructor(options: { + definition: IProduction[]; + separator: TokenType; + idx?: number; + name?: string; + }); + + accept(visitor: IGASTVisitor): void; +} + +/** + * The Grammar AST class representing a {@link BaseParser.MANY} call. + */ +export declare class Repetition implements IProductionWithOccurrence { + separator: TokenType; + idx: number; + definition: IProduction[]; + + constructor(options: { + definition: IProduction[]; + idx?: number; + name?: string; + }); + + accept(visitor: IGASTVisitor): void; +} + +/** + * The Grammar AST class representing a {@link BaseParser.MANY_SEP} call. + */ +export declare class RepetitionWithSeparator + implements IProductionWithOccurrence +{ + separator: TokenType; + idx: number; + definition: IProduction[]; + + constructor(options: { + definition: IProduction[]; + separator: TokenType; + idx?: number; + name?: string; + }); + + accept(visitor: IGASTVisitor): void; +} + +/** + * The Grammar AST class representing a {@link BaseParser.OR} call. + */ +export declare class Alternation implements IProductionWithOccurrence { + idx: number; + definition: IProduction[]; + + constructor(options: { definition: IProduction[]; idx?: number }); + + accept(visitor: IGASTVisitor): void; +} + +/** + * The Grammar AST class representing a {@link BaseParser.CONSUME} call. + */ +export declare class Terminal implements IProductionWithOccurrence { + terminalType: TokenType; + label?: string; + idx: number; + constructor(options: { + terminalType: TokenType; + label?: string; + 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; + +/** + * @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://chevrotain.io/docs/guide/generating_syntax_diagrams.html). + */ +export declare function createSyntaxDiagramsCode( + grammar: ISerializedGast[], + config?: ICreateSyntaxDiagramsConfig, +): string; + +/** + * Will generate TypeScript definitions source code (text). + * For a set of {@link Rule}. + * + * This set of Rules can be obtained from a Parser **instance** via the + * {@link BaseParser.getGAstProductions} method. + * + * Note that this function produces a **string** the output. + * It is the responsibility of the end-user to create the signatures files. + * - e.g: via `fs.writeFileSync()` + * + * See: https://chevrotain.io/docs/guide/concrete_syntax_tree.html#cst-typescript-signatures + */ +export declare function generateCstDts( + productions: Record, + options?: GenerateDtsOptions, +): string; + +export declare type GenerateDtsOptions = { + /** + * `true` by default. + * Disable this to prevent the generation of the CSTVisitor interface. + * For example, if a different traversal method on the CST has been implemented + * by the end-user and the Chevrotain CST Visitor apis are not used. + */ + includeVisitorInterface?: boolean; + /** + * The generated visitor interface will be called `ICstNodeVisitor` by default + * This parameter enables giving it a more specific name, for example: `MyCstVisitor` or `JohnDoe` + */ + visitorInterfaceName?: string; +}; diff --git a/node_modules/@chevrotain/types/package.json b/node_modules/@chevrotain/types/package.json new file mode 100644 index 0000000..8019eac --- /dev/null +++ b/node_modules/@chevrotain/types/package.json @@ -0,0 +1,50 @@ +{ + "name": "@chevrotain/types", + "version": "11.0.3", + "description": "Type Signatures and API Website for Chevrotain", + "keywords": [], + "bugs": { + "url": "https://github.com/Chevrotain/chevrotain/issues" + }, + "license": "Apache-2.0", + "author": { + "name": "Shahar Soel" + }, + "files": [ + "api.d.ts", + "README.md", + "LICENSE.TXT" + ], + "type": "module", + "types": "./api.d.ts", + "exports": { + ".": { + "types": "./api.d.ts" + } + }, + "repository": { + "type": "git", + "url": "git://github.com/Chevrotain/chevrotain.git" + }, + "homepage": "https://chevrotain.io/documentation/", + "scripts": { + "---------- CI FLOWS --------": "", + "ci": "pnpm run build", + "build": "npm-run-all clean compile api-site:build", + "postversion": "npm-run-all api-site:build api-site:upload", + "---------- BUILD STEPS --------": "", + "clean": "shx rm -rf dev lib", + "compile:watch": "tsc -w", + "compile": "tsc", + "api-site:build": "typedoc api.d.ts --out dev/docs --excludeExternals --excludePrivate", + "api-site:upload": "./scripts/api-site-upload.sh" + }, + "devDependencies": { + "typedoc": "0.24.8", + "typescript": "5.1.6" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "ac5806631779035c2c1955744a47d8ed4f25a175" +} diff --git a/node_modules/@chevrotain/utils/LICENSE.txt b/node_modules/@chevrotain/utils/LICENSE.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/@chevrotain/utils/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/utils/lib/src/api.d.ts b/node_modules/@chevrotain/utils/lib/src/api.d.ts new file mode 100644 index 0000000..ce7ef20 --- /dev/null +++ b/node_modules/@chevrotain/utils/lib/src/api.d.ts @@ -0,0 +1,3 @@ +export { PRINT_WARNING, PRINT_ERROR } from "./print.js"; +export { timer } from "./timer.js"; +export { toFastProperties } from "./to-fast-properties.js"; diff --git a/node_modules/@chevrotain/utils/lib/src/api.js b/node_modules/@chevrotain/utils/lib/src/api.js new file mode 100644 index 0000000..4d58ae4 --- /dev/null +++ b/node_modules/@chevrotain/utils/lib/src/api.js @@ -0,0 +1,4 @@ +export { PRINT_WARNING, PRINT_ERROR } from "./print.js"; +export { timer } from "./timer.js"; +export { toFastProperties } from "./to-fast-properties.js"; +//# sourceMappingURL=api.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/utils/lib/src/api.js.map b/node_modules/@chevrotain/utils/lib/src/api.js.map new file mode 100644 index 0000000..a42c6c4 --- /dev/null +++ b/node_modules/@chevrotain/utils/lib/src/api.js.map @@ -0,0 +1 @@ +{"version":3,"file":"api.js","sourceRoot":"","sources":["../../src/api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACxD,OAAO,EAAE,KAAK,EAAE,MAAM,YAAY,CAAC;AACnC,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC"} \ No newline at end of file diff --git a/node_modules/@chevrotain/utils/lib/src/print.d.ts b/node_modules/@chevrotain/utils/lib/src/print.d.ts new file mode 100644 index 0000000..68d0e71 --- /dev/null +++ b/node_modules/@chevrotain/utils/lib/src/print.d.ts @@ -0,0 +1,2 @@ +export declare function PRINT_ERROR(msg: string): void; +export declare function PRINT_WARNING(msg: string): void; diff --git a/node_modules/@chevrotain/utils/lib/src/print.js b/node_modules/@chevrotain/utils/lib/src/print.js new file mode 100644 index 0000000..e927691 --- /dev/null +++ b/node_modules/@chevrotain/utils/lib/src/print.js @@ -0,0 +1,14 @@ +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}`); + } +} +//# sourceMappingURL=print.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/utils/lib/src/print.js.map b/node_modules/@chevrotain/utils/lib/src/print.js.map new file mode 100644 index 0000000..bf3522d --- /dev/null +++ b/node_modules/@chevrotain/utils/lib/src/print.js.map @@ -0,0 +1 @@ +{"version":3,"file":"print.js","sourceRoot":"","sources":["../../src/print.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,WAAW,CAAC,GAAW;IACrC,qEAAqE;IACrE,IAAI,OAAO,IAAI,OAAO,CAAC,KAAK,EAAE;QAC5B,OAAO,CAAC,KAAK,CAAC,UAAU,GAAG,EAAE,CAAC,CAAC;KAChC;AACH,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,GAAW;IACvC,oEAAoE;IACpE,IAAI,OAAO,IAAI,OAAO,CAAC,IAAI,EAAE;QAC3B,gCAAgC;QAChC,OAAO,CAAC,IAAI,CAAC,YAAY,GAAG,EAAE,CAAC,CAAC;KACjC;AACH,CAAC"} \ No newline at end of file diff --git a/node_modules/@chevrotain/utils/lib/src/timer.d.ts b/node_modules/@chevrotain/utils/lib/src/timer.d.ts new file mode 100644 index 0000000..4b744f1 --- /dev/null +++ b/node_modules/@chevrotain/utils/lib/src/timer.d.ts @@ -0,0 +1,4 @@ +export declare function timer(func: () => T): { + time: number; + value: T; +}; diff --git a/node_modules/@chevrotain/utils/lib/src/timer.js b/node_modules/@chevrotain/utils/lib/src/timer.js new file mode 100644 index 0000000..bccd478 --- /dev/null +++ b/node_modules/@chevrotain/utils/lib/src/timer.js @@ -0,0 +1,8 @@ +export function timer(func) { + const start = new Date().getTime(); + const val = func(); + const end = new Date().getTime(); + const total = end - start; + return { time: total, value: val }; +} +//# sourceMappingURL=timer.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/utils/lib/src/timer.js.map b/node_modules/@chevrotain/utils/lib/src/timer.js.map new file mode 100644 index 0000000..b0b3b9c --- /dev/null +++ b/node_modules/@chevrotain/utils/lib/src/timer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"timer.js","sourceRoot":"","sources":["../../src/timer.ts"],"names":[],"mappings":"AAAA,MAAM,UAAU,KAAK,CAAI,IAAa;IACpC,MAAM,KAAK,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC;IACnC,MAAM,GAAG,GAAG,IAAI,EAAE,CAAC;IACnB,MAAM,GAAG,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC;IACjC,MAAM,KAAK,GAAG,GAAG,GAAG,KAAK,CAAC;IAC1B,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;AACrC,CAAC"} \ No newline at end of file diff --git a/node_modules/@chevrotain/utils/lib/src/to-fast-properties.d.ts b/node_modules/@chevrotain/utils/lib/src/to-fast-properties.d.ts new file mode 100644 index 0000000..2800bb7 --- /dev/null +++ b/node_modules/@chevrotain/utils/lib/src/to-fast-properties.d.ts @@ -0,0 +1 @@ +export declare function toFastProperties(toBecomeFast: any): any; diff --git a/node_modules/@chevrotain/utils/lib/src/to-fast-properties.js b/node_modules/@chevrotain/utils/lib/src/to-fast-properties.js new file mode 100644 index 0000000..cb04dfd --- /dev/null +++ b/node_modules/@chevrotain/utils/lib/src/to-fast-properties.js @@ -0,0 +1,24 @@ +// based 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; + const 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(); + // Always true condition to suppress the Firefox warning of unreachable + // code after a return statement. + if (1) + return toBecomeFast; + // Eval prevents optimization of this method (even though this is dead code) + // - https://esbuild.github.io/content-types/#direct-eval + /* istanbul ignore next */ + // tslint:disable-next-line + (0, eval)(toBecomeFast); +} +//# sourceMappingURL=to-fast-properties.js.map \ No newline at end of file diff --git a/node_modules/@chevrotain/utils/lib/src/to-fast-properties.js.map b/node_modules/@chevrotain/utils/lib/src/to-fast-properties.js.map new file mode 100644 index 0000000..95bec3c --- /dev/null +++ b/node_modules/@chevrotain/utils/lib/src/to-fast-properties.js.map @@ -0,0 +1 @@ +{"version":3,"file":"to-fast-properties.js","sourceRoot":"","sources":["../../src/to-fast-properties.ts"],"names":[],"mappings":"AAAA,yHAAyH;AACzH,MAAM,UAAU,gBAAgB,CAAC,YAAiB;IAChD,SAAS,eAAe,KAAI,CAAC;IAE7B,2DAA2D;IAC3D,eAAe,CAAC,SAAS,GAAG,YAAY,CAAC;IACzC,MAAM,YAAY,GAAG,IAAK,eAAuB,EAAE,CAAC;IAEpD,SAAS,UAAU;QACjB,OAAO,OAAO,YAAY,CAAC,GAAG,CAAC;IACjC,CAAC;IAED,kEAAkE;IAClE,qBAAqB;IACrB,UAAU,EAAE,CAAC;IACb,UAAU,EAAE,CAAC;IAEb,uEAAuE;IACvE,iCAAiC;IACjC,IAAI,CAAC;QAAE,OAAO,YAAY,CAAC;IAE3B,4EAA4E;IAC5E,yDAAyD;IACzD,0BAA0B;IAC1B,2BAA2B;IAC3B,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,YAAY,CAAC,CAAC;AAC1B,CAAC"} \ No newline at end of file diff --git a/node_modules/@chevrotain/utils/package.json b/node_modules/@chevrotain/utils/package.json new file mode 100644 index 0000000..1d5384d --- /dev/null +++ b/node_modules/@chevrotain/utils/package.json @@ -0,0 +1,46 @@ +{ + "name": "@chevrotain/utils", + "version": "11.0.3", + "description": "common utilities", + "keywords": [], + "bugs": { + "url": "https://github.com/Chevrotain/chevrotain/issues" + }, + "license": "Apache-2.0", + "author": { + "name": "Shahar Soel" + }, + "type": "module", + "types": "./lib/src/api.d.ts", + "exports": { + ".": { + "import": "./lib/src/api.js", + "types": "./lib/src/api.d.ts" + } + }, + "files": [ + "lib/src/**/*.js", + "lib/src/**/*.map", + "lib/src/**/*.d.ts", + "src/**/*.ts" + ], + "repository": { + "type": "git", + "url": "git://github.com/Chevrotain/chevrotain.git" + }, + "scripts": { + "---------- CI FLOWS --------": "", + "ci": "npm-run-all build test", + "build": "npm-run-all clean compile", + "test": "npm-run-all coverage", + "---------- BUILD STEPS --------": "", + "clean": "shx rm -rf lib coverage", + "compile:watch": "tsc -w", + "compile": "tsc", + "coverage": "c8 mocha --enable-source-maps" + }, + "publishConfig": { + "access": "public" + }, + "gitHead": "ac5806631779035c2c1955744a47d8ed4f25a175" +} diff --git a/node_modules/@chevrotain/utils/src/api.ts b/node_modules/@chevrotain/utils/src/api.ts new file mode 100644 index 0000000..ce7ef20 --- /dev/null +++ b/node_modules/@chevrotain/utils/src/api.ts @@ -0,0 +1,3 @@ +export { PRINT_WARNING, PRINT_ERROR } from "./print.js"; +export { timer } from "./timer.js"; +export { toFastProperties } from "./to-fast-properties.js"; diff --git a/node_modules/@chevrotain/utils/src/print.ts b/node_modules/@chevrotain/utils/src/print.ts new file mode 100644 index 0000000..db74134 --- /dev/null +++ b/node_modules/@chevrotain/utils/src/print.ts @@ -0,0 +1,14 @@ +export function PRINT_ERROR(msg: string) { + /* istanbul ignore else - can't override global.console in node.js */ + if (console && console.error) { + console.error(`Error: ${msg}`); + } +} + +export function PRINT_WARNING(msg: string) { + /* istanbul ignore else - can't override global.console in node.js*/ + if (console && console.warn) { + // TODO: modify docs accordingly + console.warn(`Warning: ${msg}`); + } +} diff --git a/node_modules/@chevrotain/utils/src/timer.ts b/node_modules/@chevrotain/utils/src/timer.ts new file mode 100644 index 0000000..f41a47f --- /dev/null +++ b/node_modules/@chevrotain/utils/src/timer.ts @@ -0,0 +1,7 @@ +export function timer(func: () => T): { time: number; value: T } { + const start = new Date().getTime(); + const val = func(); + const end = new Date().getTime(); + const total = end - start; + return { time: total, value: val }; +} diff --git a/node_modules/@chevrotain/utils/src/to-fast-properties.ts b/node_modules/@chevrotain/utils/src/to-fast-properties.ts new file mode 100644 index 0000000..4275ad7 --- /dev/null +++ b/node_modules/@chevrotain/utils/src/to-fast-properties.ts @@ -0,0 +1,27 @@ +// based on: https://github.com/petkaantonov/bluebird/blob/b97c0d2d487e8c5076e8bd897e0dcd4622d31846/src/util.js#L201-L216 +export function toFastProperties(toBecomeFast: any) { + function FakeConstructor() {} + + // If our object is used as a constructor, it would receive + FakeConstructor.prototype = toBecomeFast; + const fakeInstance = new (FakeConstructor as any)(); + + function fakeAccess() { + return typeof fakeInstance.bar; + } + + // help V8 understand this is a "real" prototype by actually using + // the fake instance. + fakeAccess(); + fakeAccess(); + + // Always true condition to suppress the Firefox warning of unreachable + // code after a return statement. + if (1) return toBecomeFast; + + // Eval prevents optimization of this method (even though this is dead code) + // - https://esbuild.github.io/content-types/#direct-eval + /* istanbul ignore next */ + // tslint:disable-next-line + (0, eval)(toBecomeFast); +} diff --git a/node_modules/chevrotain-allstar/LICENSE b/node_modules/chevrotain-allstar/LICENSE new file mode 100644 index 0000000..01e35be --- /dev/null +++ b/node_modules/chevrotain-allstar/LICENSE @@ -0,0 +1,16 @@ +Copyright 2022 TypeFox GmbH + +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. diff --git a/node_modules/chevrotain-allstar/README.md b/node_modules/chevrotain-allstar/README.md new file mode 100644 index 0000000..55fdc51 --- /dev/null +++ b/node_modules/chevrotain-allstar/README.md @@ -0,0 +1,22 @@ +# Chevrotain Allstar + +This is a lookahead plugin package for the [Chevrotain parser library](https://chevrotain.io/). +It implements the [ALL(*) lookahead algorithm](https://www.antlr.org/papers/allstar-techreport.pdf) introduced for ANTLR4. +The algorithm features unbounded lookahead, compared to the normal LL(*k*) behavior of Chevrotain. + +## Usage + +When creating your parser, pass an instance of the `LLStarLookaheadStrategy` to the `lookaheadStrategy` property of the base parser constructor options. + +```ts +import { LLStarLookaheadStrategy } from "chevrotain-allstar"; + +class Parser extends EmbeddedActionsParser { + constructor() { + super(tokens, { + lookaheadStrategy: new LLStarLookaheadStrategy() + }); + this.performSelfAnalysis() + } +} +``` diff --git a/node_modules/chevrotain-allstar/lib/all-star-lookahead.d.ts b/node_modules/chevrotain-allstar/lib/all-star-lookahead.d.ts new file mode 100644 index 0000000..2f8758a --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/all-star-lookahead.d.ts @@ -0,0 +1,36 @@ +/****************************************************************************** + * Copyright 2022 TypeFox GmbH + * This program and the accompanying materials are made available under the + * terms of the MIT License, which is available in the project root. + ******************************************************************************/ +import { Rule, BaseParser, LLkLookaheadStrategy, ILookaheadValidationError, IOrAlt, OptionalProductionType } from "chevrotain"; +export type AmbiguityReport = (message: string) => void; +export interface LLStarLookaheadOptions { + logging?: AmbiguityReport; +} +export declare class LLStarLookaheadStrategy extends LLkLookaheadStrategy { + private atn; + private dfas; + private logging; + constructor(options?: LLStarLookaheadOptions); + initialize(options: { + rules: Rule[]; + }): void; + validateAmbiguousAlternationAlternatives(): ILookaheadValidationError[]; + validateEmptyOrAlternatives(): ILookaheadValidationError[]; + buildLookaheadForAlternation(options: { + prodOccurrence: number; + rule: Rule; + maxLookahead: number; + hasPredicates: boolean; + dynamicTokensEnabled: boolean; + }): (this: BaseParser, orAlts?: IOrAlt[] | undefined) => number | undefined; + buildLookaheadForOptional(options: { + prodOccurrence: number; + prodType: OptionalProductionType; + rule: Rule; + maxLookahead: number; + dynamicTokensEnabled: boolean; + }): (this: BaseParser) => boolean; +} +//# sourceMappingURL=all-star-lookahead.d.ts.map \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/lib/all-star-lookahead.d.ts.map b/node_modules/chevrotain-allstar/lib/all-star-lookahead.d.ts.map new file mode 100644 index 0000000..5ff119c --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/all-star-lookahead.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"all-star-lookahead.d.ts","sourceRoot":"","sources":["../src/all-star-lookahead.ts"],"names":[],"mappings":"AAAA;;;;gFAIgF;AAEhF,OAAO,EAKH,IAAI,EAUJ,UAAU,EACV,oBAAoB,EACpB,yBAAyB,EACzB,MAAM,EAEN,sBAAsB,EACzB,MAAM,YAAY,CAAC;AAgCpB,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;AAkDxD,MAAM,WAAW,sBAAsB;IACnC,OAAO,CAAC,EAAE,eAAe,CAAA;CAC5B;AAED,qBAAa,uBAAwB,SAAQ,oBAAoB;IAE7D,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,IAAI,CAAa;IACzB,OAAO,CAAC,OAAO,CAAkB;gBAErB,OAAO,CAAC,EAAE,sBAAsB;IAKnC,UAAU,CAAC,OAAO,EAAE;QAAE,KAAK,EAAE,IAAI,EAAE,CAAA;KAAE,GAAG,IAAI;IAK5C,wCAAwC,IAAI,yBAAyB,EAAE;IAIvE,2BAA2B,IAAI,yBAAyB,EAAE;IAI1D,4BAA4B,CAAC,OAAO,EAAE;QAC3C,cAAc,EAAE,MAAM,CAAC;QACvB,IAAI,EAAE,IAAI,CAAC;QACX,YAAY,EAAE,MAAM,CAAC;QACrB,aAAa,EAAE,OAAO,CAAC;QACvB,oBAAoB,EAAE,OAAO,CAAA;KAChC,GAAG,CAAC,IAAI,EAAE,UAAU,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,GAAG,CAAC,EAAE,GAAG,SAAS,KAAK,MAAM,GAAG,SAAS;IAuEvE,yBAAyB,CAAC,OAAO,EAAE;QACxC,cAAc,EAAE,MAAM,CAAC;QACvB,QAAQ,EAAE,sBAAsB,CAAC;QACjC,IAAI,EAAE,IAAI,CAAC;QACX,YAAY,EAAE,MAAM,CAAC;QACrB,oBAAoB,EAAE,OAAO,CAAA;KAChC,GAAG,CAAC,IAAI,EAAE,UAAU,KAAK,OAAO;CA4DpC"} \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/lib/all-star-lookahead.js b/node_modules/chevrotain-allstar/lib/all-star-lookahead.js new file mode 100644 index 0000000..2adc731 --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/all-star-lookahead.js @@ -0,0 +1,556 @@ +/****************************************************************************** + * Copyright 2022 TypeFox GmbH + * This program and the accompanying materials are made available under the + * terms of the MIT License, which is available in the project root. + ******************************************************************************/ +import { tokenMatcher, tokenLabel, NonTerminal, Alternation, Option, RepetitionMandatory, RepetitionMandatoryWithSeparator, RepetitionWithSeparator, Repetition, Terminal, LLkLookaheadStrategy, getLookaheadPaths } from "chevrotain"; +import { ATN_RULE_STOP, AtomTransition, buildATNKey, createATN, EpsilonTransition, RuleTransition } from "./atn.js"; +import { ATNConfigSet, DFA_ERROR, getATNConfigKey } from "./dfa.js"; +import min from "lodash-es/min.js"; +import flatMap from "lodash-es/flatMap.js"; +import uniqBy from "lodash-es/uniqBy.js"; +import map from "lodash-es/map.js"; +import flatten from "lodash-es/flatten.js"; +import forEach from "lodash-es/forEach.js"; +import isEmpty from "lodash-es/isEmpty.js"; +import reduce from "lodash-es/reduce.js"; +function createDFACache(startState, decision) { + const map = {}; + return (predicateSet) => { + const key = predicateSet.toString(); + let existing = map[key]; + if (existing !== undefined) { + return existing; + } + else { + existing = { + atnStartState: startState, + decision, + states: {} + }; + map[key] = existing; + return existing; + } + }; +} +class PredicateSet { + constructor() { + this.predicates = []; + } + is(index) { + return index >= this.predicates.length || this.predicates[index]; + } + set(index, value) { + this.predicates[index] = value; + } + toString() { + let value = ""; + const size = this.predicates.length; + for (let i = 0; i < size; i++) { + value += this.predicates[i] === true ? "1" : "0"; + } + return value; + } +} +const EMPTY_PREDICATES = new PredicateSet(); +export class LLStarLookaheadStrategy extends LLkLookaheadStrategy { + constructor(options) { + var _a; + super(); + this.logging = (_a = options === null || options === void 0 ? void 0 : options.logging) !== null && _a !== void 0 ? _a : ((message) => console.log(message)); + } + initialize(options) { + this.atn = createATN(options.rules); + this.dfas = initATNSimulator(this.atn); + } + validateAmbiguousAlternationAlternatives() { + return []; + } + validateEmptyOrAlternatives() { + return []; + } + buildLookaheadForAlternation(options) { + const { prodOccurrence, rule, hasPredicates, dynamicTokensEnabled } = options; + const dfas = this.dfas; + const logging = this.logging; + const key = buildATNKey(rule, 'Alternation', prodOccurrence); + const decisionState = this.atn.decisionMap[key]; + const decisionIndex = decisionState.decision; + const partialAlts = map(getLookaheadPaths({ + maxLookahead: 1, + occurrence: prodOccurrence, + prodType: "Alternation", + rule: rule + }), (currAlt) => map(currAlt, (path) => path[0])); + if (isLL1Sequence(partialAlts, false) && !dynamicTokensEnabled) { + const choiceToAlt = reduce(partialAlts, (result, currAlt, idx) => { + forEach(currAlt, (currTokType) => { + if (currTokType) { + result[currTokType.tokenTypeIdx] = idx; + forEach(currTokType.categoryMatches, (currExtendingType) => { + result[currExtendingType] = idx; + }); + } + }); + return result; + }, {}); + if (hasPredicates) { + return function (orAlts) { + var _a; + const nextToken = this.LA(1); + const prediction = choiceToAlt[nextToken.tokenTypeIdx]; + if (orAlts !== undefined && prediction !== undefined) { + const gate = (_a = orAlts[prediction]) === null || _a === void 0 ? void 0 : _a.GATE; + if (gate !== undefined && gate.call(this) === false) { + return undefined; + } + } + return prediction; + }; + } + else { + return function () { + const nextToken = this.LA(1); + return choiceToAlt[nextToken.tokenTypeIdx]; + }; + } + } + else if (hasPredicates) { + return function (orAlts) { + const predicates = new PredicateSet(); + const length = orAlts === undefined ? 0 : orAlts.length; + for (let i = 0; i < length; i++) { + const gate = orAlts === null || orAlts === void 0 ? void 0 : orAlts[i].GATE; + predicates.set(i, gate === undefined || gate.call(this)); + } + const result = adaptivePredict.call(this, dfas, decisionIndex, predicates, logging); + return typeof result === 'number' ? result : undefined; + }; + } + else { + return function () { + const result = adaptivePredict.call(this, dfas, decisionIndex, EMPTY_PREDICATES, logging); + return typeof result === 'number' ? result : undefined; + }; + } + } + buildLookaheadForOptional(options) { + const { prodOccurrence, rule, prodType, dynamicTokensEnabled } = options; + const dfas = this.dfas; + const logging = this.logging; + const key = buildATNKey(rule, prodType, prodOccurrence); + const decisionState = this.atn.decisionMap[key]; + const decisionIndex = decisionState.decision; + const alts = map(getLookaheadPaths({ + maxLookahead: 1, + occurrence: prodOccurrence, + prodType, + rule + }), (e) => { + return map(e, (g) => g[0]); + }); + if (isLL1Sequence(alts) && alts[0][0] && !dynamicTokensEnabled) { + const alt = alts[0]; + const singleTokensTypes = flatten(alt); + if (singleTokensTypes.length === 1 && + isEmpty(singleTokensTypes[0].categoryMatches)) { + const expectedTokenType = singleTokensTypes[0]; + const expectedTokenUniqueKey = expectedTokenType.tokenTypeIdx; + return function () { + return this.LA(1).tokenTypeIdx === expectedTokenUniqueKey; + }; + } + else { + const choiceToAlt = reduce(singleTokensTypes, (result, currTokType) => { + if (currTokType !== undefined) { + result[currTokType.tokenTypeIdx] = true; + forEach(currTokType.categoryMatches, (currExtendingType) => { + result[currExtendingType] = true; + }); + } + return result; + }, {}); + return function () { + const nextToken = this.LA(1); + return choiceToAlt[nextToken.tokenTypeIdx] === true; + }; + } + } + return function () { + const result = adaptivePredict.call(this, dfas, decisionIndex, EMPTY_PREDICATES, logging); + return typeof result === "object" ? false : result === 0; + }; + } +} +function isLL1Sequence(sequences, allowEmpty = true) { + const fullSet = new Set(); + for (const alt of sequences) { + const altSet = new Set(); + for (const tokType of alt) { + if (tokType === undefined) { + if (allowEmpty) { + // Epsilon production encountered + break; + } + else { + return false; + } + } + const indices = [tokType.tokenTypeIdx].concat(tokType.categoryMatches); + for (const index of indices) { + if (fullSet.has(index)) { + if (!altSet.has(index)) { + return false; + } + } + else { + fullSet.add(index); + altSet.add(index); + } + } + } + } + return true; +} +function initATNSimulator(atn) { + const decisionLength = atn.decisionStates.length; + const decisionToDFA = Array(decisionLength); + for (let i = 0; i < decisionLength; i++) { + decisionToDFA[i] = createDFACache(atn.decisionStates[i], i); + } + return decisionToDFA; +} +function adaptivePredict(dfaCaches, decision, predicateSet, logging) { + const dfa = dfaCaches[decision](predicateSet); + let start = dfa.start; + if (start === undefined) { + const closure = computeStartState(dfa.atnStartState); + start = addDFAState(dfa, newDFAState(closure)); + dfa.start = start; + } + const alt = performLookahead.apply(this, [dfa, start, predicateSet, logging]); + return alt; +} +function performLookahead(dfa, s0, predicateSet, logging) { + let previousD = s0; + let i = 1; + const path = []; + let t = this.LA(i++); + while (true) { + let d = getExistingTargetState(previousD, t); + if (d === undefined) { + d = computeLookaheadTarget.apply(this, [dfa, previousD, t, i, predicateSet, logging]); + } + if (d === DFA_ERROR) { + return buildAdaptivePredictError(path, previousD, t); + } + if (d.isAcceptState === true) { + return d.prediction; + } + previousD = d; + path.push(t); + t = this.LA(i++); + } +} +function computeLookaheadTarget(dfa, previousD, token, lookahead, predicateSet, logging) { + const reach = computeReachSet(previousD.configs, token, predicateSet); + if (reach.size === 0) { + addDFAEdge(dfa, previousD, token, DFA_ERROR); + return DFA_ERROR; + } + let newState = newDFAState(reach); + const predictedAlt = getUniqueAlt(reach, predicateSet); + if (predictedAlt !== undefined) { + newState.isAcceptState = true; + newState.prediction = predictedAlt; + newState.configs.uniqueAlt = predictedAlt; + } + else if (hasConflictTerminatingPrediction(reach)) { + const prediction = min(reach.alts); + newState.isAcceptState = true; + newState.prediction = prediction; + newState.configs.uniqueAlt = prediction; + reportLookaheadAmbiguity.apply(this, [dfa, lookahead, reach.alts, logging]); + } + newState = addDFAEdge(dfa, previousD, token, newState); + return newState; +} +function reportLookaheadAmbiguity(dfa, lookahead, ambiguityIndices, logging) { + const prefixPath = []; + for (let i = 1; i <= lookahead; i++) { + prefixPath.push(this.LA(i).tokenType); + } + const atnState = dfa.atnStartState; + const topLevelRule = atnState.rule; + const production = atnState.production; + const message = buildAmbiguityError({ + topLevelRule, + ambiguityIndices, + production, + prefixPath + }); + logging(message); +} +function buildAmbiguityError(options) { + const pathMsg = map(options.prefixPath, (currtok) => tokenLabel(currtok)).join(", "); + const occurrence = options.production.idx === 0 ? "" : options.production.idx; + let currMessage = `Ambiguous Alternatives Detected: <${options.ambiguityIndices.join(", ")}> in <${getProductionDslName(options.production)}${occurrence}>` + + ` inside <${options.topLevelRule.name}> Rule,\n` + + `<${pathMsg}> may appears as a prefix path in all these alternatives.\n`; + currMessage = + currMessage + + `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\n` + + `For Further details.`; + return currMessage; +} +function getProductionDslName(prod) { + 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"); + } +} +function buildAdaptivePredictError(path, previous, current) { + const nextTransitions = flatMap(previous.configs.elements, (e) => e.state.transitions); + const nextTokenTypes = uniqBy(nextTransitions + .filter((e) => e instanceof AtomTransition) + .map((e) => e.tokenType), (e) => e.tokenTypeIdx); + return { + actualToken: current, + possibleTokenTypes: nextTokenTypes, + tokenPath: path + }; +} +function getExistingTargetState(state, token) { + return state.edges[token.tokenTypeIdx]; +} +function computeReachSet(configs, token, predicateSet) { + const intermediate = new ATNConfigSet(); + const skippedStopStates = []; + for (const c of configs.elements) { + if (predicateSet.is(c.alt) === false) { + continue; + } + if (c.state.type === ATN_RULE_STOP) { + skippedStopStates.push(c); + continue; + } + const transitionLength = c.state.transitions.length; + for (let i = 0; i < transitionLength; i++) { + const transition = c.state.transitions[i]; + const target = getReachableTarget(transition, token); + if (target !== undefined) { + intermediate.add({ + state: target, + alt: c.alt, + stack: c.stack + }); + } + } + } + let reach; + if (skippedStopStates.length === 0 && intermediate.size === 1) { + reach = intermediate; + } + if (reach === undefined) { + reach = new ATNConfigSet(); + for (const c of intermediate.elements) { + closure(c, reach); + } + } + if (skippedStopStates.length > 0 && !hasConfigInRuleStopState(reach)) { + for (const c of skippedStopStates) { + reach.add(c); + } + } + return reach; +} +function getReachableTarget(transition, token) { + if (transition instanceof AtomTransition && + tokenMatcher(token, transition.tokenType)) { + return transition.target; + } + return undefined; +} +function getUniqueAlt(configs, predicateSet) { + let alt; + for (const c of configs.elements) { + if (predicateSet.is(c.alt) === true) { + if (alt === undefined) { + alt = c.alt; + } + else if (alt !== c.alt) { + return undefined; + } + } + } + return alt; +} +function newDFAState(closure) { + return { + configs: closure, + edges: {}, + isAcceptState: false, + prediction: -1 + }; +} +function addDFAEdge(dfa, from, token, to) { + to = addDFAState(dfa, to); + from.edges[token.tokenTypeIdx] = to; + return to; +} +function addDFAState(dfa, state) { + if (state === DFA_ERROR) { + return state; + } + // Repetitions have the same config set + // Therefore, storing the key of the config in a map allows us to create a loop in our DFA + const mapKey = state.configs.key; + const existing = dfa.states[mapKey]; + if (existing !== undefined) { + return existing; + } + state.configs.finalize(); + dfa.states[mapKey] = state; + return state; +} +function computeStartState(atnState) { + const configs = new ATNConfigSet(); + const numberOfTransitions = atnState.transitions.length; + for (let i = 0; i < numberOfTransitions; i++) { + const target = atnState.transitions[i].target; + const config = { + state: target, + alt: i, + stack: [] + }; + closure(config, configs); + } + return configs; +} +function closure(config, configs) { + const p = config.state; + if (p.type === ATN_RULE_STOP) { + if (config.stack.length > 0) { + const atnStack = [...config.stack]; + const followState = atnStack.pop(); + const followConfig = { + state: followState, + alt: config.alt, + stack: atnStack + }; + closure(followConfig, configs); + } + else { + // Dipping into outer context, simply add the config + // This will stop computation once every config is at the rule stop state + configs.add(config); + } + return; + } + if (!p.epsilonOnlyTransitions) { + configs.add(config); + } + const transitionLength = p.transitions.length; + for (let i = 0; i < transitionLength; i++) { + const transition = p.transitions[i]; + const c = getEpsilonTarget(config, transition); + if (c !== undefined) { + closure(c, configs); + } + } +} +function getEpsilonTarget(config, transition) { + if (transition instanceof EpsilonTransition) { + return { + state: transition.target, + alt: config.alt, + stack: config.stack + }; + } + else if (transition instanceof RuleTransition) { + const stack = [...config.stack, transition.followState]; + return { + state: transition.target, + alt: config.alt, + stack + }; + } + return undefined; +} +function hasConfigInRuleStopState(configs) { + for (const c of configs.elements) { + if (c.state.type === ATN_RULE_STOP) { + return true; + } + } + return false; +} +function allConfigsInRuleStopStates(configs) { + for (const c of configs.elements) { + if (c.state.type !== ATN_RULE_STOP) { + return false; + } + } + return true; +} +function hasConflictTerminatingPrediction(configs) { + if (allConfigsInRuleStopStates(configs)) { + return true; + } + const altSets = getConflictingAltSets(configs.elements); + const heuristic = hasConflictingAltSet(altSets) && !hasStateAssociatedWithOneAlt(altSets); + return heuristic; +} +function getConflictingAltSets(configs) { + const configToAlts = new Map(); + for (const c of configs) { + const key = getATNConfigKey(c, false); + let alts = configToAlts.get(key); + if (alts === undefined) { + alts = {}; + configToAlts.set(key, alts); + } + alts[c.alt] = true; + } + return configToAlts; +} +function hasConflictingAltSet(altSets) { + for (const value of Array.from(altSets.values())) { + if (Object.keys(value).length > 1) { + return true; + } + } + return false; +} +function hasStateAssociatedWithOneAlt(altSets) { + for (const value of Array.from(altSets.values())) { + if (Object.keys(value).length === 1) { + return true; + } + } + return false; +} +//# sourceMappingURL=all-star-lookahead.js.map \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/lib/all-star-lookahead.js.map b/node_modules/chevrotain-allstar/lib/all-star-lookahead.js.map new file mode 100644 index 0000000..ff59031 --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/all-star-lookahead.js.map @@ -0,0 +1 @@ +{"version":3,"file":"all-star-lookahead.js","sourceRoot":"","sources":["../src/all-star-lookahead.ts"],"names":[],"mappings":"AAAA;;;;gFAIgF;AAEhF,OAAO,EAGH,YAAY,EACZ,UAAU,EAGV,WAAW,EACX,WAAW,EACX,MAAM,EACN,mBAAmB,EACnB,gCAAgC,EAChC,uBAAuB,EACvB,UAAU,EACV,QAAQ,EAER,oBAAoB,EAGpB,iBAAiB,EAEpB,MAAM,YAAY,CAAC;AACpB,OAAO,EAGH,aAAa,EACb,cAAc,EACd,WAAW,EACX,SAAS,EAET,iBAAiB,EACjB,cAAc,EAEjB,MAAM,UAAU,CAAC;AAClB,OAAO,EAEH,YAAY,EAGZ,SAAS,EACT,eAAe,EAClB,MAAM,UAAU,CAAC;AAClB,OAAO,GAAG,MAAM,kBAAkB,CAAC;AACnC,OAAO,OAAO,MAAM,sBAAsB,CAAC;AAC3C,OAAO,MAAM,MAAM,qBAAqB,CAAC;AACzC,OAAO,GAAG,MAAM,kBAAkB,CAAC;AACnC,OAAO,OAAO,MAAM,sBAAsB,CAAC;AAC3C,OAAO,OAAO,MAAM,sBAAsB,CAAC;AAC3C,OAAO,OAAO,MAAM,sBAAsB,CAAC;AAC3C,OAAO,MAAM,MAAM,qBAAqB,CAAC;AAMzC,SAAS,cAAc,CAAC,UAAyB,EAAE,QAAgB;IAC/D,MAAM,GAAG,GAAoC,EAAE,CAAA;IAC/C,OAAO,CAAC,YAAY,EAAE,EAAE;QACpB,MAAM,GAAG,GAAG,YAAY,CAAC,QAAQ,EAAE,CAAA;QACnC,IAAI,QAAQ,GAAG,GAAG,CAAC,GAAG,CAAC,CAAA;QACvB,IAAI,QAAQ,KAAK,SAAS,EAAE;YACxB,OAAO,QAAQ,CAAA;SAClB;aAAM;YACH,QAAQ,GAAG;gBACP,aAAa,EAAE,UAAU;gBACzB,QAAQ;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,CAAC,KAAK,CAAC,CAAC,MAAM,KAAK,CAAC,EAAE;YACjC,OAAO,IAAI,CAAA;SACd;KACJ;IACD,OAAO,KAAK,CAAA;AAChB,CAAC"} \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/lib/atn.d.ts b/node_modules/chevrotain-allstar/lib/atn.d.ts new file mode 100644 index 0000000..c23702b --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/atn.d.ts @@ -0,0 +1,105 @@ +/****************************************************************************** + * Copyright 2022 TypeFox GmbH + * This program and the accompanying materials are made available under the + * terms of the MIT License, which is available in the project root. + ******************************************************************************/ +import { IProductionWithOccurrence, TokenType, Rule, LookaheadProductionType } from "chevrotain"; +export declare function buildATNKey(rule: Rule, type: LookaheadProductionType, occurrence: number): string; +export interface ATN { + decisionMap: Record; + states: ATNState[]; + decisionStates: DecisionState[]; + ruleToStartState: Map; + ruleToStopState: Map; +} +export declare const ATN_INVALID_TYPE = 0; +export declare const ATN_BASIC = 1; +export declare const ATN_RULE_START = 2; +export declare const ATN_PLUS_BLOCK_START = 4; +export declare const ATN_STAR_BLOCK_START = 5; +export declare const ATN_TOKEN_START = 6; +export declare const ATN_RULE_STOP = 7; +export declare const ATN_BLOCK_END = 8; +export declare const ATN_STAR_LOOP_BACK = 9; +export declare const ATN_STAR_LOOP_ENTRY = 10; +export declare const ATN_PLUS_LOOP_BACK = 11; +export declare const ATN_LOOP_END = 12; +export type ATNState = BasicState | BasicBlockStartState | PlusBlockStartState | PlusLoopbackState | StarBlockStartState | StarLoopbackState | StarLoopEntryState | BlockEndState | RuleStartState | RuleStopState | LoopEndState; +export interface ATNBaseState { + atn: ATN; + production: IProductionWithOccurrence; + stateNumber: number; + rule: Rule; + epsilonOnlyTransitions: boolean; + transitions: Transition[]; + nextTokenWithinRule: number[]; +} +export interface BasicState extends ATNBaseState { + type: typeof ATN_BASIC; +} +export interface BlockStartState extends DecisionState { + end: BlockEndState; +} +export interface BasicBlockStartState extends BlockStartState { + type: typeof ATN_BASIC; +} +export interface PlusBlockStartState extends BlockStartState { + loopback: PlusLoopbackState; + type: typeof ATN_PLUS_BLOCK_START; +} +export interface PlusLoopbackState extends DecisionState { + type: typeof ATN_PLUS_LOOP_BACK; +} +export interface StarBlockStartState extends BlockStartState { + type: typeof ATN_STAR_BLOCK_START; +} +export interface StarLoopbackState extends ATNBaseState { + type: typeof ATN_STAR_LOOP_BACK; +} +export interface StarLoopEntryState extends DecisionState { + loopback: StarLoopbackState; + type: typeof ATN_STAR_LOOP_ENTRY; +} +export interface BlockEndState extends ATNBaseState { + start: BlockStartState; + type: typeof ATN_BLOCK_END; +} +export interface DecisionState extends ATNBaseState { + decision: number; +} +export interface LoopEndState extends ATNBaseState { + loopback: ATNState; + type: typeof ATN_LOOP_END; +} +export interface RuleStartState extends ATNBaseState { + stop: RuleStopState; + type: typeof ATN_RULE_START; +} +export interface RuleStopState extends ATNBaseState { + type: typeof ATN_RULE_STOP; +} +export interface Transition { + target: ATNState; + isEpsilon(): boolean; +} +export declare abstract class AbstractTransition implements Transition { + target: ATNState; + constructor(target: ATNState); + isEpsilon(): boolean; +} +export declare class AtomTransition extends AbstractTransition { + tokenType: TokenType; + constructor(target: ATNState, tokenType: TokenType); +} +export declare class EpsilonTransition extends AbstractTransition { + constructor(target: ATNState); + isEpsilon(): boolean; +} +export declare class RuleTransition extends AbstractTransition { + rule: Rule; + followState: ATNState; + constructor(ruleStart: RuleStartState, rule: Rule, followState: ATNState); + isEpsilon(): boolean; +} +export declare function createATN(rules: Rule[]): ATN; +//# sourceMappingURL=atn.d.ts.map \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/lib/atn.d.ts.map b/node_modules/chevrotain-allstar/lib/atn.d.ts.map new file mode 100644 index 0000000..f62c525 --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/atn.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"atn.d.ts","sourceRoot":"","sources":["../src/atn.ts"],"names":[],"mappings":"AAAA;;;;gFAIgF;AAIhF,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AAI,EAAE,OAAO,cAAc,CAAA;CAC9B;AAED,MAAM,WAAW,aAAc,SAAQ,YAAY;IAC/C,IAAI,EAAE,OAAO,aAAa,CAAA;CAC7B;AAED,MAAM,WAAW,UAAU;IACvB,MAAM,EAAE,QAAQ,CAAA;IAChB,SAAS,IAAI,OAAO,CAAA;CACvB;AAED,8BAAsB,kBAAmB,YAAW,UAAU;IAC1D,MAAM,EAAE,QAAQ,CAAA;gBAEJ,MAAM,EAAE,QAAQ;IAI5B,SAAS;CAGZ;AAED,qBAAa,cAAe,SAAQ,kBAAkB;IAClD,SAAS,EAAE,SAAS,CAAA;gBAER,MAAM,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS;CAIrD;AAED,qBAAa,iBAAkB,SAAQ,kBAAkB;gBACzC,MAAM,EAAE,QAAQ;IAI5B,SAAS;CAGZ;AAED,qBAAa,cAAe,SAAQ,kBAAkB;IAClD,IAAI,EAAE,IAAI,CAAA;IACV,WAAW,EAAE,QAAQ,CAAA;gBAET,SAAS,EAAE,cAAc,EAAE,IAAI,EAAE,IAAI,EAAE,WAAW,EAAE,QAAQ;IAMxE,SAAS;CAGZ;AAOD,wBAAgB,SAAS,CAAC,KAAK,EAAE,IAAI,EAAE,GAAG,GAAG,CAmB5C"} \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/lib/atn.js b/node_modules/chevrotain-allstar/lib/atn.js new file mode 100644 index 0000000..9b68084 --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/atn.js @@ -0,0 +1,404 @@ +/****************************************************************************** + * Copyright 2022 TypeFox GmbH + * This program and the accompanying materials are made available under the + * terms of the MIT License, which is available in the project root. + ******************************************************************************/ +import map from "lodash-es/map.js"; +import filter from "lodash-es/filter.js"; +import { Alternation, NonTerminal, Option, RepetitionMandatory, Repetition, Terminal, RepetitionWithSeparator, RepetitionMandatoryWithSeparator } from "chevrotain"; +export function buildATNKey(rule, type, occurrence) { + return `${rule.name}_${type}_${occurrence}`; +} +export const ATN_INVALID_TYPE = 0; +export const ATN_BASIC = 1; +export const ATN_RULE_START = 2; +export const ATN_PLUS_BLOCK_START = 4; +export const ATN_STAR_BLOCK_START = 5; +// Currently unused as the ATN is not used for lexing +export const ATN_TOKEN_START = 6; +export const ATN_RULE_STOP = 7; +export const ATN_BLOCK_END = 8; +export const ATN_STAR_LOOP_BACK = 9; +export const ATN_STAR_LOOP_ENTRY = 10; +export const ATN_PLUS_LOOP_BACK = 11; +export const ATN_LOOP_END = 12; +export class AbstractTransition { + constructor(target) { + this.target = target; + } + isEpsilon() { + return false; + } +} +export class AtomTransition extends AbstractTransition { + constructor(target, tokenType) { + super(target); + this.tokenType = tokenType; + } +} +export class EpsilonTransition extends AbstractTransition { + constructor(target) { + super(target); + } + isEpsilon() { + return true; + } +} +export class RuleTransition extends AbstractTransition { + constructor(ruleStart, rule, followState) { + super(ruleStart); + this.rule = rule; + this.followState = followState; + } + isEpsilon() { + return true; + } +} +export function createATN(rules) { + const atn = { + decisionMap: {}, + decisionStates: [], + ruleToStartState: new Map(), + ruleToStopState: new Map(), + states: [] + }; + createRuleStartAndStopATNStates(atn, rules); + const ruleLength = rules.length; + for (let i = 0; i < ruleLength; i++) { + const rule = rules[i]; + const ruleBlock = block(atn, rule, rule); + if (ruleBlock === undefined) { + continue; + } + buildRuleHandle(atn, rule, ruleBlock); + } + return atn; +} +function createRuleStartAndStopATNStates(atn, rules) { + const ruleLength = rules.length; + for (let i = 0; i < ruleLength; i++) { + const rule = rules[i]; + const start = newState(atn, rule, undefined, { + type: ATN_RULE_START + }); + const stop = newState(atn, rule, undefined, { + type: ATN_RULE_STOP + }); + start.stop = stop; + atn.ruleToStartState.set(rule, start); + atn.ruleToStopState.set(rule, stop); + } +} +function atom(atn, rule, production) { + if (production instanceof Terminal) { + return tokenRef(atn, rule, production.terminalType, production); + } + else if (production instanceof NonTerminal) { + return ruleRef(atn, rule, production); + } + else if (production instanceof Alternation) { + return alternation(atn, rule, production); + } + else if (production instanceof Option) { + return option(atn, rule, production); + } + else if (production instanceof Repetition) { + return repetition(atn, rule, production); + } + else if (production instanceof RepetitionWithSeparator) { + return repetitionSep(atn, rule, production); + } + else if (production instanceof RepetitionMandatory) { + return repetitionMandatory(atn, rule, production); + } + else if (production instanceof RepetitionMandatoryWithSeparator) { + return repetitionMandatorySep(atn, rule, production); + } + else { + return block(atn, rule, production); + } +} +function repetition(atn, rule, repetition) { + const starState = newState(atn, rule, repetition, { + type: ATN_STAR_BLOCK_START + }); + defineDecisionState(atn, starState); + const handle = makeAlts(atn, rule, starState, repetition, block(atn, rule, repetition)); + return star(atn, rule, repetition, handle); +} +function repetitionSep(atn, rule, repetition) { + const starState = newState(atn, rule, repetition, { + type: ATN_STAR_BLOCK_START + }); + defineDecisionState(atn, starState); + const handle = makeAlts(atn, rule, starState, repetition, block(atn, rule, repetition)); + const sep = tokenRef(atn, rule, repetition.separator, repetition); + return star(atn, rule, repetition, handle, sep); +} +function repetitionMandatory(atn, rule, repetition) { + const plusState = newState(atn, rule, repetition, { + type: ATN_PLUS_BLOCK_START + }); + defineDecisionState(atn, plusState); + const handle = makeAlts(atn, rule, plusState, repetition, block(atn, rule, repetition)); + return plus(atn, rule, repetition, handle); +} +function repetitionMandatorySep(atn, rule, repetition) { + const plusState = newState(atn, rule, repetition, { + type: ATN_PLUS_BLOCK_START + }); + defineDecisionState(atn, plusState); + const handle = makeAlts(atn, rule, plusState, repetition, block(atn, rule, repetition)); + const sep = tokenRef(atn, rule, repetition.separator, repetition); + return plus(atn, rule, repetition, handle, sep); +} +function alternation(atn, rule, alternation) { + const start = newState(atn, rule, alternation, { + type: ATN_BASIC + }); + defineDecisionState(atn, start); + const alts = map(alternation.definition, (e) => atom(atn, rule, e)); + const handle = makeAlts(atn, rule, start, alternation, ...alts); + return handle; +} +function option(atn, rule, option) { + const start = newState(atn, rule, option, { + type: ATN_BASIC + }); + defineDecisionState(atn, start); + const handle = makeAlts(atn, rule, start, option, block(atn, rule, option)); + return optional(atn, rule, option, handle); +} +function block(atn, rule, block) { + const handles = filter(map(block.definition, (e) => atom(atn, rule, e)), (e) => e !== undefined); + if (handles.length === 1) { + return handles[0]; + } + else if (handles.length === 0) { + return undefined; + } + else { + return makeBlock(atn, handles); + } +} +function plus(atn, rule, plus, handle, sep) { + const blkStart = handle.left; + const blkEnd = handle.right; + const loop = newState(atn, rule, plus, { + type: ATN_PLUS_LOOP_BACK + }); + defineDecisionState(atn, loop); + const end = newState(atn, rule, plus, { + type: ATN_LOOP_END + }); + blkStart.loopback = loop; + end.loopback = loop; + atn.decisionMap[buildATNKey(rule, sep ? 'RepetitionMandatoryWithSeparator' : 'RepetitionMandatory', plus.idx)] = loop; + epsilon(blkEnd, loop); // block can see loop back + // Depending on whether we have a separator we put the exit transition at index 1 or 0 + // This influences the chosen option in the lookahead DFA + if (sep === undefined) { + epsilon(loop, blkStart); // loop back to start + epsilon(loop, end); // exit + } + else { + epsilon(loop, end); // exit + // loop back to start with separator + epsilon(loop, sep.left); + epsilon(sep.right, blkStart); + } + return { + left: blkStart, + right: end + }; +} +function star(atn, rule, star, handle, sep) { + const start = handle.left; + const end = handle.right; + const entry = newState(atn, rule, star, { + type: ATN_STAR_LOOP_ENTRY + }); + defineDecisionState(atn, entry); + const loopEnd = newState(atn, rule, star, { + type: ATN_LOOP_END + }); + const loop = newState(atn, rule, star, { + type: ATN_STAR_LOOP_BACK + }); + entry.loopback = loop; + loopEnd.loopback = loop; + epsilon(entry, start); // loop enter edge (alt 2) + epsilon(entry, loopEnd); // bypass loop edge (alt 1) + epsilon(end, loop); // block end hits loop back + if (sep !== undefined) { + epsilon(loop, loopEnd); // end loop + // loop back to start of handle using separator + epsilon(loop, sep.left); + epsilon(sep.right, start); + } + else { + epsilon(loop, entry); // loop back to entry/exit decision + } + atn.decisionMap[buildATNKey(rule, sep ? 'RepetitionWithSeparator' : 'Repetition', star.idx)] = entry; + return { + left: entry, + right: loopEnd + }; +} +function optional(atn, rule, optional, handle) { + const start = handle.left; + const end = handle.right; + epsilon(start, end); + atn.decisionMap[buildATNKey(rule, 'Option', optional.idx)] = start; + return handle; +} +function defineDecisionState(atn, state) { + atn.decisionStates.push(state); + state.decision = atn.decisionStates.length - 1; + return state.decision; +} +function makeAlts(atn, rule, start, production, ...alts) { + const end = newState(atn, rule, production, { + type: ATN_BLOCK_END, + start + }); + start.end = end; + for (const alt of alts) { + if (alt !== undefined) { + // hook alts up to decision block + epsilon(start, alt.left); + epsilon(alt.right, end); + } + else { + epsilon(start, end); + } + } + const handle = { + left: start, + right: end + }; + atn.decisionMap[buildATNKey(rule, getProdType(production), production.idx)] = start; + return handle; +} +function getProdType(production) { + if (production instanceof Alternation) { + return 'Alternation'; + } + else if (production instanceof Option) { + return 'Option'; + } + else if (production instanceof Repetition) { + return 'Repetition'; + } + else if (production instanceof RepetitionWithSeparator) { + return 'RepetitionWithSeparator'; + } + else if (production instanceof RepetitionMandatory) { + return 'RepetitionMandatory'; + } + else if (production instanceof RepetitionMandatoryWithSeparator) { + return 'RepetitionMandatoryWithSeparator'; + } + else { + throw new Error('Invalid production type encountered'); + } +} +function makeBlock(atn, alts) { + const altsLength = alts.length; + for (let i = 0; i < altsLength - 1; i++) { + const handle = alts[i]; + let transition; + if (handle.left.transitions.length === 1) { + transition = handle.left.transitions[0]; + } + const isRuleTransition = transition instanceof RuleTransition; + const ruleTransition = transition; + const next = alts[i + 1].left; + if (handle.left.type === ATN_BASIC && + handle.right.type === ATN_BASIC && + transition !== undefined && + ((isRuleTransition && ruleTransition.followState === handle.right) || + transition.target === handle.right)) { + // we can avoid epsilon edge to next element + if (isRuleTransition) { + ruleTransition.followState = next; + } + else { + transition.target = next; + } + removeState(atn, handle.right); // we skipped over this state + } + else { + // need epsilon if previous block's right end node is complex + epsilon(handle.right, next); + } + } + const first = alts[0]; + const last = alts[altsLength - 1]; + return { + left: first.left, + right: last.right + }; +} +function tokenRef(atn, rule, tokenType, production) { + const left = newState(atn, rule, production, { + type: ATN_BASIC + }); + const right = newState(atn, rule, production, { + type: ATN_BASIC + }); + addTransition(left, new AtomTransition(right, tokenType)); + return { + left, + right + }; +} +function ruleRef(atn, currentRule, nonTerminal) { + const rule = nonTerminal.referencedRule; + const start = atn.ruleToStartState.get(rule); + const left = newState(atn, currentRule, nonTerminal, { + type: ATN_BASIC + }); + const right = newState(atn, currentRule, nonTerminal, { + type: ATN_BASIC + }); + const call = new RuleTransition(start, rule, right); + addTransition(left, call); + return { + left, + right + }; +} +function buildRuleHandle(atn, rule, block) { + const start = atn.ruleToStartState.get(rule); + epsilon(start, block.left); + const stop = atn.ruleToStopState.get(rule); + epsilon(block.right, stop); + const handle = { + left: start, + right: stop + }; + return handle; +} +function epsilon(a, b) { + const transition = new EpsilonTransition(b); + addTransition(a, transition); +} +function newState(atn, rule, production, partial) { + const t = Object.assign({ atn, + production, epsilonOnlyTransitions: false, rule, transitions: [], nextTokenWithinRule: [], stateNumber: atn.states.length }, partial); + atn.states.push(t); + return t; +} +function addTransition(state, transition) { + // A single ATN state can only contain epsilon transitions or non-epsilon transitions + // Because they are never mixed, only setting the property for the first transition is fine + if (state.transitions.length === 0) { + state.epsilonOnlyTransitions = transition.isEpsilon(); + } + state.transitions.push(transition); +} +function removeState(atn, state) { + atn.states.splice(atn.states.indexOf(state), 1); +} +//# sourceMappingURL=atn.js.map \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/lib/atn.js.map b/node_modules/chevrotain-allstar/lib/atn.js.map new file mode 100644 index 0000000..bd6ec3b --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/atn.js.map @@ -0,0 +1 @@ +{"version":3,"file":"atn.js","sourceRoot":"","sources":["../src/atn.ts"],"names":[],"mappings":"AAAA;;;;gFAIgF;AAEhF,OAAO,GAAG,MAAM,kBAAkB,CAAA;AAClC,OAAO,MAAM,MAAM,qBAAqB,CAAA;AACxC,OAAO,EAIH,WAAW,EACX,WAAW,EAEX,MAAM,EACN,mBAAmB,EACnB,UAAU,EACV,QAAQ,EAER,uBAAuB,EACvB,gCAAgC,E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a/node_modules/chevrotain-allstar/lib/dfa.d.ts b/node_modules/chevrotain-allstar/lib/dfa.d.ts new file mode 100644 index 0000000..a084f98 --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/dfa.d.ts @@ -0,0 +1,37 @@ +/****************************************************************************** + * Copyright 2022 TypeFox GmbH + * This program and the accompanying materials are made available under the + * terms of the MIT License, which is available in the project root. + ******************************************************************************/ +import { ATNState, DecisionState } from "./atn.js"; +export interface DFA { + start?: DFAState; + states: Record; + decision: number; + atnStartState: DecisionState; +} +export interface DFAState { + configs: ATNConfigSet; + edges: Record; + isAcceptState: boolean; + prediction: number; +} +export declare const DFA_ERROR: DFAState; +export interface ATNConfig { + state: ATNState; + alt: number; + stack: ATNState[]; +} +export declare class ATNConfigSet { + private map; + private configs; + uniqueAlt: number | undefined; + get size(): number; + finalize(): void; + add(config: ATNConfig): void; + get elements(): readonly ATNConfig[]; + get alts(): number[]; + get key(): string; +} +export declare function getATNConfigKey(config: ATNConfig, alt?: boolean): string; +//# sourceMappingURL=dfa.d.ts.map \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/lib/dfa.d.ts.map b/node_modules/chevrotain-allstar/lib/dfa.d.ts.map new file mode 100644 index 0000000..6d8c0c9 --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/dfa.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"dfa.d.ts","sourceRoot":"","sources":["../src/dfa.ts"],"names":[],"mappings":"AAAA;;;;gFAIgF;AAGhF,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AAElD,MAAM,WAAW,GAAG;IAClB,KAAK,CAAC,EAAE,QAAQ,CAAA;IAChB,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;IAChC,QAAQ,EAAE,MAAM,CAAA;IAChB,aAAa,EAAE,aAAa,CAAA;CAC7B;AAED,MAAM,WAAW,QAAQ;IACvB,OAAO,EAAE,YAAY,CAAA;IACrB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAA;IAC/B,aAAa,EAAE,OAAO,CAAA;IACtB,UAAU,EAAE,MAAM,CAAA;CACnB;AAED,eAAO,MAAM,SAAS,UAAiB,CAAA;AAEvC,MAAM,WAAW,SAAS;IACxB,KAAK,EAAE,QAAQ,CAAA;IACf,GAAG,EAAE,MAAM,CAAA;IACX,KAAK,EAAE,QAAQ,EAAE,CAAA;CAClB;AAED,qBAAa,YAAY;IACvB,OAAO,CAAC,GAAG,CAA6B;IACxC,OAAO,CAAC,OAAO,CAAkB;IAEjC,SAAS,EAAE,MAAM,GAAG,SAAS,CAAA;IAE7B,IAAI,IAAI,IAAI,MAAM,CAEjB;IAED,QAAQ,IAAI,IAAI;IAKhB,GAAG,CAAC,MAAM,EAAE,SAAS,GAAG,IAAI;IAU5B,IAAI,QAAQ,IAAI,SAAS,SAAS,EAAE,CAEnC;IAED,IAAI,IAAI,IAAI,MAAM,EAAE,CAEnB;IAED,IAAI,GAAG,IAAI,MAAM,CAMhB;CACF;AAED,wBAAgB,eAAe,CAAC,MAAM,EAAE,SAAS,EAAE,GAAG,UAAO,UAI5D"} \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/lib/dfa.js b/node_modules/chevrotain-allstar/lib/dfa.js new file mode 100644 index 0000000..d5c03ff --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/dfa.js @@ -0,0 +1,46 @@ +/****************************************************************************** + * Copyright 2022 TypeFox GmbH + * This program and the accompanying materials are made available under the + * terms of the MIT License, which is available in the project root. + ******************************************************************************/ +import map from "lodash-es/map.js"; +export const DFA_ERROR = {}; +export class ATNConfigSet { + constructor() { + this.map = {}; + this.configs = []; + } + get size() { + return this.configs.length; + } + finalize() { + // Empties the map to free up memory + this.map = {}; + } + add(config) { + const key = getATNConfigKey(config); + // Only add configs which don't exist in our map already + // While this does not influence the actual algorithm, adding them anyway would massively increase memory consumption + if (!(key in this.map)) { + this.map[key] = this.configs.length; + this.configs.push(config); + } + } + get elements() { + return this.configs; + } + get alts() { + return map(this.configs, (e) => e.alt); + } + get key() { + let value = ""; + for (const k in this.map) { + value += k + ":"; + } + return value; + } +} +export function getATNConfigKey(config, alt = true) { + return `${alt ? `a${config.alt}` : ""}s${config.state.stateNumber}:${config.stack.map((e) => e.stateNumber.toString()).join("_")}`; +} +//# sourceMappingURL=dfa.js.map \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/lib/dfa.js.map b/node_modules/chevrotain-allstar/lib/dfa.js.map new file mode 100644 index 0000000..88e2f79 --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/dfa.js.map @@ -0,0 +1 @@ +{"version":3,"file":"dfa.js","sourceRoot":"","sources":["../src/dfa.ts"],"names":[],"mappings":"AAAA;;;;gFAIgF;AAEhF,OAAO,GAAG,MAAM,kBAAkB,CAAA;AAiBlC,MAAM,CAAC,MAAM,SAAS,GAAG,EAAc,CAAA;AAQvC,MAAM,OAAO,YAAY;IAAzB;QACU,QAAG,GAA2B,EAAE,CAAA;QAChC,YAAO,GAAgB,EAAE,CAAA;IAsCnC,CAAC;IAlCC,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,CAAA;IAC5B,CAAC;IAED,QAAQ;QACN,oCAAoC;QACpC,IAAI,CAAC,GAAG,GAAG,EAAE,CAAA;IACf,CAAC;IAED,GAAG,CAAC,MAAiB;QACnB,MAAM,GAAG,GAAG,eAAe,CAAC,MAAM,CAAC,CAAA;QACnC,wDAAwD;QACxD,qHAAqH;QACrH,IAAI,CAAC,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,CAAC,EAAE;YACtB,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAA;YACnC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAA;SAC1B;IACH,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,IAAI,CAAC,OAAO,CAAA;IACrB,CAAC;IAED,IAAI,IAAI;QACN,OAAO,GAAG,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA;IACxC,CAAC;IAED,IAAI,GAAG;QACL,IAAI,KAAK,GAAG,EAAE,CAAA;QACd,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,GAAG,EAAE;YACxB,KAAK,IAAI,CAAC,GAAG,GAAG,CAAA;SACjB;QACD,OAAO,KAAK,CAAA;IACd,CAAC;CACF;AAED,MAAM,UAAU,eAAe,CAAC,MAAiB,EAAE,GAAG,GAAG,IAAI;IAC3D,OAAO,GAAG,GAAG,CAAC,CAAC,CAAC,IAAI,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,IACnC,MAAM,CAAC,KAAK,CAAC,WACf,IAAI,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,CAAC,QAAQ,EAAE,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAA;AACnE,CAAC"} \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/lib/index.d.ts b/node_modules/chevrotain-allstar/lib/index.d.ts new file mode 100644 index 0000000..e250c5e --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/index.d.ts @@ -0,0 +1,7 @@ +/****************************************************************************** + * Copyright 2022 TypeFox GmbH + * This program and the accompanying materials are made available under the + * terms of the MIT License, which is available in the project root. + ******************************************************************************/ +export { AmbiguityReport, LLStarLookaheadOptions, LLStarLookaheadStrategy } from './all-star-lookahead.js'; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/lib/index.d.ts.map b/node_modules/chevrotain-allstar/lib/index.d.ts.map new file mode 100644 index 0000000..1656582 --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;gFAIgF;AAEhF,OAAO,EACH,eAAe,EACf,sBAAsB,EACtB,uBAAuB,EAC1B,MAAM,yBAAyB,CAAC"} \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/lib/index.js b/node_modules/chevrotain-allstar/lib/index.js new file mode 100644 index 0000000..3305ead --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/index.js @@ -0,0 +1,7 @@ +/****************************************************************************** + * Copyright 2022 TypeFox GmbH + * This program and the accompanying materials are made available under the + * terms of the MIT License, which is available in the project root. + ******************************************************************************/ +export { LLStarLookaheadStrategy } from './all-star-lookahead.js'; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/lib/index.js.map b/node_modules/chevrotain-allstar/lib/index.js.map new file mode 100644 index 0000000..af53151 --- /dev/null +++ b/node_modules/chevrotain-allstar/lib/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;gFAIgF;AAEhF,OAAO,EAGH,uBAAuB,EAC1B,MAAM,yBAAyB,CAAC"} \ No newline at end of file diff --git a/node_modules/chevrotain-allstar/package.json b/node_modules/chevrotain-allstar/package.json new file mode 100644 index 0000000..fef3e8e --- /dev/null +++ b/node_modules/chevrotain-allstar/package.json @@ -0,0 +1,52 @@ +{ + "name": "chevrotain-allstar", + "version": "0.3.1", + "description": "LL(*) lookahead strategy for the Chevrotain parser library", + "keywords": [ + "parser", + "lookahead", + "chevrotain", + "langium" + ], + "license": "MIT", + "type": "module", + "types": "./lib/index.d.ts", + "exports": { + ".": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + } + }, + "scripts": { + "test": "vitest", + "build": "tsc", + "watch": "tsc -w", + "clean": "shx rm -rf lib tsconfig.tsbuildinfo" + }, + "files": [ + "src", + "lib" + ], + "dependencies": { + "lodash-es": "^4.17.21" + }, + "peerDependencies": { + "chevrotain": "^11.0.0" + }, + "devDependencies": { + "@types/jest": "^29.2.1", + "@types/lodash-es": "^4.17.8", + "shx": "^0.3.4", + "typescript": "^5.1.6", + "vitest": "^0.33.0" + }, + "repository": { + "type": "git", + "url": "https://github.com/langium/chevrotain-allstar" + }, + "bugs": "https://github.com/langium/chevrotain-allstar/issues", + "author": { + "name": "TypeFox", + "url": "https://www.typefox.io" + } +} diff --git a/node_modules/chevrotain-allstar/src/all-star-lookahead.ts b/node_modules/chevrotain-allstar/src/all-star-lookahead.ts new file mode 100644 index 0000000..000edea --- /dev/null +++ b/node_modules/chevrotain-allstar/src/all-star-lookahead.ts @@ -0,0 +1,763 @@ +/****************************************************************************** + * Copyright 2022 TypeFox GmbH + * This program and the accompanying materials are made available under the + * terms of the MIT License, which is available in the project root. + ******************************************************************************/ + +import { + IToken, + TokenType, + tokenMatcher, + tokenLabel, + Rule, + IProductionWithOccurrence, + NonTerminal, + Alternation, + Option, + RepetitionMandatory, + RepetitionMandatoryWithSeparator, + RepetitionWithSeparator, + Repetition, + Terminal, + BaseParser, + LLkLookaheadStrategy, + ILookaheadValidationError, + IOrAlt, + getLookaheadPaths, + OptionalProductionType +} from "chevrotain"; +import { + ATN, + ATNState, + ATN_RULE_STOP, + AtomTransition, + buildATNKey, + createATN, + DecisionState, + EpsilonTransition, + RuleTransition, + Transition +} from "./atn.js"; +import { + ATNConfig, + ATNConfigSet, + DFA, + DFAState, + DFA_ERROR, + getATNConfigKey +} from "./dfa.js"; +import min from "lodash-es/min.js"; +import flatMap from "lodash-es/flatMap.js"; +import uniqBy from "lodash-es/uniqBy.js"; +import map from "lodash-es/map.js"; +import flatten from "lodash-es/flatten.js"; +import forEach from "lodash-es/forEach.js"; +import isEmpty from "lodash-es/isEmpty.js"; +import reduce from "lodash-es/reduce.js"; + +type DFACache = (predicateSet: PredicateSet) => DFA + +export type AmbiguityReport = (message: string) => void; + +function createDFACache(startState: DecisionState, decision: number): DFACache { + const map: Record = {} + return (predicateSet) => { + const key = predicateSet.toString() + let existing = map[key] + if (existing !== undefined) { + return existing + } else { + existing = { + atnStartState: startState, + decision, + states: {} + } + map[key] = existing + return existing + } + } +} + +class PredicateSet { + private predicates: boolean[] = [] + + is(index: number): boolean { + return index >= this.predicates.length || this.predicates[index] + } + + set(index: number, value: boolean) { + this.predicates[index] = value + } + + toString(): string { + let value = "" + const size = this.predicates.length + for (let i = 0; i < size; i++) { + value += this.predicates[i] === true ? "1" : "0" + } + return value + } +} + +interface AdaptivePredictError { + tokenPath: IToken[] + possibleTokenTypes: TokenType[] + actualToken: IToken +} + +const EMPTY_PREDICATES = new PredicateSet() + +export interface LLStarLookaheadOptions { + logging?: AmbiguityReport +} + +export class LLStarLookaheadStrategy extends LLkLookaheadStrategy { + + private atn: ATN; + private dfas: DFACache[]; + private logging: AmbiguityReport; + + constructor(options?: LLStarLookaheadOptions) { + super(); + this.logging = options?.logging ?? ((message) => console.log(message)); + } + + override initialize(options: { rules: Rule[] }): void { + this.atn = createATN(options.rules); + this.dfas = initATNSimulator(this.atn); + } + + override validateAmbiguousAlternationAlternatives(): ILookaheadValidationError[] { + return []; + } + + override validateEmptyOrAlternatives(): ILookaheadValidationError[] { + return []; + } + + override buildLookaheadForAlternation(options: { + prodOccurrence: number; + rule: Rule; + maxLookahead: number; + hasPredicates: boolean; + dynamicTokensEnabled: boolean + }): (this: BaseParser, orAlts?: IOrAlt[] | undefined) => number | undefined { + const { prodOccurrence, rule, hasPredicates, dynamicTokensEnabled } = options; + const dfas = this.dfas; + const logging = this.logging; + const key = buildATNKey(rule, 'Alternation', prodOccurrence); + const decisionState = this.atn.decisionMap[key]; + const decisionIndex = decisionState.decision; + const partialAlts: (TokenType | undefined)[][] = map( + getLookaheadPaths({ + maxLookahead: 1, + occurrence: prodOccurrence, + prodType: "Alternation", + rule: rule + }), + (currAlt) => map(currAlt, (path) => path[0]) + ) + + if (isLL1Sequence(partialAlts, false) && !dynamicTokensEnabled) { + const choiceToAlt = reduce( + partialAlts, + (result, currAlt, idx) => { + forEach(currAlt, (currTokType) => { + if (currTokType) { + result[currTokType.tokenTypeIdx!] = idx + forEach(currTokType.categoryMatches!, (currExtendingType) => { + result[currExtendingType] = idx + }) + } + }) + return result + }, + {} as Record + ) + + if (hasPredicates) { + return function (this: BaseParser, orAlts) { + const nextToken = this.LA(1) + const prediction: number | undefined = choiceToAlt[nextToken.tokenTypeIdx] + if (orAlts !== undefined && prediction !== undefined) { + const gate = orAlts[prediction]?.GATE + if (gate !== undefined && gate.call(this) === false) { + return undefined; + } + } + return prediction + } + } else { + return function (this: BaseParser): number | undefined { + const nextToken = this.LA(1) + return choiceToAlt[nextToken.tokenTypeIdx]; + } + } + } else if (hasPredicates) { + return function (this: BaseParser, orAlts) { + const predicates = new PredicateSet() + const length = orAlts === undefined ? 0 : orAlts.length + for (let i = 0; i < length; i++) { + const gate = orAlts?.[i].GATE + predicates.set(i, gate === undefined || gate.call(this)) + } + const result = adaptivePredict.call(this, dfas, decisionIndex, predicates, logging); + return typeof result === 'number' ? result : undefined; + } + } else { + return function (this: BaseParser) { + const result = adaptivePredict.call(this, dfas, decisionIndex, EMPTY_PREDICATES, logging); + return typeof result === 'number' ? result : undefined; + } + } + } + + override buildLookaheadForOptional(options: { + prodOccurrence: number; + prodType: OptionalProductionType; + rule: Rule; + maxLookahead: number; + dynamicTokensEnabled: boolean + }): (this: BaseParser) => boolean { + const { prodOccurrence, rule, prodType, dynamicTokensEnabled } = options; + const dfas = this.dfas; + const logging = this.logging; + const key = buildATNKey(rule, prodType, prodOccurrence); + const decisionState = this.atn.decisionMap[key]; + const decisionIndex = decisionState.decision; + const alts = map( + getLookaheadPaths({ + maxLookahead: 1, + occurrence: prodOccurrence, + prodType, + rule + }), + (e) => { + return map(e, (g) => g[0]) + } + ) + + if (isLL1Sequence(alts) && alts[0][0] && !dynamicTokensEnabled) { + const alt = alts[0] + const singleTokensTypes = flatten(alt) + + if ( + singleTokensTypes.length === 1 && + isEmpty(singleTokensTypes[0].categoryMatches) + ) { + const expectedTokenType = singleTokensTypes[0] + const expectedTokenUniqueKey = expectedTokenType.tokenTypeIdx + + return function (this: BaseParser): boolean { + return this.LA(1).tokenTypeIdx === expectedTokenUniqueKey + } + } else { + const choiceToAlt = reduce( + singleTokensTypes, + (result, currTokType) => { + if (currTokType !== undefined) { + result[currTokType.tokenTypeIdx!] = true + forEach(currTokType.categoryMatches, (currExtendingType) => { + result[currExtendingType] = true + }) + } + return result + }, + {} as Record + ) + + return function (this: BaseParser): boolean { + const nextToken = this.LA(1) + return choiceToAlt[nextToken.tokenTypeIdx] === true + } + } + } + return function (this: BaseParser) { + const result = adaptivePredict.call(this, dfas, decisionIndex, EMPTY_PREDICATES, logging) + return typeof result === "object" ? false : result === 0; + } + } + +} + +function isLL1Sequence(sequences: (TokenType | undefined)[][], allowEmpty = true): boolean { + const fullSet = new Set() + + for (const alt of sequences) { + const altSet = new Set() + for (const tokType of alt) { + if (tokType === undefined) { + if (allowEmpty) { + // Epsilon production encountered + break + } else { + return false; + } + } + const indices = [tokType.tokenTypeIdx!].concat(tokType.categoryMatches!) + for (const index of indices) { + if (fullSet.has(index)) { + if (!altSet.has(index)) { + return false + } + } else { + fullSet.add(index) + altSet.add(index) + } + } + } + } + return true +} + +function initATNSimulator(atn: ATN): DFACache[] { + const decisionLength = atn.decisionStates.length + const decisionToDFA: DFACache[] = Array(decisionLength) + for (let i = 0; i < decisionLength; i++) { + decisionToDFA[i] = createDFACache(atn.decisionStates[i], i) + } + return decisionToDFA; +} + +function adaptivePredict( + this: BaseParser, + dfaCaches: DFACache[], + decision: number, + predicateSet: PredicateSet, + logging: AmbiguityReport +): number | AdaptivePredictError { + const dfa = dfaCaches[decision](predicateSet) + let start = dfa.start + if (start === undefined) { + const closure = computeStartState(dfa.atnStartState as ATNState) + start = addDFAState(dfa, newDFAState(closure)) + dfa.start = start + } + + const alt = performLookahead.apply(this, [dfa, start, predicateSet, logging]) + return alt +} + +function performLookahead( + this: BaseParser, + dfa: DFA, + s0: DFAState, + predicateSet: PredicateSet, + logging: AmbiguityReport +): number | AdaptivePredictError { + let previousD = s0 + + let i = 1 + const path: IToken[] = [] + let t = this.LA(i++) + + while (true) { + let d = getExistingTargetState(previousD, t) + if (d === undefined) { + d = computeLookaheadTarget.apply(this, [dfa, previousD, t, i, predicateSet, logging]) + } + + if (d === DFA_ERROR) { + return buildAdaptivePredictError(path, previousD, t) + } + + if (d.isAcceptState === true) { + return d.prediction + } + + previousD = d + path.push(t) + t = this.LA(i++) + } +} + +function computeLookaheadTarget( + this: BaseParser, + dfa: DFA, + previousD: DFAState, + token: IToken, + lookahead: number, + predicateSet: PredicateSet, + logging: AmbiguityReport +): DFAState { + const reach = computeReachSet(previousD.configs, token, predicateSet) + if (reach.size === 0) { + addDFAEdge(dfa, previousD, token, DFA_ERROR) + return DFA_ERROR + } + + let newState = newDFAState(reach) + const predictedAlt = getUniqueAlt(reach, predicateSet) + + if (predictedAlt !== undefined) { + newState.isAcceptState = true + newState.prediction = predictedAlt + newState.configs.uniqueAlt = predictedAlt + } else if (hasConflictTerminatingPrediction(reach)) { + const prediction = min(reach.alts)! + newState.isAcceptState = true + newState.prediction = prediction + newState.configs.uniqueAlt = prediction + reportLookaheadAmbiguity.apply(this, [dfa, lookahead, reach.alts, logging]) + } + + newState = addDFAEdge(dfa, previousD, token, newState) + return newState +} + +function reportLookaheadAmbiguity( + this: BaseParser, + dfa: DFA, + lookahead: number, + ambiguityIndices: number[], + logging: AmbiguityReport +) { + const prefixPath: TokenType[] = [] + for (let i = 1; i <= lookahead; i++) { + prefixPath.push(this.LA(i).tokenType) + } + const atnState = dfa.atnStartState + const topLevelRule = atnState.rule + const production = atnState.production + const message = buildAmbiguityError({ + topLevelRule, + ambiguityIndices, + production, + prefixPath + }) + logging(message) +} + +function buildAmbiguityError(options: { + topLevelRule: Rule + prefixPath: TokenType[] + ambiguityIndices: number[] + production: IProductionWithOccurrence +}): string { + const pathMsg = map(options.prefixPath, (currtok) => + tokenLabel(currtok) + ).join(", ") + const occurrence = + options.production.idx === 0 ? "" : options.production.idx + let currMessage = + `Ambiguous Alternatives Detected: <${options.ambiguityIndices.join( + ", " + )}> in <${getProductionDslName(options.production)}${occurrence}>` + + ` inside <${options.topLevelRule.name}> Rule,\n` + + `<${pathMsg}> may appears as a prefix path in all these alternatives.\n` + + currMessage = + currMessage + + `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES\n` + + `For Further details.` + return currMessage +} + +function getProductionDslName(prod: IProductionWithOccurrence): string { + 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") + } +} + +function buildAdaptivePredictError( + path: IToken[], + previous: DFAState, + current: IToken +): AdaptivePredictError { + const nextTransitions = flatMap( + previous.configs.elements, + (e) => e.state.transitions + ) + const nextTokenTypes = uniqBy( + nextTransitions + .filter((e): e is AtomTransition => e instanceof AtomTransition) + .map((e) => e.tokenType), + (e) => e.tokenTypeIdx + ) + return { + actualToken: current, + possibleTokenTypes: nextTokenTypes, + tokenPath: path + } +} + +function getExistingTargetState( + state: DFAState, + token: IToken +): DFAState | undefined { + return state.edges[token.tokenTypeIdx] +} + +function computeReachSet( + configs: ATNConfigSet, + token: IToken, + predicateSet: PredicateSet +): ATNConfigSet { + const intermediate = new ATNConfigSet() + const skippedStopStates: ATNConfig[] = [] + + for (const c of configs.elements) { + if (predicateSet.is(c.alt) === false) { + continue + } + if (c.state.type === ATN_RULE_STOP) { + skippedStopStates.push(c) + continue + } + const transitionLength = c.state.transitions.length + for (let i = 0; i < transitionLength; i++) { + const transition = c.state.transitions[i] + const target = getReachableTarget(transition, token) + if (target !== undefined) { + intermediate.add({ + state: target, + alt: c.alt, + stack: c.stack + }) + } + } + } + + let reach: ATNConfigSet | undefined + + if (skippedStopStates.length === 0 && intermediate.size === 1) { + reach = intermediate + } + + if (reach === undefined) { + reach = new ATNConfigSet() + for (const c of intermediate.elements) { + closure(c, reach) + } + } + + if (skippedStopStates.length > 0 && !hasConfigInRuleStopState(reach)) { + for (const c of skippedStopStates) { + reach.add(c) + } + } + + return reach +} + +function getReachableTarget( + transition: Transition, + token: IToken +): ATNState | undefined { + if ( + transition instanceof AtomTransition && + tokenMatcher(token, transition.tokenType) + ) { + return transition.target + } + return undefined +} + +function getUniqueAlt( + configs: ATNConfigSet, + predicateSet: PredicateSet +): number | undefined { + let alt: number | undefined + for (const c of configs.elements) { + if (predicateSet.is(c.alt) === true) { + if (alt === undefined) { + alt = c.alt + } else if (alt !== c.alt) { + return undefined + } + } + } + return alt +} + +function newDFAState(closure: ATNConfigSet): DFAState { + return { + configs: closure, + edges: {}, + isAcceptState: false, + prediction: -1 + } +} + +function addDFAEdge( + dfa: DFA, + from: DFAState, + token: IToken, + to: DFAState +): DFAState { + to = addDFAState(dfa, to) + from.edges[token.tokenTypeIdx] = to + return to +} + +function addDFAState(dfa: DFA, state: DFAState): DFAState { + if (state === DFA_ERROR) { + return state + } + // Repetitions have the same config set + // Therefore, storing the key of the config in a map allows us to create a loop in our DFA + const mapKey = state.configs.key + const existing = dfa.states[mapKey] + if (existing !== undefined) { + return existing + } + state.configs.finalize() + dfa.states[mapKey] = state + return state +} + +function computeStartState(atnState: ATNState): ATNConfigSet { + const configs = new ATNConfigSet() + + const numberOfTransitions = atnState.transitions.length + for (let i = 0; i < numberOfTransitions; i++) { + const target = atnState.transitions[i].target + const config: ATNConfig = { + state: target, + alt: i, + stack: [] + } + closure(config, configs) + } + + return configs +} + +function closure(config: ATNConfig, configs: ATNConfigSet): void { + const p = config.state + + if (p.type === ATN_RULE_STOP) { + if (config.stack.length > 0) { + const atnStack = [...config.stack] + const followState = atnStack.pop()! + const followConfig: ATNConfig = { + state: followState, + alt: config.alt, + stack: atnStack + } + closure(followConfig, configs) + } else { + // Dipping into outer context, simply add the config + // This will stop computation once every config is at the rule stop state + configs.add(config) + } + return + } + + if (!p.epsilonOnlyTransitions) { + configs.add(config) + } + + const transitionLength = p.transitions.length + for (let i = 0; i < transitionLength; i++) { + const transition = p.transitions[i] + const c = getEpsilonTarget(config, transition) + + if (c !== undefined) { + closure(c, configs) + } + } +} + +function getEpsilonTarget( + config: ATNConfig, + transition: Transition +): ATNConfig | undefined { + if (transition instanceof EpsilonTransition) { + return { + state: transition.target, + alt: config.alt, + stack: config.stack + } + } else if (transition instanceof RuleTransition) { + const stack = [...config.stack, transition.followState] + return { + state: transition.target, + alt: config.alt, + stack + } + } + return undefined +} + +function hasConfigInRuleStopState(configs: ATNConfigSet): boolean { + for (const c of configs.elements) { + if (c.state.type === ATN_RULE_STOP) { + return true + } + } + return false +} + +function allConfigsInRuleStopStates(configs: ATNConfigSet): boolean { + for (const c of configs.elements) { + if (c.state.type !== ATN_RULE_STOP) { + return false + } + } + return true +} + +function hasConflictTerminatingPrediction(configs: ATNConfigSet): boolean { + if (allConfigsInRuleStopStates(configs)) { + return true + } + const altSets = getConflictingAltSets(configs.elements) + const heuristic = + hasConflictingAltSet(altSets) && !hasStateAssociatedWithOneAlt(altSets) + return heuristic +} + +function getConflictingAltSets( + configs: readonly ATNConfig[] +): Map> { + const configToAlts = new Map>() + for (const c of configs) { + const key = getATNConfigKey(c, false) + let alts = configToAlts.get(key) + if (alts === undefined) { + alts = {} + configToAlts.set(key, alts) + } + alts[c.alt] = true + } + return configToAlts +} + +function hasConflictingAltSet( + altSets: Map> +): boolean { + for (const value of Array.from(altSets.values())) { + if (Object.keys(value).length > 1) { + return true + } + } + return false +} + +function hasStateAssociatedWithOneAlt( + altSets: Map> +): boolean { + for (const value of Array.from(altSets.values())) { + if (Object.keys(value).length === 1) { + return true + } + } + return false +} diff --git a/node_modules/chevrotain-allstar/src/atn.test.ts b/node_modules/chevrotain-allstar/src/atn.test.ts new file mode 100644 index 0000000..f8ce64c --- /dev/null +++ b/node_modules/chevrotain-allstar/src/atn.test.ts @@ -0,0 +1,302 @@ +/****************************************************************************** + * Copyright 2022 TypeFox GmbH + * This program and the accompanying materials are made available under the + * terms of the MIT License, which is available in the project root. + ******************************************************************************/ + +import { createToken, EmbeddedActionsParser, EOF, IToken, TokenType } from "chevrotain" +import { LLStarLookaheadStrategy } from "./all-star-lookahead" + +describe("ATN Simulator", () => { + describe("LL(*) lookahead", () => { + const A = createToken({ name: "A", pattern: "a" }) + const B = createToken({ name: "B", pattern: "b" }) + + class UnboundedLookaheadParser extends EmbeddedActionsParser { + constructor() { + super([A, B], { + lookaheadStrategy: new LLStarLookaheadStrategy() + }) + this.performSelfAnalysis() + } + + LongRule = this.RULE("LongRule", () => { + return this.OR([ + { + ALT: () => { + return 0 + } + }, + { + ALT: () => { + this.AT_LEAST_ONE1(() => this.CONSUME1(A)) + return 1 + } + }, + { + ALT: () => { + this.AT_LEAST_ONE2(() => this.CONSUME2(A)) + this.CONSUME(B) + return 2 + } + } + ]) + }) + } + + it("Should pick longest alternative instead of first #1", () => { + const parser = new UnboundedLookaheadParser() + parser.input = [ + createRegularToken(A), + createRegularToken(A), + createRegularToken(A) + ] + const result = parser.LongRule() + expect(result).toBe(1); + }) + + it("Should pick longest alternative instead of first #2", () => { + const parser = new UnboundedLookaheadParser() + parser.input = [ + createRegularToken(A), + createRegularToken(A), + createRegularToken(B) + ] + const result = parser.LongRule() + expect(result).toBe(2); + }) + + it("Should pick shortest fitting alternative", () => { + const parser = new UnboundedLookaheadParser() + parser.input = [] + const result = parser.LongRule() + expect(result).toBe(0); + }) + }) + + describe("Ambiguity Detection", () => { + const A = createToken({ name: "A" }) + const B = createToken({ name: "B" }) + + class AmbigiousParser extends EmbeddedActionsParser { + ambiguityReports: string[] = [] + + constructor() { + super([A, B], { + lookaheadStrategy: new LLStarLookaheadStrategy({ + logging: (message) => this.ambiguityReports.push(message) + }) + }); + this.performSelfAnalysis() + } + + OptionRule = this.RULE("OptionRule", () => { + let usedOption = false + this.OPTION(() => { + this.AT_LEAST_ONE1(() => this.CONSUME1(A)) + usedOption = true + }) + this.AT_LEAST_ONE2(() => this.CONSUME2(A)) + return usedOption + }) + + AltRule = this.RULE("AltRule", () => { + return this.OR([ + { + ALT: () => { + this.SUBRULE(this.RuleB) + return 0 + } + }, + { + ALT: () => { + this.SUBRULE(this.RuleC) + return 1 + } + } + ]) + }) + + RuleB = this.RULE("RuleB", () => { + this.MANY(() => this.CONSUME(A)) + }) + + RuleC = this.RULE("RuleC", () => { + this.MANY(() => this.CONSUME(A)) + this.OPTION(() => this.CONSUME(B)) + }) + + AltRuleWithEOF = this.RULE("AltRuleWithEOF", () => { + return this.OR([ + { + ALT: () => { + this.SUBRULE1(this.RuleEOF) + return 0 + } + }, + { + ALT: () => { + this.SUBRULE2(this.RuleEOF) + return 1 + } + } + ]) + }) + + RuleEOF = this.RULE("RuleEOF", () => { + this.MANY1(() => this.CONSUME(A)) + this.CONSUME(EOF) + }) + + AltRuleWithPred = this.RULE("AltRuleWithPred", (pred?: boolean) => { + return this.OR([ + { + ALT: () => { + this.CONSUME1(A) + return 0 + }, + GATE: () => (pred === undefined ? true : pred) + }, + { + ALT: () => { + this.CONSUME2(A) + return 1 + }, + GATE: () => (pred === undefined ? true : !pred) + }, + { + ALT: () => { + this.CONSUME(B) + return 2 + } + } + ]) + }) + + AltWithOption = this.RULE("AltWithOption", () => { + const intermediate = this.OR([ + { + ALT: () => { + this.CONSUME1(A) + return 2 + } + }, + { + ALT: () => { + this.CONSUME2(B) + return 4 + } + } + ]) + const option = this.OPTION(() => { + this.CONSUME3(A); + return 1; + }) + return (option ?? 0) + intermediate; + }) + } + + it("Should pick option on ambiguity", () => { + const parser = new AmbigiousParser() + parser.input = [ + createRegularToken(A), + createRegularToken(A), + createRegularToken(A) + ] + const result = parser.OptionRule() + expect(result).toBeTruthy(); + // The rule nests a `AT_LEAST_ONE` inside and outside the OPTION + // Both productions produce lookahead ambiguities + expect(parser.ambiguityReports[0]).toMatch("<0, 1> in