From 12a8749c01f668316e5e01f9ef3c8327317a1cd7 Mon Sep 17 00:00:00 2001 From: Knut Wannheden Date: Sun, 29 Sep 2024 06:06:18 +0200 Subject: [PATCH] Remove old Javet-based parser (#119) The Javet jars are very large (50MB each), because they bundle V8 and NodeJS. As a result the `rewrite-javascript` is over 100MB when counting its dependencies. --- build.gradle.kts | 3 - js/.gitignore | 1 - js/.nvmrc | 1 - js/.prettierrc | 5 - js/README.md | 22 - js/build.gradle.kts | 35 - js/package.json | 32 - js/settings.gradle.kts | 0 js/src/Paths.ts | 21 - js/src/codegen/exportEnums.ts | 174 - js/src/codegen/generateInterfaces.ts | 9 - js/src/codegen/generateLibs.ts | 29 - js/src/codegen/generatedLicenseHeader.txt | 15 - js/src/runtime/PathPrefixes.ts | 21 - js/src/runtime/index.ts | 118 - js/src/runtime/vfs.ts | 142 - js/tsconfig.json | 17 - js/yarn.lock | 1666 -------- scripts/.gitignore | 1 - scripts/common.sh | 34 - scripts/find-javet-jni-references.sh | 64 - .../caoccao/javet/interop/JavetBridge.java | 122 - .../TypeScriptSignatureBuilder.java | 548 --- .../javascript/TypeScriptTypeMapping.java | 807 ---- .../internal/JavetNativeBridge.java | 157 - .../javascript/internal/JavetUtils.java | 34 - .../javascript/internal/TsTreePrinter.java | 496 --- .../internal/TypeScriptParserVisitor.java | 3542 ----------------- .../internal/tsc/TSCContextCallback.java | 22 - .../internal/tsc/TSCConversion.java | 44 - .../internal/tsc/TSCConversions.java | 220 - .../javascript/internal/tsc/TSCGlobals.java | 57 - .../javascript/internal/tsc/TSCIndexInfo.java | 40 - .../internal/tsc/TSCInstanceOfChecks.java | 125 - .../javascript/internal/tsc/TSCInternal.java | 22 - .../javascript/internal/tsc/TSCMeta.java | 64 - .../javascript/internal/tsc/TSCNode.java | 331 -- .../javascript/internal/tsc/TSCNodeList.java | 264 -- .../internal/tsc/TSCObjectCache.java | 72 - .../internal/tsc/TSCProgramContext.java | 173 - .../javascript/internal/tsc/TSCRuntime.java | 206 - .../javascript/internal/tsc/TSCSignature.java | 39 - .../internal/tsc/TSCSourceFileContext.java | 86 - .../javascript/internal/tsc/TSCSymbol.java | 101 - .../internal/tsc/TSCSyntaxListNode.java | 159 - .../javascript/internal/tsc/TSCType.java | 73 - .../internal/tsc/TSCTypeAccessors.java | 324 -- .../internal/tsc/TSCTypeChecker.java | 344 -- .../javascript/internal/tsc/TSCUtils.java | 36 - .../javascript/internal/tsc/TSCV8Backed.java | 412 -- .../javascript/internal/tsc/TSCV8Utils.java | 73 - .../internal/tsc/TSCV8ValueHolder.java | 78 - .../internal/tsc/generated/TSCFlowFlag.java | 96 - .../internal/tsc/generated/TSCIndexKind.java | 45 - .../tsc/generated/TSCModifierFlag.java | 132 - .../internal/tsc/generated/TSCNodeFlag.java | 168 - .../internal/tsc/generated/TSCObjectFlag.java | 156 - .../tsc/generated/TSCSignatureKind.java | 45 - .../internal/tsc/generated/TSCSymbolFlag.java | 232 -- .../internal/tsc/generated/TSCSyntaxKind.java | 1157 ------ .../internal/tsc/generated/TSCTokenFlag.java | 115 - .../internal/tsc/generated/TSCTypeFlag.java | 242 -- .../tsc/generated/TSCTypePredicateKind.java | 51 - .../javascript/internal/tsc/package-info.java | 21 - .../TypeScriptSignatureBuilderTest.java | 238 -- .../javascript/TypeScriptTypeMappingTest.java | 232 -- .../javascript/internal/V8InteropTests.java | 438 -- .../javascript/tree/ParserTest.java | 46 + 68 files changed, 46 insertions(+), 14849 deletions(-) delete mode 100644 js/.gitignore delete mode 100644 js/.nvmrc delete mode 100644 js/.prettierrc delete mode 100644 js/README.md delete mode 100644 js/build.gradle.kts delete mode 100644 js/package.json delete mode 100644 js/settings.gradle.kts delete mode 100644 js/src/Paths.ts delete mode 100644 js/src/codegen/exportEnums.ts delete mode 100644 js/src/codegen/generateInterfaces.ts delete mode 100644 js/src/codegen/generateLibs.ts delete mode 100644 js/src/codegen/generatedLicenseHeader.txt delete mode 100644 js/src/runtime/PathPrefixes.ts delete mode 100644 js/src/runtime/index.ts delete mode 100644 js/src/runtime/vfs.ts delete mode 100644 js/tsconfig.json delete mode 100644 js/yarn.lock delete mode 100644 scripts/.gitignore delete mode 100644 scripts/common.sh delete mode 100755 scripts/find-javet-jni-references.sh delete mode 100644 src/main/java/com/caoccao/javet/interop/JavetBridge.java delete mode 100644 src/main/java/org/openrewrite/javascript/TypeScriptSignatureBuilder.java delete mode 100644 src/main/java/org/openrewrite/javascript/TypeScriptTypeMapping.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/JavetNativeBridge.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/JavetUtils.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/TsTreePrinter.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/TypeScriptParserVisitor.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCContextCallback.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCConversion.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCConversions.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCGlobals.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCIndexInfo.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCInstanceOfChecks.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCInternal.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCMeta.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCNode.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCNodeList.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCObjectCache.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCProgramContext.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCRuntime.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCSignature.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCSourceFileContext.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCSymbol.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCSyntaxListNode.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCType.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCTypeAccessors.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCTypeChecker.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCUtils.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCV8Backed.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCV8Utils.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/TSCV8ValueHolder.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCFlowFlag.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCIndexKind.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCModifierFlag.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCNodeFlag.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCObjectFlag.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSignatureKind.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSymbolFlag.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSyntaxKind.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTokenFlag.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTypeFlag.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTypePredicateKind.java delete mode 100644 src/main/java/org/openrewrite/javascript/internal/tsc/package-info.java delete mode 100644 src/test/java/org/openrewrite/javascript/TypeScriptSignatureBuilderTest.java delete mode 100644 src/test/java/org/openrewrite/javascript/TypeScriptTypeMappingTest.java delete mode 100644 src/test/java/org/openrewrite/javascript/internal/V8InteropTests.java diff --git a/build.gradle.kts b/build.gradle.kts index fdf8c493..83334dff 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -23,9 +23,6 @@ dependencies { testImplementation("org.junit-pioneer:junit-pioneer:2.0.0") testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:latest.release") - - implementation("com.caoccao.javet:javet-macos:3.0.0") // Mac OS (x86_64 and arm64) - implementation("com.caoccao.javet:javet:3.0.0") // Linux and Windows } // FIXME disable all tests for now until the parser tests have been moved to JavaScript diff --git a/js/.gitignore b/js/.gitignore deleted file mode 100644 index fb1aa5ad..00000000 --- a/js/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/src/generated/libs.json \ No newline at end of file diff --git a/js/.nvmrc b/js/.nvmrc deleted file mode 100644 index aad5ebe1..00000000 --- a/js/.nvmrc +++ /dev/null @@ -1 +0,0 @@ -20.8.0 \ No newline at end of file diff --git a/js/.prettierrc b/js/.prettierrc deleted file mode 100644 index 5d044708..00000000 --- a/js/.prettierrc +++ /dev/null @@ -1,5 +0,0 @@ -{ - "printWidth": 100, - "tabWidth": 4, - "trailingComma": "all" -} \ No newline at end of file diff --git a/js/README.md b/js/README.md deleted file mode 100644 index 1aa1b8a2..00000000 --- a/js/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# TypeScript Compiler Wrapper - -Until the Gradle build does it automatically, changes to the JS sub-project need to be synced to the parent project. - -The first time you check out the project, or when you change `package.json`, run (all commands from the `js` dir): -```shell -nvm use && yarn install -``` - -When you make changes here, run: -```shell -nvm use && yarn update -``` - -## Structure -Each script may be run and debugged through `package.json => scripts` -- `src/` - - `codegen/` is for scripts that generate Java and TypeScript code during the build process - - `generatedLicenseHeader.txt` is inserted at the top of every generated Java/TS file - - `runtime/` is for TypeScript code that runs on the embedded V8 inside the JVM for parsing and type-checking - - `generated/` is for TypeScript code generated by `codegen`, which can be referenced by - - `Paths.ts` exports known resolved absolute paths to avoid path-building errors when refactoring \ No newline at end of file diff --git a/js/build.gradle.kts b/js/build.gradle.kts deleted file mode 100644 index 95a7416a..00000000 --- a/js/build.gradle.kts +++ /dev/null @@ -1,35 +0,0 @@ -plugins { - id("com.github.node-gradle.node") version "7.0.1" -} - -apply(plugin = "base") -apply(plugin = "com.github.node-gradle.node") - -group = "org.openrewrite" - -node { - version.set("20.8.0") - npmVersion.set("10.1.0") - download.set(true) -} - -tasks.getByName("yarn_install") { - inputs.file("package.json") - outputs.file("yarn.lock") - outputs.dir("node_modules") -} - -tasks.getByName("clean") { - delete.add("node_modules") - delete.add("dist") -} - -tasks.getByName("yarn_build") { - inputs.file("tsconfig.json") - inputs.file("package.json") - inputs.file("yarn.lock") - inputs.dir("src") - outputs.dir("dist") -} - -// TODO add artifact for index.js diff --git a/js/package.json b/js/package.json deleted file mode 100644 index 656600f0..00000000 --- a/js/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "rewrite-javascript-bootstrap", - "source": "src/runtime/index.ts", - "main": "dist/index.js", - "targets": { - "main": { - "includeNodeModules": true, - "engines": { - "browsers": "Chrome 80" - } - } - }, - "license": "UNLICENSED", - "private": true, - "scripts": { - "generate": "ts-node src/codegen/exportEnums.ts && ts-node src/codegen/generateLibs.ts", - "buildRuntime": "parcel build && cat src/codegen/generatedLicenseHeader.txt dist/index.js > ../src/main/resources/tsc/index.js", - "update": "yarn generate && yarn buildRuntime", - "format": "prettier --write ./src" - }, - "devDependencies": { - "@types/node": "20.8.7", - "parcel": "2.10.0", - "prettier": "3.0.3", - "process": "0.11.10", - "ts-node": "10.9.1" - }, - "dependencies": { - "@typescript/vfs": "1.5.0", - "typescript": "5.2.2" - } -} diff --git a/js/settings.gradle.kts b/js/settings.gradle.kts deleted file mode 100644 index e69de29b..00000000 diff --git a/js/src/Paths.ts b/js/src/Paths.ts deleted file mode 100644 index 5cf11d39..00000000 --- a/js/src/Paths.ts +++ /dev/null @@ -1,21 +0,0 @@ -import path from "path"; - -export const Paths = new (class { - readonly JS_SUBPROJECT_SRC = path.resolve(__dirname); - readonly JS_SUBPROJECT_ROOT = path.resolve(this.JS_SUBPROJECT_SRC, ".."); - readonly JS_SUBPROJECT_NODE_MODULES = path.resolve(this.JS_SUBPROJECT_ROOT, "node_modules"); - readonly JS_SUBPROJECT_TYPESCRIPT_MODULE = path.resolve( - this.JS_SUBPROJECT_NODE_MODULES, - "typescript", - ); - - readonly REWRITE_JAVASCRIPT_ROOT = path.resolve(this.JS_SUBPROJECT_ROOT, ".."); - readonly REWRITE_JAVASCRIPT_MAIN_JAVA = path.resolve( - this.REWRITE_JAVASCRIPT_ROOT, - "src/main/java", - ); - readonly REWRITE_JAVASCRIPT_MAIN_RESOURCES = path.resolve( - this.REWRITE_JAVASCRIPT_ROOT, - "src/main/resources", - ); -})(); diff --git a/js/src/codegen/exportEnums.ts b/js/src/codegen/exportEnums.ts deleted file mode 100644 index 1773c760..00000000 --- a/js/src/codegen/exportEnums.ts +++ /dev/null @@ -1,174 +0,0 @@ -import path from "path"; -import * as fs from "fs"; -import { - FlowFlags, - IndexKind, - ModifierFlags, - NodeFlags, - ObjectFlags, - SignatureKind, - SymbolFlags, - SyntaxKind, - TokenFlags, - TypeFlags, - TypePredicateKind, -} from "typescript"; - -const baseDir = path.resolve( - __dirname, - "../../../src/main/java/org/openrewrite/javascript/internal/tsc/generated", -); -const basePkg = "org.openrewrite.javascript.internal.tsc.generated"; - -const Mappings = { - FlowFlags, - IndexKind, - ModifierFlags, - NodeFlags, - ObjectFlags, - SignatureKind, - SymbolFlags, - SyntaxKind, - TokenFlags, - TypeFlags, - TypePredicateKind, -}; - -type EnumType = "kind" | "bitfield" | "other"; - -type EnumOptions = { - readonly tscInternalEnumName: string; - readonly generatedEnumName: string; - readonly enumType: EnumType; - readonly enumObject: { readonly [k: string]: number | string }; -}; - -async function main() { - console.info(`Deleting and re-creating base directory ${baseDir}`); - await fs.promises.rm(baseDir, { recursive: true, force: true }); - await fs.promises.mkdir(baseDir, { recursive: true }); - console.info(" Done."); - - for (const [tscInternalEnumName, enumObject] of Object.entries(Mappings)) { - let generatedEnumName = "TSC" + tscInternalEnumName; - let enumType: EnumType; - if (tscInternalEnumName.endsWith("Flags")) { - enumType = "bitfield"; - } else if (tscInternalEnumName.endsWith("Kinds")) { - enumType = "kind"; - } else { - enumType = "other"; - } - - if (generatedEnumName.endsWith("s")) { - generatedEnumName = generatedEnumName.slice(0, generatedEnumName.length - 1); - } - - await exportEnum({ - tscInternalEnumName, - generatedEnumName, - enumType, - enumObject, - }); - } -} - -async function exportEnum(opts: EnumOptions) { - const { enumObject, generatedEnumName, enumType } = opts; - - const byValue = new Map(); - for (const [key, value] of Object.entries(enumObject)) { - if ("" + parseInt(key, 10) === key || typeof value === "string") { - // this is a reverse mapping - continue; - } - let bucket = byValue.get(value); - if (!bucket) { - bucket = []; - byValue.set(value, bucket); - } - bucket.push(key); - } - - const licenseHeader = await fs.promises.readFile( - path.resolve(__dirname, "generatedLicenseHeader.txt"), - "utf-8", - ); - - let output = ""; - output += licenseHeader + "\n"; - output += `package ${basePkg};\n`; - output += "\n"; - - output += "//\n"; - output += "// THIS FILE IS GENERATED. Do not modify it by hand.\n"; - output += "// See `js/README.md` for instructions to regenerate this file.\n"; - output += "//\n"; - - output += "\n"; - output += `public enum ${generatedEnumName} {\n`; - - const lastValue = [...byValue.keys()][byValue.size - 1]; - - // enum values - for (const [value, names] of byValue.entries()) { - if (names.length > 1) { - output += ` /** Also includes ${names.slice(1).join(", ")} */\n`; - } - const delim = value === lastValue ? ";" : ","; - output += ` ${names[0]}(${value})${delim}\n`; - } - - // fields - output += "\n\n"; - output += ` public final int code;\n`; - - // constructor - output += "\n"; - output += ` ${generatedEnumName}(int code) {\n`; - output += ` this.code = code;\n`; - output += ` }\n`; - - // method to map from code -> enum value - const fromCodeMethodName = enumType === "bitfield" ? "fromMaskExact" : "fromCode"; - output += "\n"; - output += ` public static ${generatedEnumName} ${fromCodeMethodName}(int code) {\n`; - output += ` switch (code) {\n`; - for (const [value, names] of byValue.entries()) { - output += ` case ${value}:\n`; - output += ` return ${generatedEnumName}.${names[0]};\n`; - } - output += ` default:\n`; - output += ` throw new IllegalArgumentException("unknown ${generatedEnumName} code: " + code);\n`; - output += ` }\n`; - output += ` }\n`; - - if (enumType === "bitfield") { - output += "\n"; - output += ` public boolean matches(int bitfield) {\n`; - output += ` return (bitfield & this.code) != 0;\n`; - output += ` }\n`; - - output += "\n"; - output += ` public static int union(${generatedEnumName}... args) {\n`; - output += ` int result = 0;\n`; - output += ` for (${generatedEnumName} arg : args) {\n`; - output += ` result = result | arg.code;\n`; - output += ` }\n`; - output += ` return result;\n`; - output += ` }\n`; - } - - output += "}\n"; - - const outputPath = path.resolve(baseDir, `${generatedEnumName}.java`); - console.info(`Generating ${outputPath}`); - await fs.promises.writeFile(outputPath, output, "utf-8"); - console.info(` Wrote ${new TextEncoder().encode(output).length} bytes.`); -} - -if (require.main === module) { - main() - .then() - .catch((err) => console.error(err)); -} diff --git a/js/src/codegen/generateInterfaces.ts b/js/src/codegen/generateInterfaces.ts deleted file mode 100644 index fab7520a..00000000 --- a/js/src/codegen/generateInterfaces.ts +++ /dev/null @@ -1,9 +0,0 @@ -async function main() {} - -function getTypeScriptTypeScriptProject() {} - -if (require.main === module) { - main() - .then() - .catch((err) => console.error(err)); -} diff --git a/js/src/codegen/generateLibs.ts b/js/src/codegen/generateLibs.ts deleted file mode 100644 index d38bf5dc..00000000 --- a/js/src/codegen/generateLibs.ts +++ /dev/null @@ -1,29 +0,0 @@ -import * as fs from "fs"; -import { Paths } from "../Paths"; -import path from "path"; - -async function main() { - const output: { [libName: string]: string } = {}; - const libsDir = path.resolve(Paths.JS_SUBPROJECT_TYPESCRIPT_MODULE, "lib"); - const libNames = await fs.promises.readdir(libsDir, { withFileTypes: true }); - for (const libFile of libNames) { - if (!libFile.isFile()) continue; - - const libName = libFile.name; - if (!libName.startsWith("lib")) continue; - if (!libName.endsWith(".d.ts")) continue; - - const libPath = path.resolve(libsDir, libName); - output[libName] = await fs.promises.readFile(libPath, "utf-8"); - } - - const outputPath = path.resolve(Paths.JS_SUBPROJECT_SRC, "generated/libs.json"); - await fs.promises.mkdir(path.dirname(outputPath), { recursive: true }); - await fs.promises.writeFile(outputPath, JSON.stringify(output, null, 2)); -} - -if (require.main === module) { - main() - .then() - .catch((err) => console.error(err)); -} diff --git a/js/src/codegen/generatedLicenseHeader.txt b/js/src/codegen/generatedLicenseHeader.txt deleted file mode 100644 index bb480b4b..00000000 --- a/js/src/codegen/generatedLicenseHeader.txt +++ /dev/null @@ -1,15 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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/js/src/runtime/PathPrefixes.ts b/js/src/runtime/PathPrefixes.ts deleted file mode 100644 index 47b8abd6..00000000 --- a/js/src/runtime/PathPrefixes.ts +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ - -/** This object's property names are referenced by the Java code; do not change them. */ -export const PathPrefixes = Object.freeze({ - lib: "/lib/", - app: "/app/", -}); diff --git a/js/src/runtime/index.ts b/js/src/runtime/index.ts deleted file mode 100644 index 22860009..00000000 --- a/js/src/runtime/index.ts +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -import * as ts from "typescript"; -import { CompilerOptions } from "typescript"; -import libFileData from "../generated/libs.json"; -import { PathPrefixes } from "./PathPrefixes"; -import { createCompilerHost, VfsOptions } from "./vfs"; - -const OPEN_REWRITE_ID_SYMBOL = Symbol("OpenRewriteId"); - -const libMap: Map = (ts as any).libMap; -const toFileNameLowerCase: (s: string) => string = (ts as any).toFileNameLowerCase; - -type ParseOptions = { - readonly compilerOptions?: CompilerOptions; - readonly forwardedPaths?: Map; -} & VfsOptions; - -// (entry point from Java code) -// noinspection JSUnusedGlobalSymbols -export default function parse(originalInputs: Map, options?: ParseOptions) { - try { - const allFiles = new Map(); - - const originalInputPathToProgramPath = new Map(); - for (const [inputPath, inputData] of originalInputs) { - const newInputPath = `${PathPrefixes.app}${inputPath}`; - originalInputPathToProgramPath.set(inputPath, newInputPath); - allFiles.set(newInputPath, inputData); - } - - for (const [libPath, libData] of Object.entries(libFileData)) { - allFiles.set(`${PathPrefixes.lib}${libPath}`, libData); - } - - let compilerOptions: ts.CompilerOptions = { - allowJs: true, - checkJs: true, - noEmit: true, - ...options?.compilerOptions, - }; - - compilerOptions = remapLibNames(compilerOptions); - - const createProgramOptions: Omit = { - options: compilerOptions, - rootNames: [...originalInputPathToProgramPath.values()], - }; - - const host = createCompilerHost(options ?? {}, compilerOptions, allFiles); - - const program = ts.createProgram({ - host, - ...createProgramOptions, - }); - - let nextNodeId = BigInt(1); - const getOpenRewriteId = (obj: any) => { - let objId = obj[OPEN_REWRITE_ID_SYMBOL]; - if (objId === undefined) { - objId = nextNodeId++; - obj[OPEN_REWRITE_ID_SYMBOL] = objId; - } - return objId; - }; - - return { - pathPrefixes: PathPrefixes, - program, - getOpenRewriteId, - typeChecker: program.getTypeChecker(), - sourceFiles: new Map( - [...originalInputPathToProgramPath].map( - ([originalInputPath, programInputPath]) => - [originalInputPath, program.getSourceFile(programInputPath)] as const, - ), - ), - createScanner: () => ts.createScanner(ts.ScriptTarget.ESNext, false, undefined), - ts, - }; - } catch (err) { - console.error("Error while parsing on the V8 side:", (err as any).stack || err); - } -} - -/** - * In TS config, the `lib` parameter looks like "ES2020" or "es2019.array". - * The actual lib paths are like "lib.es2020.d.ts" or "es2019.array.d.ts". - */ -function remapLibNames(compilerOptions: CompilerOptions): CompilerOptions { - if (compilerOptions.lib) { - compilerOptions.lib = compilerOptions.lib.map((lib) => { - const lowercaseLib = toFileNameLowerCase(lib); - const foundLib = libMap.get(lowercaseLib); - if (foundLib !== undefined) { - console.log("found lib: " + foundLib); - return `${PathPrefixes.lib}${foundLib}`; - } else { - console.log("didn't find lib: " + lib); - return lib; - } - }); - } - return compilerOptions; -} diff --git a/js/src/runtime/vfs.ts b/js/src/runtime/vfs.ts deleted file mode 100644 index 9465ac40..00000000 --- a/js/src/runtime/vfs.ts +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -import * as ts from "typescript"; -import * as tsvfs from "@typescript/vfs"; -import { PathPrefixes } from "./PathPrefixes"; - -export type VfsOptions = { - readonly traceVirtualFileSystem?: boolean; -}; - -export function createCompilerHost( - vfsOptions: VfsOptions, - compilerOptions: ts.CompilerOptions, - allFiles: Map, -) { - const system = createVirtualFileSystem(vfsOptions, allFiles); - const host = tsvfs.createVirtualCompilerHost(system, compilerOptions, ts).compilerHost; - const getSourceFile = host.getSourceFile; - - host.getSourceFile = (filename, ...args) => { - if (vfsOptions.traceVirtualFileSystem) { - console.error("host.getSourceFile(" + filename + ")"); - } - if (!host.fileExists(filename)) { - return; - } else { - return getSourceFile(filename, ...args); - } - }; - host.getDefaultLibLocation = () => PathPrefixes.lib; - host.getDefaultLibFileName = (compilerOptions) => - PathPrefixes.lib + ts.getDefaultLibFileName(compilerOptions); - - return host; -} - -function createVirtualFileSystem(vfsOptions: VfsOptions, allFiles: Map) { - const system = tsvfs.createSystem(allFiles); - - if (!system.realpath) { - // FIXME not a valid assumption - system.realpath = (path) => path; - } - - if (!system.getFileSize) { - system.getFileSize = (path) => system.readFile(path)?.length ?? 0; - } - - if (system.readFile) { - const oldReadFile = system.readFile; - system.readFile = (filename, ...args) => { - const result = oldReadFile(filename, ...args); - if (result === undefined && allFiles.has(filename)) { - return allFiles.get(filename); - } - return result; - }; - } - - if (vfsOptions.traceVirtualFileSystem) { - addFileSystemTracing(system, allFiles); - } - - return system; -} - -function addFileSystemTracing(system: ts.System, allFiles: Map) { - const readFile = system.readFile; - if (readFile) { - system.readFile = function (...[filename, ...args]: Parameters) { - console.error("system.readFile(", filename, ...args, ")"); - return readFile(filename, ...args); - }; - } else { - console.error("*** no system.readFile"); - } - - const fileExists = system.fileExists; - system.fileExists = function (path) { - console.error("system.fileExists(" + path + ")"); - const result = fileExists(path); - console.error("--> " + result); - return result; - }; - - const resolvePath = system.resolvePath; - system.resolvePath = function (path) { - console.error("system.resolvePath(" + path + ")"); - const result = resolvePath(path); - console.error("--> " + result); - return result; - }; - - const realpath = system.realpath; - if (realpath) { - system.realpath = function (path) { - console.error("system.realpath(" + path + ")"); - const result = realpath(path); - console.error("--> " + result); - return result; - }; - } - - const readDirectory = system.readDirectory; - system.readDirectory = function (path, ...args) { - console.error("system.readDirectory(" + path + ")"); - const result = readDirectory.call(system, path, ...args); - console.error("--> " + result); - return result; - }; - - const directoryExists = system.directoryExists; - system.directoryExists = function (path) { - console.error("system.directoryExists(" + path + ")"); - const result = directoryExists(path); - console.error("--> " + result); - return result; - }; - - const getFileSize = system.getFileSize; - if (getFileSize) { - system.getFileSize = function (path) { - console.error("system.getFileSize(" + path + ")"); - const result = getFileSize(path); - console.error("--> " + result); - return result; - }; - } -} diff --git a/js/tsconfig.json b/js/tsconfig.json deleted file mode 100644 index 98034bb2..00000000 --- a/js/tsconfig.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/tsconfig", - "display": "Node 14", - - "compilerOptions": { - "lib": ["esnext"], - "module": "commonjs", - "target": "esnext", - "resolveJsonModule": true, - "strict": true, - "esModuleInterop": true, - "skipLibCheck": true, - "forceConsistentCasingInFileNames": true, - "moduleResolution": "node" - }, - "include": ["src/**/*"] -} \ No newline at end of file diff --git a/js/yarn.lock b/js/yarn.lock deleted file mode 100644 index 01bb7c5e..00000000 --- a/js/yarn.lock +++ /dev/null @@ -1,1666 +0,0 @@ -# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. -# yarn lockfile v1 - - -"@babel/code-frame@^7.0.0": - version "7.21.4" - resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.21.4.tgz#d0fa9e4413aca81f2b23b9442797bda1826edb39" - integrity sha512-LYvhNKfwWSPpocw8GI7gpK2nq3HSDuEPC/uSYaALSJu9xjsalaaYFOq0Pwt5KmVqwEbZlDu81aLXwBOmD/Fv9g== - dependencies: - "@babel/highlight" "^7.18.6" - -"@babel/helper-validator-identifier@^7.18.6": - version "7.19.1" - resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.19.1.tgz#7eea834cf32901ffdc1a7ee555e2f9c27e249ca2" - integrity sha512-awrNfaMtnHUr653GgGEs++LlAvW6w+DcPrOliSMXWCKo597CwL5Acf/wWdNkf/tfEQE3mjkeD1YOVZOUV/od1w== - -"@babel/highlight@^7.18.6": - version "7.18.6" - resolved "https://registry.yarnpkg.com/@babel/highlight/-/highlight-7.18.6.tgz#81158601e93e2563795adcbfbdf5d64be3f2ecdf" - integrity sha512-u7stbOuYjaPezCuLj29hNW1v64M2Md2qupEKP1fHc7WdOA3DgLh37suiSrZYY7haUB7iBeQZ9P1uiRF359do3g== - dependencies: - "@babel/helper-validator-identifier" "^7.18.6" - chalk "^2.0.0" - js-tokens "^4.0.0" - -"@cspotcode/source-map-support@^0.8.0": - version "0.8.1" - resolved "https://registry.yarnpkg.com/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz#00629c35a688e05a88b1cda684fb9d5e73f000a1" - integrity sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw== - dependencies: - "@jridgewell/trace-mapping" "0.3.9" - -"@jridgewell/resolve-uri@^3.0.3": - version "3.1.1" - resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz#c08679063f279615a3326583ba3a90d1d82cc721" - integrity sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA== - -"@jridgewell/sourcemap-codec@^1.4.10": - version "1.4.15" - resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz#d7c6e6755c78567a951e04ab52ef0fd26de59f32" - integrity sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg== - -"@jridgewell/trace-mapping@0.3.9": - version "0.3.9" - resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz#6534fd5933a53ba7cbf3a17615e273a0d1273ff9" - integrity sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ== - dependencies: - "@jridgewell/resolve-uri" "^3.0.3" - "@jridgewell/sourcemap-codec" "^1.4.10" - -"@lezer/common@^0.15.0", "@lezer/common@^0.15.7": - version "0.15.12" - resolved "https://registry.yarnpkg.com/@lezer/common/-/common-0.15.12.tgz#2f21aec551dd5fd7d24eb069f90f54d5bc6ee5e9" - integrity sha512-edfwCxNLnzq5pBA/yaIhwJ3U3Kz8VAUOTRg0hhxaizaI1N+qxV7EXDv/kLCkLeq2RzSFvxexlaj5Mzfn2kY0Ig== - -"@lezer/lr@^0.15.4": - version "0.15.8" - resolved "https://registry.yarnpkg.com/@lezer/lr/-/lr-0.15.8.tgz#1564a911e62b0a0f75ca63794a6aa8c5dc63db21" - integrity sha512-bM6oE6VQZ6hIFxDNKk8bKPa14hqFrV07J/vHGOeiAbJReIaQXmkVb6xQu4MR+JBTLa5arGRyAAjJe1qaQt3Uvg== - dependencies: - "@lezer/common" "^0.15.0" - -"@lmdb/lmdb-darwin-arm64@2.8.5": - version "2.8.5" - resolved "https://registry.yarnpkg.com/@lmdb/lmdb-darwin-arm64/-/lmdb-darwin-arm64-2.8.5.tgz#895d8cb16a9d709ce5fedd8b60022903b875e08e" - integrity sha512-KPDeVScZgA1oq0CiPBcOa3kHIqU+pTOwRFDIhxvmf8CTNvqdZQYp5cCKW0bUk69VygB2PuTiINFWbY78aR2pQw== - -"@lmdb/lmdb-darwin-x64@2.8.5": - version "2.8.5" - resolved "https://registry.yarnpkg.com/@lmdb/lmdb-darwin-x64/-/lmdb-darwin-x64-2.8.5.tgz#ca243534c8b37d5516c557e4624256d18dd63184" - integrity sha512-w/sLhN4T7MW1nB3R/U8WK5BgQLz904wh+/SmA2jD8NnF7BLLoUgflCNxOeSPOWp8geP6nP/+VjWzZVip7rZ1ug== - -"@lmdb/lmdb-linux-arm64@2.8.5": - version "2.8.5" - resolved "https://registry.yarnpkg.com/@lmdb/lmdb-linux-arm64/-/lmdb-linux-arm64-2.8.5.tgz#b44a8023057e21512eefb9f6120096843b531c1e" - integrity sha512-vtbZRHH5UDlL01TT5jB576Zox3+hdyogvpcbvVJlmU5PdL3c5V7cj1EODdh1CHPksRl+cws/58ugEHi8bcj4Ww== - -"@lmdb/lmdb-linux-arm@2.8.5": - version "2.8.5" - resolved "https://registry.yarnpkg.com/@lmdb/lmdb-linux-arm/-/lmdb-linux-arm-2.8.5.tgz#17bd54740779c3e4324e78e8f747c21416a84b3d" - integrity sha512-c0TGMbm2M55pwTDIfkDLB6BpIsgxV4PjYck2HiOX+cy/JWiBXz32lYbarPqejKs9Flm7YVAKSILUducU9g2RVg== - -"@lmdb/lmdb-linux-x64@2.8.5": - version "2.8.5" - resolved "https://registry.yarnpkg.com/@lmdb/lmdb-linux-x64/-/lmdb-linux-x64-2.8.5.tgz#6c61835b6cc58efdf79dbd5e8c72a38300a90302" - integrity sha512-Xkc8IUx9aEhP0zvgeKy7IQ3ReX2N8N1L0WPcQwnZweWmOuKfwpS3GRIYqLtK5za/w3E60zhFfNdS+3pBZPytqQ== - -"@lmdb/lmdb-win32-x64@2.8.5": - version "2.8.5" - resolved "https://registry.yarnpkg.com/@lmdb/lmdb-win32-x64/-/lmdb-win32-x64-2.8.5.tgz#8233e8762440b0f4632c47a09b1b6f23de8b934c" - integrity sha512-4wvrf5BgnR8RpogHhtpCPJMKBmvyZPhhUtEwMJbXh0ni2BucpfF07jlmyM11zRqQ2XIq6PbC2j7W7UCCcm1rRQ== - -"@mischnic/json-sourcemap@^0.1.0": - version "0.1.0" - resolved "https://registry.yarnpkg.com/@mischnic/json-sourcemap/-/json-sourcemap-0.1.0.tgz#38af657be4108140a548638267d02a2ea3336507" - integrity sha512-dQb3QnfNqmQNYA4nFSN/uLaByIic58gOXq4Y4XqLOWmOrw73KmJPt/HLyG0wvn1bnR6mBKs/Uwvkh+Hns1T0XA== - dependencies: - "@lezer/common" "^0.15.7" - "@lezer/lr" "^0.15.4" - json5 "^2.2.1" - -"@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.2": - version "3.0.2" - resolved "https://registry.yarnpkg.com/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.2.tgz#44d752c1a2dc113f15f781b7cc4f53a307e3fa38" - integrity sha512-9bfjwDxIDWmmOKusUcqdS4Rw+SETlp9Dy39Xui9BEGEk19dDwH0jhipwFzEff/pFg95NKymc6TOTbRKcWeRqyQ== - -"@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.2": - version "3.0.2" - resolved "https://registry.yarnpkg.com/@msgpackr-extract/msgpackr-extract-darwin-x64/-/msgpackr-extract-darwin-x64-3.0.2.tgz#f954f34355712212a8e06c465bc06c40852c6bb3" - integrity sha512-lwriRAHm1Yg4iDf23Oxm9n/t5Zpw1lVnxYU3HnJPTi2lJRkKTrps1KVgvL6m7WvmhYVt/FIsssWay+k45QHeuw== - -"@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.2": - version "3.0.2" - resolved "https://registry.yarnpkg.com/@msgpackr-extract/msgpackr-extract-linux-arm64/-/msgpackr-extract-linux-arm64-3.0.2.tgz#45c63037f045c2b15c44f80f0393fa24f9655367" - integrity sha512-FU20Bo66/f7He9Fp9sP2zaJ1Q8L9uLPZQDub/WlUip78JlPeMbVL8546HbZfcW9LNciEXc8d+tThSJjSC+tmsg== - -"@msgpackr-extract/msgpackr-extract-linux-arm@3.0.2": - version "3.0.2" - resolved "https://registry.yarnpkg.com/@msgpackr-extract/msgpackr-extract-linux-arm/-/msgpackr-extract-linux-arm-3.0.2.tgz#35707efeafe6d22b3f373caf9e8775e8920d1399" - integrity sha512-MOI9Dlfrpi2Cuc7i5dXdxPbFIgbDBGgKR5F2yWEa6FVEtSWncfVNKW5AKjImAQ6CZlBK9tympdsZJ2xThBiWWA== - -"@msgpackr-extract/msgpackr-extract-linux-x64@3.0.2": - version "3.0.2" - resolved "https://registry.yarnpkg.com/@msgpackr-extract/msgpackr-extract-linux-x64/-/msgpackr-extract-linux-x64-3.0.2.tgz#091b1218b66c341f532611477ef89e83f25fae4f" - integrity sha512-gsWNDCklNy7Ajk0vBBf9jEx04RUxuDQfBse918Ww+Qb9HCPoGzS+XJTLe96iN3BVK7grnLiYghP/M4L8VsaHeA== - -"@msgpackr-extract/msgpackr-extract-win32-x64@3.0.2": - version "3.0.2" - resolved "https://registry.yarnpkg.com/@msgpackr-extract/msgpackr-extract-win32-x64/-/msgpackr-extract-win32-x64-3.0.2.tgz#0f164b726869f71da3c594171df5ebc1c4b0a407" - integrity sha512-O+6Gs8UeDbyFpbSh2CPEz/UOrrdWPTBYNblZK5CxxLisYt4kGX3Sc+czffFonyjiGSq3jWLwJS/CCJc7tBr4sQ== - -"@parcel/bundler-default@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/bundler-default/-/bundler-default-2.10.0.tgz#f5a7be4610fcc62491eae4ae5377537443a3a962" - integrity sha512-pn8McDCuS02/D9jSo9QUTIv3tBQLlJl0PD4FvrndORXLAIFGoQR7jO4lxTSJB/eVBXwqKNVIR7WpB4sjsnBFyg== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/graph" "3.0.0" - "@parcel/plugin" "2.10.0" - "@parcel/rust" "2.10.0" - "@parcel/utils" "2.10.0" - nullthrows "^1.1.1" - -"@parcel/cache@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/cache/-/cache-2.10.0.tgz#c2f2b6fb1933c6fb3c763774da4bd0ea04ec9de0" - integrity sha512-4FzZpMTAAEFE65+O+Cf7f5kLLWRCiA+04IJdDYyQG5YzW1WujKXzrbh8B6tSSlw712dsQ/cUqNW4O0Q3FFKrfw== - dependencies: - "@parcel/fs" "2.10.0" - "@parcel/logger" "2.10.0" - "@parcel/utils" "2.10.0" - lmdb "2.8.5" - -"@parcel/codeframe@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/codeframe/-/codeframe-2.10.0.tgz#03854005a55fb84fa975bc6c335cdc5f61c0519d" - integrity sha512-hHp457tddXEWrOgHHaA/NtkOhOAyt4mpBUzhnPbWDONLu5xeg1mu1Jffiu2rlw5xajhphrUFDWyJW0/xq1815g== - dependencies: - chalk "^4.1.0" - -"@parcel/compressor-raw@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/compressor-raw/-/compressor-raw-2.10.0.tgz#e782c73f1ccc256dffb6d9bd427d206c170e7980" - integrity sha512-TXjosh5+kNN4lxENeIZ/2ZFQKWXpXlOoHhJbW4cGPXBMHxm0eimVpnFpD8xbWxg7VCcWzbEaUTp20GQ153X+9A== - dependencies: - "@parcel/plugin" "2.10.0" - -"@parcel/config-default@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/config-default/-/config-default-2.10.0.tgz#689cd864c69560a42254804c4eabe7fdf5b872d2" - integrity sha512-7Ucd+KNEC08To2NrduC/yIHBN5ayedBoiuI5OVrDeKvyqUnI1S1HRqPF3DsrM8pC2PIdnwJgoOviRXwJemW28A== - dependencies: - "@parcel/bundler-default" "2.10.0" - "@parcel/compressor-raw" "2.10.0" - "@parcel/namer-default" "2.10.0" - "@parcel/optimizer-css" "2.10.0" - "@parcel/optimizer-htmlnano" "2.10.0" - "@parcel/optimizer-image" "2.10.0" - "@parcel/optimizer-svgo" "2.10.0" - "@parcel/optimizer-swc" "2.10.0" - "@parcel/packager-css" "2.10.0" - "@parcel/packager-html" "2.10.0" - "@parcel/packager-js" "2.10.0" - "@parcel/packager-raw" "2.10.0" - "@parcel/packager-svg" "2.10.0" - "@parcel/packager-wasm" "2.10.0" - "@parcel/reporter-dev-server" "2.10.0" - "@parcel/resolver-default" "2.10.0" - "@parcel/runtime-browser-hmr" "2.10.0" - "@parcel/runtime-js" "2.10.0" - "@parcel/runtime-react-refresh" "2.10.0" - "@parcel/runtime-service-worker" "2.10.0" - "@parcel/transformer-babel" "2.10.0" - "@parcel/transformer-css" "2.10.0" - "@parcel/transformer-html" "2.10.0" - "@parcel/transformer-image" "2.10.0" - "@parcel/transformer-js" "2.10.0" - "@parcel/transformer-json" "2.10.0" - "@parcel/transformer-postcss" "2.10.0" - "@parcel/transformer-posthtml" "2.10.0" - "@parcel/transformer-raw" "2.10.0" - "@parcel/transformer-react-refresh-wrap" "2.10.0" - "@parcel/transformer-svg" "2.10.0" - -"@parcel/core@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/core/-/core-2.10.0.tgz#ee262df3d51f64ed3f5a121e16b3d71cf62fe957" - integrity sha512-8jvLhLC2503HIBphJe/C1qL3bfiTSw6WgIDH0e7B8EL0v7v2JYnlTZ8o9myf+bMAxzwNLiZ2uEDCri9EWbi4tQ== - dependencies: - "@mischnic/json-sourcemap" "^0.1.0" - "@parcel/cache" "2.10.0" - "@parcel/diagnostic" "2.10.0" - "@parcel/events" "2.10.0" - "@parcel/fs" "2.10.0" - "@parcel/graph" "3.0.0" - "@parcel/logger" "2.10.0" - "@parcel/package-manager" "2.10.0" - "@parcel/plugin" "2.10.0" - "@parcel/profiler" "2.10.0" - "@parcel/rust" "2.10.0" - "@parcel/source-map" "^2.1.1" - "@parcel/types" "2.10.0" - "@parcel/utils" "2.10.0" - "@parcel/workers" "2.10.0" - abortcontroller-polyfill "^1.1.9" - base-x "^3.0.8" - browserslist "^4.6.6" - clone "^2.1.1" - dotenv "^7.0.0" - dotenv-expand "^5.1.0" - json5 "^2.2.0" - msgpackr "^1.5.4" - nullthrows "^1.1.1" - semver "^7.5.2" - -"@parcel/diagnostic@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/diagnostic/-/diagnostic-2.10.0.tgz#3407c2d8ffbc7e543e7e292493400ed47c8b8faf" - integrity sha512-ibr+sUZLc0MW75b+nThOa6YEi9QXTNYbUNCo067mtMIfhKNYTx24DaiGzDWgy1Yv49eucBaQ4u7gFI2Qa98uIA== - dependencies: - "@mischnic/json-sourcemap" "^0.1.0" - nullthrows "^1.1.1" - -"@parcel/events@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/events/-/events-2.10.0.tgz#4a2c693c7154b4b6a8913d25ed9f9684b10c324b" - integrity sha512-mhykJBnP3BPMI6A9hLZmTtmNHZuE+HGzsF6vzmA2YBuU3/BGlQUmxdObsmwQ1O24eq0EfJVwTM+R/bdu+/nFrA== - -"@parcel/fs@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/fs/-/fs-2.10.0.tgz#f1884249e090f40a623784870da82f5d1008c165" - integrity sha512-so39KdZ4o7tDekeuuQfQdbfTUvldUtzvIsuUtJMqxVOVJRZr9VjieR9GbeFhqRmi9fM5oYdzQn4lbduKdAtANA== - dependencies: - "@parcel/rust" "2.10.0" - "@parcel/types" "2.10.0" - "@parcel/utils" "2.10.0" - "@parcel/watcher" "^2.0.7" - "@parcel/workers" "2.10.0" - -"@parcel/graph@3.0.0": - version "3.0.0" - resolved "https://registry.yarnpkg.com/@parcel/graph/-/graph-3.0.0.tgz#0e7838e196912f011c37564a9fea40772a9d7c64" - integrity sha512-8Lussud6gWRM3Mysu+veBRsBdSlWgkM8y7PvF8AiRwEY2eiVxZ3Rgh8o9KJau3B8R8q+lyCaUElYpbnUT6Bkiw== - dependencies: - nullthrows "^1.1.1" - -"@parcel/logger@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/logger/-/logger-2.10.0.tgz#79fd4bf8b272294dfd0c67323fc7a8cff238685b" - integrity sha512-rDa48czGBZA313scvSEkuHSOQiGdoYLaWqInZBKtl0zke3qrgTFNG4b173H6IFdNq5KmKjafBxaV5jG87i4Gww== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/events" "2.10.0" - -"@parcel/markdown-ansi@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/markdown-ansi/-/markdown-ansi-2.10.0.tgz#fb65d8cdcc21251c7f1e39724948278d1127c406" - integrity sha512-fuOuFglNANegE2nqVURwOJ/HzKM28O0hqy120Gl0NTbCAFbG34WCFxfkmVio8fondD4NcZcDj5GGv5P5TWcTIg== - dependencies: - chalk "^4.1.0" - -"@parcel/namer-default@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/namer-default/-/namer-default-2.10.0.tgz#4be6649b0e5e7acf1f3ede075ef029edeb1ac64a" - integrity sha512-N1IF6A8Y2fYz0BteU9IkhPQGezLA3cKkoSxoIOTiUf2LZPpUIuCGEAB1IgaUVNdAeMVsGw3UrdEYZg4xdMovEg== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/plugin" "2.10.0" - nullthrows "^1.1.1" - -"@parcel/node-resolver-core@3.1.0": - version "3.1.0" - resolved "https://registry.yarnpkg.com/@parcel/node-resolver-core/-/node-resolver-core-3.1.0.tgz#28e83952a8bf39c4529b06bfb59d92cc0a3c2b2f" - integrity sha512-0KBdWIXCpnDzjoZgc1qHhgxtNe5CZ4r4+Iht+LExacXwG1A1O5qKLQE1bBAgcjqkgv1iglVuMx0kVe9G8oob8A== - dependencies: - "@mischnic/json-sourcemap" "^0.1.0" - "@parcel/diagnostic" "2.10.0" - "@parcel/fs" "2.10.0" - "@parcel/rust" "2.10.0" - "@parcel/utils" "2.10.0" - nullthrows "^1.1.1" - semver "^7.5.2" - -"@parcel/optimizer-css@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/optimizer-css/-/optimizer-css-2.10.0.tgz#7502237ed0b3a7086f72102d92864dcf2f679857" - integrity sha512-D7hFYjJpudlbSgMlzwSbSguLehwGe4vJrQ4s83jj7z0UlHd74Vir9fd9LQTPuUErgs2SOQIPxFwLGqR6Hi+mOg== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/plugin" "2.10.0" - "@parcel/source-map" "^2.1.1" - "@parcel/utils" "2.10.0" - browserslist "^4.6.6" - lightningcss "^1.16.1" - nullthrows "^1.1.1" - -"@parcel/optimizer-htmlnano@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/optimizer-htmlnano/-/optimizer-htmlnano-2.10.0.tgz#36f4a34ba59d916f4fb1173538b7c7549bc51188" - integrity sha512-uYmluYpyyVumY7d/aHkGnFVLzOHoGqzVF9os/PkqVOnGEQ3qQibO3Hl9neTtm2GEUgeOfq1lrXLEfpW/k3qG1w== - dependencies: - "@parcel/plugin" "2.10.0" - htmlnano "^2.0.0" - nullthrows "^1.1.1" - posthtml "^0.16.5" - svgo "^2.4.0" - -"@parcel/optimizer-image@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/optimizer-image/-/optimizer-image-2.10.0.tgz#8a08898d1fc591d3bb19ca21fd17f57124b12b49" - integrity sha512-uR/nd3kRxiQuPxB0nP5WLlydTUwRHcpFPAY0iV12cyjCQs+MaZHrhwoDO8kWVaT7jN7WXKYcSIHeP1kvR0HEQw== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/plugin" "2.10.0" - "@parcel/rust" "2.10.0" - "@parcel/utils" "2.10.0" - "@parcel/workers" "2.10.0" - -"@parcel/optimizer-svgo@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/optimizer-svgo/-/optimizer-svgo-2.10.0.tgz#a80782132ea3961725e5ce58affb7f76c1163730" - integrity sha512-2IXClEpjlafidKAiOh/+amdDWOHGtA4Sil/3flmhLkjNFh7z2bGTYodO5xvC3Umw6N11fPNL1Wch1jn54fMO1g== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/plugin" "2.10.0" - "@parcel/utils" "2.10.0" - svgo "^2.4.0" - -"@parcel/optimizer-swc@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/optimizer-swc/-/optimizer-swc-2.10.0.tgz#46d77c5183627291acc297dd33e466abb2aae5bb" - integrity sha512-yq17TG6uyzIbiouK57AngJa6rVwfJ8hPzgc2lqZ9LJxDX07t/5Z+k/+aq4Izy+7kQNR8kH+4asWaMXReSsXmNQ== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/plugin" "2.10.0" - "@parcel/source-map" "^2.1.1" - "@parcel/utils" "2.10.0" - "@swc/core" "^1.3.36" - nullthrows "^1.1.1" - -"@parcel/package-manager@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/package-manager/-/package-manager-2.10.0.tgz#be4170f832ab61dd3963de483c951baac0a8033f" - integrity sha512-BBUhwgX2Rz92SqGCyYp5Du4UEzm/bjrSSoeLtuRRevWKTVXhgHGbqcAlZmICoxb1lZGpn8x+pEivWd3w+5M7iA== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/fs" "2.10.0" - "@parcel/logger" "2.10.0" - "@parcel/node-resolver-core" "3.1.0" - "@parcel/types" "2.10.0" - "@parcel/utils" "2.10.0" - "@parcel/workers" "2.10.0" - semver "^7.5.2" - -"@parcel/packager-css@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/packager-css/-/packager-css-2.10.0.tgz#212cb2b96084304e9597f4a07278dc9e4b9e65de" - integrity sha512-BY1PoPPOngiJ6gFD+mUQ6YZvwDxlth8oCU9328T8kFwhmA4qL6pfIxNPI1I53Ig5f38tf1nhFkHACDCbs4MxaQ== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/plugin" "2.10.0" - "@parcel/source-map" "^2.1.1" - "@parcel/utils" "2.10.0" - nullthrows "^1.1.1" - -"@parcel/packager-html@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/packager-html/-/packager-html-2.10.0.tgz#2faebaa136e498fce605300a284d7078f95bda5e" - integrity sha512-EtxQwuQXQ6zrPRG9/pIdIcvuDCzBEsAnjN9kZ+XuxEYGoReX7weN4oALA6gCnw3w7U4cq6+VR1R08F6Cd8T2MQ== - dependencies: - "@parcel/plugin" "2.10.0" - "@parcel/types" "2.10.0" - "@parcel/utils" "2.10.0" - nullthrows "^1.1.1" - posthtml "^0.16.5" - -"@parcel/packager-js@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/packager-js/-/packager-js-2.10.0.tgz#3f47411a3780090941cb0bec7525d019987105d8" - integrity sha512-9r1pv8GScZzgGempexikym9d1aehTAp0DxK71LUxBT0os9Br+nJOtV4wmJWnHapt4r108d75DcgtytdVM5nuqA== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/plugin" "2.10.0" - "@parcel/rust" "2.10.0" - "@parcel/source-map" "^2.1.1" - "@parcel/types" "2.10.0" - "@parcel/utils" "2.10.0" - globals "^13.2.0" - nullthrows "^1.1.1" - -"@parcel/packager-raw@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/packager-raw/-/packager-raw-2.10.0.tgz#ad3e83c50517a050d47bea97db3104c7ea6bf5cd" - integrity sha512-fk1XGqMP38uyWC1Jqg8/Mp1x0dLxfd9GnmLHQCUZ0OSQLwF9Nqpow1WR4tC8juxYNK5haGqKyL9X5pVN4KLNYQ== - dependencies: - "@parcel/plugin" "2.10.0" - -"@parcel/packager-svg@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/packager-svg/-/packager-svg-2.10.0.tgz#2f4416c91b15b94149b6cdd495ebe0c87053ede8" - integrity sha512-+vXXZwENinz/N2m04tH5BDSc8Zv7XNd/fsXZ3BAcEWmYpiTHBYMgbIy+fsdQb1tpFwku7CezthHFDsXejyNtrg== - dependencies: - "@parcel/plugin" "2.10.0" - "@parcel/types" "2.10.0" - "@parcel/utils" "2.10.0" - posthtml "^0.16.4" - -"@parcel/packager-wasm@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/packager-wasm/-/packager-wasm-2.10.0.tgz#d09059cabb42ebf50eecd363db0b7472ba41d04b" - integrity sha512-G/OsV9Xpyu1D/mTwazw4FkWlFotcFMaRmejmc6km3+qjaFxMubRBLCNMCvGw2lDIhA40qz/DpZS/kblB/FGSPA== - dependencies: - "@parcel/plugin" "2.10.0" - -"@parcel/plugin@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/plugin/-/plugin-2.10.0.tgz#03a963f713fa76d76469955e3a693e7c3b607138" - integrity sha512-FaWchkYJxLOohNNb3ah9R/9gckew+iGOzcGZ1bUtLGc/Dwz1mTVeaAanqOjlZ6C5FCe9lMctkH7h0eQsJ0mlVQ== - dependencies: - "@parcel/types" "2.10.0" - -"@parcel/profiler@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/profiler/-/profiler-2.10.0.tgz#839084002fa4323e71f65de604f7863e43a59524" - integrity sha512-SGkslseYA5TQOb8Z7gepi7YiIv3uH4BYAM9nwduMZrRZENcICbgTh1Pb+dp10y+6k9hFFH748eHtxJqSWARDBw== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/events" "2.10.0" - chrome-trace-event "^1.0.2" - -"@parcel/reporter-cli@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/reporter-cli/-/reporter-cli-2.10.0.tgz#3c26779362a296c3e1bad91986c0907687376fef" - integrity sha512-+OtZUdmHFgNY8+w3/U7dEZKMTtIFh7EiFw5VelKIGdvJrZNa9j7vbFuZziK6zUW2uopCk4qsDinn6Rfi7M16KA== - dependencies: - "@parcel/plugin" "2.10.0" - "@parcel/types" "2.10.0" - "@parcel/utils" "2.10.0" - chalk "^4.1.0" - term-size "^2.2.1" - -"@parcel/reporter-dev-server@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/reporter-dev-server/-/reporter-dev-server-2.10.0.tgz#428b4784773c05c9ccd9a5849ce2f15d812165d7" - integrity sha512-1dMkVgbfx+AxRVjzX5on3LOY8Vhsr4wuwQdLhmN1kAveTNWUYBPSVzIt5ZPVj3Cmpwpaonj7tHkZ2YujaNWHQg== - dependencies: - "@parcel/plugin" "2.10.0" - "@parcel/utils" "2.10.0" - -"@parcel/reporter-tracer@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/reporter-tracer/-/reporter-tracer-2.10.0.tgz#9650d2a04e0c78c516fca59ec75e9ab895b07504" - integrity sha512-mlxF3ozH6Kys4hewG1Bze1q8wHJL1ue276Qek9xPJly8ed08wU7rPGZF0vz8fJfKT8vx+nGvnKFXYiHjF+w6bg== - dependencies: - "@parcel/plugin" "2.10.0" - "@parcel/utils" "2.10.0" - chrome-trace-event "^1.0.3" - nullthrows "^1.1.1" - -"@parcel/resolver-default@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/resolver-default/-/resolver-default-2.10.0.tgz#47a55bf6d7552cf765b54fcd52a3e024a7037da6" - integrity sha512-KWtKrmjf/CAyZkk+SSwHhMMwN6cjJJRtUSLCvwbrlevd0onRl3erUdVYrJrNB5X+N8ylCO6Vb0wCyMegOo/OwQ== - dependencies: - "@parcel/node-resolver-core" "3.1.0" - "@parcel/plugin" "2.10.0" - -"@parcel/runtime-browser-hmr@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/runtime-browser-hmr/-/runtime-browser-hmr-2.10.0.tgz#dccfcef66af867100c3ad7b155aeaf7363df64e2" - integrity sha512-x22HHUAFuhycE/NGowkEaR7zeZsp8PcViHkmuNkSvLboe8PJvq4BFpnd+RUj+o8EjN31p+8K2pFqS1hYAmtdwg== - dependencies: - "@parcel/plugin" "2.10.0" - "@parcel/utils" "2.10.0" - -"@parcel/runtime-js@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/runtime-js/-/runtime-js-2.10.0.tgz#3c1cb3b5e8b3e6b6015e1b67a7b5d493eb3756e5" - integrity sha512-AyDY+tQ9jiip6YsDGbaw7Azj60qG4fWNniUMIRMsywKQZOySLpfMNGHUcwDkV8j1NTve87Cwr2EzMOMnQHaUsQ== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/plugin" "2.10.0" - "@parcel/utils" "2.10.0" - nullthrows "^1.1.1" - -"@parcel/runtime-react-refresh@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/runtime-react-refresh/-/runtime-react-refresh-2.10.0.tgz#4b11085f5a69065de796e1cff239237ff78a55ad" - integrity sha512-hmiK9i6iitdjfcCaI0888+pecQHA0dzf6wMKnwtJsYQxCv2TrwXPsSOMHjkKr1K3ALXi8vlauG4K0Rm7c+vfdw== - dependencies: - "@parcel/plugin" "2.10.0" - "@parcel/utils" "2.10.0" - react-error-overlay "6.0.9" - react-refresh "^0.9.0" - -"@parcel/runtime-service-worker@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/runtime-service-worker/-/runtime-service-worker-2.10.0.tgz#6c10e3b24a3d5d4d565439547d8eb50acf2aae05" - integrity sha512-vi84PwAsyPI1P/5FTt1uNKjH1NGizQRdS4CmjBMz+VBT6GVuXMgZ9iQy3OYC8MsiyHlyG7mScftI74RWqw1DDg== - dependencies: - "@parcel/plugin" "2.10.0" - "@parcel/utils" "2.10.0" - nullthrows "^1.1.1" - -"@parcel/rust@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/rust/-/rust-2.10.0.tgz#fc930715a3200bb05a58007fc11cb29f444382c9" - integrity sha512-9J7riqPI8mVlFSDphK9kVUH8nFQgeMbO/95Ycf4vaEOVE1ICQo1h18WHAy2DndmL1uSd/UTimirrP6yLt/I3KA== - -"@parcel/source-map@^2.1.1": - version "2.1.1" - resolved "https://registry.yarnpkg.com/@parcel/source-map/-/source-map-2.1.1.tgz#fb193b82dba6dd62cc7a76b326f57bb35000a782" - integrity sha512-Ejx1P/mj+kMjQb8/y5XxDUn4reGdr+WyKYloBljpppUy8gs42T+BNoEOuRYqDVdgPc6NxduzIDoJS9pOFfV5Ew== - dependencies: - detect-libc "^1.0.3" - -"@parcel/transformer-babel@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/transformer-babel/-/transformer-babel-2.10.0.tgz#328573dd90948f3ec04646731e523cab9cde3b4e" - integrity sha512-XwlzHt7WPfueFlwl/bXItopgZ6ILSPzl5OmPeytHrM2TanymeLjJ1y3vxwY1C1BhNlrTwPHcf9U8aiuVSpE8RQ== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/plugin" "2.10.0" - "@parcel/source-map" "^2.1.1" - "@parcel/utils" "2.10.0" - browserslist "^4.6.6" - json5 "^2.2.0" - nullthrows "^1.1.1" - semver "^7.5.2" - -"@parcel/transformer-css@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/transformer-css/-/transformer-css-2.10.0.tgz#f23b2ffd901a02b189571d6ead752b7c1f3ec871" - integrity sha512-hITticpUE/qilpsTc7HQP04qhXwyUSKGZKgcFnvf8+BJO/LoclbVK1nzbR61eYl5Jhj1XB67p3tCt5fSvPhOsQ== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/plugin" "2.10.0" - "@parcel/source-map" "^2.1.1" - "@parcel/utils" "2.10.0" - browserslist "^4.6.6" - lightningcss "^1.16.1" - nullthrows "^1.1.1" - -"@parcel/transformer-html@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/transformer-html/-/transformer-html-2.10.0.tgz#de4d95c2124656b226620a49b7ea264c2cf19239" - integrity sha512-rc8YKjB+bE7yGHOf674CSzW8ii+m5caBo4akdRIUdhEHJS4FnSwxYIZlMcfV9pZM4Tj5PFMZyrlAHad6YrO8aA== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/plugin" "2.10.0" - "@parcel/rust" "2.10.0" - nullthrows "^1.1.1" - posthtml "^0.16.5" - posthtml-parser "^0.10.1" - posthtml-render "^3.0.0" - semver "^7.5.2" - srcset "4" - -"@parcel/transformer-image@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/transformer-image/-/transformer-image-2.10.0.tgz#d7502a8139aea0997d00982151115e0dde422e58" - integrity sha512-qbNyAJvzqdO/OnHhCOoPAZN5aBD/xphyXvDNI0Fb3UPEr5MQtAnzv2lS1I63s4rKpphBntWj7nEIAio6s7c5bw== - dependencies: - "@parcel/plugin" "2.10.0" - "@parcel/utils" "2.10.0" - "@parcel/workers" "2.10.0" - nullthrows "^1.1.1" - -"@parcel/transformer-js@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/transformer-js/-/transformer-js-2.10.0.tgz#142a70b77466e5359774d21939da06d5f579bb5e" - integrity sha512-39ZNnje8dlmME1ipjFyAFHyhHaGCwZZpXYN9SCTl/+AnjZLamnmVFkesgBbrRSBRQixRG1VwCvrWsjLLeLkTUg== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/plugin" "2.10.0" - "@parcel/rust" "2.10.0" - "@parcel/source-map" "^2.1.1" - "@parcel/utils" "2.10.0" - "@parcel/workers" "2.10.0" - "@swc/helpers" "^0.5.0" - browserslist "^4.6.6" - nullthrows "^1.1.1" - regenerator-runtime "^0.13.7" - semver "^7.5.2" - -"@parcel/transformer-json@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/transformer-json/-/transformer-json-2.10.0.tgz#77a684a2e631c3058fd8d70d4b05aaf704a6b928" - integrity sha512-4G6ZIt7IYu1l3BlsL55Hi3869X6KHE0CHybWf364h5ZUmzo3Xpc5i7cziQX+IhWDo1qn1jiziOPGY85LXlo8ug== - dependencies: - "@parcel/plugin" "2.10.0" - json5 "^2.2.0" - -"@parcel/transformer-postcss@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/transformer-postcss/-/transformer-postcss-2.10.0.tgz#b38a4892e14cf82a5324a01ff2d063207b1a383e" - integrity sha512-Xhz+MHr9Q31d3u3hsBOtmFGEQx7FsNbTumGpqIqaGkDDq4IIMKbEwyrpkmf7/02kyxcbwr6uaBqnMHm55j10sQ== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/plugin" "2.10.0" - "@parcel/rust" "2.10.0" - "@parcel/utils" "2.10.0" - clone "^2.1.1" - nullthrows "^1.1.1" - postcss-value-parser "^4.2.0" - semver "^7.5.2" - -"@parcel/transformer-posthtml@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/transformer-posthtml/-/transformer-posthtml-2.10.0.tgz#accca3feb46c367182a6ea56148e8b83e41733a2" - integrity sha512-kmz8Yip5hh2y3bfA76mC2QtI9VHdS7k5dV96/yjar0CkLHJnr33Jh7MTfuCN+01nVU20Tn3YMqEMQ/ErPVJwlg== - dependencies: - "@parcel/plugin" "2.10.0" - "@parcel/utils" "2.10.0" - nullthrows "^1.1.1" - posthtml "^0.16.5" - posthtml-parser "^0.10.1" - posthtml-render "^3.0.0" - semver "^7.5.2" - -"@parcel/transformer-raw@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/transformer-raw/-/transformer-raw-2.10.0.tgz#4e8fa1bdffca28bc7653cdbe49ab3ca464875399" - integrity sha512-1tR58kqzTh4baLq/++bp84H2lhOoAz8cJeJykgsYImva7aRWcjlTppNKjBF6Ef8etIRMPZOozTdbS53VdQ9IbA== - dependencies: - "@parcel/plugin" "2.10.0" - -"@parcel/transformer-react-refresh-wrap@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/transformer-react-refresh-wrap/-/transformer-react-refresh-wrap-2.10.0.tgz#3cf47430a31ec2402eba87fc0db8b18f8beb89e3" - integrity sha512-4ab1tiwUA2XznTh/eb/IVKEA+Ynkbqc5sgNuobf1MLKF82FXTUT5szVshff/ODpwublvVBD3YbXlapxV5xyFvA== - dependencies: - "@parcel/plugin" "2.10.0" - "@parcel/utils" "2.10.0" - react-refresh "^0.9.0" - -"@parcel/transformer-svg@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/transformer-svg/-/transformer-svg-2.10.0.tgz#3277d04f8b1d5ebf9bf7259da25fc0ee491e7dab" - integrity sha512-qEZFk4gxyVNhm2V8R3YLo9qCyYNVBySWmZLjmwuhLLmAE+r0qGebc9oXyo7C6ML5d/4Tfj6NriCOeX+HMhPVxw== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/plugin" "2.10.0" - "@parcel/rust" "2.10.0" - nullthrows "^1.1.1" - posthtml "^0.16.5" - posthtml-parser "^0.10.1" - posthtml-render "^3.0.0" - semver "^7.5.2" - -"@parcel/types@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/types/-/types-2.10.0.tgz#033f35dccb95c940847a8fb5f525a0494d07106b" - integrity sha512-iDFVvgN+jK02GY++V+WY3WuNTM6CGDPToGfL31/Sgf6/1PzT7kL6uXJ6+859u8wkTIrtkWD2XyTNkKJJ8jPwgg== - dependencies: - "@parcel/cache" "2.10.0" - "@parcel/diagnostic" "2.10.0" - "@parcel/fs" "2.10.0" - "@parcel/package-manager" "2.10.0" - "@parcel/source-map" "^2.1.1" - "@parcel/workers" "2.10.0" - utility-types "^3.10.0" - -"@parcel/utils@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/utils/-/utils-2.10.0.tgz#5764e53200cefb8fc1055638e49d746c40fba5ef" - integrity sha512-8qx9caJTjli6UKpKlcPjdSBblkwTc+BnIsSK3/7fX7kbtHLmEkQH/RWZbbOJItHbnzlsmaDJTfS7j6rrcFw2Pw== - dependencies: - "@parcel/codeframe" "2.10.0" - "@parcel/diagnostic" "2.10.0" - "@parcel/logger" "2.10.0" - "@parcel/markdown-ansi" "2.10.0" - "@parcel/rust" "2.10.0" - "@parcel/source-map" "^2.1.1" - chalk "^4.1.0" - nullthrows "^1.1.1" - -"@parcel/watcher@^2.0.7": - version "2.1.0" - resolved "https://registry.yarnpkg.com/@parcel/watcher/-/watcher-2.1.0.tgz#5f32969362db4893922c526a842d8af7a8538545" - integrity sha512-8s8yYjd19pDSsBpbkOHnT6Z2+UJSuLQx61pCFM0s5wSRvKCEMDjd/cHY3/GI1szHIWbpXpsJdg3V6ISGGx9xDw== - dependencies: - is-glob "^4.0.3" - micromatch "^4.0.5" - node-addon-api "^3.2.1" - node-gyp-build "^4.3.0" - -"@parcel/workers@2.10.0": - version "2.10.0" - resolved "https://registry.yarnpkg.com/@parcel/workers/-/workers-2.10.0.tgz#90fdbe37e3522d11b56d38ef50611f1547c31e94" - integrity sha512-PILDag4aW7G9w2AvYvBsMHe/NRCoOt+L7HJzp6UIvy6ssbafH/8fzdGjSpA99GXzC5AXpAHVt8RXhGMXmMP6QA== - dependencies: - "@parcel/diagnostic" "2.10.0" - "@parcel/logger" "2.10.0" - "@parcel/profiler" "2.10.0" - "@parcel/types" "2.10.0" - "@parcel/utils" "2.10.0" - nullthrows "^1.1.1" - -"@swc/core-darwin-arm64@1.3.93": - version "1.3.93" - resolved "https://registry.yarnpkg.com/@swc/core-darwin-arm64/-/core-darwin-arm64-1.3.93.tgz#aefd94625451988286bebccb1c072bae0a36bcdb" - integrity sha512-gEKgk7FVIgltnIfDO6GntyuQBBlAYg5imHpRgLxB1zSI27ijVVkksc6QwISzFZAhKYaBWIsFSVeL9AYSziAF7A== - -"@swc/core-darwin-x64@1.3.93": - version "1.3.93" - resolved "https://registry.yarnpkg.com/@swc/core-darwin-x64/-/core-darwin-x64-1.3.93.tgz#18409c6effdf508ddf1ebccfa77d35aaa6cd72f0" - integrity sha512-ZQPxm/fXdDQtn3yrYSL/gFfA8OfZ5jTi33yFQq6vcg/Y8talpZ+MgdSlYM0FkLrZdMTYYTNFiuBQuuvkA+av+Q== - -"@swc/core-linux-arm-gnueabihf@1.3.93": - version "1.3.93" - resolved "https://registry.yarnpkg.com/@swc/core-linux-arm-gnueabihf/-/core-linux-arm-gnueabihf-1.3.93.tgz#23a97bc94a8b2f23fb6cc4bc9d8936899e5eeff5" - integrity sha512-OYFMMI2yV+aNe3wMgYhODxHdqUB/jrK0SEMHHS44GZpk8MuBXEF+Mcz4qjkY5Q1EH7KVQqXb/gVWwdgTHpjM2A== - -"@swc/core-linux-arm64-gnu@1.3.93": - version "1.3.93" - resolved "https://registry.yarnpkg.com/@swc/core-linux-arm64-gnu/-/core-linux-arm64-gnu-1.3.93.tgz#7a17406a7cf76a959a617626d5ee2634ae9afa26" - integrity sha512-BT4dT78odKnJMNiq5HdjBsv29CiIdcCcImAPxeFqAeFw1LL6gh9nzI8E96oWc+0lVT5lfhoesCk4Qm7J6bty8w== - -"@swc/core-linux-arm64-musl@1.3.93": - version "1.3.93" - resolved "https://registry.yarnpkg.com/@swc/core-linux-arm64-musl/-/core-linux-arm64-musl-1.3.93.tgz#a30be7780090afefd3b8706398418cbe1d23db49" - integrity sha512-yH5fWEl1bktouC0mhh0Chuxp7HEO4uCtS/ly1Vmf18gs6wZ8DOOkgAEVv2dNKIryy+Na++ljx4Ym7C8tSJTrLw== - -"@swc/core-linux-x64-gnu@1.3.93": - version "1.3.93" - resolved "https://registry.yarnpkg.com/@swc/core-linux-x64-gnu/-/core-linux-x64-gnu-1.3.93.tgz#41e903fd82e059952d16051b442cbe65ee5b8cb3" - integrity sha512-OFUdx64qvrGJhXKEyxosHxgoUVgba2ztYh7BnMiU5hP8lbI8G13W40J0SN3CmFQwPP30+3oEbW7LWzhKEaYjlg== - -"@swc/core-linux-x64-musl@1.3.93": - version "1.3.93" - resolved "https://registry.yarnpkg.com/@swc/core-linux-x64-musl/-/core-linux-x64-musl-1.3.93.tgz#0866807545c44eac9b3254b374310ad5e1c573f9" - integrity sha512-4B8lSRwEq1XYm6xhxHhvHmKAS7pUp1Q7E33NQ2TlmFhfKvCOh86qvThcjAOo57x8DRwmpvEVrqvpXtYagMN6Ig== - -"@swc/core-win32-arm64-msvc@1.3.93": - version "1.3.93" - resolved "https://registry.yarnpkg.com/@swc/core-win32-arm64-msvc/-/core-win32-arm64-msvc-1.3.93.tgz#c72411dea2fd4f62a832f71a6e15424d849e7610" - integrity sha512-BHShlxtkven8ZjjvZ5QR6sC5fZCJ9bMujEkiha6W4cBUTY7ce7qGFyHmQd+iPC85d9kD/0cCiX/Xez8u0BhO7w== - -"@swc/core-win32-ia32-msvc@1.3.93": - version "1.3.93" - resolved "https://registry.yarnpkg.com/@swc/core-win32-ia32-msvc/-/core-win32-ia32-msvc-1.3.93.tgz#05c2b031b976af4ef81f5073ee114254678a5d5d" - integrity sha512-nEwNWnz4JzYAK6asVvb92yeylfxMYih7eMQOnT7ZVlZN5ba9WF29xJ6kcQKs9HRH6MvWhz9+wRgv3FcjlU6HYA== - -"@swc/core-win32-x64-msvc@1.3.93": - version "1.3.93" - resolved "https://registry.yarnpkg.com/@swc/core-win32-x64-msvc/-/core-win32-x64-msvc-1.3.93.tgz#f8748b3fd1879f13084b1b0814edf328c662935c" - integrity sha512-jibQ0zUr4kwJaQVwgmH+svS04bYTPnPw/ZkNInzxS+wFAtzINBYcU8s2PMWbDb2NGYiRSEeoSGyAvS9H+24JFA== - -"@swc/core@^1.3.36": - version "1.3.93" - resolved "https://registry.yarnpkg.com/@swc/core/-/core-1.3.93.tgz#be4282aa44deffb0e5081a2613bac00335600630" - integrity sha512-690GRr1wUGmGYZHk7fUduX/JUwViMF2o74mnZYIWEcJaCcd9MQfkhsxPBtjeg6tF+h266/Cf3RPYhsFBzzxXcA== - dependencies: - "@swc/counter" "^0.1.1" - "@swc/types" "^0.1.5" - optionalDependencies: - "@swc/core-darwin-arm64" "1.3.93" - "@swc/core-darwin-x64" "1.3.93" - "@swc/core-linux-arm-gnueabihf" "1.3.93" - "@swc/core-linux-arm64-gnu" "1.3.93" - "@swc/core-linux-arm64-musl" "1.3.93" - "@swc/core-linux-x64-gnu" "1.3.93" - "@swc/core-linux-x64-musl" "1.3.93" - "@swc/core-win32-arm64-msvc" "1.3.93" - "@swc/core-win32-ia32-msvc" "1.3.93" - "@swc/core-win32-x64-msvc" "1.3.93" - -"@swc/counter@^0.1.1": - version "0.1.2" - resolved "https://registry.yarnpkg.com/@swc/counter/-/counter-0.1.2.tgz#bf06d0770e47c6f1102270b744e17b934586985e" - integrity sha512-9F4ys4C74eSTEUNndnER3VJ15oru2NumfQxS8geE+f3eB5xvfxpWyqE5XlVnxb/R14uoXi6SLbBwwiDSkv+XEw== - -"@swc/helpers@^0.5.0": - version "0.5.3" - resolved "https://registry.yarnpkg.com/@swc/helpers/-/helpers-0.5.3.tgz#98c6da1e196f5f08f977658b80d6bd941b5f294f" - integrity sha512-FaruWX6KdudYloq1AHD/4nU+UsMTdNE8CKyrseXWEcgjDAbvkwJg2QGPAnfIJLIWsjZOSPLOAykK6fuYp4vp4A== - dependencies: - tslib "^2.4.0" - -"@swc/types@^0.1.5": - version "0.1.5" - resolved "https://registry.yarnpkg.com/@swc/types/-/types-0.1.5.tgz#043b731d4f56a79b4897a3de1af35e75d56bc63a" - integrity sha512-myfUej5naTBWnqOCc/MdVOLVjXUXtIA+NpDrDBKJtLLg2shUjBu3cZmB/85RyitKc55+lUUyl7oRfLOvkr2hsw== - -"@trysound/sax@0.2.0": - version "0.2.0" - resolved "https://registry.yarnpkg.com/@trysound/sax/-/sax-0.2.0.tgz#cccaab758af56761eb7bf37af6f03f326dd798ad" - integrity sha512-L7z9BgrNEcYyUYtF+HaEfiS5ebkh9jXqbszz7pC0hRBPaatV0XjSD3+eHrpqFemQfgwiFF0QPIarnIihIDn7OA== - -"@tsconfig/node10@^1.0.7": - version "1.0.9" - resolved "https://registry.yarnpkg.com/@tsconfig/node10/-/node10-1.0.9.tgz#df4907fc07a886922637b15e02d4cebc4c0021b2" - integrity sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA== - -"@tsconfig/node12@^1.0.7": - version "1.0.11" - resolved "https://registry.yarnpkg.com/@tsconfig/node12/-/node12-1.0.11.tgz#ee3def1f27d9ed66dac6e46a295cffb0152e058d" - integrity sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag== - -"@tsconfig/node14@^1.0.0": - version "1.0.3" - resolved "https://registry.yarnpkg.com/@tsconfig/node14/-/node14-1.0.3.tgz#e4386316284f00b98435bf40f72f75a09dabf6c1" - integrity sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow== - -"@tsconfig/node16@^1.0.2": - version "1.0.3" - resolved "https://registry.yarnpkg.com/@tsconfig/node16/-/node16-1.0.3.tgz#472eaab5f15c1ffdd7f8628bd4c4f753995ec79e" - integrity sha512-yOlFc+7UtL/89t2ZhjPvvB/DeAr3r+Dq58IgzsFkOAvVC6NMJXmCGjbptdXdR9qsX7pKcTL+s87FtYREi2dEEQ== - -"@types/node@20.8.7": - version "20.8.7" - resolved "https://registry.yarnpkg.com/@types/node/-/node-20.8.7.tgz#ad23827850843de973096edfc5abc9e922492a25" - integrity sha512-21TKHHh3eUHIi2MloeptJWALuCu5H7HQTdTrWIFReA8ad+aggoX+lRes3ex7/FtpC+sVUpFMQ+QTfYr74mruiQ== - dependencies: - undici-types "~5.25.1" - -"@types/parse-json@^4.0.0": - version "4.0.0" - resolved "https://registry.yarnpkg.com/@types/parse-json/-/parse-json-4.0.0.tgz#2f8bb441434d163b35fb8ffdccd7138927ffb8c0" - integrity sha512-//oorEZjL6sbPcKUaCdIGlIUeH26mgzimjBB77G6XRgnDl/L5wOnpyBGRe/Mmf5CVW3PwEBE1NjiMZ/ssFh4wA== - -"@typescript/vfs@1.5.0": - version "1.5.0" - resolved "https://registry.yarnpkg.com/@typescript/vfs/-/vfs-1.5.0.tgz#ed942922724f9ace8c07c80b006c47e5e3833218" - integrity sha512-AJS307bPgbsZZ9ggCT3wwpg3VbTKMFNHfaY/uF0ahSkYYrPF2dSSKDNIDIQAHm9qJqbLvCsSJH7yN4Vs/CsMMg== - dependencies: - debug "^4.1.1" - -abortcontroller-polyfill@^1.1.9: - version "1.7.5" - resolved "https://registry.yarnpkg.com/abortcontroller-polyfill/-/abortcontroller-polyfill-1.7.5.tgz#6738495f4e901fbb57b6c0611d0c75f76c485bed" - integrity sha512-JMJ5soJWP18htbbxJjG7bG6yuI6pRhgJ0scHHTfkUjf6wjP912xZWvM+A4sJK3gqd9E8fcPbDnOefbA9Th/FIQ== - -acorn-walk@^8.1.1: - version "8.2.0" - resolved "https://registry.yarnpkg.com/acorn-walk/-/acorn-walk-8.2.0.tgz#741210f2e2426454508853a2f44d0ab83b7f69c1" - integrity sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA== - -acorn@^8.4.1: - version "8.8.2" - resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.8.2.tgz#1b2f25db02af965399b9776b0c2c391276d37c4a" - integrity sha512-xjIYgE8HBrkpd/sJqOGNspf8uHG+NOHGOw6a/Urj8taM2EXfdNAH2oFcPeIFfsv3+kz/mJrS5VuMqbNLjCa2vw== - -ansi-styles@^3.2.1: - version "3.2.1" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-3.2.1.tgz#41fbb20243e50b12be0f04b8dedbf07520ce841d" - integrity sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA== - dependencies: - color-convert "^1.9.0" - -ansi-styles@^4.1.0: - version "4.3.0" - resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937" - integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg== - dependencies: - color-convert "^2.0.1" - -arg@^4.1.0: - version "4.1.3" - resolved "https://registry.yarnpkg.com/arg/-/arg-4.1.3.tgz#269fc7ad5b8e42cb63c896d5666017261c144089" - integrity sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA== - -base-x@^3.0.8: - version "3.0.9" - resolved "https://registry.yarnpkg.com/base-x/-/base-x-3.0.9.tgz#6349aaabb58526332de9f60995e548a53fe21320" - integrity sha512-H7JU6iBHTal1gp56aKoaa//YUxEaAOUiydvrV/pILqIHXTtqxSkATOnDA2u+jZ/61sD+L/412+7kzXRtWukhpQ== - dependencies: - safe-buffer "^5.0.1" - -boolbase@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/boolbase/-/boolbase-1.0.0.tgz#68dff5fbe60c51eb37725ea9e3ed310dcc1e776e" - integrity sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww== - -braces@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107" - integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A== - dependencies: - fill-range "^7.0.1" - -browserslist@^4.6.6: - version "4.21.5" - resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.21.5.tgz#75c5dae60063ee641f977e00edd3cfb2fb7af6a7" - integrity sha512-tUkiguQGW7S3IhB7N+c2MV/HZPSCPAAiYBZXLsBhFB/PCy6ZKKsZrmBayHV9fdGV/ARIfJ14NkxKzRDjvp7L6w== - dependencies: - caniuse-lite "^1.0.30001449" - electron-to-chromium "^1.4.284" - node-releases "^2.0.8" - update-browserslist-db "^1.0.10" - -callsites@^3.0.0: - version "3.1.0" - resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73" - integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ== - -caniuse-lite@^1.0.30001449: - version "1.0.30001474" - resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001474.tgz#13b6fe301a831fe666cce8ca4ef89352334133d5" - integrity sha512-iaIZ8gVrWfemh5DG3T9/YqarVZoYf0r188IjaGwx68j4Pf0SGY6CQkmJUIE+NZHkkecQGohzXmBGEwWDr9aM3Q== - -chalk@^2.0.0: - version "2.4.2" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-2.4.2.tgz#cd42541677a54333cf541a49108c1432b44c9424" - integrity sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ== - dependencies: - ansi-styles "^3.2.1" - escape-string-regexp "^1.0.5" - supports-color "^5.3.0" - -chalk@^4.1.0: - version "4.1.2" - resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01" - integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA== - dependencies: - ansi-styles "^4.1.0" - supports-color "^7.1.0" - -chrome-trace-event@^1.0.2, chrome-trace-event@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/chrome-trace-event/-/chrome-trace-event-1.0.3.tgz#1015eced4741e15d06664a957dbbf50d041e26ac" - integrity sha512-p3KULyQg4S7NIHixdwbGX+nFHkoBiA4YQmyWtjb8XngSKV124nJmRysgAeujbUVb15vh+RvFUfCPqU7rXk+hZg== - -clone@^2.1.1: - version "2.1.2" - resolved "https://registry.yarnpkg.com/clone/-/clone-2.1.2.tgz#1b7f4b9f591f1e8f83670401600345a02887435f" - integrity sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w== - -color-convert@^1.9.0: - version "1.9.3" - resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-1.9.3.tgz#bb71850690e1f136567de629d2d5471deda4c1e8" - integrity sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg== - dependencies: - color-name "1.1.3" - -color-convert@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" - integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== - dependencies: - color-name "~1.1.4" - -color-name@1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.3.tgz#a7d0558bd89c42f795dd42328f740831ca53bc25" - integrity sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw== - -color-name@~1.1.4: - version "1.1.4" - resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" - integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== - -commander@^7.0.0, commander@^7.2.0: - version "7.2.0" - resolved "https://registry.yarnpkg.com/commander/-/commander-7.2.0.tgz#a36cb57d0b501ce108e4d20559a150a391d97ab7" - integrity sha512-QrWXB+ZQSVPmIWIhtEO9H+gwHaMGYiF5ChvoJ+K9ZGHG/sVsa6yiesAD1GC/x46sET00Xlwo1u49RVVVzvcSkw== - -cosmiconfig@^7.0.1: - version "7.1.0" - resolved "https://registry.yarnpkg.com/cosmiconfig/-/cosmiconfig-7.1.0.tgz#1443b9afa596b670082ea46cbd8f6a62b84635f6" - integrity sha512-AdmX6xUzdNASswsFtmwSt7Vj8po9IuqXm0UXz7QKPuEUmPB4XyjGfaAr2PSuELMwkRMVH1EpIkX5bTZGRB3eCA== - dependencies: - "@types/parse-json" "^4.0.0" - import-fresh "^3.2.1" - parse-json "^5.0.0" - path-type "^4.0.0" - yaml "^1.10.0" - -create-require@^1.1.0: - version "1.1.1" - resolved "https://registry.yarnpkg.com/create-require/-/create-require-1.1.1.tgz#c1d7e8f1e5f6cfc9ff65f9cd352d37348756c333" - integrity sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ== - -css-select@^4.1.3: - version "4.3.0" - resolved "https://registry.yarnpkg.com/css-select/-/css-select-4.3.0.tgz#db7129b2846662fd8628cfc496abb2b59e41529b" - integrity sha512-wPpOYtnsVontu2mODhA19JrqWxNsfdatRKd64kmpRbQgh1KtItko5sTnEpPdpSaJszTOhEMlF/RPz28qj4HqhQ== - dependencies: - boolbase "^1.0.0" - css-what "^6.0.1" - domhandler "^4.3.1" - domutils "^2.8.0" - nth-check "^2.0.1" - -css-tree@^1.1.2, css-tree@^1.1.3: - version "1.1.3" - resolved "https://registry.yarnpkg.com/css-tree/-/css-tree-1.1.3.tgz#eb4870fb6fd7707327ec95c2ff2ab09b5e8db91d" - integrity sha512-tRpdppF7TRazZrjJ6v3stzv93qxRcSsFmW6cX0Zm2NVKpxE1WV1HblnghVv9TreireHkqI/VDEsfolRF1p6y7Q== - dependencies: - mdn-data "2.0.14" - source-map "^0.6.1" - -css-what@^6.0.1: - version "6.1.0" - resolved "https://registry.yarnpkg.com/css-what/-/css-what-6.1.0.tgz#fb5effcf76f1ddea2c81bdfaa4de44e79bac70f4" - integrity sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw== - -csso@^4.2.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/csso/-/csso-4.2.0.tgz#ea3a561346e8dc9f546d6febedd50187cf389529" - integrity sha512-wvlcdIbf6pwKEk7vHj8/Bkc0B4ylXZruLvOgs9doS5eOsOpuodOV2zJChSpkp+pRpYQLQMeF04nr3Z68Sta9jA== - dependencies: - css-tree "^1.1.2" - -debug@^4.1.1: - version "4.3.4" - resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865" - integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ== - dependencies: - ms "2.1.2" - -detect-libc@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-1.0.3.tgz#fa137c4bd698edf55cd5cd02ac559f91a4c4ba9b" - integrity sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg== - -detect-libc@^2.0.1: - version "2.0.2" - resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-2.0.2.tgz#8ccf2ba9315350e1241b88d0ac3b0e1fbd99605d" - integrity sha512-UX6sGumvvqSaXgdKGUsgZWqcUyIXZ/vZTrlRT/iobiKhGL0zL4d3osHj3uqllWJK+i+sixDS/3COVEOFbupFyw== - -diff@^4.0.1: - version "4.0.2" - resolved "https://registry.yarnpkg.com/diff/-/diff-4.0.2.tgz#60f3aecb89d5fae520c11aa19efc2bb982aade7d" - integrity sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A== - -dom-serializer@^1.0.1: - version "1.4.1" - resolved "https://registry.yarnpkg.com/dom-serializer/-/dom-serializer-1.4.1.tgz#de5d41b1aea290215dc45a6dae8adcf1d32e2d30" - integrity sha512-VHwB3KfrcOOkelEG2ZOfxqLZdfkil8PtJi4P8N2MMXucZq2yLp75ClViUlOVwyoHEDjYU433Aq+5zWP61+RGag== - dependencies: - domelementtype "^2.0.1" - domhandler "^4.2.0" - entities "^2.0.0" - -domelementtype@^2.0.1, domelementtype@^2.2.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/domelementtype/-/domelementtype-2.3.0.tgz#5c45e8e869952626331d7aab326d01daf65d589d" - integrity sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw== - -domhandler@^4.2.0, domhandler@^4.2.2, domhandler@^4.3.1: - version "4.3.1" - resolved "https://registry.yarnpkg.com/domhandler/-/domhandler-4.3.1.tgz#8d792033416f59d68bc03a5aa7b018c1ca89279c" - integrity sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ== - dependencies: - domelementtype "^2.2.0" - -domutils@^2.8.0: - version "2.8.0" - resolved "https://registry.yarnpkg.com/domutils/-/domutils-2.8.0.tgz#4437def5db6e2d1f5d6ee859bd95ca7d02048135" - integrity sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A== - dependencies: - dom-serializer "^1.0.1" - domelementtype "^2.2.0" - domhandler "^4.2.0" - -dotenv-expand@^5.1.0: - version "5.1.0" - resolved "https://registry.yarnpkg.com/dotenv-expand/-/dotenv-expand-5.1.0.tgz#3fbaf020bfd794884072ea26b1e9791d45a629f0" - integrity sha512-YXQl1DSa4/PQyRfgrv6aoNjhasp/p4qs9FjJ4q4cQk+8m4r6k4ZSiEyytKG8f8W9gi8WsQtIObNmKd+tMzNTmA== - -dotenv@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-7.0.0.tgz#a2be3cd52736673206e8a85fb5210eea29628e7c" - integrity sha512-M3NhsLbV1i6HuGzBUH8vXrtxOk+tWmzWKDMbAVSUp3Zsjm7ywFeuwrUXhmhQyRK1q5B5GGy7hcXPbj3bnfZg2g== - -electron-to-chromium@^1.4.284: - version "1.4.356" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.356.tgz#b75a8a8c31d571f6024310cc980a08cd6c15a8c5" - integrity sha512-nEftV1dRX3omlxAj42FwqRZT0i4xd2dIg39sog/CnCJeCcL1TRd2Uh0i9Oebgv8Ou0vzTPw++xc+Z20jzS2B6A== - -entities@^2.0.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/entities/-/entities-2.2.0.tgz#098dc90ebb83d8dffa089d55256b351d34c4da55" - integrity sha512-p92if5Nz619I0w+akJrLZH0MX0Pb5DX39XOwQTtXSdQQOaYH03S1uIQp4mhOZtAXrxq4ViO67YTiLBo2638o9A== - -entities@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/entities/-/entities-3.0.1.tgz#2b887ca62585e96db3903482d336c1006c3001d4" - integrity sha512-WiyBqoomrwMdFG1e0kqvASYfnlb0lp8M5o5Fw2OFq1hNZxxcNk8Ik0Xm7LxzBhuidnZB/UtBqVCgUz3kBOP51Q== - -error-ex@^1.3.1: - version "1.3.2" - resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.2.tgz#b4ac40648107fdcdcfae242f428bea8a14d4f1bf" - integrity sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g== - dependencies: - is-arrayish "^0.2.1" - -escalade@^3.1.1: - version "3.1.1" - resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.1.1.tgz#d8cfdc7000965c5a0174b4a82eaa5c0552742e40" - integrity sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw== - -escape-string-regexp@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz#1b61c0562190a8dff6ae3bb2cf0200ca130b86d4" - integrity sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg== - -fill-range@^7.0.1: - version "7.0.1" - resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.0.1.tgz#1919a6a7c75fe38b2c7c77e5198535da9acdda40" - integrity sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ== - dependencies: - to-regex-range "^5.0.1" - -get-port@^4.2.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/get-port/-/get-port-4.2.0.tgz#e37368b1e863b7629c43c5a323625f95cf24b119" - integrity sha512-/b3jarXkH8KJoOMQc3uVGHASwGLPq3gSFJ7tgJm2diza+bydJPTGOibin2steecKeOylE8oY2JERlVWkAJO6yw== - -globals@^13.2.0: - version "13.20.0" - resolved "https://registry.yarnpkg.com/globals/-/globals-13.20.0.tgz#ea276a1e508ffd4f1612888f9d1bad1e2717bf82" - integrity sha512-Qg5QtVkCy/kv3FUSlu4ukeZDVf9ee0iXLAUYX13gbR17bnejFTzr4iS9bY7kwCf1NztRNm1t91fjOiyx4CSwPQ== - dependencies: - type-fest "^0.20.2" - -has-flag@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd" - integrity sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw== - -has-flag@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" - integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== - -htmlnano@^2.0.0: - version "2.0.3" - resolved "https://registry.yarnpkg.com/htmlnano/-/htmlnano-2.0.3.tgz#50ee639ed63357d4a6c01309f52a35892e4edc2e" - integrity sha512-S4PGGj9RbdgW8LhbILNK7W9JhmYP8zmDY7KDV/8eCiJBQJlbmltp5I0gv8c5ntLljfdxxfmJ+UJVSqyH4mb41A== - dependencies: - cosmiconfig "^7.0.1" - posthtml "^0.16.5" - timsort "^0.3.0" - -htmlparser2@^7.1.1: - version "7.2.0" - resolved "https://registry.yarnpkg.com/htmlparser2/-/htmlparser2-7.2.0.tgz#8817cdea38bbc324392a90b1990908e81a65f5a5" - integrity sha512-H7MImA4MS6cw7nbyURtLPO1Tms7C5H602LRETv95z1MxO/7CP7rDVROehUYeYBUYEON94NXXDEPmZuq+hX4sog== - dependencies: - domelementtype "^2.0.1" - domhandler "^4.2.2" - domutils "^2.8.0" - entities "^3.0.1" - -import-fresh@^3.2.1: - version "3.3.0" - resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.3.0.tgz#37162c25fcb9ebaa2e6e53d5b4d88ce17d9e0c2b" - integrity sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw== - dependencies: - parent-module "^1.0.0" - resolve-from "^4.0.0" - -is-arrayish@^0.2.1: - version "0.2.1" - resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" - integrity sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg== - -is-extglob@^2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" - integrity sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ== - -is-glob@^4.0.3: - version "4.0.3" - resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.3.tgz#64f61e42cbbb2eec2071a9dac0b28ba1e65d5084" - integrity sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg== - dependencies: - is-extglob "^2.1.1" - -is-json@^2.0.1: - version "2.0.1" - resolved "https://registry.yarnpkg.com/is-json/-/is-json-2.0.1.tgz#6be166d144828a131d686891b983df62c39491ff" - integrity sha512-6BEnpVn1rcf3ngfmViLM6vjUjGErbdrL4rwlv+u1NO1XO8kqT4YGL8+19Q+Z/bas8tY90BTWMk2+fW1g6hQjbA== - -is-number@^7.0.0: - version "7.0.0" - resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" - integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== - -js-tokens@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" - integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== - -json-parse-even-better-errors@^2.3.0: - version "2.3.1" - resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d" - integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w== - -json5@^2.2.0, json5@^2.2.1: - version "2.2.3" - resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283" - integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg== - -lightningcss-darwin-arm64@1.19.0: - version "1.19.0" - resolved "https://registry.yarnpkg.com/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.19.0.tgz#56ab071e932f845dbb7667f44f5b78441175a343" - integrity sha512-wIJmFtYX0rXHsXHSr4+sC5clwblEMji7HHQ4Ub1/CznVRxtCFha6JIt5JZaNf8vQrfdZnBxLLC6R8pC818jXqg== - -lightningcss-darwin-x64@1.19.0: - version "1.19.0" - resolved "https://registry.yarnpkg.com/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.19.0.tgz#c867308b88859ba61a2c46c82b1ca52ff73a1bd0" - integrity sha512-Lif1wD6P4poaw9c/4Uh2z+gmrWhw/HtXFoeZ3bEsv6Ia4tt8rOJBdkfVaUJ6VXmpKHALve+iTyP2+50xY1wKPw== - -lightningcss-linux-arm-gnueabihf@1.19.0: - version "1.19.0" - resolved "https://registry.yarnpkg.com/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.19.0.tgz#0f921dc45f2e5c3aea70fab98844ac0e5f2f81be" - integrity sha512-P15VXY5682mTXaiDtbnLYQflc8BYb774j2R84FgDLJTN6Qp0ZjWEFyN1SPqyfTj2B2TFjRHRUvQSSZ7qN4Weig== - -lightningcss-linux-arm64-gnu@1.19.0: - version "1.19.0" - resolved "https://registry.yarnpkg.com/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.19.0.tgz#027f9df9c7f4ffa127c37a71726245a5794d7ba2" - integrity sha512-zwXRjWqpev8wqO0sv0M1aM1PpjHz6RVIsBcxKszIG83Befuh4yNysjgHVplF9RTU7eozGe3Ts7r6we1+Qkqsww== - -lightningcss-linux-arm64-musl@1.19.0: - version "1.19.0" - resolved "https://registry.yarnpkg.com/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.19.0.tgz#85ea987da868524eac6db94f8e1eaa23d0b688a3" - integrity sha512-vSCKO7SDnZaFN9zEloKSZM5/kC5gbzUjoJQ43BvUpyTFUX7ACs/mDfl2Eq6fdz2+uWhUh7vf92c4EaaP4udEtA== - -lightningcss-linux-x64-gnu@1.19.0: - version "1.19.0" - resolved "https://registry.yarnpkg.com/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.19.0.tgz#02bec89579ab4153dccc0def755d1fd9e3ee7f3c" - integrity sha512-0AFQKvVzXf9byrXUq9z0anMGLdZJS+XSDqidyijI5njIwj6MdbvX2UZK/c4FfNmeRa2N/8ngTffoIuOUit5eIQ== - -lightningcss-linux-x64-musl@1.19.0: - version "1.19.0" - resolved "https://registry.yarnpkg.com/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.19.0.tgz#e36a5df8193ae961d22974635e4c100a1823bb8c" - integrity sha512-SJoM8CLPt6ECCgSuWe+g0qo8dqQYVcPiW2s19dxkmSI5+Uu1GIRzyKA0b7QqmEXolA+oSJhQqCmJpzjY4CuZAg== - -lightningcss-win32-x64-msvc@1.19.0: - version "1.19.0" - resolved "https://registry.yarnpkg.com/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.19.0.tgz#0854dbd153035eca1396e2227c708ad43655a61c" - integrity sha512-C+VuUTeSUOAaBZZOPT7Etn/agx/MatzJzGRkeV+zEABmPuntv1zihncsi+AyGmjkkzq3wVedEy7h0/4S84mUtg== - -lightningcss@^1.16.1: - version "1.19.0" - resolved "https://registry.yarnpkg.com/lightningcss/-/lightningcss-1.19.0.tgz#fbbad0975de66252e38d96b5bdd2a62f2dd0ffbf" - integrity sha512-yV5UR7og+Og7lQC+70DA7a8ta1uiOPnWPJfxa0wnxylev5qfo4P+4iMpzWAdYWOca4jdNQZii+bDL/l+4hUXIA== - dependencies: - detect-libc "^1.0.3" - optionalDependencies: - lightningcss-darwin-arm64 "1.19.0" - lightningcss-darwin-x64 "1.19.0" - lightningcss-linux-arm-gnueabihf "1.19.0" - lightningcss-linux-arm64-gnu "1.19.0" - lightningcss-linux-arm64-musl "1.19.0" - lightningcss-linux-x64-gnu "1.19.0" - lightningcss-linux-x64-musl "1.19.0" - lightningcss-win32-x64-msvc "1.19.0" - -lines-and-columns@^1.1.6: - version "1.2.4" - resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.2.4.tgz#eca284f75d2965079309dc0ad9255abb2ebc1632" - integrity sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg== - -lmdb@2.8.5: - version "2.8.5" - resolved "https://registry.yarnpkg.com/lmdb/-/lmdb-2.8.5.tgz#ce191110c755c0951caa062722e300c703973837" - integrity sha512-9bMdFfc80S+vSldBmG3HOuLVHnxRdNTlpzR6QDnzqCQtCzGUEAGTzBKYMeIM+I/sU4oZfgbcbS7X7F65/z/oxQ== - dependencies: - msgpackr "^1.9.5" - node-addon-api "^6.1.0" - node-gyp-build-optional-packages "5.1.1" - ordered-binary "^1.4.1" - weak-lru-cache "^1.2.2" - optionalDependencies: - "@lmdb/lmdb-darwin-arm64" "2.8.5" - "@lmdb/lmdb-darwin-x64" "2.8.5" - "@lmdb/lmdb-linux-arm" "2.8.5" - "@lmdb/lmdb-linux-arm64" "2.8.5" - "@lmdb/lmdb-linux-x64" "2.8.5" - "@lmdb/lmdb-win32-x64" "2.8.5" - -lru-cache@^6.0.0: - version "6.0.0" - resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-6.0.0.tgz#6d6fe6570ebd96aaf90fcad1dafa3b2566db3a94" - integrity sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA== - dependencies: - yallist "^4.0.0" - -make-error@^1.1.1: - version "1.3.6" - resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2" - integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw== - -mdn-data@2.0.14: - version "2.0.14" - resolved "https://registry.yarnpkg.com/mdn-data/-/mdn-data-2.0.14.tgz#7113fc4281917d63ce29b43446f701e68c25ba50" - integrity sha512-dn6wd0uw5GsdswPFfsgMp5NSB0/aDe6fK94YJV/AJDYXL6HVLWBsxeq7js7Ad+mU2K9LAlwpk6kN2D5mwCPVow== - -micromatch@^4.0.5: - version "4.0.5" - resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.5.tgz#bc8999a7cbbf77cdc89f132f6e467051b49090c6" - integrity sha512-DMy+ERcEW2q8Z2Po+WNXuw3c5YaUSFjAO5GsJqfEl7UjvtIuFKO6ZrKvcItdy98dwFI2N1tg3zNIdKaQT+aNdA== - dependencies: - braces "^3.0.2" - picomatch "^2.3.1" - -ms@2.1.2: - version "2.1.2" - resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.2.tgz#d09d1f357b443f493382a8eb3ccd183872ae6009" - integrity sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w== - -msgpackr-extract@^3.0.1, msgpackr-extract@^3.0.2: - version "3.0.2" - resolved "https://registry.yarnpkg.com/msgpackr-extract/-/msgpackr-extract-3.0.2.tgz#e05ec1bb4453ddf020551bcd5daaf0092a2c279d" - integrity sha512-SdzXp4kD/Qf8agZ9+iTu6eql0m3kWm1A2y1hkpTeVNENutaB0BwHlSvAIaMxwntmRUAUjon2V4L8Z/njd0Ct8A== - dependencies: - node-gyp-build-optional-packages "5.0.7" - optionalDependencies: - "@msgpackr-extract/msgpackr-extract-darwin-arm64" "3.0.2" - "@msgpackr-extract/msgpackr-extract-darwin-x64" "3.0.2" - "@msgpackr-extract/msgpackr-extract-linux-arm" "3.0.2" - "@msgpackr-extract/msgpackr-extract-linux-arm64" "3.0.2" - "@msgpackr-extract/msgpackr-extract-linux-x64" "3.0.2" - "@msgpackr-extract/msgpackr-extract-win32-x64" "3.0.2" - -msgpackr@^1.5.4: - version "1.8.5" - resolved "https://registry.yarnpkg.com/msgpackr/-/msgpackr-1.8.5.tgz#8cadfb935357680648f33699d0e833c9179dbfeb" - integrity sha512-mpPs3qqTug6ahbblkThoUY2DQdNXcm4IapwOS3Vm/87vmpzLVelvp9h3It1y9l1VPpiFLV11vfOXnmeEwiIXwg== - optionalDependencies: - msgpackr-extract "^3.0.1" - -msgpackr@^1.9.5: - version "1.9.9" - resolved "https://registry.yarnpkg.com/msgpackr/-/msgpackr-1.9.9.tgz#ec71e37beb8729280847f683cb0a340eb35ce70f" - integrity sha512-sbn6mioS2w0lq1O6PpGtsv6Gy8roWM+o3o4Sqjd6DudrL/nOugY+KyJUimoWzHnf9OkO0T6broHFnYE/R05t9A== - optionalDependencies: - msgpackr-extract "^3.0.2" - -node-addon-api@^3.2.1: - version "3.2.1" - resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-3.2.1.tgz#81325e0a2117789c0128dab65e7e38f07ceba161" - integrity sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A== - -node-addon-api@^6.1.0: - version "6.1.0" - resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-6.1.0.tgz#ac8470034e58e67d0c6f1204a18ae6995d9c0d76" - integrity sha512-+eawOlIgy680F0kBzPUNFhMZGtJ1YmqM6l4+Crf4IkImjYrO/mqPwRMh352g23uIaQKFItcQ64I7KMaJxHgAVA== - -node-gyp-build-optional-packages@5.0.7: - version "5.0.7" - resolved "https://registry.yarnpkg.com/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.0.7.tgz#5d2632bbde0ab2f6e22f1bbac2199b07244ae0b3" - integrity sha512-YlCCc6Wffkx0kHkmam79GKvDQ6x+QZkMjFGrIMxgFNILFvGSbCp2fCBC55pGTT9gVaz8Na5CLmxt/urtzRv36w== - -node-gyp-build-optional-packages@5.1.1: - version "5.1.1" - resolved "https://registry.yarnpkg.com/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.1.1.tgz#52b143b9dd77b7669073cbfe39e3f4118bfc603c" - integrity sha512-+P72GAjVAbTxjjwUmwjVrqrdZROD4nf8KgpBoDxqXXTiYZZt/ud60dE5yvCSr9lRO8e8yv6kgJIC0K0PfZFVQw== - dependencies: - detect-libc "^2.0.1" - -node-gyp-build@^4.3.0: - version "4.6.0" - resolved "https://registry.yarnpkg.com/node-gyp-build/-/node-gyp-build-4.6.0.tgz#0c52e4cbf54bbd28b709820ef7b6a3c2d6209055" - integrity sha512-NTZVKn9IylLwUzaKjkas1e4u2DLNcV4rdYagA4PWdPwW87Bi7z+BznyKSRwS/761tV/lzCGXplWsiaMjLqP2zQ== - -node-releases@^2.0.8: - version "2.0.10" - resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.10.tgz#c311ebae3b6a148c89b1813fd7c4d3c024ef537f" - integrity sha512-5GFldHPXVG/YZmFzJvKK2zDSzPKhEp0+ZR5SVaoSag9fsL5YgHbUHDfnG5494ISANDcK4KwPXAx2xqVEydmd7w== - -nth-check@^2.0.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/nth-check/-/nth-check-2.1.1.tgz#c9eab428effce36cd6b92c924bdb000ef1f1ed1d" - integrity sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w== - dependencies: - boolbase "^1.0.0" - -nullthrows@^1.1.1: - version "1.1.1" - resolved "https://registry.yarnpkg.com/nullthrows/-/nullthrows-1.1.1.tgz#7818258843856ae971eae4208ad7d7eb19a431b1" - integrity sha512-2vPPEi+Z7WqML2jZYddDIfy5Dqb0r2fze2zTxNNknZaFpVHU3mFB3R+DWeJWGVx0ecvttSGlJTI+WG+8Z4cDWw== - -ordered-binary@^1.4.1: - version "1.4.1" - resolved "https://registry.yarnpkg.com/ordered-binary/-/ordered-binary-1.4.1.tgz#205cb6efd6c27fa0ef4eced994a023e081cdc911" - integrity sha512-9LtiGlPy982CsgxZvJGNNp2/NnrgEr6EAyN3iIEP3/8vd3YLgAZQHbQ75ZrkfBRGrNg37Dk3U6tuVb+B4Xfslg== - -parcel@2.10.0: - version "2.10.0" - resolved "https://registry.yarnpkg.com/parcel/-/parcel-2.10.0.tgz#6b1245baf771ab025769069a28901a54fdc10823" - integrity sha512-YJmWEsiv1ClpPcJiWkr3gFj40sRvfeK89GGGwJjpzQMQsBmN6h6OHrSkByx0jrsPIvdsOIccU702upYpRAypuw== - dependencies: - "@parcel/config-default" "2.10.0" - "@parcel/core" "2.10.0" - "@parcel/diagnostic" "2.10.0" - "@parcel/events" "2.10.0" - "@parcel/fs" "2.10.0" - "@parcel/logger" "2.10.0" - "@parcel/package-manager" "2.10.0" - "@parcel/reporter-cli" "2.10.0" - "@parcel/reporter-dev-server" "2.10.0" - "@parcel/reporter-tracer" "2.10.0" - "@parcel/utils" "2.10.0" - chalk "^4.1.0" - commander "^7.0.0" - get-port "^4.2.0" - -parent-module@^1.0.0: - version "1.0.1" - resolved "https://registry.yarnpkg.com/parent-module/-/parent-module-1.0.1.tgz#691d2709e78c79fae3a156622452d00762caaaa2" - integrity sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g== - dependencies: - callsites "^3.0.0" - -parse-json@^5.0.0: - version "5.2.0" - resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-5.2.0.tgz#c76fc66dee54231c962b22bcc8a72cf2f99753cd" - integrity sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg== - dependencies: - "@babel/code-frame" "^7.0.0" - error-ex "^1.3.1" - json-parse-even-better-errors "^2.3.0" - lines-and-columns "^1.1.6" - -path-type@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b" - integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw== - -picocolors@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.0.0.tgz#cb5bdc74ff3f51892236eaf79d68bc44564ab81c" - integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ== - -picomatch@^2.3.1: - version "2.3.1" - resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42" - integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA== - -postcss-value-parser@^4.2.0: - version "4.2.0" - resolved "https://registry.yarnpkg.com/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz#723c09920836ba6d3e5af019f92bc0971c02e514" - integrity sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ== - -posthtml-parser@^0.10.1: - version "0.10.2" - resolved "https://registry.yarnpkg.com/posthtml-parser/-/posthtml-parser-0.10.2.tgz#df364d7b179f2a6bf0466b56be7b98fd4e97c573" - integrity sha512-PId6zZ/2lyJi9LiKfe+i2xv57oEjJgWbsHGGANwos5AvdQp98i6AtamAl8gzSVFGfQ43Glb5D614cvZf012VKg== - dependencies: - htmlparser2 "^7.1.1" - -posthtml-parser@^0.11.0: - version "0.11.0" - resolved "https://registry.yarnpkg.com/posthtml-parser/-/posthtml-parser-0.11.0.tgz#25d1c7bf811ea83559bc4c21c189a29747a24b7a" - integrity sha512-QecJtfLekJbWVo/dMAA+OSwY79wpRmbqS5TeXvXSX+f0c6pW4/SE6inzZ2qkU7oAMCPqIDkZDvd/bQsSFUnKyw== - dependencies: - htmlparser2 "^7.1.1" - -posthtml-render@^3.0.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/posthtml-render/-/posthtml-render-3.0.0.tgz#97be44931496f495b4f07b99e903cc70ad6a3205" - integrity sha512-z+16RoxK3fUPgwaIgH9NGnK1HKY9XIDpydky5eQGgAFVXTCSezalv9U2jQuNV+Z9qV1fDWNzldcw4eK0SSbqKA== - dependencies: - is-json "^2.0.1" - -posthtml@^0.16.4, posthtml@^0.16.5: - version "0.16.6" - resolved "https://registry.yarnpkg.com/posthtml/-/posthtml-0.16.6.tgz#e2fc407f67a64d2fa3567afe770409ffdadafe59" - integrity sha512-JcEmHlyLK/o0uGAlj65vgg+7LIms0xKXe60lcDOTU7oVX/3LuEuLwrQpW3VJ7de5TaFKiW4kWkaIpJL42FEgxQ== - dependencies: - posthtml-parser "^0.11.0" - posthtml-render "^3.0.0" - -prettier@3.0.3: - version "3.0.3" - resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.0.3.tgz#432a51f7ba422d1469096c0fdc28e235db8f9643" - integrity sha512-L/4pUDMxcNa8R/EthV08Zt42WBO4h1rarVtK0K+QJG0X187OLo7l699jWw0GKuwzkPQ//jMFA/8Xm6Fh3J/DAg== - -process@0.11.10: - version "0.11.10" - resolved "https://registry.yarnpkg.com/process/-/process-0.11.10.tgz#7332300e840161bda3e69a1d1d91a7d4bc16f182" - integrity sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A== - -react-error-overlay@6.0.9: - version "6.0.9" - resolved "https://registry.yarnpkg.com/react-error-overlay/-/react-error-overlay-6.0.9.tgz#3c743010c9359608c375ecd6bc76f35d93995b0a" - integrity sha512-nQTTcUu+ATDbrSD1BZHr5kgSD4oF8OFjxun8uAaL8RwPBacGBNPf/yAuVVdx17N8XNzRDMrZ9XcKZHCjPW+9ew== - -react-refresh@^0.9.0: - version "0.9.0" - resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.9.0.tgz#71863337adc3e5c2f8a6bfddd12ae3bfe32aafbf" - integrity sha512-Gvzk7OZpiqKSkxsQvO/mbTN1poglhmAV7gR/DdIrRrSMXraRQQlfikRJOr3Nb9GTMPC5kof948Zy6jJZIFtDvQ== - -regenerator-runtime@^0.13.7: - version "0.13.11" - resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz#f6dca3e7ceec20590d07ada785636a90cdca17f9" - integrity sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg== - -resolve-from@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-4.0.0.tgz#4abcd852ad32dd7baabfe9b40e00a36db5f392e6" - integrity sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g== - -safe-buffer@^5.0.1: - version "5.2.1" - resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" - integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== - -semver@^7.5.2: - version "7.5.4" - resolved "https://registry.yarnpkg.com/semver/-/semver-7.5.4.tgz#483986ec4ed38e1c6c48c34894a9182dbff68a6e" - integrity sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA== - dependencies: - lru-cache "^6.0.0" - -source-map@^0.6.1: - version "0.6.1" - resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" - integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== - -srcset@4: - version "4.0.0" - resolved "https://registry.yarnpkg.com/srcset/-/srcset-4.0.0.tgz#336816b665b14cd013ba545b6fe62357f86e65f4" - integrity sha512-wvLeHgcVHKO8Sc/H/5lkGreJQVeYMm9rlmt8PuR1xE31rIuXhuzznUUqAt8MqLhB3MqJdFzlNAfpcWnxiFUcPw== - -stable@^0.1.8: - version "0.1.8" - resolved "https://registry.yarnpkg.com/stable/-/stable-0.1.8.tgz#836eb3c8382fe2936feaf544631017ce7d47a3cf" - integrity sha512-ji9qxRnOVfcuLDySj9qzhGSEFVobyt1kIOSkj1qZzYLzq7Tos/oUUWvotUPQLlrsidqsK6tBH89Bc9kL5zHA6w== - -supports-color@^5.3.0: - version "5.5.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.5.0.tgz#e2e69a44ac8772f78a1ec0b35b689df6530efc8f" - integrity sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow== - dependencies: - has-flag "^3.0.0" - -supports-color@^7.1.0: - version "7.2.0" - resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da" - integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw== - dependencies: - has-flag "^4.0.0" - -svgo@^2.4.0: - version "2.8.0" - resolved "https://registry.yarnpkg.com/svgo/-/svgo-2.8.0.tgz#4ff80cce6710dc2795f0c7c74101e6764cfccd24" - integrity sha512-+N/Q9kV1+F+UeWYoSiULYo4xYSDQlTgb+ayMobAXPwMnLvop7oxKMo9OzIrX5x3eS4L4f2UHhc9axXwY8DpChg== - dependencies: - "@trysound/sax" "0.2.0" - commander "^7.2.0" - css-select "^4.1.3" - css-tree "^1.1.3" - csso "^4.2.0" - picocolors "^1.0.0" - stable "^0.1.8" - -term-size@^2.2.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/term-size/-/term-size-2.2.1.tgz#2a6a54840432c2fb6320fea0f415531e90189f54" - integrity sha512-wK0Ri4fOGjv/XPy8SBHZChl8CM7uMc5VML7SqiQ0zG7+J5Vr+RMQDoHa2CNT6KHUnTGIXH34UDMkPzAUyapBZg== - -timsort@^0.3.0: - version "0.3.0" - resolved "https://registry.yarnpkg.com/timsort/-/timsort-0.3.0.tgz#405411a8e7e6339fe64db9a234de11dc31e02bd4" - integrity sha512-qsdtZH+vMoCARQtyod4imc2nIJwg9Cc7lPRrw9CzF8ZKR0khdr8+2nX80PBhET3tcyTtJDxAffGh2rXH4tyU8A== - -to-regex-range@^5.0.1: - version "5.0.1" - resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" - integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== - dependencies: - is-number "^7.0.0" - -ts-node@10.9.1: - version "10.9.1" - resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-10.9.1.tgz#e73de9102958af9e1f0b168a6ff320e25adcff4b" - integrity sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw== - dependencies: - "@cspotcode/source-map-support" "^0.8.0" - "@tsconfig/node10" "^1.0.7" - "@tsconfig/node12" "^1.0.7" - "@tsconfig/node14" "^1.0.0" - "@tsconfig/node16" "^1.0.2" - acorn "^8.4.1" - acorn-walk "^8.1.1" - arg "^4.1.0" - create-require "^1.1.0" - diff "^4.0.1" - make-error "^1.1.1" - v8-compile-cache-lib "^3.0.1" - yn "3.1.1" - -tslib@^2.4.0: - version "2.5.0" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.5.0.tgz#42bfed86f5787aeb41d031866c8f402429e0fddf" - integrity sha512-336iVw3rtn2BUK7ORdIAHTyxHGRIHVReokCR3XjbckJMK7ms8FysBfhLR8IXnAgy7T0PTPNBWKiH514FOW/WSg== - -type-fest@^0.20.2: - version "0.20.2" - resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.20.2.tgz#1bf207f4b28f91583666cb5fbd327887301cd5f4" - integrity sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ== - -typescript@5.2.2: - version "5.2.2" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.2.2.tgz#5ebb5e5a5b75f085f22bc3f8460fba308310fa78" - integrity sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w== - -undici-types@~5.25.1: - version "5.25.3" - resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-5.25.3.tgz#e044115914c85f0bcbb229f346ab739f064998c3" - integrity sha512-Ga1jfYwRn7+cP9v8auvEXN1rX3sWqlayd4HP7OKk4mZWylEmu3KzXDUGrQUN6Ol7qo1gPvB2e5gX6udnyEPgdA== - -update-browserslist-db@^1.0.10: - version "1.0.10" - resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.0.10.tgz#0f54b876545726f17d00cd9a2561e6dade943ff3" - integrity sha512-OztqDenkfFkbSG+tRxBeAnCVPckDBcvibKd35yDONx6OU8N7sqgwc7rCbkJ/WcYtVRZ4ba68d6byhC21GFh7sQ== - dependencies: - escalade "^3.1.1" - picocolors "^1.0.0" - -utility-types@^3.10.0: - version "3.10.0" - resolved "https://registry.yarnpkg.com/utility-types/-/utility-types-3.10.0.tgz#ea4148f9a741015f05ed74fd615e1d20e6bed82b" - integrity sha512-O11mqxmi7wMKCo6HKFt5AhO4BwY3VV68YU07tgxfz8zJTIxr4BpsezN49Ffwy9j3ZpwwJp4fkRwjRzq3uWE6Rg== - -v8-compile-cache-lib@^3.0.1: - version "3.0.1" - resolved "https://registry.yarnpkg.com/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz#6336e8d71965cb3d35a1bbb7868445a7c05264bf" - integrity sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg== - -weak-lru-cache@^1.2.2: - version "1.2.2" - resolved "https://registry.yarnpkg.com/weak-lru-cache/-/weak-lru-cache-1.2.2.tgz#fdbb6741f36bae9540d12f480ce8254060dccd19" - integrity sha512-DEAoo25RfSYMuTGc9vPJzZcZullwIqRDSI9LOy+fkCJPi6hykCnfKaXTuPBDuXAUcqHXyOgFtHNp/kB2FjYHbw== - -yallist@^4.0.0: - version "4.0.0" - resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" - integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== - -yaml@^1.10.0: - version "1.10.2" - resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.10.2.tgz#2301c5ffbf12b467de8da2333a459e29e7920e4b" - integrity sha512-r3vXyErRCYJ7wg28yvBY5VSoAF8ZvlcW9/BwUzEtUsjvX/DKs24dIkuwjtuprwJJHsbyUbLApepYTR1BN4uHrg== - -yn@3.1.1: - version "3.1.1" - resolved "https://registry.yarnpkg.com/yn/-/yn-3.1.1.tgz#1e87401a09d767c1d5eab26a6e4c185182d2eb50" - integrity sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q== diff --git a/scripts/.gitignore b/scripts/.gitignore deleted file mode 100644 index a6888157..00000000 --- a/scripts/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/javet \ No newline at end of file diff --git a/scripts/common.sh b/scripts/common.sh deleted file mode 100644 index ac4fe281..00000000 --- a/scripts/common.sh +++ /dev/null @@ -1,34 +0,0 @@ -#!/usr/bin/env bash - -export COLOR_OFF='\033[0m' -export COLOR_DIM='\033[2m' -export COLOR_RED='\033[31m' -export COLOR_GREEN='\033[32m' -export COLOR_BLUE='\033[34m' -export COLOR_MAGENTA='\033[35m' - -die() { - echo -e "$COLOR_RED" - echo "!!!!" - echo "!!!! $*" 1>&2 - echo -e "!!!!$COLOR_OFF" - exit 1 -} - -header() { - echo -e "$COLOR_DIM" - echo "##" - echo "## $*" - echo -e "##$COLOR_OFF" - echo -} - -info() { - echo - echo -e "$COLOR_DIM## $*$COLOR_OFF" - echo -} - -success() { - echo -e "$COLOR_GREEN## $*$COLOR_OFF" -} diff --git a/scripts/find-javet-jni-references.sh b/scripts/find-javet-jni-references.sh deleted file mode 100755 index 35e83e77..00000000 --- a/scripts/find-javet-jni-references.sh +++ /dev/null @@ -1,64 +0,0 @@ -#!/usr/bin/env bash - -SCRIPT_DIR=$(realpath "$(dirname "${BASH_SOURCE[0]}")") -REWRITE_JS_DIR="$(dirname "$SCRIPT_DIR")" -JAVET_CHECKOUT_DIR="$SCRIPT_DIR/javet" -JAVET_REPO="git@github.com:caoccao/Javet.git" -OUTPUT_PATH="$REWRITE_JS_DIR/src/main/resources/javet-jni-classnames.txt" - -source "$SCRIPT_DIR/common.sh" - -header "Making sure Javet checkout exists and is up-to-date..." - -if [ -d "$JAVET_CHECKOUT_DIR" ]; then - cd "$JAVET_CHECKOUT_DIR" || die "Could not cd to $JAVET_CHECKOUT_DIR" - info "Reusing existing Javet checkout." - if [ ! -z "$(git status --porcelain)" ]; then - die "Javet git checkout is not clean: $JAVET_CHECKOUT_DIR" - fi - git fetch -else - cd "$SCRIPT_DIR" || die "Could not cd to $SCRIPT_DIR" - info "Cloning a fresh Javet checkout." - git clone "$JAVET_REPO" "$JAVET_CHECKOUT_DIR" || die "Could not clone Javet git repo" - cd "$JAVET_CHECKOUT_DIR" || die "Could not cd to $JAVET_CHECKOUT_DIR" -fi - -header "Checking which Javet version is being used by rewrite-javascript..." - -cd "$REWRITE_JS_DIR" || die "Could not cd to $REWRITE_JS_DIR" -REWRITE_JS_DIR="$(dirname "$SCRIPT_DIR")" -JAVET_VERSIONS="$( - ./gradlew -q dependencyInsight --dependency com.caoccao.javet:javet-macos \ - | grep -o "com.caoccao.javet:javet-macos:[0-9.]\+" \ - | sort \ - | uniq -)" -info "Versions found: $(echo "$JAVET_VERSIONS" | tr "\n" " ")" -JAVET_VERSION_COUNT=$(echo "$JAVET_VERSIONS" | wc -l | tr -d ' ') -if [ "$JAVET_VERSION_COUNT" -ne 1 ]; then - die "Expected to find a single Javet version, but found $JAVET_VERSION_COUNT" -fi -JAVET_VERSION="$(echo "$JAVET_VERSIONS" | grep -o '[^:]\+$')" -if [ -z "$JAVET_VERSION" ]; then - die "Could not find a valid Javet version in the gradle output" -fi - -header "Checking out Javet version $JAVET_VERSION..." - -cd "$JAVET_CHECKOUT_DIR" || die "Couldn't cd to $JAVET_CHECKOUT_DIR" -if [ -z "$(git tag -l "$JAVET_VERSION")" ]; then - die "Couldn't find a $JAVET_VERSION tag in the Javet repo" -fi -git -c advice.detachedHead=false checkout "tags/$JAVET_VERSION" - -header "Scanning Javet source for \`FIND_CLASS\` and \`FindClass\` references..." - -JNI_CLASS_NAMES="$(grep -RE '(FindClass)|(FIND_CLASS)' | grep -o '".*"' | tr -d '"' | tr "/" "." | sort | uniq)" -JNI_CLASS_NAMES_COUNT="$(echo "$JNI_CLASS_NAMES" | wc -l | tr -d ' ')" - -header "Writing $JNI_CLASS_NAMES_COUNT class names to $OUTPUT_PATH..." - -echo "$JNI_CLASS_NAMES" > "$OUTPUT_PATH" - -success "Done." \ No newline at end of file diff --git a/src/main/java/com/caoccao/javet/interop/JavetBridge.java b/src/main/java/com/caoccao/javet/interop/JavetBridge.java deleted file mode 100644 index c8ba44a3..00000000 --- a/src/main/java/com/caoccao/javet/interop/JavetBridge.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package com.caoccao.javet.interop; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.interop.options.V8RuntimeOptions; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.reference.IV8ValueReference; -import com.caoccao.javet.values.reference.V8ValueFunction; -import com.caoccao.javet.values.reference.V8ValueObject; -import org.openrewrite.javascript.internal.tsc.generated.TSCSyntaxKind; - -import java.util.HashMap; -import java.util.Map; - -public final class JavetBridge { - private JavetBridge() {} - - public static Map getReferenceMapSnapshot(V8Runtime runtime) { - return new HashMap<>(runtime.referenceMap); - } - - public static V8Runtime makeWrappedV8Runtime() { - V8Host host = V8Host.getV8Instance(); - V8RuntimeOptions runtimeOptions = host.getJSRuntimeType().getRuntimeOptions(); - if (!host.isLibraryLoaded()) { - throw new IllegalStateException("native v8 library is not loaded"); - } - final long handle = host.getV8Native().createV8Runtime(runtimeOptions); - V8Runtime v8Runtime = new V8Runtime(host, handle, false, host.getV8Native(), runtimeOptions) { - private final Map remainingReferences = new HashMap<>(); - - @Override - void addReference(IV8ValueReference iV8ValueReference) { - super.addReference(iV8ValueReference); - StringBuilder sb = new StringBuilder(); - for (StackTraceElement element : Thread.currentThread().getStackTrace()) { - sb.append("\t").append(element.toString()).append("\n"); - } - remainingReferences.put(iV8ValueReference.getHandle(), sb.toString()); - } - - @Override - void removeReference(IV8ValueReference iV8ValueReference) throws JavetException { - super.removeReference(iV8ValueReference); - // Uncommenting this surfaces unmatched references for some reason -// remainingReferences.remove(iV8ValueReference.getHandle()); - } - - - @Override - public void close(boolean forceClose) throws JavetException { - if (!isClosed() && forceClose) { - debugOpenReferences(); - removeAllReferences(); - host.getV8Native().closeV8Runtime(handle); - } - } - - private void debugOpenReferences() { - Map referenceMap = getReferenceMapSnapshot(this); - boolean hasOpen = false; - for (IV8ValueReference valueV8 : referenceMap.values()) { - if (!valueV8.isClosed()) { - hasOpen = true; - System.err.print("** still open: "); - if (valueV8 instanceof V8ValueFunction) { - System.err.print(valueV8); - } else if (valueV8 instanceof V8ValueObject) { - try (V8Value constructor = ((V8ValueObject) valueV8).get("constructor")) { - if (constructor instanceof V8ValueObject) { - String name = ((V8ValueObject) constructor).getPrimitive("name"); - if (name.equals("NodeObject")) { - System.err.print("[" + name + ":" + TSCSyntaxKind.fromCode(((V8ValueObject) valueV8).getInteger("kind")) + "]"); - } else { - System.err.print("[" + name + "]"); - } - } else { - System.err.print("[object without a constructor]"); - } - } catch (JavetException e) { - System.err.print("[error while trying to display a JS object]"); - } - } else { - // TODO - System.err.print(valueV8); - } - try { - if (valueV8.isWeak()) { - System.err.print(" (weak)"); - } - } catch (JavetException e) { - throw new RuntimeException(e); - } - System.err.println(); - String caller = remainingReferences.get(valueV8.getHandle()); - System.err.println("\tfrom " + caller); - } - } - - if (hasOpen) { - throw new IllegalStateException("runtime contains un-recycled V8 references"); - } - } - }; - host.getV8Native().registerV8Runtime(handle, v8Runtime); - return v8Runtime; - } -} diff --git a/src/main/java/org/openrewrite/javascript/TypeScriptSignatureBuilder.java b/src/main/java/org/openrewrite/javascript/TypeScriptSignatureBuilder.java deleted file mode 100644 index 0d96e7d5..00000000 --- a/src/main/java/org/openrewrite/javascript/TypeScriptSignatureBuilder.java +++ /dev/null @@ -1,548 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript; - -import org.jspecify.annotations.Nullable; -import org.openrewrite.Incubating; -import org.openrewrite.java.JavaTypeSignatureBuilder; -import org.openrewrite.java.tree.JavaType; -import org.openrewrite.javascript.internal.tsc.TSCNode; -import org.openrewrite.javascript.internal.tsc.TSCNodeList; -import org.openrewrite.javascript.internal.tsc.TSCSymbol; -import org.openrewrite.javascript.internal.tsc.TSCType; -import org.openrewrite.javascript.internal.tsc.generated.TSCObjectFlag; -import org.openrewrite.javascript.internal.tsc.generated.TSCSyntaxKind; -import org.openrewrite.javascript.internal.tsc.generated.TSCTypeFlag; -import org.openrewrite.javascript.tree.TsType; - -import java.util.*; - -import static org.openrewrite.javascript.internal.tsc.TSCProgramContext.CompilerBridgeSourceKind.ApplicationCode; - -@Incubating(since = "0.0") -public class TypeScriptSignatureBuilder implements JavaTypeSignatureBuilder { - - @Nullable - Set typeVariableNameStack; - - Map signatures = new IdentityHashMap<>(); - - @Override - public String signature(@Nullable Object object) { - if (object == null) { - return "{undefined}"; - } - - TSCNode node = (TSCNode) object; - String cached = signatures.get(node); - if (cached != null) { - return cached; - } - - switch (node.syntaxKind()) { - case SourceFile: - cached = mapSourceFileFqn((TSCNode.SourceFile) node); - break; - case ClassDeclaration: - case EnumDeclaration: - case InterfaceDeclaration: - TSCNodeList typeParameters = node.getOptionalNodeListProperty("typeParameters"); - return typeParameters != null && !typeParameters.isEmpty() ? - parameterizedSignature(node) : classSignature(node); - case ArrayType: - cached = arraySignature(node); - break; - case EnumMember: - return mapEnumMember(node); - case Identifier: - return mapIdentifier(node); - case Parameter: - return mapParameter(node); - case QualifiedName: - return mapQualifiedName(node); - case ThisKeyword: - return mapThis(node); - case TypeOperator: - return mapTypeOperator(node); - case TypeParameter: - cached = genericSignature(node); - break; - case ExpressionWithTypeArguments: - case TypeReference: - case TypeQuery: - return mapTypeReference(node); - case UnionType: - return TsType.Union.getFullyQualifiedName(); - case PropertyDeclaration: - case VariableDeclaration: - cached = variableSignature(node); - break; - } - if (cached != null) { - signatures.put(node, cached); - return cached; - } - - TSCType type = node.getTypeChecker().getTypeAtLocation(node); - return mapType(type); - } - - @Override - public String arraySignature(Object object) { - TSCNode node = (TSCNode) object; - TSCNode elementType = node.getNodeProperty("elementType"); - return signature(elementType) + trimWhitespace(node.getText().substring(elementType.getText().length())); - } - - @Override - public String classSignature(Object object) { - TSCNode node = (TSCNode) object; - if (node.syntaxKind() == TSCSyntaxKind.SourceFile) { - return mapSourceFileFqn((TSCNode.SourceFile) node); - } - - return mapFqn(node); - } - - @Override - public String genericSignature(Object object) { - TSCNode node = (TSCNode) object; - - if (typeVariableNameStack == null) { - typeVariableNameStack = new HashSet<>(); - } - - String name = node.getNodeProperty("name").getText(); - if (!typeVariableNameStack.add(name)) { - return "Generic{" + name + "}"; - } - - StringBuilder s = new StringBuilder("Generic{").append(name); - StringJoiner boundSigs = new StringJoiner(" & "); - - TSCNode constraint = node.getOptionalNodeProperty("constraint"); - if (constraint != null) { - if (constraint.syntaxKind() == TSCSyntaxKind.IntersectionType) { - for (TSCNode type : constraint.getNodeListProperty("types")) { - boundSigs.add(signature(type)); - } - } else { - boundSigs.add(signature(constraint)); - } - } - - String boundSigStr = boundSigs.toString(); - if (!boundSigStr.isEmpty()) { - s.append(" extends ").append(boundSigStr); - } - - typeVariableNameStack.remove(name); - s.append("}"); - return s.toString(); - } - - public String methodSignature(Object object) { - TSCNode node = (TSCNode) object; - - String s = classSignature(getOwner(node)); - boolean isConstructor = node.syntaxKind() == TSCSyntaxKind.Constructor || - node.syntaxKind() == TSCSyntaxKind.ConstructSignature || - node.syntaxKind() == TSCSyntaxKind.NewExpression; - - TSCNode type = node.getOptionalNodeProperty("type"); - String returnType; - if (type != null) { - returnType = signature(type); - } else { - returnType = "void"; - } - - if (isConstructor) { - s += "{name=,return=" + s; - } else { - TSCNode name = node.getOptionalNodeProperty("name"); - s += "{name=" + (name == null ? "" : name.getText()) + ",return=" + returnType; - } - return s + ",parameters=" + methodArgumentSignature(node) + "}"; - } - - @Override - public String parameterizedSignature(Object object) { - TSCNode node = (TSCNode) object; - StringBuilder s = new StringBuilder(classSignature(node)); - StringJoiner joiner = new StringJoiner(", ", "<", ">"); - for (TSCNode param : node.getNodeListProperty("typeParameters")) { - joiner.add(signature(param)); - } - - s.append(joiner); - return s.toString(); - } - - @Override - public String primitiveSignature(Object object) { - TSCNode node = (TSCNode) object; - switch (node.syntaxKind()) { - case BooleanKeyword: - return JavaType.Primitive.Boolean.getKeyword(); - case NumberKeyword: - return "number"; - case StringKeyword: - return JavaType.Primitive.String.getKeyword(); - case VoidKeyword: - return JavaType.Primitive.Void.getKeyword(); - default: - throw new IllegalArgumentException("Unexpected primitive type " + object); - } - } - - private String methodArgumentSignature(TSCNode node) { - List parameters = node.getOptionalNodeListProperty("parameters"); - if (parameters != null) { - StringJoiner genericArgumentTypes = new StringJoiner(",", "[", "]"); - for (TSCNode parameter : parameters) { - genericArgumentTypes.add(signature(parameter)); - } - return genericArgumentTypes.toString(); - } - return "[]"; - } - - public String variableSignature(TSCNode node) { - String owner = signature(getOwner(node)); - //noinspection ConstantValue - if (owner == null) { - return null; - } - - if (owner.contains("<")) { - owner = owner.substring(0, owner.indexOf('<')); - } - - String name = node.getNodeProperty("name").getText(); - String typeSig; - TSCNode type = node.getOptionalNodeProperty("type"); - if (type != null) { - typeSig = signature(type); - } else if (node.syntaxKind() == TSCSyntaxKind.EnumMember) { - typeSig = owner; - } else { - typeSig = resolveNode(node); - } - return owner + "{name=" + name + ",type=" + typeSig + '}'; - } - - private String resolveNode(TSCNode node) { - TSCNode type = node.getOptionalNodeProperty("type"); - if (type != null) { - return signature(type); - } - - TSCSymbol symbol = node.getTypeChecker().getTypeAtLocation(node).getOptionalSymbolProperty("symbol"); - if (symbol != null) { - try { - return signature(symbol.getValueDeclaration()); - } catch (Exception ignored) { - } - } - return mapType(node.getTypeChecker().getTypeAtLocation(node)); - } - - private static boolean isClassDeclaration(TSCNode node) { - return node.syntaxKind() == TSCSyntaxKind.ClassDeclaration || - node.syntaxKind() == TSCSyntaxKind.InterfaceDeclaration || - node.syntaxKind() == TSCSyntaxKind.EnumDeclaration; - } - - private String mapEnumMember(TSCNode node) { - return signature(node.getParent()); - } - - public static String mapFqn(TSCNode node) { - TSCNode parent = node.getParent(); - if (parent == null) { - return ""; - } - - TSCNode name = node.getOptionalNodeProperty("name"); - String fqn = name == null ? "" : node.getNodeProperty("name").getText(); - - if (parent.syntaxKind() == TSCSyntaxKind.SourceFile) { - fqn = mapSourceFileFqn((TSCNode.SourceFile) parent) + "." + fqn; - } else if (isClassDeclaration(parent) && isClassDeclaration(node)) { - String prefix = mapFqn(parent); - fqn = prefix + "$" + fqn; - } else { - String prefix = mapFqn(parent); - fqn = prefix + "." + fqn; - } - - return fqn; - } - - private String mapIdentifier(TSCNode node) { - TSCSymbol symbol = node.getTypeChecker().getTypeAtLocation(node).getOptionalSymbolProperty("symbol"); - if (symbol != null) { - List declarations = symbol.getDeclarations(); - if (declarations != null && !declarations.isEmpty()) { - if (declarations.size() == 1) { - return signature(declarations.get(0)); - } else { - return TsType.MergedInterface.getFullyQualifiedName(); - } - } else { - implementMe(node.syntaxKind()); - } - } - return mapType(node.getTypeChecker().getTypeAtLocation(node)); - } - - private String mapParameter(TSCNode node) { - return resolveNode(node); - } - - private String mapQualifiedName(TSCNode node) { - String left = signature(node.getNodeProperty("left")); - int index = left.indexOf('<'); - if (index != -1) { - left = left.substring(0, index); - } - return left + "$" + node.getNodeProperty("right").getText(); - } - - private static String mapSourceFileFqn(TSCNode.SourceFile node) { - String path; - if (node.getCompilerBridgeSourceInfo().getSourceKind() == ApplicationCode) { - path = node.getSourceFile().getPath().replaceFirst("/app", ""); - } else { - path = node.getSourceFile().getPath().replaceFirst("/lib", "lib"); - } - String clean = path.replace("/", "."); - return clean.startsWith(".") ? clean.substring(1) : clean; - } - - private String mapThis(TSCNode node) { - return resolveNode(node); - } - - private String mapType(TSCType type) { - TSCTypeFlag flag = null; - try { - flag = type.getExactTypeFlag(); - } catch (Exception ignored) { - } - - if (flag != null) { - switch (flag) { - case Any: - return TsType.Any.getFullyQualifiedName(); - case Boolean: - case BooleanLiteral: - return JavaType.Primitive.Boolean.getKeyword(); - case Number: - case NumberLiteral: - return TsType.Number.getFullyQualifiedName(); - case Null: - return JavaType.Primitive.Null.getKeyword(); - case Object: - return TsType.Anonymous.getFullyQualifiedName(); - case String: - case StringLiteral: - return JavaType.Primitive.String.getKeyword(); - case Undefined: - return TsType.Undefined.getFullyQualifiedName(); - case Union: - return TsType.Union.getFullyQualifiedName(); - case Unit: - return TsType.Unit.getFullyQualifiedName(); - case Unknown: - return TsType.Unknown.getFullyQualifiedName(); - case Void: - return JavaType.Primitive.Void.getKeyword(); - case Enum: - return TsType.Enum.getFullyQualifiedName(); - case EnumLiteral: - return TsType.EnumLiteral.getFullyQualifiedName(); - case BigInt: - return TsType.BigInt.getFullyQualifiedName(); - case BigIntLiteral: - return TsType.BigIntLiteral.getFullyQualifiedName(); - case ESSymbol: - return TsType.ESSymbol.getFullyQualifiedName(); - case UniqueESSymbol: - return TsType.UniqueESSymbol.getFullyQualifiedName(); - case Never: - return TsType.Never.getFullyQualifiedName(); - case TypeParameter: - return TsType.TypeParameter.getFullyQualifiedName(); - case Intersection: - return TsType.Intersection.getFullyQualifiedName(); - case Index: - return TsType.Index.getFullyQualifiedName(); - case IndexedAccess: - return TsType.IndexedAccess.getFullyQualifiedName(); - case Conditional: - return TsType.Conditional.getFullyQualifiedName(); - case Substitution: - return TsType.Substitution.getFullyQualifiedName(); - case NonPrimitive: - return TsType.NonPrimitive.getFullyQualifiedName(); - case TemplateLiteral: - return TsType.TemplateLiteral.getFullyQualifiedName(); - case StringMapping: - return TsType.StringMapping.getFullyQualifiedName(); - case AnyOrUnknown: - return TsType.AnyOrUnknown.getFullyQualifiedName(); - case Nullable: - return TsType.Nullable.getFullyQualifiedName(); - case Literal: - return TsType.Literal.getFullyQualifiedName(); - case Freshable: - return TsType.Freshable.getFullyQualifiedName(); - case StringOrNumberLiteral: - return TsType.StringOrNumberLiteral.getFullyQualifiedName(); - case StringOrNumberLiteralOrUnique: - return TsType.StringOrNumberLiteralOrUnique.getFullyQualifiedName(); - case DefinitelyFalsy: - return TsType.DefinitelyFalsy.getFullyQualifiedName(); - case PossiblyFalsy: - return TsType.PossiblyFalsy.getFullyQualifiedName(); - case Intrinsic: - return TsType.Intrinsic.getFullyQualifiedName(); - case Primitive: - return TsType.Primitive.getFullyQualifiedName(); - case StringLike: - return TsType.StringLike.getFullyQualifiedName(); - case NumberLike: - return TsType.NumberLike.getFullyQualifiedName(); - case BigIntLike: - return TsType.BigIntLike.getFullyQualifiedName(); - case BooleanLike: - return TsType.BooleanLike.getFullyQualifiedName(); - case EnumLike: - return TsType.EnumLike.getFullyQualifiedName(); - case ESSymbolLike: - return TsType.ESSymbolLike.getFullyQualifiedName(); - case VoidLike: - return TsType.VoidLike.getFullyQualifiedName(); - case DefinitelyNonNullable: - return TsType.DefinitelyNonNullable.getFullyQualifiedName(); - case DisjointDomains: - return TsType.DisjointDomains.getFullyQualifiedName(); - case UnionOrIntersection: - return TsType.UnionOrIntersection.getFullyQualifiedName(); - case StructuredType: - return TsType.StructuredType.getFullyQualifiedName(); - case TypeVariable: - return TsType.TypeVariable.getFullyQualifiedName(); - case InstantiableNonPrimitive: - return TsType.InstantiableNonPrimitive.getFullyQualifiedName(); - case InstantiablePrimitive: - return TsType.InstantiablePrimitive.getFullyQualifiedName(); - case Instantiable: - return TsType.Instantiable.getFullyQualifiedName(); - case StructuredOrInstantiable: - return TsType.StructuredOrInstantiable.getFullyQualifiedName(); - case ObjectFlagsType: - return TsType.ObjectFlagsType.getFullyQualifiedName(); - case Simplifiable: - return TsType.Simplifiable.getFullyQualifiedName(); - case Singleton: - return TsType.Singleton.getFullyQualifiedName(); - case Narrowable: - return TsType.Narrowable.getFullyQualifiedName(); - case IncludesMask: - return TsType.IncludesMask.getFullyQualifiedName(); - case NotPrimitiveUnion: - return TsType.NotPrimitiveUnion.getFullyQualifiedName(); - default: - implementMe(type); - break; - } - } else { - TSCObjectFlag objectFlag = TSCObjectFlag.fromMaskExact(type.getObjectFlags()); - if (objectFlag == TSCObjectFlag.PrimitiveUnion) { - return TsType.PrimitiveUnion.getFullyQualifiedName(); - } else { - implementMe(type); - } - } - // This should never happen. If it does, we need to add support for the type. - throw new UnsupportedOperationException("Cannot map type " + type); - } - - private String mapTypeOperator(TSCNode node) { - return signature(node.getNodeProperty("type")); - } - - private String mapTypeReference(TSCNode node) { - String className = null; - TSCNode name = node.getOptionalNodeProperty("typeName"); - if (name != null) { - className = signature(name); - } - - name = node.getOptionalNodeProperty("exprName"); - if (className == null && name != null) { - className = signature(name); - } - - if (className == null) { - className = signature(node.getNodeProperty("expression")); - } - - if (className.contains("<") && !className.startsWith("Generic{")) { - className = className.substring(0, className.indexOf('<')); - } - - List typeArguments = node.getOptionalNodeListProperty("typeArguments"); - if (typeArguments != null) { - StringJoiner typeArgSigs = new StringJoiner(", ", "<", ">"); - for (TSCNode typeArg : typeArguments) { - typeArgSigs.add(signature(typeArg)); - } - className = className + typeArgSigs; - } - return className; - } - - private TSCNode getOwner(TSCNode node) { - TSCNode parent = node.getParent(); - if (parent == null) { - return node; - } else if (parent.syntaxKind() == TSCSyntaxKind.SourceFile || - parent.syntaxKind() == TSCSyntaxKind.ClassDeclaration || - parent.syntaxKind() == TSCSyntaxKind.EnumDeclaration || - parent.syntaxKind() == TSCSyntaxKind.InterfaceDeclaration || - parent.syntaxKind() == TSCSyntaxKind.MethodDeclaration) { - return parent; - } else { - return getOwner(node.getParent()); - } - } - - private String trimWhitespace(String s) { - return s.replaceAll("\\s+", ""); - } - - private void implementMe(TSCSyntaxKind syntaxKind) { - throw new UnsupportedOperationException(syntaxKind.name() + " syntaxKind is not supported in TypeScriptSignatureBuilder."); - } - - private void implementMe(TSCType type) { - throw new UnsupportedOperationException(type.typeToString() + " type is not supported in TypeScriptSignatureBuilder."); - } -} diff --git a/src/main/java/org/openrewrite/javascript/TypeScriptTypeMapping.java b/src/main/java/org/openrewrite/javascript/TypeScriptTypeMapping.java deleted file mode 100644 index b00fcb3a..00000000 --- a/src/main/java/org/openrewrite/javascript/TypeScriptTypeMapping.java +++ /dev/null @@ -1,807 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript; - -import org.jspecify.annotations.Nullable; -import org.openrewrite.Incubating; -import org.openrewrite.java.JavaTypeMapping; -import org.openrewrite.java.internal.JavaTypeCache; -import org.openrewrite.java.tree.Flag; -import org.openrewrite.java.tree.JavaType; -import org.openrewrite.java.tree.TypeUtils; -import org.openrewrite.javascript.internal.tsc.TSCNode; -import org.openrewrite.javascript.internal.tsc.TSCNodeList; -import org.openrewrite.javascript.internal.tsc.TSCSymbol; -import org.openrewrite.javascript.internal.tsc.TSCType; -import org.openrewrite.javascript.internal.tsc.generated.TSCObjectFlag; -import org.openrewrite.javascript.internal.tsc.generated.TSCSyntaxKind; -import org.openrewrite.javascript.internal.tsc.generated.TSCTypeFlag; -import org.openrewrite.javascript.tree.TsType; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import static java.util.Collections.emptyList; -import static org.openrewrite.java.tree.JavaType.GenericTypeVariable.Variance.*; -import static org.openrewrite.javascript.TypeScriptSignatureBuilder.mapFqn; - -@Incubating(since = "0.0") -public class TypeScriptTypeMapping implements JavaTypeMapping { - - private final TypeScriptSignatureBuilder signatureBuilder; - private final JavaTypeCache typeCache; - - public TypeScriptTypeMapping(JavaTypeCache typeCache) { - this.signatureBuilder = new TypeScriptSignatureBuilder(); - this.typeCache = typeCache; - } - - @Override - @SuppressWarnings("DataFlowIssue") - public JavaType type(@Nullable TSCNode node) { - if (node == null) { - return null; - } - - String signature = signatureBuilder.signature(node); - JavaType existing = typeCache.get(signature); - if (existing != null) { - return existing; - } - - switch (node.syntaxKind()) { - case SourceFile: - return mapSourceFileFqn(signature); - case ClassDeclaration: - case EnumDeclaration: - case InterfaceDeclaration: - return classType(node, signature); - case ArrayType: - return array(node, signature); - case EnumMember: - return mapEnumMember(node); - case Identifier: - return mapIdentifier(node); - case Parameter: - return mapParameter(node); - case QualifiedName: - return mapQualifiedName(node); - case ThisKeyword: - return mapThis(node); - case TypeOperator: - return mapTypeOperator(node); - case TypeParameter: - return generic(node, signature); - case ExpressionWithTypeArguments: - case TypeReference: - case TypeQuery: - return mapReference(node, signature); - case UnionType: - return TsType.Union; - case PropertyDeclaration: - case VariableDeclaration: - return variableType(node, signature); - } - TSCType type = node.getTypeChecker().getTypeAtLocation(node); - return mapType(type); - } - - private JavaType array(TSCNode node, String signature) { - JavaType.Array arr = new JavaType.Array(null, null, JavaType.EMPTY_FULLY_QUALIFIED_ARRAY); - typeCache.put(signature, arr); - TSCNode elementType = node.getNodeProperty("elementType"); - arr.unsafeSet(type(elementType), null); - return arr; - } - - private JavaType.@Nullable FullyQualified classType(@Nullable TSCNode node) { - return classType(node, signatureBuilder.signature(node)); - } - - private JavaType.@Nullable FullyQualified classType(@Nullable TSCNode node, String signature) { - if (node == null || node.syntaxKind() != TSCSyntaxKind.SourceFile && node.getTypeForNode() == null) { - return null; - } - - String fqn = signatureBuilder.classSignature(node); - JavaType fq = typeCache.get(fqn); - JavaType.Class clazz = (JavaType.Class) (fq instanceof JavaType.Parameterized ? ((JavaType.Parameterized) fq).getType() : fq); - if (clazz == null) { - TSCSyntaxKind syntaxKind = node.syntaxKind(); - JavaType.FullyQualified.Kind kind; - switch (syntaxKind) { - case EnumDeclaration: - kind = JavaType.FullyQualified.Kind.Enum; - break; - case InterfaceDeclaration: - kind = JavaType.FullyQualified.Kind.Interface; - break; - default: - kind = JavaType.FullyQualified.Kind.Class; - } - - List modifiers = node.getOptionalNodeListProperty("modifiers"); - clazz = new JavaType.Class( - null, - mapModifiers(modifiers), - mapFqn(node), - kind, - null, null, null, null, null, null, null - ); - - typeCache.put(fqn, clazz); - - JavaType.FullyQualified owner = null; - TSCNode parent = getOwner(node); - if (parent.syntaxKind() == TSCSyntaxKind.ClassDeclaration) { - owner = classType(parent); - } - - JavaType.FullyQualified supertype = null; - List interfaces = null; - List heritageClauses = node.getOptionalNodeListProperty("heritageClauses"); - if (heritageClauses != null) { - for (TSCNode heritageClause : heritageClauses) { - if (heritageClause.getText().contains("extends")) { - List superTypes = heritageClause.getNodeListProperty("types"); - if (superTypes.size() > 1) { - implementMe(node.syntaxKind()); - } else { - supertype = (JavaType.FullyQualified) type(superTypes.get(0)); - } - } else { - implementMe(node.syntaxKind()); - } - } - } - - List propertyNodes = null; - List methodNodes = null; - List enumNodes = null; - TSCNodeList memberNodes = node.getOptionalNodeListProperty("members"); - if (memberNodes != null) { - for (TSCNode member : memberNodes) { - if (member.syntaxKind() == TSCSyntaxKind.CallSignature || - member.syntaxKind() == TSCSyntaxKind.Constructor || - member.syntaxKind() == TSCSyntaxKind.ConstructSignature || - member.syntaxKind() == TSCSyntaxKind.FunctionDeclaration || - member.syntaxKind() == TSCSyntaxKind.MethodDeclaration || - member.syntaxKind() == TSCSyntaxKind.MethodSignature || - // TODO: possibly not the appropriate way to map indexed access - member.syntaxKind() == TSCSyntaxKind.IndexSignature) { - if (methodNodes == null) { - methodNodes = new ArrayList<>(1); - } - methodNodes.add(member); - } else if (member.syntaxKind() == TSCSyntaxKind.PropertyDeclaration || - member.syntaxKind() == TSCSyntaxKind.PropertySignature) { - if (propertyNodes == null) { - propertyNodes = new ArrayList<>(1); - } - propertyNodes.add(member); - } else if (member.syntaxKind() == TSCSyntaxKind.EnumMember) { - if (enumNodes == null) { - enumNodes = new ArrayList<>(1); - } - enumNodes.add(member); - } else { - throw new IllegalStateException("Unable to find value declaration for symbol " + member); - } - } - } - - List members = null; - if (enumNodes != null) { - members = new ArrayList<>(enumNodes.size() + (propertyNodes == null ? 0 : propertyNodes.size())); - for (TSCNode enumNode : enumNodes) { - members.add(variableType(enumNode, clazz)); - } - } - - if (propertyNodes != null) { - members = new ArrayList<>(propertyNodes.size()); - for (TSCNode propertyNode : propertyNodes) { - members.add(variableType(propertyNode, clazz)); - } - } - - List methods = null; - if (methodNodes != null) { - methods = new ArrayList<>(methodNodes.size()); - for (TSCNode methodNode : methodNodes) { - methods.add(methodDeclarationType(methodNode, clazz)); - } - } - - clazz.unsafeSet(null, supertype, owner, mapAnnotations(modifiers), interfaces, members, methods); - } - - TSCNodeList typeParamNodes = node.getOptionalNodeListProperty("typeParameters"); - if (typeParamNodes != null) { - JavaType jt = typeCache.get(signature); - if (jt == null) { - JavaType.Parameterized pt = new JavaType.Parameterized(null, null, null); - typeCache.put(signature, pt); - - List typeParams = new ArrayList<>(typeParamNodes.size()); - for (TSCNode paramNode : typeParamNodes) { - typeParams.add(type(paramNode)); - } - pt.unsafeSet(clazz, typeParams); - return pt; - } else if (!(jt instanceof JavaType.Parameterized)) { - throw new UnsupportedOperationException("this should not have happened."); - } - } - return clazz; - } - - public JavaType.GenericTypeVariable generic(TSCNode node, String signature) { - JavaType.GenericTypeVariable gtv = new JavaType.GenericTypeVariable(null, node.getNodeProperty("name").getText(), INVARIANT, null); - typeCache.put(signature, gtv); - - List bounds = null; - JavaType.GenericTypeVariable.Variance variance = INVARIANT; - - TSCNode constraint = node.getOptionalNodeProperty("constraint"); - if (constraint != null) { - if (constraint.syntaxKind() == TSCSyntaxKind.IntersectionType) { - List types = constraint.getNodeListProperty("types"); - bounds = new ArrayList<>(types.size()); - for (TSCNode type : types) { - bounds.add(type(type)); - } - } else { - bounds = new ArrayList<>(1); - bounds.add(type(constraint)); - } - if (node.getText().contains("extends")) { - variance = COVARIANT; - } else if (node.getText().contains("super")) { - variance = CONTRAVARIANT; - } - } - - gtv.unsafeSet(gtv.getName(), variance, bounds); - return gtv; - } - - public JavaType.@Nullable Method methodDeclarationType(TSCNode node) { - return methodDeclarationType(node, null); - } - - public JavaType.@Nullable Method methodDeclarationType(TSCNode node, JavaType.@Nullable FullyQualified declaringType) { - - String signature = signatureBuilder.methodSignature(node); - JavaType.Method existing = typeCache.get(signature); - if (existing != null) { - return existing; - } - - List paramNames = null; - List defaultValues = null; - - boolean isConstructor = node.syntaxKind() == TSCSyntaxKind.Constructor; - List modifiers = node.getOptionalNodeListProperty("modifiers"); - TSCNode nodeName = node.getOptionalNodeProperty("name"); - JavaType.Method method = new JavaType.Method( - null, - mapModifiers(modifiers), - null, - isConstructor ? "" : nodeName != null ? nodeName.getText() : "{anonymous}", - null, - paramNames, - null, null, null, - defaultValues - ); - typeCache.put(signature, method); - - List exceptionTypes = null; - - JavaType.FullyQualified resolvedDeclaringType = declaringType; - if (declaringType == null) { - resolvedDeclaringType = TypeUtils.asFullyQualified(type(getOwner(node))); - } - - if (resolvedDeclaringType == null) { - return null; - } - - TSCNode returnTypeNode = node.getOptionalNodeProperty("type"); - JavaType returnType = returnTypeNode == null ? null : type(returnTypeNode); - - List parameterTypes = null; - List paramNodes = node.getOptionalNodeListProperty("parameters"); - if (paramNodes != null && !paramNodes.isEmpty()) { - parameterTypes = new ArrayList<>(paramNodes.size()); - for (TSCNode paramNode : paramNodes) { - TSCNode typeNode = paramNode.getOptionalNodeProperty("type"); - if (typeNode == null) { - parameterTypes.add(type(paramNode)); - } else { - parameterTypes.add(type(typeNode)); - } - } - } - - method.unsafeSet(resolvedDeclaringType, - isConstructor ? resolvedDeclaringType : returnType, - parameterTypes, exceptionTypes, mapAnnotations(modifiers)); - return method; - } - - public JavaType.@Nullable Method methodInvocationType(TSCNode node) { - String signature = signatureBuilder.methodSignature(node); - JavaType.Method existing = typeCache.get(signature); - if (existing != null) { - return existing; - } - - boolean isConstructor = node.syntaxKind() == TSCSyntaxKind.Constructor || - node.syntaxKind() == TSCSyntaxKind.ConstructSignature || - node.syntaxKind() == TSCSyntaxKind.NewExpression; - - TSCNode name = node.getOptionalNodeProperty("name"); - List modifiers = node.getOptionalNodeListProperty("modifiers"); - List paramNames = null; - JavaType.Method method = new JavaType.Method( - null, - mapModifiers(modifiers), - null, - isConstructor ? "" : name == null ? "{anonymous}" : name.getText(), - null, - paramNames, - null, null, null, null - ); - typeCache.put(signature, method); - - List arguments = node.getOptionalNodeListProperty("arguments"); - List parameterTypes = null; - if (arguments != null) { - parameterTypes = new ArrayList<>(arguments.size()); - for (TSCNode argument : arguments) { - parameterTypes.add(type(argument)); - } - } - List exceptionTypes = null; - - JavaType.FullyQualified resolvedDeclaringType = null; - if (node.syntaxKind() == TSCSyntaxKind.NewExpression) { - resolvedDeclaringType = (JavaType.FullyQualified) type(node.getNodeProperty("expression")); - } else { - TSCSymbol symbol = node.getTypeChecker().getTypeAtLocation(node).getOptionalSymbolProperty("symbol"); - if (symbol != null) { - JavaType j = type(symbol.getValueDeclaration()); - if (j instanceof JavaType.FullyQualified) { - resolvedDeclaringType = (JavaType.FullyQualified) type(symbol.getValueDeclaration()); - } else { - implementMe(node.syntaxKind()); - } - } else { - resolvedDeclaringType = TsType.MissingSymbol; - } - } - - TSCNode returnNode = node.getOptionalNodeProperty("type"); - JavaType returnType = returnNode == null ? null : type(returnNode); - method.unsafeSet(resolvedDeclaringType, - isConstructor ? resolvedDeclaringType : returnType, - parameterTypes, exceptionTypes, mapAnnotations(modifiers)); - return method; - } - - public JavaType.Primitive primitive(TSCNode node) { - switch (node.syntaxKind()) { - case BigIntKeyword: - case BigIntLiteral: - implementMe(node.syntaxKind()); - case BooleanKeyword: - case FalseKeyword: - case TrueKeyword: - return JavaType.Primitive.Boolean; - case StringKeyword: - return JavaType.Primitive.String; - case NullKeyword: - return JavaType.Primitive.Null; - case NumberKeyword: - case NumericLiteral: - // NOTE: number includes doubles and floats ... - return JavaType.Primitive.Long; - case UnknownKeyword: - return JavaType.Primitive.None; - case VoidKeyword: - return JavaType.Primitive.Void; - default: - implementMe(node.syntaxKind()); - } - return JavaType.Primitive.None; - } - - public JavaType.@Nullable Variable variableType(TSCNode node) { - return variableType(node, null, signatureBuilder.variableSignature(node)); - } - - public JavaType.@Nullable Variable variableType(TSCNode node, String signature) { - return variableType(node, null, signature); - } - - public JavaType.@Nullable Variable variableType(TSCNode node, JavaType.@Nullable FullyQualified declaringType) { - return variableType(node, declaringType, signatureBuilder.variableSignature(node)); - } - - public JavaType.@Nullable Variable variableType(TSCNode node, JavaType.@Nullable FullyQualified declaringType, String signature) { - JavaType.Variable existing = typeCache.get(signature); - if (existing != null) { - return existing; - } - - List modifiers = node.getOptionalNodeListProperty("modifiers"); - JavaType.Variable variable = new JavaType.Variable( - null, - mapModifiers(modifiers), - node.getNodeProperty("name").getText(), - null, null, null); - - typeCache.put(signature, variable); - - List annotations = emptyList(); - - JavaType resolvedOwner = declaringType; - if (resolvedOwner == null) { - resolvedOwner = classType(getOwner(node)); - } - - TSCNode typeNode = node.getOptionalNodeProperty("type"); - JavaType type; - if (typeNode != null) { - type = type(typeNode); - } else { - type = resolveNode(node); - } - - if (resolvedOwner == null || type instanceof JavaType.Unknown) { - return null; - } - - variable.unsafeSet(resolvedOwner, type, annotations); - - return variable; - } - - private @Nullable List mapAnnotations(@Nullable List modifiers) { - if (modifiers == null || modifiers.isEmpty()) { - return null; - } - - List annotationNodes = modifiers.stream() - .filter(n -> n.syntaxKind() == TSCSyntaxKind.Decorator) - .collect(Collectors.toList()); - - List annotations = new ArrayList<>(annotationNodes.size()); - for (TSCNode annotation : annotationNodes) { - annotations.add((JavaType.FullyQualified) type(annotation)); - } - return annotations.isEmpty() ? null : annotations; - } - - private JavaType mapEnumMember(TSCNode node) { - return type(node.getParent()); - } - - private JavaType mapIdentifier(TSCNode node) { - TSCSymbol symbol = node.getTypeChecker().getTypeAtLocation(node).getOptionalSymbolProperty("symbol"); - if (symbol != null) { - List declarations = symbol.getDeclarations(); - if (declarations != null && !declarations.isEmpty()) { - if (declarations.size() == 1) { - return type(declarations.get(0)); - } else { - return TsType.MergedInterface; - } - } else { - implementMe(node.syntaxKind()); - } - } - return mapType(node.getTypeChecker().getTypeAtLocation(node)); - } - - private long mapModifiers(@Nullable List modifiers) { - if (modifiers == null) { - return 0; - } - - Set flags = new HashSet<>(); - for (TSCNode modifier : modifiers) { - switch (modifier.getText()) { - case "public": - flags.add(Flag.Public); - break; - case "private": - flags.add(Flag.Private); - break; - case "protected": - flags.add(Flag.Protected); - break; - case "static": - flags.add(Flag.Static); - break; - case "readonly": - flags.add(Flag.Final); - break; - case "abstract": - flags.add(Flag.Abstract); - break; - case "default": - flags.add(Flag.Default); - break; - case "async": - case "export": - // TODO: get input from Gary ... is there any reason to add export as a modifier to the JavaType? - break; - default: - if (modifier.syntaxKind() != TSCSyntaxKind.Decorator) { - // Decorators are handled separately to ensure the JavaType for a class is cached before type attributing annotations. - implementMe(modifier.syntaxKind()); - } - } - } - - return Flag.flagsToBitMap(flags); - } - - private JavaType mapParameter(TSCNode node) { - return resolveNode(node); - } - - private JavaType mapQualifiedName(TSCNode node) { - return resolveNode(node); - } - - private JavaType mapReference(TSCNode node, String signature) { - JavaType classType = null; - TSCNode name = node.getOptionalNodeProperty("typeName"); - if (name != null) { - classType = type(name); - } - - name = node.getOptionalNodeProperty("exprName"); - if (classType == null && name != null) { - classType = type(name); - } - - if (classType == null) { - classType = type(node.getNodeProperty("expression")); - } - - if (classType instanceof JavaType.Parameterized) { - classType = ((JavaType.Parameterized) classType).getType(); - } - - List typeArguments = node.getOptionalNodeListProperty("typeArguments"); - if (typeArguments == null) { - typeCache.put(signature, classType); - return classType; - } else { - JavaType fq = TypeUtils.asFullyQualified(classType); - assert fq != null; - - JavaType.Parameterized pt = new JavaType.Parameterized(null, null, null); - typeCache.put(signature, pt); - List params = new ArrayList<>(typeArguments.size()); - for (TSCNode typeArg : typeArguments) { - params.add(type(typeArg)); - } - pt.unsafeSet(TypeUtils.asFullyQualified(classType), params); - return pt; - } - } - - private JavaType mapSourceFileFqn(String signature) { - JavaType sourceClass = JavaType.ShallowClass.build(signature); - typeCache.put(signature, sourceClass); - return sourceClass; - } - - private JavaType mapThis(TSCNode node) { - return resolveNode(node); - } - - private JavaType mapTypeOperator(TSCNode node) { - return type(node.getNodeProperty("type")); - } - - private JavaType mapType(TSCType type) { - TSCTypeFlag flag = null; - try { - flag = type.getExactTypeFlag(); - } catch (Exception ignored) { - } - - if (flag != null) { - switch (flag) { - case Any: - return TsType.Any; - case Boolean: - case BooleanLiteral: - return JavaType.Primitive.Boolean; - case Number: - case NumberLiteral: - return TsType.Number; - case Null: - return JavaType.Primitive.Null; - case Object: - return TsType.Anonymous; - case String: - case StringLiteral: - return JavaType.Primitive.String; - case Undefined: - return TsType.Undefined; - case Union: - return TsType.Union; - case Unit: - return TsType.Unit; - case Unknown: - return TsType.Unknown; - case Void: - return JavaType.Primitive.Void; - case Enum: - return TsType.Enum; - case EnumLiteral: - return TsType.EnumLiteral; - case BigInt: - return TsType.BigInt; - case BigIntLiteral: - return TsType.BigIntLiteral; - case ESSymbol: - return TsType.ESSymbol; - case UniqueESSymbol: - return TsType.UniqueESSymbol; - case Never: - return TsType.Never; - case TypeParameter: - return TsType.TypeParameter; - case Intersection: - return TsType.Intersection; - case Index: - return TsType.Index; - case IndexedAccess: - return TsType.IndexedAccess; - case Conditional: - return TsType.Conditional; - case Substitution: - return TsType.Substitution; - case NonPrimitive: - return TsType.NonPrimitive; - case TemplateLiteral: - return TsType.TemplateLiteral; - case StringMapping: - return TsType.StringMapping; - case AnyOrUnknown: - return TsType.AnyOrUnknown; - case Nullable: - return TsType.Nullable; - case Literal: - return TsType.Literal; - case Freshable: - return TsType.Freshable; - case StringOrNumberLiteral: - return TsType.StringOrNumberLiteral; - case StringOrNumberLiteralOrUnique: - return TsType.StringOrNumberLiteralOrUnique; - case DefinitelyFalsy: - return TsType.DefinitelyFalsy; - case PossiblyFalsy: - return TsType.PossiblyFalsy; - case Intrinsic: - return TsType.Intrinsic; - case Primitive: - return TsType.Primitive; - case StringLike: - return TsType.StringLike; - case NumberLike: - return TsType.NumberLike; - case BigIntLike: - return TsType.BigIntLike; - case BooleanLike: - return TsType.BooleanLike; - case EnumLike: - return TsType.EnumLike; - case ESSymbolLike: - return TsType.ESSymbolLike; - case VoidLike: - return TsType.VoidLike; - case DefinitelyNonNullable: - return TsType.DefinitelyNonNullable; - case DisjointDomains: - return TsType.DisjointDomains; - case UnionOrIntersection: - return TsType.UnionOrIntersection; - case StructuredType: - return TsType.StructuredType; - case TypeVariable: - return TsType.TypeVariable; - case InstantiableNonPrimitive: - return TsType.InstantiableNonPrimitive; - case InstantiablePrimitive: - return TsType.InstantiablePrimitive; - case Instantiable: - return TsType.Instantiable; - case StructuredOrInstantiable: - return TsType.StructuredOrInstantiable; - case ObjectFlagsType: - return TsType.ObjectFlagsType; - case Simplifiable: - return TsType.Simplifiable; - case Singleton: - return TsType.Singleton; - case Narrowable: - return TsType.Narrowable; - case IncludesMask: - return TsType.IncludesMask; - case NotPrimitiveUnion: - return TsType.NotPrimitiveUnion; - default: - implementMe(type); - break; - } - } else { - TSCObjectFlag objectFlag = TSCObjectFlag.fromMaskExact(type.getObjectFlags()); - if (objectFlag == TSCObjectFlag.PrimitiveUnion) { - return TsType.PrimitiveUnion; - } else { - implementMe(type); - } - } - return null; - } - - private TSCNode getOwner(TSCNode node) { - TSCNode parent = node.getParent(); - if (parent == null) { - return node; - } else if (parent.syntaxKind() == TSCSyntaxKind.SourceFile || - parent.syntaxKind() == TSCSyntaxKind.ClassDeclaration || - parent.syntaxKind() == TSCSyntaxKind.EnumDeclaration || - parent.syntaxKind() == TSCSyntaxKind.InterfaceDeclaration || - parent.syntaxKind() == TSCSyntaxKind.MethodDeclaration) { - return parent; - } else { - return getOwner(node.getParent()); - } - } - - private JavaType resolveNode(TSCNode node) { - TSCSymbol symbol = node.getTypeChecker().getTypeAtLocation(node).getOptionalSymbolProperty("symbol"); - if (symbol != null) { - try { - return type(symbol.getValueDeclaration()); - } catch (Exception ignored) { - } - } - return mapType(node.getTypeChecker().getTypeAtLocation(node)); - } - - private void implementMe(TSCSyntaxKind syntaxKind) { - throw new UnsupportedOperationException(syntaxKind.name() + " syntaxKind is not supported in TypeMapping."); - } - - private void implementMe(TSCType type) { - throw new UnsupportedOperationException(type.typeToString() + " type is not supported in TypeMapping."); - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/JavetNativeBridge.java b/src/main/java/org/openrewrite/javascript/internal/JavetNativeBridge.java deleted file mode 100644 index 63c85fc9..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/JavetNativeBridge.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal; - -import com.caoccao.javet.enums.JSRuntimeType; -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.interop.loader.JavetLibLoader; -import com.caoccao.javet.utils.JavetOSUtils; -import org.jspecify.annotations.Nullable; -import org.openrewrite.internal.StringUtils; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.nio.file.Files; -import java.util.Arrays; -import java.util.List; -import java.util.stream.Collectors; - -public class JavetNativeBridge { - - private JavetNativeBridge() { - } - - private static volatile boolean hasLoadedNativeLib = false; - private static volatile @Nullable Throwable nativeLibError = null; - private static final Object loadNativeLibLock = new Object(); - - public static Class[] getClassesInitializedByBridge() { - return new Class[]{ - JavetNativeBridge.class, - JavetLibLoader.class, - JavetOSUtils.class, - JSRuntimeType.class, - StringUtils.class - }; - } - - public static String[] getPackagesInitializedByBridge() { - return new String[]{ - "com.caoccao.javet.interop", - "com.caoccao.javet.interop.loader", - "com.caoccao.javet.values.reference", - "com.caoccao.javet.enums", - "com.caoccao.javet.utils", - "com.caoccao.javet.exceptions" - }; - } - - public static String getLibResourcePath() { - try { - return "/" + new JavetLibLoader(JSRuntimeType.V8).getLibFileName(); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - public static List getJavetClassNamesUsedByJNI() { - try (InputStream is = JavetNativeBridge.class.getResourceAsStream("/javet-jni-classnames.txt")) { - if (is == null) { - throw new IllegalStateException("javet-jni-classnames.txt does not exist"); - } - return Arrays.stream(StringUtils.readFully(is).split("\n")) - .filter(name -> !name.isEmpty()) - .collect(Collectors.toList()); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public static void init() { - if (!hasLoadedNativeLib) { - synchronized (loadNativeLibLock) { - if (!hasLoadedNativeLib) { - hasLoadedNativeLib = true; - actuallyInit(); - } - } - } - if (nativeLibError != null) { - throw new RuntimeException("error while loading Javet library", nativeLibError); - } - } - - private static void actuallyInit() { - String nativeLibPath = getLibResourcePath(); - File tempFile = null; - if (System.getProperty("org.graalvm.nativeimage.kind") != null) { - try { - try { - tempFile = Files.createTempFile("libjavet", "").toFile(); - } catch (IOException e) { - throw new RuntimeException("error while creating temp file to extract Javet native library", e); - } - - try ( - InputStream inputStream = JavetLibLoader.class.getResourceAsStream(nativeLibPath); - FileOutputStream outputStream = new FileOutputStream(tempFile) - ) { - if (inputStream == null) { - throw new IllegalStateException("Could not find bundled resource for " + nativeLibPath); - } - byte[] buffer = new byte[4096]; - while (true) { - int length = inputStream.read(buffer); - if (length == -1) { - break; - } - outputStream.write(buffer, 0, length); - } - if (JavetOSUtils.IS_LINUX || JavetOSUtils.IS_MACOS || JavetOSUtils.IS_ANDROID) { - try { - final int result = Runtime.getRuntime().exec(new String[]{"chmod", "755", tempFile.getAbsolutePath()}).waitFor(); - if (result != 0) { - throw new RuntimeException("attempt to chmod Javet library resulted in " + result); - } - } catch (Throwable t) { - throw new RuntimeException("error while chmod-ing extracted Javet library (" + nativeLibPath + ")", t); - } - } - } - - System.load(tempFile.getAbsolutePath()); - } catch (Throwable t) { - System.err.println("Javet debugging information:"); - System.err.printf(" OS arch: %s%n", JavetOSUtils.OS_ARCH); - System.err.printf(" OS name: %s%n", JavetOSUtils.OS_NAME); - System.err.printf(" lib name: %s%n", nativeLibPath); - if (tempFile != null) { - try { - System.err.printf(" tmp path: %s%n", tempFile.getAbsolutePath()); - System.err.printf(" tmp exists: %s%n", tempFile.exists()); - System.err.printf(" tmp size: %s%n", tempFile.length()); - } catch (Throwable ignored) { - } - } - - t.printStackTrace(); - nativeLibError = t; - } - } - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/JavetUtils.java b/src/main/java/org/openrewrite/javascript/internal/JavetUtils.java deleted file mode 100644 index 6f8a54db..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/JavetUtils.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal; - -import com.caoccao.javet.values.IV8Value; -import org.jspecify.annotations.Nullable; - -public class JavetUtils { - private JavetUtils() {} - - public static void close(@Nullable IV8Value valueV8) { - if (valueV8 != null && !valueV8.isClosed()) { - try { - valueV8.close(); - } catch (Exception e) { - System.err.println("Error while attempting to close V8 value: " + e); - e.printStackTrace(); - } - } - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/TsTreePrinter.java b/src/main/java/org/openrewrite/javascript/internal/TsTreePrinter.java deleted file mode 100644 index 4e600d59..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/TsTreePrinter.java +++ /dev/null @@ -1,496 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal; - -import lombok.AllArgsConstructor; -import lombok.Data; -import org.jspecify.annotations.Nullable; -import org.openrewrite.*; -import org.openrewrite.java.tree.*; -import org.openrewrite.javascript.internal.tsc.TSCNode; -import org.openrewrite.javascript.internal.tsc.TSCSourceFileContext; -import org.openrewrite.javascript.internal.tsc.generated.TSCSyntaxKind; - -import java.util.*; -import java.util.stream.Collectors; - -import static java.util.stream.StreamSupport.stream; - -@SuppressWarnings({"unused", "DuplicatedCode", "SameParameterValue"}) -public class TsTreePrinter { - - private static final String TAB = " "; - private static final String ELEMENT_PREFIX = "\\---"; - private static final char BRANCH_CONTINUE_CHAR = '|'; - private static final char BRANCH_END_CHAR = '\\'; - private static final int CONTENT_MAX_LENGTH = 200; - - private static final String CONTINUE_PREFIX = "----"; - private static final String UNVISITED_PREFIX = "#"; - - // Set to true to print types and verify, otherwise just verify the parse to print idempotent. - private final static boolean printTypes = true; - - private final List outputLines; - - protected TsTreePrinter() { - outputLines = new ArrayList<>(); - } - - public static String print(Parser.Input input) { - return printIndexedSourceCode(input.getSource(new InMemoryExecutionContext()).readFully()); - } - - public static String print(Tree tree) { - return "------------\nJ Tree\n" + printJTree(tree); - } - - public static String print(TSCNode node, TSCSourceFileContext context, boolean printSpace) { - return printTSTree(node, context, printSpace); - } - - @AllArgsConstructor - @Data - public static class TreePrinterContext { - List lines; - int depth; - } - - public static String printTSTree(TSCNode node, TSCSourceFileContext context, boolean printSpace) { - TsTreePrinter treePrinter = new TsTreePrinter(); - StringBuilder sb = new StringBuilder(); - sb.append("------------").append("\n"); - sb.append("TS tree").append("\n"); - if (printSpace) { - treePrinter.printBeforeFirstNode(node, 0, context); - } - treePrinter.printTSCNode(node, 1, context, printSpace); - sb.append(String.join("\n", treePrinter.outputLines)); - context.resetScanner(0); - return sb.toString(); - } - - private void printBeforeFirstNode(TSCNode node, int depth, TSCSourceFileContext context) { - if (node.getStart() == 0) { - return; - } - - StringBuilder line = new StringBuilder(); - context.resetScanner(0); - int stop = node.getStart(); - while (true) { - TSCSyntaxKind kind = context.nextScannerSyntaxType(); - String text = context.scannerTokenText(); - int start = context.scannerTokenStart(); - int end = context.scannerTokenEnd(); - if (end > stop || kind == TSCSyntaxKind.EndOfFileToken) { - break; - } - - StringBuilder subLine = new StringBuilder(); - subLine.append(leftPadding(depth + 1)) - .append("[") - .append(start) - .append(",").append(end) - .append(")") - .append(" | ") - .append("* ") - .append(kind).append(" | Text : \"") - .append(truncate(text).replace("\n", "\\n").replace("\r", "\\r")) - .append("\""); - connectToLatestSibling(depth + 1); - outputLines.add(subLine); - } - } - - private void printTSCNode(TSCNode node, int depth, TSCSourceFileContext context, boolean printSpace) { - StringBuilder line = new StringBuilder(); - line.append(leftPadding(depth)) - .append(toString(node)); - connectToLatestSibling(depth); - outputLines.add(line); - List tscNodes = node.getAllChildNodes(); - - for ( int i = 0; i < tscNodes.size(); i++) { - TSCNode childNode = tscNodes.get(i); - TSCNode nextChildNode = i < tscNodes.size() - 1 ? tscNodes.get(i + 1) : null; - boolean hasGap = nextChildNode != null && nextChildNode.getStart() > childNode.getEnd(); - printTSCNode(childNode, depth + 1, context, printSpace); - - if (printSpace && hasGap) { - context.resetScanner(childNode.getEnd()); - int stop = nextChildNode.getStart(); - while (true) { - TSCSyntaxKind kind = context.nextScannerSyntaxType(); - String text = context.scannerTokenText(); - int start = context.scannerTokenStart(); - int end = context.scannerTokenEnd(); - if (end > stop || kind == TSCSyntaxKind.EndOfFileToken) { - break; - } - - StringBuilder subLine = new StringBuilder(); - subLine.append(leftPadding(depth + 1)) - .append("[") - .append(start) - .append(",").append(end) - .append(")") - .append(" | ") - .append("* ") - .append(kind).append(" | Text : \"") - .append(truncate(text).replace("\n", "\\n").replace("\r", "\\r")) - .append("\""); - connectToLatestSibling(depth + 1); - outputLines.add(subLine); - } - } - } - } - - private static String toString(TSCNode node) { - return "[" + node.getStart() + "," + node.getEnd() + ")" + " | " + node.syntaxKind().name() + " | Text : \"" + - truncate(node.getText()).replace("\n", "\\n").replace("\r", "\\r") + "\""; - } - - /** - * print J tree with all types - */ - @SuppressWarnings("rawtypes") - static class TreeVisitingPrinter extends TreeVisitor { - private List lastCursorStack; - private final List outputLines; - private final boolean skipUnvisitedElement; - private final boolean printContent; - - public TreeVisitingPrinter(boolean skipUnvisitedElement, boolean printContent) { - lastCursorStack = new ArrayList<>(); - outputLines = new ArrayList<>(); - this.skipUnvisitedElement = skipUnvisitedElement; - this.printContent = printContent; - } - - public String print() { - return String.join("\n", outputLines); - } - - @Override - public @Nullable Tree visit(@Nullable Tree tree, ExecutionContext ctx) { - if (tree == null) { - return super.visit((Tree) null, ctx); - } - - Cursor cursor = this.getCursor(); - List cursorStack = - stream(Spliterators.spliteratorUnknownSize(cursor.getPath(), 0), false) - .collect(Collectors.toList()); - Collections.reverse(cursorStack); - int depth = cursorStack.size(); - - // Compare lastCursorStack vs cursorStack, find the fork and print the diff - int diffPos = -1; - for (int i = 0; i < cursorStack.size(); i++) { - if (i >= lastCursorStack.size() || cursorStack.get(i) != lastCursorStack.get(i)) { - diffPos = i; - break; - } - } - - StringBuilder line = new StringBuilder(); - - // print cursor stack diff - if (diffPos >= 0) { - for (int i = diffPos; i < cursorStack.size(); i++) { - Object element = cursorStack.get(i); - if (skipUnvisitedElement) { - // skip unvisited elements, just print indents in the line - if (i == diffPos) { - line.append(leftPadding(i)); - connectToLatestSibling(i, outputLines); - } else { - line.append(CONTINUE_PREFIX); - } - } else { - // print each unvisited element to a line - connectToLatestSibling(i, outputLines); - StringBuilder newLine = new StringBuilder() - .append(leftPadding(i)) - .append(UNVISITED_PREFIX) - .append(element instanceof String ? element : element.getClass().getSimpleName()); - - if (element instanceof JRightPadded) { - JRightPadded rp = (JRightPadded) element; - newLine.append(" | "); - newLine.append(" after = ").append(printSpace(rp.getAfter())); - } - - if (element instanceof JLeftPadded) { - JLeftPadded lp = (JLeftPadded) element; - newLine.append(" | "); - newLine.append(" before = ").append(printSpace(lp.getBefore())); - } - - outputLines.add(newLine); - } - } - } - - // print current visiting element - String typeName = tree instanceof J ? - tree.getClass().getCanonicalName().substring(tree.getClass().getPackage().getName().length() + 1) : - tree.getClass().getCanonicalName(); - - if (skipUnvisitedElement) { - boolean leftPadded = diffPos >= 0; - if (leftPadded) { - line.append(CONTINUE_PREFIX); - } else { - connectToLatestSibling(depth, outputLines); - line.append(leftPadding(depth)); - } - line.append(typeName); - } else { - connectToLatestSibling(depth, outputLines); - line.append(leftPadding(depth)).append(typeName); - } - - String type = printType(tree); - if (printTypes && !type.isEmpty()) { - line.append(" | TYPE = ").append(type); - } - - if (printContent) { - String content = truncate(printTreeElement(tree)); - if (!content.isEmpty()) { - line.append(" | \"").append(content).append("\""); - } - } - - outputLines.add(line); - - cursorStack.add(tree); - lastCursorStack = cursorStack; - return super.visit(tree, ctx); - } - } - - private static String printType(Tree tree) { - StringBuilder sb = new StringBuilder(); - if (tree instanceof TypedTree) { - JavaType type = ((TypedTree) tree).getType(); - if (type != null && !(type instanceof JavaType.Unknown)) { - sb.append(type); - } - } - - if (tree instanceof J.MethodInvocation) { - J.MethodInvocation m = (J.MethodInvocation) tree; - if (m.getMethodType() != null) { - sb.append(" MethodType = ").append(m.getMethodType()); - } - } - - if (tree instanceof J.MethodDeclaration) { - J.MethodDeclaration m = (J.MethodDeclaration) tree; - if (m.getMethodType() != null) { - sb.append(" MethodType = ").append(m.getMethodType()); - } - } - - if (tree instanceof J.VariableDeclarations.NamedVariable) { - J.VariableDeclarations.NamedVariable v = (J.VariableDeclarations.NamedVariable) tree; - if (v.getVariableType() != null) { - sb.append(" VariableType = ").append(v.getVariableType()); - } - } - - if (tree instanceof J.Identifier) { - J.Identifier id = (J.Identifier) tree; - if (id.getFieldType() != null) { - sb.append(" FieldType = ").append(id.getFieldType()); - } - } - - return sb.toString(); - } - - private static String printTreeElement(Tree tree) { - // skip some specific types printed in the output to make the output looks clean - if (tree instanceof J.CompilationUnit || - tree instanceof J.ClassDeclaration || - tree instanceof J.Block || - tree instanceof J.Empty || - tree instanceof J.Try || - tree instanceof J.Try.Catch || - tree instanceof J.ForLoop || - tree instanceof J.WhileLoop || - tree instanceof J.DoWhileLoop || - tree instanceof J.Lambda || - tree instanceof J.Lambda.Parameters || - tree instanceof J.If || - tree instanceof J.If.Else || - tree instanceof J.EnumValueSet || - tree instanceof J.TypeParameter || - tree instanceof J.Package || - tree instanceof J.ForEachLoop - ) { - return ""; - } - - if (tree instanceof J.Literal) { - String s = ((J.Literal) tree).getValueSource(); - return s != null ? s : ""; - } - - String[] lines = tree.toString().split("\n"); - StringBuilder output = new StringBuilder(); - for (int i = 0; i < lines.length; i++) { - output.append(lines[i].trim()); - if (i < lines.length - 1) { - output.append(" "); - } - } - return output.toString(); - } - - private static String printSpace(Space space) { - String sb = " whitespace=\"" + - space.getWhitespace() + "\"" + - " comments=\"" + - space.getComments().stream().map(c -> c.printComment(new Cursor(null, "root"))).collect(Collectors.joining(",")) + - "\""; - return sb.replace("\n", "\\s\n"); - } - - public static String printJTree(Tree tree) { - TreeVisitingPrinter visitor = new TreeVisitingPrinter(true, true); - visitor.visit(tree, new InMemoryExecutionContext()); - return visitor.print(); - } - - public static String printIndexedSourceCode(String sourceCode) { - int count = 0; - String[] lines = sourceCode.split("\n"); - StringBuilder sb = new StringBuilder(); - sb.append("------------").append("\n"); - sb.append("Source code with index:").append("\n\n"); - Queue digits = new ArrayDeque<>(); - - for (String line : lines) { - StringBuilder spacesSb = new StringBuilder(); - for (int i = 0; i < line.length(); i++) { - if (count % 10 == 0) { - String numStr = Integer.toString(count); - for (int j = 0; j < numStr.length(); j++) { - char c = numStr.charAt(j); - int digit = Character.getNumericValue(c); - digits.add(digit); - } - } - - if (!digits.isEmpty()) { - spacesSb.append(digits.poll()) ; - } else { - spacesSb.append(" "); - } - - count++; - } - - sb.append(line) - .append("\n") - .append(spacesSb) - .append("\n"); - count++; - } - return sb.toString(); - } - - /** - * print left padding for a line - * @param depth, depth starts from 0 (the root) - */ - private static String leftPadding(int depth) { - StringBuilder sb = new StringBuilder(); - int tabCount = depth - 1; - if (tabCount > 0) { - sb.append(String.join("", Collections.nCopies(tabCount, TAB))); - } - // only root has not prefix - if (depth > 0) { - sb.append(ELEMENT_PREFIX); - } - return sb.toString(); - } - - /** - * Print a vertical line that connects the current element to the latest sibling. - * @param depth current element depth - */ - private void connectToLatestSibling(int depth) { - if (depth <= 1) { - return; - } - - int pos = (depth - 1) * TAB.length(); - for (int i = outputLines.size() - 1; i > 0; i--) { - StringBuilder line = outputLines.get(i); - if (pos >= line.length()) { - break; - } - - if (line.charAt(pos) != ' ') { - if (line.charAt(pos) == BRANCH_END_CHAR) { - line.setCharAt(pos, BRANCH_CONTINUE_CHAR); - } - break; - } - line.setCharAt(pos, BRANCH_CONTINUE_CHAR); - } - } - - /** - * Print a vertical line that connects the current element to the latest sibling. - * @param depth current element depth - */ - private static void connectToLatestSibling(int depth, List lines) { - if (depth <= 1) { - return; - } - - int pos = (depth - 1) * TAB.length(); - for (int i = lines.size() - 1; i > 0; i--) { - StringBuilder line = lines.get(i); - if (pos >= line.length()) { - break; - } - - if (line.charAt(pos) != ' ') { - if (line.charAt(pos) == BRANCH_END_CHAR) { - line.setCharAt(pos, BRANCH_CONTINUE_CHAR); - } - break; - } - line.setCharAt(pos, BRANCH_CONTINUE_CHAR); - } - } - - private static String truncate(String content) { - if (content.length() > CONTENT_MAX_LENGTH) { - return content.substring(0, CONTENT_MAX_LENGTH - 3) + "..."; - } - return content; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/TypeScriptParserVisitor.java b/src/main/java/org/openrewrite/javascript/internal/TypeScriptParserVisitor.java deleted file mode 100644 index a8651f85..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/TypeScriptParserVisitor.java +++ /dev/null @@ -1,3542 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal; - -import org.jspecify.annotations.Nullable; -import org.openrewrite.FileAttributes; -import org.openrewrite.ParseExceptionResult; -import org.openrewrite.java.internal.JavaTypeCache; -import org.openrewrite.java.marker.Semicolon; -import org.openrewrite.java.marker.TrailingComma; -import org.openrewrite.java.tree.*; -import org.openrewrite.javascript.JavaScriptParser; -import org.openrewrite.javascript.TypeScriptTypeMapping; -import org.openrewrite.javascript.internal.tsc.TSCNode; -import org.openrewrite.javascript.internal.tsc.TSCNodeList; -import org.openrewrite.javascript.internal.tsc.TSCSourceFileContext; -import org.openrewrite.javascript.internal.tsc.generated.TSCSyntaxKind; -import org.openrewrite.javascript.markers.*; -import org.openrewrite.javascript.tree.JS; -import org.openrewrite.javascript.tree.TsType; -import org.openrewrite.marker.Markers; -import org.openrewrite.style.NamedStyles; - -import java.nio.file.Path; -import java.util.*; -import java.util.function.Function; - -import static java.util.Collections.emptyList; -import static java.util.Collections.singletonList; -import static org.openrewrite.Tree.randomId; -import static org.openrewrite.java.tree.Space.EMPTY; - -@SuppressWarnings({"DataFlowIssue", "SameParameterValue"}) -public class TypeScriptParserVisitor { - - private final TSCNode source; - private final String sourceText; - private final TSCSourceFileContext cursorContext; - private final Path sourcePath; - private final TypeScriptTypeMapping typeMapping; - - private final String charset; - private final boolean isCharsetBomMarked; - private final Collection styles; - - public TypeScriptParserVisitor(TSCNode source, TSCSourceFileContext sourceContext, Path sourcePath, JavaTypeCache typeCache, String charset, boolean isCharsetBomMarked, Collection styles) { - this.source = source; - this.sourceText = source.getOptionalStringProperty("text"); - this.cursorContext = sourceContext; - this.sourcePath = sourcePath; - this.charset = charset; - this.isCharsetBomMarked = isCharsetBomMarked; - this.styles = styles; - this.typeMapping = new TypeScriptTypeMapping(typeCache); - } - - public JS.CompilationUnit visitSourceFile() { - TSCNodeList statementList = source.getNodeListProperty("statements"); - List> statements = new ArrayList<>(statementList.size()); - Space prefix = whitespace(); - for (TSCNode child : statementList) { - @Nullable J visited; - int saveCursor = getCursor(); - try { - visited = visitNode(child); - } catch (Throwable t) { - cursor(saveCursor); - Space childPrefix = whitespace(); - String text = child.getText(); - skip(text); - Markers childMarkers = Markers.build(singletonList(ParseExceptionResult.build(JavaScriptParser.builder().build(), t) - .withTreeType(child.syntaxKind().name()))); - visited = new J.Unknown( - randomId(), - childPrefix, - Markers.EMPTY, - new J.Unknown.Source( - randomId(), - EMPTY, - childMarkers, - text)); - } - - if (visited != null) { - if (!(visited instanceof Statement) && visited instanceof Expression) { - visited = new JS.ExpressionStatement(randomId(), (Expression) visited); - } - statements.add(maybeSemicolon((Statement) visited)); - } - } - - Space eof = whitespace(); - String remainingWhitespace = ""; - if (getCursor() < sourceText.length()) { - remainingWhitespace = sourceText.substring(getCursor()); - } - - eof = eof.withWhitespace(eof.getWhitespace() + remainingWhitespace); - return new JS.CompilationUnit( - randomId(), - prefix, - Markers.build(styles), - sourcePath, - FileAttributes.fromPath(sourcePath), - charset, - isCharsetBomMarked, - null, - emptyList(), - statements, - eof - ); - } - - private J.Assignment visitAssignment(TSCNode node) { - Space prefix = whitespace(); - Expression left = (Expression) visitNode(node.getNodeProperty("left")); - Space before = sourceBefore(TSCSyntaxKind.EqualsToken); - J j = visitNode(node.getNodeProperty("right")); - if (!(j instanceof Expression) && j instanceof Statement) { - j = new JS.StatementExpression(randomId(), (Statement) j); - } - return new J.Assignment( - randomId(), - prefix, - Markers.EMPTY, - left, - padLeft(before, (Expression) j), - typeMapping.type(node) - ); - } - - private J.AssignmentOperation visitAssignmentOperation(TSCNode node) { - Space prefix = whitespace(); - Expression left = (Expression) visitNode(node.getNodeProperty("left")); - JLeftPadded op = null; - TSCSyntaxKind opKind = node.getNodeProperty("operatorToken").syntaxKind(); - switch (opKind) { - case AsteriskEqualsToken: - op = padLeft(sourceBefore(TSCSyntaxKind.AsteriskEqualsToken), J.AssignmentOperation.Type.Multiplication); - break; - case MinusEqualsToken: - op = padLeft(sourceBefore(TSCSyntaxKind.MinusEqualsToken), J.AssignmentOperation.Type.Subtraction); - break; - case PercentEqualsToken: - op = padLeft(sourceBefore(TSCSyntaxKind.PercentEqualsToken), J.AssignmentOperation.Type.Modulo); - break; - case PlusEqualsToken: - op = padLeft(sourceBefore(TSCSyntaxKind.PlusEqualsToken), J.AssignmentOperation.Type.Addition); - break; - case SlashEqualsToken: - op = padLeft(sourceBefore(TSCSyntaxKind.SlashEqualsToken), J.AssignmentOperation.Type.Division); - break; - default: - implementMe(node); - } - - Expression right = (Expression) visitNode(node.getNodeProperty("right")); - return new J.AssignmentOperation( - randomId(), - prefix, - Markers.EMPTY, - left, - op, - right, - typeMapping.type(node) - ); - } - - private J visitArrayBindingPattern(TSCNode node) { - return unknown(node); - } - - private J visitArrowFunction(TSCNode node) { - implementMe(node, "typeParameters"); - implementMe(node, "typeArguments"); - - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - - List leading = new ArrayList<>(); - List trailing = new ArrayList<>(); - List modifiers = mapModifiers(node.getOptionalNodeListProperty("modifiers"), leading, trailing); - if (!trailing.isEmpty()) { - throw new UnsupportedOperationException("Add support for trailing annotations on: " + node.getText()); - } - - int saveCursor = getCursor(); - Space before = whitespace(); - TSCSyntaxKind next = scan(); - boolean parenthesized = next == TSCSyntaxKind.OpenParenToken; - if (!parenthesized) { - before = EMPTY; - cursor(saveCursor); - } - - List paramNodes = node.getNodeListProperty("parameters"); - J.Lambda.Parameters params = new J.Lambda.Parameters( - randomId(), - before, - Markers.EMPTY, - parenthesized, - paramNodes.isEmpty() ? singletonList(padRight(new J.Empty(randomId(), EMPTY, Markers.EMPTY), parenthesized ? sourceBefore(TSCSyntaxKind.CloseParenToken) : EMPTY)) : - convertAll(node.getNodeListProperty("parameters"), commaDelim, parenthesized ? t -> sourceBefore(TSCSyntaxKind.CloseParenToken) : noDelim, true) - ); - - TSCNode typeNode = node.getOptionalNodeProperty("type"); - TypeTree returnTypeExpression = null; - if (typeNode != null) { - markers = markers.addIfAbsent(new TypeReferencePrefix(randomId(), sourceBefore(TSCSyntaxKind.ColonToken))); - returnTypeExpression = (TypeTree) visitNode(typeNode); - } - - return new JS.ArrowFunction( - randomId(), - prefix, - markers, - leading.isEmpty() ? emptyList() : leading, - modifiers, - params, - returnTypeExpression, - sourceBefore(TSCSyntaxKind.EqualsGreaterThanToken), - visitNode(node.getOptionalNodeProperty("body")), - typeMapping.type(node) - ); - } - - private J.NewArray visitArrayLiteralExpression(TSCNode node) { - Space prefix = whitespace(); - - JContainer jContainer = mapContainer( - TSCSyntaxKind.OpenBracketToken, - node.getNodeListProperty("elements"), - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.CloseBracketToken, - this::visitNode, - true - ); - List> elements = new ArrayList<>(jContainer.getElements().size()); - for (JRightPadded jjRightPadded : jContainer.getPadding().getElements()) { - Expression exp = (!(jjRightPadded.getElement() instanceof Expression) && jjRightPadded.getElement() instanceof Statement) ? - new JS.StatementExpression(randomId(), (Statement) jjRightPadded.getElement()) : (Expression) jjRightPadded.getElement(); - JRightPadded apply = padRight(exp, jjRightPadded.getAfter(), jjRightPadded.getMarkers()); - elements.add(apply); - } - JContainer arguments = JContainer.build(jContainer.getBefore(), elements, jContainer.getMarkers()); - - return new J.NewArray( - randomId(), - prefix, - Markers.EMPTY, - null, - emptyList(), - arguments, - typeMapping.type(node) - ); - } - - private J.TypeCast visitAsExpression(TSCNode node) { - Space prefix = whitespace(); - Expression nameExpr = (Expression) visitNode(node.getNodeProperty("expression")); - Space asPrefix = sourceBefore(TSCSyntaxKind.AsKeyword); - TypeTree type = visitIdentifier(node.getNodeProperty("type")); - - J.ControlParentheses control = new J.ControlParentheses<>( - randomId(), - asPrefix, - Markers.EMPTY, - padRight(type, whitespace()) - ); - - return new J.TypeCast( - randomId(), - prefix, - Markers.EMPTY, - control, - nameExpr - ); - } - - private J visitBinary(TSCNode node) { - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - Expression left = (Expression) visitNode(node.getNodeProperty("left")); - - Space opPrefix = whitespace(); - JLeftPadded op = null; - JLeftPadded jsOp = null; - TSCSyntaxKind opKind = node.getNodeProperty("operatorToken").syntaxKind(); - switch (opKind) { - // Bitwise ops - case AmpersandToken: - consumeToken(TSCSyntaxKind.AmpersandToken); - op = padLeft(opPrefix, J.Binary.Type.BitAnd); - break; - case BarToken: - consumeToken(TSCSyntaxKind.BarToken); - op = padLeft(opPrefix, J.Binary.Type.BitOr); - break; - case CaretToken: - consumeToken(TSCSyntaxKind.CaretToken); - op = padLeft(opPrefix, J.Binary.Type.BitXor); - break; - case GreaterThanGreaterThanToken: - consumeToken(TSCSyntaxKind.GreaterThanToken); - consumeToken(TSCSyntaxKind.GreaterThanToken); - op = padLeft(opPrefix, J.Binary.Type.RightShift); - break; - case LessThanLessThanToken: - consumeToken(TSCSyntaxKind.LessThanLessThanToken); - op = padLeft(opPrefix, J.Binary.Type.LeftShift); - break; - // Logical ops - case AmpersandAmpersandToken: - consumeToken(TSCSyntaxKind.AmpersandAmpersandToken); - op = padLeft(opPrefix, J.Binary.Type.And); - break; - case CommaToken: - markers = markers.addIfAbsent(new Comma(randomId())); - consumeToken(TSCSyntaxKind.CommaToken); - op = padLeft(opPrefix, J.Binary.Type.Or); - break; - case BarBarToken: - consumeToken(TSCSyntaxKind.BarBarToken); - op = padLeft(opPrefix, J.Binary.Type.Or); - break; - case EqualsEqualsToken: - consumeToken(TSCSyntaxKind.EqualsEqualsToken); - op = padLeft(opPrefix, J.Binary.Type.Equal); - break; - case ExclamationEqualsToken: - consumeToken(TSCSyntaxKind.ExclamationEqualsToken); - op = padLeft(opPrefix, J.Binary.Type.NotEqual); - break; - case GreaterThanToken: - consumeToken(TSCSyntaxKind.GreaterThanToken); - op = padLeft(opPrefix, J.Binary.Type.GreaterThan); - break; - case GreaterThanEqualsToken: - consumeToken(TSCSyntaxKind.GreaterThanToken); - consumeToken(TSCSyntaxKind.EqualsToken); - op = padLeft(opPrefix, J.Binary.Type.GreaterThanOrEqual); - break; - case GreaterThanGreaterThanGreaterThanToken: - consumeToken(TSCSyntaxKind.GreaterThanToken); - consumeToken(TSCSyntaxKind.GreaterThanToken); - consumeToken(TSCSyntaxKind.GreaterThanToken); - op = padLeft(opPrefix, J.Binary.Type.UnsignedRightShift); - break; - case LessThanToken: - consumeToken(TSCSyntaxKind.LessThanToken); - op = padLeft(opPrefix, J.Binary.Type.LessThan); - break; - case LessThanEqualsToken: - consumeToken(TSCSyntaxKind.LessThanEqualsToken); - op = padLeft(opPrefix, J.Binary.Type.LessThanOrEqual); - break; - // Arithmetic ops - case AsteriskToken: - consumeToken(TSCSyntaxKind.AsteriskToken); - op = padLeft(opPrefix, J.Binary.Type.Multiplication); - break; - case MinusToken: - consumeToken(TSCSyntaxKind.MinusToken); - op = padLeft(opPrefix, J.Binary.Type.Subtraction); - break; - case PercentToken: - consumeToken(TSCSyntaxKind.PercentToken); - op = padLeft(opPrefix, J.Binary.Type.Modulo); - break; - case PlusToken: - consumeToken(TSCSyntaxKind.PlusToken); - op = padLeft(opPrefix, J.Binary.Type.Addition); - break; - case SlashToken: - consumeToken(TSCSyntaxKind.SlashToken); - op = padLeft(opPrefix, J.Binary.Type.Division); - break; - // TS/JS specific ops - case InKeyword: - consumeToken(TSCSyntaxKind.InKeyword); - jsOp = padLeft(opPrefix, JS.JsBinary.Type.In); - break; - default: - implementMe(node); - } - - Expression right = (Expression) visitNode(node.getNodeProperty("right")); - - if (jsOp != null) { - return new JS.JsBinary( - randomId(), - prefix, - markers, - left, - jsOp, - right, - typeMapping.type(node) - ); - } else { - return new J.Binary( - randomId(), - prefix, - markers, - left, - op, - right, - typeMapping.type(node) - ); - } - } - - private J visitBinaryExpression(TSCNode node) { - TSCSyntaxKind opKind = node.getNodeProperty("operatorToken").syntaxKind(); - // TS represents J.Assignment, J.AssignmentOperation, and J.Binary as a BinaryExpression. - switch (opKind) { - case EqualsToken: - return visitAssignment(node); - case AsteriskEqualsToken: - case MinusEqualsToken: - case PercentEqualsToken: - case PlusEqualsToken: - case SlashEqualsToken: - return visitAssignmentOperation(node); - case AmpersandToken: - case AmpersandAmpersandToken: - case AsteriskToken: - case BarToken: - case BarBarToken: - case CaretToken: - case CommaToken: - case EqualsEqualsToken: - case ExclamationEqualsToken: - case GreaterThanToken: - case GreaterThanEqualsToken: - case GreaterThanGreaterThanToken: - case GreaterThanGreaterThanGreaterThanToken: - case InKeyword: - case LessThanToken: - case LessThanEqualsToken: - case LessThanLessThanToken: - case MinusToken: - case PercentToken: - case PlusToken: - case SlashToken: - return visitBinary(node); - case EqualsEqualsEqualsToken: - case ExclamationEqualsEqualsToken: - return visitJsBinary(node); - case InstanceOfKeyword: - return visitInstanceOf(node); - default: - implementMe(node.getNodeProperty("operatorToken")); - } - - return null; - } - - private void visitBinaryUpdateExpression(TSCNode incrementor, List> updates) { - assert (incrementor.syntaxKind() == TSCSyntaxKind.BinaryExpression); - TSCNode left = incrementor.getNodeProperty("left"); - if (left.syntaxKind() == TSCSyntaxKind.BinaryExpression) { - visitBinaryUpdateExpression(left, updates); - } else { - updates.add(padRight((Statement) visitNode(left), sourceBefore(TSCSyntaxKind.CommaToken))); - } - Statement r = (Statement) visitNode(incrementor.getNodeProperty("right")); - Space after = whitespace(); - if (tryConsume(TSCSyntaxKind.CommaToken)) { - // TODO check where to add this to LST - } else if (tryConsume(TSCSyntaxKind.CloseParenToken)) { - // TODO check where to add this to LST - } - updates.add(padRight(r, after)); - } - - private J.@Nullable Block visitBlock(@Nullable TSCNode node) { - if (node == null) { - return null; - } - - Space prefix = sourceBefore(TSCSyntaxKind.OpenBraceToken); - - List statementNodes = node.getNodeListProperty("statements"); - List> statements = new ArrayList<>(statementNodes.size()); - - for (TSCNode statementNode : statementNodes) { - statements.add(visitStatement(statementNode)); - } - - Space endOfBlock = sourceBefore(TSCSyntaxKind.CloseBraceToken); - return new J.Block( - randomId(), - prefix, - Markers.EMPTY, - JRightPadded.build(false), - statements, - endOfBlock - ); - } - - private J.Break visitBreakStatement(TSCNode node) { - TSCNode label = node.getOptionalNodeProperty("label"); - return new J.Break( - randomId(), - sourceBefore(TSCSyntaxKind.BreakKeyword), - Markers.EMPTY, - label != null ? (J.Identifier) visitNode(label) : null - ); - } - - private J.MethodInvocation visitCallExpression(TSCNode node) { - implementMe(node, "questionDotToken"); - List typeArgs = node.getOptionalNodeListProperty("typeArguments"); - if (typeArgs != null) { - implementMe(node, "typeArguments"); - } - - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - - JRightPadded select = null; - TSCNode expression = node.getNodeProperty("expression"); - TSCNode expr = expression.getOptionalNodeProperty("expression"); - if (expr != null) { - // Adjust padding. - implementMe(expression, "questionDotToken"); - - if (expression.syntaxKind() == TSCSyntaxKind.PropertyAccessExpression) { - select = padRight((Expression) visitNode(expr), sourceBefore(TSCSyntaxKind.DotToken)); - } else if (expression.syntaxKind() == TSCSyntaxKind.ParenthesizedExpression) { - markers = markers.addIfAbsent(new OmitDot(randomId())); - select = padRight((Expression) visitNode(expression), whitespace()); - } else { - implementMe(expression); - } - } - - JavaType.Method type = typeMapping.methodInvocationType(node); - J.Identifier name = null; - TSCNode nameNode = expression.getOptionalNodeProperty("name"); - if (nameNode != null) { - name = visitIdentifier(nameNode, type); - } else if (expression.syntaxKind() == TSCSyntaxKind.Identifier) { - name = visitIdentifier(expression, type); - } else if (expression.syntaxKind() == TSCSyntaxKind.SuperKeyword) { - name = convertToIdentifier(sourceBefore(TSCSyntaxKind.SuperKeyword), "super"); - } else if (expression.syntaxKind() == TSCSyntaxKind.ParenthesizedExpression) { - // FIXME. @Gary. - // This block of code means the call expression has multiple names via the select expression. - // It's probably better to add a new JS LST object to represent this to enable JS recipes to detect and handle this case. - // However, there are currently too many unknowns. So, it's added to J via the select `Expression` field. - // Due to type-mapping, method matchers will not detect this code, which will prevent invalid changes. - name = convertToIdentifier(EMPTY, ""); - } else { - implementMe(expression); - } - - JContainer typeParameters = null; - - List tpNodes = node.getOptionalNodeListProperty("typeParameters"); - if (tpNodes != null) { - JContainer jContainer = mapContainer( - TSCSyntaxKind.LessThanToken, - tpNodes, - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.GreaterThanToken, - this::visitNode, - true - ); - - List> typeParams = new ArrayList<>(jContainer.getElements().size()); - for (JRightPadded jjRightPadded : jContainer.getPadding().getElements()) { - Expression exp = (!(jjRightPadded.getElement() instanceof Expression) && jjRightPadded.getElement() instanceof Statement) ? - new JS.StatementExpression(randomId(), (Statement) jjRightPadded.getElement()) : (Expression) jjRightPadded.getElement(); - JRightPadded apply = padRight(exp, jjRightPadded.getAfter(), jjRightPadded.getMarkers()); - typeParams.add(apply); - } - typeParameters = JContainer.build(jContainer.getBefore(), typeParams, jContainer.getMarkers()); - } - - JContainer arguments = null; - TSCNodeList argNodes = node.getOptionalNodeListProperty("arguments"); - if (argNodes != null) { - JContainer jContainer = mapContainer( - TSCSyntaxKind.OpenParenToken, - argNodes, - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.CloseParenToken, - this::visitNode, - true - ); - List> elements = new ArrayList<>(jContainer.getElements().size()); - for (JRightPadded jjRightPadded : jContainer.getPadding().getElements()) { - Expression exp = (!(jjRightPadded.getElement() instanceof Expression) && jjRightPadded.getElement() instanceof Statement) ? - new JS.StatementExpression(randomId(), (Statement) jjRightPadded.getElement()) : (Expression) jjRightPadded.getElement(); - JRightPadded apply = padRight(exp, jjRightPadded.getAfter(), jjRightPadded.getMarkers()); - elements.add(apply); - } - arguments = JContainer.build(jContainer.getBefore(), elements, jContainer.getMarkers()); - } - - return new J.MethodInvocation( - randomId(), - prefix, - markers, - select, - typeParameters, - name, - arguments, - type - ); - } - - private J.ClassDeclaration visitClassDeclaration(TSCNode node) { - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - - List leading = new ArrayList<>(); - List trailing = new ArrayList<>(); - List modifiers; - List modifierNodes = node.getOptionalNodeListProperty("modifiers"); - if (modifierNodes != null) { - modifiers = mapModifiers(node.getNodeListProperty("modifiers"), leading, trailing); - } else { - modifiers = emptyList(); - } - - Space kindPrefix; - TSCSyntaxKind syntaxKind = node.syntaxKind(); - J.ClassDeclaration.Kind.Type type; - switch (syntaxKind) { - case EnumDeclaration: - kindPrefix = sourceBefore(TSCSyntaxKind.EnumKeyword); - type = J.ClassDeclaration.Kind.Type.Enum; - break; - case InterfaceDeclaration: - kindPrefix = sourceBefore(TSCSyntaxKind.InterfaceKeyword); - type = J.ClassDeclaration.Kind.Type.Interface; - break; - default: - kindPrefix = sourceBefore(TSCSyntaxKind.ClassKeyword); - type = J.ClassDeclaration.Kind.Type.Class; - } - - J.ClassDeclaration.Kind kind = new J.ClassDeclaration.Kind(randomId(), kindPrefix, Markers.EMPTY, trailing, type); - - J.Identifier name; - TSCNode nameNode = node.getOptionalNodeProperty("name"); - name = nameNode != null ? visitIdentifier(nameNode) : convertToIdentifier(EMPTY, ""); - TSCNodeList typeParameterNodes = node.getOptionalNodeListProperty("typeParameters"); - JContainer typeParams = typeParameterNodes == null ? null : mapContainer( - TSCSyntaxKind.LessThanToken, - typeParameterNodes, - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.GreaterThanToken, - t -> (J.TypeParameter) visitNode(t) - ); - - JLeftPadded extendings = null; - JContainer implementings = null; - TSCNodeList heritageClausesNodes = node.getOptionalNodeListProperty("heritageClauses"); - if (heritageClausesNodes != null) { - for (TSCNode tscNode : heritageClausesNodes) { - if (TSCSyntaxKind.fromCode(tscNode.getIntProperty("token")) == TSCSyntaxKind.ExtendsKeyword) { - List types = tscNode.getNodeListProperty("types"); - assert types.size() == 1; - extendings = padLeft(sourceBefore(TSCSyntaxKind.ExtendsKeyword), (TypeTree) visitNode(types.get(0))); - } else { - implementMe(tscNode); - } - } - } - - J.Block body; - List> members; - TSCNodeList memberNodes = node.getOptionalNodeListProperty("members"); - if (memberNodes != null) { - Space bodyPrefix = sourceBefore(TSCSyntaxKind.OpenBraceToken); - - if (kind.getType() == J.ClassDeclaration.Kind.Type.Enum) { - Space enumPrefix = whitespace(); - - members = new ArrayList<>(1); - List> enumValues = new ArrayList<>(memberNodes.size()); - for (int i = 0; i < memberNodes.size(); i++) { - TSCNode enumValue = memberNodes.get(i); - J.EnumValue value = (J.EnumValue) visitNode(enumValue); - if (value != null) { - boolean hasTrailingComma = i == memberNodes.size() - 1 && memberNodes.getBooleanProperty("hasTrailingComma"); - Space after = i < memberNodes.size() - 1 ? sourceBefore(TSCSyntaxKind.CommaToken) : - hasTrailingComma ? sourceBefore(TSCSyntaxKind.CommaToken) : EMPTY; - JRightPadded ev = padRight(value, after); - if (i == memberNodes.size() - 1) { - if (hasTrailingComma) { - ev = ev.withMarkers(ev.getMarkers().addIfAbsent(new TrailingComma(randomId(), EMPTY))); - } - } - enumValues.add(ev); - } - } - - JRightPadded enumSet = maybeSemicolon( - new J.EnumValueSet( - randomId(), - enumPrefix, - Markers.EMPTY, - enumValues, - false - ) - ); - members.add(enumSet); - } else { - members = new ArrayList<>(memberNodes.size()); - for (TSCNode statement : memberNodes) { - members.add(visitStatement(statement)); - } - } - - body = new J.Block(randomId(), bodyPrefix, Markers.EMPTY, new JRightPadded<>(false, EMPTY, Markers.EMPTY), - members, sourceBefore(TSCSyntaxKind.CloseBraceToken)); - } else { - // This shouldn't happen. - throw new UnsupportedOperationException("Add support for empty body"); - } - - JContainer primaryConstructor = null; - - return new J.ClassDeclaration( - randomId(), - prefix, - markers, - leading.isEmpty() ? emptyList() : leading, - modifiers, - kind, - name, - typeParams, - primaryConstructor, - extendings, - implementings, - null, - body, - (JavaType.FullyQualified) typeMapping.type(node)); - } - - private J visitCaseClause(TSCNode node) { - TSCNode expression = node.getOptionalNodeProperty("expression"); - List statements = node.getNodeListProperty("statements"); - Space prefix = whitespace(); - JContainer expressions = JContainer.build( - expression == null ? EMPTY : sourceBefore(TSCSyntaxKind.CaseKeyword), - singletonList(JRightPadded.build((Expression) visitNode(expression))), - Markers.EMPTY - ); - List> list = new ArrayList<>(statements.size()); - Space before = sourceBefore(TSCSyntaxKind.ColonToken); - for (TSCNode it : statements) { - JRightPadded statementJRightPadded = maybeSemicolon((Statement) visitNode(it)); - list.add(statementJRightPadded); - } - return new J.Case( - randomId(), - prefix, - Markers.EMPTY, - J.Case.Type.Statement, - null, - expressions, - JContainer.build( - before, - list, - Markers.EMPTY - ), - null - ); - } - - private J.Ternary visitConditionalExpression(TSCNode node) { - return new J.Ternary( - randomId(), - whitespace(), - Markers.EMPTY, - (Expression) visitNode(node.getNodeProperty("condition")), - padLeft(sourceBefore(TSCSyntaxKind.QuestionToken), (Expression) visitNode(node.getNodeProperty("whenTrue"))), - padLeft(sourceBefore(TSCSyntaxKind.ColonToken), (Expression) visitNode(node.getNodeProperty("whenFalse"))), - typeMapping.type(node) - ); - } - - private J.Continue visitContinueStatement(TSCNode node) { - TSCNode label = node.getOptionalNodeProperty("label"); - return new J.Continue( - randomId(), - sourceBefore(TSCSyntaxKind.ContinueKeyword), - Markers.EMPTY, - label != null ? (J.Identifier) visitNode(node.getNodeProperty("label")) : null - ); - } - - private J.MethodDeclaration visitConstructor(TSCNode node) { - implementMe(node, "type"); - implementMe(node, "typeArguments"); - - Space prefix = whitespace(); - List modifiers; - List leading = new ArrayList<>(); - List trailing = new ArrayList<>(); - TSCNodeList modifierNodes = node.getOptionalNodeListProperty("modifiers"); - if (modifierNodes != null) { - modifiers = mapModifiers(modifierNodes, leading, trailing); - } else { - modifiers = emptyList(); - } - - Space before = sourceBefore(TSCSyntaxKind.ConstructorKeyword); - J.Identifier name = convertToIdentifier(before, "constructor"); - J.TypeParameters typeParameters = mapTypeParameters(node.getOptionalNodeListProperty("typeParameters")); - - JContainer params = mapContainer( - TSCSyntaxKind.OpenParenToken, - node.getNodeListProperty("parameters"), - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.CloseParenToken, - t -> (Statement) visitNode(t), - true); - - J.Block body = (J.Block) visitNode(node.getNodeProperty("body")); - return new J.MethodDeclaration( - randomId(), - prefix, - Markers.EMPTY, - leading.isEmpty() ? emptyList() : leading, - modifiers, - typeParameters, - null, - new J.MethodDeclaration.IdentifierWithAnnotations(name, Collections.emptyList()), - params, - null, - body, - null, - typeMapping.methodDeclarationType(node) - ); - } - - private J.Annotation visitDecorator(TSCNode node) { - Space prefix = sourceBefore(TSCSyntaxKind.AtToken); - implementMe(node, "questionDotToken"); - implementMe(node, "typeArguments"); - TSCNode callExpression = node.getNodeProperty("expression"); - NameTree name = (NameTree) visitNameExpression(callExpression.getNodeProperty("expression")); - JContainer arguments = null; - TSCNodeList args = callExpression.getOptionalNodeListProperty("arguments"); - if (args != null) { - JContainer jContainer = mapContainer( - TSCSyntaxKind.OpenParenToken, - args, - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.CloseParenToken, - this::visitNode, - true - ); - - List> elements = new ArrayList<>(jContainer.getElements().size()); - for (JRightPadded jjRightPadded : jContainer.getPadding().getElements()) { - Expression exp = (!(jjRightPadded.getElement() instanceof Expression) && jjRightPadded.getElement() instanceof Statement) ? - new JS.StatementExpression(randomId(), (Statement) jjRightPadded.getElement()) : (Expression) jjRightPadded.getElement(); - JRightPadded apply = padRight(exp, jjRightPadded.getAfter(), jjRightPadded.getMarkers()); - elements.add(apply); - } - arguments = JContainer.build(jContainer.getBefore(), elements, jContainer.getMarkers()); - } - return new J.Annotation( - randomId(), - prefix, - Markers.EMPTY, - name, - arguments - ); - } - - private J visitDefaultClause(TSCNode node) { - List statements = node.getNodeListProperty("statements"); - Space prefix = whitespace(); - JContainer expressions = JContainer.build( - EMPTY, - singletonList(JRightPadded.build(new J.Identifier(randomId(), sourceBefore(TSCSyntaxKind.DefaultKeyword), Markers.EMPTY, emptyList(), "default", null, null))), - Markers.EMPTY - ); - Space before = sourceBefore(TSCSyntaxKind.ColonToken); - List> list = new ArrayList<>(statements.size()); - for (TSCNode it : statements) { - JRightPadded statementJRightPadded = maybeSemicolon((Statement) visitNode(it)); - list.add(statementJRightPadded); - } - return new J.Case( - randomId(), - prefix, - Markers.EMPTY, - J.Case.Type.Statement, - null, - expressions, - JContainer.build( - before, - list, - Markers.EMPTY - ), - null - ); - } - - private J visitDeleteExpression(TSCNode node) { - Space prefix = sourceBefore(TSCSyntaxKind.DeleteKeyword); - return new JS.Delete( - randomId(), - prefix, - Markers.EMPTY, - (Expression) visitNode(node.getNodeProperty("expression")), - typeMapping.type(node) - ); - } - - private J.DoWhileLoop visitDoStatement(TSCNode node) { - Space prefix = sourceBefore(TSCSyntaxKind.DoKeyword); - JRightPadded body = maybeSemicolon((Statement) visitNode(node.getNodeProperty("statement"))); - - JLeftPadded> control = - padLeft(sourceBefore(TSCSyntaxKind.WhileKeyword), mapControlParentheses(node.getNodeProperty("expression"))); - return new J.DoWhileLoop( - randomId(), - prefix, - Markers.EMPTY, - body, - control - ); - } - - private J.ArrayAccess visitElementAccessExpression(TSCNode node) { - implementMe(node, "questionDotToken"); - return new J.ArrayAccess( - randomId(), - whitespace(), - Markers.EMPTY, - (Expression) visitNode(node.getNodeProperty("expression")), - new J.ArrayDimension( - randomId(), - sourceBefore(TSCSyntaxKind.OpenBracketToken), - Markers.EMPTY, - padRight((Expression) visitNode(node.getNodeProperty("argumentExpression")), sourceBefore(TSCSyntaxKind.CloseBracketToken)) - ), - typeMapping.type(node) - ); - } - - private Statement visitEmptyStatement(TSCNode ignored) { - return new J.Empty(randomId(), EMPTY, Markers.EMPTY); - } - - private J.EnumValue visitEnumMember(TSCNode node) { - return new J.EnumValue( - randomId(), - whitespace(), - Markers.EMPTY, - emptyList(), - visitIdentifier(node.getNodeProperty("name")), - null); - } - - private JS.Export visitExportAssignment(TSCNode node) { - Space prefix = sourceBefore(TSCSyntaxKind.ExportKeyword); - implementMe(node, "isExportEquals"); - return new JS.Export( - randomId(), - prefix, - Markers.EMPTY, - null, - null, - null, - padLeft(sourceBefore(TSCSyntaxKind.DefaultKeyword), (Expression) visitNode(node.getNodeProperty("expression"))) - ); - } - - private JS.Export visitExportDeclaration(TSCNode node) { - implementMe(node, "assertClause"); - implementMe(node, "modifiers"); - - Space prefix = sourceBefore(TSCSyntaxKind.ExportKeyword); - boolean isTypeOnly = node.getBooleanProperty("isTypeOnly"); - if (isTypeOnly) { - implementMe(node); - } - - TSCNode exportClause = node.getOptionalNodeProperty("exportClause"); - JContainer exports; - if (exportClause != null) { - if (exportClause.syntaxKind() != TSCSyntaxKind.NamedExports) { - implementMe(exportClause); - } - - List elements = exportClause.getOptionalNodeListProperty("elements"); - if (elements == null) { - implementMe(exportClause); - } - exports = mapContainer( - TSCSyntaxKind.OpenBraceToken, - elements, - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.CloseBraceToken, - t -> (Expression) visitNode(t), - true - ).withMarkers(Markers.build(singletonList(new Braces(randomId())))); - } else { - exports = JContainer.build(sourceBefore(TSCSyntaxKind.AsteriskToken), - singletonList(padRight(convertToIdentifier(EMPTY, "*"), EMPTY)), Markers.EMPTY); - } - - TSCNode moduleSpecifier = node.getOptionalNodeProperty("moduleSpecifier"); - Space beforeFrom = moduleSpecifier == null ? null : sourceBefore(TSCSyntaxKind.FromKeyword); - J.Literal target = null; - if (moduleSpecifier != null) { - Space before = whitespace(); - String nodeText = moduleSpecifier.getText(); - skip(nodeText); - target = new J.Literal( - randomId(), - before, - Markers.EMPTY, - moduleSpecifier.getStringProperty("text"), - nodeText, - null, - JavaType.Primitive.None - ); - } - return new JS.Export( - randomId(), - prefix, - Markers.EMPTY, - exports, - beforeFrom, - target, - null - ); - } - - private J visitExportSpecifier(TSCNode node) { - boolean isTypeOnly = node.getBooleanProperty("isTypeOnly"); - if (isTypeOnly) { - implementMe(node); - } - TSCNode propertyName = node.getOptionalNodeProperty("propertyName"); - if (propertyName != null) { - return new JS.Alias( - randomId(), - whitespace(), - Markers.EMPTY, - padRight((J.Identifier) visitNode(propertyName), sourceBefore(TSCSyntaxKind.AsKeyword)), - (J.Identifier) visitNode(node.getNodeProperty("name")) - ); - } - - return visitNode(node.getNodeProperty("name")); - } - - public J visitExpressionStatement(TSCNode node) { - return visitNode(node.getNodeProperty("expression")); - } - - - private J.ForLoop visitForStatement(TSCNode node) { - Space prefix = sourceBefore(TSCSyntaxKind.ForKeyword); - - Space beforeControl = sourceBefore(TSCSyntaxKind.OpenParenToken); - List> initStatements = singletonList(padRight((Statement) visitNode(node.getNodeProperty("initializer")), whitespace())); - consumeToken(TSCSyntaxKind.SemicolonToken); - - JRightPadded condition = padRight((Expression) visitNode(node.getNodeProperty("condition")), sourceBefore(TSCSyntaxKind.SemicolonToken)); - - TSCNode incrementor = node.getNodeProperty("incrementor"); - List> update; - if (incrementor.syntaxKind() == TSCSyntaxKind.BinaryExpression) { - update = new ArrayList<>(2); - visitBinaryUpdateExpression(incrementor, update); - } else { - update = singletonList(padRight((Statement) visitNode(incrementor), sourceBefore(TSCSyntaxKind.CloseParenToken))); - } - J.ForLoop.Control control = new J.ForLoop.Control( - randomId(), - beforeControl, - Markers.EMPTY, - initStatements, - condition, - update - ); - - return new J.ForLoop( - randomId(), - prefix, - Markers.EMPTY, - control, - maybeSemicolon((Statement) visitNode(node.getNodeProperty("statement"))) - ); - } - - private J.ForEachLoop visitForEachStatement(TSCNode node) { - Space prefix = sourceBefore(TSCSyntaxKind.ForKeyword); - Markers markers = Markers.EMPTY; - implementMe(node, "awaitModifier"); - - Space beforeControl = sourceBefore(TSCSyntaxKind.OpenParenToken); - JRightPadded variable = padRight((J.VariableDeclarations) visitNode(node.getNodeProperty("initializer")), whitespace()); - - TSCSyntaxKind forEachKind = scan(); - if (forEachKind == TSCSyntaxKind.OfKeyword) { - markers = markers.addIfAbsent(new ForLoopType(randomId(), ForLoopType.Keyword.OF)); - } else if (forEachKind == TSCSyntaxKind.InKeyword) { - markers = markers.addIfAbsent(new ForLoopType(randomId(), ForLoopType.Keyword.IN)); - } - - JRightPadded iterable = padRight((Expression) visitNode(node.getNodeProperty("expression")), sourceBefore(TSCSyntaxKind.CloseParenToken)); - J.ForEachLoop.Control control = new J.ForEachLoop.Control( - randomId(), - beforeControl, - Markers.EMPTY, - variable, - iterable - ); - - JRightPadded statement = maybeSemicolon((Statement) visitNode(node.getNodeProperty("statement"))); - return new J.ForEachLoop( - randomId(), - prefix, - markers, - control, - statement - ); - } - - private J visitExpressionWithTypeArguments(TSCNode node) { - Space prefix = whitespace(); - NameTree nameTree = (NameTree) visitNode(node.getNodeProperty("expression")); - List typeArguments = node.getOptionalNodeListProperty("typeArguments"); - if (typeArguments != null) { - return new J.ParameterizedType( - randomId(), - prefix, - Markers.EMPTY, - nameTree, - mapContainer( - TSCSyntaxKind.LessThanToken, - typeArguments, - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.GreaterThanToken, - t -> (Expression) visitNode(t), - true - ), - typeMapping.type(node) - ); - } - - return nameTree.withPrefix(prefix); - } - - private J.MethodDeclaration visitFunctionDeclaration(TSCNode node) { - implementMe(node, "asteriskToken"); - implementMe(node, "typeArguments"); - - Space prefix = whitespace(); - - List leading = new ArrayList<>(); - List trailing = new ArrayList<>(); - List modifiers = mapModifiers(node.getOptionalNodeListProperty("modifiers"), leading, trailing); - - Space before = sourceBefore(TSCSyntaxKind.FunctionKeyword); - Markers markers = Markers.build(singletonList(new FunctionKeyword(randomId(), before))); - - J.Identifier name; - JavaType.Method method = typeMapping.methodDeclarationType(node); - TSCNode nameNode = node.getOptionalNodeProperty("name"); - if (nameNode != null) { - name = visitIdentifier(nameNode); - } else { - // FIXME: get input, we can add an anonymous name and prevent printing with a marker. - // Function expressions do not require a name `function (..)` - name = convertToIdentifier(EMPTY, ""); - } - if (!trailing.isEmpty()) { - name = name.withAnnotations(trailing); - } - name = name.withType(method); - - J.TypeParameters typeParameters = mapTypeParameters(node.getOptionalNodeListProperty("typeParameters")); - JContainer parameters = mapContainer( - TSCSyntaxKind.OpenParenToken, - node.getNodeListProperty("parameters"), - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.CloseParenToken, - this::visitFunctionParameter, - true - ); - - TSCNode typeNode = node.getOptionalNodeProperty("type"); - TypeTree returnTypeExpression = null; - if (typeNode != null) { - markers = markers.addIfAbsent(new TypeReferencePrefix(randomId(), sourceBefore(TSCSyntaxKind.ColonToken))); - returnTypeExpression = (TypeTree) visitNode(typeNode); - } - - J.Block block = visitBlock(node.getOptionalNodeProperty("body")); - - return new J.MethodDeclaration( - randomId(), - prefix, - markers, - leading.isEmpty() ? emptyList() : leading, - modifiers, - typeParameters, - returnTypeExpression, - new J.MethodDeclaration.IdentifierWithAnnotations(name, Collections.emptyList()), - parameters, - null, - block, - null, - method - ); - } - - private Statement visitFunctionParameter(TSCNode node) { - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - - List leading = new ArrayList<>(); - List trailing = new ArrayList<>(); - List modifiers = mapModifiers(node.getOptionalNodeListProperty("modifiers"), leading, trailing); - - Space variablePrefix = whitespace(); - J.Identifier name = visitIdentifier(node.getNodeProperty("name")); - if (!trailing.isEmpty()) { - name = name.withAnnotations(trailing); - } - TypeTree typeTree = null; - TSCNode type = node.getOptionalNodeProperty("type"); - if (type != null) { - TSCNode questionToken = node.getOptionalNodeProperty("questionToken"); - if (questionToken != null) { - markers = markers.addIfAbsent(new PostFixOperator(randomId(), sourceBefore(TSCSyntaxKind.QuestionToken), PostFixOperator.Operator.Question)); - } - Space beforeColon = sourceBefore(TSCSyntaxKind.ColonToken); - markers = markers.addIfAbsent(new TypeReferencePrefix(randomId(), beforeColon)); - typeTree = (TypeTree) visitNode(type); - } - List> variables = new ArrayList<>(1); - variables.add(padRight(new J.VariableDeclarations.NamedVariable( - randomId(), - variablePrefix, - Markers.EMPTY, - name, - emptyList(), - null, - typeMapping.variableType(node) - ), EMPTY)); - - implementMe(node, "initializer"); - - Space varargs = null; - List> dimensionsBeforeName = emptyList(); - - return new J.VariableDeclarations( - randomId(), - prefix, - markers, - leading.isEmpty() ? emptyList() : leading, - modifiers.isEmpty() ? emptyList() : modifiers, - typeTree, - varargs, - dimensionsBeforeName, - variables - ); - } - - private J visitExternalModuleReference(TSCNode node) { - Space prefix = whitespace(); - - consumeToken(TSCSyntaxKind.RequireKeyword); - J.Identifier name = convertToIdentifier(EMPTY, "require"); - - return new J.MethodInvocation( - randomId(), - prefix, - Markers.EMPTY, - null, - null, - name, - mapContainer( - TSCSyntaxKind.OpenParenToken, - singletonList(node.getNodeProperty("expression")), - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.CloseParenToken, - t -> (Expression) visitNode(t), - true - ), - null - ); - } - - private J.Identifier visitIdentifier(TSCNode node) { - return visitIdentifier(node, null, null); - } - - private J.Identifier visitIdentifier(TSCNode node, @Nullable JavaType type) { - return visitIdentifier(node, type, null); - } - - private J.Identifier visitIdentifier(TSCNode node, @Nullable JavaType type, JavaType.@Nullable Variable fieldType) { - Space prefix = whitespace(); - skip(node.getText()); - // TODO: check on escapedText property. - return new J.Identifier( - randomId(), - prefix, - Markers.EMPTY, - emptyList(), - node.getText(), - type == null ? typeMapping.type(node) : type, - fieldType - ); - } - - private J visitImportDeclaration(TSCNode node) { - implementMe(node, "assertClause"); - implementMe(node, "modifiers"); - - Space prefix = sourceBefore(TSCSyntaxKind.ImportKeyword); - - TSCNode importClause = node.getOptionalNodeProperty("importClause"); - JRightPadded name = null; - JContainer imports = null; - if (importClause != null) { - boolean isTypeOnly = importClause.getBooleanProperty("isTypeOnly"); - if (isTypeOnly) { - implementMe(importClause, "isTypeOnly"); - } - - TSCNode nameNode = importClause.getOptionalNodeProperty("name"); - if (nameNode != null) { - name = padRight((J.Identifier) visitNode(nameNode), whitespace()); - } - - TSCNode namedBindings = importClause.getOptionalNodeProperty("namedBindings"); - if (namedBindings != null) { - if (name != null) { - consumeToken(TSCSyntaxKind.CommaToken); - } - - imports = mapContainer( - TSCSyntaxKind.OpenBraceToken, - namedBindings.getNodeListProperty("elements"), - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.CloseBraceToken, - t -> (Expression) visitNode(t), - true - ).withMarkers(Markers.build(singletonList(new Braces(randomId())))); - } - } - - TSCNode moduleSpecifier = node.getOptionalNodeProperty("moduleSpecifier"); - Space beforeFrom = moduleSpecifier == null ? null : sourceBefore(TSCSyntaxKind.FromKeyword); - J.Literal target = null; - if (moduleSpecifier != null) { - Space before = whitespace(); - String nodeText = moduleSpecifier.getText(); - skip(nodeText); - target = new J.Literal( - randomId(), - before, - Markers.EMPTY, - moduleSpecifier.getStringProperty("text"), - nodeText, - null, - JavaType.Primitive.None - ); - } - - JLeftPadded initializer = null; - TSCNode moduleReference = node.getOptionalNodeProperty("moduleReference"); - if (moduleReference != null) { - name = padRight((J.Identifier) visitNode(node.getNodeProperty("name")), whitespace()); - initializer = padLeft(sourceBefore(TSCSyntaxKind.EqualsToken), (Expression) visitNode(moduleReference)); - } - - return new JS.JsImport( - randomId(), - prefix, - Markers.EMPTY, - name, - imports, - beforeFrom, - target, - initializer - ); - } - - private J visitIndexedAccessType(TSCNode node) { - return unknown(node); - } - - private J.If visitIfStatement(TSCNode node) { - Space prefix = sourceBefore(TSCSyntaxKind.IfKeyword); - - J.ControlParentheses control = mapControlParentheses(node.getNodeProperty("expression")); - JRightPadded thenPart = visitStatement(node.getNodeProperty("thenStatement")); - - J.If.Else elsePart = null; - TSCNode elseNode = node.getOptionalNodeProperty("elseStatement"); - if (elseNode != null) { - Space elsePartPrefix = sourceBefore(TSCSyntaxKind.ElseKeyword); - elsePart = new J.If.Else( - randomId(), - elsePartPrefix, - Markers.EMPTY, - visitStatement(elseNode) - ); - } - return new J.If( - randomId(), - prefix, - Markers.EMPTY, - control, - thenPart, - elsePart - ); - } - - private J.InstanceOf visitInstanceOf(TSCNode node) { - return new J.InstanceOf( - randomId(), - whitespace(), - Markers.EMPTY, - padRight((Expression) visitNode(node.getNodeProperty("left")), sourceBefore(TSCSyntaxKind.InstanceOfKeyword)), - visitNode(node.getNodeProperty("right")), - null, - typeMapping.type(node) - ); - } - - private JS.JsBinary visitJsBinary(TSCNode node) { - Space prefix = whitespace(); - Expression left = (Expression) visitNode(node.getNodeProperty("left")); - - JLeftPadded op; - TSCSyntaxKind opKind = node.getNodeProperty("operatorToken").syntaxKind(); - if (opKind == TSCSyntaxKind.EqualsEqualsEqualsToken) { - op = padLeft(sourceBefore(TSCSyntaxKind.EqualsEqualsEqualsToken), JS.JsBinary.Type.IdentityEquals); - } else if (opKind == TSCSyntaxKind.ExclamationEqualsEqualsToken) { - op = padLeft(sourceBefore(TSCSyntaxKind.ExclamationEqualsEqualsToken), JS.JsBinary.Type.IdentityNotEquals); - } else { - throw new IllegalArgumentException(String.format("Binary operator kind <%s> is not supported.", opKind)); - } - - Expression right = (Expression) visitNode(node.getNodeProperty("right")); - return new JS.JsBinary( - randomId(), - prefix, - Markers.EMPTY, - left, - op, - right, - typeMapping.type(node) - ); - } - - private J.Identifier visitKeyword(TSCNode node) { - return visitIdentifier(node); - } - - private J visitFunctionType(TSCNode node) { -// implementMe(node, "typeParameters"); -// implementMe(node, "modifiers"); -// implementMe(node, "typeArguments"); -// implementMe(node, "asteriskToken"); -// -// Space prefix = whitespace(); -// -// List params = node.getOptionalNodeListProperty("parameters"); -// if (params == null) { -// implementMe(node); -// } -// JContainer parameters = mapContainer( -// TSCSyntaxKind.OpenParenToken, -// params, -// TSCSyntaxKind.CommaToken, -// TSCSyntaxKind.CloseParenToken, -// t -> (Statement) visitNode(t), -// true -// ); -// -// TSCNode type = node.getOptionalNodeProperty("type"); -// if (type == null) { -// implementMe(node); -// } -// -// return new JS.FunctionType( -// randomId(), -// prefix, -// Markers.EMPTY, -// parameters, -// sourceBefore(TSCSyntaxKind.EqualsGreaterThanToken), -// (Expression) visitNode(type), -// typeMapping.type(node) -// ); - return unknown(node); - } - - private J.Label visitLabelledStatement(TSCNode node) { - return new J.Label( - randomId(), - whitespace(), - Markers.EMPTY, - padRight(visitIdentifier(node.getNodeProperty("label")), sourceBefore(TSCSyntaxKind.ColonToken)), - (Statement) visitNode(node.getNodeProperty("statement")) - ); - } - - private J.MethodDeclaration visitMethodDeclaration(TSCNode node) { - implementMe(node, "questionToken"); - implementMe(node, "exclamationToken"); - implementMe(node, "typeArguments"); - - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - List leading = new ArrayList<>(); - List trailing = new ArrayList<>(); - List modifiers = mapModifiers(node.getOptionalNodeListProperty("modifiers"), leading, trailing); - - if (node.hasProperty("asteriskToken")) { - markers = markers.addIfAbsent(new Asterisk(randomId(), sourceBefore(TSCSyntaxKind.AsteriskToken))); - } - JavaType.Method methodType = typeMapping.methodDeclarationType(node); - TSCNode nameNode = node.getOptionalNodeProperty("name"); - J.Identifier name; - if (nameNode == null) { - name = convertToIdentifier(EMPTY, ""); - } else { - name = visitIdentifier(nameNode, methodType); - } - if (!trailing.isEmpty()) { - name = name.withAnnotations(trailing); - } - J.TypeParameters typeParameters = mapTypeParameters(node.getOptionalNodeListProperty("typeParameters")); - - JContainer parameters = mapContainer( - TSCSyntaxKind.OpenParenToken, - node.getNodeListProperty("parameters"), - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.CloseParenToken, - t -> (Statement) visitNode(t), - true - ); - - JContainer throw_ = null; - - TypeTree returnTypeExpression = null; - TSCNode typeNode = node.getOptionalNodeProperty("type"); - if (typeNode != null) { - markers = markers.addIfAbsent(new TypeReferencePrefix(randomId(), sourceBefore(TSCSyntaxKind.ColonToken))); - returnTypeExpression = (TypeTree) visitNode(typeNode); - } - - J.Block body = visitBlock(node.getOptionalNodeProperty("body")); - JLeftPadded defaultValue = null; - - return new J.MethodDeclaration( - randomId(), - prefix, - markers, - leading.isEmpty() ? emptyList() : leading, - modifiers, - typeParameters, - returnTypeExpression, - new J.MethodDeclaration.IdentifierWithAnnotations(name, emptyList()), - parameters, - throw_, - body, - defaultValue, - methodType - ); - } - - private Expression visitNameExpression(TSCNode expression) { - TSCNode expr = expression.getOptionalNodeProperty("expression"); - if (expr != null) { - Space prefix = whitespace(); - Expression select = visitNameExpression(expr); - - // Adjust left padding from sourceBefore. - implementMe(expression, "questionDotToken"); - - JLeftPadded name = padLeft(sourceBefore(TSCSyntaxKind.DotToken), visitIdentifier(expression.getNodeProperty("name"))); - - return new J.FieldAccess( - randomId(), - prefix, - Markers.EMPTY, - select, - name, - typeMapping.type(expression) - ); - } else { - Expression identifier = null; - TSCNode name = expression.getOptionalNodeProperty("name"); - if (name != null) { - identifier = (Expression) visitNode(name); - } - - if (identifier == null && expression.hasProperty("escapedText") || expression.syntaxKind() == TSCSyntaxKind.ThisKeyword) { - identifier = (Expression) visitNode(expression); - } - - if (identifier == null) { - implementMe(expression); - } - return identifier; - } - } - - private J.Literal visitLiteralType(TSCNode node) { - Space prefix = whitespace(); - - TSCNode literal = node.getNodeProperty("literal"); - Object value = null; - if (literal.syntaxKind() != TSCSyntaxKind.NullKeyword) { - implementMe(literal, "text"); - } - - skip(node.getText()); - return new J.Literal( - randomId(), - prefix, - Markers.EMPTY, - value, - node.getText(), - null, - typeMapping.primitive(literal) - ); - } - - private J visitMetaProperty(TSCNode node) { - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - - Integer keywordToken = node.getOptionalIntProperty("keywordToken"); - TSCSyntaxKind syntaxKind = TSCSyntaxKind.fromCode(keywordToken); - Expression nameExpression = null; - if (syntaxKind == TSCSyntaxKind.ImportKeyword) { - consumeToken(TSCSyntaxKind.ImportKeyword); - nameExpression = convertToIdentifier(EMPTY, "import"); - } else { - implementMe(node); - } - return new J.FieldAccess( - randomId(), - prefix, - markers, - nameExpression, - padLeft(sourceBefore(TSCSyntaxKind.DotToken), visitIdentifier(node.getNodeProperty("name"))), - typeMapping.type(node) - ); - } - - private J.NewClass visitNewExpression(TSCNode node) { - Space prefix = sourceBefore(TSCSyntaxKind.NewKeyword); - TypeTree typeTree = null; - TSCNode expr = node.getOptionalNodeProperty("expression"); - if (expr != null) { - typeTree = (TypeTree) visitNameExpression(expr); - } - implementMe(node, "typeArguments"); - JContainer jContainer = mapContainer( - TSCSyntaxKind.OpenParenToken, - node.getNodeListProperty("arguments"), - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.CloseParenToken, - this::visitNode, - true - ); - List> elements = new ArrayList<>(jContainer.getElements().size()); - for (JRightPadded jjRightPadded : jContainer.getPadding().getElements()) { - Expression exp = (!(jjRightPadded.getElement() instanceof Expression) && jjRightPadded.getElement() instanceof Statement) ? - new JS.StatementExpression(randomId(), (Statement) jjRightPadded.getElement()) : (Expression) jjRightPadded.getElement(); - JRightPadded apply = padRight(exp, jjRightPadded.getAfter(), jjRightPadded.getMarkers()); - elements.add(apply); - } - JContainer arguments = JContainer.build(jContainer.getBefore(), elements, jContainer.getMarkers()); - return new J.NewClass( - randomId(), - EMPTY, - Markers.EMPTY, - null, - prefix, - typeTree, - arguments, - null, - typeMapping.methodInvocationType(node) - ); - } - - private J.Literal visitNumericLiteral(TSCNode node) { - return new J.Literal( - randomId(), - sourceBefore(TSCSyntaxKind.NumericLiteral), - Markers.EMPTY, - node.getStringProperty("text"), - node.getText(), - null, // TODO - typeMapping.primitive(node) - ); - } - - private J visitObjectLiteralExpression(TSCNode node) { - Space prefix = whitespace(); - return mapPropertyNodesToNewClass( node.getOptionalNodeListProperty("properties"), prefix); - } - - private JS.ObjectBindingDeclarations mapObjectBindingDeclaration(TSCNode node) { - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - - List leading = new ArrayList<>(); - List trailing = new ArrayList<>(); - List modifiers = mapModifiers(node.getOptionalNodeListProperty("modifiers"), leading, trailing); - - Space beforeVariableModifier = whitespace(); - TSCSyntaxKind keyword = scan(); - if (keyword == TSCSyntaxKind.ConstKeyword) { - modifiers.add(mapModifier(beforeVariableModifier, "const", trailing)); - } else if (keyword == TSCSyntaxKind.LetKeyword) { - modifiers.add(mapModifier(beforeVariableModifier, "let", trailing)); - } else if (keyword == TSCSyntaxKind.VarKeyword) { - modifiers.add(mapModifier(beforeVariableModifier, "var", trailing)); - } else { - // Unclear if the modifier should be `@Nullable` in the `JSVariableDeclaration`. - implementMe(node); - } - - - TSCNode declarationList = node.getOptionalNodeProperty("declarationList"); - List declarations = declarationList == null ? - emptyList() : declarationList.getNodeListProperty("declarations"); - - TypeTree typeTree = null; - TSCNode bindingNode = declarations.get(0); - TSCNode objectBindingPattern = bindingNode.getNodeProperty("name"); - implementMe(bindingNode, "exclamationToken"); - implementMe(bindingNode, "type"); - List elements = objectBindingPattern.getNodeListProperty("elements"); - List> bindings = new ArrayList<>(elements.size()); - Space beforeBraces = sourceBefore(TSCSyntaxKind.OpenBraceToken); - for (int i = 0; i < elements.size(); i++) { - TSCNode binding = elements.get(i); - Space bindingPrefix = whitespace(); - - Space varArg = binding.hasProperty("dotDotDotToken") ? sourceBefore(TSCSyntaxKind.DotDotDotToken) : null; - - JRightPadded propertyName = null; - TSCNode propertyNameNode = binding.getOptionalNodeProperty("propertyName"); - if (propertyNameNode != null) { - J j = visitNode(propertyNameNode); - J.Identifier name = null; - if (j instanceof J.Identifier) { - name = (J.Identifier) j; - } else { - implementMe(propertyNameNode); - } - propertyName = padRight(name, sourceBefore(TSCSyntaxKind.ColonToken)); - } - - TSCNode nameNode = binding.getNodeProperty("name"); - J j = visitNode(nameNode); - J.Identifier name = null; - if (j instanceof J.Identifier) { - name = (J.Identifier) j; - } else { - implementMe(nameNode); - } - - TSCNode initializer = binding.getOptionalNodeProperty("initializer"); - JLeftPadded bindingInitializer = null; - if (initializer != null) { - bindingInitializer = padLeft(sourceBefore(TSCSyntaxKind.EqualsToken), (Expression) visitNode(initializer)); - } - - Space after = whitespace(); - Markers bindingMarkers = Markers.EMPTY; - if (i < elements.size() - 1) { - consumeToken(TSCSyntaxKind.CommaToken); - } else { - // check for trailing comma. - TSCSyntaxKind kind = scan(); - if (kind == TSCSyntaxKind.CommaToken) { - bindingMarkers = bindingMarkers.addIfAbsent(new TrailingComma(randomId(), sourceBefore(TSCSyntaxKind.CloseBraceToken))); - } - } - - JS.ObjectBindingDeclarations.Binding b = new JS.ObjectBindingDeclarations.Binding( - randomId(), - bindingPrefix, - Markers.EMPTY, - propertyName, - name, - emptyList(), - varArg, - bindingInitializer, - null // FIXME: @Gary What is the type of an object binding declaration? - ); - bindings.add(padRight(b, after).withMarkers(bindingMarkers)); - } - - TSCNode init = bindingNode.getOptionalNodeProperty("initializer"); - return new JS.ObjectBindingDeclarations( - randomId(), - prefix, - markers, - leading.isEmpty() ? emptyList() : leading, - modifiers, - typeTree, - JContainer.build(beforeBraces, bindings, Markers.EMPTY), - init != null ? padLeft(sourceBefore(TSCSyntaxKind.EqualsToken), (Expression) visitNode(init)) : null - ); - } - - private J.Parentheses visitParenthesizedExpression(TSCNode node) { - //noinspection unchecked - return new J.Parentheses<>( - randomId(), - sourceBefore(TSCSyntaxKind.OpenParenToken), - Markers.EMPTY, - padRight((J2) visitNode(node.getNodeProperty("expression")), sourceBefore(TSCSyntaxKind.CloseParenToken)) - ); - } - - private J.FieldAccess visitPropertyAccessExpression(TSCNode node) { - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - - Expression nameExpression = (Expression) visitNode(node.getNodeProperty("expression")); - TSCNode questionToken = node.getOptionalNodeProperty("questionDotToken"); - boolean isQuestionDot = false; - if (questionToken != null) { - markers = markers.addIfAbsent(new PostFixOperator(randomId(), EMPTY, PostFixOperator.Operator.Question)); - isQuestionDot = true; - } - return new J.FieldAccess( - randomId(), - prefix, - markers, - nameExpression, - padLeft(sourceBefore(isQuestionDot ? TSCSyntaxKind.QuestionDotToken : TSCSyntaxKind.DotToken), visitIdentifier(node.getNodeProperty("name"))), - typeMapping.type(node) - ); - } - - private J.VariableDeclarations visitPropertyDeclaration(TSCNode node) { - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - - List leading = new ArrayList<>(); - List trailing = new ArrayList<>(); - List modifiers = mapModifiers(node.getOptionalNodeListProperty("modifiers"), leading, trailing); - - TSCNode varArgNode = node.getOptionalNodeProperty("dotDotDotToken"); - Space varArg = varArgNode != null ? sourceBefore(TSCSyntaxKind.DotDotDotToken) : null; - J j = visitNode(node.getNodeProperty("name")); - J.Identifier name = null; - if (j instanceof J.Identifier) { - name = (J.Identifier) j; - } else { - implementMe(node); - } - if (!trailing.isEmpty()) { - name = name.withAnnotations(trailing); - } - TypeTree typeTree = null; - TSCNode typeNode = node.getOptionalNodeProperty("type"); - if (typeNode != null) { - TSCNode questionToken = node.getOptionalNodeProperty("questionToken"); - TSCNode exclamationToken = node.getOptionalNodeProperty("exclamationToken"); - if (questionToken != null) { - markers = markers.addIfAbsent(new PostFixOperator(randomId(), sourceBefore(TSCSyntaxKind.QuestionToken), PostFixOperator.Operator.Question)); - } else if (exclamationToken != null) { - markers = markers.addIfAbsent(new PostFixOperator(randomId(), sourceBefore(TSCSyntaxKind.ExclamationToken), PostFixOperator.Operator.Exclamation)); - } - - Space beforeColon = sourceBefore(TSCSyntaxKind.ColonToken); - markers = markers.addIfAbsent(new TypeReferencePrefix(randomId(), beforeColon)); - - typeTree = (TypeTree) visitNode(typeNode); - name = name.withType(typeMapping.type(typeNode)); - } - - JLeftPadded initializer; - TSCNode initNode = node.getOptionalNodeProperty("initializer"); - if (initNode != null) { - Space beforeEquals = sourceBefore(TSCSyntaxKind.EqualsToken); - J init = visitNode(initNode); - if (init != null && !(init instanceof Expression)) { - init = new JS.StatementExpression(randomId(), (Statement) init); - } - initializer = padLeft(beforeEquals, (Expression) init); - } else { - initializer = null; - } - List> variables = new ArrayList<>(1); - variables.add(maybeSemicolon(new J.VariableDeclarations.NamedVariable( - randomId(), - EMPTY, - Markers.EMPTY, - name, - emptyList(), - initializer, - typeMapping.variableType(node) - ))); - - List> dimensions = emptyList(); - return new J.VariableDeclarations( - randomId(), - prefix, - markers, - leading.isEmpty() ? emptyList() : leading, - modifiers.isEmpty() ? emptyList() : modifiers, - typeTree, - varArg, - dimensions, - variables - ); - } - - private J visitPropertyAssignment(TSCNode node) { - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - - List leading = new ArrayList<>(); - List trailing = new ArrayList<>(); - List modifiers = mapModifiers(node.getOptionalNodeListProperty("modifiers"), leading, trailing); - - Space variablePrefix = whitespace(); - J j = visitNode(node.getOptionalNodeProperty("name")); - J.Identifier name = null; - if (j instanceof J.Identifier) { - name = (J.Identifier) j; - } else if (j instanceof J.Literal) { - // FIXME: covers code like `'Content-Type': undefined`. - // The identifier might be `Content-Type` and only use the `'` to enable `-` in the name. - // If the identifier is `Content-Type`, then use the value instead of the value source and add a marker to represent the `'`. - name = convertToIdentifier(j.getPrefix(), ((J.Literal) j).getValueSource()); - } else { - implementMe(node); - } - if (!trailing.isEmpty()) { - name = name.withAnnotations(trailing); - } - TypeTree typeTree = null; - - // The initializer on a property declaration is the type reference. - // { x : 1 } - JLeftPadded initializer; - TSCNode initNode = node.getOptionalNodeProperty("initializer"); - if (initNode != null) { - TSCNode questionToken = node.getOptionalNodeProperty("questionToken"); - TSCNode exclamationToken = node.getOptionalNodeProperty("exclamationToken"); - if (questionToken != null) { - markers = markers.addIfAbsent(new PostFixOperator(randomId(), sourceBefore(TSCSyntaxKind.QuestionToken), PostFixOperator.Operator.Question)); - } else if (exclamationToken != null) { - markers = markers.addIfAbsent(new PostFixOperator(randomId(), sourceBefore(TSCSyntaxKind.ExclamationToken), PostFixOperator.Operator.Exclamation)); - } - - Space beforeEquals = sourceBefore(TSCSyntaxKind.ColonToken); - J init = visitNode(initNode); - if (init != null && !(init instanceof Expression)) { - init = new JS.StatementExpression(randomId(), (Statement) init); - } - initializer = padLeft(beforeEquals, (Expression) init); - } else { - initializer = null; - } - - List> variables = new ArrayList<>(1); - variables.add(maybeSemicolon(new J.VariableDeclarations.NamedVariable( - randomId(), - variablePrefix, - Markers.build(singletonList(new Colon(randomId()))), - name, - emptyList(), - initializer, - typeMapping.variableType(node) - ))); - - List> dimensions = emptyList(); - return new J.VariableDeclarations( - randomId(), - prefix, - markers, - leading.isEmpty() ? emptyList() : leading, - modifiers.isEmpty() ? emptyList() : modifiers, - typeTree, - null, - dimensions, - variables - ); - } - - private J.FieldAccess visitQualifiedName(TSCNode node) { - return new J.FieldAccess( - randomId(), - whitespace(), - Markers.EMPTY, - (Expression) visitNode(node.getNodeProperty("left")), - padLeft(sourceBefore(TSCSyntaxKind.DotToken), (J.Identifier) visitNode(node.getNodeProperty("right"))), - typeMapping.type(node) - ); - } - - private J visitRegularExpressionLiteral(TSCNode node) { - Space prefix = whitespace(); - skip(node.getText()); - return new J.Literal( - randomId(), - prefix, - Markers.EMPTY, - node.getStringProperty("text"), - node.getText(), - null, - JavaType.Primitive.None - ); - } - - private J.Return visitReturnStatement(TSCNode node) { - Space prefix = sourceBefore(TSCSyntaxKind.ReturnKeyword); - Expression expression = null; - TSCNode expressionNode = node.getOptionalNodeProperty("expression"); - if (expressionNode != null) { - J j = visitNode(expressionNode); - expression = !(j instanceof Expression) && j instanceof Statement ? - new JS.StatementExpression(randomId(), (Statement) j) : (Expression) j; - } - return new J.Return( - randomId(), - prefix, - Markers.EMPTY, - expression - ); - } - - private JRightPadded visitStatement(TSCNode node) { - Statement statement = (Statement) visitNode(node); - - assert statement != null; - return maybeSemicolon(statement); - } - - private J visitSpreadElement(TSCNode node) { - Space prefix = whitespace(); - consumeToken(TSCSyntaxKind.DotDotDotToken); - return new JS.Unary( - randomId(), - prefix, - Markers.EMPTY, - padLeft(Space.EMPTY, JS.Unary.Type.Spread), - convertToExpression(visitNode(node.getNodeProperty("expression"))), - null - ); - } - - private J.Literal visitStringLiteral(TSCNode node) { - implementMe(node, "singleQuote"); - if (node.getBooleanProperty("hasExtendedUnicodeEscape")) { - implementMe(node, "hasExtendedUnicodeEscape"); - } - return new J.Literal( - randomId(), - sourceBefore(TSCSyntaxKind.StringLiteral), - Markers.EMPTY, - node.getStringProperty("text"), - node.getText(), - null, // TODO - JavaType.Primitive.String - ); - } - - private J visitTemplateExpression(TSCNode node) { - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - JRightPadded tag = null; - TSCNode templateExpression; - if (node.syntaxKind() == TSCSyntaxKind.TaggedTemplateExpression) { - J j = visitNode(node.getNodeProperty("tag")); - tag = padRight(!(j instanceof Expression) && j instanceof Statement ? - new JS.StatementExpression(randomId(), (Statement) j) : (Expression) j, whitespace()); - if (node.hasProperty("questionDotToken")) { - markers = markers.addIfAbsent(new PostFixOperator(randomId(), sourceBefore(TSCSyntaxKind.QuestionDotToken), PostFixOperator.Operator.QuestionDot)); - } - templateExpression = node.getNodeProperty("template"); - } else { - templateExpression = node; - } - - TSCNode head; - if (templateExpression.syntaxKind() == TSCSyntaxKind.NoSubstitutionTemplateLiteral) { - head = node; - } else { - head = templateExpression.getNodeProperty("head"); - } - - String text = head.getStringProperty("text"); - String rawText = head.getStringProperty("rawText"); - String delimiter = String.valueOf(head.getText().charAt(0)); - boolean isEnclosedInBraces = head.getText().endsWith("{"); - - skip(delimiter); - List spans = templateExpression.syntaxKind() == TSCSyntaxKind.NoSubstitutionTemplateLiteral ? emptyList() : - templateExpression.getNodeListProperty("templateSpans"); - List elements = new ArrayList<>(spans.size() * 2 + 1); - if (!rawText.isEmpty()) { - skip(rawText); - elements.add(new J.Literal( - randomId(), - EMPTY, - Markers.EMPTY, - text, - rawText, - null, - JavaType.Primitive.String - )); - } - - for (TSCNode span : spans) { - // Skip past the ${ characters. - cursor(getCursor() + (isEnclosedInBraces ? 2 : 1)); - - elements.add(new JS.TemplateExpression.Value( - randomId(), - EMPTY, - Markers.EMPTY, - visitNode(span.getNodeProperty("expression")), - whitespace(), - isEnclosedInBraces - )); - consumeToken(TSCSyntaxKind.CloseBraceToken); - - TSCNode literal = span.getNodeProperty("literal"); - String snapText = literal.getStringProperty("text"); - String spanRawText = literal.getStringProperty("rawText"); - if (!spanRawText.isEmpty()) { - skip(spanRawText); - elements.add(new J.Literal( - randomId(), - EMPTY, - Markers.EMPTY, - snapText, - spanRawText, - null, - JavaType.Primitive.String - )); - } - - if (literal.syntaxKind() == TSCSyntaxKind.TemplateTail) { - skip(delimiter); - } else { - isEnclosedInBraces = literal.getText().endsWith("{"); - } - } - - if (templateExpression.syntaxKind() == TSCSyntaxKind.NoSubstitutionTemplateLiteral) { - skip(delimiter); - } - return new JS.TemplateExpression( - randomId(), - prefix, - markers, - delimiter, - tag, - elements, - typeMapping.type(node) - ); - } - - private J visitSwitchStatement(TSCNode node) { - Space prefix = sourceBefore(TSCSyntaxKind.SwitchKeyword); - - Space before = sourceBefore(TSCSyntaxKind.OpenParenToken); - J j = visitNode(node.getNodeProperty("expression")); - J.ControlParentheses selector = new J.ControlParentheses<>( - randomId(), - before, - Markers.EMPTY, - padRight(!(j instanceof Expression) && j instanceof Statement ? - new JS.StatementExpression(randomId(), (Statement) j) : (Expression) j, sourceBefore(TSCSyntaxKind.CloseParenToken)) - ); - TSCNode caseBlock = node.getNodeProperty("caseBlock"); - return new J.Switch( - randomId(), - prefix, - Markers.EMPTY, - selector, - new J.Block(randomId(), sourceBefore(TSCSyntaxKind.OpenBraceToken), Markers.EMPTY, new JRightPadded<>(false, EMPTY, Markers.EMPTY), - convertAll(caseBlock.getNodeListProperty("clauses"), noDelim, noDelim, true), sourceBefore(TSCSyntaxKind.CloseBraceToken)) - ); - } - - private J.Throw visitThrowStatement(TSCNode node) { - return new J.Throw( - randomId(), - sourceBefore(TSCSyntaxKind.ThrowKeyword), - Markers.EMPTY, - (Expression) visitNode(node.getNodeProperty("expression")) - ); - } - - private J.Try visitTryStatement(TSCNode node) { - Space prefix = sourceBefore(TSCSyntaxKind.TryKeyword); - J.Block tryBlock = (J.Block) visitNode(node.getNodeProperty("tryBlock")); - - TSCNode catchClause = node.getNodeProperty("catchClause"); - J.Try.Catch aCatch = new J.Try.Catch( - randomId(), - sourceBefore(TSCSyntaxKind.CatchKeyword), - Markers.EMPTY, - mapControlParentheses(catchClause.getNodeProperty("variableDeclaration")), - (J.Block) visitNode(catchClause.getNodeProperty("block")) - ); - - JLeftPadded finallyBlock = null; - TSCNode finallyBlockNode = node.getOptionalNodeProperty("finallyBlock"); - if (finallyBlockNode != null) { - finallyBlock = padLeft(sourceBefore(TSCSyntaxKind.FinallyKeyword), (J.Block) visitNode(finallyBlockNode)); - } - - return new J.Try( - randomId(), - prefix, - Markers.EMPTY, - null, - tryBlock, - singletonList(aCatch), - finallyBlock - ); - } - - private J visitTupleType(TSCNode node) { - Space prefix = whitespace(); - TSCNodeList nodes = node.getOptionalNodeListProperty("elements"); - JContainer types = mapContainer( - TSCSyntaxKind.OpenBracketToken, - nodes == null ? emptyList() : nodes, - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.CloseBracketToken, - this::visitNode, - true - ); - return new JS.Tuple( - randomId(), - prefix, - Markers.EMPTY, - types, - typeMapping.type(node) - ); - } - - private J visitTypeAliasDeclaration(TSCNode node) { - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - - List leading = new ArrayList<>(); - List trailing = new ArrayList<>(); - List modifiers = mapModifiers(node.getOptionalNodeListProperty("modifiers"), leading, trailing); - - Space before = whitespace(); - modifiers.add(mapModifier(before, "type", trailing)); - - TSCNode nameNode = node.getNodeProperty("name"); - J.Identifier name = (J.Identifier) visitNode(nameNode); - name = name.withType(typeMapping.type(nameNode)); - J.TypeParameters typeParameters = mapTypeParameters(node.getOptionalNodeListProperty("typeParameters")); - - Space beforeEquals = sourceBefore(TSCSyntaxKind.EqualsToken); - J j = visitNode(node.getNodeProperty("type")); - JLeftPadded initializer = padLeft(beforeEquals, !(j instanceof Expression) && j instanceof Statement ? - new JS.StatementExpression(randomId(), (Statement) j) : (Expression) j); - - return new JS.TypeDeclaration( - randomId(), - prefix, - markers, - leading, - modifiers, - name, - typeParameters, - initializer, - typeMapping.type(node) - ); - } - - private J visitTypeLiteral(TSCNode node) { - Space prefix = whitespace(); - return mapPropertyNodesToNewClass( node.getOptionalNodeListProperty("members"), prefix); - } - - private JS.TypeOperator visitTypeOperator(TSCNode node) { - Space prefix = whitespace(); - - TSCSyntaxKind op = node.getSyntaxKindProperty("operator"); - JS.TypeOperator.Type operator = null; - Space before = EMPTY; - if (op == TSCSyntaxKind.ReadonlyKeyword) { - before = sourceBefore(TSCSyntaxKind.ReadonlyKeyword); - operator = JS.TypeOperator.Type.ReadOnly; - } else if (op == TSCSyntaxKind.KeyOfKeyword) { - before = sourceBefore(TSCSyntaxKind.KeyOfKeyword); - operator = JS.TypeOperator.Type.KeyOf; - } else { - implementMe(node); - } - - return new JS.TypeOperator( - randomId(), - prefix, - Markers.EMPTY, - operator, - padLeft(before, (Expression) visitNode(node.getNodeProperty("type"))) - ); - } - - private J.TypeParameter visitTypeParameter(TSCNode node) { - Space prefix = whitespace(); - List leading = new ArrayList<>(); - List trailing = new ArrayList<>(); - List modifiers = mapModifiers(node.getOptionalNodeListProperty("modifiers"), leading, trailing); - if (!trailing.isEmpty()) { - throw new UnsupportedOperationException("Add support for trailing annotations on: " + node.getText()); - } - implementMe(node, "expression"); - TSCNode defaultType = node.getOptionalNodeProperty("default"); - Expression name = (Expression) visitNode(node.getNodeProperty("name")); - - if (defaultType != null) { - name = new JS.DefaultType( - randomId(), - name.getPrefix(), - Markers.EMPTY, - name.withPrefix(EMPTY), - sourceBefore(TSCSyntaxKind.EqualsToken), - (Expression) visitNode(defaultType), - typeMapping.type(defaultType) - ); - } - - TSCNode constraint = node.getOptionalNodeProperty("constraint"); - JContainer bounds; - if (constraint == null) { - bounds = null; - } else if (constraint.syntaxKind() == TSCSyntaxKind.IntersectionType) { - bounds = JContainer.build( - sourceBefore(TSCSyntaxKind.ExtendsKeyword), - convertAll(constraint.getNodeListProperty("types"), t -> sourceBefore(TSCSyntaxKind.AmpersandToken), noDelim, true), - Markers.EMPTY); - } else { - bounds = JContainer.build( - sourceBefore(TSCSyntaxKind.ExtendsKeyword), - convertAll(singletonList(constraint), t -> sourceBefore(TSCSyntaxKind.AmpersandToken), noDelim, true), - Markers.EMPTY); - } - - return new J.TypeParameter( - randomId(), - prefix, - Markers.EMPTY, - leading.isEmpty() ? emptyList() : leading, - modifiers, - name, - bounds - ); - } - - private J.ParameterizedType visitTypeReference(TSCNode node) { - TSCNodeList typeArguments = node.getOptionalNodeListProperty("typeArguments"); - return new J.ParameterizedType( - randomId(), - whitespace(), - Markers.EMPTY, - (NameTree) visitNode(node.getNodeProperty("typeName")), - typeArguments == null ? null : - mapContainer( - TSCSyntaxKind.LessThanToken, - typeArguments, - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.GreaterThanToken, - t -> (Expression) visitNode(t), - true - ), - typeMapping.type(node) - ); - } - - private J.Unary visitUnaryExpression(TSCNode node) { - Space prefix = whitespace(); - - JLeftPadded op = null; - TSCSyntaxKind opKind = TSCSyntaxKind.fromCode(node.getIntProperty("operator")); - Expression expression; - if (node.syntaxKind() == TSCSyntaxKind.PrefixUnaryExpression) { - if (opKind == TSCSyntaxKind.ExclamationToken) { - op = padLeft(sourceBefore(TSCSyntaxKind.ExclamationToken), J.Unary.Type.Not); - } else if (opKind == TSCSyntaxKind.MinusMinusToken) { - op = padLeft(sourceBefore(TSCSyntaxKind.MinusMinusToken), J.Unary.Type.PreDecrement); - } else if (opKind == TSCSyntaxKind.PlusPlusToken) { - op = padLeft(sourceBefore(TSCSyntaxKind.PlusPlusToken), J.Unary.Type.PreIncrement); - } else if (opKind == TSCSyntaxKind.MinusToken) { - op = padLeft(sourceBefore(TSCSyntaxKind.MinusToken), J.Unary.Type.Negative); - } else if (opKind == TSCSyntaxKind.PlusToken) { - op = padLeft(sourceBefore(TSCSyntaxKind.PlusToken), J.Unary.Type.Positive); - } else { - implementMe(node); - } - expression = (Expression) visitNode(node.getNodeProperty("operand")); - } else { - expression = (Expression) visitNode(node.getNodeProperty("operand")); - if (opKind == TSCSyntaxKind.MinusMinusToken) { - op = padLeft(sourceBefore(TSCSyntaxKind.MinusMinusToken), J.Unary.Type.PostDecrement); - } else if (opKind == TSCSyntaxKind.PlusPlusToken) { - op = padLeft(sourceBefore(TSCSyntaxKind.PlusPlusToken), J.Unary.Type.PostIncrement); - } else { - implementMe(node); - } - } - - return new J.Unary( - randomId(), - prefix, - Markers.EMPTY, - op, - expression, - typeMapping.type(node) - ); - } - - private JS.Union visitUnionType(TSCNode node) { - Space prefix = whitespace(); - return new JS.Union( - randomId(), - prefix, - Markers.EMPTY, - convertAll(node.getNodeListProperty("types"), t -> sourceBefore(TSCSyntaxKind.BarToken), t -> EMPTY, true), - TsType.Union - ); - } - - private J.VariableDeclarations visitVariableDeclaration(TSCNode node) { - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - - List leading = new ArrayList<>(); - List trailing = new ArrayList<>(); - List modifiers = mapModifiers(node.getOptionalNodeListProperty("modifiers"), leading, trailing); - int saveCursor = getCursor(); - Space beforeVariableModifier = whitespace(); - TSCSyntaxKind keyword = scan(); - if (keyword == TSCSyntaxKind.ConstKeyword) { - modifiers.add(mapModifier(beforeVariableModifier, "const", trailing)); - trailing = null; - } else if (keyword == TSCSyntaxKind.LetKeyword) { - modifiers.add(mapModifier(beforeVariableModifier, "let", trailing)); - trailing = null; - } else if (keyword == TSCSyntaxKind.VarKeyword) { - modifiers.add(mapModifier(beforeVariableModifier, "var", trailing)); - trailing = null; - } else { - cursor(saveCursor); - } - - TypeTree typeTree = null; - List> namedVariables = new ArrayList<>(1); - Space variablePrefix = whitespace(); - J j = visitNode(node.getNodeProperty("name")); - J.Identifier name = null; - if (j instanceof J.Identifier) { - name = (J.Identifier) j; - if (!trailing.isEmpty()) { - name = name.withAnnotations(trailing); - } - } else { - implementMe(node); - } - - Markers variableMarker = Markers.EMPTY; - TSCNode type = node.getOptionalNodeProperty("type"); - if (type != null) { - TSCNode questionToken = node.getOptionalNodeProperty("questionToken"); - TSCNode exclamationToken = node.getOptionalNodeProperty("exclamationToken"); - if (questionToken != null) { - markers = markers.addIfAbsent(new PostFixOperator(randomId(), sourceBefore(TSCSyntaxKind.QuestionToken), PostFixOperator.Operator.Question)); - } else if (exclamationToken != null) { - markers = markers.addIfAbsent(new PostFixOperator(randomId(), sourceBefore(TSCSyntaxKind.ExclamationToken), PostFixOperator.Operator.Exclamation)); - } - - Space beforeColon = sourceBefore(TSCSyntaxKind.ColonToken); - markers = markers.addIfAbsent(new TypeReferencePrefix(randomId(), beforeColon)); - typeTree = (TypeTree) visitNode(type); - } - TSCNode init = node.getOptionalNodeProperty("initializer"); - J.VariableDeclarations.NamedVariable variable = new J.VariableDeclarations.NamedVariable( - randomId(), - variablePrefix, - variableMarker, - name, - emptyList(), - init != null ? - padLeft(sourceBefore(TSCSyntaxKind.EqualsToken), - (Expression) Objects.requireNonNull(visitNode(init))) : null, - typeMapping.variableType(node) - ); - - namedVariables.add(padRight(variable, EMPTY)); - - return new J.VariableDeclarations( - randomId(), - prefix, - markers, - leading.isEmpty() ? emptyList() : leading, - modifiers.isEmpty() ? emptyList() : modifiers, - typeTree, - null, - emptyList(), - namedVariables - ); - } - - private J.VariableDeclarations visitVariableDeclarationList(TSCNode node) { - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - - Space beforeVariableModifier = whitespace(); - TSCSyntaxKind keyword = scan(); - List modifiers = new ArrayList<>(); - if (keyword == TSCSyntaxKind.ConstKeyword) { - modifiers.add(mapModifier(beforeVariableModifier, "const", null)); - } else if (keyword == TSCSyntaxKind.LetKeyword) { - modifiers.add(mapModifier(beforeVariableModifier, "let", null)); - } else if (keyword == TSCSyntaxKind.VarKeyword) { - modifiers.add(mapModifier(beforeVariableModifier, "var", null)); - } else { - // Unclear if the modifier should be `@Nullable` in the `JSVariableDeclaration`. - throw new UnsupportedOperationException("Unsupported variable modifier."); - } - - List> namedVariables = emptyList(); - TypeTree typeTree = null; - TSCNodeList declarations = node.getOptionalNodeListProperty("declarations"); - if (declarations != null) { - Set types = new HashSet<>(declarations.size()); - namedVariables = new ArrayList<>(declarations.size()); - for (int i = 0; i < declarations.size(); i++) { - TSCNode declaration = declarations.get(i); - - Space variablePrefix = whitespace(); - J j = visitNode(declaration.getNodeProperty("name")); - J.Identifier name = null; - if (j instanceof J.Identifier) { - name = (J.Identifier) j; - } else { - implementMe(declaration); - } - - TSCNode type = declaration.getOptionalNodeProperty("type"); - if (type != null) { - TSCNode questionToken = node.getOptionalNodeProperty("questionToken"); - TSCNode exclamationToken = node.getOptionalNodeProperty("exclamationToken"); - if (questionToken != null) { - markers = markers.addIfAbsent(new PostFixOperator(randomId(), sourceBefore(TSCSyntaxKind.QuestionToken), PostFixOperator.Operator.Question)); - } else if (exclamationToken != null) { - markers = markers.addIfAbsent(new PostFixOperator(randomId(), sourceBefore(TSCSyntaxKind.ExclamationToken), PostFixOperator.Operator.Exclamation)); - } - - Space beforeColon = sourceBefore(TSCSyntaxKind.ColonToken); - markers = markers.addIfAbsent(new TypeReferencePrefix(randomId(), beforeColon)); - typeTree = (TypeTree) visitNode(type); - if (typeTree.getType() != null) { - types.add(typeTree.getType()); - if (types.size() > 1) { - throw new UnsupportedOperationException("Multiple variable types are not supported"); - } - } - } - TSCNode init = declaration.getOptionalNodeProperty("initializer"); - J.VariableDeclarations.NamedVariable variable = new J.VariableDeclarations.NamedVariable( - randomId(), - variablePrefix, - Markers.EMPTY, - name, - emptyList(), - init != null ? - padLeft(sourceBefore(TSCSyntaxKind.EqualsToken), - (Expression) Objects.requireNonNull(visitNode(init))) : null, - typeMapping.variableType(declaration) - ); - - Space after = whitespace(); - if (i < declarations.size() - 1) { - consumeToken(TSCSyntaxKind.CommaToken); - } - namedVariables.add(padRight(variable, after)); - } - } - - return new J.VariableDeclarations( - randomId(), - prefix, - markers, - emptyList(), - modifiers.isEmpty() ? emptyList() : modifiers, - typeTree, - null, - emptyList(), - namedVariables - ); - } - - private J.VariableDeclarations visitVariableStatement(TSCNode node) { - Space prefix = whitespace(); - Markers markers = Markers.EMPTY; - - implementMe(node, "exclamationToken"); - - List leading = new ArrayList<>(); - List trailing = new ArrayList<>(); - List modifiers = mapModifiers(node.getOptionalNodeListProperty("modifiers"), leading, trailing); - - Space beforeVariableModifier = whitespace(); - TSCSyntaxKind keyword = scan(); - if (keyword == TSCSyntaxKind.ConstKeyword) { - modifiers.add(mapModifier(beforeVariableModifier, "const", trailing)); - } else if (keyword == TSCSyntaxKind.LetKeyword) { - modifiers.add(mapModifier(beforeVariableModifier, "let", trailing)); - } else if (keyword == TSCSyntaxKind.VarKeyword) { - modifiers.add(mapModifier(beforeVariableModifier, "var", trailing)); - } else { - // Unclear if the modifier should be `@Nullable` in the `JSVariableDeclaration`. - throw new UnsupportedOperationException("Unsupported variable modifier."); - } - - List> namedVariables; - TypeTree typeTree = null; - - TSCNode declarationList = node.getOptionalNodeProperty("declarationList"); - List declarations = declarationList == null ? - emptyList() : declarationList.getNodeListProperty("declarations"); - - Set types = new HashSet<>(declarations.size()); - namedVariables = new ArrayList<>(declarations.size()); - - for (int i = 0; i < declarations.size(); i++) { - TSCNode declaration = declarations.get(i); - - Space variablePrefix = whitespace(); - J j = visitNode(declaration.getNodeProperty("name")); - J.Identifier name = null; - if (j instanceof J.Identifier) { - name = (J.Identifier) j; - } else { - implementMe(declaration); - } - - TSCNode type = declaration.getOptionalNodeProperty("type"); - if (type != null) { - Space beforeColon = sourceBefore(TSCSyntaxKind.ColonToken); - markers = markers.addIfAbsent(new TypeReferencePrefix(randomId(), beforeColon)); - typeTree = (TypeTree) visitNode(type); - if (typeTree.getType() != null) { - types.add(typeTree.getType()); - // TS allows for multiple variable types to be expressed in a single statement. - // The count is used to prevent a malformed LST element until multiple variable types are supported. - if (types.size() > 1) { - throw new UnsupportedOperationException("Multiple variable types are not supported"); - } - } - } - JLeftPadded initializer = null; - TSCNode init = declaration.getOptionalNodeProperty("initializer"); - if (init != null) { - Space before = sourceBefore(TSCSyntaxKind.EqualsToken); - J element = visitNode(init); - if (!(element instanceof Expression) && element instanceof Statement) { - initializer = padLeft(before, new JS.StatementExpression(randomId(), (Statement) element)); - } else if (element instanceof Expression) { - initializer = padLeft(before, (Expression) element); - } else { - implementMe(init); - } - } - J.VariableDeclarations.NamedVariable variable = new J.VariableDeclarations.NamedVariable( - randomId(), - variablePrefix, - Markers.EMPTY, - name, - emptyList(), - initializer, - typeMapping.variableType(declaration) - ); - - Space after = whitespace(); - if (i < declarations.size() - 1) { - consumeToken(TSCSyntaxKind.CommaToken); - } - namedVariables.add(padRight(variable, after)); - } - - return new J.VariableDeclarations( - randomId(), - prefix, - markers, - leading.isEmpty() ? emptyList() : leading, - modifiers.isEmpty() ? emptyList() : modifiers, - typeTree, - null, - emptyList(), - namedVariables - ); - } - - private J.WhileLoop visitWhileStatement(TSCNode node) { - Space prefix = sourceBefore(TSCSyntaxKind.WhileKeyword); - J.ControlParentheses control = mapControlParentheses(node.getNodeProperty("expression")); - return new J.WhileLoop( - randomId(), - prefix, - Markers.EMPTY, - control, - maybeSemicolon((Statement) visitNode(node.getNodeProperty("statement"))) - ); - } - - private J visitYieldExpression(TSCNode node) { - Space prefix = sourceBefore(TSCSyntaxKind.YieldKeyword); - Markers markers = Markers.EMPTY; - if (node.hasProperty("asteriskToken")) { - markers = markers.add(new Asterisk(randomId(), sourceBefore(TSCSyntaxKind.AsteriskToken))); - } - J j = visitNode(node.getNodeProperty("expression")); - Expression expr = (!(j instanceof Expression) && j instanceof Statement) ? - new JS.StatementExpression(randomId(), (Statement) j) : (Expression) j; - return new J.Yield( - randomId(), - prefix, - markers, - false, // FIXME - expr - ); - } - - private @Nullable J visitNode(@Nullable TSCNode node) { - if (node == null) { - return null; - } - - J j; - switch (node.syntaxKind()) { - // Multi-case statements - case ClassDeclaration: - case ClassExpression: - case EnumDeclaration: - case InterfaceDeclaration: - j = visitClassDeclaration(node); - break; - case AnyKeyword: - case AsyncKeyword: - case BooleanKeyword: - case DeclareKeyword: - case DefaultKeyword: - case ExportKeyword: - case NumberKeyword: - case NullKeyword: - case ReadonlyKeyword: - case StringKeyword: - case SuperKeyword: - case ThisKeyword: - case UndefinedKeyword: - case UnknownKeyword: - case VoidKeyword: - j = visitKeyword(node); - break; - case FalseKeyword: - case TrueKeyword: - j = mapKeywordToLiteralType(node); - break; - case ForOfStatement: - case ForInStatement: - j = visitForEachStatement(node); - break; - case FunctionDeclaration: - case FunctionExpression: - j = visitFunctionDeclaration(node); - break; - case ExportSpecifier: - case ImportSpecifier: - j = visitExportSpecifier(node); - break; - case ImportEqualsDeclaration: - case ImportDeclaration: - j = visitImportDeclaration(node); - break; - case CallSignature: - case MethodDeclaration: - case MethodSignature: - j = visitMethodDeclaration(node); - break; - case BindingElement: - case Parameter: - case PropertyDeclaration: - j = visitPropertyDeclaration(node); - break; - case NoSubstitutionTemplateLiteral: - case TaggedTemplateExpression: - case TemplateExpression: - j = visitTemplateExpression(node); - break; - case PostfixUnaryExpression: - case PrefixUnaryExpression: - j = visitUnaryExpression(node); - break; - case PropertySignature: - case VariableDeclaration: - j = visitVariableDeclaration(node); - break; - // Single case statements - case ArrayBindingPattern: - j = visitArrayBindingPattern(node); - break; - case ArrowFunction: - j = visitArrowFunction(node); - break; - case ArrayLiteralExpression: - j = visitArrayLiteralExpression(node); - break; - case ArrayType: - j = mapArrayType(node); - break; - case AsExpression: - j = visitAsExpression(node); - break; - case BinaryExpression: - j = visitBinaryExpression(node); - break; - case Block: - j = visitBlock(node); - break; - case BreakStatement: - j = visitBreakStatement(node); - break; - case CallExpression: - j = visitCallExpression(node); - break; - case CaseClause: - j = visitCaseClause(node); - break; - case ConditionalExpression: - j = visitConditionalExpression(node); - break; - case ContinueStatement: - j = visitContinueStatement(node); - break; - case Constructor: - j = visitConstructor(node); - break; - case Decorator: - j = visitDecorator(node); - break; - case DefaultClause: - j = visitDefaultClause(node); - break; - case DeleteExpression: - j = visitDeleteExpression(node); - break; - case DoStatement: - j = visitDoStatement(node); - break; - case ElementAccessExpression: - j = visitElementAccessExpression(node); - break; - case EmptyStatement: - j = visitEmptyStatement(node); - break; - case EnumMember: - j = visitEnumMember(node); - break; - case ExportAssignment: - j = visitExportAssignment(node); - break; - case ExportDeclaration: - j = visitExportDeclaration(node); - break; - case ExpressionStatement: - j = visitExpressionStatement(node); - break; - case ExpressionWithTypeArguments: - j = visitExpressionWithTypeArguments(node); - break; - case ExternalModuleReference: - j = visitExternalModuleReference(node); - break; - case Identifier: - j = visitIdentifier(node); - break; - case IfStatement: - j = visitIfStatement(node); - break; - case IndexedAccessType: - j = visitIndexedAccessType(node); - break; - case ForStatement: - j = visitForStatement(node); - break; - case FunctionType: - j = visitFunctionType(node); - break; - case LabeledStatement: - j = visitLabelledStatement(node); - break; - case LiteralType: - j = visitLiteralType(node); - break; - case MetaProperty: - j = visitMetaProperty(node); - break; - case NewExpression: - j = visitNewExpression(node); - break; - case NumericLiteral: - j = visitNumericLiteral(node); - break; - case ObjectLiteralExpression: - j = visitObjectLiteralExpression(node); - break; - case ParenthesizedExpression: - j = visitParenthesizedExpression(node); - break; - case PropertyAccessExpression: - j = visitPropertyAccessExpression(node); - break; - case PropertyAssignment: - j = visitPropertyAssignment(node); - break; - case QualifiedName: - j = visitQualifiedName(node); - break; - case RegularExpressionLiteral: - j = visitRegularExpressionLiteral(node); - break; - case ReturnStatement: - j = visitReturnStatement(node); - break; - case SpreadElement: - j = visitSpreadElement(node); - break; - case StringLiteral: - j = visitStringLiteral(node); - break; - case SwitchStatement: - j = visitSwitchStatement(node); - break; - case ThrowStatement: - j = visitThrowStatement(node); - break; - case TryStatement: - j = visitTryStatement(node); - break; - case TupleType: - j = visitTupleType(node); - break; - case TypeAliasDeclaration: - j = visitTypeAliasDeclaration(node); - break; - case TypeLiteral: - j = visitTypeLiteral(node); - break; - case TypeOperator: - j = visitTypeOperator(node); - break; - case TypeParameter: - j = visitTypeParameter(node); - break; - case TypeReference: - j = visitTypeReference(node); - break; - case UnionType: - j = visitUnionType(node); - break; - case VariableDeclarationList: - j = visitVariableDeclarationList(node); - break; - case VariableStatement: - j = mapVariableStatement(node); - break; - case WhileStatement: - j = visitWhileStatement(node); - break; - case YieldExpression: - j = visitYieldExpression(node); - break; - default: - implementMe(node); - j = null; - } - return j; - } - - private final Function commaDelim = ignored -> sourceBefore(TSCSyntaxKind.CommaToken); - private final Function noDelim = ignored -> EMPTY; - - /** - * Returns the current cursor position in the TSC.Context. - */ - private Integer getCursor() { - return this.cursorContext.scannerTokenEnd(); - } - - - /** - * Consume the provided text if it matches the current cursor position. - */ - private void skip(String text) { - if (sourceStartsWithAtCursor(text)) { - cursor(getCursor() + text.length()); - } - } - - /** - * Set the cursor position to the specified index. - */ - private void cursor(int cursor) { - this.cursorContext.resetScanner(cursor); - } - - private JLeftPadded padLeft(Space left, T tree) { - return new JLeftPadded<>(left, tree, Markers.EMPTY); - } - - private JRightPadded padRight(T tree, @Nullable Space right) { - return new JRightPadded<>(tree, right == null ? EMPTY : right, Markers.EMPTY); - } - - private JRightPadded padRight(T tree, @Nullable Space right, Markers markers) { - return new JRightPadded<>(tree, right == null ? EMPTY : right, markers); - } - - private JRightPadded maybeSemicolon(K2 k) { - return tryConsumeWithPrefix( - TSCSyntaxKind.SemicolonToken, - prefix -> new JRightPadded<>(k, prefix, Markers.EMPTY.add(new Semicolon(randomId()))) - ).orElseGet(() -> JRightPadded.build(k)); - } - - private boolean tryConsume(TSCSyntaxKind kind) { - int saveCursor = getCursor(); - if (scan() == kind) { - return true; - } else { - cursorContext.resetScanner(saveCursor); - return false; - } - } - - private Optional tryConsumeWithPrefix(TSCSyntaxKind kind, Function whenMatched) { - int saveCursor = getCursor(); - Space prefix = whitespace(); - if (scan() == kind) { - return Optional.of(whenMatched.apply(prefix)); - } else { - cursorContext.resetScanner(saveCursor); - return Optional.empty(); - } - } - - private TSCSyntaxKind scan() { - return this.cursorContext.nextScannerSyntaxType(); - } - - private String lastToken() { - return this.cursorContext.scannerTokenText(); - } - - private void consumeToken(TSCSyntaxKind kind) { - TSCSyntaxKind actual = scan(); - if (kind != actual) { - throw new IllegalStateException(String.format("expected kind '%s'; found '%s' at position %d", kind, actual, cursorContext.scannerTokenStart())); - } - } - - private List> convertAll(List elements, - Function innerSuffix, - Function suffix) { - return convertAll(elements, innerSuffix, suffix, false); - } - - private List> convertAll(List elements, - Function innerSuffix, - Function suffix, - boolean enableParseErrorRecovery) { - - if (elements.isEmpty()) { - return emptyList(); - } - - List> converted = new ArrayList<>(elements.size()); - for (int i = 0; i < elements.size(); i++) { - TSCNode element = elements.get(i); - int saveCursor = getCursor(); - J2 j; - try { - //noinspection unchecked - j = (J2) visitNode(element); - } catch (Exception e) { - if (!enableParseErrorRecovery) { - throw new JavaScriptParsingException("Unable to parse JavaScript", e); - } - - cursor(saveCursor); - Space prefix = whitespace(); - String text = element.getText(); - skip(text); - //noinspection unchecked - j = (J2) new J.Unknown( - randomId(), - prefix, - Markers.EMPTY, - new J.Unknown.Source( - randomId(), - EMPTY, - Markers.build(singletonList(ParseExceptionResult.build(JavaScriptParser.builder().build(), e) - .withTreeType(element.syntaxKind().name()))), - text)); - } - Space after = i == elements.size() - 1 ? suffix.apply(element) : innerSuffix.apply(element); - if (j == null && i < elements.size() - 1) { - continue; - } - if (j == null) { - //noinspection unchecked - j = (J2) new J.Empty(randomId(), EMPTY, Markers.EMPTY); - } - JRightPadded rightPadded = padRight(j, after); - converted.add(rightPadded); - } - return converted.isEmpty() ? emptyList() : converted; - } - - /** - * Converts a String that does not require type attribution to a J.Identifier. - * Primarily used to convert keywords that do not exist in J to a J.Identifier. - *

- * Note: the cursor must be incremented before the call. - * @param simpleName the String to convert. - * @return a J.Identifier representing the String. - */ - private J.Identifier convertToIdentifier(Space prefix, String simpleName) { - return new J.Identifier(randomId(), prefix, Markers.EMPTY, emptyList(), simpleName, null, null); - } - - private J.Literal mapKeywordToLiteralType(TSCNode node) { - Space prefix = sourceBefore(node.syntaxKind()); - Object value; - String valueSource; - JavaType.Primitive primitiveType; - if (node.syntaxKind() == TSCSyntaxKind.TrueKeyword) { - value = true; - valueSource = "true"; - primitiveType = JavaType.Primitive.Boolean; - } else if (node.syntaxKind() == TSCSyntaxKind.FalseKeyword) { - value = false; - valueSource = "false"; - primitiveType = JavaType.Primitive.Boolean; - } else { - throw new IllegalArgumentException("Cannot convert node to literal type: " + node.syntaxKind()); - } - return new J.Literal(randomId(), prefix, Markers.EMPTY, value, valueSource, null, primitiveType); - } - - private JContainer mapContainer(TSCSyntaxKind open, List nodes, @Nullable TSCSyntaxKind delimiter, TSCSyntaxKind close, Function visitFn) { - return mapContainer(open, nodes, delimiter, close, visitFn, false); - } - - private JContainer mapContainer(TSCSyntaxKind open, List nodes, @Nullable TSCSyntaxKind delimiter, TSCSyntaxKind close, Function visitFn, boolean withUnknown) { - Space containerPrefix = sourceBefore(open); - List> elements; - if (nodes.isEmpty()) { - Space withinContainerSpace = whitespace(); - //noinspection unchecked - elements = Collections.singletonList( - JRightPadded.build((T) new J.Empty(randomId(), withinContainerSpace, Markers.EMPTY)) - ); - } else { - elements = new ArrayList<>(nodes.size()); - for (int i = 0; i < nodes.size(); i++) { - TSCNode node = nodes.get(i); - int saveCursor = getCursor(); - T visited; - try { - visited = visitFn.apply(node); - } catch (Exception e) { - if (withUnknown) { - cursor(saveCursor); - Space prefix = whitespace(); - String text = node.getText(); - skip(text); - //noinspection unchecked - visited = (T) new J.Unknown( - randomId(), - prefix, - Markers.EMPTY, - new J.Unknown.Source( - randomId(), - EMPTY, - Markers.build(singletonList(ParseExceptionResult.build(JavaScriptParser.builder().build(), e) - .withTreeType(node.syntaxKind().name()))), - text)); - } else { - throw e; - } - } - Markers markers = Markers.EMPTY; - Space after = EMPTY; - if (delimiter != null) { - if (i < nodes.size() - 1) { - after = sourceBefore(delimiter); - } else if (delimiter == TSCSyntaxKind.CommaToken) { - after = whitespace(); - if (tryConsume(TSCSyntaxKind.CommaToken)) { - markers = markers.add(new TrailingComma(randomId(), whitespace())); - } - } else { - after = whitespace(); - } - } - elements.add(JRightPadded.build(visited).withAfter(after).withMarkers(markers)); - } - } - consumeToken(close); - return JContainer.build(containerPrefix, elements, Markers.EMPTY); - } - - private J.ControlParentheses mapControlParentheses(TSCNode node) { - //noinspection unchecked - return new J.ControlParentheses<>( - randomId(), - sourceBefore(TSCSyntaxKind.OpenParenToken), - Markers.EMPTY, - padRight((J2) visitNode(node), sourceBefore(TSCSyntaxKind.CloseParenToken)) - ); - } - - private J.ArrayType mapArrayType(TSCNode node) { - Space prefix = whitespace(); - TypeTree typeTree = (TypeTree) visitNode(node.getNodeProperty("elementType")); - - return new J.ArrayType( - randomId(), - prefix, - Markers.EMPTY, - typeTree, - null, - new JLeftPadded<>(sourceBefore(TSCSyntaxKind.OpenBracketToken), sourceBefore(TSCSyntaxKind.CloseBracketToken), Markers.EMPTY), - typeTree.getType() - ); - } - - private List mapModifiers(@Nullable List nodes, List leadingAnnotations, List trailingAnnotations) { - if (nodes == null) { - return new ArrayList<>(); - } - - List modifiers = new ArrayList<>(nodes.size()); - List leading = new ArrayList<>(); - List trailing = null; - for (TSCNode node : nodes) { - Space prefix = whitespace(); - switch (node.syntaxKind()) { - // JS/TS equivalent of an annotation. - case Decorator: { - J.Annotation annotation = (J.Annotation) visitNode(node); - if (leading != null) { - leading.add(annotation); - } else { - if (trailing == null) { - trailing = new ArrayList<>(1); - } else { - trailing.add(annotation); - } - } - break; - } - // JS/TS keywords. - case DeclareKeyword: - case DefaultKeyword: - case ExportKeyword: - case ReadonlyKeyword: { - if (!leading.isEmpty()) { - leadingAnnotations.addAll(leading); - leading = null; - } - modifiers.add(mapModifier(prefix, node.getText(), trailing)); - trailing = null; - break; - } - // Keywords that exist in J. - case AbstractKeyword: - if (!leading.isEmpty()) { - leadingAnnotations.addAll(leading); - leading = null; - } - consumeToken(TSCSyntaxKind.AbstractKeyword); - modifiers.add(new J.Modifier(randomId(), prefix, Markers.EMPTY, null, J.Modifier.Type.Abstract, trailing == null ? emptyList() : trailing)); - trailing = null; - break; - case AsyncKeyword: - if (!leading.isEmpty()) { - leadingAnnotations.addAll(leading); - leading = null; - } - consumeToken(TSCSyntaxKind.AsyncKeyword); - modifiers.add(new J.Modifier(randomId(), prefix, Markers.EMPTY, null, J.Modifier.Type.Async, trailing == null ? emptyList() : trailing)); - trailing = null; - break; - case PublicKeyword: - if (!leading.isEmpty()) { - leadingAnnotations.addAll(leading); - leading = null; - } - consumeToken(TSCSyntaxKind.PublicKeyword); - modifiers.add(new J.Modifier(randomId(), prefix, Markers.EMPTY, null, J.Modifier.Type.Public, trailing == null ? emptyList() : trailing)); - trailing = null; - break; - case PrivateKeyword: - if (!leading.isEmpty()) { - leadingAnnotations.addAll(leading); - leading = null; - } - consumeToken(TSCSyntaxKind.PrivateKeyword); - modifiers.add(new J.Modifier(randomId(), prefix, Markers.EMPTY, null, J.Modifier.Type.Private, trailing == null ? emptyList() : trailing)); - trailing = null; - break; - case ProtectedKeyword: - if (!leading.isEmpty()) { - leadingAnnotations.addAll(leading); - leading = null; - } - consumeToken(TSCSyntaxKind.ProtectedKeyword); - modifiers.add(new J.Modifier(randomId(), prefix, Markers.EMPTY, null, J.Modifier.Type.Protected, trailing == null ? emptyList() : trailing)); - trailing = null; - break; - case StaticKeyword: - if (!leading.isEmpty()) { - leadingAnnotations.addAll(leading); - leading = null; - } - consumeToken(TSCSyntaxKind.StaticKeyword); - modifiers.add(new J.Modifier(randomId(), prefix, Markers.EMPTY, null, J.Modifier.Type.Static, trailing == null ? emptyList() : trailing)); - trailing = null; - break; - default: - implementMe(node); - } - } - if (leading != null) { - leadingAnnotations.addAll(leading); - } - if (trailing != null) { - trailingAnnotations.addAll(trailing); - } - return modifiers.isEmpty() ? new ArrayList<>() : modifiers; - } - - private J.@Nullable TypeParameters mapTypeParameters(@Nullable List typeParameters) { - return typeParameters == null ? null : new J.TypeParameters(randomId(), sourceBefore(TSCSyntaxKind.LessThanToken), Markers.EMPTY, - emptyList(), - convertAll(typeParameters, commaDelim, t -> sourceBefore(TSCSyntaxKind.GreaterThanToken))); - } - - private J mapVariableStatement(TSCNode node) { - TSCNode declarationList = node.getOptionalNodeProperty("declarationList"); - List declarations = declarationList == null ? - emptyList() : declarationList.getNodeListProperty("declarations"); - if (declarationList != null) { - for (TSCNode declaration : declarations) { - if (declaration.syntaxKind() == TSCSyntaxKind.VariableDeclaration) { - TSCNode name = declaration.getOptionalNodeProperty("name"); - if (name != null && name.syntaxKind() == TSCSyntaxKind.ObjectBindingPattern) { - return mapObjectBindingDeclaration(node); - } - } - } - } - - return visitVariableStatement(node); - } - - private boolean sourceStartsWithAtCursor(String text) { - return sourceText.startsWith(text, getCursor()); - } - - private Space sourceBefore(TSCSyntaxKind syntaxKind) { - Space prefix = whitespace(); - consumeToken(syntaxKind); - return prefix; - } - - private J.Modifier mapModifier(Space prefix, String name, @Nullable List annotations) { - skip(name); - return new J.Modifier( - randomId(), - prefix, - Markers.EMPTY, - name, - J.Modifier.Type.LanguageExtension, - annotations == null ? emptyList() : annotations - ); - } - - private J.NewClass mapPropertyNodesToNewClass(List propertyNodes, Space prefix) { - return new J.NewClass( - randomId(), - prefix, - Markers.build(singletonList(new ObjectLiteral(randomId()))), - null, - EMPTY, - null, - mapContainer( - TSCSyntaxKind.OpenBraceToken, - propertyNodes, - TSCSyntaxKind.CommaToken, - TSCSyntaxKind.CloseBraceToken, - x -> convertToExpression(visitNode(x)), - true - ), - null, - null - ); - } - - @SuppressWarnings("unchecked") - private J2 convertToExpression(J j) { - if (j instanceof Statement && !(j instanceof Expression)) { - j = new JS.StatementExpression(randomId(), (Statement) j); - } - return (J2) j; - } - - - /** - * Consume whitespace and leading comments until the current node. - * The type-script spec is not actively maintained, so we need to rely on the parser elements to collect - * whitespace and comments. - */ - private Space whitespace() { - StringBuilder initialSpace = null; - List comments = Collections.emptyList(); - TSCSyntaxKind kind; - boolean done = false; - do { - kind = scan(); - switch (kind) { - case WhitespaceTrivia: - case NewLineTrivia: { - if (comments.isEmpty()) { - if (initialSpace == null) { - initialSpace = new StringBuilder(); - } - initialSpace.append(lastToken()); - } else { - Comment lastComment = comments.get(comments.size() - 1); - comments.set(comments.size() - 1, lastComment.withSuffix(lastComment.getSuffix() + lastToken())); - } - break; - } - case SingleLineCommentTrivia: - case MultiLineCommentTrivia: { - String commentText = lastToken(); - commentText = commentText.substring(2, kind == TSCSyntaxKind.SingleLineCommentTrivia ? commentText.length() : commentText.length() - 2); - Comment comment = new TextComment( - kind == TSCSyntaxKind.MultiLineCommentTrivia, - commentText, - "", - Markers.EMPTY - ); - if (comments.isEmpty()) { - comments = new ArrayList<>(1); - comments.add(comment); - } else { - comments.add(comment); - } - break; - } - default: - cursor(cursorContext.scannerTokenStart()); - done = true; - break; - } - } while (!done); - return Space.build(initialSpace == null ? null : initialSpace.toString(), comments); - } - - private J unknown(TSCNode node) { - Space prefix = whitespace(); - String text = node.getText(); - skip(text); - return new J.Unknown( - randomId(), - prefix, - Markers.EMPTY, - new J.Unknown.Source( - randomId(), - EMPTY, - Markers.build(singletonList(ParseExceptionResult.build(JavaScriptParser.builder().build(), new UnsupportedOperationException(node.syntaxKind().name() + " not implemented")) - .withTreeType(node.syntaxKind().name()))), - text)); - } - - private void implementMe(TSCNode node) { - throw new UnsupportedOperationException(node.syntaxKind() + " not implemented"); - } - - private void implementMe(TSCNode node, String propertyName) { - if (node.hasProperty(propertyName)) { - throw new UnsupportedOperationException(node.syntaxKind() + "#" + propertyName + " not implemented"); - } - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCContextCallback.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCContextCallback.java deleted file mode 100644 index 931bb2d4..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCContextCallback.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.values.V8Value; - -public interface TSCContextCallback { - V8Value apply(V8Value... args); -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCConversion.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCConversion.java deleted file mode 100644 index b36a498f..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCConversion.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.values.V8Value; -import org.jspecify.annotations.Nullable; - -public interface TSCConversion { - T convertUnsafe(TSCProgramContext context, V8Value value) throws JavetException; - - default @Nullable T convertNullable(TSCProgramContext context, V8Value value) { - try { - if (value.isNullOrUndefined()) { - return null; - } else { - return convertUnsafe(context, value); - } - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - default T convertNonNull(TSCProgramContext context, V8Value value) { - @Nullable T converted = convertNullable(context, value); - if (converted == null) { - throw new IllegalArgumentException("value converted to null, but was required to be non-null"); - } - return converted; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCConversions.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCConversions.java deleted file mode 100644 index 17948024..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCConversions.java +++ /dev/null @@ -1,220 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.primitive.*; -import com.caoccao.javet.values.reference.IV8ValueArray; -import com.caoccao.javet.values.reference.V8ValueArray; -import com.caoccao.javet.values.reference.V8ValueFunction; -import com.caoccao.javet.values.reference.V8ValueObject; -import org.openrewrite.javascript.internal.tsc.generated.TSCSignatureKind; -import org.openrewrite.javascript.internal.tsc.generated.TSCSyntaxKind; - -import java.util.*; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.IntFunction; - -public final class TSCConversions { - private TSCConversions() { - } - - public static final TSCConversion STRING = (context, value) -> { - if (!(value instanceof V8ValueString)) { - throw new IllegalArgumentException("expected V8 string"); - } - return ((V8ValueString) value).getValue(); - }; - - public static final TSCConversion BOOLEAN = (context, value) -> { - if (value instanceof V8ValueBoolean) { - return ((V8ValueBoolean) value).getValue(); - } - throw new IllegalArgumentException("expected V8 boolean"); - }; - - public static final TSCConversion INTEGER = (context, value) -> { - if (value instanceof V8ValueInteger) { - return ((V8ValueInteger) value).getValue(); - } - throw new IllegalArgumentException("expected V8 integer"); - }; - - public static final TSCConversion LONG = (context, value) -> { - if (value instanceof V8ValueLong) { - return ((V8ValueLong) value).getValue(); - } else if (value instanceof V8ValueInteger) { - return ((V8ValueInteger) value).getValue().longValue(); - } - throw new IllegalArgumentException("expected V8 long or integer"); - }; - - public static final TSCConversion INDEX_INFO = builder(TSCIndexInfo::fromJS); - public static final TSCConversion> INDEX_INFO_LIST = list(INDEX_INFO); - - public static final TSCConversion SYNTAX_KIND = enumeration(TSCSyntaxKind::fromCode); - public static final TSCConversion SIGNATURE_KIND = enumeration(TSCSignatureKind::fromCode); - - public static final TSCConversion TYPE = cached(context -> context.typeCache); - public static final TSCConversion> TYPE_LIST = list(TYPE); - - public static final TSCConversion NODE = cached(context -> context.nodeCache); - - static final TSCConversion NODE_LIST = cached(context -> context.nodeListCache); - - public static final TSCConversion TYPE_NODE = cast(NODE, TSCNode.TypeNode.class); - - public static final TSCConversion SYNTAX_LIST_NODE = cast(NODE, TSCSyntaxListNode.class); - - public static final TSCConversion SYMBOL = cached(context -> context.symbolCache); - public static final TSCConversion> SYMBOL_LIST = list(SYMBOL); - - public static final TSCConversion SIGNATURE = cached(context -> context.signatureCache); - public static final TSCConversion> SIGNATURE_LIST = list(SIGNATURE); - - public static final TSCConversion AUTO = TSCConversions::autoConvert; - - private static final ThreadLocal autoConversionDepth = ThreadLocal.withInitial(() -> 0); - private static final int MAX_AUTO_CONVERSION_DEPTH = 10; - - private static Object autoConvert(TSCProgramContext context, V8Value value) throws JavetException { - final int initialDepth = autoConversionDepth.get(); - if (initialDepth > MAX_AUTO_CONVERSION_DEPTH) { - return value.getV8Runtime().getConverter().toObject(value, true); - } - autoConversionDepth.set(initialDepth + 1); - try { - if (value instanceof V8ValuePrimitive) { - return ((V8ValuePrimitive) value).getValue(); - } - - if (value instanceof V8ValueObject) { - TSCInstanceOfChecks.InterfaceKind interfaceKind = context.getInstanceOfChecks().identifyInterfaceKind(value); - if (interfaceKind != null) { - switch (interfaceKind) { - case Node: - return NODE.convertUnsafe(context, value); - case Type: - return TYPE.convertUnsafe(context, value); - case Symbol: - return SYMBOL.convertUnsafe(context, value); - case Signature: - return SIGNATURE.convertUnsafe(context, value); - case SourceMapSource: - default: - break; - } - } - } - - if (value instanceof V8ValueArray) { - return list(AUTO).convertUnsafe(context, value); - } - - if (value instanceof V8ValueFunction) { - V8ValueFunction copy = value.toClone(); - copy.setWeak(); - return copy; - } - - if (value instanceof V8ValueObject) { - return objectMap(AUTO).convertUnsafe(context, value); - } - - // TODO better auto-conversion? - return value.getV8Runtime().getConverter().toObject(value, true); - } finally { - autoConversionDepth.set(initialDepth); - } - } - - public static TSCConversion> list(TSCConversion of) { - return (context, value) -> { - if (!(value instanceof V8ValueArray)) { - throw new IllegalArgumentException("expected V8 array"); - } - V8ValueArray array = (V8ValueArray) value; - List result = new ArrayList<>(array.getLength()); - array.forEach(element -> result.add(of.convertNonNull(context, element))); - return result; - }; - } - - public static TSCConversion> objectMap(TSCConversion ofValue) { - return (context, value) -> { - if (!(value instanceof V8ValueObject)) { - throw new IllegalArgumentException("expected a V8 object"); - } - Map primitives = new LinkedHashMap<>(); - Map objects = new LinkedHashMap<>(); - Map collections = new LinkedHashMap<>(); - - V8ValueObject object = (V8ValueObject) value; - IV8ValueArray propNames = object.getPropertyNames(); - for (int i = 0; i < propNames.getLength(); i++) { - String propName = propNames.getString(i); - T propValue = ofValue.convertNullable(context, object.get(propName)); - if (propValue == null || propValue instanceof Number || propValue instanceof String || propValue instanceof Enum) { - primitives.put(propName, propValue); - } else if (propValue instanceof Collection) { - collections.put(propName, propValue); - } else { - objects.put(propName, propValue); - } - } - - Map converted = new LinkedHashMap<>(); - converted.putAll(primitives); - converted.putAll(objects); - converted.putAll(collections); - - return converted; - }; - } - - static TSCConversion cached(Function> getCache) { - return (context, value) -> getCache.apply(context).getOrCreate(context, (V8ValueObject) value); - } - - static TSCConversion cast(TSCConversion base, Class subtype) { - return (context, value) -> { - T object = base.convertUnsafe(context, value); - if (!subtype.isInstance(object)) { - throw new IllegalArgumentException("expected a " + subtype.getSimpleName() + ", but got a " + object.getClass().getSimpleName()); - } - return (U) object; - }; - } - - static TSCConversion builder(BiFunction fromJS) { - return (context, value) -> { - if (!(value instanceof V8ValueObject)) { - throw new IllegalArgumentException("expected V8 object"); - } - return fromJS.apply(context, (V8ValueObject) value); - }; - } - - static TSCConversion enumeration(IntFunction fromCode) { - return (context, value) -> { - final int code = INTEGER.convertNonNull(context, value); - return fromCode.apply(code); - }; - } - -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCGlobals.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCGlobals.java deleted file mode 100644 index f33977aa..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCGlobals.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.values.reference.V8ValueObject; -import org.jspecify.annotations.Nullable; - -import java.util.List; -import java.util.function.Supplier; - -import static org.openrewrite.javascript.internal.tsc.TSCConversions.NODE_LIST; - -public class TSCGlobals extends TSCV8ValueHolder implements TSCV8Backed { - - public static TSCGlobals fromJS(Supplier context, V8ValueObject objectV8) { - return new TSCGlobals(context, objectV8); - } - - private final Supplier programContext; - private final V8ValueObject typescriptV8; - - private TSCGlobals(Supplier programContext, V8ValueObject typescriptV8) { - this.programContext = programContext; - this.typescriptV8 = lifecycleLinked(typescriptV8); - } - - @Override - public TSCProgramContext getProgramContext() { - return programContext.get(); - } - - @Override - public V8ValueObject getBackingV8Object() { - return typescriptV8; - } - - public @Nullable List getDecorators(TSCNode node) { - return this.invokeMethodNullable("getDecorators", NODE_LIST, node); - } - - public @Nullable List getModifiers(TSCNode node) { - return this.invokeMethodNullable("getModifiers", NODE_LIST, node); - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCIndexInfo.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCIndexInfo.java deleted file mode 100644 index 310f2c39..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCIndexInfo.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.values.reference.V8ValueObject; -import lombok.NonNull; -import lombok.Value; - -@Value -public class TSCIndexInfo { - @NonNull TSCType keyType; - - @NonNull TSCType type; - - boolean isReadonly; - TSCNode declaration; - - public static TSCIndexInfo fromJS(TSCProgramContext programContext, V8ValueObject objectV8) { - TSCV8Backed temp = TSCV8Backed.temporary(programContext, objectV8); - return new TSCIndexInfo( - temp.getTypeProperty("keyType"), - temp.getTypeProperty("type"), - temp.getBooleanProperty("isReadonly"), - temp.getOptionalNodeProperty("declaration") - ); - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCInstanceOfChecks.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCInstanceOfChecks.java deleted file mode 100644 index eff2438e..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCInstanceOfChecks.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.interop.V8Runtime; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.primitive.V8ValuePrimitive; -import com.caoccao.javet.values.reference.V8ValueArray; -import com.caoccao.javet.values.reference.V8ValueFunction; -import com.caoccao.javet.values.reference.V8ValueObject; -import org.intellij.lang.annotations.Language; -import org.jspecify.annotations.Nullable; - -public class TSCInstanceOfChecks extends TSCV8ValueHolder { - - public enum InterfaceKind { - Node, - Symbol, - Type, - Signature, - SourceMapSource, - } - - public enum ConstructorKind { - Node(InterfaceKind.Node, "getNodeConstructor"), - Token(InterfaceKind.Node, "getTokenConstructor"), - Identifier(InterfaceKind.Node, "getIdentifierConstructor"), - PrivateIdentifier(InterfaceKind.Node, "getPrivateIdentifierConstructor"), - SourceFile(InterfaceKind.Node, "getSourceFileConstructor"), - Symbol(InterfaceKind.Symbol, "getSymbolConstructor"), - Type(InterfaceKind.Type, "getTypeConstructor"), - Signature(InterfaceKind.Signature, "getSignatureConstructor"), - SourceMapSource(InterfaceKind.SourceMapSource, "getSourceMapSourceConstructor"); - - public final InterfaceKind interfaceKind; - - /** - * see `getServicesObjectAllocator` in services.ts - */ - private final String allocatorAccessorName; - - ConstructorKind(InterfaceKind interfaceKind, String allocatorAccessorName) { - this.interfaceKind = interfaceKind; - this.allocatorAccessorName = allocatorAccessorName; - } - } - - public static TSCInstanceOfChecks fromJS(V8ValueObject tsGlobalsV8) { - V8Runtime runtimeV8 = tsGlobalsV8.getV8Runtime(); - try ( - V8ValueObject allocators = tsGlobalsV8.get("objectAllocator"); - V8ValueArray constructors = runtimeV8.createV8ValueArray(); - V8ValueObject outerVars = runtimeV8.createV8ValueObject() - ) { - - for (ConstructorKind constructorKind : ConstructorKind.values()) { - try (V8ValueFunction constructor = allocators.invoke(constructorKind.allocatorAccessorName)) { - constructors.set(constructorKind.ordinal(), constructor); - } - } - - @Language("typescript") - String code = "" + - "(arg) => {\n" + - " for (let i = 0; i < ctors.length; i++) {\n" + - " if (arg.constructor === ctors[i]) return i;\n" + - " }\n" + - "}"; - - outerVars.set("ctors", constructors); - try (V8ValueFunction constructorOrdinalFunctionV8 = TSCV8Utils.makeFunction(runtimeV8, code, outerVars)) { - return new TSCInstanceOfChecks(constructorOrdinalFunctionV8); - } - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - private final V8ValueFunction constructorOrdinalFunctionV8; - - private TSCInstanceOfChecks(V8ValueFunction constructorOrdinalFunctionV8) { - this.constructorOrdinalFunctionV8 = lifecycleLinked(constructorOrdinalFunctionV8); - } - - public @Nullable ConstructorKind identifyConstructorKind(V8Value valueV8) { - try (V8Value ordinalV8 = constructorOrdinalFunctionV8.call(null, valueV8)) { - if (ordinalV8.isNullOrUndefined()) { - return null; - } - if (!(ordinalV8 instanceof V8ValuePrimitive)) { - throw new IllegalStateException("expected a primitive; found: " + ordinalV8.getClass().getSimpleName()); - } - Object ordinalObj = ((V8ValuePrimitive) ordinalV8).getValue(); - if (!(ordinalObj instanceof Number)) { - throw new IllegalArgumentException("expected a Number; found: " + ordinalObj.getClass()); - } - int ordinal = ((Number) ordinalObj).intValue(); - return ConstructorKind.values()[ordinal]; - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - public @Nullable InterfaceKind identifyInterfaceKind(V8Value valueV8) { - ConstructorKind constructorKind = identifyConstructorKind(valueV8); - if (constructorKind == null) { - return null; - } - return constructorKind.interfaceKind; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCInternal.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCInternal.java deleted file mode 100644 index c0fa45cd..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCInternal.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -/** - * Indicates that a type or method is marked `@internal` in the TSC source code. - */ -@interface TSCInternal { -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCMeta.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCMeta.java deleted file mode 100644 index 845d64e7..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCMeta.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.primitive.V8ValueInteger; -import com.caoccao.javet.values.primitive.V8ValueString; -import com.caoccao.javet.values.reference.V8ValueMap; -import com.caoccao.javet.values.reference.V8ValueObject; - -import java.util.HashMap; -import java.util.Map; - -public class TSCMeta { - private final Map syntaxKindsByName = new HashMap<>(); - private final Map syntaxKindsByCode = new HashMap<>(); - - public static TSCMeta fromJS(V8ValueObject metaV8) throws JavetException { - try { - TSCMeta result = new TSCMeta(); - - try (V8Value syntaxKinds = metaV8.get("syntaxKinds")) { - if (!(syntaxKinds instanceof V8ValueMap)) { - throw new IllegalArgumentException("expected syntaxKinds to be a Map"); - } - - ((V8ValueMap) syntaxKinds).forEach((V8Value keyV8, V8Value valueV8) -> { - if (keyV8 instanceof V8ValueString && valueV8 instanceof V8ValueInteger) { - int code = ((V8ValueInteger) valueV8).getValue(); - String name = ((V8ValueString) keyV8).getValue(); - result.syntaxKindsByCode.put(code, name); - result.syntaxKindsByName.put(name, code); - } - }); - } - - return result; - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - public int syntaxKindCode(String name) { - return this.syntaxKindsByName.get(name); - } - - public String syntaxKindName(int code) { - return this.syntaxKindsByCode.get(code); - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCNode.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCNode.java deleted file mode 100644 index a86fa2e3..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCNode.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.reference.V8ValueArray; -import com.caoccao.javet.values.reference.V8ValueObject; -import org.jspecify.annotations.Nullable; -import org.openrewrite.DebugOnly; -import org.openrewrite.javascript.internal.tsc.generated.TSCSyntaxKind; - -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; - -public class TSCNode implements TSCV8Backed { - - static boolean isValidBackingObject(TSCProgramContext programContext, V8ValueObject objectV8) { - TSCInstanceOfChecks.InterfaceKind interfaceKind = programContext.identifyInterfaceKind(objectV8); - return interfaceKind == TSCInstanceOfChecks.InterfaceKind.Node; - } - - static TSCNode wrap(TSCProgramContext programContext, V8ValueObject objectV8) { - if (!isValidBackingObject(programContext, objectV8)) { - throw new IllegalArgumentException("object provided is not actually a TSC node"); - } - - TSCSyntaxKind syntaxKind; - try { - syntaxKind = TSCSyntaxKind.fromCode(objectV8.getInteger("kind")); - } catch (JavetException e) { - throw new RuntimeException(e); - } - - switch (syntaxKind) { - case SyntaxList: - return new TSCSyntaxListNode(programContext, objectV8); - case SourceFile: - return new TSCNode.SourceFile(programContext, objectV8); - default: - TSCGlobals ts = programContext.getTypeScriptGlobals(); - if (ts.invokeMethodBoolean("isTypeNode", objectV8)) { - return new TSCNode.TypeNode(programContext, objectV8); - } - return new TSCNode(programContext, objectV8); - } - } - - public static class SourceFile extends TSCNode { - protected SourceFile(TSCProgramContext programContext, V8ValueObject nodeV8) { - super(programContext, nodeV8); - } - - public String getFileName() { - return getStringProperty("fileName"); - } - - public String getPath() { - return getStringProperty("path"); - } - - public String getResolvedPath() { - return getStringProperty("resolvedPath"); - } - - public String getOriginalFileName() { - return getStringProperty("originalFileName"); - } - - public String getModuleName() { - return getStringProperty("moduleName"); - } - - /** This is *not* a concept in the TS compiler. This is part of the OpenRewrite-to-TSC bridge. */ - public TSCProgramContext.CompilerBridgeSourceInfo getCompilerBridgeSourceInfo() { - return this.getProgramContext().getBridgeSourceInfo(this); - } - } - - public static class TypeNode extends TSCNode { - protected TypeNode(TSCProgramContext programContext, V8ValueObject nodeV8) { - super(programContext, nodeV8); - } - - public TSCType getTypeFromTypeNode() { - return this.getTypeChecker().getTypeFromTypeNode(this); - } - } - - private final TSCProgramContext programContext; - public final V8ValueObject nodeV8; - - protected TSCNode(TSCProgramContext programContext, V8ValueObject nodeV8) { - this.programContext = programContext; - this.nodeV8 = nodeV8; - } - - @Override - public TSCProgramContext getProgramContext() { - return programContext; - } - - @Override - public String toString() { - return String.format( - "Node(%s@[%d,%d); «%s»)", - syntaxKind().name(), - getStart(), - getEnd(), - TSCUtils.preview(getText(), 100) - ); - } - - public int syntaxKindCode() { - return getIntProperty("kind"); - } - - public TSCSyntaxKind syntaxKind() { - return TSCSyntaxKind.fromCode(this.syntaxKindCode()); - } - - public @Nullable TSCType getTypeForNode() { - return this.programContext.getTypeChecker().getTypeAtLocation(this); - } - - @DebugOnly - public TSCNode firstNodeContaining(String text) { - return firstNodeContaining(text, null); - } - - @DebugOnly - public TSCNode firstNodeContaining(String text, @Nullable TSCSyntaxKind kind) { - for (TSCNode child : this.getAllChildNodes()) { - TSCNode found = child.firstNodeContaining(text, kind); - if (found != null) { - return found; - } - } - if (!this.getText().contains(text)) { - return null; - } - if (kind != null && this.syntaxKind() != kind) { - return null; - } - return this; - } - - @DebugOnly - public TSCNode firstNodeWithText(String text) { - return Objects.requireNonNull(firstNodeWithTextOrNull(text)); - } - - @DebugOnly - public @Nullable TSCNode firstNodeWithTextOrNull(String text) { - for (TSCNode child : this.getAllChildNodes()) { - TSCNode found = child.firstNodeWithTextOrNull(text); - if (found != null) { - return found; - } - } - if (text.equals(this.getText())) { - return this; - } - return null; - } - - /** - * Only intended for debugging and tests. - */ - public @Nullable TSCNode findNodeAtPosition(int position) { - if (!containsPosition(position)) { - throw new IllegalArgumentException(String.format( - "Attempt to find node at position %d, but this %s node only covers [%d, %d).", - position, - this.syntaxKind(), - this.getStart(), - this.getEnd() - )); - } - if (getStart() == position) { - return this; - } - for (TSCNode child : this.getAllChildNodes()) { - if (child.containsPosition(position)) { - return child.findNodeAtPosition(position); - } - } - return null; - } - - public boolean containsPosition(int position) { - return position >= this.getStart() && position < this.getEnd(); - } - - public @Nullable TSCSymbol getSymbolForNode() { - return this.programContext.getTypeChecker().getSymbolAtLocation(this); - } - - public int getStartWithLeadingSpace() { - return getIntProperty("pos"); - } - - public int getStart() { - return getIntProperty("getStart()"); - } - - public int getEnd() { - return getIntProperty("end"); - } - - public int getChildCount() { - return getIntProperty("getChildCount"); - } - - public @Nullable TSCNode getParent() { - return getOptionalNodeProperty("parent"); - } - - @DebugOnly - public @Nullable TSCNode nearestContainingNamedDeclaration() { - return Objects.requireNonNull(nearestContainingNamedDeclarationOrNull()); - } - - @DebugOnly - public @Nullable TSCNode nearestContainingNamedDeclarationOrNull() { - for (TSCNode node = this.getParent(); node != null; node = node.getParent()) { - if (node.hasProperty("name")) { - return node; - } - } - return null; - } - - @Deprecated - public @Nullable TSCNode getChildNode(String name) { - return getOptionalNodeProperty(name); - } - - @Deprecated - public TSCNode getChildNodeRequired(String name) { - return getNodeProperty(name); - } - - @Deprecated - public List getChildNodes(String name) { - return getNodeListProperty(name); - } - - public SourceFile getSourceFile() { - return Objects.requireNonNull(this.getNodeProperty("getSourceFile()").assertSourceFile()); - } - - public TSCNode.SourceFile assertSourceFile() { - if (this instanceof TSCNode.SourceFile) { - return (SourceFile) this; - } else { - throw new IllegalStateException("not a source file: " + syntaxKind()); - } - } - - public String getText() { - return this.getStringProperty("getText()"); - } - - public TypeNode assertTypeNode() { - if (this instanceof TypeNode) { - return (TypeNode) this; - } - throw new IllegalStateException("expected a TypeNode, but this is an ordinary Node"); - } - - public List getAllChildNodes() { - try (V8Value v8Value = this.nodeV8.invoke("getChildren")) { - if (v8Value.isNullOrUndefined()) { - return Collections.emptyList(); - } - V8ValueArray v8Array = (V8ValueArray) v8Value; - - final int count = v8Array.getLength(); - List result = new ArrayList<>(count); - for (int i = 0; i < count; i++) { - try (V8Value child = v8Array.get(i)) { - result.add(programContext.tscNode((V8ValueObject) child)); - } - } - return result; - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - @DebugOnly - public void printTree(PrintStream ps) { - printTree(ps, ""); - } - - private void printTree(PrintStream ps, String indent) { - ps.print(indent); - ps.print(syntaxKind()); - if (syntaxKind().name().contains("Literal")) { - ps.print(" (" + this.getText() + ")"); - } - ps.println(); - - String childIndent = indent + " "; - for (TSCNode child : getAllChildNodes()) { - child.printTree(ps, childIndent); - } - } - - @Override - public V8ValueObject getBackingV8Object() { - return this.nodeV8; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCNodeList.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCNodeList.java deleted file mode 100644 index b018c884..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCNodeList.java +++ /dev/null @@ -1,264 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.reference.V8ValueArray; -import com.caoccao.javet.values.reference.V8ValueObject; - -import java.util.*; - -public class TSCNodeList implements TSCV8Backed, List { - - public static TSCNodeList wrap(TSCProgramContext programContext, V8ValueObject maybeArrayV8) { - if (!(maybeArrayV8 instanceof V8ValueArray)) { - throw new IllegalArgumentException("expected a v8 array"); - } - return new TSCNodeList(programContext, (V8ValueArray) maybeArrayV8); - } - - private final TSCProgramContext programContext; - private final V8ValueArray arrayV8; - - private TSCNodeList(TSCProgramContext programContext, V8ValueArray arrayV8) { - this.programContext = programContext; - this.arrayV8 = arrayV8; - } - - @Override - public TSCProgramContext getProgramContext() { - return programContext; - } - - @Override - public V8ValueArray getBackingV8Object() { - return arrayV8; - } - - @Override - public int size() { - try { - return arrayV8.getLength(); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean isEmpty() { - return size() == 0; - } - - @Override - public boolean contains(Object o) { - return indexOf(o) >= 0; - } - - @Override - public Iterator iterator() { - return listIterator(); - } - - @Override - public Object[] toArray() { - int size = size(); - Object[] array = new Object[size]; - for (int i = 0; i < size; i++) { - array[i] = get(i); - } - return array; - } - - @Override - public T2[] toArray(T2[] array) { - int size = size(); - if (array.length < size) { - array = Arrays.copyOf(array, size); - } - for (int i = 0; i < size; i++) { - array[i] = (T2) get(i); - } - return array; - } - - @Override - public boolean add(TSCNode tscNode) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public boolean remove(Object o) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public boolean containsAll(Collection args) { - for (Object arg : args) { - if (!contains(arg)) { - return false; - } - } - return true; - } - - @Override - public boolean addAll(Collection c) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public boolean addAll(int index, Collection c) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public boolean removeAll(Collection c) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public boolean retainAll(Collection c) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public void clear() { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public TSCNode get(int index) { - try (V8Value childV8 = arrayV8.get(index)) { - return programContext.tscNode((V8ValueObject) childV8); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - @Override - public TSCNode set(int index, TSCNode element) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public void add(int index, TSCNode element) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public TSCNode remove(int index) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public int indexOf(Object o) { - if (!(o instanceof TSCNode)) { - return -1; - } - TSCNode node = (TSCNode) o; - final int size = size(); - for (int i = 0; i < size; i++) { - if (get(i) == node) { - return i; - } - } - return -1; - } - - @Override - public int lastIndexOf(Object o) { - if (!(o instanceof TSCNode)) { - return -1; - } - TSCNode node = (TSCNode) o; - final int size = size(); - for (int i = size - 1; i >= 0; i--) { - if (get(i) == node) { - return i; - } - } - return -1; - } - - @Override - public ListIterator listIterator() { - return listIterator(0); - } - - @Override - public ListIterator listIterator(int startIndex) { - return new ListIterator() { - - final int size = size(); - int cursor = startIndex; - - @Override - public boolean hasNext() { - return cursor < size; - } - - @Override - public TSCNode next() { - return get(cursor++); - } - - @Override - public boolean hasPrevious() { - return cursor > 0; - } - - @Override - public TSCNode previous() { - return get(--cursor); - } - - @Override - public int nextIndex() { - return cursor; - } - - @Override - public int previousIndex() { - return cursor - 1; - } - - @Override - public void remove() { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public void set(TSCNode tscNode) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public void add(TSCNode tscNode) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - }; - } - - @Override - public List subList(int fromIndex, int toIndex) { - ArrayList result = new ArrayList<>(toIndex - fromIndex); - for (int i = fromIndex; i < toIndex; i++) { - result.add(get(i)); - } - return result; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCObjectCache.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCObjectCache.java deleted file mode 100644 index a34aaf37..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCObjectCache.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.values.reference.V8ValueObject; - -import java.util.HashMap; -import java.util.Map; - -public abstract class TSCObjectCache extends TSCV8ValueHolder { - - public interface KeyProvider { - TKey getKey(TSCProgramContext context, V8ValueObject objectV8) throws JavetException; - } - - public interface InstanceConstructor { - T makeInstance(TSCProgramContext programContext, V8ValueObject objectV8) throws JavetException; - } - - public static TSCObjectCache usingInternalKey(InstanceConstructor makeInstance) { - return new Impl<>(TSCProgramContext::getInternalObjectId, makeInstance); - } - - public static TSCObjectCache usingPropertyAsKey(String propertyName, InstanceConstructor makeInstance) { - return new Impl<>((context, objectV8) -> objectV8.getPrimitive(propertyName), makeInstance); - } - - public abstract T getOrCreate(TSCProgramContext programContext, V8ValueObject objectV8); - - /** Hide the `TKey` implementation detail within an Impl class. */ - private static class Impl extends TSCObjectCache { - private final Map cache = new HashMap<>(); - private final KeyProvider getKey; - private final InstanceConstructor makeInstance; - - public Impl(KeyProvider getKey, InstanceConstructor makeInstance) { - this.getKey = getKey; - this.makeInstance = makeInstance; - } - - @Override - public T getOrCreate(TSCProgramContext programContext, V8ValueObject objectV8) { - try { - TKey key = getKey.getKey(programContext, objectV8); - return this.cache.computeIfAbsent(key, (_key) -> { - V8ValueObject clone = lifecycleLinked(objectV8); - try { - return makeInstance.makeInstance(programContext, clone); - } catch (JavetException e) { - throw new RuntimeException(e); - } - }); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCProgramContext.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCProgramContext.java deleted file mode 100644 index 0f8a2f11..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCProgramContext.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.reference.V8ValueFunction; -import com.caoccao.javet.values.reference.V8ValueObject; -import lombok.Getter; -import lombok.Value; -import org.jspecify.annotations.Nullable; - -import java.nio.file.Path; -import java.nio.file.Paths; - -public class TSCProgramContext extends TSCV8ValueHolder { - private final V8ValueObject program; - private final V8ValueFunction createScanner; - private final V8ValueFunction getOpenRewriteId; - - /** - * In the virtual filesystem used by the compiler, this is the prefix for all input sources. - */ - private final Path compilerAppPath; - /** - * In the virtual filesystem used by the compiler, this is the prefix for all libs shipped with TS. - */ - private final Path compilerLibPath; - - private final TSCGlobals typescriptGlobals; - - @Getter - private final TSCTypeChecker typeChecker; - - @Getter - private final TSCInstanceOfChecks instanceOfChecks; - - final TSCObjectCache nodeCache = lifecycleLinked(TSCObjectCache.usingInternalKey(TSCNode::wrap)); - final TSCObjectCache nodeListCache = lifecycleLinked(TSCObjectCache.usingInternalKey(TSCNodeList::wrap)); - final TSCObjectCache typeCache = lifecycleLinked(TSCObjectCache.usingPropertyAsKey("id", TSCType::new)); - final TSCObjectCache symbolCache = lifecycleLinked(TSCObjectCache.usingInternalKey(TSCSymbol::new)); - final TSCObjectCache signatureCache = lifecycleLinked(TSCObjectCache.usingInternalKey(TSCSignature::new)); - - public TSCProgramContext( - V8ValueObject program, - V8ValueObject tsGlobalsV8, - V8ValueObject typeCheckerV8, - V8ValueFunction createScanner, - V8ValueFunction getOpenRewriteId, - Path compilerAppPath, - Path compilerLibPath - ) { - this.program = lifecycleLinked(program); - this.typescriptGlobals = lifecycleLinked(TSCGlobals.fromJS(() -> this, tsGlobalsV8)); - this.typeChecker = lifecycleLinked(TSCTypeChecker.fromJS(() -> this, typeCheckerV8)); - this.instanceOfChecks = lifecycleLinked(TSCInstanceOfChecks.fromJS(tsGlobalsV8)); - this.createScanner = lifecycleLinked(createScanner); - this.getOpenRewriteId = lifecycleLinked(getOpenRewriteId); - this.compilerAppPath = compilerAppPath; - this.compilerLibPath = compilerLibPath; - } - - public static TSCProgramContext fromJS(V8ValueObject contextV8) { - try ( - V8ValueObject program = contextV8.get("program"); - V8ValueObject tsGlobals = contextV8.get("ts"); - V8ValueObject typeChecker = contextV8.get("typeChecker"); - V8ValueFunction createScanner = contextV8.get("createScanner"); - V8ValueFunction getOpenRewriteId = contextV8.get("getOpenRewriteId"); - V8ValueObject pathPrefixes = contextV8.get("pathPrefixes"); - ) { - return new TSCProgramContext( - program, - tsGlobals, - typeChecker, - createScanner, - getOpenRewriteId, - Paths.get(pathPrefixes.getString("app")), - Paths.get(pathPrefixes.getString("lib")) - ); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - public long getInternalObjectId(V8ValueObject objectV8) { - try { - return getOpenRewriteId.callLong(null, objectV8); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - - public TSCGlobals getTypeScriptGlobals() { - return this.typescriptGlobals; - } - - public TSCInstanceOfChecks.@Nullable InterfaceKind identifyInterfaceKind(V8Value valueV8) { - return this.getInstanceOfChecks().identifyInterfaceKind(valueV8); - } - - public TSCInstanceOfChecks.@Nullable ConstructorKind identifyConstructorKind(V8Value valueV8) { - return this.getInstanceOfChecks().identifyConstructorKind(valueV8); - } - - public V8ValueFunction getCreateScannerFunction() { - return this.createScanner; - } - - public TSCType tscType(V8ValueObject v8Value) { - return this.typeCache.getOrCreate(this, v8Value); - } - - public TSCNode tscNode(V8ValueObject v8Value) { - return this.nodeCache.getOrCreate(this, v8Value); - } - - public TSCNodeList tscNodeList(V8ValueObject v8Value) { - return this.nodeListCache.getOrCreate(this, v8Value); - } - - public TSCSymbol tscSymbol(V8ValueObject v8Value) { - return this.symbolCache.getOrCreate(this, v8Value); - } - - public TSCSignature tscSignature(V8ValueObject v8Value) { - return this.signatureCache.getOrCreate(this, v8Value); - } - - /** - * This is *not* a concept in the TS compiler. This is part of the OpenRewrite-to-TSC bridge. - */ - public enum CompilerBridgeSourceKind { - ApplicationCode, - SystemLibrary, - } - - @Value - public static class CompilerBridgeSourceInfo { - CompilerBridgeSourceKind sourceKind; - Path relativePath; - } - - protected CompilerBridgeSourceInfo getBridgeSourceInfo(TSCNode.SourceFile sourceFile) { - Path rawPath = Paths.get(sourceFile.getOriginalFileName()); - Path sourceKindRoot; - CompilerBridgeSourceKind sourceKind; - if (rawPath.startsWith(this.compilerAppPath)) { - sourceKindRoot = this.compilerAppPath; - sourceKind = CompilerBridgeSourceKind.ApplicationCode; - } else if (rawPath.startsWith(this.compilerLibPath)) { - sourceKindRoot = this.compilerLibPath; - sourceKind = CompilerBridgeSourceKind.SystemLibrary; - } else { - throw new IllegalArgumentException("unknown bridge source path (expected app or lib): " + rawPath); - } - return new CompilerBridgeSourceInfo(sourceKind, sourceKindRoot.relativize(rawPath)); - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCRuntime.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCRuntime.java deleted file mode 100644 index fb061ebb..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCRuntime.java +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.interception.logging.JavetStandardConsoleInterceptor; -import com.caoccao.javet.interop.JavetBridge; -import com.caoccao.javet.interop.V8Host; -import com.caoccao.javet.interop.V8Runtime; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.primitive.V8ValueString; -import com.caoccao.javet.values.reference.V8ValueFunction; -import com.caoccao.javet.values.reference.V8ValueMap; -import com.caoccao.javet.values.reference.V8ValueObject; -import org.intellij.lang.annotations.Language; -import org.jspecify.annotations.Nullable; -import org.openrewrite.DebugOnly; -import org.openrewrite.javascript.internal.JavetUtils; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.Collections; -import java.util.Map; -import java.util.function.BiConsumer; - -import static org.openrewrite.internal.StringUtils.readFully; - -public class TSCRuntime implements AutoCloseable { - /** - * Manually enable this when tracking down reference-counting issues. - *
- * This causes tests to fail if references are not recycled, and will - * attribute dangling references to the call site that created them. - */ - private final static boolean USE_WRAPPED_V8_RUNTIME = false; - - public final V8Runtime v8Runtime; - - @Nullable - public V8ValueFunction tsParseV8 = null; - - private final V8ValueObject parseOptionsV8; - - private final JavetStandardConsoleInterceptor javetStandardConsoleInterceptor; - - public static TSCRuntime init() { - return init(false); - } - - public static TSCRuntime init(boolean forceWrappedV8Runtime) { - try { - V8Runtime v8Runtime = (forceWrappedV8Runtime || USE_WRAPPED_V8_RUNTIME) ? - JavetBridge.makeWrappedV8Runtime() : - V8Host.getV8Instance().createV8Runtime(); - JavetStandardConsoleInterceptor javetStandardConsoleInterceptor = new JavetStandardConsoleInterceptor(v8Runtime); - javetStandardConsoleInterceptor.register(v8Runtime.getGlobalObject()); - return new TSCRuntime(v8Runtime, javetStandardConsoleInterceptor); - } catch ( - JavetException e) { - throw new RuntimeException(e); - } - } - - public TSCRuntime setCompilerOptionOverride(String key, Object value) { - try { - this.close(); - TSCRuntime runtime = init(false); - V8Value compilerOptions = runtime.parseOptionsV8.get("compilerOptions"); - if (compilerOptions.isNullOrUndefined()) { - compilerOptions = runtime.v8Runtime.createV8ValueObject(); - runtime.parseOptionsV8.set("compilerOptions", compilerOptions); - } - ((V8ValueObject) compilerOptions).setWeak(); - ((V8ValueObject) compilerOptions).set(key, value); - return runtime; - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - public TSCRuntime enableVirtualFileSystemTracing() { - try { - this.parseOptionsV8.set("traceVirtualFileSystem", true); - } catch (JavetException e) { - throw new RuntimeException(e); - } - return this; - } - - public TSCRuntime(V8Runtime v8Runtime, JavetStandardConsoleInterceptor javetStandardConsoleInterceptor) { - this.v8Runtime = v8Runtime; - this.javetStandardConsoleInterceptor = javetStandardConsoleInterceptor; - try { - this.parseOptionsV8 = v8Runtime.createV8ValueObject(); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - private static String getJSEntryProgramText() { - try (InputStream is = TSCRuntime.class.getResourceAsStream("/tsc/index.js")) { - if (is == null) { - throw new IllegalStateException("entry JS resource does not exist"); - } - return readFully(is, StandardCharsets.UTF_8); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - public void importTS() { - if (tsParseV8 != null) { - return; - } - try { - v8Runtime.getExecutor("const require = () => undefined;").executeVoid(); - v8Runtime.getExecutor("const module = {exports: {}};").executeVoid(); - v8Runtime.getExecutor(getJSEntryProgramText()).executeVoid(); - this.tsParseV8 = v8Runtime.getExecutor("module.exports.default").execute(); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - @DebugOnly - public void parseSingleSource(@Language("typescript") String sourceText, BiConsumer callback) { - parseSingleSource(sourceText, "file.ts", callback); - } - - public void parseSingleSource(@Language("typescript") String sourceText, String filename, BiConsumer callback) { - parseSourceTexts(Collections.singletonMap(Paths.get(filename), sourceText), callback); - } - - public void parseSourceTexts(Map sourceTexts, BiConsumer callback) { - importTS(); - assert tsParseV8 != null; - try (V8ValueMap sourceTextsV8 = v8Runtime.createV8ValueMap()) { - for (Map.Entry entry : sourceTexts.entrySet()) { - sourceTextsV8.set(entry.getKey().toString(), entry.getValue()); - } - try ( - V8ValueObject parseResultV8 = tsParseV8.call(null, sourceTextsV8, this.parseOptionsV8); - TSCProgramContext programContext = TSCProgramContext.fromJS(parseResultV8); - V8ValueMap sourceFilesByPathV8 = parseResultV8.get("sourceFiles") - ) { - sourceFilesByPathV8.forEach((V8ValueString filePathV8, V8Value maybeSourceFileV8) -> { - if (maybeSourceFileV8.isNullOrUndefined()) { - // TODO figure out how to handle this - System.err.println("**** missing source file: " + filePathV8.getValue()); - return; - } - - V8ValueObject sourceFileV8 = (V8ValueObject) maybeSourceFileV8; - String sourceText = sourceFileV8.getPropertyString("text"); - Path filePath = Paths.get(filePathV8.getValue()); - try (TSCSourceFileContext sourceFileContext = new TSCSourceFileContext(programContext, sourceText, filePath)) { - TSCNode node = programContext.tscNode(sourceFileV8); - callback.accept(node, sourceFileContext); - } - }); - } - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - @Override - public void close() { - JavetUtils.close(this.tsParseV8); - JavetUtils.close(this.parseOptionsV8); - - if (!v8Runtime.isClosed()) { - v8Runtime.await(); - v8Runtime.lowMemoryNotification(); - - try { - javetStandardConsoleInterceptor.unregister(v8Runtime.getGlobalObject()); - } catch (JavetException ignored) { - } - v8Runtime.await(); - v8Runtime.lowMemoryNotification(); - } - - try { - v8Runtime.close(); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCSignature.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCSignature.java deleted file mode 100644 index 4f67f7b2..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCSignature.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.values.reference.V8ValueObject; - -public class TSCSignature implements TSCV8Backed { - - private final TSCProgramContext programContext; - public final V8ValueObject signatureV8; - - public TSCSignature(TSCProgramContext programContext, V8ValueObject signatureV8) { - this.programContext = programContext; - this.signatureV8 = signatureV8; - } - - @Override - public TSCProgramContext getProgramContext() { - return programContext; - } - - @Override - public V8ValueObject getBackingV8Object() { - return signatureV8; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCSourceFileContext.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCSourceFileContext.java deleted file mode 100644 index 56d17255..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCSourceFileContext.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.values.reference.V8ValueObject; -import lombok.Getter; -import org.openrewrite.javascript.internal.tsc.generated.TSCSyntaxKind; - -import java.nio.file.Path; - -@Getter -public class TSCSourceFileContext extends TSCV8ValueHolder { - private final TSCProgramContext programContext; - - private final V8ValueObject scanner; - - private final Path relativeSourcePath; - - TSCSourceFileContext(TSCProgramContext programContext, String sourceText, Path relativeSourcePath) { - this.programContext = programContext; - this.relativeSourcePath = relativeSourcePath; - try (V8ValueObject scannerV8 = programContext.getCreateScannerFunction().call(null)) { - this.scanner = lifecycleLinked(scannerV8); - this.scanner.invokeVoid("setText", sourceText); - } catch (JavetException e) { - throw new RuntimeException(e); - } - resetScanner(0); - } - - public Integer scannerTokenStart() { - try { - return this.scanner.invokeInteger("getTokenPos"); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - public Integer scannerTokenEnd() { - try { - return this.scanner.invokeInteger("getTextPos"); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - public String scannerTokenText() { - try { - return this.scanner.invokeString("getTokenText"); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - public void resetScanner(int offset) { - try { - this.scanner.invokeVoid("setTextPos", offset); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - public TSCSyntaxKind nextScannerSyntaxType() { - try { - final int code = this.scanner.invokeInteger("scan"); - return TSCSyntaxKind.fromCode(code); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCSymbol.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCSymbol.java deleted file mode 100644 index e927c9bd..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCSymbol.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.values.reference.V8ValueObject; -import lombok.Value; -import org.jspecify.annotations.Nullable; -import org.openrewrite.javascript.internal.tsc.generated.TSCSymbolFlag; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class TSCSymbol implements TSCV8Backed { - - @Value - public static class DebugInfo { - List symbolFlags; - Map properties; - } - - private final TSCProgramContext programContext; - public final V8ValueObject symbolV8; - - public TSCSymbol(TSCProgramContext programContext, V8ValueObject symbolV8) { - this.programContext = programContext; - this.symbolV8 = symbolV8; - } - - @Override - public TSCProgramContext getProgramContext() { - return programContext; - } - - @Override - public String toString() { - return "Symbol(" + getTypeChecker().symbolToString(this) + ")"; - } - - public @Nullable TSCNode getValueDeclaration() { - return getOptionalNodeProperty("valueDeclaration"); - } - - public @Nullable List getDeclarations() { - return getOptionalNodeListProperty("declarations"); - } - - public int getSymbolFlags() { - try { - return this.symbolV8.getInteger("flags"); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - public boolean hasSymbolFlag(TSCSymbolFlag flag) { - return flag.matches(this.getSymbolFlags()); - } - - /** - * Only intended for debugging; this is slow. - */ - public List listMatchingSymbolFlags() { - final int symbolFlags = this.getSymbolFlags(); - List result = new ArrayList<>(); - for (TSCSymbolFlag flag : TSCSymbolFlag.values()) { - if (flag.matches(symbolFlags)) { - result.add(flag); - } - } - return result; - } - - public String getEscapedName() { - return getStringProperty("escapedName"); - } - - @Override - public DebugInfo getDebugInfo() { - return new DebugInfo(listMatchingSymbolFlags(), getAllPropertiesForDebugging()); - } - - @Override - public V8ValueObject getBackingV8Object() { - return symbolV8; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCSyntaxListNode.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCSyntaxListNode.java deleted file mode 100644 index b80ebf43..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCSyntaxListNode.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.values.reference.V8ValueObject; -import org.jspecify.annotations.NonNull; -import org.jspecify.annotations.Nullable; - -import java.util.*; - -public class TSCSyntaxListNode extends TSCNode implements List { - @Nullable - private List children; - - public TSCSyntaxListNode(TSCProgramContext programContext, V8ValueObject nodeV8) { - super(programContext, nodeV8); - } - - private List getChildren() { - if (children == null) { - children = this.getNodeListProperty("_children"); - } - return children; - } - - @Override - public int size() { - return getChildren().size(); - } - - @Override - public boolean isEmpty() { - return getChildren().isEmpty(); - } - - @Override - public boolean contains(Object o) { - return getChildren().contains(o); - } - - @NonNull - @Override - public Iterator iterator() { - return getChildren().iterator(); - } - - @NonNull - @Override - public Object[] toArray() { - return getChildren().toArray(); - } - - @NonNull - @Override - public T[] toArray(@NonNull T[] a) { - return getChildren().toArray(a); - } - - @Override - public boolean add(TSCNode tscNode) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public boolean remove(Object o) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public boolean containsAll(@NonNull Collection c) { - return new HashSet<>(getChildren()).containsAll(c); - } - - @Override - public boolean addAll(@NonNull Collection c) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public boolean addAll(int index, @NonNull Collection c) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public boolean removeAll(@NonNull Collection c) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public boolean retainAll(@NonNull Collection c) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public void clear() { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public TSCNode get(int index) { - return getChildren().get(index); - } - - @Override - public TSCNode set(int index, TSCNode element) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public void add(int index, TSCNode element) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public TSCNode remove(int index) { - throw new UnsupportedOperationException("node list is not modifiable"); - } - - @Override - public int indexOf(Object o) { - return getChildren().indexOf(o); - } - - @Override - public int lastIndexOf(Object o) { - return getChildren().lastIndexOf(o); - } - - @NonNull - @Override - public ListIterator listIterator() { - return getChildren().listIterator(); - } - - @NonNull - @Override - public ListIterator listIterator(int index) { - return getChildren().listIterator(index); - } - - @NonNull - @Override - public List subList(int fromIndex, int toIndex) { - return getChildren().subList(fromIndex, toIndex); - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCType.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCType.java deleted file mode 100644 index e905bd66..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCType.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.values.reference.V8ValueObject; -import lombok.Value; -import org.openrewrite.javascript.internal.tsc.generated.TSCObjectFlag; -import org.openrewrite.javascript.internal.tsc.generated.TSCTypeFlag; - -import java.util.List; -import java.util.Map; - -public class TSCType implements TSCV8Backed, TSCTypeAccessors { - @Value - public static class DebugInfo { - List typeFlags; - List objectFlags; - Map properties; - List typedInterfaces; - } - - private final TSCProgramContext programContext; - public final V8ValueObject typeV8; - - public TSCType(TSCProgramContext programContext, V8ValueObject typeV8) { - this.programContext = programContext; - this.typeV8 = typeV8; - } - - @Override - public TSCType _typeInstanceInternal() { - return this; - } - - @Override - public TSCProgramContext getProgramContext() { - return programContext; - } - - @Override - public String toString() { - return "Type#" + getTypeId() + "(" + typeToString() + ")"; - } - - @Override - public V8ValueObject getBackingV8Object() { - return typeV8; - } - -// @Override -// @DebugOnly -// public DebugInfo getDebugInfo() { -// return new DebugInfo( -// listMatchingTypeFlags(), -// listMatchingObjectFlags(), -// getAllPropertiesForDebugging(), -// listMatchingTypeInterfaces() -// ); -// } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCTypeAccessors.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCTypeAccessors.java deleted file mode 100644 index c9be06c7..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCTypeAccessors.java +++ /dev/null @@ -1,324 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import org.jspecify.annotations.Nullable; -import org.openrewrite.DebugOnly; -import org.openrewrite.javascript.internal.tsc.generated.TSCObjectFlag; -import org.openrewrite.javascript.internal.tsc.generated.TSCTypeFlag; - -import java.util.*; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -public interface TSCTypeAccessors extends TSCV8Backed { - - // - // common accessors for all types, including the base TSCType - // - - TSCType _typeInstanceInternal(); - - default String typeToString() { - return getTypeChecker().typeToString(_typeInstanceInternal()); - } - - @Override - default TSCType.DebugInfo getDebugInfo() { - return new TSCType.DebugInfo( - listMatchingTypeFlags(), - listMatchingObjectFlags(), - getAllPropertiesForDebugging(), - listMatchingTypeInterfaces() - ); - } - - default long getTypeId() { - return getLongProperty("id"); - } - - default TSCSymbol getSymbolForType() { - return getSymbolProperty("symbol"); - } - - default int getTypeFlags() { - return getIntProperty("flags"); - } - - default boolean hasTypeFlag(TSCTypeFlag flag) { - return flag.matches(this.getTypeFlags()); - } - - default boolean hasExactTypeFlag(TSCTypeFlag flag) { - return flag.code == this.getTypeFlags(); - } - - /** - * This is not what you usually want. Type flags are a bit field. - */ - default TSCTypeFlag getExactTypeFlag() { - return TSCTypeFlag.fromMaskExact(this.getTypeFlags()); - } - - @DebugOnly - default List listMatchingTypeFlags() { - final int typeFlags = this.getTypeFlags(); - List result = new ArrayList<>(); - for (TSCTypeFlag flag : TSCTypeFlag.values()) { - if (flag.matches(typeFlags)) { - result.add(flag); - } - } - return result; - } - - default int getObjectFlags() { - if (!this.hasTypeFlag(TSCTypeFlag.ObjectFlagsType)) { - return 0; - } else { - return getIntProperty("objectFlags"); - } - } - - default boolean hasObjectFlag(TSCObjectFlag flag) { - return flag.matches(this.getObjectFlags()); - } - - @DebugOnly - default List listMatchingObjectFlags() { - final int objectFlags = this.getObjectFlags(); - List result = new ArrayList<>(); - for (TSCObjectFlag flag : TSCObjectFlag.values()) { - if (flag.matches(objectFlags)) { - result.add(flag); - } - } - return result; - } - - default List getTypeProperties() { - return this.getSymbolListProperty("getProperties()"); - } - - default @Nullable TSCType getConstraint() { - return this.getOptionalTypeProperty("getConstraint()"); - } - - default @Nullable TSCType getDefault() { - return this.getOptionalTypeProperty("getDefault()"); - } - - default @Nullable InterfaceType asInterfaceType() { - if (hasObjectFlag(TSCObjectFlag.Interface) || hasObjectFlag(TSCObjectFlag.Class)) { - return new InterfaceType.Impl(_typeInstanceInternal()); - } - return null; - } - - default InterfaceType assertInterfaceType() { - return Objects.requireNonNull(asInterfaceType()); - } - - default @Nullable UnionOrIntersectionType asUnionOrIntersectionType() { - if (hasTypeFlag(TSCTypeFlag.UnionOrIntersection)) { - return new UnionOrIntersectionType.Impl(_typeInstanceInternal()); - } - return null; - } - - default UnionOrIntersectionType assertUnionOrIntersectionType() { - return Objects.requireNonNull(asUnionOrIntersectionType()); - } - - default @Nullable ObjectType asObjectType() { - if (hasTypeFlag(TSCTypeFlag.Object)) { - return new ObjectType.Impl(this._typeInstanceInternal()); - } - return null; - } - - default ObjectType assertObjectType() { - return Objects.requireNonNull(asObjectType()); - } - - default @Nullable TypeReference asTypeReference() { - if (hasObjectFlag(TSCObjectFlag.Reference)) { - return new TypeReference.Impl(_typeInstanceInternal()); - } - return null; - } - - default TypeReference assertTypeReference() { - return Objects.requireNonNull(asTypeReference()); - } - - @DebugOnly - default List listMatchingTypeInterfaces() { - TSCTypeAccessors[] allAccessors = { - asInterfaceType(), - asTypeReference(), - asObjectType(), - asUnionOrIntersectionType() - }; - return Stream.of(allAccessors) - .filter(Objects::nonNull) - .collect(Collectors.toList()); - } - - - // - // specialized accessors for each interface under `Type` in the TSC - // - - interface TypeWrapper extends TSCV8Backed.Wrapper, TSCTypeAccessors { - abstract class Impl implements TypeWrapper { - private final TSCType wrapped; - - public Impl(TSCType wrapped) { - this.wrapped = wrapped; - } - - @Override - public TSCType _typeInstanceInternal() { - return wrapped; - } - - @Override - public String toString() { - String interfaceName = "???"; - Class enclosing = this.getClass().getEnclosingClass(); - if (enclosing != null) { - interfaceName = enclosing.getSimpleName(); - } - return "Type[as " + interfaceName + "]#" + getTypeId() + "(" + typeToString() + ")"; - } - } - - @Override - default TSCType wrapped() { - return _typeInstanceInternal(); - } - } - - interface ObjectType extends TypeWrapper { - class Impl extends TypeWrapper.Impl implements ObjectType { - public Impl(TSCType wrapped) { - super(wrapped); - } - } - - // TODO unmapped properties: `members` - - @TSCInternal - default @Nullable List getProperties() { - return getOptionalSymbolListProperty("properties"); - } - - @TSCInternal - default @Nullable List getCallSignatures() { - return getOptionalSignatureListProperty("callSignatures"); - } - - @TSCInternal - default @Nullable List getConstructSignatures() { - return getOptionalSignatureListProperty("constructSignatures"); - } - - @TSCInternal - default @Nullable List getIndexInfos() { - return getOptionalIndexInfoListProperty("indexInfos"); - } - - @TSCInternal - default @Nullable ObjectType getObjectTypeWithoutAbstractConstructSignatures() { - TSCType resultType = getOptionalTypeProperty("objectTypeWithoutAbstractConstructSignatures"); - return resultType == null ? null : resultType.asObjectType(); - } - } - - interface InterfaceType extends TypeWrapper, ObjectType { - class Impl extends TypeWrapper.Impl implements InterfaceType { - public Impl(TSCType wrapped) { - super(wrapped); - } - } - - default @Nullable List getTypeParameters() { - return wrapped().getOptionalTypeListProperty("typeParameters"); - } - - default @Nullable List getOuterTypeParameters() { - return wrapped().getOptionalTypeListProperty("outerTypeParameters"); - } - - default @Nullable List getLocalTypeParameters() { - return wrapped().getOptionalTypeListProperty("localTypeParameters"); - } - - default @Nullable TSCType getThisType() { - return wrapped().getOptionalTypeProperty("thisType"); - } - - @TSCInternal - default @Nullable TSCType getResolvedBaseConstructorType() { - return wrapped().getOptionalTypeProperty("resolvedBaseConstructorType"); - } - - @TSCInternal - default List getResolvedBaseTypes() { - return wrapped().getTypeListProperty("resolvedBaseTypes"); - } - - @TSCInternal - default boolean getBaseTypesResolved() { - return wrapped().getBooleanProperty("baseTypesResolved"); - } - } - - interface UnionOrIntersectionType extends TypeWrapper { - class Impl extends TypeWrapper.Impl implements UnionOrIntersectionType { - public Impl(TSCType wrapped) { - super(wrapped); - } - } - - // TODO unmapped properties: all @internal properties - default List getTypes() { - return wrapped().getTypeListProperty("types"); - } - } - - interface TypeReference extends TypeWrapper, ObjectType { - class Impl extends TypeWrapper.Impl implements TypeReference { - public Impl(TSCType wrapped) { - super(wrapped); - } - } - - default TSCType getTarget() { - return getTypeProperty("target"); - } - - default TSCNode.@Nullable TypeNode getNode() { - return getOptionalTypeNodeProperty("node"); - } - - default List getTypeArguments() { - return getTypeChecker().getTypeArguments(_typeInstanceInternal()); - } - } - -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCTypeChecker.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCTypeChecker.java deleted file mode 100644 index 0e0ac345..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCTypeChecker.java +++ /dev/null @@ -1,344 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.values.reference.V8ValueObject; -import org.jspecify.annotations.Nullable; -import org.openrewrite.javascript.internal.tsc.generated.TSCIndexKind; -import org.openrewrite.javascript.internal.tsc.generated.TSCSignatureKind; -import org.openrewrite.javascript.internal.tsc.generated.TSCSymbolFlag; -import org.openrewrite.javascript.internal.tsc.generated.TSCTypeFlag; - -import java.util.List; -import java.util.function.Supplier; - -import static org.openrewrite.javascript.internal.tsc.TSCConversions.*; - -public class TSCTypeChecker extends TSCV8ValueHolder implements TSCV8Backed { - - // TODO: unmapped functions include all marked @internal and those that return "uncheckable" nodes - - public static TSCTypeChecker fromJS(Supplier context, V8ValueObject objectV8) { - return new TSCTypeChecker(context, objectV8); - } - - private final Supplier programContext; - private final V8ValueObject objectV8; - - private TSCTypeChecker(Supplier programContext, V8ValueObject objectV8) { - this.programContext = programContext; - this.objectV8 = lifecycleLinked(objectV8); - } - - public TSCType getTypeOfSymbolAtLocation(TSCSymbol symbol, TSCNode node) { - return this.invokeMethodNonNull( - "getTypeOfSymbolAtLocation", - TYPE, - symbol, - node - ); - } - - public TSCType getTypeOfSymbol(TSCSymbol symbol) { - return this.invokeMethodNonNull( - "getTypeOfSymbol", - TYPE, - symbol - ); - } - - public TSCType getDeclaredTypeOfSymbol(TSCSymbol symbol) { - return this.invokeMethodNonNull( - "getDeclaredTypeOfSymbol", - TYPE, - symbol - ); - } - - public List getPropertiesOfType(TSCType type) { - return this.invokeMethodNonNull( - "getPropertiesOfType", - SYMBOL_LIST, - type - ); - } - - public @Nullable TSCSymbol getPropertyOfType(TSCType type, String name) { - return this.invokeMethodNullable( - "getPropertyOfType", - SYMBOL, - type, - name - ); - } - - public @Nullable TSCSymbol getPrivateIdentifierPropertyOfType(TSCType leftType, String name, TSCNode location) { - return this.invokeMethodNullable( - "getPrivateIdentifierPropertyOfType", - SYMBOL, - leftType, - name, - location - ); - } - - public @Nullable TSCIndexInfo getIndexInfoOfType(TSCType type, TSCIndexKind kind) { - return this.invokeMethodNullable( - "getIndexInfoOfType", - INDEX_INFO, - type, - kind.code - ); - } - - public List getIndexInfosOfType(TSCType type) { - return this.invokeMethodNonNull( - "getIndexInfosOfType", - INDEX_INFO_LIST, - type - ); - } - - public List getIndexInfosOfIndexSymbol(TSCSymbol indexSymbol) { - return this.invokeMethodNonNull( - "getIndexInfosOfIndexSymbol", - INDEX_INFO_LIST, - indexSymbol - ); - } - - public List getSignaturesOfType(TSCType type, TSCSignatureKind signatureKind) { - return this.invokeMethodNonNull( - "getSignaturesOfType", - SIGNATURE_LIST, - type, - signatureKind.code - ); - } - - public @Nullable TSCType getIndexTypeOfType(TSCType type, TSCIndexKind indexKind) { - return this.invokeMethodNullable( - "getIndexTypeOfType", - TYPE, - type, - indexKind.code - ); - } - - public @Nullable List getBaseTypes(TSCType interfaceType) { - return this.invokeMethodNonNull( - "getBaseTypes", - TYPE_LIST, - interfaceType - ); - } - - public TSCType getBaseTypeOfLiteralType(TSCType type) { - return this.invokeMethodNonNull( - "getBaseTypeOfLiteralType", - TYPE, - type - ); - } - - public TSCType getWidenedType(TSCType type) { - return this.invokeMethodNonNull( - "getWidenedType", - TYPE, - type - ); - } - - public TSCType getReturnTypeOfSignature(TSCSignature signature) { - return this.invokeMethodNonNull( - "getReturnTypeOfSignature", - TYPE, - signature - ); - } - - public TSCType getNullableType(TSCType type, TSCTypeFlag... typeFlags) { - return this.invokeMethodNonNull( - "getNullableType", - TYPE, - type, - TSCTypeFlag.union(typeFlags) - ); - } - - public TSCType getNonNullableType(TSCType type) { - return this.invokeMethodNonNull( - "getNonNullableType", - TYPE, - type - ); - } - - public List getTypeArguments(TSCType type) { - return this.invokeMethodNonNull( - "getTypeArguments", - TYPE_LIST, - type - ); - } - - public List getSymbolsInScope(TSCNode location, TSCSymbolFlag... meaning) { - return this.invokeMethodNonNull( - "getSymbolsInScope", - SYMBOL_LIST, - location, - TSCSymbolFlag.union(meaning) - ); - } - - public @Nullable TSCSymbol getSymbolAtLocation(TSCNode node) { - return this.invokeMethodNullable( - "getSymbolAtLocation", - SYMBOL, - node - ); - } - - public List getSymbolsOfParameterPropertyDeclaration(TSCNode parameterDeclaration, String parameterName) { - return this.invokeMethodNonNull( - "getSymbolsOfParameterPropertyDeclaration", - SYMBOL_LIST, - parameterDeclaration, - parameterName - ); - } - - // - // TODO everything from `getShorthandAssignmentValueSymbol` on is unmapped, except the functions below - // - - public TSCType getTypeAtLocation(TSCNode node) { - return this.invokeMethodNonNull( - "getTypeAtLocation", - TYPE, - node - ); - } - - public TSCType getTypeFromTypeNode(TSCNode node) { - return this.invokeMethodNonNull( - "getTypeFromTypeNode", - TYPE, - node - ); - } - - public String signatureToString(TSCSignature signature) { - // TODO leaves out optional parameters - return this.invokeMethodNonNull( - "signatureToString", - STRING, - signature - ); - } - - public String typeToString(TSCType type) { - // TODO leaves out optional parameters - return this.invokeMethodNonNull( - "typeToString", - STRING, - type - ); - } - - public String symbolToString(TSCSymbol symbol) { - // TODO leaves out optional parameters - return this.invokeMethodNonNull( - "symbolToString", - STRING, - symbol - ); - } - - public String getFullyQualifiedName(TSCSymbol symbol) { - return this.invokeMethodNonNull( - "getFullyQualifiedName", - STRING, - symbol - ); - } - - public TSCType getAnyType() { - return this.invokeMethodNonNull("getAnyType", TYPE); - } - - public TSCType getStringType() { - return this.invokeMethodNonNull("getStringType", TYPE); - } - - public TSCType getStringLiteralType(String value) { - return this.invokeMethodNonNull("getStringLiteralType", TYPE, value); - } - - public TSCType getNumberType() { - return this.invokeMethodNonNull("getNumberType", TYPE); - } - - public TSCType getNumberLiteralType(Number value) { - return this.invokeMethodNonNull("getNumberLiteralType", TYPE, value); - } - - public TSCType getBigIntType() { - return this.invokeMethodNonNull("getBigIntType", TYPE); - } - - public TSCType getBooleanType() { - return this.invokeMethodNonNull("getBooleanType", TYPE); - } - - public TSCType getFalseType() { - return this.invokeMethodNonNull("getFalseType", TYPE); - } - - public TSCType getTrueType() { - return this.invokeMethodNonNull("getTrueType", TYPE); - } - - public TSCType getVoidType() { - return this.invokeMethodNonNull("getVoidType", TYPE); - } - - public TSCType getUndefinedType() { - return this.invokeMethodNonNull("getUndefinedType", TYPE); - } - - public TSCType getNullType() { - return this.invokeMethodNonNull("getNullType", TYPE); - } - - public TSCType getESSymbolType() { - return this.invokeMethodNonNull("getESSymbolType", TYPE); - } - - public TSCType getNeverType() { - return this.invokeMethodNonNull("getNeverType", TYPE); - } - - @Override - public TSCProgramContext getProgramContext() { - return programContext.get(); - } - - @Override - public V8ValueObject getBackingV8Object() { - return objectV8; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCUtils.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCUtils.java deleted file mode 100644 index 0501625b..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCUtils.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -public final class TSCUtils { - private TSCUtils() { - } - - public static String preview(String text, int maxLength) { - text = text.replace("\n", "⏎") - .replace("\t", "⇥") - .replace(" ", "·"); - - if (text.length() <= maxLength) { - return text; - } - - maxLength--; // to accommodate the ellipsis - int startLength = maxLength / 2; - int endLength = maxLength - startLength; - return text.substring(0, startLength) + "…" + text.substring(text.length() - endLength); - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCV8Backed.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCV8Backed.java deleted file mode 100644 index 4ac965e2..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCV8Backed.java +++ /dev/null @@ -1,412 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.reference.IV8ValueArray; -import com.caoccao.javet.values.reference.V8ValueArray; -import com.caoccao.javet.values.reference.V8ValueFunction; -import com.caoccao.javet.values.reference.V8ValueObject; -import lombok.Value; -import org.jspecify.annotations.Nullable; -import org.openrewrite.DebugOnly; -import org.openrewrite.javascript.internal.tsc.generated.TSCSyntaxKind; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import static org.openrewrite.javascript.internal.tsc.TSCConversions.*; - -public interface TSCV8Backed { - - interface Wrapper extends TSCV8Backed { - TSCV8Backed wrapped(); - - @Override - default TSCProgramContext getProgramContext() { - return wrapped().getProgramContext(); - } - - @Override - default V8ValueObject getBackingV8Object() { - return wrapped().getBackingV8Object(); - } - } - - @Value - class DebugInfo { - Map properties; - } - - /** - * For mapping objects that don't have long-lived V8 wrappers. - */ - static TSCV8Backed temporary(TSCProgramContext programContext, V8ValueObject objectV8) { - return new TSCV8Backed() { - @Override - public TSCProgramContext getProgramContext() { - return programContext; - } - - @Override - public V8ValueObject getBackingV8Object() { - return objectV8; - } - }; - } - - TSCProgramContext getProgramContext(); - - default TSCTypeChecker getTypeChecker() { - return getProgramContext().getTypeChecker(); - } - - default TSCGlobals getTS() { - return getProgramContext().getTypeScriptGlobals(); - } - - V8ValueObject getBackingV8Object(); - - @DebugOnly - default Object getDebugInfo() { - return new DebugInfo(getAllPropertiesForDebugging()); - } - - default V8Value getPropertyUnsafe(String name) { - try { - if (name.endsWith("()")) { - return this.getBackingV8Object().invoke(name.substring(0, name.length() - 2)); - } else { - return this.getBackingV8Object().get(name); - } - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - default V8Value invokeMethodUnsafe(String name, Object... args) { - Object[] converted = null; - for (int i = 0; i < args.length; i++) { - if (args[i] instanceof TSCV8Backed) { - if (converted == null) { - converted = args.clone(); - } - converted[i] = ((TSCV8Backed) args[i]).getBackingV8Object(); - } - } - if (converted == null) { - converted = args; - } - try { - return this.getBackingV8Object().invoke(name, converted); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - default @Nullable T invokeMethodNullable(String name, TSCConversion conversion, Object... args) { - try (V8Value valueV8 = invokeMethodUnsafe(name, args)) { - return conversion.convertNullable(getProgramContext(), valueV8); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - default T invokeMethodNonNull(String name, TSCConversion conversion, Object... args) { - try (V8Value valueV8 = invokeMethodUnsafe(name, args)) { - return conversion.convertNonNull(getProgramContext(), valueV8); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - default boolean invokeMethodBoolean(String name, Object... args) { - return invokeMethodNonNull(name, BOOLEAN, args); - } - - default @Nullable T getPropertyNullable(String name, TSCConversion conversion) { - try (V8Value value = getPropertyUnsafe(name)) { - return conversion.convertNullable(getProgramContext(), value); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - default T getPropertyNonNull(String name, TSCConversion conversion) { - try (V8Value value = getPropertyUnsafe(name)) { - return conversion.convertNonNull(getProgramContext(), value); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - // - // primitive properties - // - - default boolean getBooleanProperty(String name) { - return getPropertyNonNull(name, BOOLEAN); - } - - default @Nullable Boolean getOptionalBooleanProperty(String name) { - return getPropertyNullable(name, BOOLEAN); - } - - default int getIntProperty(String name) { - return getPropertyNonNull(name, INTEGER); - } - - default @Nullable Integer getOptionalIntProperty(String name) { - return getPropertyNullable(name, INTEGER); - } - - default long getLongProperty(String name) { - return getPropertyNonNull(name, LONG); - } - - default @Nullable Long getOptionalLongProperty(String name) { - return getPropertyNullable(name, LONG); - } - - - default String getStringProperty(String name) { - return getPropertyNonNull(name, STRING); - } - - default @Nullable String getOptionalStringProperty(String name) { - return getPropertyNullable(name, STRING); - } - - // - // enum properties - // - - default TSCSyntaxKind getSyntaxKindProperty(String name) { - return getPropertyNonNull(name, SYNTAX_KIND); - } - - default @Nullable TSCSyntaxKind getOptionalSyntaxKindProperty(String name) { - return getPropertyNullable(name, SYNTAX_KIND); - } - - // - // node properties - // - - default TSCNode getNodeProperty(String name) { - return getPropertyNonNull(name, NODE); - } - - default @Nullable TSCNode getOptionalNodeProperty(String name) { - return getPropertyNullable(name, NODE); - } - - default TSCNodeList getNodeListProperty(String name) { - return getPropertyNonNull(name, NODE_LIST); - } - - default @Nullable TSCNodeList getOptionalNodeListProperty(String name) { - return getPropertyNullable(name, NODE_LIST); - } - - default TSCNode.TypeNode getTypeNodeProperty(String name) { - return getPropertyNonNull(name, TYPE_NODE); - } - - default TSCNode.@Nullable TypeNode getOptionalTypeNodeProperty(String name) { - return getPropertyNullable(name, TYPE_NODE); - } - - default TSCSyntaxListNode getSyntaxListProperty(String name) { - return getPropertyNonNull(name, SYNTAX_LIST_NODE); - } - - default @Nullable TSCSyntaxListNode getOptionalSyntaxListProperty(String name) { - return getPropertyNullable(name, SYNTAX_LIST_NODE); - } - - // - // type properties - // - - default TSCType getTypeProperty(String name) { - return getPropertyNonNull(name, TYPE); - } - - default @Nullable TSCType getOptionalTypeProperty(String name) { - return getPropertyNullable(name, TYPE); - } - - default List getTypeListProperty(String name) { - return getPropertyNonNull(name, TYPE_LIST); - } - - default @Nullable List getOptionalTypeListProperty(String name) { - return getPropertyNullable(name, TYPE_LIST); - } - - // - // symbol properties - // - - default TSCSymbol getSymbolProperty(String name) { - return getPropertyNonNull(name, SYMBOL); - } - - default @Nullable TSCSymbol getOptionalSymbolProperty(String name) { - return getPropertyNullable(name, SYMBOL); - } - - default List getSymbolListProperty(String name) { - return getPropertyNonNull(name, SYMBOL_LIST); - } - - default @Nullable List getOptionalSymbolListProperty(String name) { - return getPropertyNullable(name, SYMBOL_LIST); - } - - // - // signature properties - // - - default TSCSignature getSignatureProperty(String name) { - return getPropertyNonNull(name, SIGNATURE); - } - - default @Nullable TSCSignature getOptionalSignatureProperty(String name) { - return getPropertyNullable(name, SIGNATURE); - } - - - default List getSignatureListProperty(String name) { - return getPropertyNonNull(name, SIGNATURE_LIST); - } - - default @Nullable List getOptionalSignatureListProperty(String name) { - return getPropertyNullable(name, SIGNATURE_LIST); - } - - // - // IndexInfo properties - // - - default TSCIndexInfo getIndexInfoProperty(String name) { - try (V8Value v8Value = getPropertyUnsafe(name)) { - return TSCIndexInfo.fromJS(getProgramContext(), (V8ValueObject) v8Value); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - default @Nullable TSCIndexInfo getOptionalIndexInfoProperty(String name) { - try (V8Value v8Value = getPropertyUnsafe(name)) { - if (v8Value.isNullOrUndefined()) { - return null; - } - return TSCIndexInfo.fromJS(getProgramContext(), (V8ValueObject) v8Value); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - - default List getIndexInfoListProperty(String name) { - try (V8Value v8Value = getPropertyUnsafe(name)) { - V8ValueArray v8Array = (V8ValueArray) v8Value; - List result = new ArrayList<>(v8Array.getLength()); - ((V8ValueArray) v8Value).forEach(childV8Value -> { - result.add(TSCIndexInfo.fromJS(getProgramContext(), (V8ValueObject) childV8Value)); - }); - return result; - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - default @Nullable List getOptionalIndexInfoListProperty(String name) { - try (V8Value v8Value = getPropertyUnsafe(name)) { - if (v8Value.isNullOrUndefined()) { - return null; - } - V8ValueArray v8Array = (V8ValueArray) v8Value; - List result = new ArrayList<>(v8Array.getLength()); - ((V8ValueArray) v8Value).forEach(childV8Value -> { - result.add(TSCIndexInfo.fromJS(getProgramContext(), (V8ValueObject) childV8Value)); - }); - return result; - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - // - // misc - // - - default boolean hasProperty(String propertyName) { - try (V8Value value = getPropertyUnsafe(propertyName)) { - return !value.isUndefined(); - } catch (JavetException ignored) { - return false; - } - } - - default @Nullable String getConstructorName() { - try (V8Value constructor = this.getPropertyUnsafe("constructor")) { - if (constructor.isNullOrUndefined()) { - return null; - } - if (!(constructor instanceof V8ValueFunction)) { - return null; - } - return ((V8ValueFunction) constructor).getPropertyString("name"); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - @DebugOnly - default Map getAllPropertiesForDebugging() { - return this.as(objectMap(AUTO)); - } - - default List getOwnPropertyNames() { - try { - return this.getBackingV8Object().getOwnPropertyNameStrings(); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - default List getAllPropertyNames() { - try(IV8ValueArray propertyNames = this.getBackingV8Object().getPropertyNames()) { - List result = new ArrayList<>(propertyNames.getLength()); - for (int i = 0; i < propertyNames.getLength(); i++) { - result.add(propertyNames.getString(i)); - } - return result; - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - - default T as(TSCConversion conversion) { - return conversion.convertNonNull(this.getProgramContext(), this.getBackingV8Object()); - } - -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCV8Utils.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCV8Utils.java deleted file mode 100644 index 7b791f4e..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCV8Utils.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.interop.V8Runtime; -import com.caoccao.javet.values.V8Value; -import com.caoccao.javet.values.primitive.V8ValueString; -import com.caoccao.javet.values.reference.IV8ValueObject; -import com.caoccao.javet.values.reference.V8ValueFunction; -import org.intellij.lang.annotations.Language; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; - -public class TSCV8Utils { - private TSCV8Utils() { - } - - private final static Pattern IDENTIFIER_PATTERN = Pattern.compile("^([a-zA-Z_$][a-zA-Z\\\\d_$]*)$"); - - public static void assertValidIdentifier(String name) { - if (!IDENTIFIER_PATTERN.matcher(name).matches()) { - throw new IllegalArgumentException(String.format("not a valid JS identifier: `%s`", name)); - } - } - - public static V8ValueFunction makeFunction( - V8Runtime runtime, - @Language("typescript") String innerCode, - IV8ValueObject variables - ) { - final List varNames; - try { - varNames = new ArrayList<>(); - variables.forEach((V8ValueString varName, V8Value varValue) -> { - TSCV8Utils.assertValidIdentifier(varName.getValue()); - varNames.add(varName.getValue()); - }); - } catch (JavetException e) { - throw new RuntimeException(e); - } - - String outerArgs = "{" + String.join(",", varNames) + "}"; - String outerCode = String.format("(%s) => {return %s;}", outerArgs, innerCode); - try ( - V8ValueFunction outerFn = runtime.createV8ValueFunction(outerCode); - V8Value innerFnObject = outerFn.call(null, variables) - ) { - if (!(innerFnObject instanceof V8ValueFunction)) { - throw new IllegalStateException("expected a function; found: " + innerFnObject.getClass().getSimpleName()); - } - return innerFnObject.toClone(); - } catch (JavetException e) { - throw new RuntimeException(e); - } - } - -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCV8ValueHolder.java b/src/main/java/org/openrewrite/javascript/internal/tsc/TSCV8ValueHolder.java deleted file mode 100644 index 39a6ac3e..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/TSCV8ValueHolder.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal.tsc; - -import com.caoccao.javet.exceptions.JavetException; -import com.caoccao.javet.values.IV8Value; -import com.caoccao.javet.values.primitive.V8ValueNull; -import com.caoccao.javet.values.primitive.V8ValuePrimitive; -import com.caoccao.javet.values.primitive.V8ValueUndefined; -import org.openrewrite.javascript.internal.JavetUtils; - -import java.util.ArrayList; -import java.util.List; - -public abstract class TSCV8ValueHolder implements AutoCloseable { - - private final List v8Values = new ArrayList<>(); - private final List otherValues = new ArrayList<>(); - private boolean isClosed = false; - - protected T lifecycleLinked(T value) { - if (isClosed) { - throw new IllegalStateException("attempt to add value when already closed"); - } - - if (value instanceof V8ValuePrimitive || value instanceof V8ValueUndefined || value instanceof V8ValueNull) { - // primitives, null, and undefined aren't managed - return value; - } - - if (value instanceof IV8Value) { - try { - //noinspection unchecked - value = (T) ((IV8Value) value).toClone(); - } catch (JavetException e) { - throw new RuntimeException(e); - } - this.v8Values.add((IV8Value) value); - } else { - this.otherValues.add(value); - } - - return value; - } - - @Override - public final void close() { - if (this.isClosed) { - throw new IllegalStateException("already closed"); - } - this.isClosed = true; - - for (IV8Value valueV8 : v8Values) { - JavetUtils.close(valueV8); - } - for (AutoCloseable value : otherValues) { - try { - value.close(); - } catch (Exception e) { - System.err.println("Exception while attempting to close a " + value.getClass().getName()); - e.printStackTrace(); - } - } - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCFlowFlag.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCFlowFlag.java deleted file mode 100644 index 0430d4d4..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCFlowFlag.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ - -package org.openrewrite.javascript.internal.tsc.generated; - -// -// THIS FILE IS GENERATED. Do not modify it by hand. -// See `js/README.md` for instructions to regenerate this file. -// - -public enum TSCFlowFlag { - Unreachable(1), - Start(2), - BranchLabel(4), - LoopLabel(8), - Assignment(16), - TrueCondition(32), - FalseCondition(64), - SwitchClause(128), - ArrayMutation(256), - Call(512), - ReduceLabel(1024), - Referenced(2048), - Shared(4096), - Label(12), - Condition(96); - - - public final int code; - - TSCFlowFlag(int code) { - this.code = code; - } - - public static TSCFlowFlag fromMaskExact(int code) { - switch (code) { - case 1: - return TSCFlowFlag.Unreachable; - case 2: - return TSCFlowFlag.Start; - case 4: - return TSCFlowFlag.BranchLabel; - case 8: - return TSCFlowFlag.LoopLabel; - case 16: - return TSCFlowFlag.Assignment; - case 32: - return TSCFlowFlag.TrueCondition; - case 64: - return TSCFlowFlag.FalseCondition; - case 128: - return TSCFlowFlag.SwitchClause; - case 256: - return TSCFlowFlag.ArrayMutation; - case 512: - return TSCFlowFlag.Call; - case 1024: - return TSCFlowFlag.ReduceLabel; - case 2048: - return TSCFlowFlag.Referenced; - case 4096: - return TSCFlowFlag.Shared; - case 12: - return TSCFlowFlag.Label; - case 96: - return TSCFlowFlag.Condition; - default: - throw new IllegalArgumentException("unknown TSCFlowFlag code: " + code); - } - } - - public boolean matches(int bitfield) { - return (bitfield & this.code) != 0; - } - - public static int union(TSCFlowFlag... args) { - int result = 0; - for (TSCFlowFlag arg : args) { - result = result | arg.code; - } - return result; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCIndexKind.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCIndexKind.java deleted file mode 100644 index a817793a..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCIndexKind.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ - -package org.openrewrite.javascript.internal.tsc.generated; - -// -// THIS FILE IS GENERATED. Do not modify it by hand. -// See `js/README.md` for instructions to regenerate this file. -// - -public enum TSCIndexKind { - String(0), - Number(1); - - - public final int code; - - TSCIndexKind(int code) { - this.code = code; - } - - public static TSCIndexKind fromCode(int code) { - switch (code) { - case 0: - return TSCIndexKind.String; - case 1: - return TSCIndexKind.Number; - default: - throw new IllegalArgumentException("unknown TSCIndexKind code: " + code); - } - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCModifierFlag.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCModifierFlag.java deleted file mode 100644 index b1adc9db..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCModifierFlag.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ - -package org.openrewrite.javascript.internal.tsc.generated; - -// -// THIS FILE IS GENERATED. Do not modify it by hand. -// See `js/README.md` for instructions to regenerate this file. -// - -public enum TSCModifierFlag { - None(0), - Export(1), - Ambient(2), - Public(4), - Private(8), - Protected(16), - Static(32), - Readonly(64), - Accessor(128), - Abstract(256), - Async(512), - Default(1024), - Const(2048), - HasComputedJSDocModifiers(4096), - Deprecated(8192), - Override(16384), - In(32768), - Out(65536), - Decorator(131072), - HasComputedFlags(536870912), - AccessibilityModifier(28), - ParameterPropertyModifier(16476), - NonPublicAccessibilityModifier(24), - TypeScriptModifier(117086), - ExportDefault(1025), - All(258047), - Modifier(126975); - - - public final int code; - - TSCModifierFlag(int code) { - this.code = code; - } - - public static TSCModifierFlag fromMaskExact(int code) { - switch (code) { - case 0: - return TSCModifierFlag.None; - case 1: - return TSCModifierFlag.Export; - case 2: - return TSCModifierFlag.Ambient; - case 4: - return TSCModifierFlag.Public; - case 8: - return TSCModifierFlag.Private; - case 16: - return TSCModifierFlag.Protected; - case 32: - return TSCModifierFlag.Static; - case 64: - return TSCModifierFlag.Readonly; - case 128: - return TSCModifierFlag.Accessor; - case 256: - return TSCModifierFlag.Abstract; - case 512: - return TSCModifierFlag.Async; - case 1024: - return TSCModifierFlag.Default; - case 2048: - return TSCModifierFlag.Const; - case 4096: - return TSCModifierFlag.HasComputedJSDocModifiers; - case 8192: - return TSCModifierFlag.Deprecated; - case 16384: - return TSCModifierFlag.Override; - case 32768: - return TSCModifierFlag.In; - case 65536: - return TSCModifierFlag.Out; - case 131072: - return TSCModifierFlag.Decorator; - case 536870912: - return TSCModifierFlag.HasComputedFlags; - case 28: - return TSCModifierFlag.AccessibilityModifier; - case 16476: - return TSCModifierFlag.ParameterPropertyModifier; - case 24: - return TSCModifierFlag.NonPublicAccessibilityModifier; - case 117086: - return TSCModifierFlag.TypeScriptModifier; - case 1025: - return TSCModifierFlag.ExportDefault; - case 258047: - return TSCModifierFlag.All; - case 126975: - return TSCModifierFlag.Modifier; - default: - throw new IllegalArgumentException("unknown TSCModifierFlag code: " + code); - } - } - - public boolean matches(int bitfield) { - return (bitfield & this.code) != 0; - } - - public static int union(TSCModifierFlag... args) { - int result = 0; - for (TSCModifierFlag arg : args) { - result = result | arg.code; - } - return result; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCNodeFlag.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCNodeFlag.java deleted file mode 100644 index 28006845..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCNodeFlag.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ - -package org.openrewrite.javascript.internal.tsc.generated; - -// -// THIS FILE IS GENERATED. Do not modify it by hand. -// See `js/README.md` for instructions to regenerate this file. -// - -public enum TSCNodeFlag { - None(0), - Let(1), - Const(2), - Using(4), - /** Also includes Constant */ - AwaitUsing(6), - NestedNamespace(8), - Synthesized(16), - Namespace(32), - OptionalChain(64), - ExportContext(128), - /** Also includes IdentifierHasExtendedUnicodeEscape */ - ContainsThis(256), - HasImplicitReturn(512), - HasExplicitReturn(1024), - GlobalAugmentation(2048), - /** Also includes IdentifierIsInJSDocNamespace */ - HasAsyncFunctions(4096), - DisallowInContext(8192), - YieldContext(16384), - DecoratorContext(32768), - AwaitContext(65536), - DisallowConditionalTypesContext(131072), - ThisNodeHasError(262144), - JavaScriptFile(524288), - ThisNodeOrAnySubNodesHasError(1048576), - HasAggregatedChildData(2097152), - PossiblyContainsDynamicImport(4194304), - PossiblyContainsImportMeta(8388608), - JSDoc(16777216), - Ambient(33554432), - InWithStatement(67108864), - JsonFile(134217728), - TypeCached(268435456), - Deprecated(536870912), - BlockScoped(7), - ReachabilityCheckFlags(1536), - ReachabilityAndEmitFlags(5632), - ContextFlags(101441536), - TypeExcludesFlags(81920), - PermanentlySetIncrementalFlags(12582912); - - - public final int code; - - TSCNodeFlag(int code) { - this.code = code; - } - - public static TSCNodeFlag fromMaskExact(int code) { - switch (code) { - case 0: - return TSCNodeFlag.None; - case 1: - return TSCNodeFlag.Let; - case 2: - return TSCNodeFlag.Const; - case 4: - return TSCNodeFlag.Using; - case 6: - return TSCNodeFlag.AwaitUsing; - case 8: - return TSCNodeFlag.NestedNamespace; - case 16: - return TSCNodeFlag.Synthesized; - case 32: - return TSCNodeFlag.Namespace; - case 64: - return TSCNodeFlag.OptionalChain; - case 128: - return TSCNodeFlag.ExportContext; - case 256: - return TSCNodeFlag.ContainsThis; - case 512: - return TSCNodeFlag.HasImplicitReturn; - case 1024: - return TSCNodeFlag.HasExplicitReturn; - case 2048: - return TSCNodeFlag.GlobalAugmentation; - case 4096: - return TSCNodeFlag.HasAsyncFunctions; - case 8192: - return TSCNodeFlag.DisallowInContext; - case 16384: - return TSCNodeFlag.YieldContext; - case 32768: - return TSCNodeFlag.DecoratorContext; - case 65536: - return TSCNodeFlag.AwaitContext; - case 131072: - return TSCNodeFlag.DisallowConditionalTypesContext; - case 262144: - return TSCNodeFlag.ThisNodeHasError; - case 524288: - return TSCNodeFlag.JavaScriptFile; - case 1048576: - return TSCNodeFlag.ThisNodeOrAnySubNodesHasError; - case 2097152: - return TSCNodeFlag.HasAggregatedChildData; - case 4194304: - return TSCNodeFlag.PossiblyContainsDynamicImport; - case 8388608: - return TSCNodeFlag.PossiblyContainsImportMeta; - case 16777216: - return TSCNodeFlag.JSDoc; - case 33554432: - return TSCNodeFlag.Ambient; - case 67108864: - return TSCNodeFlag.InWithStatement; - case 134217728: - return TSCNodeFlag.JsonFile; - case 268435456: - return TSCNodeFlag.TypeCached; - case 536870912: - return TSCNodeFlag.Deprecated; - case 7: - return TSCNodeFlag.BlockScoped; - case 1536: - return TSCNodeFlag.ReachabilityCheckFlags; - case 5632: - return TSCNodeFlag.ReachabilityAndEmitFlags; - case 101441536: - return TSCNodeFlag.ContextFlags; - case 81920: - return TSCNodeFlag.TypeExcludesFlags; - case 12582912: - return TSCNodeFlag.PermanentlySetIncrementalFlags; - default: - throw new IllegalArgumentException("unknown TSCNodeFlag code: " + code); - } - } - - public boolean matches(int bitfield) { - return (bitfield & this.code) != 0; - } - - public static int union(TSCNodeFlag... args) { - int result = 0; - for (TSCNodeFlag arg : args) { - result = result | arg.code; - } - return result; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCObjectFlag.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCObjectFlag.java deleted file mode 100644 index c797f497..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCObjectFlag.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ - -package org.openrewrite.javascript.internal.tsc.generated; - -// -// THIS FILE IS GENERATED. Do not modify it by hand. -// See `js/README.md` for instructions to regenerate this file. -// - -public enum TSCObjectFlag { - None(0), - Class(1), - Interface(2), - Reference(4), - Tuple(8), - Anonymous(16), - Mapped(32), - Instantiated(64), - ObjectLiteral(128), - EvolvingArray(256), - ObjectLiteralPatternWithComputedProperties(512), - ReverseMapped(1024), - JsxAttributes(2048), - JSLiteral(4096), - FreshLiteral(8192), - ArrayLiteral(16384), - PrimitiveUnion(32768), - ContainsWideningType(65536), - ContainsObjectOrArrayLiteral(131072), - NonInferrableType(262144), - CouldContainTypeVariablesComputed(524288), - CouldContainTypeVariables(1048576), - ClassOrInterface(3), - RequiresWidening(196608), - PropagatingFlags(458752), - ObjectTypeKindMask(1343), - /** Also includes IsGenericTypeComputed */ - ContainsSpread(2097152), - /** Also includes IsGenericObjectType */ - ObjectRestType(4194304), - /** Also includes IsGenericIndexType */ - InstantiationExpressionType(8388608), - /** Also includes ContainsIntersections, IsNeverIntersectionComputed */ - IsClassInstanceClone(16777216), - /** Also includes IsUnknownLikeUnionComputed, IsNeverIntersection */ - IdenticalBaseTypeCalculated(33554432), - /** Also includes IsUnknownLikeUnion */ - IdenticalBaseTypeExists(67108864), - IsGenericType(12582912); - - - public final int code; - - TSCObjectFlag(int code) { - this.code = code; - } - - public static TSCObjectFlag fromMaskExact(int code) { - switch (code) { - case 0: - return TSCObjectFlag.None; - case 1: - return TSCObjectFlag.Class; - case 2: - return TSCObjectFlag.Interface; - case 4: - return TSCObjectFlag.Reference; - case 8: - return TSCObjectFlag.Tuple; - case 16: - return TSCObjectFlag.Anonymous; - case 32: - return TSCObjectFlag.Mapped; - case 64: - return TSCObjectFlag.Instantiated; - case 128: - return TSCObjectFlag.ObjectLiteral; - case 256: - return TSCObjectFlag.EvolvingArray; - case 512: - return TSCObjectFlag.ObjectLiteralPatternWithComputedProperties; - case 1024: - return TSCObjectFlag.ReverseMapped; - case 2048: - return TSCObjectFlag.JsxAttributes; - case 4096: - return TSCObjectFlag.JSLiteral; - case 8192: - return TSCObjectFlag.FreshLiteral; - case 16384: - return TSCObjectFlag.ArrayLiteral; - case 32768: - return TSCObjectFlag.PrimitiveUnion; - case 65536: - return TSCObjectFlag.ContainsWideningType; - case 131072: - return TSCObjectFlag.ContainsObjectOrArrayLiteral; - case 262144: - return TSCObjectFlag.NonInferrableType; - case 524288: - return TSCObjectFlag.CouldContainTypeVariablesComputed; - case 1048576: - return TSCObjectFlag.CouldContainTypeVariables; - case 3: - return TSCObjectFlag.ClassOrInterface; - case 196608: - return TSCObjectFlag.RequiresWidening; - case 458752: - return TSCObjectFlag.PropagatingFlags; - case 1343: - return TSCObjectFlag.ObjectTypeKindMask; - case 2097152: - return TSCObjectFlag.ContainsSpread; - case 4194304: - return TSCObjectFlag.ObjectRestType; - case 8388608: - return TSCObjectFlag.InstantiationExpressionType; - case 16777216: - return TSCObjectFlag.IsClassInstanceClone; - case 33554432: - return TSCObjectFlag.IdenticalBaseTypeCalculated; - case 67108864: - return TSCObjectFlag.IdenticalBaseTypeExists; - case 12582912: - return TSCObjectFlag.IsGenericType; - default: - throw new IllegalArgumentException("unknown TSCObjectFlag code: " + code); - } - } - - public boolean matches(int bitfield) { - return (bitfield & this.code) != 0; - } - - public static int union(TSCObjectFlag... args) { - int result = 0; - for (TSCObjectFlag arg : args) { - result = result | arg.code; - } - return result; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSignatureKind.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSignatureKind.java deleted file mode 100644 index 70f9c30d..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSignatureKind.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ - -package org.openrewrite.javascript.internal.tsc.generated; - -// -// THIS FILE IS GENERATED. Do not modify it by hand. -// See `js/README.md` for instructions to regenerate this file. -// - -public enum TSCSignatureKind { - Call(0), - Construct(1); - - - public final int code; - - TSCSignatureKind(int code) { - this.code = code; - } - - public static TSCSignatureKind fromCode(int code) { - switch (code) { - case 0: - return TSCSignatureKind.Call; - case 1: - return TSCSignatureKind.Construct; - default: - throw new IllegalArgumentException("unknown TSCSignatureKind code: " + code); - } - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSymbolFlag.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSymbolFlag.java deleted file mode 100644 index e1dbfb18..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSymbolFlag.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ - -package org.openrewrite.javascript.internal.tsc.generated; - -// -// THIS FILE IS GENERATED. Do not modify it by hand. -// See `js/README.md` for instructions to regenerate this file. -// - -public enum TSCSymbolFlag { - /** Also includes PropertyExcludes, NamespaceModuleExcludes */ - None(0), - FunctionScopedVariable(1), - BlockScopedVariable(2), - Property(4), - EnumMember(8), - Function(16), - Class(32), - Interface(64), - ConstEnum(128), - RegularEnum(256), - ValueModule(512), - NamespaceModule(1024), - TypeLiteral(2048), - ObjectLiteral(4096), - Method(8192), - Constructor(16384), - GetAccessor(32768), - SetAccessor(65536), - Signature(131072), - TypeParameter(262144), - TypeAlias(524288), - ExportValue(1048576), - /** Also includes AliasExcludes */ - Alias(2097152), - Prototype(4194304), - ExportStar(8388608), - Optional(16777216), - Transient(33554432), - Assignment(67108864), - ModuleExports(134217728), - All(67108863), - Enum(384), - Variable(3), - /** Also includes BlockScopedVariableExcludes, ParameterExcludes */ - Value(111551), - /** Also includes TypeAliasExcludes */ - Type(788968), - Namespace(1920), - Module(1536), - Accessor(98304), - FunctionScopedVariableExcludes(111550), - EnumMemberExcludes(900095), - FunctionExcludes(110991), - ClassExcludes(899503), - InterfaceExcludes(788872), - RegularEnumExcludes(899327), - ConstEnumExcludes(899967), - ValueModuleExcludes(110735), - MethodExcludes(103359), - GetAccessorExcludes(46015), - SetAccessorExcludes(78783), - AccessorExcludes(13247), - TypeParameterExcludes(526824), - ModuleMember(2623475), - ExportHasLocal(944), - BlockScoped(418), - PropertyOrAccessor(98308), - ClassMember(106500), - ExportSupportsDefaultModifier(112), - ExportDoesNotSupportDefaultModifier(-113), - Classifiable(2885600), - LateBindingContainer(6256); - - - public final int code; - - TSCSymbolFlag(int code) { - this.code = code; - } - - public static TSCSymbolFlag fromMaskExact(int code) { - switch (code) { - case 0: - return TSCSymbolFlag.None; - case 1: - return TSCSymbolFlag.FunctionScopedVariable; - case 2: - return TSCSymbolFlag.BlockScopedVariable; - case 4: - return TSCSymbolFlag.Property; - case 8: - return TSCSymbolFlag.EnumMember; - case 16: - return TSCSymbolFlag.Function; - case 32: - return TSCSymbolFlag.Class; - case 64: - return TSCSymbolFlag.Interface; - case 128: - return TSCSymbolFlag.ConstEnum; - case 256: - return TSCSymbolFlag.RegularEnum; - case 512: - return TSCSymbolFlag.ValueModule; - case 1024: - return TSCSymbolFlag.NamespaceModule; - case 2048: - return TSCSymbolFlag.TypeLiteral; - case 4096: - return TSCSymbolFlag.ObjectLiteral; - case 8192: - return TSCSymbolFlag.Method; - case 16384: - return TSCSymbolFlag.Constructor; - case 32768: - return TSCSymbolFlag.GetAccessor; - case 65536: - return TSCSymbolFlag.SetAccessor; - case 131072: - return TSCSymbolFlag.Signature; - case 262144: - return TSCSymbolFlag.TypeParameter; - case 524288: - return TSCSymbolFlag.TypeAlias; - case 1048576: - return TSCSymbolFlag.ExportValue; - case 2097152: - return TSCSymbolFlag.Alias; - case 4194304: - return TSCSymbolFlag.Prototype; - case 8388608: - return TSCSymbolFlag.ExportStar; - case 16777216: - return TSCSymbolFlag.Optional; - case 33554432: - return TSCSymbolFlag.Transient; - case 67108864: - return TSCSymbolFlag.Assignment; - case 134217728: - return TSCSymbolFlag.ModuleExports; - case 67108863: - return TSCSymbolFlag.All; - case 384: - return TSCSymbolFlag.Enum; - case 3: - return TSCSymbolFlag.Variable; - case 111551: - return TSCSymbolFlag.Value; - case 788968: - return TSCSymbolFlag.Type; - case 1920: - return TSCSymbolFlag.Namespace; - case 1536: - return TSCSymbolFlag.Module; - case 98304: - return TSCSymbolFlag.Accessor; - case 111550: - return TSCSymbolFlag.FunctionScopedVariableExcludes; - case 900095: - return TSCSymbolFlag.EnumMemberExcludes; - case 110991: - return TSCSymbolFlag.FunctionExcludes; - case 899503: - return TSCSymbolFlag.ClassExcludes; - case 788872: - return TSCSymbolFlag.InterfaceExcludes; - case 899327: - return TSCSymbolFlag.RegularEnumExcludes; - case 899967: - return TSCSymbolFlag.ConstEnumExcludes; - case 110735: - return TSCSymbolFlag.ValueModuleExcludes; - case 103359: - return TSCSymbolFlag.MethodExcludes; - case 46015: - return TSCSymbolFlag.GetAccessorExcludes; - case 78783: - return TSCSymbolFlag.SetAccessorExcludes; - case 13247: - return TSCSymbolFlag.AccessorExcludes; - case 526824: - return TSCSymbolFlag.TypeParameterExcludes; - case 2623475: - return TSCSymbolFlag.ModuleMember; - case 944: - return TSCSymbolFlag.ExportHasLocal; - case 418: - return TSCSymbolFlag.BlockScoped; - case 98308: - return TSCSymbolFlag.PropertyOrAccessor; - case 106500: - return TSCSymbolFlag.ClassMember; - case 112: - return TSCSymbolFlag.ExportSupportsDefaultModifier; - case -113: - return TSCSymbolFlag.ExportDoesNotSupportDefaultModifier; - case 2885600: - return TSCSymbolFlag.Classifiable; - case 6256: - return TSCSymbolFlag.LateBindingContainer; - default: - throw new IllegalArgumentException("unknown TSCSymbolFlag code: " + code); - } - } - - public boolean matches(int bitfield) { - return (bitfield & this.code) != 0; - } - - public static int union(TSCSymbolFlag... args) { - int result = 0; - for (TSCSymbolFlag arg : args) { - result = result | arg.code; - } - return result; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSyntaxKind.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSyntaxKind.java deleted file mode 100644 index 34b24817..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCSyntaxKind.java +++ /dev/null @@ -1,1157 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ - -package org.openrewrite.javascript.internal.tsc.generated; - -// -// THIS FILE IS GENERATED. Do not modify it by hand. -// See `js/README.md` for instructions to regenerate this file. -// - -public enum TSCSyntaxKind { - /** Also includes FirstToken */ - Unknown(0), - EndOfFileToken(1), - /** Also includes FirstTriviaToken */ - SingleLineCommentTrivia(2), - MultiLineCommentTrivia(3), - NewLineTrivia(4), - WhitespaceTrivia(5), - ShebangTrivia(6), - /** Also includes LastTriviaToken */ - ConflictMarkerTrivia(7), - NonTextFileMarkerTrivia(8), - /** Also includes FirstLiteralToken */ - NumericLiteral(9), - BigIntLiteral(10), - StringLiteral(11), - JsxText(12), - JsxTextAllWhiteSpaces(13), - RegularExpressionLiteral(14), - /** Also includes LastLiteralToken, FirstTemplateToken */ - NoSubstitutionTemplateLiteral(15), - TemplateHead(16), - TemplateMiddle(17), - /** Also includes LastTemplateToken */ - TemplateTail(18), - /** Also includes FirstPunctuation */ - OpenBraceToken(19), - CloseBraceToken(20), - OpenParenToken(21), - CloseParenToken(22), - OpenBracketToken(23), - CloseBracketToken(24), - DotToken(25), - DotDotDotToken(26), - SemicolonToken(27), - CommaToken(28), - QuestionDotToken(29), - /** Also includes FirstBinaryOperator */ - LessThanToken(30), - LessThanSlashToken(31), - GreaterThanToken(32), - LessThanEqualsToken(33), - GreaterThanEqualsToken(34), - EqualsEqualsToken(35), - ExclamationEqualsToken(36), - EqualsEqualsEqualsToken(37), - ExclamationEqualsEqualsToken(38), - EqualsGreaterThanToken(39), - PlusToken(40), - MinusToken(41), - AsteriskToken(42), - AsteriskAsteriskToken(43), - SlashToken(44), - PercentToken(45), - PlusPlusToken(46), - MinusMinusToken(47), - LessThanLessThanToken(48), - GreaterThanGreaterThanToken(49), - GreaterThanGreaterThanGreaterThanToken(50), - AmpersandToken(51), - BarToken(52), - CaretToken(53), - ExclamationToken(54), - TildeToken(55), - AmpersandAmpersandToken(56), - BarBarToken(57), - QuestionToken(58), - ColonToken(59), - AtToken(60), - QuestionQuestionToken(61), - BacktickToken(62), - HashToken(63), - /** Also includes FirstAssignment */ - EqualsToken(64), - /** Also includes FirstCompoundAssignment */ - PlusEqualsToken(65), - MinusEqualsToken(66), - AsteriskEqualsToken(67), - AsteriskAsteriskEqualsToken(68), - SlashEqualsToken(69), - PercentEqualsToken(70), - LessThanLessThanEqualsToken(71), - GreaterThanGreaterThanEqualsToken(72), - GreaterThanGreaterThanGreaterThanEqualsToken(73), - AmpersandEqualsToken(74), - BarEqualsToken(75), - BarBarEqualsToken(76), - AmpersandAmpersandEqualsToken(77), - QuestionQuestionEqualsToken(78), - /** Also includes LastAssignment, LastCompoundAssignment, LastPunctuation, LastBinaryOperator */ - CaretEqualsToken(79), - Identifier(80), - PrivateIdentifier(81), - JSDocCommentTextToken(82), - /** Also includes FirstReservedWord, FirstKeyword */ - BreakKeyword(83), - CaseKeyword(84), - CatchKeyword(85), - ClassKeyword(86), - ConstKeyword(87), - ContinueKeyword(88), - DebuggerKeyword(89), - DefaultKeyword(90), - DeleteKeyword(91), - DoKeyword(92), - ElseKeyword(93), - EnumKeyword(94), - ExportKeyword(95), - ExtendsKeyword(96), - FalseKeyword(97), - FinallyKeyword(98), - ForKeyword(99), - FunctionKeyword(100), - IfKeyword(101), - ImportKeyword(102), - InKeyword(103), - InstanceOfKeyword(104), - NewKeyword(105), - NullKeyword(106), - ReturnKeyword(107), - SuperKeyword(108), - SwitchKeyword(109), - ThisKeyword(110), - ThrowKeyword(111), - TrueKeyword(112), - TryKeyword(113), - TypeOfKeyword(114), - VarKeyword(115), - VoidKeyword(116), - WhileKeyword(117), - /** Also includes LastReservedWord */ - WithKeyword(118), - /** Also includes FirstFutureReservedWord */ - ImplementsKeyword(119), - InterfaceKeyword(120), - LetKeyword(121), - PackageKeyword(122), - PrivateKeyword(123), - ProtectedKeyword(124), - PublicKeyword(125), - StaticKeyword(126), - /** Also includes LastFutureReservedWord */ - YieldKeyword(127), - /** Also includes FirstContextualKeyword */ - AbstractKeyword(128), - AccessorKeyword(129), - AsKeyword(130), - AssertsKeyword(131), - AssertKeyword(132), - AnyKeyword(133), - AsyncKeyword(134), - AwaitKeyword(135), - BooleanKeyword(136), - ConstructorKeyword(137), - DeclareKeyword(138), - GetKeyword(139), - InferKeyword(140), - IntrinsicKeyword(141), - IsKeyword(142), - KeyOfKeyword(143), - ModuleKeyword(144), - NamespaceKeyword(145), - NeverKeyword(146), - OutKeyword(147), - ReadonlyKeyword(148), - RequireKeyword(149), - NumberKeyword(150), - ObjectKeyword(151), - SatisfiesKeyword(152), - SetKeyword(153), - StringKeyword(154), - SymbolKeyword(155), - TypeKeyword(156), - UndefinedKeyword(157), - UniqueKeyword(158), - UnknownKeyword(159), - UsingKeyword(160), - FromKeyword(161), - GlobalKeyword(162), - BigIntKeyword(163), - OverrideKeyword(164), - /** Also includes LastKeyword, LastToken, LastContextualKeyword */ - OfKeyword(165), - /** Also includes FirstNode */ - QualifiedName(166), - ComputedPropertyName(167), - TypeParameter(168), - Parameter(169), - Decorator(170), - PropertySignature(171), - PropertyDeclaration(172), - MethodSignature(173), - MethodDeclaration(174), - ClassStaticBlockDeclaration(175), - Constructor(176), - GetAccessor(177), - SetAccessor(178), - CallSignature(179), - ConstructSignature(180), - IndexSignature(181), - /** Also includes FirstTypeNode */ - TypePredicate(182), - TypeReference(183), - FunctionType(184), - ConstructorType(185), - TypeQuery(186), - TypeLiteral(187), - ArrayType(188), - TupleType(189), - OptionalType(190), - RestType(191), - UnionType(192), - IntersectionType(193), - ConditionalType(194), - InferType(195), - ParenthesizedType(196), - ThisType(197), - TypeOperator(198), - IndexedAccessType(199), - MappedType(200), - LiteralType(201), - NamedTupleMember(202), - TemplateLiteralType(203), - TemplateLiteralTypeSpan(204), - /** Also includes LastTypeNode */ - ImportType(205), - ObjectBindingPattern(206), - ArrayBindingPattern(207), - BindingElement(208), - ArrayLiteralExpression(209), - ObjectLiteralExpression(210), - PropertyAccessExpression(211), - ElementAccessExpression(212), - CallExpression(213), - NewExpression(214), - TaggedTemplateExpression(215), - TypeAssertionExpression(216), - ParenthesizedExpression(217), - FunctionExpression(218), - ArrowFunction(219), - DeleteExpression(220), - TypeOfExpression(221), - VoidExpression(222), - AwaitExpression(223), - PrefixUnaryExpression(224), - PostfixUnaryExpression(225), - BinaryExpression(226), - ConditionalExpression(227), - TemplateExpression(228), - YieldExpression(229), - SpreadElement(230), - ClassExpression(231), - OmittedExpression(232), - ExpressionWithTypeArguments(233), - AsExpression(234), - NonNullExpression(235), - MetaProperty(236), - SyntheticExpression(237), - SatisfiesExpression(238), - TemplateSpan(239), - SemicolonClassElement(240), - Block(241), - EmptyStatement(242), - /** Also includes FirstStatement */ - VariableStatement(243), - ExpressionStatement(244), - IfStatement(245), - DoStatement(246), - WhileStatement(247), - ForStatement(248), - ForInStatement(249), - ForOfStatement(250), - ContinueStatement(251), - BreakStatement(252), - ReturnStatement(253), - WithStatement(254), - SwitchStatement(255), - LabeledStatement(256), - ThrowStatement(257), - TryStatement(258), - /** Also includes LastStatement */ - DebuggerStatement(259), - VariableDeclaration(260), - VariableDeclarationList(261), - FunctionDeclaration(262), - ClassDeclaration(263), - InterfaceDeclaration(264), - TypeAliasDeclaration(265), - EnumDeclaration(266), - ModuleDeclaration(267), - ModuleBlock(268), - CaseBlock(269), - NamespaceExportDeclaration(270), - ImportEqualsDeclaration(271), - ImportDeclaration(272), - ImportClause(273), - NamespaceImport(274), - NamedImports(275), - ImportSpecifier(276), - ExportAssignment(277), - ExportDeclaration(278), - NamedExports(279), - NamespaceExport(280), - ExportSpecifier(281), - MissingDeclaration(282), - ExternalModuleReference(283), - JsxElement(284), - JsxSelfClosingElement(285), - JsxOpeningElement(286), - JsxClosingElement(287), - JsxFragment(288), - JsxOpeningFragment(289), - JsxClosingFragment(290), - JsxAttribute(291), - JsxAttributes(292), - JsxSpreadAttribute(293), - JsxExpression(294), - JsxNamespacedName(295), - CaseClause(296), - DefaultClause(297), - HeritageClause(298), - CatchClause(299), - AssertClause(300), - AssertEntry(301), - ImportTypeAssertionContainer(302), - PropertyAssignment(303), - ShorthandPropertyAssignment(304), - SpreadAssignment(305), - EnumMember(306), - UnparsedPrologue(307), - UnparsedPrepend(308), - UnparsedText(309), - UnparsedInternalText(310), - UnparsedSyntheticReference(311), - SourceFile(312), - Bundle(313), - UnparsedSource(314), - InputFiles(315), - /** Also includes FirstJSDocNode */ - JSDocTypeExpression(316), - JSDocNameReference(317), - JSDocMemberName(318), - JSDocAllType(319), - JSDocUnknownType(320), - JSDocNullableType(321), - JSDocNonNullableType(322), - JSDocOptionalType(323), - JSDocFunctionType(324), - JSDocVariadicType(325), - JSDocNamepathType(326), - /** Also includes JSDocComment */ - JSDoc(327), - JSDocText(328), - JSDocTypeLiteral(329), - JSDocSignature(330), - JSDocLink(331), - JSDocLinkCode(332), - JSDocLinkPlain(333), - /** Also includes FirstJSDocTagNode */ - JSDocTag(334), - JSDocAugmentsTag(335), - JSDocImplementsTag(336), - JSDocAuthorTag(337), - JSDocDeprecatedTag(338), - JSDocClassTag(339), - JSDocPublicTag(340), - JSDocPrivateTag(341), - JSDocProtectedTag(342), - JSDocReadonlyTag(343), - JSDocOverrideTag(344), - JSDocCallbackTag(345), - JSDocOverloadTag(346), - JSDocEnumTag(347), - JSDocParameterTag(348), - JSDocReturnTag(349), - JSDocThisTag(350), - JSDocTypeTag(351), - JSDocTemplateTag(352), - JSDocTypedefTag(353), - JSDocSeeTag(354), - JSDocPropertyTag(355), - JSDocThrowsTag(356), - /** Also includes LastJSDocNode, LastJSDocTagNode */ - JSDocSatisfiesTag(357), - SyntaxList(358), - NotEmittedStatement(359), - PartiallyEmittedExpression(360), - CommaListExpression(361), - SyntheticReferenceExpression(362), - Count(363); - - - public final int code; - - TSCSyntaxKind(int code) { - this.code = code; - } - - public static TSCSyntaxKind fromCode(int code) { - switch (code) { - case 0: - return TSCSyntaxKind.Unknown; - case 1: - return TSCSyntaxKind.EndOfFileToken; - case 2: - return TSCSyntaxKind.SingleLineCommentTrivia; - case 3: - return TSCSyntaxKind.MultiLineCommentTrivia; - case 4: - return TSCSyntaxKind.NewLineTrivia; - case 5: - return TSCSyntaxKind.WhitespaceTrivia; - case 6: - return TSCSyntaxKind.ShebangTrivia; - case 7: - return TSCSyntaxKind.ConflictMarkerTrivia; - case 8: - return TSCSyntaxKind.NonTextFileMarkerTrivia; - case 9: - return TSCSyntaxKind.NumericLiteral; - case 10: - return TSCSyntaxKind.BigIntLiteral; - case 11: - return TSCSyntaxKind.StringLiteral; - case 12: - return TSCSyntaxKind.JsxText; - case 13: - return TSCSyntaxKind.JsxTextAllWhiteSpaces; - case 14: - return TSCSyntaxKind.RegularExpressionLiteral; - case 15: - return TSCSyntaxKind.NoSubstitutionTemplateLiteral; - case 16: - return TSCSyntaxKind.TemplateHead; - case 17: - return TSCSyntaxKind.TemplateMiddle; - case 18: - return TSCSyntaxKind.TemplateTail; - case 19: - return TSCSyntaxKind.OpenBraceToken; - case 20: - return TSCSyntaxKind.CloseBraceToken; - case 21: - return TSCSyntaxKind.OpenParenToken; - case 22: - return TSCSyntaxKind.CloseParenToken; - case 23: - return TSCSyntaxKind.OpenBracketToken; - case 24: - return TSCSyntaxKind.CloseBracketToken; - case 25: - return TSCSyntaxKind.DotToken; - case 26: - return TSCSyntaxKind.DotDotDotToken; - case 27: - return TSCSyntaxKind.SemicolonToken; - case 28: - return TSCSyntaxKind.CommaToken; - case 29: - return TSCSyntaxKind.QuestionDotToken; - case 30: - return TSCSyntaxKind.LessThanToken; - case 31: - return TSCSyntaxKind.LessThanSlashToken; - case 32: - return TSCSyntaxKind.GreaterThanToken; - case 33: - return TSCSyntaxKind.LessThanEqualsToken; - case 34: - return TSCSyntaxKind.GreaterThanEqualsToken; - case 35: - return TSCSyntaxKind.EqualsEqualsToken; - case 36: - return TSCSyntaxKind.ExclamationEqualsToken; - case 37: - return TSCSyntaxKind.EqualsEqualsEqualsToken; - case 38: - return TSCSyntaxKind.ExclamationEqualsEqualsToken; - case 39: - return TSCSyntaxKind.EqualsGreaterThanToken; - case 40: - return TSCSyntaxKind.PlusToken; - case 41: - return TSCSyntaxKind.MinusToken; - case 42: - return TSCSyntaxKind.AsteriskToken; - case 43: - return TSCSyntaxKind.AsteriskAsteriskToken; - case 44: - return TSCSyntaxKind.SlashToken; - case 45: - return TSCSyntaxKind.PercentToken; - case 46: - return TSCSyntaxKind.PlusPlusToken; - case 47: - return TSCSyntaxKind.MinusMinusToken; - case 48: - return TSCSyntaxKind.LessThanLessThanToken; - case 49: - return TSCSyntaxKind.GreaterThanGreaterThanToken; - case 50: - return TSCSyntaxKind.GreaterThanGreaterThanGreaterThanToken; - case 51: - return TSCSyntaxKind.AmpersandToken; - case 52: - return TSCSyntaxKind.BarToken; - case 53: - return TSCSyntaxKind.CaretToken; - case 54: - return TSCSyntaxKind.ExclamationToken; - case 55: - return TSCSyntaxKind.TildeToken; - case 56: - return TSCSyntaxKind.AmpersandAmpersandToken; - case 57: - return TSCSyntaxKind.BarBarToken; - case 58: - return TSCSyntaxKind.QuestionToken; - case 59: - return TSCSyntaxKind.ColonToken; - case 60: - return TSCSyntaxKind.AtToken; - case 61: - return TSCSyntaxKind.QuestionQuestionToken; - case 62: - return TSCSyntaxKind.BacktickToken; - case 63: - return TSCSyntaxKind.HashToken; - case 64: - return TSCSyntaxKind.EqualsToken; - case 65: - return TSCSyntaxKind.PlusEqualsToken; - case 66: - return TSCSyntaxKind.MinusEqualsToken; - case 67: - return TSCSyntaxKind.AsteriskEqualsToken; - case 68: - return TSCSyntaxKind.AsteriskAsteriskEqualsToken; - case 69: - return TSCSyntaxKind.SlashEqualsToken; - case 70: - return TSCSyntaxKind.PercentEqualsToken; - case 71: - return TSCSyntaxKind.LessThanLessThanEqualsToken; - case 72: - return TSCSyntaxKind.GreaterThanGreaterThanEqualsToken; - case 73: - return TSCSyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken; - case 74: - return TSCSyntaxKind.AmpersandEqualsToken; - case 75: - return TSCSyntaxKind.BarEqualsToken; - case 76: - return TSCSyntaxKind.BarBarEqualsToken; - case 77: - return TSCSyntaxKind.AmpersandAmpersandEqualsToken; - case 78: - return TSCSyntaxKind.QuestionQuestionEqualsToken; - case 79: - return TSCSyntaxKind.CaretEqualsToken; - case 80: - return TSCSyntaxKind.Identifier; - case 81: - return TSCSyntaxKind.PrivateIdentifier; - case 82: - return TSCSyntaxKind.JSDocCommentTextToken; - case 83: - return TSCSyntaxKind.BreakKeyword; - case 84: - return TSCSyntaxKind.CaseKeyword; - case 85: - return TSCSyntaxKind.CatchKeyword; - case 86: - return TSCSyntaxKind.ClassKeyword; - case 87: - return TSCSyntaxKind.ConstKeyword; - case 88: - return TSCSyntaxKind.ContinueKeyword; - case 89: - return TSCSyntaxKind.DebuggerKeyword; - case 90: - return TSCSyntaxKind.DefaultKeyword; - case 91: - return TSCSyntaxKind.DeleteKeyword; - case 92: - return TSCSyntaxKind.DoKeyword; - case 93: - return TSCSyntaxKind.ElseKeyword; - case 94: - return TSCSyntaxKind.EnumKeyword; - case 95: - return TSCSyntaxKind.ExportKeyword; - case 96: - return TSCSyntaxKind.ExtendsKeyword; - case 97: - return TSCSyntaxKind.FalseKeyword; - case 98: - return TSCSyntaxKind.FinallyKeyword; - case 99: - return TSCSyntaxKind.ForKeyword; - case 100: - return TSCSyntaxKind.FunctionKeyword; - case 101: - return TSCSyntaxKind.IfKeyword; - case 102: - return TSCSyntaxKind.ImportKeyword; - case 103: - return TSCSyntaxKind.InKeyword; - case 104: - return TSCSyntaxKind.InstanceOfKeyword; - case 105: - return TSCSyntaxKind.NewKeyword; - case 106: - return TSCSyntaxKind.NullKeyword; - case 107: - return TSCSyntaxKind.ReturnKeyword; - case 108: - return TSCSyntaxKind.SuperKeyword; - case 109: - return TSCSyntaxKind.SwitchKeyword; - case 110: - return TSCSyntaxKind.ThisKeyword; - case 111: - return TSCSyntaxKind.ThrowKeyword; - case 112: - return TSCSyntaxKind.TrueKeyword; - case 113: - return TSCSyntaxKind.TryKeyword; - case 114: - return TSCSyntaxKind.TypeOfKeyword; - case 115: - return TSCSyntaxKind.VarKeyword; - case 116: - return TSCSyntaxKind.VoidKeyword; - case 117: - return TSCSyntaxKind.WhileKeyword; - case 118: - return TSCSyntaxKind.WithKeyword; - case 119: - return TSCSyntaxKind.ImplementsKeyword; - case 120: - return TSCSyntaxKind.InterfaceKeyword; - case 121: - return TSCSyntaxKind.LetKeyword; - case 122: - return TSCSyntaxKind.PackageKeyword; - case 123: - return TSCSyntaxKind.PrivateKeyword; - case 124: - return TSCSyntaxKind.ProtectedKeyword; - case 125: - return TSCSyntaxKind.PublicKeyword; - case 126: - return TSCSyntaxKind.StaticKeyword; - case 127: - return TSCSyntaxKind.YieldKeyword; - case 128: - return TSCSyntaxKind.AbstractKeyword; - case 129: - return TSCSyntaxKind.AccessorKeyword; - case 130: - return TSCSyntaxKind.AsKeyword; - case 131: - return TSCSyntaxKind.AssertsKeyword; - case 132: - return TSCSyntaxKind.AssertKeyword; - case 133: - return TSCSyntaxKind.AnyKeyword; - case 134: - return TSCSyntaxKind.AsyncKeyword; - case 135: - return TSCSyntaxKind.AwaitKeyword; - case 136: - return TSCSyntaxKind.BooleanKeyword; - case 137: - return TSCSyntaxKind.ConstructorKeyword; - case 138: - return TSCSyntaxKind.DeclareKeyword; - case 139: - return TSCSyntaxKind.GetKeyword; - case 140: - return TSCSyntaxKind.InferKeyword; - case 141: - return TSCSyntaxKind.IntrinsicKeyword; - case 142: - return TSCSyntaxKind.IsKeyword; - case 143: - return TSCSyntaxKind.KeyOfKeyword; - case 144: - return TSCSyntaxKind.ModuleKeyword; - case 145: - return TSCSyntaxKind.NamespaceKeyword; - case 146: - return TSCSyntaxKind.NeverKeyword; - case 147: - return TSCSyntaxKind.OutKeyword; - case 148: - return TSCSyntaxKind.ReadonlyKeyword; - case 149: - return TSCSyntaxKind.RequireKeyword; - case 150: - return TSCSyntaxKind.NumberKeyword; - case 151: - return TSCSyntaxKind.ObjectKeyword; - case 152: - return TSCSyntaxKind.SatisfiesKeyword; - case 153: - return TSCSyntaxKind.SetKeyword; - case 154: - return TSCSyntaxKind.StringKeyword; - case 155: - return TSCSyntaxKind.SymbolKeyword; - case 156: - return TSCSyntaxKind.TypeKeyword; - case 157: - return TSCSyntaxKind.UndefinedKeyword; - case 158: - return TSCSyntaxKind.UniqueKeyword; - case 159: - return TSCSyntaxKind.UnknownKeyword; - case 160: - return TSCSyntaxKind.UsingKeyword; - case 161: - return TSCSyntaxKind.FromKeyword; - case 162: - return TSCSyntaxKind.GlobalKeyword; - case 163: - return TSCSyntaxKind.BigIntKeyword; - case 164: - return TSCSyntaxKind.OverrideKeyword; - case 165: - return TSCSyntaxKind.OfKeyword; - case 166: - return TSCSyntaxKind.QualifiedName; - case 167: - return TSCSyntaxKind.ComputedPropertyName; - case 168: - return TSCSyntaxKind.TypeParameter; - case 169: - return TSCSyntaxKind.Parameter; - case 170: - return TSCSyntaxKind.Decorator; - case 171: - return TSCSyntaxKind.PropertySignature; - case 172: - return TSCSyntaxKind.PropertyDeclaration; - case 173: - return TSCSyntaxKind.MethodSignature; - case 174: - return TSCSyntaxKind.MethodDeclaration; - case 175: - return TSCSyntaxKind.ClassStaticBlockDeclaration; - case 176: - return TSCSyntaxKind.Constructor; - case 177: - return TSCSyntaxKind.GetAccessor; - case 178: - return TSCSyntaxKind.SetAccessor; - case 179: - return TSCSyntaxKind.CallSignature; - case 180: - return TSCSyntaxKind.ConstructSignature; - case 181: - return TSCSyntaxKind.IndexSignature; - case 182: - return TSCSyntaxKind.TypePredicate; - case 183: - return TSCSyntaxKind.TypeReference; - case 184: - return TSCSyntaxKind.FunctionType; - case 185: - return TSCSyntaxKind.ConstructorType; - case 186: - return TSCSyntaxKind.TypeQuery; - case 187: - return TSCSyntaxKind.TypeLiteral; - case 188: - return TSCSyntaxKind.ArrayType; - case 189: - return TSCSyntaxKind.TupleType; - case 190: - return TSCSyntaxKind.OptionalType; - case 191: - return TSCSyntaxKind.RestType; - case 192: - return TSCSyntaxKind.UnionType; - case 193: - return TSCSyntaxKind.IntersectionType; - case 194: - return TSCSyntaxKind.ConditionalType; - case 195: - return TSCSyntaxKind.InferType; - case 196: - return TSCSyntaxKind.ParenthesizedType; - case 197: - return TSCSyntaxKind.ThisType; - case 198: - return TSCSyntaxKind.TypeOperator; - case 199: - return TSCSyntaxKind.IndexedAccessType; - case 200: - return TSCSyntaxKind.MappedType; - case 201: - return TSCSyntaxKind.LiteralType; - case 202: - return TSCSyntaxKind.NamedTupleMember; - case 203: - return TSCSyntaxKind.TemplateLiteralType; - case 204: - return TSCSyntaxKind.TemplateLiteralTypeSpan; - case 205: - return TSCSyntaxKind.ImportType; - case 206: - return TSCSyntaxKind.ObjectBindingPattern; - case 207: - return TSCSyntaxKind.ArrayBindingPattern; - case 208: - return TSCSyntaxKind.BindingElement; - case 209: - return TSCSyntaxKind.ArrayLiteralExpression; - case 210: - return TSCSyntaxKind.ObjectLiteralExpression; - case 211: - return TSCSyntaxKind.PropertyAccessExpression; - case 212: - return TSCSyntaxKind.ElementAccessExpression; - case 213: - return TSCSyntaxKind.CallExpression; - case 214: - return TSCSyntaxKind.NewExpression; - case 215: - return TSCSyntaxKind.TaggedTemplateExpression; - case 216: - return TSCSyntaxKind.TypeAssertionExpression; - case 217: - return TSCSyntaxKind.ParenthesizedExpression; - case 218: - return TSCSyntaxKind.FunctionExpression; - case 219: - return TSCSyntaxKind.ArrowFunction; - case 220: - return TSCSyntaxKind.DeleteExpression; - case 221: - return TSCSyntaxKind.TypeOfExpression; - case 222: - return TSCSyntaxKind.VoidExpression; - case 223: - return TSCSyntaxKind.AwaitExpression; - case 224: - return TSCSyntaxKind.PrefixUnaryExpression; - case 225: - return TSCSyntaxKind.PostfixUnaryExpression; - case 226: - return TSCSyntaxKind.BinaryExpression; - case 227: - return TSCSyntaxKind.ConditionalExpression; - case 228: - return TSCSyntaxKind.TemplateExpression; - case 229: - return TSCSyntaxKind.YieldExpression; - case 230: - return TSCSyntaxKind.SpreadElement; - case 231: - return TSCSyntaxKind.ClassExpression; - case 232: - return TSCSyntaxKind.OmittedExpression; - case 233: - return TSCSyntaxKind.ExpressionWithTypeArguments; - case 234: - return TSCSyntaxKind.AsExpression; - case 235: - return TSCSyntaxKind.NonNullExpression; - case 236: - return TSCSyntaxKind.MetaProperty; - case 237: - return TSCSyntaxKind.SyntheticExpression; - case 238: - return TSCSyntaxKind.SatisfiesExpression; - case 239: - return TSCSyntaxKind.TemplateSpan; - case 240: - return TSCSyntaxKind.SemicolonClassElement; - case 241: - return TSCSyntaxKind.Block; - case 242: - return TSCSyntaxKind.EmptyStatement; - case 243: - return TSCSyntaxKind.VariableStatement; - case 244: - return TSCSyntaxKind.ExpressionStatement; - case 245: - return TSCSyntaxKind.IfStatement; - case 246: - return TSCSyntaxKind.DoStatement; - case 247: - return TSCSyntaxKind.WhileStatement; - case 248: - return TSCSyntaxKind.ForStatement; - case 249: - return TSCSyntaxKind.ForInStatement; - case 250: - return TSCSyntaxKind.ForOfStatement; - case 251: - return TSCSyntaxKind.ContinueStatement; - case 252: - return TSCSyntaxKind.BreakStatement; - case 253: - return TSCSyntaxKind.ReturnStatement; - case 254: - return TSCSyntaxKind.WithStatement; - case 255: - return TSCSyntaxKind.SwitchStatement; - case 256: - return TSCSyntaxKind.LabeledStatement; - case 257: - return TSCSyntaxKind.ThrowStatement; - case 258: - return TSCSyntaxKind.TryStatement; - case 259: - return TSCSyntaxKind.DebuggerStatement; - case 260: - return TSCSyntaxKind.VariableDeclaration; - case 261: - return TSCSyntaxKind.VariableDeclarationList; - case 262: - return TSCSyntaxKind.FunctionDeclaration; - case 263: - return TSCSyntaxKind.ClassDeclaration; - case 264: - return TSCSyntaxKind.InterfaceDeclaration; - case 265: - return TSCSyntaxKind.TypeAliasDeclaration; - case 266: - return TSCSyntaxKind.EnumDeclaration; - case 267: - return TSCSyntaxKind.ModuleDeclaration; - case 268: - return TSCSyntaxKind.ModuleBlock; - case 269: - return TSCSyntaxKind.CaseBlock; - case 270: - return TSCSyntaxKind.NamespaceExportDeclaration; - case 271: - return TSCSyntaxKind.ImportEqualsDeclaration; - case 272: - return TSCSyntaxKind.ImportDeclaration; - case 273: - return TSCSyntaxKind.ImportClause; - case 274: - return TSCSyntaxKind.NamespaceImport; - case 275: - return TSCSyntaxKind.NamedImports; - case 276: - return TSCSyntaxKind.ImportSpecifier; - case 277: - return TSCSyntaxKind.ExportAssignment; - case 278: - return TSCSyntaxKind.ExportDeclaration; - case 279: - return TSCSyntaxKind.NamedExports; - case 280: - return TSCSyntaxKind.NamespaceExport; - case 281: - return TSCSyntaxKind.ExportSpecifier; - case 282: - return TSCSyntaxKind.MissingDeclaration; - case 283: - return TSCSyntaxKind.ExternalModuleReference; - case 284: - return TSCSyntaxKind.JsxElement; - case 285: - return TSCSyntaxKind.JsxSelfClosingElement; - case 286: - return TSCSyntaxKind.JsxOpeningElement; - case 287: - return TSCSyntaxKind.JsxClosingElement; - case 288: - return TSCSyntaxKind.JsxFragment; - case 289: - return TSCSyntaxKind.JsxOpeningFragment; - case 290: - return TSCSyntaxKind.JsxClosingFragment; - case 291: - return TSCSyntaxKind.JsxAttribute; - case 292: - return TSCSyntaxKind.JsxAttributes; - case 293: - return TSCSyntaxKind.JsxSpreadAttribute; - case 294: - return TSCSyntaxKind.JsxExpression; - case 295: - return TSCSyntaxKind.JsxNamespacedName; - case 296: - return TSCSyntaxKind.CaseClause; - case 297: - return TSCSyntaxKind.DefaultClause; - case 298: - return TSCSyntaxKind.HeritageClause; - case 299: - return TSCSyntaxKind.CatchClause; - case 300: - return TSCSyntaxKind.AssertClause; - case 301: - return TSCSyntaxKind.AssertEntry; - case 302: - return TSCSyntaxKind.ImportTypeAssertionContainer; - case 303: - return TSCSyntaxKind.PropertyAssignment; - case 304: - return TSCSyntaxKind.ShorthandPropertyAssignment; - case 305: - return TSCSyntaxKind.SpreadAssignment; - case 306: - return TSCSyntaxKind.EnumMember; - case 307: - return TSCSyntaxKind.UnparsedPrologue; - case 308: - return TSCSyntaxKind.UnparsedPrepend; - case 309: - return TSCSyntaxKind.UnparsedText; - case 310: - return TSCSyntaxKind.UnparsedInternalText; - case 311: - return TSCSyntaxKind.UnparsedSyntheticReference; - case 312: - return TSCSyntaxKind.SourceFile; - case 313: - return TSCSyntaxKind.Bundle; - case 314: - return TSCSyntaxKind.UnparsedSource; - case 315: - return TSCSyntaxKind.InputFiles; - case 316: - return TSCSyntaxKind.JSDocTypeExpression; - case 317: - return TSCSyntaxKind.JSDocNameReference; - case 318: - return TSCSyntaxKind.JSDocMemberName; - case 319: - return TSCSyntaxKind.JSDocAllType; - case 320: - return TSCSyntaxKind.JSDocUnknownType; - case 321: - return TSCSyntaxKind.JSDocNullableType; - case 322: - return TSCSyntaxKind.JSDocNonNullableType; - case 323: - return TSCSyntaxKind.JSDocOptionalType; - case 324: - return TSCSyntaxKind.JSDocFunctionType; - case 325: - return TSCSyntaxKind.JSDocVariadicType; - case 326: - return TSCSyntaxKind.JSDocNamepathType; - case 327: - return TSCSyntaxKind.JSDoc; - case 328: - return TSCSyntaxKind.JSDocText; - case 329: - return TSCSyntaxKind.JSDocTypeLiteral; - case 330: - return TSCSyntaxKind.JSDocSignature; - case 331: - return TSCSyntaxKind.JSDocLink; - case 332: - return TSCSyntaxKind.JSDocLinkCode; - case 333: - return TSCSyntaxKind.JSDocLinkPlain; - case 334: - return TSCSyntaxKind.JSDocTag; - case 335: - return TSCSyntaxKind.JSDocAugmentsTag; - case 336: - return TSCSyntaxKind.JSDocImplementsTag; - case 337: - return TSCSyntaxKind.JSDocAuthorTag; - case 338: - return TSCSyntaxKind.JSDocDeprecatedTag; - case 339: - return TSCSyntaxKind.JSDocClassTag; - case 340: - return TSCSyntaxKind.JSDocPublicTag; - case 341: - return TSCSyntaxKind.JSDocPrivateTag; - case 342: - return TSCSyntaxKind.JSDocProtectedTag; - case 343: - return TSCSyntaxKind.JSDocReadonlyTag; - case 344: - return TSCSyntaxKind.JSDocOverrideTag; - case 345: - return TSCSyntaxKind.JSDocCallbackTag; - case 346: - return TSCSyntaxKind.JSDocOverloadTag; - case 347: - return TSCSyntaxKind.JSDocEnumTag; - case 348: - return TSCSyntaxKind.JSDocParameterTag; - case 349: - return TSCSyntaxKind.JSDocReturnTag; - case 350: - return TSCSyntaxKind.JSDocThisTag; - case 351: - return TSCSyntaxKind.JSDocTypeTag; - case 352: - return TSCSyntaxKind.JSDocTemplateTag; - case 353: - return TSCSyntaxKind.JSDocTypedefTag; - case 354: - return TSCSyntaxKind.JSDocSeeTag; - case 355: - return TSCSyntaxKind.JSDocPropertyTag; - case 356: - return TSCSyntaxKind.JSDocThrowsTag; - case 357: - return TSCSyntaxKind.JSDocSatisfiesTag; - case 358: - return TSCSyntaxKind.SyntaxList; - case 359: - return TSCSyntaxKind.NotEmittedStatement; - case 360: - return TSCSyntaxKind.PartiallyEmittedExpression; - case 361: - return TSCSyntaxKind.CommaListExpression; - case 362: - return TSCSyntaxKind.SyntheticReferenceExpression; - case 363: - return TSCSyntaxKind.Count; - default: - throw new IllegalArgumentException("unknown TSCSyntaxKind code: " + code); - } - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTokenFlag.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTokenFlag.java deleted file mode 100644 index b2d59b96..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTokenFlag.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ - -package org.openrewrite.javascript.internal.tsc.generated; - -// -// THIS FILE IS GENERATED. Do not modify it by hand. -// See `js/README.md` for instructions to regenerate this file. -// - -public enum TSCTokenFlag { - None(0), - PrecedingLineBreak(1), - PrecedingJSDocComment(2), - Unterminated(4), - ExtendedUnicodeEscape(8), - Scientific(16), - Octal(32), - HexSpecifier(64), - BinarySpecifier(128), - OctalSpecifier(256), - ContainsSeparator(512), - UnicodeEscape(1024), - ContainsInvalidEscape(2048), - HexEscape(4096), - ContainsLeadingZero(8192), - ContainsInvalidSeparator(16384), - BinaryOrOctalSpecifier(384), - WithSpecifier(448), - /** Also includes TemplateLiteralLikeFlags */ - StringLiteralFlags(7176), - NumericLiteralFlags(25584), - IsInvalid(26656); - - - public final int code; - - TSCTokenFlag(int code) { - this.code = code; - } - - public static TSCTokenFlag fromMaskExact(int code) { - switch (code) { - case 0: - return TSCTokenFlag.None; - case 1: - return TSCTokenFlag.PrecedingLineBreak; - case 2: - return TSCTokenFlag.PrecedingJSDocComment; - case 4: - return TSCTokenFlag.Unterminated; - case 8: - return TSCTokenFlag.ExtendedUnicodeEscape; - case 16: - return TSCTokenFlag.Scientific; - case 32: - return TSCTokenFlag.Octal; - case 64: - return TSCTokenFlag.HexSpecifier; - case 128: - return TSCTokenFlag.BinarySpecifier; - case 256: - return TSCTokenFlag.OctalSpecifier; - case 512: - return TSCTokenFlag.ContainsSeparator; - case 1024: - return TSCTokenFlag.UnicodeEscape; - case 2048: - return TSCTokenFlag.ContainsInvalidEscape; - case 4096: - return TSCTokenFlag.HexEscape; - case 8192: - return TSCTokenFlag.ContainsLeadingZero; - case 16384: - return TSCTokenFlag.ContainsInvalidSeparator; - case 384: - return TSCTokenFlag.BinaryOrOctalSpecifier; - case 448: - return TSCTokenFlag.WithSpecifier; - case 7176: - return TSCTokenFlag.StringLiteralFlags; - case 25584: - return TSCTokenFlag.NumericLiteralFlags; - case 26656: - return TSCTokenFlag.IsInvalid; - default: - throw new IllegalArgumentException("unknown TSCTokenFlag code: " + code); - } - } - - public boolean matches(int bitfield) { - return (bitfield & this.code) != 0; - } - - public static int union(TSCTokenFlag... args) { - int result = 0; - for (TSCTokenFlag arg : args) { - result = result | arg.code; - } - return result; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTypeFlag.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTypeFlag.java deleted file mode 100644 index 3764f753..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTypeFlag.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ - -package org.openrewrite.javascript.internal.tsc.generated; - -// -// THIS FILE IS GENERATED. Do not modify it by hand. -// See `js/README.md` for instructions to regenerate this file. -// - -public enum TSCTypeFlag { - Any(1), - Unknown(2), - String(4), - Number(8), - Boolean(16), - Enum(32), - BigInt(64), - StringLiteral(128), - NumberLiteral(256), - BooleanLiteral(512), - EnumLiteral(1024), - BigIntLiteral(2048), - ESSymbol(4096), - UniqueESSymbol(8192), - Void(16384), - Undefined(32768), - Null(65536), - Never(131072), - /** Also includes IncludesMissingType */ - TypeParameter(262144), - Object(524288), - Union(1048576), - Intersection(2097152), - /** Also includes IncludesNonWideningType */ - Index(4194304), - /** Also includes IncludesWildcard */ - IndexedAccess(8388608), - /** Also includes IncludesEmptyObject */ - Conditional(16777216), - /** Also includes IncludesInstantiable */ - Substitution(33554432), - NonPrimitive(67108864), - TemplateLiteral(134217728), - StringMapping(268435456), - AnyOrUnknown(3), - Nullable(98304), - Literal(2944), - Unit(109472), - Freshable(2976), - StringOrNumberLiteral(384), - StringOrNumberLiteralOrUnique(8576), - DefinitelyFalsy(117632), - PossiblyFalsy(117724), - Intrinsic(67359327), - StringLike(402653316), - NumberLike(296), - BigIntLike(2112), - BooleanLike(528), - EnumLike(1056), - ESSymbolLike(12288), - VoidLike(49152), - Primitive(402784252), - DefinitelyNonNullable(470302716), - DisjointDomains(469892092), - UnionOrIntersection(3145728), - StructuredType(3670016), - TypeVariable(8650752), - InstantiableNonPrimitive(58982400), - InstantiablePrimitive(406847488), - Instantiable(465829888), - StructuredOrInstantiable(469499904), - ObjectFlagsType(138117121), - Simplifiable(25165824), - Singleton(67358815), - Narrowable(536624127), - IncludesMask(473694207), - NotPrimitiveUnion(36323331); - - - public final int code; - - TSCTypeFlag(int code) { - this.code = code; - } - - public static TSCTypeFlag fromMaskExact(int code) { - switch (code) { - case 1: - return TSCTypeFlag.Any; - case 2: - return TSCTypeFlag.Unknown; - case 4: - return TSCTypeFlag.String; - case 8: - return TSCTypeFlag.Number; - case 16: - return TSCTypeFlag.Boolean; - case 32: - return TSCTypeFlag.Enum; - case 64: - return TSCTypeFlag.BigInt; - case 128: - return TSCTypeFlag.StringLiteral; - case 256: - return TSCTypeFlag.NumberLiteral; - case 512: - return TSCTypeFlag.BooleanLiteral; - case 1024: - return TSCTypeFlag.EnumLiteral; - case 2048: - return TSCTypeFlag.BigIntLiteral; - case 4096: - return TSCTypeFlag.ESSymbol; - case 8192: - return TSCTypeFlag.UniqueESSymbol; - case 16384: - return TSCTypeFlag.Void; - case 32768: - return TSCTypeFlag.Undefined; - case 65536: - return TSCTypeFlag.Null; - case 131072: - return TSCTypeFlag.Never; - case 262144: - return TSCTypeFlag.TypeParameter; - case 524288: - return TSCTypeFlag.Object; - case 1048576: - return TSCTypeFlag.Union; - case 2097152: - return TSCTypeFlag.Intersection; - case 4194304: - return TSCTypeFlag.Index; - case 8388608: - return TSCTypeFlag.IndexedAccess; - case 16777216: - return TSCTypeFlag.Conditional; - case 33554432: - return TSCTypeFlag.Substitution; - case 67108864: - return TSCTypeFlag.NonPrimitive; - case 134217728: - return TSCTypeFlag.TemplateLiteral; - case 268435456: - return TSCTypeFlag.StringMapping; - case 3: - return TSCTypeFlag.AnyOrUnknown; - case 98304: - return TSCTypeFlag.Nullable; - case 2944: - return TSCTypeFlag.Literal; - case 109472: - return TSCTypeFlag.Unit; - case 2976: - return TSCTypeFlag.Freshable; - case 384: - return TSCTypeFlag.StringOrNumberLiteral; - case 8576: - return TSCTypeFlag.StringOrNumberLiteralOrUnique; - case 117632: - return TSCTypeFlag.DefinitelyFalsy; - case 117724: - return TSCTypeFlag.PossiblyFalsy; - case 67359327: - return TSCTypeFlag.Intrinsic; - case 402653316: - return TSCTypeFlag.StringLike; - case 296: - return TSCTypeFlag.NumberLike; - case 2112: - return TSCTypeFlag.BigIntLike; - case 528: - return TSCTypeFlag.BooleanLike; - case 1056: - return TSCTypeFlag.EnumLike; - case 12288: - return TSCTypeFlag.ESSymbolLike; - case 49152: - return TSCTypeFlag.VoidLike; - case 402784252: - return TSCTypeFlag.Primitive; - case 470302716: - return TSCTypeFlag.DefinitelyNonNullable; - case 469892092: - return TSCTypeFlag.DisjointDomains; - case 3145728: - return TSCTypeFlag.UnionOrIntersection; - case 3670016: - return TSCTypeFlag.StructuredType; - case 8650752: - return TSCTypeFlag.TypeVariable; - case 58982400: - return TSCTypeFlag.InstantiableNonPrimitive; - case 406847488: - return TSCTypeFlag.InstantiablePrimitive; - case 465829888: - return TSCTypeFlag.Instantiable; - case 469499904: - return TSCTypeFlag.StructuredOrInstantiable; - case 138117121: - return TSCTypeFlag.ObjectFlagsType; - case 25165824: - return TSCTypeFlag.Simplifiable; - case 67358815: - return TSCTypeFlag.Singleton; - case 536624127: - return TSCTypeFlag.Narrowable; - case 473694207: - return TSCTypeFlag.IncludesMask; - case 36323331: - return TSCTypeFlag.NotPrimitiveUnion; - default: - throw new IllegalArgumentException("unknown TSCTypeFlag code: " + code); - } - } - - public boolean matches(int bitfield) { - return (bitfield & this.code) != 0; - } - - public static int union(TSCTypeFlag... args) { - int result = 0; - for (TSCTypeFlag arg : args) { - result = result | arg.code; - } - return result; - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTypePredicateKind.java b/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTypePredicateKind.java deleted file mode 100644 index efdcf3d5..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/generated/TSCTypePredicateKind.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ - -package org.openrewrite.javascript.internal.tsc.generated; - -// -// THIS FILE IS GENERATED. Do not modify it by hand. -// See `js/README.md` for instructions to regenerate this file. -// - -public enum TSCTypePredicateKind { - This(0), - Identifier(1), - AssertsThis(2), - AssertsIdentifier(3); - - - public final int code; - - TSCTypePredicateKind(int code) { - this.code = code; - } - - public static TSCTypePredicateKind fromCode(int code) { - switch (code) { - case 0: - return TSCTypePredicateKind.This; - case 1: - return TSCTypePredicateKind.Identifier; - case 2: - return TSCTypePredicateKind.AssertsThis; - case 3: - return TSCTypePredicateKind.AssertsIdentifier; - default: - throw new IllegalArgumentException("unknown TSCTypePredicateKind code: " + code); - } - } -} diff --git a/src/main/java/org/openrewrite/javascript/internal/tsc/package-info.java b/src/main/java/org/openrewrite/javascript/internal/tsc/package-info.java deleted file mode 100644 index 1e3669d3..00000000 --- a/src/main/java/org/openrewrite/javascript/internal/tsc/package-info.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright 2022 the original author or authors. - *

- * 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 - *

- * https://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. - */ -@NullMarked -@NonNullFields -package org.openrewrite.javascript.internal.tsc; - -import org.jspecify.annotations.NullMarked; -import org.openrewrite.internal.lang.NonNullFields; diff --git a/src/test/java/org/openrewrite/javascript/TypeScriptSignatureBuilderTest.java b/src/test/java/org/openrewrite/javascript/TypeScriptSignatureBuilderTest.java deleted file mode 100644 index f113b44c..00000000 --- a/src/test/java/org/openrewrite/javascript/TypeScriptSignatureBuilderTest.java +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript; - -import org.intellij.lang.annotations.Language; -import org.junit.jupiter.api.AfterAll; -import org.junit.jupiter.api.Test; -import org.openrewrite.internal.StringUtils; -import org.openrewrite.javascript.internal.tsc.TSCNode; -import org.openrewrite.javascript.internal.tsc.TSCRuntime; -import org.openrewrite.javascript.internal.tsc.generated.TSCSyntaxKind; - -import java.util.List; -import java.util.Objects; - -import static org.assertj.core.api.Assertions.assertThat; - -class TypeScriptSignatureBuilderTest { - - @Language("typescript") - private static final String goat = StringUtils.readFully(TypeScriptSignatureBuilderTest.class.getResourceAsStream("/TypeScriptTypeGoat.ts")); - - private static final TSCRuntime runtime = TSCRuntime.init(); - - @AfterAll - static void afterAll() { - runtime.close(); - } - - TypeScriptSignatureBuilder signatureBuilder() { - return new TypeScriptSignatureBuilder(); - } - - @Test - void constructor() { - runtime.parseSingleSource( - goat, - (node, context) -> assertThat(constructorSignature(node)) - .isEqualTo("file.ts.TypeScriptTypeGoat{name=,return=file.ts.TypeScriptTypeGoat,parameters=[]}") - ); - } - - @Test - void parameterizedField() { - runtime.parseSingleSource( - goat, - (node, context) -> assertThat(fieldSignature(node, "parameterizedField")) - .isEqualTo("file.ts.TypeScriptTypeGoat{name=parameterizedField,type=file.ts.PT}") - ); - } - - @Test - void array() { - assertMethodSignature("array", - "file.ts.A[]", - "file.ts.TypeScriptTypeGoat{name=array,return=void,parameters=[file.ts.A[]]}"); - } - - @Test - void multidimensionalArray() { - assertMethodSignature("multidimensionalArray", - "file.ts.A[][]", - "file.ts.TypeScriptTypeGoat{name=multidimensionalArray,return=void,parameters=[file.ts.A[][]]}"); - } - - @Test - void classSignature() { - assertMethodSignature("clazz", - "file.ts.A", - "file.ts.TypeScriptTypeGoat{name=clazz,return=void,parameters=[file.ts.A]}"); - } - - @Test - void primitive() { - assertMethodSignature("primitive", - "number", - "file.ts.TypeScriptTypeGoat{name=primitive,return=void,parameters=[number]}"); - } - - @Test - void parameterized() { - assertMethodSignature("parameterized", - "file.ts.PT", - "file.ts.TypeScriptTypeGoat{name=parameterized,return=file.ts.PT,parameters=[file.ts.PT]}"); - } - - @Test - void parameterizedRecursive() { - assertMethodSignature("parameterizedRecursive", - "file.ts.PT>", - "file.ts.TypeScriptTypeGoat{name=parameterizedRecursive,return=file.ts.PT>,parameters=[file.ts.PT>]}"); - } - - @Test - void generic() { - assertMethodSignature("generic", - "file.ts.PT", - "file.ts.TypeScriptTypeGoat{name=generic,return=file.ts.PT,parameters=[file.ts.PT]}"); - } - - @Test - void genericUnbounded() { - assertMethodSignature("genericUnbounded", - "file.ts.PT", - "file.ts.TypeScriptTypeGoat{name=genericUnbounded,return=file.ts.PT,parameters=[file.ts.PT]}"); - } - - @Test - void mergedInterfaceGeneric() { - assertMethodSignature("mergedGeneric", - "file.ts.PT", - "file.ts.TypeScriptTypeGoat{name=mergedGeneric,return=file.ts.PT,parameters=[file.ts.PT]}"); - } - - @Test - void genericT() { - assertMethodSignature("genericT", - "Generic{T}", - "file.ts.TypeScriptTypeGoat{name=genericT,return=Generic{T},parameters=[Generic{T}]}"); - } - - @Test - void genericRecursiveInClassDefinition() { - runtime.parseSingleSource( - goat, - (node, context) -> assertThat(lastClassTypeParameterSignature(node)) - .isEqualTo("Generic{S extends file.ts.PT & file.ts.A}") - ); - } - - @Test - void genericRecursiveInMethodDeclaration() { - assertMethodSignature("genericRecursive", - "file.ts.TypeScriptTypeGoat}[], unknown>", - "file.ts.TypeScriptTypeGoat{name=genericRecursive,return=file.ts.TypeScriptTypeGoat}[], unknown>,parameters=[file.ts.TypeScriptTypeGoat}[], unknown>]}"); - } - - @Test - void genericIntersection() { - assertMethodSignature("genericIntersection", - "Generic{U extends type.analysis.Anonymous & file.ts.PT & file.ts.C}", - "file.ts.TypeScriptTypeGoat{name=genericIntersection,return=Generic{U extends type.analysis.Anonymous & file.ts.PT & file.ts.C},parameters=[Generic{U extends type.analysis.Anonymous & file.ts.PT & file.ts.C}]}"); - } - - @Test - void recursiveIntersection() { - assertMethodSignature("recursiveIntersection", - "Generic{U extends file.ts.Extension & file.ts.Intersection}", - "file.ts.TypeScriptTypeGoat{name=recursiveIntersection,return=void,parameters=[Generic{U extends file.ts.Extension & file.ts.Intersection}]}"); - } - - @Test - void merged() { - assertMethodSignature("merged", - "type.analysis.MergedInterface", - "file.ts.TypeScriptTypeGoat{name=merged,return=void,parameters=[type.analysis.MergedInterface]}"); - } - - @Test - void unionField() { - runtime.parseSingleSource( - goat, - (node, context) -> assertThat(fieldSignature(node, "unionField")) - .isEqualTo("file.ts.TypeScriptTypeGoat{name=unionField,type=type.analysis.Union}") - ); - } - - private String fieldSignature(TSCNode node, String field) { - return signatureBuilder().variableSignature(node.getNodeListProperty("statements").stream() - .filter(it -> it.syntaxKind() == TSCSyntaxKind.ClassDeclaration && it.hasProperty("members")) - .flatMap(it -> it.getNodeListProperty("members").stream()) - .filter(it -> it.syntaxKind() == TSCSyntaxKind.PropertyDeclaration && it.hasProperty("name") && field.equals(it.getNodeProperty("name").getText())) - .findFirst() - .orElseThrow()); - } - - String methodSignature(TSCNode node, String methodName) { - return signatureBuilder().methodSignature(node.getNodeListProperty("statements").stream() - .filter(it -> it.syntaxKind() == TSCSyntaxKind.ClassDeclaration && it.hasProperty("members")) - .flatMap(it -> it.getNodeListProperty("members").stream()) - .filter(it -> it.syntaxKind() == TSCSyntaxKind.MethodDeclaration && it.hasProperty("name")) - .filter(it -> it.getNodeProperty("name").getText().equals(methodName)) - .findFirst() - .orElseThrow()); - } - - private String constructorSignature(TSCNode node) { - return signatureBuilder().methodSignature(node.getNodeListProperty("statements").stream() - .filter(it -> it.syntaxKind() == TSCSyntaxKind.ClassDeclaration && it.hasProperty("members")) - .flatMap(it -> it.getNodeListProperty("members").stream()) - .filter(it -> it.syntaxKind() == TSCSyntaxKind.Constructor) - .findFirst() - .orElseThrow()); - } - - private String firstMethodParameterSignature(TSCNode node, String methodName) { - return Objects.requireNonNull(signatureBuilder().signature(node.getNodeListProperty("statements").stream() - .filter(it -> it.syntaxKind() == TSCSyntaxKind.ClassDeclaration && it.hasProperty("members")) - .flatMap(it -> it.getNodeListProperty("members").stream()) - .filter(it -> it.syntaxKind() == TSCSyntaxKind.MethodDeclaration && it.hasProperty("name")) - .filter(it -> it.getNodeProperty("name").getText().equals(methodName)) - .findFirst() - .orElseThrow() - .getNodeListProperty("parameters") - .get(0) - .getNodeProperty("type"))); - } - - String lastClassTypeParameterSignature(TSCNode node) { - List typeParams = node.getNodeListProperty("statements").get(0).getNodeListProperty("typeParameters"); - return Objects.requireNonNull(signatureBuilder().signature(typeParams.get(typeParams.size() - 1))); - } - - private void assertMethodSignature(String target, String expectedMethodParameterSignature, String expectedMethodSignature) { - runtime.parseSingleSource( - goat, - (node, context) -> { - assertThat(firstMethodParameterSignature(node, target)) - .isEqualTo(expectedMethodParameterSignature); - assertThat(methodSignature(node, target)) - .isEqualTo(expectedMethodSignature); - } - ); - } -} diff --git a/src/test/java/org/openrewrite/javascript/TypeScriptTypeMappingTest.java b/src/test/java/org/openrewrite/javascript/TypeScriptTypeMappingTest.java deleted file mode 100644 index 1acf51a2..00000000 --- a/src/test/java/org/openrewrite/javascript/TypeScriptTypeMappingTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript; - -import org.junit.jupiter.api.Test; -import org.junitpioneer.jupiter.ExpectedToFail; -import org.openrewrite.InMemoryExecutionContext; -import org.openrewrite.internal.StringUtils; -import org.openrewrite.java.tree.J; -import org.openrewrite.java.tree.JavaType; -import org.openrewrite.java.tree.TypeUtils; -import org.openrewrite.javascript.tree.JS; - -import java.util.List; -import java.util.stream.Collectors; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.openrewrite.java.tree.JavaType.GenericTypeVariable.Variance.COVARIANT; -import static org.openrewrite.java.tree.JavaType.GenericTypeVariable.Variance.INVARIANT; - -@SuppressWarnings({"DataFlowIssue", "SimplifyStreamApiCallChains", "SameParameterValue"}) -class TypeScriptTypeMappingTest { - private static final String goat = StringUtils.readFully(TypeScriptSignatureBuilderTest.class.getResourceAsStream("/TypeScriptTypeGoat.ts")); - private static final JS.CompilationUnit cu = JavaScriptParser.builder().build() - .parse(new InMemoryExecutionContext(), goat) - .map(s -> (JS.CompilationUnit) s) - .collect(Collectors.toList()) - .get(0); - private static final List classes = cu - .getStatements() - .stream() - .filter(it -> it instanceof J.ClassDeclaration) - .map(it -> (J.ClassDeclaration) it) - .map(J.ClassDeclaration::getType) - .collect(Collectors.toList()); - private static final JavaType.Parameterized goatType = TypeUtils.asParameterized(classes.get(0)); - - // TODO: add methods to access methods via name. - // Add methods to access types as types are added. - - private String getSourcePath() { - return cu.getSourcePath().toString().replace("/", "."); - } - - @Test - void className() { - JavaType.FullyQualified clazz = TypeUtils.asFullyQualified(this.firstMethodParameter("clazz")); - assertThat(clazz).isNotNull(); - assertThat(clazz.getFullyQualifiedName()).isEqualTo(getSourcePath() + ".A"); - } - - @Test - void constructor() { - JavaType.Method ctor = methodType(""); - assertThat(ctor.getDeclaringType().getFullyQualifiedName()).isEqualTo("%s.TypeScriptTypeGoat", getSourcePath()); - } - - @Test - void parameterizedField() { - JavaType.Variable type = firstField("parameterizedField"); - assertThat(type.getType().toString()).isEqualTo("%s.PT", getSourcePath()); - } - - @Test - void unionField() { - JavaType.Variable type = firstField("unionField"); - assertThat(type.getType().toString()).isEqualTo("type.analysis.Union", getSourcePath()); - } - - @ExpectedToFail - @Test - void extendsJavaTypeGoat() { - JavaType.Variable type = firstField("ExtendsTypeScriptTypeGoat"); - assertThat(type.getType().toString()).isEqualTo("implement me", getSourcePath()); - } - - @Test - void parameterized() { - String sourcePath = getSourcePath(); - JavaType.Parameterized parameterized = (JavaType.Parameterized) firstMethodParameter("parameterized"); - assertThat(parameterized.getType().getFullyQualifiedName()).isEqualTo("%s.PT", sourcePath); - assertThat(TypeUtils.asFullyQualified(parameterized.getTypeParameters().get(0)).getFullyQualifiedName()).isEqualTo("%s.A", sourcePath); - } - - @Test - void parameterizedRecursive() { - String sourcePath = getSourcePath(); - JavaType.Parameterized parameterized = (JavaType.Parameterized) firstMethodParameter("parameterizedRecursive"); - assertThat(parameterized.getType().getFullyQualifiedName()).isEqualTo("%s.PT", sourcePath); - assertThat(TypeUtils.asFullyQualified(parameterized.getTypeParameters().get(0)).getFullyQualifiedName()).isEqualTo("%s.PT", sourcePath); - } - - @Test - void primitive() { - JavaType.Class kotlinBasicType = (JavaType.Class) firstMethodParameter("primitive"); - assertThat(kotlinBasicType.getFullyQualifiedName()).isEqualTo("number"); - } - - @Test - void generic() { - JavaType.GenericTypeVariable generic = (JavaType.GenericTypeVariable) TypeUtils.asParameterized(firstMethodParameter("generic")).getTypeParameters().get(0); - assertThat(generic.getName()).isEqualTo("T"); - assertThat(generic.getVariance()).isEqualTo(COVARIANT); - assertThat(TypeUtils.asFullyQualified(generic.getBounds().get(0)).getFullyQualifiedName()).isEqualTo("%s.A", getSourcePath()); - } - - @Test - void genericT() { - JavaType.GenericTypeVariable generic = (JavaType.GenericTypeVariable) firstMethodParameter("genericT"); - assertThat(generic.getName()).isEqualTo("T"); - assertThat(generic.getVariance()).isEqualTo(INVARIANT); - } - - @Test - void genericUnbounded() { - JavaType.GenericTypeVariable generic = (JavaType.GenericTypeVariable) TypeUtils.asParameterized(firstMethodParameter("genericUnbounded")).getTypeParameters().get(0); - assertThat(generic.getName()).isEqualTo("U"); - assertThat(generic.getVariance()).isEqualTo(INVARIANT); - } - - @Test - void genericMultipleBounds() { - String sourcePath = getSourcePath(); - List typeParameters = goatType.getTypeParameters(); - JavaType.GenericTypeVariable generic = (JavaType.GenericTypeVariable) typeParameters.get(typeParameters.size() - 1); - assertThat(generic.getName()).isEqualTo("S"); - assertThat(generic.getVariance()).isEqualTo(COVARIANT); - assertThat(TypeUtils.asFullyQualified(generic.getBounds().get(0)).getFullyQualifiedName()).isEqualTo("%s.PT", sourcePath); - assertThat(TypeUtils.asFullyQualified(generic.getBounds().get(1)).getFullyQualifiedName()).isEqualTo("%s.A", sourcePath); - } - - @Test - void genericRecursive() { - String sourcePath = getSourcePath(); - JavaType.Parameterized param = (JavaType.Parameterized) firstMethodParameter("genericRecursive"); - assertThat(param.toString()).isEqualTo("%s.TypeScriptTypeGoat}[], unknown>", sourcePath, sourcePath); - JavaType.Array.GenericTypeVariable generic = (JavaType.GenericTypeVariable) ((JavaType.Array) param.getTypeParameters().get(0)).getElemType(); - assertThat(generic.getName()).isEqualTo("U"); - assertThat(generic.getVariance()).isEqualTo(COVARIANT); - assertThat(TypeUtils.asParameterized(generic.getBounds().get(0))).isNotNull(); - - JavaType.GenericTypeVariable elemType = (JavaType.GenericTypeVariable) TypeUtils.asParameterized(generic.getBounds().get(0)).getTypeParameters().get(0); - assertThat(elemType.getName()).isEqualTo("U"); - assertThat(elemType.getVariance()).isEqualTo(COVARIANT); - assertThat(elemType.getBounds()).hasSize(1); - - JavaType.GenericTypeVariable gtv = (JavaType.GenericTypeVariable) ((JavaType.Parameterized) elemType.getBounds().get(0)).getTypeParameters().get(0); - assertThat(gtv.toString()).isEqualTo("Generic{U extends %s.TypeScriptTypeGoat}", sourcePath); - } - - @Test - void inheritedTypeScriptTypeGoat() { - String sourcePath = getSourcePath(); - JavaType.Parameterized clazz = (JavaType.Parameterized) firstMethodParameter("inheritedTypeScriptTypeGoat"); - assertThat(clazz.getTypeParameters().get(0).toString()).isEqualTo("Generic{T}"); - assertThat(clazz.getTypeParameters().get(1).toString()).isEqualTo("Generic{U extends %s.PT & %s.C}", sourcePath, sourcePath); - assertThat(clazz.toString()).isEqualTo("%s.InheritedTypeScriptTypeGoat & %s.C}>", sourcePath, sourcePath, sourcePath); - } - - @Test - void genericIntersectionType() { - String sourcePath = getSourcePath(); - JavaType.GenericTypeVariable clazz = (JavaType.GenericTypeVariable) firstMethodParameter("genericIntersection"); - assertThat(clazz.getBounds().get(0).toString()).isEqualTo("type.analysis.Anonymous"); - assertThat(clazz.getBounds().get(1).toString()).isEqualTo("%s.PT", sourcePath, sourcePath, sourcePath); - assertThat(clazz.getBounds().get(2).toString()).isEqualTo("%s.C", sourcePath); - assertThat(clazz.toString()).isEqualTo("Generic{U extends type.analysis.Anonymous & %s.PT & %s.C}", sourcePath, sourcePath); - } - - @Test - void enumTypeA() { - String sourcePath = getSourcePath(); - JavaType.Class clazz = (JavaType.Class) firstClassType("EnumTypeA"); - - List enumConstants = clazz.getMembers().stream() - .filter(m -> m instanceof JavaType.Variable) - .collect(Collectors.toList()); - assertThat(enumConstants).hasSize(2); - assertThat(enumConstants.get(0).getName()).isEqualTo("FOO"); - assertThat(TypeUtils.asFullyQualified(enumConstants.get(0).getOwner()).getFullyQualifiedName()).isEqualTo("%s.EnumTypeA", sourcePath); - assertThat(TypeUtils.asFullyQualified(enumConstants.get(0).getType()).getFullyQualifiedName()).isEqualTo("%s.EnumTypeA", sourcePath); - assertThat(enumConstants.get(1).getName()).isEqualTo("BAR"); - assertThat(TypeUtils.asFullyQualified(enumConstants.get(1).getOwner()).getFullyQualifiedName()).isEqualTo("%s.EnumTypeA", sourcePath); - assertThat(TypeUtils.asFullyQualified(enumConstants.get(1).getType()).getFullyQualifiedName()).isEqualTo("%s.EnumTypeA", sourcePath); - } - - @Test - void recursiveIntersection() { - String sourcePath = getSourcePath(); - JavaType.GenericTypeVariable clazz = TypeUtils.asGeneric(firstMethodParameter("recursiveIntersection")); - assertThat(clazz.toString()).isEqualTo("Generic{U extends %s.Extension & %s.Intersection}", sourcePath, sourcePath); - } - - JavaType.Method methodType(String methodName) { - JavaType.Method type = goatType.getMethods().stream() - .filter(m -> m.getName().equals(methodName)) - .findFirst() - .orElseThrow(() -> new IllegalStateException("Expected to find matching method named " + methodName)); - assertThat(type.getDeclaringType().toString()).isEqualTo("%s.TypeScriptTypeGoat", getSourcePath()); - return type; - } - - JavaType firstMethodParameter(String methodName) { - return methodType(methodName).getParameterTypes().get(0); - } - - JavaType.Variable firstField(String fieldName) { - JavaType.Variable type = goatType.getMembers().stream() - .filter(m -> m.getName().equals(fieldName)) - .findFirst() - .orElseThrow(() -> new IllegalStateException("Expected to find matching member named " + fieldName)); - assertThat(type.getOwner().toString()).isEqualTo("%s.TypeScriptTypeGoat", getSourcePath()); - return type; - } - - JavaType firstClassType(String className) { - return classes.stream().filter(it -> className.equals(it.getClassName())).findFirst().orElseThrow(); - } -} diff --git a/src/test/java/org/openrewrite/javascript/internal/V8InteropTests.java b/src/test/java/org/openrewrite/javascript/internal/V8InteropTests.java deleted file mode 100644 index ffc70ef1..00000000 --- a/src/test/java/org/openrewrite/javascript/internal/V8InteropTests.java +++ /dev/null @@ -1,438 +0,0 @@ -/* - * Copyright 2023 the original author or authors. - *

- * 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 - *

- * https://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. - */ -package org.openrewrite.javascript.internal; - -import org.intellij.lang.annotations.Language; -import org.junit.jupiter.api.Test; -import org.openrewrite.javascript.internal.tsc.*; -import org.openrewrite.javascript.internal.tsc.generated.TSCObjectFlag; -import org.openrewrite.javascript.internal.tsc.generated.TSCTypeFlag; - -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.*; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiConsumer; -import java.util.function.Function; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.fail; -import static org.junit.jupiter.api.Assertions.*; - -public class V8InteropTests { - - private void parseSingleSource( - @Language("typescript") String source, - BiConsumer callback - ) { - parseSingleSource(source, "test.ts", runtime -> runtime, callback); - } - - private void parseSingleSource( - @Language("typescript") String source, - Function configureRuntime, - BiConsumer callback - ) { - parseSingleSource(source, "test.ts", configureRuntime, callback); - } - - private void parseSingleSource( - @Language("typescript") String source, - String filename, - BiConsumer callback - ) { - parseSingleSource(source, filename, runtime -> runtime, callback); - } - - private void parseSingleSource( - @Language("typescript") String source, - String filename, - Function configureRuntime, - BiConsumer callback - ) { - AtomicBoolean ran = new AtomicBoolean(); - try (TSCRuntime runtime = configureRuntime.apply(TSCRuntime.init())) { - runtime.parseSingleSource(source, filename, (root, ctx) -> { - callback.accept(root, ctx); - ran.set(true); - }); - } - if (!ran.get()) { - fail("Single-source parsing did not complete normally during the test."); - } - } - - @Test - public void testTypeIdentity() { - parseSingleSource("function foo() {}", (root, ctx) -> - root.getAllChildNodes().forEach(child -> { - TSCType first = child.getTypeForNode(); - TSCType second = child.getTypeForNode(); - assertSame(first, second); - })); - } - - @Test - public void testNodeIdentity() { - parseSingleSource("function foo() {}", (root, ctx) -> { - List first = root.getAllChildNodes(); - List second = root.getAllChildNodes(); - for (int i = 0; i < first.size(); i++) { - assertSame(first.get(i), second.get(i)); - } - }); - } - - @Test - public void testTypeIdentityInDifferentLocations() { - parseSingleSource("class Foo{} const x = new Foo(); const y = new Foo();", (root, ctx) -> { - TSCType xType = root.firstNodeWithText("x").getTypeForNode(); - TSCType yType = root.firstNodeWithText("y").getTypeForNode(); - assertSame(xType, yType); - }); - } - - @Test - public void testTypeIdentityInDifferentFiles() { - try (TSCRuntime runtime = TSCRuntime.init()) { - Map sources = new HashMap<>(); - sources.put(Paths.get("a.ts"), "export class Foo {}"); - sources.put(Paths.get("b.ts"), "import {Foo} from './a'; const x = new Foo();"); - sources.put(Paths.get("c.ts"), "import {Foo} from './a'; const x = new Foo();"); - AtomicReference inOtherFile = new AtomicReference<>(); - AtomicBoolean checked = new AtomicBoolean(); - runtime.parseSourceTexts(sources, (root, ctx) -> { - if (ctx.getRelativeSourcePath().toString().equals("a.ts")) { - return; - } - TSCType type = root.firstNodeWithText("x").getTypeForNode(); - if (inOtherFile.get() == null) { - inOtherFile.set(type); - } else { - checked.set(true); - assertSame(inOtherFile.get(), type); - } - }); - assertThat(checked.get()).isTrue(); - } - } - - @Test - public void testNumberFlags() { - parseSingleSource("const x: number = 2;", (root, ctx) -> { - TSCNode name = root.firstNodeWithText("x"); - TSCType type = Objects.requireNonNull(name.getTypeForNode()); - assertNotNull(type); - assertTrue(type.hasExactTypeFlag(TSCTypeFlag.Number)); - }); - } - - @Test - public void testClassTypeFlags() { - parseSingleSource("class Cls{} const x: Cls = new Cls();", (root, ctx) -> { - TSCNode name = root.firstNodeWithText("x"); - TSCType type = Objects.requireNonNull(name.getTypeForNode()); - assertTrue(type.hasExactTypeFlag(TSCTypeFlag.Object)); - assertTrue(type.hasObjectFlag(TSCObjectFlag.Class)); - }); - } - - @Test - public void testInterfaceTypeWrapper() { - parseSingleSource("class Cls{y: string} const x: Cls = new Cls();", (root, ctx) -> { - TSCNode name = root.firstNodeWithText("x"); - TSCType type = Objects.requireNonNull(name.getTypeForNode()); - - TSCType.InterfaceType wrapper = Objects.requireNonNull(type.asInterfaceType()); - assertNotNull(wrapper.getThisType()); - }); - } - - @Test - public void compilerOptionsHandleJsExtension() { - parseSingleSource("const x = 3;", "file.js", (root, ctx) -> { - }); - } - - @Test - public void nodeReturnsSourceFile() { - parseSingleSource("const x = 3;", "file.js", (root, ctx) -> { - TSCNode ident = root.firstNodeWithText("x"); - TSCNode.SourceFile sourceFile = ident.getSourceFile(); - assertEquals("/app/file.js", sourceFile.getFileName()); - assertEquals("/app/file.js", sourceFile.getPath()); - }); - } - - @Test - public void nodeHasParent() { - parseSingleSource("const x = 3;", "file.js", (root, ctx) -> { - TSCNode ident = root.firstNodeWithText("x"); - TSCNode parent = ident.getParent().getParent().getParent().getParent(); - assertSame(root, parent); - }); - } - - @Test - public void testGlobalFunctions() { - parseSingleSource("class A {private foo: string;}", (root, ctx) -> { - TSCNode stmt = root.firstNodeWithText("private foo: string;"); - List modifiers = stmt.getProgramContext().getTypeScriptGlobals().getModifiers(stmt); - assertNotNull(modifiers); - assertEquals(1, modifiers.size()); - }); - } - - @Test - public void testNodeConstructorName() { - parseSingleSource("const x = 3;", (root, ctx) -> { - TSCNode ident = root.firstNodeWithText("x"); - assertEquals("IdentifierObject", ident.getConstructorName()); - }); - } - - @Test - public void testNodeConstructorKind() { - parseSingleSource("const x = 3;", (root, ctx) -> { - TSCInstanceOfChecks instanceOfChecks = ctx.getProgramContext().getInstanceOfChecks(); - - assertEquals( - TSCInstanceOfChecks.ConstructorKind.SourceFile, - instanceOfChecks.identifyConstructorKind(root.getBackingV8Object()) - ); - - TSCNode ident = root.firstNodeWithText("x"); - assertEquals( - TSCInstanceOfChecks.ConstructorKind.Identifier, - instanceOfChecks.identifyConstructorKind(ident.getBackingV8Object()) - ); - - TSCNode stmt = root.firstNodeWithText("const x = 3;"); - assertEquals( - TSCInstanceOfChecks.ConstructorKind.Node, - instanceOfChecks.identifyConstructorKind(stmt.getBackingV8Object()) - ); - }); - } - - @Test - public void testTypeNodeType() { - parseSingleSource( - """ - class Foo {} - - function test(x: Foo) { - } - """, - (root, ctx) -> { - TSCNode Foo = root.firstNodeWithText("class Foo {}"); - TSCType FooType = Foo.getTypeForNode(); - - TSCNode x = root.firstNodeWithText("x: Foo"); - TSCNode.TypeNode xTypeNode = x.getTypeNodeProperty("type"); - TSCType xType = xTypeNode.getTypeFromTypeNode(); - - assertSame(FooType, xType); - } - ); - } - - @Test - public void testGenericTypeBound() { - parseSingleSource( - """ - class A {} - """, - (root, ctx) -> { - TSCNode classDef = root.firstNodeContaining("class A"); - TSCType classType = classDef.getTypeForNode(); - assertNotNull(classType); - - TSCType.InterfaceType asInterfaceType = classType.assertInterfaceType(); - List typeParams = asInterfaceType.getTypeParameters(); - assertNotNull(typeParams); - assertEquals(1, typeParams.size()); - - TSCType typeParam = typeParams.get(0); - assertNotNull(typeParam); - - TSCType typeParamConstraint = typeParam.getConstraint(); - assertNotNull(typeParamConstraint); - - TSCType globalStringType = ctx.getProgramContext().getTypeChecker().getStringType(); - assertSame(globalStringType, typeParamConstraint); - } - ); - } - - @Test - public void testGenericTypeBoundWithLocalReference() { - parseSingleSource( - """ - class A> {} - interface B { - foo(): [U1, U2, U3]; - } - """, - (root, ctx) -> { - TSCType classA = root.firstNodeContaining("class A").getTypeForNode(); - assertNotNull(classA); - - TSCType interfaceB = root.firstNodeContaining("interface B").getTypeForNode(); - assertNotNull(interfaceB); - - TSCType.InterfaceType asInterfaceType = classA.assertInterfaceType(); - List typeParams = asInterfaceType.getTypeParameters(); - assertNotNull(typeParams); - assertEquals(2, typeParams.size()); - - TSCType typeParam1 = typeParams.get(0); - TSCType typeParam2 = typeParams.get(1); - assertNotNull(typeParam1); - assertNotNull(typeParam2); - - TSCType typeParam1Constraint = typeParam1.getConstraint(); - TSCType typeParam2Constraint = typeParam2.getConstraint(); - assertNull(typeParam1Constraint); - assertNotNull(typeParam2Constraint); - - TSCType globalStringType = ctx.getProgramContext().getTypeChecker().getStringType(); - TSCType globalNumberType = ctx.getProgramContext().getTypeChecker().getNumberType(); - - // The constraint type args are those passed to `B` in `T2 extends B` - List constraintTypeArgs = typeParam2Constraint.assertTypeReference().getTypeArguments(); - assertEquals(3, constraintTypeArgs.size()); - // Used type variables, i.e. `string, T1, number` - assertSame(globalStringType, constraintTypeArgs.get(0)); - assertSame(typeParam1, constraintTypeArgs.get(1)); - assertSame(globalNumberType, constraintTypeArgs.get(2)); - } - ); - } - - @Test - public void testLibSupport() { - // Explicitly turn libs off --> `string` type should be empty - parseSingleSource( - "const x: string = '';", - runtime -> runtime.setCompilerOptionOverride("noLib", true), - (root, ctx) -> { - TSCNode x = root.firstNodeContaining("x"); - TSCType xType = x.getTypeForNode(); - assertNotNull(xType); - assertEquals(0, xType.getTypeProperties().size()); - } - ); - - // Explicitly turn libs on --> `string` type should have properties - parseSingleSource( - "const x: string = '';", - runtime -> runtime.setCompilerOptionOverride("lib", Collections.singletonList("ES2020")), - (root, ctx) -> { - TSCNode x = root.firstNodeContaining("x"); - TSCType xType = x.getTypeForNode(); - assertNotNull(xType); - assertNotEquals(0, xType.getTypeProperties().size()); - } - ); - - // Default lib --> `string` type should also have properties - parseSingleSource( - "const x: string = '';", - (root, ctx) -> { - TSCNode x = root.firstNodeContaining("x"); - TSCType xType = x.getTypeForNode(); - assertNotNull(xType); - assertNotEquals(0, xType.getTypeProperties().size()); - } - ); - } - - @Test - public void testBridgeSourceInfo() { - parseSingleSource( - """ - class Foo {} - - function test(x: String) {} - """, - "example.ts", - (root, ctx) -> { - TSCNode Foo = root.firstNodeWithText("Foo"); - assertEquals( - new TSCProgramContext.CompilerBridgeSourceInfo( - TSCProgramContext.CompilerBridgeSourceKind.ApplicationCode, - Paths.get("example.ts") - ), - Foo.getSourceFile().getCompilerBridgeSourceInfo() - ); - - TSCNode string = root.firstNodeWithText("String"); - TSCType stringType = string.getTypeForNode(); - assertNotNull(stringType); - List declarations = stringType.getSymbolForType().getDeclarations(); - assertNotNull(declarations); - assertFalse(declarations.isEmpty()); - for (TSCNode declaration : declarations) { - TSCProgramContext.CompilerBridgeSourceInfo declSourceInfo = declaration.getSourceFile().getCompilerBridgeSourceInfo(); - assertEquals( - TSCProgramContext.CompilerBridgeSourceKind.SystemLibrary, - declSourceInfo.getSourceKind() - ); - assertTrue(declSourceInfo.getRelativePath().toString().startsWith("lib.")); - } - } - ); - } - - @Test - public void missingImportDoesNotThrow() { - parseSingleSource( - """ - import * as doesNotExist from './does/not/exist'; - - function test() { - return doesNotExist; - } - """, - "example.ts", - (root, ctx) -> { - } - ); - } - - @Test - public void missingDirectiveOrDirectiveDoesNotThrow() { - parseSingleSource( - """ - /// - - function test() { - return 42; - } - """, - "example.ts", - (root, ctx) -> { - } - ); - } - - @Test - public void testEmptyFile() { - parseSingleSource("", (root, ctx) -> {}); - } -} diff --git a/src/test/java/org/openrewrite/javascript/tree/ParserTest.java b/src/test/java/org/openrewrite/javascript/tree/ParserTest.java index 944935f6..0ec225bb 100644 --- a/src/test/java/org/openrewrite/javascript/tree/ParserTest.java +++ b/src/test/java/org/openrewrite/javascript/tree/ParserTest.java @@ -15,10 +15,25 @@ */ package org.openrewrite.javascript.tree; +import com.fasterxml.jackson.dataformat.cbor.CBORFactory; import org.junit.jupiter.api.Test; +import org.openrewrite.InMemoryExecutionContext; import org.openrewrite.Issue; +import org.openrewrite.SourceFile; +import org.openrewrite.remote.ReceiverContext; +import org.openrewrite.remote.RemotingContext; +import org.openrewrite.remote.RemotingMessenger; +import org.openrewrite.remote.java.RemotingClient; import org.openrewrite.test.RewriteTest; +import java.io.IOException; +import java.net.InetAddress; +import java.net.Socket; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + import static org.openrewrite.javascript.Assertions.javaScript; class ParserTest implements RewriteTest { @@ -32,4 +47,35 @@ void preservesOrder() { javaScript("class C {}", s -> s.path("C.js")) ); } + + @Test + void project() { + RemotingContext context = new RemotingContext(RewriteTest.class.getClassLoader(), false); + Map>> handlers = Map.of(); + RemotingClient client = new RemotingClient(() -> { + try { + return new Socket(InetAddress.getLoopbackAddress(), 54323); + } catch (IOException e) { + throw new RuntimeException(e); + } + }, context, new RemotingMessenger((CBORFactory) context.objectMapper().getFactory(), handlers, (m) -> new InMemoryExecutionContext())); + + List sourceFileStream = client.runUsingSocket((socket, messenger) -> messenger.sendRequest(generator -> { + generator.writeString("parse-project-sources"); + generator.writeString("/Users/knut/git/emilkowalski/vaul"); + }, parser -> { + parser.nextToken(); + int count = parser.getIntValue(); + + ReceiverContext receiverContext = new ReceiverContext(context.newReceiver(parser), context); + List sourceFiles = new ArrayList<>(count); + for (int i = 0; i < count; i++) { + SourceFile sourceFile = receiverContext.receiveTree(null); + System.out.println(sourceFile.getSourcePath()); + sourceFiles.add(sourceFile); + } + return sourceFiles.stream(); + }, socket)).toList(); + System.out.println(sourceFileStream); + } }