diff --git a/.dprint.jsonc b/.dprint.jsonc index 97a7f142a21..30f65144c18 100644 --- a/.dprint.jsonc +++ b/.dprint.jsonc @@ -52,14 +52,14 @@ "internal/lsp/lsproto/_generate/*.json", "internal/lsp/lsproto/_generate/metaModelSchema.mts", // Needs to be LF to have a working shebang. - "_packages/native-preview/bin/tsgo.js", + "_packages/native-preview/bin/tsgo", "_packages/native-preview/vendor/**" ], // Note: if adding new languages, make sure settings.template.json is updated too. // Also, if updating typescript, update the one in package.json. "plugins": [ "https://plugins.dprint.dev/typescript-0.96.1.wasm", - "https://plugins.dprint.dev/json-0.21.3.wasm", + "https://plugins.dprint.dev/json-0.22.0.wasm", "https://plugins.dprint.dev/g-plane/pretty_yaml-v0.6.0.wasm", "https://plugins.dprint.dev/jakebailey/gofumpt-v0.0.12.wasm" ] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c05b5049b63..23a018e89cd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -359,6 +359,8 @@ jobs: - run: npx hereby check:scripts + - run: npx hereby native-preview:check-platforms + required: runs-on: ubuntu-slim if: ${{ always() }} diff --git a/CHANGES.md b/CHANGES.md index 95f4cf7bec0..107e60984c8 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -187,6 +187,22 @@ const FORWARD = 1, BACKWARD = 2; ``` +#### `arguments` usage within a JS function body no longer implies a `...args: any[]` parameter +```js +function f() { + return arguments[0]; +} +f("something"); // Previously allowed, now an error +``` + +Instead, explicitly use a spread parameter: +```js +function f(...args) { + return args[0]; +} +f("something"); // Still allowed +``` + ### JSDoc Types #### JSDoc variadic types are now only synonyms for array types. diff --git a/Herebyfile.mjs b/Herebyfile.mjs index 389811acd40..41bf0855c3c 100644 --- a/Herebyfile.mjs +++ b/Herebyfile.mjs @@ -84,8 +84,19 @@ const { values: rawOptions } = parseArgs({ */ const options = /** @type {Options} */ (rawOptions); -if (options.forRelease && !options.setPrerelease) { - throw new Error("forRelease requires setPrerelease"); +// Native release branches can edit these constants to publish a different +// package flavor. Main's defaults publish @typescript/native-preview. +const nativePreviewReleaseProfile = /** @type {"native-preview" | "typescript"} */ ("native-preview"); +const nativePreviewReleaseVersion = /** @type {string | undefined} */ (undefined); +const produceNativePreviewVsix = /** @type {boolean} */ (true); +const publishAsTypescript = nativePreviewReleaseProfile === "typescript"; + +if (publishAsTypescript && !nativePreviewReleaseVersion) { + throw new Error("Publishing as 'typescript' requires hardcoding nativePreviewReleaseVersion."); +} + +if (options.forRelease && !options.setPrerelease && (!nativePreviewReleaseVersion || produceNativePreviewVsix)) { + throw new Error("forRelease requires setPrerelease unless nativePreviewReleaseVersion is hardcoded and VSIX production is disabled"); } const defaultGoBuildTags = [ @@ -312,6 +323,8 @@ export const generateExtension = task({ * goPrefix: string; * goFile: string; * outDir: string; + * stringEnum?: boolean; + * valueReplacements?: Record; * }} EnumDef */ @@ -329,17 +342,22 @@ const enumDefs = [ { name: "NodeFlags", goPrefix: "NodeFlags", goFile: "internal/ast/nodeflags.go", outDir: "_packages/native-preview/src/enums" }, { name: "OuterExpressionKinds", goPrefix: "OEK", goFile: "internal/ast/utilities.go", outDir: "_packages/native-preview/src/enums" }, { name: "ModifierFlags", goPrefix: "ModifierFlags", goFile: "internal/ast/modifierflags.go", outDir: "_packages/native-preview/src/enums" }, + { name: "ModuleKind", goPrefix: "ModuleKind", goFile: "internal/core/compileroptions.go", outDir: "_packages/native-preview/src/enums" }, { name: "TokenFlags", goPrefix: "TokenFlags", goFile: "internal/ast/tokenflags.go", outDir: "_packages/native-preview/src/enums" }, { name: "NodeBuilderFlags", goPrefix: "Flags", goFile: "internal/nodebuilder/types.go", outDir: "_packages/native-preview/src/enums" }, { name: "CompletionItemKind", goPrefix: "CompletionItemKind", goFile: "internal/lsp/lsproto/lsp_generated.go", outDir: "_packages/native-preview/src/enums" }, + // String enum: Go stores internal names with a "\xFE" sentinel prefix, but the escaped + // form sent over the wire uses "__" (see EscapeSymbolName), so map the sentinel accordingly. + { name: "InternalSymbolName", goPrefix: "InternalSymbolName", goFile: "internal/ast/symbol.go", outDir: "_packages/native-preview/src/enums", stringEnum: true, valueReplacements: { InternalSymbolNamePrefix: "__" } }, ]; /** * @param {string} block - * @param {string} prefix + * @param {EnumDef} def * @returns {{ name: string, value: string }[]} */ -function parseGoConstBlock(block, prefix) { +function parseGoConstBlock(block, def) { + const prefix = def.goPrefix; const members = []; let iotaCounter = 0; let hasIota = false; @@ -362,7 +380,10 @@ function parseGoConstBlock(block, prefix) { const memberName = goName.slice(prefix.length); let tsValue; - if (goValue === "iota") { + if (def.stringEnum) { + tsValue = parseGoStringValue(goValue, def.valueReplacements ?? {}); + } + else if (goValue === "iota") { tsValue = String(iotaCounter); hasIota = true; } @@ -383,6 +404,31 @@ function parseGoConstBlock(block, prefix) { return members; } +/** + * Resolve a Go string-constant expression (e.g. `Prefix + "call"` or `"export="`) + * into a quoted, JS-escaped TypeScript string literal. `replacements` maps bare + * Go identifiers (such as a sentinel-prefix constant) to their literal value. + * @param {string} goValue + * @param {Record} replacements + * @returns {string} + */ +function parseGoStringValue(goValue, replacements) { + let result = ""; + for (const part of goValue.split("+").map(p => p.trim())) { + if (Object.prototype.hasOwnProperty.call(replacements, part)) { + result += replacements[part]; + continue; + } + const stringMatch = part.match(/^"((?:[^"\\]|\\.)*)"$/); + if (stringMatch === null) { + throw new Error(`Cannot parse string enum value: ${goValue}`); + } + // Interpret Go escape sequences via JSON, then re-stringify below. + result += JSON.parse(`"${stringMatch[1]}"`); + } + return JSON.stringify(result); +} + /** * @param {EnumDef} def * @returns {{ name: string, value: string }[]} @@ -392,7 +438,7 @@ function parseGoEnum(def) { const constBlockRegex = /const\s*\(([\s\S]*?)\n\)/g; for (const match of source.matchAll(constBlockRegex)) { - const members = parseGoConstBlock(match[1], def.goPrefix); + const members = parseGoConstBlock(match[1], def); if (members.length > 0) return topoSortMembers(members); } @@ -1107,6 +1153,10 @@ export class Debouncer { constructor(timeout, action) { this._timeout = timeout; this._action = action; + /** @type {ReturnType | undefined} */ + this._timer = undefined; + /** @type {Deferred | undefined} */ + this._deferred = undefined; } get empty() { @@ -1146,6 +1196,10 @@ export class Debouncer { } const getVersion = memoize(() => { + if (nativePreviewReleaseVersion) { + return nativePreviewReleaseVersion; + } + const f = fs.readFileSync("./internal/core/version.go", "utf8"); const match = f.match(/var version\s*=\s*"(\d+\.\d+\.\d+)(-[^"]+)?"/); @@ -1164,6 +1218,20 @@ const getVersion = memoize(() => { return version; }); +function getPublishTag() { + if (publishAsTypescript) { + const version = getVersion(); + if (!version) { + throw new Error("Publishing as 'typescript' requires a version before selecting an npm tag."); + } + const match = version.match(/-(dev|beta|rc)(?:[.-]|$)/); + if (match?.[1]) return match[1] === "dev" ? "next" : match[1]; + if (version === nativePreviewReleaseVersion) return "latest"; + throw new Error(`Refusing to publish 'typescript' with the latest tag from non-release version ${version}.`); + } + return "latest"; +} + const extensionDir = path.resolve("./_extension"); const builtNpm = path.resolve("./built/npm"); const builtVsix = path.resolve("./built/vsix"); @@ -1398,68 +1466,170 @@ function cpWithoutNodeModulesOrTsconfig(src, dest) { } const mainNativePreviewPackage = { - npmPackageName: "@typescript/native-preview", - npmDir: path.join(builtNpm, "native-preview"), - npmTarball: path.join(builtNpm, "native-preview.tgz"), + npmPackageName: publishAsTypescript ? "typescript" : "@typescript/native-preview", + npmDir: path.join(builtNpm, publishAsTypescript ? "typescript" : "native-preview"), + npmTarball: path.join(builtNpm, publishAsTypescript ? "typescript.tgz" : "native-preview.tgz"), }; /** - * @typedef {"win32" | "linux" | "darwin"} OS - * @typedef {"x64" | "arm" | "arm64"} Arch + * @typedef {"win32" | "linux" | "darwin" | "aix" | "android" | "freebsd" | "netbsd" | "openbsd" | "sunos"} OS + * @typedef {"x64" | "arm" | "arm64" | "ia32" | "ppc64" | "loong64" | "mips64el" | "riscv64" | "s390x"} Arch * @typedef {"Microsoft400" | "LinuxSign" | "MacDeveloperHarden" | "8020" | "VSCodePublisher"} Cert * @typedef {`${OS | "alpine"}-${Exclude | "armhf"}`} VSCodeTarget + * @typedef {{ vscodeTarget: string; extensionDir: string; vsixPath: string; vsixManifestPath: string; vsixSignaturePath: string }} VsixExtension + * @typedef {{ GOOS: string; GOARCH: string }} GoDistTarget + * @typedef {{ os: OS; arch: Arch; cert?: Cert; vsix?: boolean; alpine?: boolean }} Platform */ void 0; -const nativePreviewPlatforms = memoize(() => { - /** @type {[os: OS, arch: Arch, cert: Cert, alpine?: boolean][]} */ - let supportedPlatforms = [ - ["win32", "x64", "Microsoft400"], - ["win32", "arm64", "Microsoft400"], - ["linux", "x64", "LinuxSign", true], - ["linux", "arm", "LinuxSign"], - ["linux", "arm64", "LinuxSign", true], - ["darwin", "x64", "MacDeveloperHarden"], - ["darwin", "arm64", "MacDeveloperHarden"], - // Wasm? - ]; +/** + * npm package platforms supported by the native release. + * The native-preview package publishes only the entries with vsix: true; + * the typescript package publishes the full list. + * BSD targets that are not in Node's supported-platforms table are best-effort + * and limited to mainstream 64-bit x64/arm64 architectures. + * alpine is set only for the subset that also produces Alpine VSIXes. + * cert defaults to LinuxSign. + * @type {Platform[]} + */ +const platforms = [ + { os: "win32", arch: "x64", vsix: true, cert: "Microsoft400" }, + { os: "win32", arch: "arm64", vsix: true, cert: "Microsoft400" }, + { os: "linux", arch: "x64", vsix: true, alpine: true }, + { os: "linux", arch: "arm", vsix: true }, + { os: "linux", arch: "arm64", vsix: true, alpine: true }, + { os: "darwin", arch: "x64", vsix: true, cert: "MacDeveloperHarden" }, + { os: "darwin", arch: "arm64", vsix: true, cert: "MacDeveloperHarden" }, + { os: "aix", arch: "ppc64" }, + { os: "freebsd", arch: "arm64" }, + { os: "freebsd", arch: "x64" }, + { os: "linux", arch: "loong64" }, + { os: "linux", arch: "mips64el" }, + { os: "linux", arch: "ppc64" }, + { os: "linux", arch: "riscv64" }, + { os: "linux", arch: "s390x" }, + { os: "netbsd", arch: "arm64" }, + { os: "netbsd", arch: "x64" }, + { os: "openbsd", arch: "arm64" }, + { os: "openbsd", arch: "x64" }, + { os: "sunos", arch: "x64" }, + // Wasm? +]; + +const ignoredGoTargets = new Map([ + ["android/386", "Android is not a Node runtime target TypeScript supports"], + ["android/amd64", "Android is not a Node runtime target TypeScript supports"], + ["android/arm", "Android is not a Node runtime target TypeScript supports"], + ["android/arm64", "Android is not a Node runtime target TypeScript supports"], + ["freebsd/386", "FreeBSD is experimental in Node and limited here to mainstream 64-bit x64/arm64"], + ["freebsd/arm", "FreeBSD is experimental in Node and limited here to mainstream 64-bit x64/arm64"], + ["linux/386", "ia32 means 32-bit x86, which TypeScript does not support for native packages"], + ["linux/ppc64", "Node supports Linux ppc64le; npm's ppc64 CPU name cannot select big-endian ppc64 separately"], + ["netbsd/386", "NetBSD is not in Node's supported-platforms table and is limited here to mainstream 64-bit x64/arm64"], + ["netbsd/arm", "NetBSD is not in Node's supported-platforms table and is limited here to mainstream 64-bit x64/arm64"], + ["openbsd/386", "OpenBSD is not in Node's supported-platforms table and is limited here to mainstream 64-bit x64/arm64"], + ["openbsd/arm", "OpenBSD is not in Node's supported-platforms table and is limited here to mainstream 64-bit x64/arm64"], + ["openbsd/ppc64", "OpenBSD is not in Node's supported-platforms table and is limited here to mainstream 64-bit x64/arm64"], + ["openbsd/riscv64", "OpenBSD is not in Node's supported-platforms table and is limited here to mainstream 64-bit x64/arm64"], + ["solaris/amd64", "Node documents SmartOS/sunos rather than Oracle Solaris; sunos-x64 publishes illumos/amd64 for that runtime family"], + ["windows/386", "ia32 means 32-bit x86, which TypeScript does not support for native packages"], +]); + +/** + * @param {string} os + * @returns {"windows" | "illumos" | "darwin" | "linux" | "aix" | "android" | "freebsd" | "netbsd" | "openbsd"} + */ +function nodeToGOOS(os) { + switch (os) { + case "win32": + return "windows"; + case "sunos": + return "illumos"; + case "darwin": + case "linux": + case "aix": + case "android": + case "freebsd": + case "netbsd": + case "openbsd": + return os; + default: + throw new Error(`Unsupported OS: ${os}`); + } +} + +/** + * @param {string} arch + * @param {string} os + * @returns {"amd64" | "386" | "mips64le" | "ppc64" | "ppc64le" | "arm" | "arm64" | "loong64" | "riscv64" | "s390x"} + */ +function nodeToGOARCH(arch, os) { + switch (arch) { + case "x64": + return "amd64"; + case "ia32": + return "386"; + case "mips64el": + return "mips64le"; + case "ppc64": + return os === "aix" ? "ppc64" : "ppc64le"; + case "arm": + case "arm64": + case "loong64": + case "riscv64": + case "s390x": + return arch; + default: + throw new Error(`Unsupported ARCH: ${arch}`); + } +} + +const getPlatforms = memoize(() => { + let supportedPlatforms = publishAsTypescript + ? platforms + : platforms.filter(({ vsix }) => vsix); if (!options.forRelease) { - supportedPlatforms = supportedPlatforms.filter(([os, arch]) => os === process.platform && arch === process.arch); + supportedPlatforms = supportedPlatforms.filter(({ os, arch }) => os === process.platform && arch === process.arch); assert.equal(supportedPlatforms.length, 1, "No supported platforms found"); } - return supportedPlatforms.map(([os, arch, cert, alpine]) => { - const npmDirName = `native-preview-${os}-${arch}`; + return supportedPlatforms.map(({ os, arch, cert = "LinuxSign", vsix, alpine }) => { + const packageBaseName = publishAsTypescript ? "typescript" : "native-preview"; + const npmDirName = `${packageBaseName}-${os}-${arch}`; const npmDir = path.join(builtNpm, npmDirName); const npmTarball = `${npmDir}.tgz`; const npmPackageName = `@typescript/${npmDirName}`; - /** @type {VSCodeTarget[]} */ - const vscodeTargets = [`${os}-${arch === "arm" ? "armhf" : arch}`]; - if (alpine) { - vscodeTargets.push(`alpine-${arch === "arm" ? "armhf" : arch}`); - } + /** @type {VsixExtension[]} */ + let extensions = []; + if (produceNativePreviewVsix && vsix) { + /** @type {string[]} */ + const vscodeTargets = [`${os}-${arch === "arm" ? "armhf" : arch}`]; + if (alpine) { + vscodeTargets.push(`alpine-${arch === "arm" ? "armhf" : arch}`); + } - const extensions = vscodeTargets.map(vscodeTarget => { - const extensionDir = path.join(builtVsix, `typescript-native-preview-${vscodeTarget}`); - const vsixPath = extensionDir + ".vsix"; - const vsixManifestPath = extensionDir + ".manifest"; - const vsixSignaturePath = extensionDir + ".signature.p7s"; - return { - vscodeTarget, - extensionDir, - vsixPath, - vsixManifestPath, - vsixSignaturePath, - }; - }); + extensions = vscodeTargets.map(vscodeTarget => { + const extensionDir = path.join(builtVsix, `typescript-native-preview-${vscodeTarget}`); + const vsixPath = extensionDir + ".vsix"; + const vsixManifestPath = extensionDir + ".manifest"; + const vsixSignaturePath = extensionDir + ".signature.p7s"; + return { + vscodeTarget, + extensionDir, + vsixPath, + vsixManifestPath, + vsixSignaturePath, + }; + }); + } return { nodeOs: os, nodeArch: arch, goos: nodeToGOOS(os), - goarch: nodeToGOARCH(arch), + goarch: nodeToGOARCH(arch, os), npmPackageName, npmDirName, npmDir, @@ -1468,41 +1638,110 @@ const nativePreviewPlatforms = memoize(() => { cert, }; }); +}); - /** - * @param {string} os - * @returns {"darwin" | "linux" | "windows"} - */ - function nodeToGOOS(os) { - switch (os) { - case "darwin": - return "darwin"; - case "linux": - return "linux"; - case "win32": - return "windows"; - default: - throw new Error(`Unsupported OS: ${os}`); +export const checkPlatforms = task({ + name: "native-preview:check-platforms", + hiddenFromTaskList: true, + run: runCheckPlatforms, +}); + +/** + * @param {GoDistTarget} target + */ +function goDistTargetToPlatform(target) { + const goTarget = `${target.GOOS}/${target.GOARCH}`; + if (ignoredGoTargets.has(goTarget)) { + return undefined; + } + + /** @type {OS | undefined} */ + let nodeOs; + switch (target.GOOS) { + case "windows": + nodeOs = "win32"; + break; + case "illumos": + nodeOs = "sunos"; + break; + case "aix": + case "android": + case "darwin": + case "freebsd": + case "linux": + case "netbsd": + case "openbsd": + nodeOs = target.GOOS; + break; + default: + return undefined; + } + + /** @type {Arch | undefined} */ + let nodeArch; + switch (target.GOARCH) { + case "386": + nodeArch = "ia32"; + break; + case "amd64": + nodeArch = "x64"; + break; + case "mips64le": + nodeArch = "mips64el"; + break; + case "ppc64": + nodeArch = "ppc64"; + break; + case "ppc64le": + nodeArch = "ppc64"; + break; + case "arm": + case "arm64": + case "loong64": + case "riscv64": + case "s390x": + nodeArch = target.GOARCH; + break; + default: + return undefined; + } + + return `${nodeOs}-${nodeArch}`; +} + +async function runCheckPlatforms() { + const { stdout } = await $pipe`go tool dist list -json`; + /** @type {GoDistTarget[]} */ + const goTargets = JSON.parse(stdout); + const goTargetSet = new Set(goTargets.map(({ GOOS, GOARCH }) => `${GOOS}/${GOARCH}`)); + + /** @type {[os: OS, arch: Arch][]} */ + const packagePlatforms = platforms.map(({ os, arch }) => /** @type {[OS, Arch]} */ ([os, arch])); + const actual = new Set(packagePlatforms.map(([os, arch]) => `${os}-${arch}`)); + const expected = new Set(goTargets.map(goDistTargetToPlatform).filter(platform => platform !== undefined)); + + const errors = []; + for (const [os, arch] of packagePlatforms) { + const goTarget = `${nodeToGOOS(os)}/${nodeToGOARCH(arch, os)}`; + if (!goTargetSet.has(goTarget)) { + errors.push(`Configured package platform ${os}-${arch} maps to unsupported Go target ${goTarget}.`); } } - /** - * @param {string} arch - * @returns {"amd64" | "arm" | "arm64"} - */ - function nodeToGOARCH(arch) { - switch (arch) { - case "x64": - return "amd64"; - case "arm": - return "arm"; - case "arm64": - return "arm64"; - default: - throw new Error(`Unsupported ARCH: ${arch}`); - } + const missing = [...expected].filter(platform => !actual.has(platform)); + if (missing.length) { + errors.push(`Missing package platform(s) for the current Go toolchain: ${missing.join(", ")}.`); + } + + const extra = [...actual].filter(platform => !expected.has(platform)); + if (extra.length) { + errors.push(`Unexpected package platform(s), or missing exclusion policy: ${extra.join(", ")}.`); } -}); + + if (errors.length) { + throw new Error(`native-preview platform list is out of sync with 'go tool dist list':\n${errors.map(e => ` - ${e}`).join("\n")}`); + } +} /** * Recursively strips `@typescript/source` export conditions from a package.json object. @@ -1548,7 +1787,7 @@ export const buildNativePreviewPackages = task({ async function runBuildNativePreviewPackages() { await rimraf(builtNpm); - const platforms = nativePreviewPlatforms(); + const platforms = getPlatforms(); const inputDir = "./_packages/native-preview"; @@ -1556,13 +1795,25 @@ async function runBuildNativePreviewPackages() { inputPackageJson.version = getVersion(); delete inputPackageJson.private; inputPackageJson.files = [...new Set([...(inputPackageJson.files ?? []), "NOTICE.txt"])]; + if (publishAsTypescript) { + inputPackageJson.bin = { + tsc: "./bin/tsc", + }; + delete inputPackageJson.scripts; + delete inputPackageJson.devDependencies; + } stripSourceConditions(inputPackageJson); const { stdout: gitHead } = await $pipe`git rev-parse HEAD`; inputPackageJson.gitHead = gitHead; + inputPackageJson.publishConfig = { + access: "public", + tag: getPublishTag(), + }; const mainPackage = { ...inputPackageJson, + name: mainNativePreviewPackage.npmPackageName, optionalDependencies: Object.fromEntries(platforms.map(p => [p.npmPackageName, getVersion()])), }; @@ -1573,6 +1824,12 @@ async function runBuildNativePreviewPackages() { // Copy package contents excluding node_modules and dist (dist is copied separately after build). // The package.json "files" field controls what npm pack actually includes. await cpRecursive(inputDir, mainPackageDir, p => !p.endsWith("/node_modules") && !p.includes("/dist")); + if (publishAsTypescript) { + await fs.promises.rename(path.join(mainPackageDir, "bin", "tsgo"), path.join(mainPackageDir, "bin", "tsc")); + await fs.promises.rename(path.join(mainPackageDir, "lib", "tsgo.js"), path.join(mainPackageDir, "lib", "tsc.js")); + await fs.promises.writeFile(path.join(mainPackageDir, "bin", "tsc"), '#!/usr/bin/env node\nimport "../lib/tsc.js";\n'); + await fs.promises.chmod(path.join(mainPackageDir, "bin", "tsc"), 0o755); + } await fs.promises.writeFile(path.join(mainPackageDir, "package.json"), JSON.stringify(mainPackage, undefined, 4)); await fs.promises.copyFile("LICENSE", path.join(mainPackageDir, "LICENSE")); @@ -1606,7 +1863,7 @@ async function runBuildNativePreviewPackages() { throw new Error(`Found external imports in .d.ts files:\n${importErrors.map(e => " " + e).join("\n")}`); } - const extraFlags = getReleaseBuildFlags(options.setPrerelease ? getVersion() : undefined); + const extraFlags = getReleaseBuildFlags(options.setPrerelease || nativePreviewReleaseVersion ? getVersion() : undefined); const platformBuilders = platforms.map(({ npmDir, npmPackageName, nodeOs, nodeArch, goos, goarch }) => async () => { const packageJson = { @@ -1639,8 +1896,9 @@ async function runBuildNativePreviewPackages() { await generateLibs(out); + const exeName = nativePreviewExeName(nodeOs); await buildTsgo({ - out, + out: publishAsTypescript ? path.join(out, exeName) : out, env: { GOOS: goos, GOARCH: goarch, GOARM: "6", CGO_ENABLED: "0" }, extraFlags, }); @@ -1666,12 +1924,20 @@ export const signNativePreviewPackages = task({ run: runSignNativePreviewPackages, }); +/** + * @param {string} nodeOs + */ +function nativePreviewExeName(nodeOs) { + const baseName = publishAsTypescript ? "tsc" : "tsgo"; + return nodeOs === "win32" ? `${baseName}.exe` : baseName; +} + async function runSignNativePreviewPackages() { if (!options.forRelease) { throw new Error("This task should not be run in non-release builds."); } - const platforms = nativePreviewPlatforms(); + const platforms = getPlatforms(); /** @type {Map} */ const filelistByCert = new Map(); @@ -1682,7 +1948,7 @@ async function runSignNativePreviewPackages() { } certFilelist.push({ tmpName: npmDirName, - path: path.join(npmDir, "lib", nodeOs === "win32" ? "tsgo.exe" : "tsgo"), + path: path.join(npmDir, "lib", nativePreviewExeName(nodeOs)), }); } @@ -1789,40 +2055,50 @@ export const packNativePreviewPackages = task({ }); async function runPackNativePreviewPackages() { - const platforms = nativePreviewPlatforms(); + const platforms = getPlatforms(); await Promise.all([mainNativePreviewPackage, ...platforms].map(async ({ npmDir, npmTarball }) => { const { stdout } = await $pipe`npm pack --json ${npmDir}`; const filename = JSON.parse(stdout)[0].filename.replace("@", "").replace("/", "-"); await fs.promises.rename(filename, npmTarball); })); - // npm packages need to be published in reverse dep order, e.g. such that no package - // is published before its dependencies. - const publishOrder = [ - ...platforms.map(p => p.npmTarball), - mainNativePreviewPackage.npmTarball, - ].map(p => path.basename(p)); - - const publishManifest = publishOrder.map(pkg => ({ - filename: pkg, - tag: "latest", - })); + // npm packages need to be published in dependency order: platform packages + // first, then the main package that references them as optionalDependencies. + const publishManifest = { + stages: [ + platforms.map(p => ({ + filename: path.basename(p.npmTarball), + })), + [ + { + filename: path.basename(mainNativePreviewPackage.npmTarball), + }, + ], + ], + }; - const publishOrderPath = path.join(builtNpm, "publish-order.json"); - await fs.promises.writeFile(publishOrderPath, JSON.stringify(publishManifest, undefined, 4) + "\n"); + const publishManifestPath = path.join(builtNpm, "publish-manifest.json"); + await fs.promises.writeFile(publishManifestPath, JSON.stringify(publishManifest, undefined, 4) + "\n"); } -export const packNativePreviewExtensions = task({ +export const packVsixExtensions = task({ name: "native-preview:pack-extensions", hiddenFromTaskList: true, dependencies: options.forRelease ? undefined : [buildNativePreviewPackages, cleanSignTempDirectory], - run: runPackNativePreviewExtensions, + run: runPackVsixExtensions, }); -async function runPackNativePreviewExtensions() { +async function runPackVsixExtensions() { await rimraf(builtVsix); await fs.promises.mkdir(builtVsix, { recursive: true }); + const platforms = getPlatforms(); + const extensions = platforms.flatMap(({ npmDir, extensions }) => extensions.map(e => ({ npmDir, ...e }))); + if (!extensions.length) { + console.log("No VSIX targets configured; skipping extension packaging."); + return; + } + // We don't use vscode:prepublish, as that would run the build for each package below. await $({ cwd: extensionDir })`npm run bundle:release`; @@ -1844,9 +2120,6 @@ async function runPackNativePreviewExtensions() { console.log("Version:", version); - const platforms = nativePreviewPlatforms(); - const extensions = platforms.flatMap(({ npmDir, extensions }) => extensions.map(e => ({ npmDir, ...e }))); - await Promise.all(extensions.map(async ({ npmDir, vscodeTarget, extensionDir: thisExtensionDir, vsixPath, vsixManifestPath, vsixSignaturePath }) => { const npmLibDir = path.join(npmDir, "lib"); const extensionLibDir = path.join(thisExtensionDir, "lib"); @@ -1872,19 +2145,23 @@ async function runPackNativePreviewExtensions() { })); } -export const signNativePreviewExtensions = task({ +export const signVsixExtensions = task({ name: "native-preview:sign-extensions", hiddenFromTaskList: true, - run: runSignNativePreviewExtensions, + run: runSignVsixExtensions, }); -async function runSignNativePreviewExtensions() { +async function runSignVsixExtensions() { if (!options.forRelease) { throw new Error("This task should not be run in non-release builds."); } - const platforms = nativePreviewPlatforms(); + const platforms = getPlatforms(); const extensions = platforms.flatMap(({ npmDir, extensions }) => extensions.map(e => ({ npmDir, ...e }))); + if (!extensions.length) { + console.log("No VSIX targets configured; skipping extension signing."); + return; + } await sign({ SignFileRecordList: [ @@ -1901,14 +2178,14 @@ export const nativePreviewRelease = task({ name: "native-preview:release", hiddenFromTaskList: true, run: async () => { - if (!options.forRelease || !options.setPrerelease) { - throw new Error("native-preview:release requires --forRelease and --setPrerelease flags. Example: npx hereby native-preview:release --forRelease --setPrerelease=dev.1.0"); + if (!options.forRelease || !options.setPrerelease && (!nativePreviewReleaseVersion || produceNativePreviewVsix)) { + throw new Error("native-preview:release requires --forRelease and --setPrerelease flags, unless nativePreviewReleaseVersion is hardcoded and VSIX production is disabled. Example: npx hereby native-preview:release --forRelease --setPrerelease=dev.1.0"); } await runBuildNativePreviewPackages(); await runSignNativePreviewPackages(); await runPackNativePreviewPackages(); - await runPackNativePreviewExtensions(); - await runSignNativePreviewExtensions(); + await runPackVsixExtensions(); + await runSignVsixExtensions(); await runCleanSignTempDirectory(); }, }); @@ -1916,7 +2193,7 @@ export const nativePreviewRelease = task({ export const nativePreview = task({ name: "native-preview", hiddenFromTaskList: true, - dependencies: options.forRelease ? undefined : [packNativePreviewPackages, packNativePreviewExtensions], + dependencies: options.forRelease ? undefined : [packNativePreviewPackages, packVsixExtensions], run: options.forRelease ? async () => { throw new Error("This task should not be run in release builds."); } : undefined, diff --git a/NOTICE.txt b/NOTICE.txt index 7f19b1c39e6..0c40b1e6165 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -221,7 +221,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND --------------------------------------------------------- -github.com/go-json-experiment/json v0.0.0-20260601182631-00ed12fed2a6 - BSD-3-Clause +github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 - BSD-3-Clause Copyright 2010 The Go Authors diff --git a/_extension/package.json b/_extension/package.json index 1ac0d5aa83b..7fcac71a398 100644 --- a/_extension/package.json +++ b/_extension/package.json @@ -252,12 +252,12 @@ }, "dependencies": { "@vscode/extension-telemetry": "^1.5.2", - "vscode-languageclient": "^10.0.0", + "vscode-languageclient": "^10.0.1", "vscode-tas-client": "^0.2.1" }, "devDependencies": { "@types/vscode": "~1.110.0", "@vscode/vsce": "^3.9.2", - "esbuild": "^0.28.0" + "esbuild": "^0.28.1" } } diff --git a/_extension/src/client.ts b/_extension/src/client.ts index 4db89dcf47f..582a35b87bf 100644 --- a/_extension/src/client.ts +++ b/_extension/src/client.ts @@ -89,7 +89,7 @@ export class Client implements vscode.Disposable { sendNotification: sendNotificationMiddleware, provideHover: () => undefined, }, - diagnosticCollectionName: "typescript", + diagnosticCollectionName: "typescript-push", diagnosticPullOptions: { onChange: true, onSave: true, diff --git a/_extension/src/util.ts b/_extension/src/util.ts index f9237658f76..c3bd3417d9d 100644 --- a/_extension/src/util.ts +++ b/_extension/src/util.ts @@ -128,22 +128,35 @@ export function resolveTsdkPath(tsdkPath: string): string { } export async function resolveTsdkPathToExe(tsdkPath: string): Promise<{ path: string; version: string; } | undefined> { - if (tsdkPath.endsWith("/@typescript/native-preview") || tsdkPath.endsWith("\\@typescript\\native-preview")) { + const resolved = workspaceResolve(tsdkPath); + for (const packagePath of [resolved, vscode.Uri.joinPath(resolved, "..")]) { try { - const packagePath = workspaceResolve(tsdkPath); const packageJsonPath = vscode.Uri.joinPath(packagePath, "package.json"); const packageJson = JSON.parse(await vscode.workspace.fs.readFile(packageJsonPath).then(buffer => buffer.toString())); // NOTE: Keep in sync with _packages/native-preview/lib/getExePath.js. - const exeName = `tsgo${process.platform === "win32" ? ".exe" : ""}`; - const platformPackage = `native-preview-${process.platform}-${process.arch}`; - const exePath = vscode.Uri.joinPath(packagePath, "..", platformPackage, "lib", exeName); + const name: unknown = packageJson.name; + const bin: unknown = packageJson.bin; + if (typeof name !== "string" || !bin || typeof bin !== "object") continue; + + const baseName = name.startsWith("@") ? name.split("/")[1] : name; + if (!baseName) continue; + const expectedBinName = baseName === "typescript" ? "tsc" : "tsgo"; + const binNames = Object.keys(bin); + if (binNames.length !== 1 || binNames[0] !== expectedBinName) continue; + + const exeName = `${expectedBinName}${process.platform === "win32" ? ".exe" : ""}`; + const platformPackage = `${baseName}-${process.platform}-${process.arch}`; + const nodeModules = name.startsWith("@") + ? vscode.Uri.joinPath(packagePath, "..", "..") + : vscode.Uri.joinPath(packagePath, ".."); + const exePath = vscode.Uri.joinPath(nodeModules, "@typescript", platformPackage, "lib", exeName); await vscode.workspace.fs.stat(exePath); - return { path: withLongPathPrefix(exePath.fsPath), version: packageJson.version }; + return { path: withLongPathPrefix(exePath.fsPath), version: typeof packageJson.version === "string" ? packageJson.version : "unknown" }; } catch {} } try { - const exePath = workspaceResolve(path.join(tsdkPath, `tsgo${process.platform === "win32" ? ".exe" : ""}`)); + const exePath = vscode.Uri.joinPath(resolved, `tsgo${process.platform === "win32" ? ".exe" : ""}`); await vscode.workspace.fs.stat(exePath); return { path: withLongPathPrefix(exePath.fsPath), version: "(local)" }; } diff --git a/_packages/native-preview/bin/tsgo b/_packages/native-preview/bin/tsgo new file mode 100755 index 00000000000..fd1812bee63 --- /dev/null +++ b/_packages/native-preview/bin/tsgo @@ -0,0 +1,2 @@ +#!/usr/bin/env node +import "../lib/tsgo.js"; diff --git a/_packages/native-preview/lib/getExePath.js b/_packages/native-preview/lib/getExePath.js index ccc57d32378..ade3d7bb92e 100644 --- a/_packages/native-preview/lib/getExePath.js +++ b/_packages/native-preview/lib/getExePath.js @@ -8,15 +8,27 @@ export default function getExePath() { const __dirname = path.dirname(fileURLToPath(import.meta.url)); const normalizedDirname = __dirname.replace(/\\/g, "/"); + const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "package.json"), "utf8")); + const pkgName = pkg.name; + const baseName = pkgName.startsWith("@") ? pkgName.split("/")[1] : pkgName; + const expectedBinName = baseName === "typescript" ? "tsc" : "tsgo"; + const binNames = pkg.bin && typeof pkg.bin === "object" ? Object.keys(pkg.bin) : []; + if (binNames.length !== 1 || binNames[0] !== expectedBinName) { + throw new Error(`Expected ${pkgName} to declare exactly one bin entry named ${expectedBinName}.`); + } + let binName = expectedBinName; let exeDir; - const expectedPackage = "native-preview-" + process.platform + "-" + process.arch; + const expectedPackage = baseName + "-" + process.platform + "-" + process.arch; - if (normalizedDirname.endsWith("/_packages/native-preview/lib")) { + if (normalizedDirname.endsWith("/_packages/" + baseName + "/lib")) { // We're running directly from source in the repo. + // The local repo build (`hereby build`) always produces `tsgo`, regardless + // of the published `bin` name, so don't use binName here. exeDir = path.resolve(__dirname, "..", "..", "..", "built", "local"); + binName = "tsgo"; } - else if (normalizedDirname.endsWith("/built/npm/native-preview/lib")) { + else if (normalizedDirname.endsWith("/built/npm/" + baseName + "/lib")) { // We're running from the built output. exeDir = path.resolve(__dirname, "..", "..", expectedPackage, "lib"); } @@ -42,7 +54,7 @@ export default function getExePath() { } } - let exe = path.join(exeDir, "tsgo"); + let exe = path.join(exeDir, binName); if (process.platform === "win32") { exe += ".exe"; if (exe.length >= 248) { diff --git a/_packages/native-preview/bin/tsgo.js b/_packages/native-preview/lib/tsgo.js old mode 100755 new mode 100644 similarity index 95% rename from _packages/native-preview/bin/tsgo.js rename to _packages/native-preview/lib/tsgo.js index 721fde8fb13..eb869b71573 --- a/_packages/native-preview/bin/tsgo.js +++ b/_packages/native-preview/lib/tsgo.js @@ -1,28 +1,28 @@ -#!/usr/bin/env node - -import getExePath from "#getExePath"; -import { execFileSync } from "node:child_process"; - -const exe = getExePath(); - -if (process.platform !== "win32" && typeof process.execve === "function") { - // > v22.15.0 - try { - process.execve(exe, [exe, ...process.argv.slice(2)]); - } - catch { - // may not be available, ignore the error and fallback - } -} - -try { - execFileSync(exe, process.argv.slice(2), { stdio: "inherit" }); -} -catch (e) { - if (e.status) { - process.exitCode = e.status; - } - else { - throw e; - } -} +#!/usr/bin/env node + +import getExePath from "#getExePath"; +import { execFileSync } from "node:child_process"; + +const exe = getExePath(); + +if (process.platform !== "win32" && typeof process.execve === "function") { + // > v22.15.0 + try { + process.execve(exe, [exe, ...process.argv.slice(2)]); + } + catch { + // may not be available, ignore the error and fallback + } +} + +try { + execFileSync(exe, process.argv.slice(2), { stdio: "inherit" }); +} +catch (e) { + if (e.status) { + process.exitCode = e.status; + } + else { + throw e; + } +} diff --git a/_packages/native-preview/lib/version.cjs b/_packages/native-preview/lib/version.cjs new file mode 100644 index 00000000000..5a2e8c81368 --- /dev/null +++ b/_packages/native-preview/lib/version.cjs @@ -0,0 +1,3 @@ +const { version } = require("../package.json"); +exports.version = version; +exports.versionMajorMinor = "7.0"; diff --git a/_packages/native-preview/lib/version.d.cts b/_packages/native-preview/lib/version.d.cts new file mode 100644 index 00000000000..b434811c6fd --- /dev/null +++ b/_packages/native-preview/lib/version.d.cts @@ -0,0 +1,2 @@ +export declare const version: string; +export declare const versionMajorMinor = "7.0"; diff --git a/_packages/native-preview/package.json b/_packages/native-preview/package.json index fe964cd71b0..7a322799b73 100644 --- a/_packages/native-preview/package.json +++ b/_packages/native-preview/package.json @@ -21,9 +21,6 @@ "type": "git", "url": "https://github.com/microsoft/typescript-go.git" }, - "publishConfig": { - "access": "public" - }, "type": "module", "preferUnplugged": true, "engines": { @@ -36,10 +33,11 @@ "vendor" ], "bin": { - "tsgo": "./bin/tsgo.js" + "tsgo": "./bin/tsgo" }, "exports": { "./package.json": "./package.json", + ".": "./lib/version.cjs", "./unstable/sync": { "@typescript/source": "./src/api/sync/api.ts", "default": "./dist/api/sync/api.js" @@ -113,7 +111,7 @@ "test": "npm run test:only" }, "devDependencies": { - "@types/node": "^25.9.1", + "@types/node": "^25.9.4", "tinybench": "^6.0.2", "vscode-jsonrpc": "^9.0.0" } diff --git a/_packages/native-preview/src/api/async/api.ts b/_packages/native-preview/src/api/async/api.ts index ec37e1a61a1..85f00c220dd 100644 --- a/_packages/native-preview/src/api/async/api.ts +++ b/_packages/native-preview/src/api/async/api.ts @@ -2,6 +2,7 @@ import { CompletionItemKind } from "#enums/completionItemKind"; import { DiagnosticCategory } from "#enums/diagnosticCategory"; import { ElementFlags } from "#enums/elementFlags"; +import { ModuleKind } from "#enums/moduleKind"; import { NodeBuilderFlags } from "#enums/nodeBuilderFlags"; import { ObjectFlags } from "#enums/objectFlags"; import { SignatureFlags } from "#enums/signatureFlags"; @@ -10,6 +11,7 @@ import { SymbolFlags } from "#enums/symbolFlags"; import { TypeFlags } from "#enums/typeFlags"; import { TypePredicateKind } from "#enums/typePredicateKind"; import { + type __String, type Expression, type Identifier, ModifierFlags, @@ -18,6 +20,7 @@ import { type SourceFile, type SyntaxKind, type TypeNode, + unescapeLeadingUnderscores, } from "../../ast/index.ts"; import { encodeNode, @@ -31,6 +34,7 @@ import { readSourceFileHash, RemoteSourceFile, } from "../node/node.ts"; +import { Wtf8Decoder } from "../node/wtf8.ts"; import type { APIOptions, LSPConnectionOptions, @@ -50,13 +54,17 @@ import type { ProfileResult, ProjectResponse, SignatureResponse, + SourceFileMetadata, SymbolResponse, TypePredicateResponse, TypeResponse, UpdateSnapshotParams, UpdateSnapshotResponse, } from "../proto.ts"; -import { resolveFileName } from "../proto.ts"; +import { + resolveFileName, + toUpdateSnapshotRequest, +} from "../proto.ts"; import { SourceFileCache } from "../sourceFileCache.ts"; import { Client, @@ -81,6 +89,7 @@ import type { InterfaceType, IntersectionType, IntrinsicType, + JSDocTagInfo, LiteralType, NumberLiteralType, ObjectType, @@ -99,9 +108,9 @@ import type { UnionType, } from "./types.ts"; -export { CompletionItemKind, DiagnosticCategory, ElementFlags, ModifierFlags, NodeBuilderFlags, ObjectFlags, SignatureFlags, SignatureKind, SymbolFlags, TypeFlags, TypePredicateKind }; -export type { APIOptions, ClientSocketOptions, ClientSpawnOptions, DocumentIdentifier, DocumentPosition, LSPConnectionOptions }; -export type { AssertsIdentifierTypePredicate, AssertsThisTypePredicate, BigIntLiteralType, BooleanLiteralType, CompletionEntry, CompletionInfo, CompletionOptions, ConditionalType, Diagnostic, FreshableType, IdentifierTypePredicate, IndexedAccessType, IndexInfo, IndexType, InterfaceType, IntersectionType, IntrinsicType, LiteralType, NumberLiteralType, ObjectType, StringLiteralType, StringMappingType, SubstitutionType, TemplateLiteralType, ThisTypePredicate, TupleType, Type, TypeParameter, TypePredicate, TypePredicateBase, TypeReference, UnionOrIntersectionType, UnionType }; +export { CompletionItemKind, DiagnosticCategory, ElementFlags, ModifierFlags, ModuleKind, NodeBuilderFlags, ObjectFlags, SignatureFlags, SignatureKind, SymbolFlags, TypeFlags, TypePredicateKind }; +export type { APIOptions, ClientSocketOptions, ClientSpawnOptions, DocumentIdentifier, DocumentPosition, LSPConnectionOptions, SourceFileMetadata }; +export type { AssertsIdentifierTypePredicate, AssertsThisTypePredicate, BigIntLiteralType, BooleanLiteralType, CompletionEntry, CompletionInfo, CompletionOptions, ConditionalType, Diagnostic, FreshableType, IdentifierTypePredicate, IndexedAccessType, IndexInfo, IndexType, InterfaceType, IntersectionType, IntrinsicType, JSDocTagInfo, LiteralType, NumberLiteralType, ObjectType, StringLiteralType, StringMappingType, SubstitutionType, TemplateLiteralType, ThisTypePredicate, TupleType, Type, TypeParameter, TypePredicate, TypePredicateBase, TypeReference, UnionOrIntersectionType, UnionType }; export { documentURIToFileName, fileNameToDocumentURI } from "../path.ts"; export class API { @@ -113,7 +122,7 @@ export class API { private latestSnapshot: Snapshot | undefined; readonly internal: InternalAPI; - constructor(options: APIOptions | LSPConnectionOptions) { + constructor(options: APIOptions | LSPConnectionOptions = {}) { this.client = new Client(options); this.sourceFileCache = new SourceFileCache(); this.internal = new InternalAPI(this.client, () => this.ensureInitialized()); @@ -147,11 +156,7 @@ export class API { async updateSnapshot(params?: FromLSP extends true ? LSPUpdateSnapshotParams : UpdateSnapshotParams): Promise { await this.ensureInitialized(); - const requestParams: UpdateSnapshotParams = params ?? {}; - if (requestParams.openProject) { - requestParams.openProject = resolveFileName(requestParams.openProject); - } - + const requestParams = toUpdateSnapshotRequest(params); const data = await this.client.apiRequest("updateSnapshot", requestParams); // Retain cached source files from previous snapshot for unchanged files @@ -247,9 +252,9 @@ export class Snapshot { this.client = client; this.toPath = toPath; this.onDispose = onDispose; - this.snapshotRegistry = new SnapshotObjectRegistry(client, this.id); - this.projectMap = new Map(); + this.snapshotRegistry = new SnapshotObjectRegistry(client, this.id, projectId => this.projectMap.get(projectId)); + for (const projData of data.projects) { const project = new Project(projData, this.id, client, sourceFileCache, toPath, this.snapshotRegistry); this.projectMap.set(toPath(projData.configFileName), project); @@ -307,10 +312,17 @@ class SnapshotObjectRegistry { private readonly symbols: Map = new Map(); private readonly client: Client; private readonly snapshotId: number; + private readonly resolveProject: (projectId: Path) => Project | undefined; - constructor(client: Client, snapshotId: number) { + constructor(client: Client, snapshotId: number, resolveProject: (projectId: Path) => Project | undefined) { this.client = client; this.snapshotId = snapshotId; + this.resolveProject = resolveProject; + } + + /** Resolve a project id (a config file path) to its Project within this snapshot. */ + getProject(projectId: Path): Project | undefined { + return this.resolveProject(projectId); } getOrCreateSymbol(data: SymbolResponse): Symbol { @@ -330,7 +342,7 @@ class SnapshotObjectRegistry { this.symbols.clear(); } - async fetchSymbol(source: Symbol | Signature | Type, method: string, handle: number | undefined, projectId?: string): Promise { + async fetchSymbol(source: Symbol | Signature | Type, method: string, handle: number | undefined, projectId?: Path): Promise { if (!handle) return undefined as unknown as Symbol; const cached = this.getSymbol(handle); if (cached) return cached; @@ -344,7 +356,7 @@ class SnapshotObjectRegistry { return this.getOrCreateSymbol(data); } - async fetchSymbols(source: Symbol | Signature | Type, method: string, handles?: readonly number[], projectId?: string): Promise { + async fetchSymbols(source: Symbol | Signature | Type, method: string, handles?: readonly number[], projectId?: Path): Promise { if (handles) { const result = new Array(handles.length); let allCached = true; @@ -371,7 +383,7 @@ class SnapshotObjectRegistry { class ProjectObjectRegistry { private client: Client; private snapshotId: number; - private projectId: string; + private project: Project; private snapshotRegistry: SnapshotObjectRegistry; private types: Map = new Map(); private signatures: Map = new Map(); @@ -379,12 +391,12 @@ class ProjectObjectRegistry { constructor( client: Client, snapshotId: number, - projectId: string, + project: Project, snapshotRegistry: SnapshotObjectRegistry, ) { this.client = client; this.snapshotId = snapshotId; - this.projectId = projectId; + this.project = project; this.snapshotRegistry = snapshotRegistry; } @@ -412,7 +424,7 @@ class ProjectObjectRegistry { getOrCreateSignature(data: SignatureResponse): Signature { let sig = this.signatures.get(data.id); if (!sig) { - sig = new Signature(data, this); + sig = new Signature(data, this.project, this); this.signatures.set(data.id, sig); } return sig; @@ -427,14 +439,16 @@ class ProjectObjectRegistry { this.signatures.clear(); } - async fetchType(source: Symbol | Signature | Type, method: string, handle: number | undefined): Promise { - if (!handle) return undefined as unknown as T; - const cached = this.getType(handle); - if (cached) return cached as unknown as T; + async fetchType(source: Symbol | Signature | Type, method: string, handle: number | false | undefined): Promise { + if (handle !== false) { + if (!handle) return undefined as unknown as T; + const cached = this.getType(handle); + if (cached) return cached as unknown as T; + } const data = await this.client.apiRequest(method, { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, objectId: source.id, }); if (!data) throw new Error(`${method} returned null type for ${source.constructor.name} ${source.id}`); @@ -442,7 +456,7 @@ class ProjectObjectRegistry { } async fetchSymbol(source: Symbol | Signature | Type, method: string, handle: number | undefined): Promise { - return this.snapshotRegistry.fetchSymbol(source, method, handle, this.projectId); + return this.snapshotRegistry.fetchSymbol(source, method, handle, this.project.id); } async fetchSignature(source: Symbol | Signature | Type, method: string, handle: number | undefined): Promise { @@ -452,7 +466,7 @@ class ProjectObjectRegistry { const data = await this.client.apiRequest(method, { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, objectId: source.id, }); if (!data) throw new Error(`${method} returned null signature for ${source.constructor.name} ${source.id}`); @@ -475,7 +489,7 @@ class ProjectObjectRegistry { } const typesData = await this.client.apiRequest(method, { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, objectId: source.id, }); if (typesData == null) return []; @@ -483,12 +497,24 @@ class ProjectObjectRegistry { } async fetchSymbols(source: Symbol | Signature | Type, method: string, handles?: readonly number[]): Promise { - return this.snapshotRegistry.fetchSymbols(source, method, handles, this.projectId); + return this.snapshotRegistry.fetchSymbols(source, method, handles, this.project.id); + } + + // getBaseTypes is a checker-level endpoint keyed by `type` (not `objectId`), + // so it cannot go through fetchTypes. This helper reuses that server method. + async fetchBaseTypes(source: Type): Promise { + const typesData = await this.client.apiRequest("getBaseTypes", { + snapshot: this.snapshotId, + project: this.project.id, + type: source.id, + }); + if (typesData == null) return []; + return typesData.map(data => this.getOrCreateType(data)); } } export class Project { - readonly id: string; + readonly id: Path; readonly configFileName: string; readonly compilerOptions: Record; readonly rootFiles: readonly string[]; @@ -518,10 +544,10 @@ export class Project { sourceFileCache, toPath, ); - const objectRegistry = new ProjectObjectRegistry(client, snapshotId, this.id, snapshotRegistry); + const objectRegistry = new ProjectObjectRegistry(client, snapshotId, this, snapshotRegistry); this.checker = new Checker( snapshotId, - this.id, + this, client, objectRegistry, ); @@ -535,15 +561,16 @@ export class Project { export class Program { private snapshotId: number; - private projectId: string; + private projectId: Path; private client: Client; private sourceFileCache: SourceFileCache; private toPath: (fileName: string) => Path; - private decoder = new TextDecoder(); + private decoder = new Wtf8Decoder(); + private sourceFileMetadataCache = new Map>(); constructor( snapshotId: number, - projectId: string, + projectId: Path, client: Client, sourceFileCache: SourceFileCache, toPath: (fileName: string) => Path, @@ -584,6 +611,67 @@ export class Program { return this.sourceFileCache.set(path, sourceFile, parseOptionsKey, contentHash, this.snapshotId, this.projectId); } + async getSourceFileNames(): Promise { + const data = await this.client.apiRequest("getSourceFileNames", { + snapshot: this.snapshotId, + project: this.projectId, + }); + return data ?? []; + } + + /** + * Returns program-stored metadata for the given source file, or `undefined` if the file + * is not part of the program. Metadata is fetched lazily per file and cached on this + * `Program` instance. + */ + getSourceFileMetadata(fileName: string): Promise { + return this.getSourceFileMetadataByPath(this.toPath(fileName)); + } + + /** + * Returns program-stored metadata for the source file at the given path, or `undefined` + * if the file is not part of the program. Like {@link getSourceFileMetadata}, but skips + * the file name to path conversion. Metadata is fetched lazily per file and cached on + * this `Program` instance. + */ + getSourceFileMetadataByPath(path: Path): Promise { + let metadata = this.sourceFileMetadataCache.get(path); + if (metadata === undefined) { + metadata = this.fetchSourceFileMetadata(path); + this.sourceFileMetadataCache.set(path, metadata); + } + return metadata; + } + + private async fetchSourceFileMetadata(path: Path): Promise { + const data = await this.client.apiRequest("getSourceFileMetadata", { + snapshot: this.snapshotId, + project: this.projectId, + file: path, + }); + return data ?? undefined; + } + + /** + * Returns whether the given source file was loaded as part of an external library + * (e.g. a dependency resolved from `node_modules`). The underlying program metadata is + * fetched lazily per file and cached on this `Program` instance. + */ + async isSourceFileFromExternalLibrary(file: SourceFile): Promise { + const metadata = await this.getSourceFileMetadataByPath(file.path); + return metadata?.isFromExternalLibrary ?? false; + } + + /** + * Returns whether the given source file is a default library file (e.g. `lib.d.ts`). + * The underlying program metadata is fetched lazily per file and cached on this + * `Program` instance. + */ + async isSourceFileDefaultLibrary(file: SourceFile): Promise { + const metadata = await this.getSourceFileMetadataByPath(file.path); + return metadata?.isDefaultLibrary ?? false; + } + /** * Get syntactic (parse) diagnostics for a specific file or all files. * @param file - Optional file to get diagnostics for. If omitted, returns diagnostics for all files. @@ -597,6 +685,19 @@ export class Program { return data ?? []; } + /** + * Get binder diagnostics for a specific file or all files. + * @param file - Optional file to get diagnostics for. If omitted, returns diagnostics for all files. + */ + async getBindDiagnostics(file?: DocumentIdentifier): Promise { + const data = await this.client.apiRequest("getBindDiagnostics", { + snapshot: this.snapshotId, + project: this.projectId, + ...(file !== undefined ? { file } : {}), + }); + return data ?? []; + } + /** * Get semantic (type-check) diagnostics for a specific file or all files. * @param file - Optional file to get diagnostics for. If omitted, returns diagnostics for all files. @@ -636,6 +737,28 @@ export class Program { return data ?? []; } + /** + * Get program-wide diagnostics for the project, including compiler options diagnostics. + */ + async getProgramDiagnostics(): Promise { + const data = await this.client.apiRequest("getProgramDiagnostics", { + snapshot: this.snapshotId, + project: this.projectId, + }); + return data ?? []; + } + + /** + * Get global (non-file-specific) semantic diagnostics for the project. + */ + async getGlobalDiagnostics(): Promise { + const data = await this.client.apiRequest("getGlobalDiagnostics", { + snapshot: this.snapshotId, + project: this.projectId, + }); + return data ?? []; + } + /** * Get config file parsing diagnostics for the project. */ @@ -650,18 +773,19 @@ export class Program { export class Checker { private snapshotId: number; - private projectId: string; + private project: Project; private client: Client; private objectRegistry: ProjectObjectRegistry; + private wellKnownSymbols: Promise<{ unknown: number; undefined: number; arguments: number; }> | undefined; constructor( snapshotId: number, - projectId: string, + project: Project, client: Client, objectRegistry: ProjectObjectRegistry, ) { this.snapshotId = snapshotId; - this.projectId = projectId; + this.project = project; this.client = client; this.objectRegistry = objectRegistry; } @@ -676,14 +800,14 @@ export class Checker { if (Array.isArray(nodeOrNodes)) { const data = await this.client.apiRequest<(SymbolResponse | null)[]>("getSymbolsAtLocations", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, locations: nodeOrNodes.map(node => getNodeId(node)), }); return data.map(d => d ? this.objectRegistry.getOrCreateSymbol(d) : undefined); } const data = await this.client.apiRequest("getSymbolAtLocation", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, location: getNodeId(nodeOrNodes as Node), }); return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; @@ -695,7 +819,7 @@ export class Checker { if (typeof positionOrPositions === "number") { const data = await this.client.apiRequest("getSymbolAtPosition", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, file, position: positionOrPositions, }); @@ -703,7 +827,7 @@ export class Checker { } const data = await this.client.apiRequest<(SymbolResponse | null)[]>("getSymbolsAtPositions", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, file, positions: positionOrPositions, }); @@ -716,68 +840,74 @@ export class Checker { if (Array.isArray(symbolOrSymbols)) { const data = await this.client.apiRequest<(TypeResponse | null)[]>("getTypesOfSymbols", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, symbols: symbolOrSymbols.map(s => s.id), }); return data.map(d => d ? this.objectRegistry.getOrCreateType(d) : undefined); } const data = await this.client.apiRequest("getTypeOfSymbol", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, symbol: (symbolOrSymbols as Symbol).id, }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; } - async getDeclaredTypeOfSymbol(symbol: Symbol): Promise { + /** + * Get the declared type of a symbol. Always returns a type; for symbols whose + * declared type cannot be determined the checker yields the error type (use + * {@link Type.isErrorType} to detect it). + */ + async getDeclaredTypeOfSymbol(symbol: Symbol): Promise { const data = await this.client.apiRequest("getDeclaredTypeOfSymbol", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, symbol: symbol.id, }); - return data ? this.objectRegistry.getOrCreateType(data) : undefined; + if (!data) throw new Error(`getDeclaredTypeOfSymbol returned no type for symbol ${symbol.id}`); + return this.objectRegistry.getOrCreateType(data); } async getReferencesToSymbolInFile(file: DocumentIdentifier, symbol: Symbol): Promise { const data = await this.client.apiRequest("getReferencesToSymbolInFile", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, file, symbol: symbol.id, }); - return (data ?? []).map(h => new NodeHandle(h)); + return (data ?? []).map(h => new NodeHandle(h, this.project)); } async getReferencedSymbolsForNode(node: Node, position: number): Promise { const data = await this.client.apiRequest<{ definition: string; symbol?: SymbolResponse; references: string[]; }[] | null>("getReferencedSymbolsForNode", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, node: getNodeId(node), position, }); return (data ?? []).map(entry => ({ - definition: new NodeHandle(entry.definition), + definition: new NodeHandle(entry.definition, this.project), symbol: entry.symbol ? this.objectRegistry.getOrCreateSymbol(entry.symbol) : undefined, - references: (entry.references ?? []).map(h => new NodeHandle(h)), + references: (entry.references ?? []).map(h => new NodeHandle(h, this.project)), })); } async getSignatureUsage(signatureDecl: Node): Promise { const data = await this.client.apiRequest<{ name: string; call?: string; }[] | null>("getSignatureUsages", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, signatureDecl: getNodeId(signatureDecl), }); return (data ?? []).map(entry => ({ - name: new NodeHandle(entry.name), - call: entry.call ? new NodeHandle(entry.call) : undefined, + name: new NodeHandle(entry.name, this.project), + call: entry.call ? new NodeHandle(entry.call, this.project) : undefined, })); } async getCompletionsAtPosition(document: string, position: number, options?: CompletionOptions): Promise { const data = await this.client.apiRequest("getCompletionsAtPosition", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, file: document, position, triggerCharacter: options?.triggerCharacter, @@ -799,14 +929,14 @@ export class Checker { if (Array.isArray(nodeOrNodes)) { const data = await this.client.apiRequest<(TypeResponse | null)[]>("getTypeAtLocations", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, locations: nodeOrNodes.map(node => getNodeId(node)), }); return data.map(d => d ? this.objectRegistry.getOrCreateType(d) : undefined); } const data = await this.client.apiRequest("getTypeAtLocation", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, location: getNodeId(nodeOrNodes as Node), }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -815,7 +945,7 @@ export class Checker { async getSignaturesOfType(type: Type, kind: SignatureKind): Promise { const data = await this.client.apiRequest("getSignaturesOfType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, kind, }); @@ -825,7 +955,7 @@ export class Checker { async getResolvedSignature(node: Node): Promise { const data = await this.client.apiRequest("getResolvedSignature", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, location: getNodeId(node), }); return data ? this.objectRegistry.getOrCreateSignature(data) : undefined; @@ -837,7 +967,7 @@ export class Checker { if (typeof positionOrPositions === "number") { const data = await this.client.apiRequest("getTypeAtPosition", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, file, position: positionOrPositions, }); @@ -845,7 +975,7 @@ export class Checker { } const data = await this.client.apiRequest<(TypeResponse | null)[]>("getTypesAtPositions", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, file, positions: positionOrPositions, }); @@ -862,7 +992,7 @@ export class Checker { const isNode = location && "kind" in location; const data = await this.client.apiRequest("resolveName", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, name, meaning, location: isNode ? getNodeId(location as Node) : undefined, @@ -882,7 +1012,7 @@ export class Checker { async getContextualType(node: Expression): Promise { const data = await this.client.apiRequest("getContextualType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, location: getNodeId(node), }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -891,7 +1021,7 @@ export class Checker { async getBaseTypeOfLiteralType(type: Type): Promise { const data = await this.client.apiRequest("getBaseTypeOfLiteralType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -900,7 +1030,7 @@ export class Checker { async getNonNullableType(type: Type): Promise { const data = await this.client.apiRequest("getNonNullableType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -909,7 +1039,7 @@ export class Checker { async getTypeFromTypeNode(node: TypeNode): Promise { const data = await this.client.apiRequest("getTypeFromTypeNode", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, location: getNodeId(node), }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -918,7 +1048,7 @@ export class Checker { async getWidenedType(type: Type): Promise { const data = await this.client.apiRequest("getWidenedType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -927,7 +1057,7 @@ export class Checker { async getParameterType(signature: Signature, index: number): Promise { const data = await this.client.apiRequest("getParameterType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, signature: signature.id, index, }); @@ -937,7 +1067,7 @@ export class Checker { async isArrayLikeType(type: Type): Promise { return this.client.apiRequest("isArrayLikeType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); } @@ -945,7 +1075,7 @@ export class Checker { async isTypeAssignableTo(source: Type, target: Type): Promise { return this.client.apiRequest("isTypeAssignableTo", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, source: source.id, target: target.id, }); @@ -954,26 +1084,32 @@ export class Checker { async getShorthandAssignmentValueSymbol(node: Node): Promise { const data = await this.client.apiRequest("getShorthandAssignmentValueSymbol", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, location: getNodeId(node), }); return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; } - async getTypeOfSymbolAtLocation(symbol: Symbol, location: Node): Promise { + /** + * Get the type of a symbol as narrowed at a specific location. Always returns + * a type; for symbols whose type cannot be determined the checker yields the + * error type (use {@link Type.isErrorType} to detect it). + */ + async getTypeOfSymbolAtLocation(symbol: Symbol, location: Node): Promise { const data = await this.client.apiRequest("getTypeOfSymbolAtLocation", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, symbol: symbol.id, location: getNodeId(location), }); - return data ? this.objectRegistry.getOrCreateType(data) : undefined; + if (!data) throw new Error(`getTypeOfSymbolAtLocation returned no type for symbol ${symbol.id}`); + return this.objectRegistry.getOrCreateType(data); } private async getIntrinsicType(method: string): Promise { const data = await this.client.apiRequest(method, { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, }); return this.objectRegistry.getOrCreateType(data); } @@ -1015,7 +1151,7 @@ export class Checker { async typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: number): Promise { const binaryData = await this.client.apiRequestBinary("typeToTypeNode", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, location: enclosingDeclaration ? getNodeId(enclosingDeclaration) : undefined, flags, @@ -1027,7 +1163,7 @@ export class Checker { async signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Promise { const binaryData = await this.client.apiRequestBinary("signatureToSignatureDeclaration", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, signature: signature.id, kind, location: enclosingDeclaration ? getNodeId(enclosingDeclaration) : undefined, @@ -1040,7 +1176,7 @@ export class Checker { async typeToString(type: Type, enclosingDeclaration?: Node, flags?: number): Promise { return this.client.apiRequest("typeToString", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, location: enclosingDeclaration ? getNodeId(enclosingDeclaration) : undefined, flags, @@ -1050,15 +1186,31 @@ export class Checker { async isContextSensitive(node: Node): Promise { return this.client.apiRequest("isContextSensitive", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, location: getNodeId(node), }); } + async isArrayType(type: Type): Promise { + return this.client.apiRequest("isArrayType", { + snapshot: this.snapshotId, + project: this.project.id, + type: type.id, + }); + } + + async isTupleType(type: Type): Promise { + return this.client.apiRequest("isTupleType", { + snapshot: this.snapshotId, + project: this.project.id, + type: type.id, + }); + } + async getReturnTypeOfSignature(signature: Signature): Promise { const data = await this.client.apiRequest("getReturnTypeOfSignature", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, signature: signature.id, }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -1067,7 +1219,7 @@ export class Checker { async getRestTypeOfSignature(signature: Signature): Promise { const data = await this.client.apiRequest("getRestTypeOfSignature", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, signature: signature.id, }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -1076,7 +1228,7 @@ export class Checker { async getTypePredicateOfSignature(signature: Signature): Promise { const data = await this.client.apiRequest("getTypePredicateOfSignature", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, signature: signature.id, }); if (!data) return undefined; @@ -1088,19 +1240,32 @@ export class Checker { } as TypePredicate; } - async getBaseTypes(type: Type): Promise { + /** + * Get the base types of a class or interface type. A type with no base types + * yields an empty array. + */ + async getBaseTypes(type: InterfaceType): Promise { const data = await this.client.apiRequest("getBaseTypes", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); return data ? data.map(d => this.objectRegistry.getOrCreateType(d)) : []; } + async getApparentType(type: Type): Promise { + const data = await this.client.apiRequest("getApparentType", { + snapshot: this.snapshotId, + project: this.project.id, + type: type.id, + }); + return data ? this.objectRegistry.getOrCreateType(data) : undefined; + } + async getPropertiesOfType(type: Type): Promise { const data = await this.client.apiRequest("getPropertiesOfType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); return data ? data.map(d => this.objectRegistry.getOrCreateSymbol(d)) : []; @@ -1109,7 +1274,7 @@ export class Checker { async getIndexInfosOfType(type: Type): Promise { const data = await this.client.apiRequest("getIndexInfosOfType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); if (!data) return []; @@ -1117,23 +1282,171 @@ export class Checker { keyType: this.objectRegistry.getOrCreateType(d.keyType), valueType: this.objectRegistry.getOrCreateType(d.valueType), isReadonly: d.isReadonly ?? false, - declaration: d.declaration ? new NodeHandle(d.declaration) : undefined, + declaration: d.declaration ? new NodeHandle(d.declaration, this.project) : undefined, })); } - async getConstraintOfTypeParameter(type: Type): Promise { + /** + * Get the constraint of a type parameter (the `T` in ``), or + * undefined if it has none. + */ + async getConstraintOfTypeParameter(type: TypeParameter): Promise { const data = await this.client.apiRequest("getConstraintOfTypeParameter", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; } - async getTypeArguments(type: Type): Promise { + async getBaseConstraintOfType(type: Type): Promise { + const data = await this.client.apiRequest("getBaseConstraintOfType", { + snapshot: this.snapshotId, + project: this.project.id, + type: type.id, + }); + return data ? this.objectRegistry.getOrCreateType(data) : undefined; + } + + async getPropertyOfType(type: Type, name: string): Promise { + const data = await this.client.apiRequest("getPropertyOfType", { + snapshot: this.snapshotId, + project: this.project.id, + type: type.id, + name, + }); + return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; + } + + async getConstantValue(node: Node): Promise { + const data = await this.client.apiRequest("getConstantValue", { + snapshot: this.snapshotId, + project: this.project.id, + location: getNodeId(node), + }); + return data ?? undefined; + } + + async getSignatureFromDeclaration(node: Node): Promise { + const data = await this.client.apiRequest("getSignatureFromDeclaration", { + snapshot: this.snapshotId, + project: this.project.id, + location: getNodeId(node), + }); + return data ? this.objectRegistry.getOrCreateSignature(data) : undefined; + } + + async getExportSpecifierLocalTargetSymbol(node: Node): Promise { + const data = await this.client.apiRequest("getExportSpecifierLocalTargetSymbol", { + snapshot: this.snapshotId, + project: this.project.id, + location: getNodeId(node), + }); + return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; + } + + /** + * Follow all aliases to get the original symbol. Always returns a symbol; for + * an unresolved alias the checker yields the unknown symbol (use + * {@link Checker.isUnknownSymbol} to detect it). + */ + async getAliasedSymbol(symbol: Symbol): Promise { + const data = await this.client.apiRequest("getAliasedSymbol", { + snapshot: this.snapshotId, + project: this.project.id, + symbol: symbol.id, + }); + if (!data) throw new Error(`getAliasedSymbol returned no symbol for symbol ${symbol.id}`); + return this.objectRegistry.getOrCreateSymbol(data); + } + + async getImmediateAliasedSymbol(symbol: Symbol): Promise { + const data = await this.client.apiRequest("getImmediateAliasedSymbol", { + snapshot: this.snapshotId, + project: this.project.id, + symbol: symbol.id, + }); + return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; + } + + /** + * Fetch (once, then cache) the handle ids of the per-checker singleton + * symbols (unknown, undefined, arguments). These ids are stable for the life + * of the project's checker, so identity checks against them are local after + * the first call. + */ + private getWellKnownSymbols(): Promise<{ unknown: number; undefined: number; arguments: number; }> { + return this.wellKnownSymbols ??= this.client.apiRequest<{ unknown: number; undefined: number; arguments: number; }>("getWellKnownSymbols", { + snapshot: this.snapshotId, + project: this.project.id, + }); + } + + /** + * Returns `true` if the symbol is the checker's "unknown" symbol (e.g. the + * result of {@link Checker.getAliasedSymbol} on an unresolved alias). + */ + async isUnknownSymbol(symbol: Symbol): Promise { + return symbol.id === (await this.getWellKnownSymbols()).unknown; + } + + /** + * Returns `true` if the symbol is the checker's "undefined" symbol. + */ + async isUndefinedSymbol(symbol: Symbol): Promise { + return symbol.id === (await this.getWellKnownSymbols()).undefined; + } + + /** + * Returns `true` if the symbol is the checker's "arguments" symbol. + */ + async isArgumentsSymbol(symbol: Symbol): Promise { + return symbol.id === (await this.getWellKnownSymbols()).arguments; + } + + async getExportsOfModule(symbol: Symbol): Promise { + const data = await this.client.apiRequest("getExportsOfModule", { + snapshot: this.snapshotId, + project: this.project.id, + symbol: symbol.id, + }); + return data ? data.map(d => this.objectRegistry.getOrCreateSymbol(d)) : []; + } + + async getMemberInModuleExports(symbol: Symbol, name: string): Promise { + const data = await this.client.apiRequest("getMemberInModuleExports", { + snapshot: this.snapshotId, + project: this.project.id, + symbol: symbol.id, + name, + }); + return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; + } + + async getJsDocTagsOfSymbol(symbol: Symbol): Promise { + const data = await this.client.apiRequest("getJsDocTags", { + snapshot: this.snapshotId, + project: this.project.id, + symbol: symbol.id, + }); + return data ?? []; + } + + async getDocumentationCommentOfSymbol(symbol: Symbol): Promise { + return this.client.apiRequest("getDocumentationComment", { + snapshot: this.snapshotId, + project: this.project.id, + symbol: symbol.id, + }); + } + + /** + * Get the type arguments of a type reference (e.g. the `string` in `Array`). + */ + async getTypeArguments(type: TypeReference): Promise { const data = await this.client.apiRequest("getTypeArguments", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); return data ? data.map(d => this.objectRegistry.getOrCreateType(d)) : []; @@ -1141,9 +1454,9 @@ export class Checker { } export interface PrintNodeOptions { - preserveSourceNewlines?: boolean; - neverAsciiEscape?: boolean; - terminateUnterminatedLiterals?: boolean; + preserveSourceNewlines?: boolean | undefined; + neverAsciiEscape?: boolean | undefined; + terminateUnterminatedLiterals?: boolean | undefined; } export class Emitter { @@ -1164,22 +1477,30 @@ export class Emitter { } export class NodeHandle { + /** + * The project this handle was produced in, used as the default for {@link resolve}. + * Node handles are only meaningful within a project's program, so the producing project + * is remembered so callers don't have to pass it explicitly. + */ + private readonly canonicalProject: Project; readonly index: number; readonly kind: SyntaxKind; readonly path: Path; - constructor(handle: string) { + constructor(handle: string, canonicalProject: Project) { const parsed = parseNodeHandle(handle); this.index = parsed.index; this.kind = parsed.kind; this.path = parsed.path; + this.canonicalProject = canonicalProject; } /** - * Resolve this handle to the actual AST node by fetching the source file - * from the given project and looking up the node by index. + * Resolve this handle to the actual AST node by fetching the source file from a project + * and looking up the node by index. If no project is passed, the project that produced + * the handle is used. */ - async resolve(project: Project): Promise { + async resolve(project: Project = this.canonicalProject): Promise { const sourceFile = await project.program.getSourceFile(this.path); if (!sourceFile) { return undefined; @@ -1193,7 +1514,7 @@ export interface ReferencedSymbolEntry { /** The node handle for the symbol's definition. */ definition: NodeHandle; /** The resolved symbol for the definition, if available. */ - symbol?: Symbol; + symbol?: Symbol | undefined; /** The node handles for each reference to the symbol. */ references: NodeHandle[]; } @@ -1203,50 +1524,92 @@ export interface SignatureUsage { /** The node handle for the name reference. */ name: NodeHandle; /** The node handle for the call expression, if the reference is invoked. */ - call?: NodeHandle; + call?: NodeHandle | undefined; } export class Symbol { private objectRegistry: SnapshotObjectRegistry; + /** + * The project this symbol was first observed in, used as the default project for + * lookups that need a project context (members/exports/parent). Symbols are shared + * snapshot-wide, so these lookups can otherwise be ambiguous about which project to use. + */ + private readonly canonicalProject: Project; readonly id: number; + /** The escaped (`__String`) name, used as the key in member/export tables. */ + readonly escapedName: __String; + /** The display name (escaped underscores removed). */ readonly name: string; readonly flags: SymbolFlags; readonly checkFlags: number; readonly declarations: readonly NodeHandle[]; readonly valueDeclaration: NodeHandle | undefined; - readonly parent!: number; - readonly exportSymbol!: number; + private readonly parent!: number; + private readonly exportSymbol!: number; + private membersCache: Promise> | undefined; + private exportsCache: Promise> | undefined; constructor(data: SymbolResponse, objectRegistry: SnapshotObjectRegistry) { this.objectRegistry = objectRegistry; this.id = data.id; - this.name = data.name; + this.escapedName = data.name; + this.name = unescapeLeadingUnderscores(data.name); this.flags = data.flags; this.checkFlags = data.checkFlags; - this.declarations = (data.declarations ?? []).map(d => new NodeHandle(d)); - this.valueDeclaration = data.valueDeclaration ? new NodeHandle(data.valueDeclaration) : undefined; + const canonicalProject = objectRegistry.getProject(data.project); + if (!canonicalProject) { + throw new Error(`Symbol ${data.id} references unknown canonical project '${data.project}'`); + } + this.canonicalProject = canonicalProject; + this.declarations = (data.declarations ?? []).map(d => new NodeHandle(d, canonicalProject)); + this.valueDeclaration = data.valueDeclaration ? new NodeHandle(data.valueDeclaration, canonicalProject) : undefined; if (data.parent !== undefined) this.parent = data.parent; if (data.exportSymbol !== undefined) this.exportSymbol = data.exportSymbol; } async getParent(): Promise { - return this.objectRegistry.fetchSymbol(this, "getParentOfSymbol", this.parent); + return this.objectRegistry.fetchSymbol(this, "getParentOfSymbol", this.parent, this.canonicalProject.id); + } + + /** + * Get this symbol's members keyed by escaped name. The result is cached on + * the symbol, so repeated calls do not round-trip to the server. + */ + getMembers(): Promise> { + return this.membersCache ??= this.fetchSymbolTable("getMembersOfSymbol"); } - async getMembers(): Promise { - return this.objectRegistry.fetchSymbols(this, "getMembersOfSymbol"); + /** + * Get this symbol's exports keyed by escaped name. The result is cached on + * the symbol, so repeated calls do not round-trip to the server. + */ + getExports(): Promise> { + return this.exportsCache ??= this.fetchSymbolTable("getExportsOfSymbol"); } - async getExports(): Promise { - return this.objectRegistry.fetchSymbols(this, "getExportsOfSymbol"); + private async fetchSymbolTable(method: string): Promise> { + const symbols = await this.objectRegistry.fetchSymbols(this, method, undefined, this.canonicalProject.id); + const table = new Map<__String, Symbol>(); + for (const symbol of symbols) { + table.set(symbol.escapedName, symbol); + } + return table; } async getExportSymbol(): Promise { if (!this.exportSymbol) return this; - return this.objectRegistry.fetchSymbol(this, "getExportSymbolOfSymbol", this.exportSymbol); + return this.objectRegistry.fetchSymbol(this, "getExportSymbolOfSymbol", this.exportSymbol, this.canonicalProject.id); + } + + async getJsDocTags(checker: Checker): Promise { + return checker.getJsDocTagsOfSymbol(this); + } + + async getDocumentationComment(checker: Checker): Promise { + return checker.getDocumentationCommentOfSymbol(this); } } @@ -1279,6 +1642,9 @@ class TypeObject implements Type { readonly baseType!: number; readonly substConstraint!: number; + private trueType: number | false; // false if not yet loaded + private falseType: number | false; // false if not yet loaded + constructor(data: TypeResponse, objectRegistry: ProjectObjectRegistry) { this.objectRegistry = objectRegistry; @@ -1311,6 +1677,9 @@ class TypeObject implements Type { if (data.extendsType !== undefined) this.extendsType = data.extendsType; if (data.baseType !== undefined) this.baseType = data.baseType; if (data.substConstraint !== undefined) this.substConstraint = data.substConstraint; + + this.trueType = false; + this.falseType = false; } async getSymbol(): Promise { @@ -1333,20 +1702,26 @@ class TypeObject implements Type { return this.objectRegistry.fetchType(this, "getRegularTypeOfType", this.regularType); } - async getTypes(): Promise { + async getTypes(): Promise { + // Only union, intersection, and template literal types have constituent + // types; any other kind has none, so return undefined rather than sending + // a request the server cannot satisfy. + if (!(this.flags & (TypeFlags.UnionOrIntersection | TypeFlags.TemplateLiteral))) { + return undefined; + } return this.objectRegistry.fetchTypes(this, "getTypesOfType"); } - async getTypeParameters(): Promise { - return this.objectRegistry.fetchTypes(this, "getTypeParametersOfType", this.typeParameters); + async getTypeParameters(): Promise { + return this.objectRegistry.fetchTypes(this, "getTypeParametersOfType", this.typeParameters) as Promise; } - async getOuterTypeParameters(): Promise { - return this.objectRegistry.fetchTypes(this, "getOuterTypeParametersOfType", this.outerTypeParameters); + async getOuterTypeParameters(): Promise { + return this.objectRegistry.fetchTypes(this, "getOuterTypeParametersOfType", this.outerTypeParameters) as Promise; } - async getLocalTypeParameters(): Promise { - return this.objectRegistry.fetchTypes(this, "getLocalTypeParametersOfType", this.localTypeParameters); + async getLocalTypeParameters(): Promise { + return this.objectRegistry.fetchTypes(this, "getLocalTypeParametersOfType", this.localTypeParameters) as Promise; } async getAliasTypeArguments(): Promise { @@ -1376,6 +1751,195 @@ class TypeObject implements Type { async getConstraint(): Promise { return this.objectRegistry.fetchType(this, "getConstraintOfType", this.substConstraint); } + + async getTrueType(): Promise { + const result = await this.objectRegistry.fetchType(this, "getTrueTypeOfConditionalType", this.trueType); + this.trueType = result.id; + return result; + } + + async getFalseType(): Promise { + const result = await this.objectRegistry.fetchType(this, "getFalseTypeOfConditionalType", this.falseType); + this.falseType = result.id; + return result; + } + + /** + * Get the base types of this type. Returns `undefined` for any type that is + * not a class or interface. + */ + async getBaseTypes(): Promise { + if (!this.isClassOrInterface()) { + return undefined; + } + return this.objectRegistry.fetchBaseTypes(this); + } + + isClassOrInterface(): this is InterfaceType { + return isClassOrInterfaceType(this); + } + + isUnionType(): this is UnionType { + return isUnionType(this); + } + + isIntersectionType(): this is IntersectionType { + return isIntersectionType(this); + } + + isObjectType(): this is ObjectType { + return isObjectType(this); + } + + isIntrinsicType(): this is IntrinsicType { + return isIntrinsicType(this); + } + + isErrorType(): boolean { + return isErrorType(this); + } + + isLiteralType(): this is LiteralType { + return isLiteralType(this); + } + + isStringLiteralType(): this is StringLiteralType { + return isStringLiteralType(this); + } + + isNumberLiteralType(): this is NumberLiteralType { + return isNumberLiteralType(this); + } + + isBigIntLiteralType(): this is BigIntLiteralType { + return isBigIntLiteralType(this); + } + + isBooleanLiteralType(): this is BooleanLiteralType { + return isBooleanLiteralType(this); + } + + isTypeReference(): this is TypeReference { + return isTypeReference(this); + } + + isTupleType(): this is TupleType { + return isTupleType(this); + } + + isIndexType(): this is IndexType { + return isIndexType(this); + } + + isIndexedAccessType(): this is IndexedAccessType { + return isIndexedAccessType(this); + } + + isConditionalType(): this is ConditionalType { + return isConditionalType(this); + } + + isSubstitutionType(): this is SubstitutionType { + return isSubstitutionType(this); + } + + isTemplateLiteralType(): this is TemplateLiteralType { + return isTemplateLiteralType(this); + } + + isStringMappingType(): this is StringMappingType { + return isStringMappingType(this); + } + + isTypeParameter(): this is TypeParameter { + return isTypeParameter(this); + } +} + +export function isUnionType(type: Type): type is UnionType { + return (type.flags & TypeFlags.Union) !== 0; +} + +export function isIntersectionType(type: Type): type is IntersectionType { + return (type.flags & TypeFlags.Intersection) !== 0; +} + +export function isObjectType(type: Type): type is ObjectType { + return (type.flags & TypeFlags.Object) !== 0; +} + +export function isClassOrInterfaceType(type: Type): type is InterfaceType { + return isObjectType(type) && (type.objectFlags & ObjectFlags.ClassOrInterface) !== 0; +} + +export function isIntrinsicType(type: Type): type is IntrinsicType { + return (type.flags & TypeFlags.Intrinsic) !== 0; +} + +/** + * Whether this is the error type — the placeholder the checker produces when a + * type cannot be determined (e.g. an unresolved reference). It is an intrinsic + * type named `"error"` (this covers both the singleton error type and the + * per-alias error types manufactured for unresolved type alias references). + */ +export function isErrorType(type: Type): boolean { + return isIntrinsicType(type) && type.intrinsicName === "error"; +} + +export function isLiteralType(type: Type): type is LiteralType { + return (type.flags & TypeFlags.Literal) !== 0; +} + +export function isStringLiteralType(type: Type): type is StringLiteralType { + return (type.flags & TypeFlags.StringLiteral) !== 0; +} + +export function isNumberLiteralType(type: Type): type is NumberLiteralType { + return (type.flags & TypeFlags.NumberLiteral) !== 0; +} + +export function isBigIntLiteralType(type: Type): type is BigIntLiteralType { + return (type.flags & TypeFlags.BigIntLiteral) !== 0; +} + +export function isBooleanLiteralType(type: Type): type is BooleanLiteralType { + return (type.flags & TypeFlags.BooleanLiteral) !== 0; +} + +export function isTypeReference(type: Type): type is TypeReference { + return isObjectType(type) && (type.objectFlags & ObjectFlags.Reference) !== 0; +} + +export function isTupleType(type: Type): type is TupleType { + return isObjectType(type) && (type.objectFlags & ObjectFlags.Tuple) !== 0; +} + +export function isIndexType(type: Type): type is IndexType { + return (type.flags & TypeFlags.Index) !== 0; +} + +export function isIndexedAccessType(type: Type): type is IndexedAccessType { + return (type.flags & TypeFlags.IndexedAccess) !== 0; +} + +export function isConditionalType(type: Type): type is ConditionalType { + return (type.flags & TypeFlags.Conditional) !== 0; +} + +export function isSubstitutionType(type: Type): type is SubstitutionType { + return (type.flags & TypeFlags.Substitution) !== 0; +} + +export function isTemplateLiteralType(type: Type): type is TemplateLiteralType { + return (type.flags & TypeFlags.TemplateLiteral) !== 0; +} + +export function isStringMappingType(type: Type): type is StringMappingType { + return (type.flags & TypeFlags.StringMapping) !== 0; +} + +export function isTypeParameter(type: Type): type is TypeParameter { + return (type.flags & TypeFlags.TypeParameter) !== 0; } export class Signature { @@ -1389,19 +1953,19 @@ export class Signature { readonly thisParameter?: number | undefined; readonly target?: number | undefined; - constructor(data: SignatureResponse, objectRegistry: ProjectObjectRegistry) { + constructor(data: SignatureResponse, project: Project, objectRegistry: ProjectObjectRegistry) { this.id = data.id; this.flags = data.flags; this.objectRegistry = objectRegistry; - this.declaration = data.declaration ? new NodeHandle(data.declaration) : undefined; + this.declaration = data.declaration ? new NodeHandle(data.declaration, project) : undefined; this.typeParameters = data.typeParameters ?? []; this.parameters = data.parameters ?? []; this.thisParameter = data.thisParameter; this.target = data.target; } - async getTypeParameters(): Promise { - return this.objectRegistry.fetchTypes(this, "getTypeParametersOfSignature", this.typeParameters); + async getTypeParameters(): Promise { + return this.objectRegistry.fetchTypes(this, "getTypeParametersOfSignature", this.typeParameters) as Promise; } async getParameters(): Promise { diff --git a/_packages/native-preview/src/api/async/types.ts b/_packages/native-preview/src/api/async/types.ts index 955d36178d2..ccc619227f1 100644 --- a/_packages/native-preview/src/api/async/types.ts +++ b/_packages/native-preview/src/api/async/types.ts @@ -22,10 +22,11 @@ import type { * ``` */ export interface Type { + /** Type flags — use to determine the specific kind of type. */ + readonly flags: TypeFlags; + /** Unique identifier for this type */ readonly id: number; - /** Type flags — use to determine the specific kind of type */ - readonly flags: TypeFlags; /** Get the symbol associated with this type, if any */ getSymbol(): Promise; @@ -35,6 +36,56 @@ export interface Type { /** Get the symbol of the type alias this type was instantiated from, if any */ getAliasSymbol(): Promise; + + /** + * Get the base types of this type, or `undefined` if it is not a class or + * interface type. + */ + getBaseTypes(): Promise; + + /** Whether this type is a class or interface type */ + isClassOrInterface(): this is InterfaceType; + /** Whether this type is a union type */ + isUnionType(): this is UnionType; + /** Whether this type is an intersection type */ + isIntersectionType(): this is IntersectionType; + /** Whether this type is an object type */ + isObjectType(): this is ObjectType; + /** Whether this type is an intrinsic primitive type */ + isIntrinsicType(): this is IntrinsicType; + /** + * Whether this is the error type — the placeholder produced when a type + * cannot be determined (e.g. an unresolved reference). + */ + isErrorType(): boolean; + /** Whether this type is a literal type */ + isLiteralType(): this is LiteralType; + /** Whether this type is a string literal type */ + isStringLiteralType(): this is StringLiteralType; + /** Whether this type is a number literal type */ + isNumberLiteralType(): this is NumberLiteralType; + /** Whether this type is a bigint literal type */ + isBigIntLiteralType(): this is BigIntLiteralType; + /** Whether this type is a boolean literal type */ + isBooleanLiteralType(): this is BooleanLiteralType; + /** Whether this type is a type reference */ + isTypeReference(): this is TypeReference; + /** Whether this type is a tuple type */ + isTupleType(): this is TupleType; + /** Whether this type is an index type (`keyof T`) */ + isIndexType(): this is IndexType; + /** Whether this type is an indexed access type (`T[K]`) */ + isIndexedAccessType(): this is IndexedAccessType; + /** Whether this type is a conditional type */ + isConditionalType(): this is ConditionalType; + /** Whether this type is a substitution type */ + isSubstitutionType(): this is SubstitutionType; + /** Whether this type is a template literal type */ + isTemplateLiteralType(): this is TemplateLiteralType; + /** Whether this type is a string mapping type */ + isStringMappingType(): this is StringMappingType; + /** Whether this type is a type parameter */ + isTypeParameter(): this is TypeParameter; } /** @@ -79,7 +130,7 @@ export interface BooleanLiteralType extends LiteralType { /** Object types (TypeFlags.Object) */ export interface ObjectType extends Type { - /** Object flags — use to determine the specific kind of object type */ + /** Object flags — use to determine the specific kind of object type. */ readonly objectFlags: ObjectFlags; } @@ -92,11 +143,11 @@ export interface TypeReference extends ObjectType { /** Interface types — classes and interfaces (ObjectFlags.ClassOrInterface) */ export interface InterfaceType extends TypeReference { /** Get all type parameters (outer + local, excluding thisType) */ - getTypeParameters(): Promise; + getTypeParameters(): Promise; /** Get outer type parameters from enclosing declarations */ - getOuterTypeParameters(): Promise; + getOuterTypeParameters(): Promise; /** Get local type parameters declared on this interface/class */ - getLocalTypeParameters(): Promise; + getLocalTypeParameters(): Promise; } /** Tuple types (ObjectFlags.Tuple) */ @@ -126,7 +177,7 @@ export interface IntersectionType extends UnionOrIntersectionType { /** Type parameters (TypeFlags.TypeParameter) */ export interface TypeParameter extends Type { /** True if this is the synthetic `this` type of an interface, class, or tuple */ - readonly isThisType?: boolean; + readonly isThisType?: boolean | undefined; } /** Index types — keyof T (TypeFlags.Index) */ @@ -149,6 +200,10 @@ export interface ConditionalType extends Type { getCheckType(): Promise; /** Get the extends type U in `T extends U ? X : Y` */ getExtendsType(): Promise; + /** Get the true type X in `T extends U ? X : Y` */ + getTrueType(): Promise; + /** Get the false type Y in `T extends U ? X : Y` */ + getFalseType(): Promise; } /** Substitution types (TypeFlags.Substitution) */ @@ -227,32 +282,42 @@ export interface IndexInfo { /** Whether the index signature is readonly */ readonly isReadonly: boolean; /** The index signature declaration, if any */ - readonly declaration?: NodeHandle; + readonly declaration?: NodeHandle | undefined; +} + +/** + * A single JSDoc tag attached to a symbol — e.g. `@param`, `@returns`. + */ +export interface JSDocTagInfo { + /** The tag name, without the leading `@` — e.g. `"param"`. */ + readonly name: string; + /** The rendered tag text, if any — e.g. `"a the first number"` for `@param a the first number`. */ + readonly text?: string | undefined; } export interface CompletionEntryLabelDetails { - detail?: string; - description?: string; + detail?: string | undefined; + description?: string | undefined; } /** Options for {@link Checker.getCompletionsAtPosition}. */ export interface CompletionOptions { - triggerCharacter?: string; + triggerCharacter?: string | undefined; /** Include a `symbol` property on each completion entry. Only populated for symbol-based completions (not keywords or literals). */ - includeSymbol?: boolean; + includeSymbol?: boolean | undefined; } /** A single completion item returned by {@link Checker.getCompletionsAtPosition}. */ export interface CompletionEntry { readonly name: string; - readonly kind?: CompletionItemKind; - readonly sortText?: string; - readonly insertText?: string; - readonly filterText?: string; - readonly detail?: string; - readonly labelDetails?: CompletionEntryLabelDetails; + readonly kind?: CompletionItemKind | undefined; + readonly sortText?: string | undefined; + readonly insertText?: string | undefined; + readonly filterText?: string | undefined; + readonly detail?: string | undefined; + readonly labelDetails?: CompletionEntryLabelDetails | undefined; /** The symbol associated with this completion entry. Only set when `includeSymbol: true` is passed and a symbol is available. */ - readonly symbol?: Symbol; + readonly symbol?: Symbol | undefined; } /** The result of {@link Checker.getCompletionsAtPosition}. */ @@ -266,7 +331,7 @@ export interface CompletionInfo { */ export interface Diagnostic { /** File name of the source file this diagnostic belongs to, if any */ - readonly fileName?: string; + readonly fileName?: string | undefined; /** Start position of the diagnostic */ readonly pos: number; /** End position of the diagnostic */ @@ -278,11 +343,11 @@ export interface Diagnostic { /** Localized diagnostic message text */ readonly text: string; /** Whether this diagnostic highlights unnecessary code */ - readonly reportsUnnecessary?: boolean; + readonly reportsUnnecessary?: boolean | undefined; /** Whether this diagnostic highlights deprecated code */ - readonly reportsDeprecated?: boolean; + readonly reportsDeprecated?: boolean | undefined; /** Chained diagnostic messages */ - readonly messageChain?: readonly Diagnostic[]; + readonly messageChain?: readonly Diagnostic[] | undefined; /** Related diagnostic information */ - readonly relatedInformation?: readonly Diagnostic[]; + readonly relatedInformation?: readonly Diagnostic[] | undefined; } diff --git a/_packages/native-preview/src/api/node/encoder.ts b/_packages/native-preview/src/api/node/encoder.ts index bffa243a92b..d026565071a 100644 --- a/_packages/native-preview/src/api/node/encoder.ts +++ b/_packages/native-preview/src/api/node/encoder.ts @@ -1,6 +1,5 @@ import type { FileReference, - JSDocParameterOrPropertyTag, LiteralLikeNode, Node, NodeArray, @@ -88,15 +87,6 @@ function cachedEncoder(): TextEncoder { function getChildrenPropertyMask(node: Node): number { const kind = node.kind; - // Special handling for JSDocParameterTag and JSDocPropertyTag - if (kind === SyntaxKind.JSDocParameterTag || kind === SyntaxKind.JSDocPropertyTag) { - const tag = node as JSDocParameterOrPropertyTag; - if (tag.isNameFirst) { - return (boolBit(tag.tagName) << 0) | (boolBit(tag.name) << 1) | (boolBit(tag.typeExpression) << 2) | (boolBit(tag.comment) << 3); - } - return (boolBit(tag.tagName) << 0) | (boolBit(tag.typeExpression) << 1) | (boolBit(tag.name) << 2) | (boolBit(tag.comment) << 3); - } - const props = childProperties[kind]; if (!props) { return 0; @@ -112,10 +102,6 @@ function getChildrenPropertyMask(node: Node): number { return mask; } -function boolBit(v: unknown): number { - return isChildPresent(v) ? 1 : 0; -} - // A child is "present" if it's non-null/non-undefined. // This matches the Go encoder's behavior where non-nil NodeLists (even empty) // are treated as present, and only nil NodeLists are absent. @@ -196,13 +182,7 @@ function getNodeData(node: Node, strs: StringTable, extendedData: number[], stru } function getChildPropertiesForNode(node: Node): readonly (string | undefined)[] | undefined { - const kind = node.kind; - if (kind === SyntaxKind.JSDocParameterTag || kind === SyntaxKind.JSDocPropertyTag) { - return (node as JSDocParameterOrPropertyTag).isNameFirst - ? ["tagName", "name", "typeExpression", "comment"] - : ["tagName", "typeExpression", "name", "comment"]; - } - return childProperties[kind]; + return childProperties[node.kind]; } // Returns whether a value is a NodeArray (array-like with pos and end). diff --git a/_packages/native-preview/src/api/node/msgpack.ts b/_packages/native-preview/src/api/node/msgpack.ts index 6e32df4283d..50248d27bda 100644 --- a/_packages/native-preview/src/api/node/msgpack.ts +++ b/_packages/native-preview/src/api/node/msgpack.ts @@ -1,6 +1,8 @@ // Minimal msgpack encoder/decoder. // Supports: arrays, unsigned integers, strings, booleans, binary data. +import { Wtf8Decoder } from "./wtf8.ts"; + // ── MessagePack format constants ──────────────────────────────────── export const MSGPACK_FIXARRAY3 = 0x93; // 3-element fixarray export const MSGPACK_BIN8 = 0xc4; @@ -39,7 +41,7 @@ export function writeBinHeader(buf: Uint8Array, off: number, len: number): numbe } const encoder = new TextEncoder(); -const decoder = new TextDecoder(); +const decoder = new Wtf8Decoder(); export class MsgpackWriter { private buf: Uint8Array; diff --git a/_packages/native-preview/src/api/node/node.generated.ts b/_packages/native-preview/src/api/node/node.generated.ts index ff74677b3fa..555c7c70333 100644 --- a/_packages/native-preview/src/api/node/node.generated.ts +++ b/_packages/native-preview/src/api/node/node.generated.ts @@ -36,6 +36,12 @@ import { } from "./protocol.ts"; export class RemoteNodeList extends Array implements NodeArray { + // Inherited Array methods like filter/map/slice use ArraySpeciesCreate, which would + // otherwise call `new RemoteNodeList(length)` and fail. Produce a plain Array instead. + static get [Symbol.species](): ArrayConstructor { + return Array; + } + parent: RemoteNode; hasTrailingComma?: boolean; transformFlags: number = 0; @@ -217,9 +223,11 @@ export class RemoteNode extends RemoteNodeBase implements Node { return result; } } - const result = child.forEachNode(visitNode); - if (result) { - return result; + else { + const result = child.forEachNode(visitNode); + if (result) { + return result; + } } } else if (child.kind !== SyntaxKind.JSDoc) { @@ -320,44 +328,7 @@ export class RemoteNode extends RemoteNodeBase implements Node { } private getNamedChild(propertyName: string): RemoteNode | RemoteNodeList | undefined { - // JSDocPropertyTag and JSDocParameterTag have runtime-dependent child order based on isNameFirst. - // Handle them before the general childProperties lookup. const kind = this.kind; - if (kind === SyntaxKind.JSDocPropertyTag) { - let order: number; - switch (propertyName) { - case "name": - order = this.isNameFirst ? 0 : 1; - break; - case "typeExpression": - order = this.isNameFirst ? 1 : 0; - break; - default: - return undefined; - } - return this.getChildAtOrder(order); - } - else if (kind === SyntaxKind.JSDocParameterTag) { - let order: number; - switch (propertyName) { - case "tagName": - order = 0; - break; - case "name": - order = this.isNameFirst ? 1 : 2; - break; - case "typeExpression": - order = this.isNameFirst ? 2 : 1; - break; - case "comment": - order = 3; - break; - default: - return undefined; - } - return this.getChildAtOrder(order); - } - const propertyNames = childProperties[kind]; if (!propertyNames) { return undefined; diff --git a/_packages/native-preview/src/api/node/node.infrastructure.ts b/_packages/native-preview/src/api/node/node.infrastructure.ts index f5f3d842e4a..a1e00cbe031 100644 --- a/_packages/native-preview/src/api/node/node.infrastructure.ts +++ b/_packages/native-preview/src/api/node/node.infrastructure.ts @@ -2,7 +2,6 @@ import { type FileReference, ModifierFlags, type Node, - type NodeArray, SyntaxKind, } from "../../ast/index.ts"; import { @@ -39,6 +38,11 @@ export const NODE_EXTENDED_DATA_MASK = 0x00_ff_ff_ff; // source file, avoiding a direct dependency on RemoteSourceFile. // ═══════════════════════════════════════════════════════════════════════════ +// The global type is not available in earlier @types/node versions +export interface TextDecoder { + decode(input?: ArrayBufferView | ArrayBufferLike): string; +} + export interface SourceFileInfo { readonly _offsetNodes: number; readonly _offsetStringTableOffsets: number; diff --git a/_packages/native-preview/src/api/node/node.ts b/_packages/native-preview/src/api/node/node.ts index 2bd0f41eaaa..fc7d56290e0 100644 --- a/_packages/native-preview/src/api/node/node.ts +++ b/_packages/native-preview/src/api/node/node.ts @@ -14,6 +14,7 @@ import { import { NODE_EXTENDED_DATA_MASK, type SourceFileInfo, + type TextDecoder, } from "./node.infrastructure.ts"; import { HEADER_OFFSET_EXTENDED_DATA, @@ -26,6 +27,7 @@ import { NODE_OFFSET_KIND, NODE_OFFSET_PARENT, } from "./protocol.ts"; +import { Wtf8Decoder } from "./wtf8.ts"; // Re-export everything consumers need from the other two files. export { RemoteNode, RemoteNodeList } from "./node.generated.ts"; @@ -45,6 +47,13 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { readonly _offsetExtendedData: number; readonly _offsetStructuredData: number; readonly _decoder: TextDecoder; + private _cachedText: string | undefined; + private _cachedReferencedFiles: readonly FileReference[] | undefined; + private _cachedTypeReferenceDirectives: readonly FileReference[] | undefined; + private _cachedLibReferenceDirectives: readonly FileReference[] | undefined; + private _cachedImports: readonly Node[] | undefined; + private _cachedModuleAugmentations: readonly Node[] | undefined; + private _cachedAmbientModuleNames: readonly string[] | undefined; constructor(data: Uint8Array, decoder: TextDecoder) { const view = new DataView(data.buffer, data.byteOffset, data.byteLength); @@ -159,33 +168,51 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { } get referencedFiles(): readonly FileReference[] { + if (this._cachedReferencedFiles !== undefined) return this._cachedReferencedFiles; const offset = this.view.getUint32(this.extendedDataOffset + 20, true); - return this.readFileReferences(offset); + const files = this.readFileReferences(offset); + this._cachedReferencedFiles = files; + return files; } get typeReferenceDirectives(): readonly FileReference[] { + if (this._cachedTypeReferenceDirectives !== undefined) return this._cachedTypeReferenceDirectives; const offset = this.view.getUint32(this.extendedDataOffset + 24, true); - return this.readFileReferences(offset); + const directives = this.readFileReferences(offset); + this._cachedTypeReferenceDirectives = directives; + return directives; } get libReferenceDirectives(): readonly FileReference[] { + if (this._cachedLibReferenceDirectives !== undefined) return this._cachedLibReferenceDirectives; const offset = this.view.getUint32(this.extendedDataOffset + 28, true); - return this.readFileReferences(offset); + const directives = this.readFileReferences(offset); + this._cachedLibReferenceDirectives = directives; + return directives; } get imports(): readonly Node[] { + if (this._cachedImports !== undefined) return this._cachedImports; const offset = this.view.getUint32(this.extendedDataOffset + 32, true); - return this.readNodeIndexArray(offset); + const imports = this.readNodeIndexArray(offset); + this._cachedImports = imports; + return imports; } get moduleAugmentations(): readonly Node[] { + if (this._cachedModuleAugmentations !== undefined) return this._cachedModuleAugmentations; const offset = this.view.getUint32(this.extendedDataOffset + 36, true); - return this.readNodeIndexArray(offset); + const moduleAugmentations = this.readNodeIndexArray(offset); + this._cachedModuleAugmentations = moduleAugmentations; + return moduleAugmentations; } get ambientModuleNames(): readonly string[] { + if (this._cachedAmbientModuleNames !== undefined) return this._cachedAmbientModuleNames; const offset = this.view.getUint32(this.extendedDataOffset + 40, true); - return this.readStringArray(offset); + const names = this.readStringArray(offset); + this._cachedAmbientModuleNames = names; + return names; } get externalModuleIndicator(): Node | true | undefined { @@ -198,6 +225,13 @@ export class RemoteSourceFile extends RemoteNode implements SourceFileInfo { get isDeclarationFile(): boolean { return (this.flags & NodeFlags.Ambient) !== 0; } + + get text(): string { + if (this._cachedText !== undefined) return this._cachedText; + const text = super.text!; + this._cachedText = text; + return text; + } } /** @@ -258,7 +292,7 @@ export function parseNodeHandle(handle: string): ParsedNodeHandle { * (e.g. from typeToTypeNode) that don't have a source file. */ export function decodeNode(data: Uint8Array): Node { - const sf = new RemoteSourceFile(data, new TextDecoder()); + const sf = new RemoteSourceFile(data, new Wtf8Decoder()); return sf as unknown as Node; } diff --git a/_packages/native-preview/src/api/node/wtf8.ts b/_packages/native-preview/src/api/node/wtf8.ts new file mode 100644 index 00000000000..45bba64a910 --- /dev/null +++ b/_packages/native-preview/src/api/node/wtf8.ts @@ -0,0 +1,72 @@ +import { Buffer } from "node:buffer"; + +const surrogateLeadByte = 0xED; +const surrogateSecondByteMin = 0xA0; +const surrogateSecondByteMax = 0xBF; +const continuationByteMin = 0x80; +const continuationByteMax = 0xBF; +type DecodeOptions = Parameters[1]; + +function isWtf8Surrogate(bytes: Uint8Array, index: number): boolean { + return index + 2 < bytes.length + && bytes[index] === surrogateLeadByte + && bytes[index + 1] >= surrogateSecondByteMin + && bytes[index + 1] <= surrogateSecondByteMax + && bytes[index + 2] >= continuationByteMin + && bytes[index + 2] <= continuationByteMax; +} + +function getSurrogateCodeUnit(bytes: Uint8Array, index: number): number { + return 0xD000 | ((bytes[index + 1] & 0x3F) << 6) | (bytes[index + 2] & 0x3F); +} + +function hasSurrogateLeadByte(bytes: Uint8Array): boolean { + return Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).indexOf(surrogateLeadByte) >= 0; +} + +function toUint8Array(input: NodeJS.AllowSharedBufferSource): Uint8Array { + if (input instanceof Uint8Array) { + return input; + } + if (ArrayBuffer.isView(input)) { + return new Uint8Array(input.buffer, input.byteOffset, input.byteLength); + } + return new Uint8Array(input); +} + +export class Wtf8Decoder extends TextDecoder { + override decode(input?: NodeJS.AllowSharedBufferSource, options?: DecodeOptions): string { + if (input === undefined) { + return super.decode(input, options); + } + + const bytes = toUint8Array(input); + if (!hasSurrogateLeadByte(bytes)) { + return super.decode(bytes, options); + } + + const parts: string[] = []; + let segmentStart = 0; + + for (let i = 0; i < bytes.length; i++) { + if (!isWtf8Surrogate(bytes, i)) { + continue; + } + + if (segmentStart < i) { + parts.push(super.decode(bytes.subarray(segmentStart, i), options)); + } + parts.push(String.fromCharCode(getSurrogateCodeUnit(bytes, i))); + i += 2; + segmentStart = i + 1; + } + + if (segmentStart === 0) { + return super.decode(bytes, options); + } + if (segmentStart < bytes.length) { + parts.push(super.decode(bytes.subarray(segmentStart), options)); + } + return parts.join(""); + } +} diff --git a/_packages/native-preview/src/api/proto.ts b/_packages/native-preview/src/api/proto.ts index 0edeb9b5274..2bb9a258c79 100644 --- a/_packages/native-preview/src/api/proto.ts +++ b/_packages/native-preview/src/api/proto.ts @@ -1,4 +1,9 @@ import type { CompletionItemKind } from "#enums/completionItemKind"; +import type { ModuleKind } from "#enums/moduleKind"; +import type { + __String, + Path, +} from "../ast/index.ts"; import { documentURIToFileName, fileNameToDocumentURI, @@ -64,8 +69,37 @@ export interface ConfigResponse { } export interface LSPUpdateSnapshotParams { - /** Path to a tsconfig.json file to open in the new snapshot */ + /** + * @deprecated Use {@link openProjects} instead. + * Path to a tsconfig.json file to open in the new snapshot. + */ openProject?: string; + /** + * tsconfig.json files to open/load in the new snapshot. Opens are ref-counted + * and persist across snapshots until closed via {@link closeProjects}. + */ + openProjects?: DocumentIdentifier[]; + /** + * tsconfig.json files to release in the new snapshot. A project is only unloaded + * once every API client that opened it closes it. + */ + closeProjects?: DocumentIdentifier[]; + /** + * Files to keep open for the API client, mirroring LSP's `textDocument/didOpen`. + * For each file, ancestor directories are searched for a tsconfig that contains it; + * if one is found, that configured project is loaded and becomes the file's default + * project. Otherwise the file is loaded into the inferred project (e.g. a d.ts in + * node_modules that is not part of any project's import graph). Opens persist across + * subsequent snapshots until the file is closed via {@link closeFiles}. + * After calling updateSnapshot with openFiles, getDefaultProjectForFile returns the + * resolved configured or inferred project. + */ + openFiles?: DocumentIdentifier[]; + /** + * Files to release in the new snapshot. A file is only fully closed once every + * API client that opened it closes it. + */ + closeFiles?: DocumentIdentifier[]; } export interface FileChangeSummary { @@ -83,6 +117,22 @@ export interface UpdateSnapshotParams extends LSPUpdateSnapshotParams { fileChanges?: FileChanges; } +/** + * Builds the wire request for updateSnapshot, applying the deprecated `openProject` + * compatibility shim: a single `openProject` is folded into `openProjects` and is + * never sent on the wire. + */ +export function toUpdateSnapshotRequest(params?: UpdateSnapshotParams): UpdateSnapshotParams { + const { openProject, openProjects, ...rest } = params ?? {}; + const mergedOpenProjects = openProject !== undefined + ? [resolveFileName(openProject), ...(openProjects ?? [])] + : openProjects; + return { + ...rest, + ...(mergedOpenProjects !== undefined ? { openProjects: mergedOpenProjects } : {}), + }; +} + /** * Changes to source files within a single project. */ @@ -116,7 +166,7 @@ export interface UpdateSnapshotResponse { } export interface ProjectResponse { - id: string; + id: Path; configFileName: string; compilerOptions: Record; rootFiles: string[]; @@ -127,9 +177,23 @@ export interface SourceFileResponse { data: string; } +export interface SourceFileMetadata { + isDefaultLibrary: boolean; + isFromExternalLibrary: boolean; + packageJsonType: string; + packageJsonDirectory: string; + impliedNodeFormat: ModuleKind; +} + export interface SymbolResponse { id: number; - name: string; + /** + * The project the symbol was first observed in. Used as the default project for + * follow-up lookups that need a project context (e.g. members/exports), since symbols + * are shared snapshot-wide and such lookups can vary by project. + */ + project: Path; + name: __String; flags: number; checkFlags: number; declarations?: string[]; diff --git a/_packages/native-preview/src/api/sync/api.ts b/_packages/native-preview/src/api/sync/api.ts index 40224ef06e8..40ccc52d043 100644 --- a/_packages/native-preview/src/api/sync/api.ts +++ b/_packages/native-preview/src/api/sync/api.ts @@ -10,6 +10,7 @@ import { CompletionItemKind } from "#enums/completionItemKind"; import { DiagnosticCategory } from "#enums/diagnosticCategory"; import { ElementFlags } from "#enums/elementFlags"; +import { ModuleKind } from "#enums/moduleKind"; import { NodeBuilderFlags } from "#enums/nodeBuilderFlags"; import { ObjectFlags } from "#enums/objectFlags"; import { SignatureFlags } from "#enums/signatureFlags"; @@ -18,6 +19,7 @@ import { SymbolFlags } from "#enums/symbolFlags"; import { TypeFlags } from "#enums/typeFlags"; import { TypePredicateKind } from "#enums/typePredicateKind"; import { + type __String, type Expression, type Identifier, ModifierFlags, @@ -26,6 +28,7 @@ import { type SourceFile, type SyntaxKind, type TypeNode, + unescapeLeadingUnderscores, } from "../../ast/index.ts"; import { encodeNode, @@ -39,6 +42,7 @@ import { readSourceFileHash, RemoteSourceFile, } from "../node/node.ts"; +import { Wtf8Decoder } from "../node/wtf8.ts"; import type { APIOptions, LSPConnectionOptions, @@ -58,13 +62,17 @@ import type { ProfileResult, ProjectResponse, SignatureResponse, + SourceFileMetadata, SymbolResponse, TypePredicateResponse, TypeResponse, UpdateSnapshotParams, UpdateSnapshotResponse, } from "../proto.ts"; -import { resolveFileName } from "../proto.ts"; +import { + resolveFileName, + toUpdateSnapshotRequest, +} from "../proto.ts"; import { SourceFileCache } from "../sourceFileCache.ts"; import { Client, @@ -89,6 +97,7 @@ import type { InterfaceType, IntersectionType, IntrinsicType, + JSDocTagInfo, LiteralType, NumberLiteralType, ObjectType, @@ -107,9 +116,9 @@ import type { UnionType, } from "./types.ts"; -export { CompletionItemKind, DiagnosticCategory, ElementFlags, ModifierFlags, NodeBuilderFlags, ObjectFlags, SignatureFlags, SignatureKind, SymbolFlags, TypeFlags, TypePredicateKind }; -export type { APIOptions, ClientSocketOptions, ClientSpawnOptions, DocumentIdentifier, DocumentPosition, LSPConnectionOptions }; -export type { AssertsIdentifierTypePredicate, AssertsThisTypePredicate, BigIntLiteralType, BooleanLiteralType, CompletionEntry, CompletionInfo, CompletionOptions, ConditionalType, Diagnostic, FreshableType, IdentifierTypePredicate, IndexedAccessType, IndexInfo, IndexType, InterfaceType, IntersectionType, IntrinsicType, LiteralType, NumberLiteralType, ObjectType, StringLiteralType, StringMappingType, SubstitutionType, TemplateLiteralType, ThisTypePredicate, TupleType, Type, TypeParameter, TypePredicate, TypePredicateBase, TypeReference, UnionOrIntersectionType, UnionType }; +export { CompletionItemKind, DiagnosticCategory, ElementFlags, ModifierFlags, ModuleKind, NodeBuilderFlags, ObjectFlags, SignatureFlags, SignatureKind, SymbolFlags, TypeFlags, TypePredicateKind }; +export type { APIOptions, ClientSocketOptions, ClientSpawnOptions, DocumentIdentifier, DocumentPosition, LSPConnectionOptions, SourceFileMetadata }; +export type { AssertsIdentifierTypePredicate, AssertsThisTypePredicate, BigIntLiteralType, BooleanLiteralType, CompletionEntry, CompletionInfo, CompletionOptions, ConditionalType, Diagnostic, FreshableType, IdentifierTypePredicate, IndexedAccessType, IndexInfo, IndexType, InterfaceType, IntersectionType, IntrinsicType, JSDocTagInfo, LiteralType, NumberLiteralType, ObjectType, StringLiteralType, StringMappingType, SubstitutionType, TemplateLiteralType, ThisTypePredicate, TupleType, Type, TypeParameter, TypePredicate, TypePredicateBase, TypeReference, UnionOrIntersectionType, UnionType }; export { documentURIToFileName, fileNameToDocumentURI } from "../path.ts"; export class API { @@ -121,7 +130,7 @@ export class API { private latestSnapshot: Snapshot | undefined; readonly internal: InternalAPI; - constructor(options: APIOptions | LSPConnectionOptions) { + constructor(options: APIOptions | LSPConnectionOptions = {}) { this.client = new Client(options); this.sourceFileCache = new SourceFileCache(); this.internal = new InternalAPI(this.client, () => this.ensureInitialized()); @@ -155,11 +164,7 @@ export class API { updateSnapshot(params?: FromLSP extends true ? LSPUpdateSnapshotParams : UpdateSnapshotParams): Snapshot { this.ensureInitialized(); - const requestParams: UpdateSnapshotParams = params ?? {}; - if (requestParams.openProject) { - requestParams.openProject = resolveFileName(requestParams.openProject); - } - + const requestParams = toUpdateSnapshotRequest(params); const data = this.client.apiRequest("updateSnapshot", requestParams); // Retain cached source files from previous snapshot for unchanged files @@ -255,9 +260,9 @@ export class Snapshot { this.client = client; this.toPath = toPath; this.onDispose = onDispose; - this.snapshotRegistry = new SnapshotObjectRegistry(client, this.id); - this.projectMap = new Map(); + this.snapshotRegistry = new SnapshotObjectRegistry(client, this.id, projectId => this.projectMap.get(projectId)); + for (const projData of data.projects) { const project = new Project(projData, this.id, client, sourceFileCache, toPath, this.snapshotRegistry); this.projectMap.set(toPath(projData.configFileName), project); @@ -315,10 +320,17 @@ class SnapshotObjectRegistry { private readonly symbols: Map = new Map(); private readonly client: Client; private readonly snapshotId: number; + private readonly resolveProject: (projectId: Path) => Project | undefined; - constructor(client: Client, snapshotId: number) { + constructor(client: Client, snapshotId: number, resolveProject: (projectId: Path) => Project | undefined) { this.client = client; this.snapshotId = snapshotId; + this.resolveProject = resolveProject; + } + + /** Resolve a project id (a config file path) to its Project within this snapshot. */ + getProject(projectId: Path): Project | undefined { + return this.resolveProject(projectId); } getOrCreateSymbol(data: SymbolResponse): Symbol { @@ -338,7 +350,7 @@ class SnapshotObjectRegistry { this.symbols.clear(); } - fetchSymbol(source: Symbol | Signature | Type, method: string, handle: number | undefined, projectId?: string): Symbol { + fetchSymbol(source: Symbol | Signature | Type, method: string, handle: number | undefined, projectId?: Path): Symbol { if (!handle) return undefined as unknown as Symbol; const cached = this.getSymbol(handle); if (cached) return cached; @@ -352,7 +364,7 @@ class SnapshotObjectRegistry { return this.getOrCreateSymbol(data); } - fetchSymbols(source: Symbol | Signature | Type, method: string, handles?: readonly number[], projectId?: string): readonly Symbol[] { + fetchSymbols(source: Symbol | Signature | Type, method: string, handles?: readonly number[], projectId?: Path): readonly Symbol[] { if (handles) { const result = new Array(handles.length); let allCached = true; @@ -379,7 +391,7 @@ class SnapshotObjectRegistry { class ProjectObjectRegistry { private client: Client; private snapshotId: number; - private projectId: string; + private project: Project; private snapshotRegistry: SnapshotObjectRegistry; private types: Map = new Map(); private signatures: Map = new Map(); @@ -387,12 +399,12 @@ class ProjectObjectRegistry { constructor( client: Client, snapshotId: number, - projectId: string, + project: Project, snapshotRegistry: SnapshotObjectRegistry, ) { this.client = client; this.snapshotId = snapshotId; - this.projectId = projectId; + this.project = project; this.snapshotRegistry = snapshotRegistry; } @@ -420,7 +432,7 @@ class ProjectObjectRegistry { getOrCreateSignature(data: SignatureResponse): Signature { let sig = this.signatures.get(data.id); if (!sig) { - sig = new Signature(data, this); + sig = new Signature(data, this.project, this); this.signatures.set(data.id, sig); } return sig; @@ -435,14 +447,16 @@ class ProjectObjectRegistry { this.signatures.clear(); } - fetchType(source: Symbol | Signature | Type, method: string, handle: number | undefined): T { - if (!handle) return undefined as unknown as T; - const cached = this.getType(handle); - if (cached) return cached as unknown as T; + fetchType(source: Symbol | Signature | Type, method: string, handle: number | false | undefined): T { + if (handle !== false) { + if (!handle) return undefined as unknown as T; + const cached = this.getType(handle); + if (cached) return cached as unknown as T; + } const data = this.client.apiRequest(method, { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, objectId: source.id, }); if (!data) throw new Error(`${method} returned null type for ${source.constructor.name} ${source.id}`); @@ -450,7 +464,7 @@ class ProjectObjectRegistry { } fetchSymbol(source: Symbol | Signature | Type, method: string, handle: number | undefined): Symbol { - return this.snapshotRegistry.fetchSymbol(source, method, handle, this.projectId); + return this.snapshotRegistry.fetchSymbol(source, method, handle, this.project.id); } fetchSignature(source: Symbol | Signature | Type, method: string, handle: number | undefined): Signature { @@ -460,7 +474,7 @@ class ProjectObjectRegistry { const data = this.client.apiRequest(method, { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, objectId: source.id, }); if (!data) throw new Error(`${method} returned null signature for ${source.constructor.name} ${source.id}`); @@ -483,7 +497,7 @@ class ProjectObjectRegistry { } const typesData = this.client.apiRequest(method, { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, objectId: source.id, }); if (typesData == null) return []; @@ -491,12 +505,24 @@ class ProjectObjectRegistry { } fetchSymbols(source: Symbol | Signature | Type, method: string, handles?: readonly number[]): readonly Symbol[] { - return this.snapshotRegistry.fetchSymbols(source, method, handles, this.projectId); + return this.snapshotRegistry.fetchSymbols(source, method, handles, this.project.id); + } + + // getBaseTypes is a checker-level endpoint keyed by `type` (not `objectId`), + // so it cannot go through fetchTypes. This helper reuses that server method. + fetchBaseTypes(source: Type): readonly Type[] { + const typesData = this.client.apiRequest("getBaseTypes", { + snapshot: this.snapshotId, + project: this.project.id, + type: source.id, + }); + if (typesData == null) return []; + return typesData.map(data => this.getOrCreateType(data)); } } export class Project { - readonly id: string; + readonly id: Path; readonly configFileName: string; readonly compilerOptions: Record; readonly rootFiles: readonly string[]; @@ -526,10 +552,10 @@ export class Project { sourceFileCache, toPath, ); - const objectRegistry = new ProjectObjectRegistry(client, snapshotId, this.id, snapshotRegistry); + const objectRegistry = new ProjectObjectRegistry(client, snapshotId, this, snapshotRegistry); this.checker = new Checker( snapshotId, - this.id, + this, client, objectRegistry, ); @@ -543,15 +569,16 @@ export class Project { export class Program { private snapshotId: number; - private projectId: string; + private projectId: Path; private client: Client; private sourceFileCache: SourceFileCache; private toPath: (fileName: string) => Path; - private decoder = new TextDecoder(); + private decoder = new Wtf8Decoder(); + private sourceFileMetadataCache = new Map(); constructor( snapshotId: number, - projectId: string, + projectId: Path, client: Client, sourceFileCache: SourceFileCache, toPath: (fileName: string) => Path, @@ -592,6 +619,67 @@ export class Program { return this.sourceFileCache.set(path, sourceFile, parseOptionsKey, contentHash, this.snapshotId, this.projectId); } + getSourceFileNames(): readonly string[] { + const data = this.client.apiRequest("getSourceFileNames", { + snapshot: this.snapshotId, + project: this.projectId, + }); + return data ?? []; + } + + /** + * Returns program-stored metadata for the given source file, or `undefined` if the file + * is not part of the program. Metadata is fetched lazily per file and cached on this + * `Program` instance. + */ + getSourceFileMetadata(fileName: string): SourceFileMetadata | undefined { + return this.getSourceFileMetadataByPath(this.toPath(fileName)); + } + + /** + * Returns program-stored metadata for the source file at the given path, or `undefined` + * if the file is not part of the program. Like {@link getSourceFileMetadata}, but skips + * the file name to path conversion. Metadata is fetched lazily per file and cached on + * this `Program` instance. + */ + getSourceFileMetadataByPath(path: Path): SourceFileMetadata | undefined { + let metadata = this.sourceFileMetadataCache.get(path); + if (metadata === undefined) { + metadata = this.fetchSourceFileMetadata(path); + this.sourceFileMetadataCache.set(path, metadata); + } + return metadata; + } + + private fetchSourceFileMetadata(path: Path): SourceFileMetadata | undefined { + const data = this.client.apiRequest("getSourceFileMetadata", { + snapshot: this.snapshotId, + project: this.projectId, + file: path, + }); + return data ?? undefined; + } + + /** + * Returns whether the given source file was loaded as part of an external library + * (e.g. a dependency resolved from `node_modules`). The underlying program metadata is + * fetched lazily per file and cached on this `Program` instance. + */ + isSourceFileFromExternalLibrary(file: SourceFile): boolean { + const metadata = this.getSourceFileMetadataByPath(file.path); + return metadata?.isFromExternalLibrary ?? false; + } + + /** + * Returns whether the given source file is a default library file (e.g. `lib.d.ts`). + * The underlying program metadata is fetched lazily per file and cached on this + * `Program` instance. + */ + isSourceFileDefaultLibrary(file: SourceFile): boolean { + const metadata = this.getSourceFileMetadataByPath(file.path); + return metadata?.isDefaultLibrary ?? false; + } + /** * Get syntactic (parse) diagnostics for a specific file or all files. * @param file - Optional file to get diagnostics for. If omitted, returns diagnostics for all files. @@ -605,6 +693,19 @@ export class Program { return data ?? []; } + /** + * Get binder diagnostics for a specific file or all files. + * @param file - Optional file to get diagnostics for. If omitted, returns diagnostics for all files. + */ + getBindDiagnostics(file?: DocumentIdentifier): readonly Diagnostic[] { + const data = this.client.apiRequest("getBindDiagnostics", { + snapshot: this.snapshotId, + project: this.projectId, + ...(file !== undefined ? { file } : {}), + }); + return data ?? []; + } + /** * Get semantic (type-check) diagnostics for a specific file or all files. * @param file - Optional file to get diagnostics for. If omitted, returns diagnostics for all files. @@ -644,6 +745,28 @@ export class Program { return data ?? []; } + /** + * Get program-wide diagnostics for the project, including compiler options diagnostics. + */ + getProgramDiagnostics(): readonly Diagnostic[] { + const data = this.client.apiRequest("getProgramDiagnostics", { + snapshot: this.snapshotId, + project: this.projectId, + }); + return data ?? []; + } + + /** + * Get global (non-file-specific) semantic diagnostics for the project. + */ + getGlobalDiagnostics(): readonly Diagnostic[] { + const data = this.client.apiRequest("getGlobalDiagnostics", { + snapshot: this.snapshotId, + project: this.projectId, + }); + return data ?? []; + } + /** * Get config file parsing diagnostics for the project. */ @@ -658,18 +781,19 @@ export class Program { export class Checker { private snapshotId: number; - private projectId: string; + private project: Project; private client: Client; private objectRegistry: ProjectObjectRegistry; + private wellKnownSymbols: { unknown: number; undefined: number; arguments: number; } | undefined; constructor( snapshotId: number, - projectId: string, + project: Project, client: Client, objectRegistry: ProjectObjectRegistry, ) { this.snapshotId = snapshotId; - this.projectId = projectId; + this.project = project; this.client = client; this.objectRegistry = objectRegistry; } @@ -684,14 +808,14 @@ export class Checker { if (Array.isArray(nodeOrNodes)) { const data = this.client.apiRequest<(SymbolResponse | null)[]>("getSymbolsAtLocations", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, locations: nodeOrNodes.map(node => getNodeId(node)), }); return data.map(d => d ? this.objectRegistry.getOrCreateSymbol(d) : undefined); } const data = this.client.apiRequest("getSymbolAtLocation", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, location: getNodeId(nodeOrNodes as Node), }); return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; @@ -703,7 +827,7 @@ export class Checker { if (typeof positionOrPositions === "number") { const data = this.client.apiRequest("getSymbolAtPosition", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, file, position: positionOrPositions, }); @@ -711,7 +835,7 @@ export class Checker { } const data = this.client.apiRequest<(SymbolResponse | null)[]>("getSymbolsAtPositions", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, file, positions: positionOrPositions, }); @@ -724,68 +848,74 @@ export class Checker { if (Array.isArray(symbolOrSymbols)) { const data = this.client.apiRequest<(TypeResponse | null)[]>("getTypesOfSymbols", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, symbols: symbolOrSymbols.map(s => s.id), }); return data.map(d => d ? this.objectRegistry.getOrCreateType(d) : undefined); } const data = this.client.apiRequest("getTypeOfSymbol", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, symbol: (symbolOrSymbols as Symbol).id, }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; } - getDeclaredTypeOfSymbol(symbol: Symbol): Type | undefined { + /** + * Get the declared type of a symbol. Always returns a type; for symbols whose + * declared type cannot be determined the checker yields the error type (use + * {@link Type.isErrorType} to detect it). + */ + getDeclaredTypeOfSymbol(symbol: Symbol): Type { const data = this.client.apiRequest("getDeclaredTypeOfSymbol", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, symbol: symbol.id, }); - return data ? this.objectRegistry.getOrCreateType(data) : undefined; + if (!data) throw new Error(`getDeclaredTypeOfSymbol returned no type for symbol ${symbol.id}`); + return this.objectRegistry.getOrCreateType(data); } getReferencesToSymbolInFile(file: DocumentIdentifier, symbol: Symbol): NodeHandle[] { const data = this.client.apiRequest("getReferencesToSymbolInFile", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, file, symbol: symbol.id, }); - return (data ?? []).map(h => new NodeHandle(h)); + return (data ?? []).map(h => new NodeHandle(h, this.project)); } getReferencedSymbolsForNode(node: Node, position: number): ReferencedSymbolEntry[] { const data = this.client.apiRequest<{ definition: string; symbol?: SymbolResponse; references: string[]; }[] | null>("getReferencedSymbolsForNode", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, node: getNodeId(node), position, }); return (data ?? []).map(entry => ({ - definition: new NodeHandle(entry.definition), + definition: new NodeHandle(entry.definition, this.project), symbol: entry.symbol ? this.objectRegistry.getOrCreateSymbol(entry.symbol) : undefined, - references: (entry.references ?? []).map(h => new NodeHandle(h)), + references: (entry.references ?? []).map(h => new NodeHandle(h, this.project)), })); } getSignatureUsage(signatureDecl: Node): SignatureUsage[] { const data = this.client.apiRequest<{ name: string; call?: string; }[] | null>("getSignatureUsages", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, signatureDecl: getNodeId(signatureDecl), }); return (data ?? []).map(entry => ({ - name: new NodeHandle(entry.name), - call: entry.call ? new NodeHandle(entry.call) : undefined, + name: new NodeHandle(entry.name, this.project), + call: entry.call ? new NodeHandle(entry.call, this.project) : undefined, })); } getCompletionsAtPosition(document: string, position: number, options?: CompletionOptions): CompletionInfo | undefined { const data = this.client.apiRequest("getCompletionsAtPosition", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, file: document, position, triggerCharacter: options?.triggerCharacter, @@ -807,14 +937,14 @@ export class Checker { if (Array.isArray(nodeOrNodes)) { const data = this.client.apiRequest<(TypeResponse | null)[]>("getTypeAtLocations", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, locations: nodeOrNodes.map(node => getNodeId(node)), }); return data.map(d => d ? this.objectRegistry.getOrCreateType(d) : undefined); } const data = this.client.apiRequest("getTypeAtLocation", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, location: getNodeId(nodeOrNodes as Node), }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -823,7 +953,7 @@ export class Checker { getSignaturesOfType(type: Type, kind: SignatureKind): readonly Signature[] { const data = this.client.apiRequest("getSignaturesOfType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, kind, }); @@ -833,7 +963,7 @@ export class Checker { getResolvedSignature(node: Node): Signature | undefined { const data = this.client.apiRequest("getResolvedSignature", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, location: getNodeId(node), }); return data ? this.objectRegistry.getOrCreateSignature(data) : undefined; @@ -845,7 +975,7 @@ export class Checker { if (typeof positionOrPositions === "number") { const data = this.client.apiRequest("getTypeAtPosition", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, file, position: positionOrPositions, }); @@ -853,7 +983,7 @@ export class Checker { } const data = this.client.apiRequest<(TypeResponse | null)[]>("getTypesAtPositions", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, file, positions: positionOrPositions, }); @@ -870,7 +1000,7 @@ export class Checker { const isNode = location && "kind" in location; const data = this.client.apiRequest("resolveName", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, name, meaning, location: isNode ? getNodeId(location as Node) : undefined, @@ -890,7 +1020,7 @@ export class Checker { getContextualType(node: Expression): Type | undefined { const data = this.client.apiRequest("getContextualType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, location: getNodeId(node), }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -899,7 +1029,7 @@ export class Checker { getBaseTypeOfLiteralType(type: Type): Type | undefined { const data = this.client.apiRequest("getBaseTypeOfLiteralType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -908,7 +1038,7 @@ export class Checker { getNonNullableType(type: Type): Type | undefined { const data = this.client.apiRequest("getNonNullableType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -917,7 +1047,7 @@ export class Checker { getTypeFromTypeNode(node: TypeNode): Type | undefined { const data = this.client.apiRequest("getTypeFromTypeNode", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, location: getNodeId(node), }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -926,7 +1056,7 @@ export class Checker { getWidenedType(type: Type): Type | undefined { const data = this.client.apiRequest("getWidenedType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -935,7 +1065,7 @@ export class Checker { getParameterType(signature: Signature, index: number): Type | undefined { const data = this.client.apiRequest("getParameterType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, signature: signature.id, index, }); @@ -945,7 +1075,7 @@ export class Checker { isArrayLikeType(type: Type): boolean { return this.client.apiRequest("isArrayLikeType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); } @@ -953,7 +1083,7 @@ export class Checker { isTypeAssignableTo(source: Type, target: Type): boolean { return this.client.apiRequest("isTypeAssignableTo", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, source: source.id, target: target.id, }); @@ -962,26 +1092,32 @@ export class Checker { getShorthandAssignmentValueSymbol(node: Node): Symbol | undefined { const data = this.client.apiRequest("getShorthandAssignmentValueSymbol", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, location: getNodeId(node), }); return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; } - getTypeOfSymbolAtLocation(symbol: Symbol, location: Node): Type | undefined { + /** + * Get the type of a symbol as narrowed at a specific location. Always returns + * a type; for symbols whose type cannot be determined the checker yields the + * error type (use {@link Type.isErrorType} to detect it). + */ + getTypeOfSymbolAtLocation(symbol: Symbol, location: Node): Type { const data = this.client.apiRequest("getTypeOfSymbolAtLocation", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, symbol: symbol.id, location: getNodeId(location), }); - return data ? this.objectRegistry.getOrCreateType(data) : undefined; + if (!data) throw new Error(`getTypeOfSymbolAtLocation returned no type for symbol ${symbol.id}`); + return this.objectRegistry.getOrCreateType(data); } private getIntrinsicType(method: string): Type { const data = this.client.apiRequest(method, { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, }); return this.objectRegistry.getOrCreateType(data); } @@ -1023,7 +1159,7 @@ export class Checker { typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: number): TypeNode | undefined { const binaryData = this.client.apiRequestBinary("typeToTypeNode", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, location: enclosingDeclaration ? getNodeId(enclosingDeclaration) : undefined, flags, @@ -1035,7 +1171,7 @@ export class Checker { signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Node | undefined { const binaryData = this.client.apiRequestBinary("signatureToSignatureDeclaration", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, signature: signature.id, kind, location: enclosingDeclaration ? getNodeId(enclosingDeclaration) : undefined, @@ -1048,7 +1184,7 @@ export class Checker { typeToString(type: Type, enclosingDeclaration?: Node, flags?: number): string { return this.client.apiRequest("typeToString", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, location: enclosingDeclaration ? getNodeId(enclosingDeclaration) : undefined, flags, @@ -1058,15 +1194,31 @@ export class Checker { isContextSensitive(node: Node): boolean { return this.client.apiRequest("isContextSensitive", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, location: getNodeId(node), }); } + isArrayType(type: Type): boolean { + return this.client.apiRequest("isArrayType", { + snapshot: this.snapshotId, + project: this.project.id, + type: type.id, + }); + } + + isTupleType(type: Type): boolean { + return this.client.apiRequest("isTupleType", { + snapshot: this.snapshotId, + project: this.project.id, + type: type.id, + }); + } + getReturnTypeOfSignature(signature: Signature): Type | undefined { const data = this.client.apiRequest("getReturnTypeOfSignature", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, signature: signature.id, }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -1075,7 +1227,7 @@ export class Checker { getRestTypeOfSignature(signature: Signature): Type | undefined { const data = this.client.apiRequest("getRestTypeOfSignature", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, signature: signature.id, }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; @@ -1084,7 +1236,7 @@ export class Checker { getTypePredicateOfSignature(signature: Signature): TypePredicate | undefined { const data = this.client.apiRequest("getTypePredicateOfSignature", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, signature: signature.id, }); if (!data) return undefined; @@ -1096,19 +1248,32 @@ export class Checker { } as TypePredicate; } - getBaseTypes(type: Type): readonly Type[] { + /** + * Get the base types of a class or interface type. A type with no base types + * yields an empty array. + */ + getBaseTypes(type: InterfaceType): readonly Type[] { const data = this.client.apiRequest("getBaseTypes", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); return data ? data.map(d => this.objectRegistry.getOrCreateType(d)) : []; } + getApparentType(type: Type): Type | undefined { + const data = this.client.apiRequest("getApparentType", { + snapshot: this.snapshotId, + project: this.project.id, + type: type.id, + }); + return data ? this.objectRegistry.getOrCreateType(data) : undefined; + } + getPropertiesOfType(type: Type): readonly Symbol[] { const data = this.client.apiRequest("getPropertiesOfType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); return data ? data.map(d => this.objectRegistry.getOrCreateSymbol(d)) : []; @@ -1117,7 +1282,7 @@ export class Checker { getIndexInfosOfType(type: Type): readonly IndexInfo[] { const data = this.client.apiRequest("getIndexInfosOfType", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); if (!data) return []; @@ -1125,23 +1290,171 @@ export class Checker { keyType: this.objectRegistry.getOrCreateType(d.keyType), valueType: this.objectRegistry.getOrCreateType(d.valueType), isReadonly: d.isReadonly ?? false, - declaration: d.declaration ? new NodeHandle(d.declaration) : undefined, + declaration: d.declaration ? new NodeHandle(d.declaration, this.project) : undefined, })); } - getConstraintOfTypeParameter(type: Type): Type | undefined { + /** + * Get the constraint of a type parameter (the `T` in ``), or + * undefined if it has none. + */ + getConstraintOfTypeParameter(type: TypeParameter): Type | undefined { const data = this.client.apiRequest("getConstraintOfTypeParameter", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); return data ? this.objectRegistry.getOrCreateType(data) : undefined; } - getTypeArguments(type: Type): readonly Type[] { + getBaseConstraintOfType(type: Type): Type | undefined { + const data = this.client.apiRequest("getBaseConstraintOfType", { + snapshot: this.snapshotId, + project: this.project.id, + type: type.id, + }); + return data ? this.objectRegistry.getOrCreateType(data) : undefined; + } + + getPropertyOfType(type: Type, name: string): Symbol | undefined { + const data = this.client.apiRequest("getPropertyOfType", { + snapshot: this.snapshotId, + project: this.project.id, + type: type.id, + name, + }); + return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; + } + + getConstantValue(node: Node): string | number | undefined { + const data = this.client.apiRequest("getConstantValue", { + snapshot: this.snapshotId, + project: this.project.id, + location: getNodeId(node), + }); + return data ?? undefined; + } + + getSignatureFromDeclaration(node: Node): Signature | undefined { + const data = this.client.apiRequest("getSignatureFromDeclaration", { + snapshot: this.snapshotId, + project: this.project.id, + location: getNodeId(node), + }); + return data ? this.objectRegistry.getOrCreateSignature(data) : undefined; + } + + getExportSpecifierLocalTargetSymbol(node: Node): Symbol | undefined { + const data = this.client.apiRequest("getExportSpecifierLocalTargetSymbol", { + snapshot: this.snapshotId, + project: this.project.id, + location: getNodeId(node), + }); + return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; + } + + /** + * Follow all aliases to get the original symbol. Always returns a symbol; for + * an unresolved alias the checker yields the unknown symbol (use + * {@link Checker.isUnknownSymbol} to detect it). + */ + getAliasedSymbol(symbol: Symbol): Symbol { + const data = this.client.apiRequest("getAliasedSymbol", { + snapshot: this.snapshotId, + project: this.project.id, + symbol: symbol.id, + }); + if (!data) throw new Error(`getAliasedSymbol returned no symbol for symbol ${symbol.id}`); + return this.objectRegistry.getOrCreateSymbol(data); + } + + getImmediateAliasedSymbol(symbol: Symbol): Symbol | undefined { + const data = this.client.apiRequest("getImmediateAliasedSymbol", { + snapshot: this.snapshotId, + project: this.project.id, + symbol: symbol.id, + }); + return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; + } + + /** + * Fetch (once, then cache) the handle ids of the per-checker singleton + * symbols (unknown, undefined, arguments). These ids are stable for the life + * of the project's checker, so identity checks against them are local after + * the first call. + */ + private getWellKnownSymbols(): { unknown: number; undefined: number; arguments: number; } { + return this.wellKnownSymbols ??= this.client.apiRequest<{ unknown: number; undefined: number; arguments: number; }>("getWellKnownSymbols", { + snapshot: this.snapshotId, + project: this.project.id, + }); + } + + /** + * Returns `true` if the symbol is the checker's "unknown" symbol (e.g. the + * result of {@link Checker.getAliasedSymbol} on an unresolved alias). + */ + isUnknownSymbol(symbol: Symbol): boolean { + return symbol.id === (this.getWellKnownSymbols()).unknown; + } + + /** + * Returns `true` if the symbol is the checker's "undefined" symbol. + */ + isUndefinedSymbol(symbol: Symbol): boolean { + return symbol.id === (this.getWellKnownSymbols()).undefined; + } + + /** + * Returns `true` if the symbol is the checker's "arguments" symbol. + */ + isArgumentsSymbol(symbol: Symbol): boolean { + return symbol.id === (this.getWellKnownSymbols()).arguments; + } + + getExportsOfModule(symbol: Symbol): readonly Symbol[] { + const data = this.client.apiRequest("getExportsOfModule", { + snapshot: this.snapshotId, + project: this.project.id, + symbol: symbol.id, + }); + return data ? data.map(d => this.objectRegistry.getOrCreateSymbol(d)) : []; + } + + getMemberInModuleExports(symbol: Symbol, name: string): Symbol | undefined { + const data = this.client.apiRequest("getMemberInModuleExports", { + snapshot: this.snapshotId, + project: this.project.id, + symbol: symbol.id, + name, + }); + return data ? this.objectRegistry.getOrCreateSymbol(data) : undefined; + } + + getJsDocTagsOfSymbol(symbol: Symbol): readonly JSDocTagInfo[] { + const data = this.client.apiRequest("getJsDocTags", { + snapshot: this.snapshotId, + project: this.project.id, + symbol: symbol.id, + }); + return data ?? []; + } + + getDocumentationCommentOfSymbol(symbol: Symbol): string { + return this.client.apiRequest("getDocumentationComment", { + snapshot: this.snapshotId, + project: this.project.id, + symbol: symbol.id, + }); + } + + /** + * Get the type arguments of a type reference (e.g. the `string` in `Array`). + */ + getTypeArguments(type: TypeReference): readonly Type[] { const data = this.client.apiRequest("getTypeArguments", { snapshot: this.snapshotId, - project: this.projectId, + project: this.project.id, type: type.id, }); return data ? data.map(d => this.objectRegistry.getOrCreateType(d)) : []; @@ -1149,9 +1462,9 @@ export class Checker { } export interface PrintNodeOptions { - preserveSourceNewlines?: boolean; - neverAsciiEscape?: boolean; - terminateUnterminatedLiterals?: boolean; + preserveSourceNewlines?: boolean | undefined; + neverAsciiEscape?: boolean | undefined; + terminateUnterminatedLiterals?: boolean | undefined; } export class Emitter { @@ -1172,22 +1485,30 @@ export class Emitter { } export class NodeHandle { + /** + * The project this handle was produced in, used as the default for {@link resolve}. + * Node handles are only meaningful within a project's program, so the producing project + * is remembered so callers don't have to pass it explicitly. + */ + private readonly canonicalProject: Project; readonly index: number; readonly kind: SyntaxKind; readonly path: Path; - constructor(handle: string) { + constructor(handle: string, canonicalProject: Project) { const parsed = parseNodeHandle(handle); this.index = parsed.index; this.kind = parsed.kind; this.path = parsed.path; + this.canonicalProject = canonicalProject; } /** - * Resolve this handle to the actual AST node by fetching the source file - * from the given project and looking up the node by index. + * Resolve this handle to the actual AST node by fetching the source file from a project + * and looking up the node by index. If no project is passed, the project that produced + * the handle is used. */ - resolve(project: Project): Node | undefined { + resolve(project: Project = this.canonicalProject): Node | undefined { const sourceFile = project.program.getSourceFile(this.path); if (!sourceFile) { return undefined; @@ -1201,7 +1522,7 @@ export interface ReferencedSymbolEntry { /** The node handle for the symbol's definition. */ definition: NodeHandle; /** The resolved symbol for the definition, if available. */ - symbol?: Symbol; + symbol?: Symbol | undefined; /** The node handles for each reference to the symbol. */ references: NodeHandle[]; } @@ -1211,50 +1532,92 @@ export interface SignatureUsage { /** The node handle for the name reference. */ name: NodeHandle; /** The node handle for the call expression, if the reference is invoked. */ - call?: NodeHandle; + call?: NodeHandle | undefined; } export class Symbol { private objectRegistry: SnapshotObjectRegistry; + /** + * The project this symbol was first observed in, used as the default project for + * lookups that need a project context (members/exports/parent). Symbols are shared + * snapshot-wide, so these lookups can otherwise be ambiguous about which project to use. + */ + private readonly canonicalProject: Project; readonly id: number; + /** The escaped (`__String`) name, used as the key in member/export tables. */ + readonly escapedName: __String; + /** The display name (escaped underscores removed). */ readonly name: string; readonly flags: SymbolFlags; readonly checkFlags: number; readonly declarations: readonly NodeHandle[]; readonly valueDeclaration: NodeHandle | undefined; - readonly parent!: number; - readonly exportSymbol!: number; + private readonly parent!: number; + private readonly exportSymbol!: number; + private membersCache: ReadonlyMap<__String, Symbol> | undefined; + private exportsCache: ReadonlyMap<__String, Symbol> | undefined; constructor(data: SymbolResponse, objectRegistry: SnapshotObjectRegistry) { this.objectRegistry = objectRegistry; this.id = data.id; - this.name = data.name; + this.escapedName = data.name; + this.name = unescapeLeadingUnderscores(data.name); this.flags = data.flags; this.checkFlags = data.checkFlags; - this.declarations = (data.declarations ?? []).map(d => new NodeHandle(d)); - this.valueDeclaration = data.valueDeclaration ? new NodeHandle(data.valueDeclaration) : undefined; + const canonicalProject = objectRegistry.getProject(data.project); + if (!canonicalProject) { + throw new Error(`Symbol ${data.id} references unknown canonical project '${data.project}'`); + } + this.canonicalProject = canonicalProject; + this.declarations = (data.declarations ?? []).map(d => new NodeHandle(d, canonicalProject)); + this.valueDeclaration = data.valueDeclaration ? new NodeHandle(data.valueDeclaration, canonicalProject) : undefined; if (data.parent !== undefined) this.parent = data.parent; if (data.exportSymbol !== undefined) this.exportSymbol = data.exportSymbol; } getParent(): Symbol | undefined { - return this.objectRegistry.fetchSymbol(this, "getParentOfSymbol", this.parent); + return this.objectRegistry.fetchSymbol(this, "getParentOfSymbol", this.parent, this.canonicalProject.id); + } + + /** + * Get this symbol's members keyed by escaped name. The result is cached on + * the symbol, so repeated calls do not round-trip to the server. + */ + getMembers(): ReadonlyMap<__String, Symbol> { + return this.membersCache ??= this.fetchSymbolTable("getMembersOfSymbol"); } - getMembers(): readonly Symbol[] { - return this.objectRegistry.fetchSymbols(this, "getMembersOfSymbol"); + /** + * Get this symbol's exports keyed by escaped name. The result is cached on + * the symbol, so repeated calls do not round-trip to the server. + */ + getExports(): ReadonlyMap<__String, Symbol> { + return this.exportsCache ??= this.fetchSymbolTable("getExportsOfSymbol"); } - getExports(): readonly Symbol[] { - return this.objectRegistry.fetchSymbols(this, "getExportsOfSymbol"); + private fetchSymbolTable(method: string): ReadonlyMap<__String, Symbol> { + const symbols = this.objectRegistry.fetchSymbols(this, method, undefined, this.canonicalProject.id); + const table = new Map<__String, Symbol>(); + for (const symbol of symbols) { + table.set(symbol.escapedName, symbol); + } + return table; } getExportSymbol(): Symbol { if (!this.exportSymbol) return this; - return this.objectRegistry.fetchSymbol(this, "getExportSymbolOfSymbol", this.exportSymbol); + return this.objectRegistry.fetchSymbol(this, "getExportSymbolOfSymbol", this.exportSymbol, this.canonicalProject.id); + } + + getJsDocTags(checker: Checker): readonly JSDocTagInfo[] { + return checker.getJsDocTagsOfSymbol(this); + } + + getDocumentationComment(checker: Checker): string { + return checker.getDocumentationCommentOfSymbol(this); } } @@ -1287,6 +1650,9 @@ class TypeObject implements Type { readonly baseType!: number; readonly substConstraint!: number; + private trueType: number | false; // false if not yet loaded + private falseType: number | false; // false if not yet loaded + constructor(data: TypeResponse, objectRegistry: ProjectObjectRegistry) { this.objectRegistry = objectRegistry; @@ -1319,6 +1685,9 @@ class TypeObject implements Type { if (data.extendsType !== undefined) this.extendsType = data.extendsType; if (data.baseType !== undefined) this.baseType = data.baseType; if (data.substConstraint !== undefined) this.substConstraint = data.substConstraint; + + this.trueType = false; + this.falseType = false; } getSymbol(): Symbol | undefined { @@ -1341,20 +1710,26 @@ class TypeObject implements Type { return this.objectRegistry.fetchType(this, "getRegularTypeOfType", this.regularType); } - getTypes(): readonly Type[] { + getTypes(): readonly Type[] | undefined { + // Only union, intersection, and template literal types have constituent + // types; any other kind has none, so return undefined rather than sending + // a request the server cannot satisfy. + if (!(this.flags & (TypeFlags.UnionOrIntersection | TypeFlags.TemplateLiteral))) { + return undefined; + } return this.objectRegistry.fetchTypes(this, "getTypesOfType"); } - getTypeParameters(): readonly Type[] { - return this.objectRegistry.fetchTypes(this, "getTypeParametersOfType", this.typeParameters); + getTypeParameters(): readonly TypeParameter[] { + return this.objectRegistry.fetchTypes(this, "getTypeParametersOfType", this.typeParameters) as readonly TypeParameter[]; } - getOuterTypeParameters(): readonly Type[] { - return this.objectRegistry.fetchTypes(this, "getOuterTypeParametersOfType", this.outerTypeParameters); + getOuterTypeParameters(): readonly TypeParameter[] { + return this.objectRegistry.fetchTypes(this, "getOuterTypeParametersOfType", this.outerTypeParameters) as readonly TypeParameter[]; } - getLocalTypeParameters(): readonly Type[] { - return this.objectRegistry.fetchTypes(this, "getLocalTypeParametersOfType", this.localTypeParameters); + getLocalTypeParameters(): readonly TypeParameter[] { + return this.objectRegistry.fetchTypes(this, "getLocalTypeParametersOfType", this.localTypeParameters) as readonly TypeParameter[]; } getAliasTypeArguments(): readonly Type[] { @@ -1384,6 +1759,195 @@ class TypeObject implements Type { getConstraint(): Type { return this.objectRegistry.fetchType(this, "getConstraintOfType", this.substConstraint); } + + getTrueType(): Type { + const result = this.objectRegistry.fetchType(this, "getTrueTypeOfConditionalType", this.trueType); + this.trueType = result.id; + return result; + } + + getFalseType(): Type { + const result = this.objectRegistry.fetchType(this, "getFalseTypeOfConditionalType", this.falseType); + this.falseType = result.id; + return result; + } + + /** + * Get the base types of this type. Returns `undefined` for any type that is + * not a class or interface. + */ + getBaseTypes(): readonly Type[] | undefined { + if (!this.isClassOrInterface()) { + return undefined; + } + return this.objectRegistry.fetchBaseTypes(this); + } + + isClassOrInterface(): this is InterfaceType { + return isClassOrInterfaceType(this); + } + + isUnionType(): this is UnionType { + return isUnionType(this); + } + + isIntersectionType(): this is IntersectionType { + return isIntersectionType(this); + } + + isObjectType(): this is ObjectType { + return isObjectType(this); + } + + isIntrinsicType(): this is IntrinsicType { + return isIntrinsicType(this); + } + + isErrorType(): boolean { + return isErrorType(this); + } + + isLiteralType(): this is LiteralType { + return isLiteralType(this); + } + + isStringLiteralType(): this is StringLiteralType { + return isStringLiteralType(this); + } + + isNumberLiteralType(): this is NumberLiteralType { + return isNumberLiteralType(this); + } + + isBigIntLiteralType(): this is BigIntLiteralType { + return isBigIntLiteralType(this); + } + + isBooleanLiteralType(): this is BooleanLiteralType { + return isBooleanLiteralType(this); + } + + isTypeReference(): this is TypeReference { + return isTypeReference(this); + } + + isTupleType(): this is TupleType { + return isTupleType(this); + } + + isIndexType(): this is IndexType { + return isIndexType(this); + } + + isIndexedAccessType(): this is IndexedAccessType { + return isIndexedAccessType(this); + } + + isConditionalType(): this is ConditionalType { + return isConditionalType(this); + } + + isSubstitutionType(): this is SubstitutionType { + return isSubstitutionType(this); + } + + isTemplateLiteralType(): this is TemplateLiteralType { + return isTemplateLiteralType(this); + } + + isStringMappingType(): this is StringMappingType { + return isStringMappingType(this); + } + + isTypeParameter(): this is TypeParameter { + return isTypeParameter(this); + } +} + +export function isUnionType(type: Type): type is UnionType { + return (type.flags & TypeFlags.Union) !== 0; +} + +export function isIntersectionType(type: Type): type is IntersectionType { + return (type.flags & TypeFlags.Intersection) !== 0; +} + +export function isObjectType(type: Type): type is ObjectType { + return (type.flags & TypeFlags.Object) !== 0; +} + +export function isClassOrInterfaceType(type: Type): type is InterfaceType { + return isObjectType(type) && (type.objectFlags & ObjectFlags.ClassOrInterface) !== 0; +} + +export function isIntrinsicType(type: Type): type is IntrinsicType { + return (type.flags & TypeFlags.Intrinsic) !== 0; +} + +/** + * Whether this is the error type — the placeholder the checker produces when a + * type cannot be determined (e.g. an unresolved reference). It is an intrinsic + * type named `"error"` (this covers both the singleton error type and the + * per-alias error types manufactured for unresolved type alias references). + */ +export function isErrorType(type: Type): boolean { + return isIntrinsicType(type) && type.intrinsicName === "error"; +} + +export function isLiteralType(type: Type): type is LiteralType { + return (type.flags & TypeFlags.Literal) !== 0; +} + +export function isStringLiteralType(type: Type): type is StringLiteralType { + return (type.flags & TypeFlags.StringLiteral) !== 0; +} + +export function isNumberLiteralType(type: Type): type is NumberLiteralType { + return (type.flags & TypeFlags.NumberLiteral) !== 0; +} + +export function isBigIntLiteralType(type: Type): type is BigIntLiteralType { + return (type.flags & TypeFlags.BigIntLiteral) !== 0; +} + +export function isBooleanLiteralType(type: Type): type is BooleanLiteralType { + return (type.flags & TypeFlags.BooleanLiteral) !== 0; +} + +export function isTypeReference(type: Type): type is TypeReference { + return isObjectType(type) && (type.objectFlags & ObjectFlags.Reference) !== 0; +} + +export function isTupleType(type: Type): type is TupleType { + return isObjectType(type) && (type.objectFlags & ObjectFlags.Tuple) !== 0; +} + +export function isIndexType(type: Type): type is IndexType { + return (type.flags & TypeFlags.Index) !== 0; +} + +export function isIndexedAccessType(type: Type): type is IndexedAccessType { + return (type.flags & TypeFlags.IndexedAccess) !== 0; +} + +export function isConditionalType(type: Type): type is ConditionalType { + return (type.flags & TypeFlags.Conditional) !== 0; +} + +export function isSubstitutionType(type: Type): type is SubstitutionType { + return (type.flags & TypeFlags.Substitution) !== 0; +} + +export function isTemplateLiteralType(type: Type): type is TemplateLiteralType { + return (type.flags & TypeFlags.TemplateLiteral) !== 0; +} + +export function isStringMappingType(type: Type): type is StringMappingType { + return (type.flags & TypeFlags.StringMapping) !== 0; +} + +export function isTypeParameter(type: Type): type is TypeParameter { + return (type.flags & TypeFlags.TypeParameter) !== 0; } export class Signature { @@ -1397,19 +1961,19 @@ export class Signature { readonly thisParameter?: number | undefined; readonly target?: number | undefined; - constructor(data: SignatureResponse, objectRegistry: ProjectObjectRegistry) { + constructor(data: SignatureResponse, project: Project, objectRegistry: ProjectObjectRegistry) { this.id = data.id; this.flags = data.flags; this.objectRegistry = objectRegistry; - this.declaration = data.declaration ? new NodeHandle(data.declaration) : undefined; + this.declaration = data.declaration ? new NodeHandle(data.declaration, project) : undefined; this.typeParameters = data.typeParameters ?? []; this.parameters = data.parameters ?? []; this.thisParameter = data.thisParameter; this.target = data.target; } - getTypeParameters(): readonly Type[] { - return this.objectRegistry.fetchTypes(this, "getTypeParametersOfSignature", this.typeParameters); + getTypeParameters(): readonly TypeParameter[] { + return this.objectRegistry.fetchTypes(this, "getTypeParametersOfSignature", this.typeParameters) as readonly TypeParameter[]; } getParameters(): readonly Symbol[] { diff --git a/_packages/native-preview/src/api/sync/types.ts b/_packages/native-preview/src/api/sync/types.ts index 86d31f003a0..658d0780655 100644 --- a/_packages/native-preview/src/api/sync/types.ts +++ b/_packages/native-preview/src/api/sync/types.ts @@ -30,10 +30,11 @@ import type { * ``` */ export interface Type { + /** Type flags — use to determine the specific kind of type. */ + readonly flags: TypeFlags; + /** Unique identifier for this type */ readonly id: number; - /** Type flags — use to determine the specific kind of type */ - readonly flags: TypeFlags; /** Get the symbol associated with this type, if any */ getSymbol(): Symbol | undefined; @@ -43,6 +44,56 @@ export interface Type { /** Get the symbol of the type alias this type was instantiated from, if any */ getAliasSymbol(): Symbol | undefined; + + /** + * Get the base types of this type, or `undefined` if it is not a class or + * interface type. + */ + getBaseTypes(): readonly Type[] | undefined; + + /** Whether this type is a class or interface type */ + isClassOrInterface(): this is InterfaceType; + /** Whether this type is a union type */ + isUnionType(): this is UnionType; + /** Whether this type is an intersection type */ + isIntersectionType(): this is IntersectionType; + /** Whether this type is an object type */ + isObjectType(): this is ObjectType; + /** Whether this type is an intrinsic primitive type */ + isIntrinsicType(): this is IntrinsicType; + /** + * Whether this is the error type — the placeholder produced when a type + * cannot be determined (e.g. an unresolved reference). + */ + isErrorType(): boolean; + /** Whether this type is a literal type */ + isLiteralType(): this is LiteralType; + /** Whether this type is a string literal type */ + isStringLiteralType(): this is StringLiteralType; + /** Whether this type is a number literal type */ + isNumberLiteralType(): this is NumberLiteralType; + /** Whether this type is a bigint literal type */ + isBigIntLiteralType(): this is BigIntLiteralType; + /** Whether this type is a boolean literal type */ + isBooleanLiteralType(): this is BooleanLiteralType; + /** Whether this type is a type reference */ + isTypeReference(): this is TypeReference; + /** Whether this type is a tuple type */ + isTupleType(): this is TupleType; + /** Whether this type is an index type (`keyof T`) */ + isIndexType(): this is IndexType; + /** Whether this type is an indexed access type (`T[K]`) */ + isIndexedAccessType(): this is IndexedAccessType; + /** Whether this type is a conditional type */ + isConditionalType(): this is ConditionalType; + /** Whether this type is a substitution type */ + isSubstitutionType(): this is SubstitutionType; + /** Whether this type is a template literal type */ + isTemplateLiteralType(): this is TemplateLiteralType; + /** Whether this type is a string mapping type */ + isStringMappingType(): this is StringMappingType; + /** Whether this type is a type parameter */ + isTypeParameter(): this is TypeParameter; } /** @@ -87,7 +138,7 @@ export interface BooleanLiteralType extends LiteralType { /** Object types (TypeFlags.Object) */ export interface ObjectType extends Type { - /** Object flags — use to determine the specific kind of object type */ + /** Object flags — use to determine the specific kind of object type. */ readonly objectFlags: ObjectFlags; } @@ -100,11 +151,11 @@ export interface TypeReference extends ObjectType { /** Interface types — classes and interfaces (ObjectFlags.ClassOrInterface) */ export interface InterfaceType extends TypeReference { /** Get all type parameters (outer + local, excluding thisType) */ - getTypeParameters(): readonly Type[]; + getTypeParameters(): readonly TypeParameter[]; /** Get outer type parameters from enclosing declarations */ - getOuterTypeParameters(): readonly Type[]; + getOuterTypeParameters(): readonly TypeParameter[]; /** Get local type parameters declared on this interface/class */ - getLocalTypeParameters(): readonly Type[]; + getLocalTypeParameters(): readonly TypeParameter[]; } /** Tuple types (ObjectFlags.Tuple) */ @@ -134,7 +185,7 @@ export interface IntersectionType extends UnionOrIntersectionType { /** Type parameters (TypeFlags.TypeParameter) */ export interface TypeParameter extends Type { /** True if this is the synthetic `this` type of an interface, class, or tuple */ - readonly isThisType?: boolean; + readonly isThisType?: boolean | undefined; } /** Index types — keyof T (TypeFlags.Index) */ @@ -157,6 +208,10 @@ export interface ConditionalType extends Type { getCheckType(): Type; /** Get the extends type U in `T extends U ? X : Y` */ getExtendsType(): Type; + /** Get the true type X in `T extends U ? X : Y` */ + getTrueType(): Type; + /** Get the false type Y in `T extends U ? X : Y` */ + getFalseType(): Type; } /** Substitution types (TypeFlags.Substitution) */ @@ -235,32 +290,42 @@ export interface IndexInfo { /** Whether the index signature is readonly */ readonly isReadonly: boolean; /** The index signature declaration, if any */ - readonly declaration?: NodeHandle; + readonly declaration?: NodeHandle | undefined; +} + +/** + * A single JSDoc tag attached to a symbol — e.g. `@param`, `@returns`. + */ +export interface JSDocTagInfo { + /** The tag name, without the leading `@` — e.g. `"param"`. */ + readonly name: string; + /** The rendered tag text, if any — e.g. `"a the first number"` for `@param a the first number`. */ + readonly text?: string | undefined; } export interface CompletionEntryLabelDetails { - detail?: string; - description?: string; + detail?: string | undefined; + description?: string | undefined; } /** Options for {@link Checker.getCompletionsAtPosition}. */ export interface CompletionOptions { - triggerCharacter?: string; + triggerCharacter?: string | undefined; /** Include a `symbol` property on each completion entry. Only populated for symbol-based completions (not keywords or literals). */ - includeSymbol?: boolean; + includeSymbol?: boolean | undefined; } /** A single completion item returned by {@link Checker.getCompletionsAtPosition}. */ export interface CompletionEntry { readonly name: string; - readonly kind?: CompletionItemKind; - readonly sortText?: string; - readonly insertText?: string; - readonly filterText?: string; - readonly detail?: string; - readonly labelDetails?: CompletionEntryLabelDetails; + readonly kind?: CompletionItemKind | undefined; + readonly sortText?: string | undefined; + readonly insertText?: string | undefined; + readonly filterText?: string | undefined; + readonly detail?: string | undefined; + readonly labelDetails?: CompletionEntryLabelDetails | undefined; /** The symbol associated with this completion entry. Only set when `includeSymbol: true` is passed and a symbol is available. */ - readonly symbol?: Symbol; + readonly symbol?: Symbol | undefined; } /** The result of {@link Checker.getCompletionsAtPosition}. */ @@ -274,7 +339,7 @@ export interface CompletionInfo { */ export interface Diagnostic { /** File name of the source file this diagnostic belongs to, if any */ - readonly fileName?: string; + readonly fileName?: string | undefined; /** Start position of the diagnostic */ readonly pos: number; /** End position of the diagnostic */ @@ -286,11 +351,11 @@ export interface Diagnostic { /** Localized diagnostic message text */ readonly text: string; /** Whether this diagnostic highlights unnecessary code */ - readonly reportsUnnecessary?: boolean; + readonly reportsUnnecessary?: boolean | undefined; /** Whether this diagnostic highlights deprecated code */ - readonly reportsDeprecated?: boolean; + readonly reportsDeprecated?: boolean | undefined; /** Chained diagnostic messages */ - readonly messageChain?: readonly Diagnostic[]; + readonly messageChain?: readonly Diagnostic[] | undefined; /** Related diagnostic information */ - readonly relatedInformation?: readonly Diagnostic[]; + readonly relatedInformation?: readonly Diagnostic[] | undefined; } diff --git a/_packages/native-preview/src/ast/ast.generated.ts b/_packages/native-preview/src/ast/ast.generated.ts index 94dcab245fe..ef6664e2ccb 100644 --- a/_packages/native-preview/src/ast/ast.generated.ts +++ b/_packages/native-preview/src/ast/ast.generated.ts @@ -487,7 +487,7 @@ export interface JSDocTagBase extends NodeBase { readonly comment?: NodeArray; } export interface JSDocCommentBase extends NodeBase { - readonly text: readonly string[]; + readonly text: string; } export interface Token extends NodeBase { diff --git a/_packages/native-preview/src/ast/ast.ts b/_packages/native-preview/src/ast/ast.ts index c12a7953e4e..6601d3d3e4a 100644 --- a/_packages/native-preview/src/ast/ast.ts +++ b/_packages/native-preview/src/ast/ast.ts @@ -1,6 +1,7 @@ // ast.ts — Hand-written AST type definitions // Generated types are in ast.generated.ts +import type { InternalSymbolName } from "#enums/internalSymbolName"; import type { LanguageVariant } from "#enums/languageVariant"; import type { NodeFlags } from "#enums/nodeFlags"; import type { ScriptKind } from "#enums/scriptKind"; @@ -26,6 +27,15 @@ export * from "./ast.generated.ts"; export type Path = string & { __pathBrand: any; }; +/** + * The escaped form of a symbol/identifier name. Internal compiler names are + * prefixed with `__` (e.g. `__type`, `__call`), and user names that already + * begin with `__` carry an extra leading underscore. Use + * {@link unescapeLeadingUnderscores} to recover the display name and + * {@link escapeLeadingUnderscores} to produce a key from a display name. + */ +export type __String = (string & { __escapedIdentifier: void; }) | InternalSymbolName; + export interface TextRange { pos: number; end: number; @@ -45,7 +55,7 @@ export interface Node extends ReadonlyTextRange { readonly kind: SyntaxKind; readonly flags: NodeFlags; readonly parent: Node; - readonly jsDoc?: readonly Node[]; + readonly jsDoc?: readonly Node[] | undefined; forEachChild(visitor: (node: Node) => T, visitArray?: (nodes: NodeArray) => T): T | undefined; getSourceFile(): SourceFile; getStart(sourceFile?: SourceFile, includeJsDocComment?: boolean): number; diff --git a/_packages/native-preview/src/ast/factory.generated.ts b/_packages/native-preview/src/ast/factory.generated.ts index 3181d175715..f29cfc3d107 100644 --- a/_packages/native-preview/src/ast/factory.generated.ts +++ b/_packages/native-preview/src/ast/factory.generated.ts @@ -258,6 +258,7 @@ import type { YieldExpression, } from "./ast.ts"; import { getTokenPosOfNode } from "./astnav.ts"; +import { cloneSourceFileData } from "./utils.ts"; import { forEachChildOfJSDocParameterTag, forEachChildOfJSDocPropertyTag, @@ -1094,7 +1095,7 @@ function cloneNodeData(node: Node): any { case SyntaxKind.JSDocPropertyTag: return { tagName: n.tagName, name: n.name, isBracketed: n.isBracketed, typeExpression: n.typeExpression, isNameFirst: n.isNameFirst, comment: n.comment }; case SyntaxKind.SourceFile: - return { statements: n.statements, endOfFileToken: n.endOfFileToken, text: n.text, fileName: n.fileName, path: n.path }; + return cloneSourceFileData(n); default: return undefined; } @@ -2986,27 +2987,27 @@ export function createImportSpecifier(isTypeOnly: boolean = false, propertyName: }) as unknown as ImportSpecifier; } -export function createJSDocText(text: readonly string[]): JSDocText { +export function createJSDocText(text: string): JSDocText { return new NodeObject(SyntaxKind.JSDocText, { text, }) as unknown as JSDocText; } -export function createJSDocLink(name: EntityName | undefined, text: readonly string[]): JSDocLink { +export function createJSDocLink(name: EntityName | undefined, text: string): JSDocLink { return new NodeObject(SyntaxKind.JSDocLink, { name, text, }) as unknown as JSDocLink; } -export function createJSDocLinkPlain(name: EntityName | undefined, text: readonly string[]): JSDocLinkPlain { +export function createJSDocLinkPlain(name: EntityName | undefined, text: string): JSDocLinkPlain { return new NodeObject(SyntaxKind.JSDocLinkPlain, { name, text, }) as unknown as JSDocLinkPlain; } -export function createJSDocLinkCode(name: EntityName | undefined, text: readonly string[]): JSDocLinkCode { +export function createJSDocLinkCode(name: EntityName | undefined, text: string): JSDocLinkCode { return new NodeObject(SyntaxKind.JSDocLinkCode, { name, text, @@ -3793,8 +3794,16 @@ export function createSourceFile(statements: readonly Statement[], endOfFileToke }) as unknown as SourceFile; } +function cloneSourceFileWithChanges(source: SourceFile, statements: readonly Statement[], endOfFileToken: EndOfFile): SourceFile { + return new NodeObject(SyntaxKind.SourceFile, { + ...cloneSourceFileData(source), + statements: createNodeArray(statements), + endOfFileToken, + }) as unknown as SourceFile; +} + export function updateSourceFile(node: SourceFile, statements: readonly Statement[], endOfFileToken: EndOfFile): SourceFile { return node.statements !== statements || node.endOfFileToken !== endOfFileToken - ? createSourceFile(statements, endOfFileToken, node.text, node.fileName, node.path) + ? cloneSourceFileWithChanges(node, statements, endOfFileToken) : node; } diff --git a/_packages/native-preview/src/ast/index.ts b/_packages/native-preview/src/ast/index.ts index b1b7a819cb9..f1b0e488cd5 100644 --- a/_packages/native-preview/src/ast/index.ts +++ b/_packages/native-preview/src/ast/index.ts @@ -1,5 +1,6 @@ export { CharacterCodes } from "#enums/characterCodes"; export { CommentDirectiveType } from "#enums/commentDirectiveType"; +export { InternalSymbolName } from "#enums/internalSymbolName"; export { LanguageVariant } from "#enums/languageVariant"; export { ModifierFlags } from "#enums/modifierFlags"; export { NodeFlags } from "#enums/nodeFlags"; diff --git a/_packages/native-preview/src/ast/is.generated.ts b/_packages/native-preview/src/ast/is.generated.ts index af226c91b6e..2ec8661866a 100644 --- a/_packages/native-preview/src/ast/is.generated.ts +++ b/_packages/native-preview/src/ast/is.generated.ts @@ -273,6 +273,7 @@ import type { ShiftOperatorOrHigher, ShorthandPropertyAssignment, SignatureDeclaration, + SourceFile, SpreadAssignment, SpreadElement, StaticKeyword, @@ -1034,6 +1035,10 @@ export function isJSDocNameReference(node: Node): node is JSDocNameReference { return node.kind === SyntaxKind.JSDocNameReference; } +export function isSourceFile(node: Node): node is SourceFile { + return node.kind === SyntaxKind.SourceFile; +} + export function isModuleDeclaration(node: Node): node is ModuleDeclaration { return node.kind === SyntaxKind.ModuleDeclaration; } diff --git a/_packages/native-preview/src/ast/utils.ts b/_packages/native-preview/src/ast/utils.ts index 8ef83804fff..0739540e365 100644 --- a/_packages/native-preview/src/ast/utils.ts +++ b/_packages/native-preview/src/ast/utils.ts @@ -1,4 +1,9 @@ +import { CharacterCodes } from "#enums/characterCodes"; import { SyntaxKind } from "#enums/syntaxKind"; +import type { + __String, + SourceFile, +} from "./ast.ts"; let syntaxKindNames: Map | undefined; function getSyntaxKindNames(): Map { @@ -19,6 +24,27 @@ export function formatSyntaxKind(kind: SyntaxKind): string { return getSyntaxKindNames().get(kind) ?? `Unknown(${kind})`; } +/** + * Remove one extra leading underscore from an identifier name, recovering the + * display form from its escaped {@link __String} key. + */ +export function unescapeLeadingUnderscores(identifier: __String): string { + const id = identifier as string; + return id.length >= 3 && id.charCodeAt(0) === CharacterCodes._ && id.charCodeAt(1) === CharacterCodes._ && id.charCodeAt(2) === CharacterCodes._ + ? id.slice(1) + : id; +} + +/** + * Add an extra leading underscore to a display name that already begins with + * `__`, producing its escaped {@link __String} key. + */ +export function escapeLeadingUnderscores(identifier: string): __String { + return (identifier.length >= 2 && identifier.charCodeAt(0) === CharacterCodes._ && identifier.charCodeAt(1) === CharacterCodes._ + ? "_" + identifier + : identifier) as __String; +} + export function tryCast(value: TIn | undefined, test: (value: TIn) => value is TOut): TOut | undefined { return value !== undefined && test(value) ? value : undefined; } @@ -28,3 +54,24 @@ export function cast(value: TIn | undefined, test: throw new Error(`Invalid cast. The supplied value ${value} did not pass the test '${test.name}'.`); } + +export function cloneSourceFileData(sourceFile: SourceFile): Record { + return { + statements: sourceFile.statements, + endOfFileToken: sourceFile.endOfFileToken, + text: sourceFile.text, + fileName: sourceFile.fileName, + path: sourceFile.path, + languageVariant: sourceFile.languageVariant, + scriptKind: sourceFile.scriptKind, + isDeclarationFile: sourceFile.isDeclarationFile, + referencedFiles: sourceFile.referencedFiles, + typeReferenceDirectives: sourceFile.typeReferenceDirectives, + libReferenceDirectives: sourceFile.libReferenceDirectives, + imports: sourceFile.imports, + moduleAugmentations: sourceFile.moduleAugmentations, + ambientModuleNames: sourceFile.ambientModuleNames, + externalModuleIndicator: sourceFile.externalModuleIndicator, + tokenCache: undefined, + }; +} diff --git a/_packages/native-preview/src/enums/internalSymbolName.enum.ts b/_packages/native-preview/src/enums/internalSymbolName.enum.ts new file mode 100644 index 00000000000..b7b6438f8aa --- /dev/null +++ b/_packages/native-preview/src/enums/internalSymbolName.enum.ts @@ -0,0 +1,24 @@ +// Code generated by Herebyfile.mjs generate:enums from internal/ast/symbol.go. DO NOT EDIT. + +export enum InternalSymbolName { + Call = "__call", + Constructor = "__constructor", + New = "__new", + Index = "__index", + ExportStar = "__export", + Global = "__global", + Missing = "__missing", + Type = "__type", + Object = "__object", + JSXAttributes = "__jsxAttributes", + Class = "__class", + Function = "__function", + Computed = "__computed", + AssignmentDeclaration = "__assignment", + InstantiationExpression = "__instantiationExpression", + ImportAttributes = "__importAttributes", + ExportEquals = "export=", + Default = "default", + This = "this", + ModuleExports = "module.exports", +} diff --git a/_packages/native-preview/src/enums/internalSymbolName.ts b/_packages/native-preview/src/enums/internalSymbolName.ts new file mode 100644 index 00000000000..0d32ffb0878 --- /dev/null +++ b/_packages/native-preview/src/enums/internalSymbolName.ts @@ -0,0 +1,24 @@ +// Code generated by Herebyfile.mjs generate:enums from internal/ast/symbol.go. DO NOT EDIT. +export var InternalSymbolName: any; +(function (InternalSymbolName) { + InternalSymbolName["Call"] = "__call"; + InternalSymbolName["Constructor"] = "__constructor"; + InternalSymbolName["New"] = "__new"; + InternalSymbolName["Index"] = "__index"; + InternalSymbolName["ExportStar"] = "__export"; + InternalSymbolName["Global"] = "__global"; + InternalSymbolName["Missing"] = "__missing"; + InternalSymbolName["Type"] = "__type"; + InternalSymbolName["Object"] = "__object"; + InternalSymbolName["JSXAttributes"] = "__jsxAttributes"; + InternalSymbolName["Class"] = "__class"; + InternalSymbolName["Function"] = "__function"; + InternalSymbolName["Computed"] = "__computed"; + InternalSymbolName["AssignmentDeclaration"] = "__assignment"; + InternalSymbolName["InstantiationExpression"] = "__instantiationExpression"; + InternalSymbolName["ImportAttributes"] = "__importAttributes"; + InternalSymbolName["ExportEquals"] = "export="; + InternalSymbolName["Default"] = "default"; + InternalSymbolName["This"] = "this"; + InternalSymbolName["ModuleExports"] = "module.exports"; +})(InternalSymbolName || (InternalSymbolName = {})); diff --git a/_packages/native-preview/src/enums/moduleKind.enum.ts b/_packages/native-preview/src/enums/moduleKind.enum.ts new file mode 100644 index 00000000000..d167c8e04dc --- /dev/null +++ b/_packages/native-preview/src/enums/moduleKind.enum.ts @@ -0,0 +1,18 @@ +// Code generated by Herebyfile.mjs generate:enums from internal/core/compileroptions.go. DO NOT EDIT. + +export enum ModuleKind { + None = 0, + CommonJS = 1, + AMD = 2, + UMD = 3, + System = 4, + ES2015 = 5, + ES2020 = 6, + ES2022 = 7, + ESNext = 99, + Node16 = 100, + Node18 = 101, + Node20 = 102, + NodeNext = 199, + Preserve = 200, +} diff --git a/_packages/native-preview/src/enums/moduleKind.ts b/_packages/native-preview/src/enums/moduleKind.ts new file mode 100644 index 00000000000..9fe89dda79a --- /dev/null +++ b/_packages/native-preview/src/enums/moduleKind.ts @@ -0,0 +1,18 @@ +// Code generated by Herebyfile.mjs generate:enums from internal/core/compileroptions.go. DO NOT EDIT. +export var ModuleKind: any; +(function (ModuleKind) { + ModuleKind[ModuleKind["None"] = 0] = "None"; + ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS"; + ModuleKind[ModuleKind["AMD"] = 2] = "AMD"; + ModuleKind[ModuleKind["UMD"] = 3] = "UMD"; + ModuleKind[ModuleKind["System"] = 4] = "System"; + ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015"; + ModuleKind[ModuleKind["ES2020"] = 6] = "ES2020"; + ModuleKind[ModuleKind["ES2022"] = 7] = "ES2022"; + ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext"; + ModuleKind[ModuleKind["Node16"] = 100] = "Node16"; + ModuleKind[ModuleKind["Node18"] = 101] = "Node18"; + ModuleKind[ModuleKind["Node20"] = 102] = "Node20"; + ModuleKind[ModuleKind["NodeNext"] = 199] = "NodeNext"; + ModuleKind[ModuleKind["Preserve"] = 200] = "Preserve"; +})(ModuleKind || (ModuleKind = {})); diff --git a/_packages/native-preview/test/async/api.test.ts b/_packages/native-preview/test/async/api.test.ts index 015cd521e36..bb6011a2f67 100644 --- a/_packages/native-preview/test/async/api.test.ts +++ b/_packages/native-preview/test/async/api.test.ts @@ -1,7 +1,10 @@ import { + type __String, cast, + escapeLeadingUnderscores, type Expression, getSynthesizedDeepClone, + InternalSymbolName, isCallExpression, isFunctionDeclaration, isIdentifier, @@ -13,11 +16,14 @@ import { isTemplateHead, isTemplateMiddle, isTemplateTail, + isTypeAliasDeclaration, isTypeNode, isVariableDeclarationList, type Node, + type NodeArray, NodeFlags, SyntaxKind, + unescapeLeadingUnderscores, } from "@typescript/native-preview/unstable/ast"; import { createArrayTypeNode, @@ -39,9 +45,12 @@ import { type FreshableType, type IndexedAccessType, type IndexType, + type InterfaceType, type IntrinsicType, + isErrorType, type LiteralType, ModifierFlags, + ModuleKind, ObjectFlags, SignatureKind, type StringMappingType, @@ -85,6 +94,29 @@ describe("API", () => { }); }); +describe("Checker - getImmediateAliasedSymbol", () => { + test("resolves one level of alias indirection", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/foo.ts": `export const foo = 42;`, + "/src/main.ts": `import { foo } from "./foo";\nexport const usage = foo;`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const pos = `import { foo } from "./foo";`.indexOf("foo }"); + const aliasSymbol = await project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(aliasSymbol); + const aliased = await project.checker.getImmediateAliasedSymbol(aliasSymbol); + assert.ok(aliased, "Should resolve the immediate aliased symbol"); + assert.equal(aliased.name, "foo"); + } + finally { + await api.close(); + } + }); +}); + describe("Snapshot", () => { test("updateSnapshot returns snapshot with projects", async () => { const api = spawnAPI(); @@ -154,7 +186,167 @@ describe("Snapshot", () => { }); }); +describe("Checker - getApparentType", () => { + test("returns the apparent type of a literal type", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const x = "hello" as const;`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const pos = `export const x = "hello" as const;`.indexOf("x ="); + const symbol = await project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = await project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + assert.equal(type.isLiteralType(), true); + assert.equal(type.isStringLiteralType(), true); + assert.equal(type.isIntrinsicType(), false); + const apparent = await project.checker.getApparentType(type); + assert.ok(apparent); + assert.ok(apparent.id > 0); + } + finally { + await api.close(); + } + }); +}); + +describe("Checker - getMemberInModuleExports", () => { + test("returns a named export when present", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/index.ts": `export const direct = 1;`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = await project.program.getSourceFile("/src/index.ts"); + assert.ok(sourceFile); + const moduleSymbol = await project.checker.getSymbolAtLocation(sourceFile); + assert.ok(moduleSymbol); + const found = await project.checker.getMemberInModuleExports(moduleSymbol, "direct"); + assert.ok(found); + assert.equal(found.name, "direct"); + const missing = await project.checker.getMemberInModuleExports(moduleSymbol, "missing"); + assert.equal(missing, undefined); + } + finally { + await api.close(); + } + }); +}); + describe("SourceFile", () => { + test("getSourceFileNames returns all program files, not just root files", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ + compilerOptions: { + moduleResolution: "node10", + noLib: true, + }, + }), + "/src/index.ts": `import { foo } from "./foo";\nimport { bar } from "my-lib";\nexport const result = foo + bar;`, + "/src/foo.ts": `export const foo = 42;`, + "/node_modules/my-lib/package.json": JSON.stringify({ name: "my-lib", types: "./index.d.ts" }), + "/node_modules/my-lib/index.d.ts": `export declare const bar: number;`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const fileNames = await project.program.getSourceFileNames(); + assert.deepEqual(fileNames, [ + "/src/foo.ts", + "/node_modules/my-lib/index.d.ts", + "/src/index.ts", + ]); + } + finally { + await api.close(); + } + }); + + test("source file metadata identifies external library and default library files", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ + compilerOptions: { + moduleResolution: "node10", + }, + }), + "/src/index.ts": `import { bar } from "my-lib";\nexport const result = bar;`, + "/node_modules/my-lib/package.json": JSON.stringify({ name: "my-lib", types: "./index.d.ts" }), + "/node_modules/my-lib/index.d.ts": `export declare const bar: number;`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const program = project.program; + + const index = await program.getSourceFile("/src/index.ts"); + assert.ok(index); + assert.equal(await program.isSourceFileFromExternalLibrary(index), false); + assert.equal(await program.isSourceFileDefaultLibrary(index), false); + + const lib = await program.getSourceFile("/node_modules/my-lib/index.d.ts"); + assert.ok(lib); + assert.equal(await program.isSourceFileFromExternalLibrary(lib), true); + assert.equal(await program.isSourceFileDefaultLibrary(lib), false); + + const fileNames = await program.getSourceFileNames(); + const defaultLibName = fileNames.find(name => name.endsWith("lib.d.ts") || name.includes("/lib.")); + assert.ok(defaultLibName, "expected a default library file in the program"); + const defaultLib = await program.getSourceFile(defaultLibName); + assert.ok(defaultLib); + assert.equal(await program.isSourceFileDefaultLibrary(defaultLib), true); + } + finally { + await api.close(); + } + }); + + test("source file metadata reports implied node format", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ + compilerOptions: { + module: "nodenext", + moduleResolution: "nodenext", + }, + }), + "/src/index.ts": `export const x = 1;`, + "/src/esm.mts": `export const e = 1;`, + "/src/cjs.cts": `export const c = 1;`, + "/esm/package.json": JSON.stringify({ type: "module" }), + "/esm/index.ts": `export const m = 1;`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const program = snapshot.getProject("/tsconfig.json")!.program; + + const mts = await program.getSourceFile("/src/esm.mts"); + assert.ok(mts); + assert.equal((await program.getSourceFileMetadata(mts.fileName))?.impliedNodeFormat, ModuleKind.ESNext); + assert.equal((await program.getSourceFileMetadataByPath(mts.path))?.impliedNodeFormat, ModuleKind.ESNext); + + const cts = await program.getSourceFile("/src/cjs.cts"); + assert.ok(cts); + assert.equal((await program.getSourceFileMetadata(cts.fileName))?.impliedNodeFormat, ModuleKind.CommonJS); + + // A plain .ts file with no nearby `"type": "module"` is CommonJS. + const index = await program.getSourceFile("/src/index.ts"); + assert.ok(index); + assert.equal((await program.getSourceFileMetadata(index.fileName))?.impliedNodeFormat, ModuleKind.CommonJS); + + // A plain .ts file under a `"type": "module"` package is ESM. + const esmIndex = await program.getSourceFile("/esm/index.ts"); + assert.ok(esmIndex); + assert.equal((await program.getSourceFileMetadata(esmIndex.fileName))?.impliedNodeFormat, ModuleKind.ESNext); + } + finally { + await api.close(); + } + }); + test("file properties", async () => { const api = spawnAPI(); try { @@ -205,6 +397,43 @@ describe("SourceFile", () => { await api.close(); } }); + + test("forEachChild with visitList does not visit array children twice", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ files: ["/input.ts"] }), + "/input.ts": `let arrow = () => {}`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = await project.program.getSourceFile("/input.ts"); + + assert.ok(sourceFile); + + const visited: { kind: SyntaxKind; pos: number; end: number; }[] = []; + (function walk(node: Node): void { + visited.push({ kind: node.kind, pos: node.pos, end: node.end }); + node.forEachChild(walk, (nodes: NodeArray) => { + for (let i = 0; i < nodes.length; i++) { + walk(nodes[i]); + } + return undefined; + }); + })(sourceFile); + + // Each node should be visited exactly once, even when a visitList callback + // is supplied. Previously array children were visited twice. + const seen = new Set(); + for (const { kind, pos, end } of visited) { + const key = `${kind}.${pos}.${end}`; + assert.ok(!seen.has(key), `Node ${key} was visited more than once`); + seen.add(key); + } + } + finally { + await api.close(); + } + }); }); test("unicode escapes", async () => { @@ -212,18 +441,24 @@ test("unicode escapes", async () => { "/tsconfig.json": "{}", "/src/1.ts": `"😃"`, "/src/2.ts": `"\\ud83d\\ude03"`, + "/src/3.ts": `"\\ud800a\\udc00"`, }); try { const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); const project = snapshot.getProject("/tsconfig.json")!; + const expectedTexts = new Map([ + ["/src/1.ts", "😃"], + ["/src/2.ts", "😃"], + ["/src/3.ts", "\ud800a\udc00"], + ]); - for (const file of ["/src/1.ts", "/src/2.ts"]) { + for (const file of expectedTexts.keys()) { const sourceFile = await project.program.getSourceFile(file); assert.ok(sourceFile); sourceFile.forEachChild(function visit(node) { if (isStringLiteral(node)) { - assert.equal(node.text, "😃"); + assert.equal(node.text, expectedTexts.get(file)); } node.forEachChild(visit); }); @@ -234,6 +469,38 @@ test("unicode escapes", async () => { } }); +test("template unicode escapes", async () => { + const api = spawnAPI({ + "/tsconfig.json": "{}", + "/src/index.ts": "`\\ud800${0}\\udc00`", + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = await project.program.getSourceFile("/src/index.ts"); + assert.ok(sourceFile); + + let sawHead = false; + let sawTail = false; + sourceFile.forEachChild(function visit(node) { + if (isTemplateHead(node)) { + assert.equal(node.text, "\ud800"); + sawHead = true; + } + else if (isTemplateTail(node)) { + assert.equal(node.text, "\udc00"); + sawTail = true; + } + node.forEachChild(visit); + }); + assert.ok(sawHead); + assert.ok(sawTail); + } + finally { + await api.close(); + } +}); + test("Object equality", async () => { const api = spawnAPI(); try { @@ -970,6 +1237,10 @@ export class Cache { assert.ok(sig.declaration); const node = await sig.declaration.resolve(project); assert.ok(node); + // The handle remembers its canonical project, so resolve() works without an argument. + const nodeFromCanonical = await sig.declaration.resolve(); + assert.ok(nodeFromCanonical); + assert.strictEqual(nodeFromCanonical.kind, node.kind); const methodPos = src.indexOf("getValue"); const methodSymbol = await project.checker.getSymbolAtPosition("/src/main.ts", methodPos); @@ -979,6 +1250,10 @@ export class Cache { assert.ok(methodNode); assert.strictEqual(methodNode.parent.kind, SyntaxKind.ClassDeclaration); assert.strictEqual(methodNode.parent.parent.kind, SyntaxKind.SourceFile); + // A symbol's declaration handles default to the symbol's canonical project. + const methodNodeFromCanonical = await methodSymbol.valueDeclaration.resolve(); + assert.ok(methodNodeFromCanonical); + assert.strictEqual(methodNodeFromCanonical.kind, methodNode.kind); } finally { await api.close(); @@ -1163,8 +1438,8 @@ export const value = 1; const symbol = await project.checker.getSymbolAtPosition("/src/mod.ts", animalPos); assert.ok(symbol); const members = await symbol.getMembers(); - assert.ok(members.length > 0); - const memberNames = members.map(m => m.name); + assert.ok(members.size > 0); + const memberNames = [...members.values()].map(m => m.name); assert.ok(memberNames.includes("name"), "should have 'name' member"); assert.ok(memberNames.includes("speak"), "should have 'speak' member"); } @@ -1183,8 +1458,8 @@ export const value = 1; const moduleSymbol = await project.checker.getSymbolAtLocation(sourceFile); assert.ok(moduleSymbol); const exports = await moduleSymbol.getExports(); - assert.ok(exports.length > 0); - const exportNames = exports.map(e => e.name); + assert.ok(exports.size > 0); + const exportNames = [...exports.values()].map(e => e.name); assert.ok(exportNames.includes("Animal"), "should export Animal"); assert.ok(exportNames.includes("value"), "should export value"); } @@ -1278,6 +1553,9 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; assert.ok(type.flags & TypeFlags.Object); const ref = type as TypeReference; assert.ok(ref.objectFlags & ObjectFlags.Reference); + assert.equal(type.isObjectType(), true); + assert.equal(type.isTypeReference(), true); + assert.equal(type.isLiteralType(), false); const target = await ref.getTarget(); assert.ok(target); assert.ok(target.flags & TypeFlags.Object); @@ -1294,6 +1572,8 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; const union = type as UnionOrIntersectionType; const types = await union.getTypes(); assert.ok(types.length >= 2); + assert.equal(type.isUnionType(), true); + assert.equal(type.isIntersectionType(), false); } finally { await api.close(); @@ -1313,6 +1593,37 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; } }); + test("UnionOrIntersectionType.getTypes() on a wrongly-cast type returns undefined without hitting the server", async () => { + const src = `export const s: string = ""; export const u: string | number = "";`; + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": src, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + + // `string` is neither a union/intersection nor a template literal type, + // so it has no constituent types. The client guards on the type's flags + // and returns undefined without ever sending a request the server cannot satisfy. + const sSymbol = await project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("s:")); + assert.ok(sSymbol); + const sType = await project.checker.getTypeOfSymbol(sSymbol); + assert.ok(sType); + assert.equal(await (sType as unknown as UnionOrIntersectionType).getTypes(), undefined); + + // A real union still returns its constituents. + const uSymbol = await project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("u:")); + assert.ok(uSymbol); + const uType = await project.checker.getTypeOfSymbol(uSymbol); + assert.ok(uType); + assert.equal((await (uType as UnionOrIntersectionType).getTypes()).length, 2); + } + finally { + await api.close(); + } + }); + test("IndexType.getTarget() returns the target type", async () => { const api = spawnAPI(typeFiles); try { @@ -1344,6 +1655,7 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; assert.ok(type); assert.ok(type.flags & TypeFlags.IndexedAccess, `Expected IndexedAccessType, got flags ${type.flags}`); const ia = type as IndexedAccessType; + assert.equal(type.isIndexedAccessType(), true); const objectType = await ia.getObjectType(); assert.ok(objectType); const indexType = await ia.getIndexType(); @@ -1365,6 +1677,7 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; assert.ok(type); assert.ok(type.flags & TypeFlags.Conditional, `Expected ConditionalType, got flags ${type.flags}`); const cond = type as ConditionalType; + assert.equal(type.isConditionalType(), true); const checkType = await cond.getCheckType(); assert.ok(checkType); const extendsType = await cond.getExtendsType(); @@ -1375,6 +1688,32 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; } }); + test("ConditionalType.getTrueType() and getFalseType()", async () => { + const api = spawnAPI(typeFiles); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const symbol = await project.checker.resolveName("Cond", SymbolFlags.TypeAlias, { document: "/src/types.ts", position: 0 }); + assert.ok(symbol); + const type = await project.checker.getDeclaredTypeOfSymbol(symbol); + assert.ok(type); + assert.ok(type.flags & TypeFlags.Conditional, `Expected ConditionalType, got flags ${type.flags}`); + + const trueType = await (type as ConditionalType).getTrueType(); + assert.ok(trueType, "should return the true-branch type"); + assert.ok(trueType.flags & TypeFlags.StringLiteral, `Expected StringLiteral for true branch, got flags ${trueType.flags}`); + assert.equal((trueType as LiteralType).value, "yes"); + + const falseType = await (type as ConditionalType).getFalseType(); + assert.ok(falseType, "should return the false-branch type"); + assert.ok(falseType.flags & TypeFlags.StringLiteral, `Expected StringLiteral for false branch, got flags ${falseType.flags}`); + assert.equal((falseType as LiteralType).value, "no"); + } + finally { + await api.close(); + } + }); + test("TemplateLiteralType.texts and getTypes()", async () => { const { type, api } = await getTypeAtName(spawnAPI(typeFiles), "tpl:"); try { @@ -1946,6 +2285,140 @@ describe("readFile callback semantics", () => { }); }); +describe("Checker - isArrayType / isTupleType", () => { + test("number[] is array, not tuple", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const xs: number[] = [];`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `export const xs: number[] = [];`; + const pos = src.indexOf("xs"); + const symbol = await project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = await project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + assert.equal(await project.checker.isArrayType(type), true); + assert.equal(await project.checker.isTupleType(type), false); + } + finally { + await api.close(); + } + }); + + test("readonly number[] is array", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const xs: readonly number[] = [];`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `export const xs: readonly number[] = [];`; + const pos = src.indexOf("xs"); + const symbol = await project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = await project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + assert.equal(await project.checker.isArrayType(type), true); + assert.equal(await project.checker.isTupleType(type), false); + } + finally { + await api.close(); + } + }); + + test("Array is array, not tuple", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const xs: Array = [];`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `export const xs: Array = [];`; + const pos = src.indexOf("xs"); + const symbol = await project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = await project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + assert.equal(await project.checker.isArrayType(type), true); + assert.equal(await project.checker.isTupleType(type), false); + } + finally { + await api.close(); + } + }); + + test("[number, string] is tuple, not array", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const tup: [number, string] = [1, "a"];`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `export const tup: [number, string] = [1, "a"];`; + const pos = src.indexOf("tup"); + const symbol = await project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = await project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + assert.equal(await project.checker.isArrayType(type), false); + assert.equal(await project.checker.isTupleType(type), true); + } + finally { + await api.close(); + } + }); + + test("readonly [number, string] is tuple, not array", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const tup: readonly [number, string] = [1, "a"];`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `export const tup: readonly [number, string] = [1, "a"];`; + const pos = src.indexOf("tup"); + const symbol = await project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = await project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + assert.equal(await project.checker.isArrayType(type), false); + assert.equal(await project.checker.isTupleType(type), true); + } + finally { + await api.close(); + } + }); + + test("string is neither array nor tuple", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const str: string = "";`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `export const str: string = "";`; + const pos = src.indexOf("str"); + const symbol = await project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = await project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + assert.equal(await project.checker.isArrayType(type), false); + assert.equal(await project.checker.isTupleType(type), false); + } + finally { + await api.close(); + } + }); +}); + describe("Checker - getReturnTypeOfSignature", () => { test("returns the return type of a function signature", async () => { const api = spawnAPI({ @@ -2138,7 +2611,7 @@ export class Derived extends Base { assert.ok(symbol); const type = await project.checker.getDeclaredTypeOfSymbol(symbol); assert.ok(type); - const baseTypes = await project.checker.getBaseTypes(type); + const baseTypes = await project.checker.getBaseTypes(type as InterfaceType); assert.ok(baseTypes.length > 0, "Should have at least one base type"); const baseSymbol = await baseTypes[0].getSymbol(); assert.ok(baseSymbol); @@ -2170,7 +2643,7 @@ export interface Dog extends Animal { assert.ok(symbol); const type = await project.checker.getDeclaredTypeOfSymbol(symbol); assert.ok(type); - const baseTypes = await project.checker.getBaseTypes(type); + const baseTypes = await project.checker.getBaseTypes(type as InterfaceType); assert.ok(baseTypes.length > 0, "Should have at least one base type"); const baseSymbol = await baseTypes[0].getSymbol(); assert.ok(baseSymbol); @@ -2180,17 +2653,224 @@ export interface Dog extends Animal { await api.close(); } }); -}); -describe("Checker - getPropertiesOfType", () => { - test("returns properties of an object type", async () => { + test("does not panic for a type alias to a generic interface instantiation", async () => { const api = spawnAPI({ "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), "/src/main.ts": ` -export interface Person { - name: string; - age: number; - greet(): void; +export interface Box { + value: T; +} +export type BoxOfString = Box; +`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = await project.program.getSourceFile("/src/main.ts"); + assert.ok(sourceFile); + const typeAlias = sourceFile.statements.find(isTypeAliasDeclaration); + assert.ok(typeAlias); + const type = await project.checker.getTypeAtLocation(typeAlias); + assert.ok(type); + // A generic interface instantiation produces a type reference, not an + // interface type, so it has no base types and yields []. + const baseTypes = await project.checker.getBaseTypes(type as InterfaceType); + assert.deepEqual(baseTypes, []); + } + finally { + await api.close(); + } + }); +}); + +describe("Type - getBaseTypes", () => { + test("returns base types for a class type and undefined for a non-class/interface", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +export class Base { + x: number = 0; +} +export class Derived extends Base { + y: string = ""; +} +export const n: number = 0; +`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `\nexport class Base {\n x: number = 0;\n}\nexport class Derived extends Base {\n y: string = "";\n}\nexport const n: number = 0;\n`; + + const derivedSymbol = await project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("Derived")); + assert.ok(derivedSymbol); + const derivedType = await project.checker.getDeclaredTypeOfSymbol(derivedSymbol); + assert.ok(derivedType.isClassOrInterface(), "Derived should be a class/interface type"); + const baseTypes = await derivedType.getBaseTypes(); + assert.ok(baseTypes && baseTypes.length > 0, "class type should have base types"); + const baseSymbol = await baseTypes![0].getSymbol(); + assert.equal(baseSymbol?.name, "Base"); + + // A primitive type is not a class/interface, so getBaseTypes() is undefined. + const numberSymbol = await project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("n:")); + assert.ok(numberSymbol); + const numberType = await project.checker.getTypeOfSymbol(numberSymbol); + assert.ok(numberType); + assert.equal(numberType.isClassOrInterface(), false); + assert.equal(await numberType.getBaseTypes(), undefined); + } + finally { + await api.close(); + } + }); +}); + +describe("Type - isErrorType", () => { + test("identifies the error type from an unresolvable annotation", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +declare const good: string; +declare const bad: ThisTypeDoesNotExist; +`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `\ndeclare const good: string;\ndeclare const bad: ThisTypeDoesNotExist;\n`; + + const badSymbol = await project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("bad")); + assert.ok(badSymbol); + const badType = await project.checker.getTypeOfSymbol(badSymbol); + assert.ok(badType); + assert.ok(badType.isErrorType(), "unresolved annotation should yield the error type"); + assert.ok(isErrorType(badType)); + + const goodSymbol = await project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("good")); + assert.ok(goodSymbol); + const goodType = await project.checker.getTypeOfSymbol(goodSymbol); + assert.ok(goodType); + assert.equal(goodType.isErrorType(), false, "string type is not the error type"); + assert.equal(isErrorType(goodType), false); + } + finally { + await api.close(); + } + }); +}); + +describe("Checker - well-known symbols", () => { + test("isUnknownSymbol identifies the aliased unknown symbol", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +export const value = 1; +export type Alias = typeof value; +`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `\nexport const value = 1;\nexport type Alias = typeof value;\n`; + + // A real symbol is not the unknown/undefined symbol. + const valueSymbol = await project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("value")); + assert.ok(valueSymbol); + assert.equal(await project.checker.isUnknownSymbol(valueSymbol), false); + assert.equal(await project.checker.isUndefinedSymbol(valueSymbol), false); + } + finally { + await api.close(); + } + }); +}); + +describe("Symbol - escaped names and tables", () => { + test("getExports/getMembers return a cached Map keyed by escaped name", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +export class Animal { + name: string = ""; + speak(): void {} +} +export const value = 1; +`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = await project.program.getSourceFile("/src/main.ts"); + assert.ok(sourceFile); + const moduleSymbol = await project.checker.getSymbolAtLocation(sourceFile); + assert.ok(moduleSymbol); + + const exports = await moduleSymbol.getExports(); + assert.ok(exports.has(escapeLeadingUnderscores("Animal"))); + assert.ok(exports.get(escapeLeadingUnderscores("value"))); + // Calling again returns the same cached Map instance. + assert.strictEqual(await moduleSymbol.getExports(), exports); + + const animal = exports.get(escapeLeadingUnderscores("Animal"))!; + const members = await animal.getMembers(); + assert.ok(members.get(escapeLeadingUnderscores("name"))); + assert.ok(members.get(escapeLeadingUnderscores("speak"))); + assert.strictEqual(await animal.getMembers(), members); + } + finally { + await api.close(); + } + }); + + test("anonymous type symbol has a __-escaped name, never the \\xFE sentinel", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +export const obj: { a: number } = { a: 1 }; +`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `\nexport const obj: { a: number } = { a: 1 };\n`; + const objSymbol = await project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("obj")); + assert.ok(objSymbol); + const objType = await project.checker.getTypeOfSymbol(objSymbol); + assert.ok(objType); + const typeSymbol = await objType.getSymbol(); + assert.ok(typeSymbol); + // The anonymous type literal symbol is internally named; over the wire + // it must be the "__type" escaped form, not the raw "\xFE" sentinel. + assert.equal(typeSymbol.escapedName, InternalSymbolName.Type); + assert.ok(!typeSymbol.escapedName.includes("\xFE")); + } + finally { + await api.close(); + } + }); +}); + +describe("ast - escapeLeadingUnderscores", () => { + test("round-trips display and escaped names", () => { + assert.equal(escapeLeadingUnderscores("foo"), "foo"); + assert.equal(escapeLeadingUnderscores("_foo"), "_foo"); + assert.equal(escapeLeadingUnderscores("__foo"), "___foo"); + assert.equal(unescapeLeadingUnderscores("foo" as __String), "foo"); + assert.equal(unescapeLeadingUnderscores("__type" as __String), "__type"); + assert.equal(unescapeLeadingUnderscores("___foo" as __String), "__foo"); + }); +}); + +describe("Checker - getPropertiesOfType", () => { + test("returns properties of an object type", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +export interface Person { + name: string; + age: number; + greet(): void; } export declare const p: Person; `, @@ -2324,7 +3004,7 @@ describe("Checker - getTypeArguments", () => { assert.ok(symbol); const type = await project.checker.getTypeOfSymbol(symbol); assert.ok(type); - const typeArgs = await project.checker.getTypeArguments(type); + const typeArgs = await project.checker.getTypeArguments(type as TypeReference); assert.ok(typeArgs.length > 0, "Should have type arguments"); assert.ok(typeArgs[0].flags & TypeFlags.Number, `Expected number type argument, got flags ${typeArgs[0].flags}`); } @@ -2332,6 +3012,338 @@ describe("Checker - getTypeArguments", () => { await api.close(); } }); + + test("a wrongly-typed call throws on the client without taking down the server", async () => { + const src = `export const s: string = ""; export const arr: Array = [1];`; + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": src, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + + // `string` is not a type reference. When getTypeArguments is reached + // with one, the server panics, but the per-request panic recovery + // converts that into an error response rather than crashing the process. + const sSymbol = await project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("s:")); + assert.ok(sSymbol); + const sType = await project.checker.getTypeOfSymbol(sSymbol); + assert.ok(sType); + await assert.rejects(() => project.checker.getTypeArguments(sType as unknown as TypeReference)); // @sync: assert.throws(() => project.checker.getTypeArguments(sType as unknown as TypeReference)); + + // The server survived: a subsequent valid request still succeeds. + const arrSymbol = await project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("arr:")); + assert.ok(arrSymbol); + const arrType = await project.checker.getTypeOfSymbol(arrSymbol); + assert.ok(arrType); + const typeArgs = await project.checker.getTypeArguments(arrType as TypeReference); + assert.ok(typeArgs.length > 0, "Server should still serve valid requests"); + } + finally { + await api.close(); + } + }); +}); + +describe("Checker - getBaseConstraintOfType", () => { + test("returns the base constraint of a type parameter", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export function identity(x: T): T { return x; }`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `export function identity(x: T): T { return x; }`; + const pos = src.indexOf("identity<"); + const symbol = await project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = await project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + const sigs = await project.checker.getSignaturesOfType(type, SignatureKind.Call); + assert.ok(sigs.length > 0); + const typeParams = await sigs[0].getTypeParameters(); + const constraint = await project.checker.getBaseConstraintOfType(typeParams[0]); + assert.ok(constraint, "Should resolve a base constraint"); + assert.ok(constraint.flags & TypeFlags.String, `Expected string constraint, got flags ${constraint.flags}`); + } + finally { + await api.close(); + } + }); + + test("returns undefined for a non-instantiable type", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const x: number = 1;`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const pos = `export const x: number = 1;`.indexOf("x:"); + const symbol = await project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = await project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + const constraint = await project.checker.getBaseConstraintOfType(type); + assert.equal(constraint, undefined); + } + finally { + await api.close(); + } + }); +}); + +describe("Checker - getPropertyOfType", () => { + test("returns a named property symbol of a type", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +export interface Person { + name: string; + age: number; +} +export declare const p: Person; +`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `\nexport interface Person {\n name: string;\n age: number;\n}\nexport declare const p: Person;\n`; + const pos = src.indexOf("p: Person"); + const symbol = await project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = await project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + const nameProp = await project.checker.getPropertyOfType(type, "name"); + assert.ok(nameProp, "Should find 'name' property"); + assert.equal(nameProp.name, "name"); + const missing = await project.checker.getPropertyOfType(type, "doesNotExist"); + assert.equal(missing, undefined); + } + finally { + await api.close(); + } + }); +}); + +describe("Checker - getConstantValue", () => { + test("returns numeric value of an enum member", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export enum E { A = 1, B = 2 }`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = await project.program.getSourceFile("/src/main.ts"); + assert.ok(sourceFile); + let memberB: Node | undefined; + sourceFile.forEachChild(function visit(node) { + if (node.kind === SyntaxKind.EnumMember) { + const text = sourceFile.text.slice(node.pos, node.end).trim(); + if (text.startsWith("B")) memberB = node; + } + node.forEachChild(visit); + }); + assert.ok(memberB, "Should find enum member B"); + const value = await project.checker.getConstantValue(memberB); + assert.equal(value, 2); + } + finally { + await api.close(); + } + }); + + test("returns string value of a string-initialized enum member", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export enum Color { Red = "red" }`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = await project.program.getSourceFile("/src/main.ts"); + assert.ok(sourceFile); + let member: Node | undefined; + sourceFile.forEachChild(function visit(node) { + if (node.kind === SyntaxKind.EnumMember) member = node; + node.forEachChild(visit); + }); + assert.ok(member); + const value = await project.checker.getConstantValue(member); + assert.equal(value, "red"); + } + finally { + await api.close(); + } + }); +}); + +describe("Checker - getSignatureFromDeclaration", () => { + test("returns the signature of a function declaration", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export function add(a: number, b: number): number { return a + b; }`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = await project.program.getSourceFile("/src/main.ts"); + assert.ok(sourceFile); + let funcDecl: Node | undefined; + sourceFile.forEachChild(function visit(node) { + if (isFunctionDeclaration(node)) funcDecl = node; + node.forEachChild(visit); + }); + assert.ok(funcDecl, "Should find the function declaration"); + const sig = await project.checker.getSignatureFromDeclaration(funcDecl); + assert.ok(sig, "Should resolve a signature"); + assert.equal(sig.parameters.length, 2); + const returnType = await project.checker.getReturnTypeOfSignature(sig); + assert.ok(returnType); + assert.ok(returnType.flags & TypeFlags.Number); + } + finally { + await api.close(); + } + }); +}); + +describe("Checker - getExportSpecifierLocalTargetSymbol", () => { + test("resolves the local target of an export specifier", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +const value = 42; +export { value as renamed }; +`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = await project.program.getSourceFile("/src/main.ts"); + assert.ok(sourceFile); + let exportSpecifier: Node | undefined; + sourceFile.forEachChild(function visit(node) { + if (node.kind === SyntaxKind.ExportSpecifier) exportSpecifier = node; + node.forEachChild(visit); + }); + assert.ok(exportSpecifier, "Should find the export specifier"); + const target = await project.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); + assert.ok(target, "Should resolve a local target symbol"); + assert.equal(target.name, "value"); + } + finally { + await api.close(); + } + }); +}); + +describe("Checker - getAliasedSymbol", () => { + test("resolves an import alias to its target symbol", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/foo.ts": `export const foo = 42;`, + "/src/main.ts": `import { foo } from "./foo";\nexport const usage = foo;`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const pos = `import { foo } from "./foo";`.indexOf("foo }"); + const aliasSymbol = await project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(aliasSymbol); + assert.ok(aliasSymbol.flags & SymbolFlags.Alias, "Import binding should be an alias"); + const aliased = await project.checker.getAliasedSymbol(aliasSymbol); + assert.ok(aliased, "Should resolve the aliased symbol"); + assert.equal(aliased.name, "foo"); + assert.ok(!(aliased.flags & SymbolFlags.Alias), "Target should not be an alias"); + } + finally { + await api.close(); + } + }); +}); + +describe("Checker - getExportsOfModule", () => { + test("returns all exports including re-exports via 'export *'", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/inner.ts": `export const innerValue = 1;`, + "/src/index.ts": ` +export const direct = 1; +export * from "./inner"; +`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = await project.program.getSourceFile("/src/index.ts"); + assert.ok(sourceFile); + const moduleSymbol = await project.checker.getSymbolAtLocation(sourceFile); + assert.ok(moduleSymbol, "Source file should have a module symbol"); + const exports = await project.checker.getExportsOfModule(moduleSymbol); + const names = exports.map(e => e.name); + assert.ok(names.includes("direct"), "should include directly-declared export"); + assert.ok(names.includes("innerValue"), "should include 'export *' re-export"); + } + finally { + await api.close(); + } + }); +}); + +describe("Symbol - getDocumentationComment and getJsDocTags", () => { + const docFiles = { + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +/** + * Adds two numbers together. + * @param a the first number + * @returns the sum + */ +export function add(a: number, b: number): number { return a + b; } +`, + }; + + test("getDocumentationComment returns the leading comment text", async () => { + const api = spawnAPI(docFiles); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const pos = docFiles["/src/main.ts"].indexOf("add(a"); + const symbol = await project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const doc = await symbol.getDocumentationComment(project.checker); + assert.ok(doc.includes("Adds two numbers together"), `Expected documentation, got: ${doc}`); + assert.ok(!doc.includes("@param"), "Documentation comment should not include tags"); + } + finally { + await api.close(); + } + }); + + test("getJsDocTags returns structured tag name/text pairs", async () => { + const api = spawnAPI(docFiles); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const pos = docFiles["/src/main.ts"].indexOf("add(a"); + const symbol = await project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const tags = await symbol.getJsDocTags(project.checker); + const param = tags.find(t => t.name === "param"); + assert.ok(param, `Expected a @param tag, got: ${JSON.stringify(tags)}`); + assert.equal(param.text, "a the first number"); + const returns = tags.find(t => t.name === "returns"); + assert.ok(returns, `Expected a @returns tag, got: ${JSON.stringify(tags)}`); + assert.equal(returns.text, "the sum"); + } + finally { + await api.close(); + } + }); }); describe("TypeParameter - isThisType", () => { @@ -3590,6 +4602,113 @@ describe("Program - diagnostics", () => { await api.close(); } }); + + test("getBindDiagnostics", async () => { + const source = `let x = 1;\nlet x = 2;`; + const api = spawnAPI({ + "/tsconfig.json": "{}", + "/src/index.ts": source, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const diags = await project.program.getBindDiagnostics("/src/index.ts"); + assert.deepEqual(diags, [ + { + fileName: "/src/index.ts", + ...rangeOf(source, "x", 0), + code: 2451, + category: DiagnosticCategory.Error, + text: "Cannot redeclare block-scoped variable 'x'.", + }, + { + fileName: "/src/index.ts", + ...rangeOf(source, "x", 1), + code: 2451, + category: DiagnosticCategory.Error, + text: "Cannot redeclare block-scoped variable 'x'.", + }, + ]); + } + finally { + await api.close(); + } + }); + + test("getProgramDiagnostics", async () => { + const config = `{ "compilerOptions": { "moduleResolution": "bundler", "module": "nodenext" } }`; + const api = spawnAPI({ + "/tsconfig.json": config, + "/src/index.ts": `export const x = 1;`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const diags = await project.program.getProgramDiagnostics(); + assert.deepEqual(diags, [ + { + fileName: "/tsconfig.json", + ...rangeOf(config, `"bundler"`), + code: 5095, + category: DiagnosticCategory.Error, + text: "Option 'bundler' can only be used when 'module' is set to 'preserve', 'commonjs', or 'es2015' or later.", + }, + { + fileName: "/tsconfig.json", + ...rangeOf(config, `"bundler"`), + code: 5109, + category: DiagnosticCategory.Error, + text: "Option 'moduleResolution' must be set to 'NodeNext' (or left unspecified) when option 'module' is set to 'NodeNext'.", + }, + ]); + } + finally { + await api.close(); + } + }); + + test("getGlobalDiagnostics", async () => { + const api = spawnAPI({ + "/tsconfig.json": "{}", + "/src/index.ts": `export const x = 1;`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const diags = await project.program.getGlobalDiagnostics(); + assert.deepEqual(diags, []); + } + finally { + await api.close(); + } + }); + + test("getGlobalDiagnostics returns file-less diagnostics from the checker", async () => { + const api = spawnAPI({ + "/tsconfig.json": `{ "compilerOptions": { "noLib": true } }`, + "/src/index.ts": `export const x = [1, 2, 3];`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const diags = await project.program.getGlobalDiagnostics(); + // With noLib, the checker reports "Cannot find global type" diagnostics that + // are not associated with any source file. + assert.ok(diags.length > 0, "expected global diagnostics to be reported"); + for (const diag of diags) { + assert.equal(diag.fileName, undefined); + assert.equal(diag.code, 2318); + assert.equal(diag.category, DiagnosticCategory.Error); + } + assert.ok( + diags.some(d => d.text === "Cannot find global type 'Array'."), + "expected a global diagnostic for the 'Array' type", + ); + } + finally { + await api.close(); + } + }); }); describe("Checker - getReferencedSymbolsForNode", () => { @@ -3642,6 +4761,138 @@ describe("Checker - getSignatureUsage", () => { }); }); +describe("getDefaultProjectForFile", () => { + test("finds inferred project for d.ts in node_modules after openFiles", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/index.ts": `export const x = 1;`, + "/node_modules/my-lib/package.json": JSON.stringify({ name: "my-lib", types: "./index.d.ts" }), + "/node_modules/my-lib/index.d.ts": `export declare const foo: string;`, + }); + try { + const snapshot = await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + + // The d.ts is not imported, so it is not in the project's program + const dtsSf = await project.program.getSourceFile("/node_modules/my-lib/index.d.ts"); + assert.equal(dtsSf, undefined, "d.ts not in import graph should not be found via project.program.getSourceFile"); + + // Before opening the file, getDefaultProjectForFile returns undefined (no error) + const noProject = await snapshot.getDefaultProjectForFile("/node_modules/my-lib/index.d.ts"); + assert.equal(noProject, undefined, "getDefaultProjectForFile returns undefined for unloaded file"); + + // Load the file into the inferred project via updateSnapshot openFiles + const snapshot2 = await api.updateSnapshot({ openFiles: ["/node_modules/my-lib/index.d.ts"] }); + const defaultProject = await snapshot2.getDefaultProjectForFile("/node_modules/my-lib/index.d.ts"); + assert.ok(defaultProject, "getDefaultProjectForFile should find inferred project after openFiles"); + + const fooPos = `export declare const foo: string;`.indexOf("foo"); + const fooType = await defaultProject.checker.getTypeAtPosition("/node_modules/my-lib/index.d.ts", fooPos); + assert.ok(fooType); + assert.ok(fooType.flags & TypeFlags.String); + } + finally { + await api.close(); + } + }); + + test("keeps previously opened files open across subsequent openFiles calls", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/index.ts": `export const x = 1;`, + "/node_modules/my-lib/package.json": JSON.stringify({ name: "my-lib", types: "./index.d.ts" }), + "/node_modules/my-lib/index.d.ts": `export declare const foo: string;`, + "/node_modules/other-lib/package.json": JSON.stringify({ name: "other-lib", types: "./index.d.ts" }), + "/node_modules/other-lib/index.d.ts": `export declare const bar: number;`, + }); + try { + await api.updateSnapshot({ openProject: "/tsconfig.json" }); + await api.updateSnapshot({ openFiles: ["/node_modules/my-lib/index.d.ts"] }); + + // Opening a second file in a later snapshot must not close the first one. + const snapshot = await api.updateSnapshot({ openFiles: ["/node_modules/other-lib/index.d.ts"] }); + + const firstProject = await snapshot.getDefaultProjectForFile("/node_modules/my-lib/index.d.ts"); + assert.ok(firstProject, "previously opened file should remain in the inferred project"); + const secondProject = await snapshot.getDefaultProjectForFile("/node_modules/other-lib/index.d.ts"); + assert.ok(secondProject, "newly opened file should be in the inferred project"); + } + finally { + await api.close(); + } + }); + + test("opening a file resolves to a configured project via ancestor search", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/index.ts": `export const x = 1;`, + }); + try { + // Open the file without first opening the project. Like LSP's didOpen, this + // should search ancestor directories for a tsconfig that contains the file. + const snapshot = await api.updateSnapshot({ openFiles: ["/src/index.ts"] }); + const defaultProject = await snapshot.getDefaultProjectForFile("/src/index.ts"); + assert.ok(defaultProject, "should find a project for the opened file"); + assert.equal( + defaultProject.configFileName, + "/tsconfig.json", + "opened file should resolve to the containing configured project, not the inferred project", + ); + } + finally { + await api.close(); + } + }); + + test("closeProjects releases a project opened via openProjects", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/index.ts": `export const x = 1;`, + }); + try { + const opened = await api.updateSnapshot({ openProjects: ["/tsconfig.json"] }); + assert.ok(opened.getProject("/tsconfig.json"), "project should be open after openProjects"); + + const closed = await api.updateSnapshot({ closeProjects: ["/tsconfig.json"] }); + assert.equal( + closed.getProject("/tsconfig.json"), + undefined, + "project should be unloaded after closeProjects", + ); + } + finally { + await api.close(); + } + }); + + test("closeFiles releases a file opened via openFiles", async () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/index.ts": `export const x = 1;`, + "/node_modules/my-lib/package.json": JSON.stringify({ name: "my-lib", types: "./index.d.ts" }), + "/node_modules/my-lib/index.d.ts": `export declare const foo: string;`, + }); + try { + await api.updateSnapshot({ openProject: "/tsconfig.json" }); + const opened = await api.updateSnapshot({ openFiles: ["/node_modules/my-lib/index.d.ts"] }); + assert.ok( + await opened.getDefaultProjectForFile("/node_modules/my-lib/index.d.ts"), + "file should resolve to a project after openFiles", + ); + + const closed = await api.updateSnapshot({ closeFiles: ["/node_modules/my-lib/index.d.ts"] }); + assert.equal( + await closed.getDefaultProjectForFile("/node_modules/my-lib/index.d.ts"), + undefined, + "file should no longer resolve to a project after closeFiles", + ); + } + finally { + await api.close(); + } + }); +}); + test("Benchmarks", async () => { await runBenchmarks({ singleIteration: true }); }); diff --git a/_packages/native-preview/test/sync/api.test.ts b/_packages/native-preview/test/sync/api.test.ts index 74041ca1e85..4a2ebac0dca 100644 --- a/_packages/native-preview/test/sync/api.test.ts +++ b/_packages/native-preview/test/sync/api.test.ts @@ -7,9 +7,12 @@ // Regenerate: npm run generate (from _packages/native-preview) // import { + type __String, cast, + escapeLeadingUnderscores, type Expression, getSynthesizedDeepClone, + InternalSymbolName, isCallExpression, isFunctionDeclaration, isIdentifier, @@ -21,11 +24,14 @@ import { isTemplateHead, isTemplateMiddle, isTemplateTail, + isTypeAliasDeclaration, isTypeNode, isVariableDeclarationList, type Node, + type NodeArray, NodeFlags, SyntaxKind, + unescapeLeadingUnderscores, } from "@typescript/native-preview/unstable/ast"; import { createArrayTypeNode, @@ -49,9 +55,12 @@ import { type FreshableType, type IndexedAccessType, type IndexType, + type InterfaceType, type IntrinsicType, + isErrorType, type LiteralType, ModifierFlags, + ModuleKind, ObjectFlags, SignatureKind, type StringMappingType, @@ -93,6 +102,29 @@ describe("API", () => { }); }); +describe("Checker - getImmediateAliasedSymbol", () => { + test("resolves one level of alias indirection", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/foo.ts": `export const foo = 42;`, + "/src/main.ts": `import { foo } from "./foo";\nexport const usage = foo;`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const pos = `import { foo } from "./foo";`.indexOf("foo }"); + const aliasSymbol = project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(aliasSymbol); + const aliased = project.checker.getImmediateAliasedSymbol(aliasSymbol); + assert.ok(aliased, "Should resolve the immediate aliased symbol"); + assert.equal(aliased.name, "foo"); + } + finally { + api.close(); + } + }); +}); + describe("Snapshot", () => { test("updateSnapshot returns snapshot with projects", () => { const api = spawnAPI(); @@ -162,7 +194,167 @@ describe("Snapshot", () => { }); }); +describe("Checker - getApparentType", () => { + test("returns the apparent type of a literal type", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const x = "hello" as const;`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const pos = `export const x = "hello" as const;`.indexOf("x ="); + const symbol = project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + assert.equal(type.isLiteralType(), true); + assert.equal(type.isStringLiteralType(), true); + assert.equal(type.isIntrinsicType(), false); + const apparent = project.checker.getApparentType(type); + assert.ok(apparent); + assert.ok(apparent.id > 0); + } + finally { + api.close(); + } + }); +}); + +describe("Checker - getMemberInModuleExports", () => { + test("returns a named export when present", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/index.ts": `export const direct = 1;`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = project.program.getSourceFile("/src/index.ts"); + assert.ok(sourceFile); + const moduleSymbol = project.checker.getSymbolAtLocation(sourceFile); + assert.ok(moduleSymbol); + const found = project.checker.getMemberInModuleExports(moduleSymbol, "direct"); + assert.ok(found); + assert.equal(found.name, "direct"); + const missing = project.checker.getMemberInModuleExports(moduleSymbol, "missing"); + assert.equal(missing, undefined); + } + finally { + api.close(); + } + }); +}); + describe("SourceFile", () => { + test("getSourceFileNames returns all program files, not just root files", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ + compilerOptions: { + moduleResolution: "node10", + noLib: true, + }, + }), + "/src/index.ts": `import { foo } from "./foo";\nimport { bar } from "my-lib";\nexport const result = foo + bar;`, + "/src/foo.ts": `export const foo = 42;`, + "/node_modules/my-lib/package.json": JSON.stringify({ name: "my-lib", types: "./index.d.ts" }), + "/node_modules/my-lib/index.d.ts": `export declare const bar: number;`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const fileNames = project.program.getSourceFileNames(); + assert.deepEqual(fileNames, [ + "/src/foo.ts", + "/node_modules/my-lib/index.d.ts", + "/src/index.ts", + ]); + } + finally { + api.close(); + } + }); + + test("source file metadata identifies external library and default library files", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ + compilerOptions: { + moduleResolution: "node10", + }, + }), + "/src/index.ts": `import { bar } from "my-lib";\nexport const result = bar;`, + "/node_modules/my-lib/package.json": JSON.stringify({ name: "my-lib", types: "./index.d.ts" }), + "/node_modules/my-lib/index.d.ts": `export declare const bar: number;`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const program = project.program; + + const index = program.getSourceFile("/src/index.ts"); + assert.ok(index); + assert.equal(program.isSourceFileFromExternalLibrary(index), false); + assert.equal(program.isSourceFileDefaultLibrary(index), false); + + const lib = program.getSourceFile("/node_modules/my-lib/index.d.ts"); + assert.ok(lib); + assert.equal(program.isSourceFileFromExternalLibrary(lib), true); + assert.equal(program.isSourceFileDefaultLibrary(lib), false); + + const fileNames = program.getSourceFileNames(); + const defaultLibName = fileNames.find(name => name.endsWith("lib.d.ts") || name.includes("/lib.")); + assert.ok(defaultLibName, "expected a default library file in the program"); + const defaultLib = program.getSourceFile(defaultLibName); + assert.ok(defaultLib); + assert.equal(program.isSourceFileDefaultLibrary(defaultLib), true); + } + finally { + api.close(); + } + }); + + test("source file metadata reports implied node format", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ + compilerOptions: { + module: "nodenext", + moduleResolution: "nodenext", + }, + }), + "/src/index.ts": `export const x = 1;`, + "/src/esm.mts": `export const e = 1;`, + "/src/cjs.cts": `export const c = 1;`, + "/esm/package.json": JSON.stringify({ type: "module" }), + "/esm/index.ts": `export const m = 1;`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const program = snapshot.getProject("/tsconfig.json")!.program; + + const mts = program.getSourceFile("/src/esm.mts"); + assert.ok(mts); + assert.equal((program.getSourceFileMetadata(mts.fileName))?.impliedNodeFormat, ModuleKind.ESNext); + assert.equal((program.getSourceFileMetadataByPath(mts.path))?.impliedNodeFormat, ModuleKind.ESNext); + + const cts = program.getSourceFile("/src/cjs.cts"); + assert.ok(cts); + assert.equal((program.getSourceFileMetadata(cts.fileName))?.impliedNodeFormat, ModuleKind.CommonJS); + + // A plain .ts file with no nearby `"type": "module"` is CommonJS. + const index = program.getSourceFile("/src/index.ts"); + assert.ok(index); + assert.equal((program.getSourceFileMetadata(index.fileName))?.impliedNodeFormat, ModuleKind.CommonJS); + + // A plain .ts file under a `"type": "module"` package is ESM. + const esmIndex = program.getSourceFile("/esm/index.ts"); + assert.ok(esmIndex); + assert.equal((program.getSourceFileMetadata(esmIndex.fileName))?.impliedNodeFormat, ModuleKind.ESNext); + } + finally { + api.close(); + } + }); + test("file properties", () => { const api = spawnAPI(); try { @@ -213,6 +405,43 @@ describe("SourceFile", () => { api.close(); } }); + + test("forEachChild with visitList does not visit array children twice", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ files: ["/input.ts"] }), + "/input.ts": `let arrow = () => {}`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = project.program.getSourceFile("/input.ts"); + + assert.ok(sourceFile); + + const visited: { kind: SyntaxKind; pos: number; end: number; }[] = []; + (function walk(node: Node): void { + visited.push({ kind: node.kind, pos: node.pos, end: node.end }); + node.forEachChild(walk, (nodes: NodeArray) => { + for (let i = 0; i < nodes.length; i++) { + walk(nodes[i]); + } + return undefined; + }); + })(sourceFile); + + // Each node should be visited exactly once, even when a visitList callback + // is supplied. Previously array children were visited twice. + const seen = new Set(); + for (const { kind, pos, end } of visited) { + const key = `${kind}.${pos}.${end}`; + assert.ok(!seen.has(key), `Node ${key} was visited more than once`); + seen.add(key); + } + } + finally { + api.close(); + } + }); }); test("unicode escapes", () => { @@ -220,18 +449,24 @@ test("unicode escapes", () => { "/tsconfig.json": "{}", "/src/1.ts": `"😃"`, "/src/2.ts": `"\\ud83d\\ude03"`, + "/src/3.ts": `"\\ud800a\\udc00"`, }); try { const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); const project = snapshot.getProject("/tsconfig.json")!; + const expectedTexts = new Map([ + ["/src/1.ts", "😃"], + ["/src/2.ts", "😃"], + ["/src/3.ts", "\ud800a\udc00"], + ]); - for (const file of ["/src/1.ts", "/src/2.ts"]) { + for (const file of expectedTexts.keys()) { const sourceFile = project.program.getSourceFile(file); assert.ok(sourceFile); sourceFile.forEachChild(function visit(node) { if (isStringLiteral(node)) { - assert.equal(node.text, "😃"); + assert.equal(node.text, expectedTexts.get(file)); } node.forEachChild(visit); }); @@ -242,6 +477,38 @@ test("unicode escapes", () => { } }); +test("template unicode escapes", () => { + const api = spawnAPI({ + "/tsconfig.json": "{}", + "/src/index.ts": "`\\ud800${0}\\udc00`", + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = project.program.getSourceFile("/src/index.ts"); + assert.ok(sourceFile); + + let sawHead = false; + let sawTail = false; + sourceFile.forEachChild(function visit(node) { + if (isTemplateHead(node)) { + assert.equal(node.text, "\ud800"); + sawHead = true; + } + else if (isTemplateTail(node)) { + assert.equal(node.text, "\udc00"); + sawTail = true; + } + node.forEachChild(visit); + }); + assert.ok(sawHead); + assert.ok(sawTail); + } + finally { + api.close(); + } +}); + test("Object equality", () => { const api = spawnAPI(); try { @@ -978,6 +1245,10 @@ export class Cache { assert.ok(sig.declaration); const node = sig.declaration.resolve(project); assert.ok(node); + // The handle remembers its canonical project, so resolve() works without an argument. + const nodeFromCanonical = sig.declaration.resolve(); + assert.ok(nodeFromCanonical); + assert.strictEqual(nodeFromCanonical.kind, node.kind); const methodPos = src.indexOf("getValue"); const methodSymbol = project.checker.getSymbolAtPosition("/src/main.ts", methodPos); @@ -987,6 +1258,10 @@ export class Cache { assert.ok(methodNode); assert.strictEqual(methodNode.parent.kind, SyntaxKind.ClassDeclaration); assert.strictEqual(methodNode.parent.parent.kind, SyntaxKind.SourceFile); + // A symbol's declaration handles default to the symbol's canonical project. + const methodNodeFromCanonical = methodSymbol.valueDeclaration.resolve(); + assert.ok(methodNodeFromCanonical); + assert.strictEqual(methodNodeFromCanonical.kind, methodNode.kind); } finally { api.close(); @@ -1171,8 +1446,8 @@ export const value = 1; const symbol = project.checker.getSymbolAtPosition("/src/mod.ts", animalPos); assert.ok(symbol); const members = symbol.getMembers(); - assert.ok(members.length > 0); - const memberNames = members.map(m => m.name); + assert.ok(members.size > 0); + const memberNames = [...members.values()].map(m => m.name); assert.ok(memberNames.includes("name"), "should have 'name' member"); assert.ok(memberNames.includes("speak"), "should have 'speak' member"); } @@ -1191,8 +1466,8 @@ export const value = 1; const moduleSymbol = project.checker.getSymbolAtLocation(sourceFile); assert.ok(moduleSymbol); const exports = moduleSymbol.getExports(); - assert.ok(exports.length > 0); - const exportNames = exports.map(e => e.name); + assert.ok(exports.size > 0); + const exportNames = [...exports.values()].map(e => e.name); assert.ok(exportNames.includes("Animal"), "should export Animal"); assert.ok(exportNames.includes("value"), "should export value"); } @@ -1286,6 +1561,9 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; assert.ok(type.flags & TypeFlags.Object); const ref = type as TypeReference; assert.ok(ref.objectFlags & ObjectFlags.Reference); + assert.equal(type.isObjectType(), true); + assert.equal(type.isTypeReference(), true); + assert.equal(type.isLiteralType(), false); const target = ref.getTarget(); assert.ok(target); assert.ok(target.flags & TypeFlags.Object); @@ -1302,6 +1580,8 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; const union = type as UnionOrIntersectionType; const types = union.getTypes(); assert.ok(types.length >= 2); + assert.equal(type.isUnionType(), true); + assert.equal(type.isIntersectionType(), false); } finally { api.close(); @@ -1321,6 +1601,37 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; } }); + test("UnionOrIntersectionType.getTypes() on a wrongly-cast type returns undefined without hitting the server", () => { + const src = `export const s: string = ""; export const u: string | number = "";`; + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": src, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + + // `string` is neither a union/intersection nor a template literal type, + // so it has no constituent types. The client guards on the type's flags + // and returns undefined without ever sending a request the server cannot satisfy. + const sSymbol = project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("s:")); + assert.ok(sSymbol); + const sType = project.checker.getTypeOfSymbol(sSymbol); + assert.ok(sType); + assert.equal((sType as unknown as UnionOrIntersectionType).getTypes(), undefined); + + // A real union still returns its constituents. + const uSymbol = project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("u:")); + assert.ok(uSymbol); + const uType = project.checker.getTypeOfSymbol(uSymbol); + assert.ok(uType); + assert.equal(((uType as UnionOrIntersectionType).getTypes()).length, 2); + } + finally { + api.close(); + } + }); + test("IndexType.getTarget() returns the target type", () => { const api = spawnAPI(typeFiles); try { @@ -1352,6 +1663,7 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; assert.ok(type); assert.ok(type.flags & TypeFlags.IndexedAccess, `Expected IndexedAccessType, got flags ${type.flags}`); const ia = type as IndexedAccessType; + assert.equal(type.isIndexedAccessType(), true); const objectType = ia.getObjectType(); assert.ok(objectType); const indexType = ia.getIndexType(); @@ -1373,6 +1685,7 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; assert.ok(type); assert.ok(type.flags & TypeFlags.Conditional, `Expected ConditionalType, got flags ${type.flags}`); const cond = type as ConditionalType; + assert.equal(type.isConditionalType(), true); const checkType = cond.getCheckType(); assert.ok(checkType); const extendsType = cond.getExtendsType(); @@ -1383,6 +1696,32 @@ export const tuple: readonly [number, string?, ...boolean[]] = [1]; } }); + test("ConditionalType.getTrueType() and getFalseType()", () => { + const api = spawnAPI(typeFiles); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const symbol = project.checker.resolveName("Cond", SymbolFlags.TypeAlias, { document: "/src/types.ts", position: 0 }); + assert.ok(symbol); + const type = project.checker.getDeclaredTypeOfSymbol(symbol); + assert.ok(type); + assert.ok(type.flags & TypeFlags.Conditional, `Expected ConditionalType, got flags ${type.flags}`); + + const trueType = (type as ConditionalType).getTrueType(); + assert.ok(trueType, "should return the true-branch type"); + assert.ok(trueType.flags & TypeFlags.StringLiteral, `Expected StringLiteral for true branch, got flags ${trueType.flags}`); + assert.equal((trueType as LiteralType).value, "yes"); + + const falseType = (type as ConditionalType).getFalseType(); + assert.ok(falseType, "should return the false-branch type"); + assert.ok(falseType.flags & TypeFlags.StringLiteral, `Expected StringLiteral for false branch, got flags ${falseType.flags}`); + assert.equal((falseType as LiteralType).value, "no"); + } + finally { + api.close(); + } + }); + test("TemplateLiteralType.texts and getTypes()", () => { const { type, api } = getTypeAtName(spawnAPI(typeFiles), "tpl:"); try { @@ -1954,6 +2293,140 @@ describe("readFile callback semantics", () => { }); }); +describe("Checker - isArrayType / isTupleType", () => { + test("number[] is array, not tuple", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const xs: number[] = [];`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `export const xs: number[] = [];`; + const pos = src.indexOf("xs"); + const symbol = project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + assert.equal(project.checker.isArrayType(type), true); + assert.equal(project.checker.isTupleType(type), false); + } + finally { + api.close(); + } + }); + + test("readonly number[] is array", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const xs: readonly number[] = [];`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `export const xs: readonly number[] = [];`; + const pos = src.indexOf("xs"); + const symbol = project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + assert.equal(project.checker.isArrayType(type), true); + assert.equal(project.checker.isTupleType(type), false); + } + finally { + api.close(); + } + }); + + test("Array is array, not tuple", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const xs: Array = [];`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `export const xs: Array = [];`; + const pos = src.indexOf("xs"); + const symbol = project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + assert.equal(project.checker.isArrayType(type), true); + assert.equal(project.checker.isTupleType(type), false); + } + finally { + api.close(); + } + }); + + test("[number, string] is tuple, not array", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const tup: [number, string] = [1, "a"];`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `export const tup: [number, string] = [1, "a"];`; + const pos = src.indexOf("tup"); + const symbol = project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + assert.equal(project.checker.isArrayType(type), false); + assert.equal(project.checker.isTupleType(type), true); + } + finally { + api.close(); + } + }); + + test("readonly [number, string] is tuple, not array", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const tup: readonly [number, string] = [1, "a"];`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `export const tup: readonly [number, string] = [1, "a"];`; + const pos = src.indexOf("tup"); + const symbol = project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + assert.equal(project.checker.isArrayType(type), false); + assert.equal(project.checker.isTupleType(type), true); + } + finally { + api.close(); + } + }); + + test("string is neither array nor tuple", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const str: string = "";`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `export const str: string = "";`; + const pos = src.indexOf("str"); + const symbol = project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + assert.equal(project.checker.isArrayType(type), false); + assert.equal(project.checker.isTupleType(type), false); + } + finally { + api.close(); + } + }); +}); + describe("Checker - getReturnTypeOfSignature", () => { test("returns the return type of a function signature", () => { const api = spawnAPI({ @@ -2146,7 +2619,7 @@ export class Derived extends Base { assert.ok(symbol); const type = project.checker.getDeclaredTypeOfSymbol(symbol); assert.ok(type); - const baseTypes = project.checker.getBaseTypes(type); + const baseTypes = project.checker.getBaseTypes(type as InterfaceType); assert.ok(baseTypes.length > 0, "Should have at least one base type"); const baseSymbol = baseTypes[0].getSymbol(); assert.ok(baseSymbol); @@ -2178,7 +2651,7 @@ export interface Dog extends Animal { assert.ok(symbol); const type = project.checker.getDeclaredTypeOfSymbol(symbol); assert.ok(type); - const baseTypes = project.checker.getBaseTypes(type); + const baseTypes = project.checker.getBaseTypes(type as InterfaceType); assert.ok(baseTypes.length > 0, "Should have at least one base type"); const baseSymbol = baseTypes[0].getSymbol(); assert.ok(baseSymbol); @@ -2188,17 +2661,224 @@ export interface Dog extends Animal { api.close(); } }); -}); -describe("Checker - getPropertiesOfType", () => { - test("returns properties of an object type", () => { + test("does not panic for a type alias to a generic interface instantiation", () => { const api = spawnAPI({ "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), "/src/main.ts": ` -export interface Person { - name: string; - age: number; - greet(): void; +export interface Box { + value: T; +} +export type BoxOfString = Box; +`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = project.program.getSourceFile("/src/main.ts"); + assert.ok(sourceFile); + const typeAlias = sourceFile.statements.find(isTypeAliasDeclaration); + assert.ok(typeAlias); + const type = project.checker.getTypeAtLocation(typeAlias); + assert.ok(type); + // A generic interface instantiation produces a type reference, not an + // interface type, so it has no base types and yields []. + const baseTypes = project.checker.getBaseTypes(type as InterfaceType); + assert.deepEqual(baseTypes, []); + } + finally { + api.close(); + } + }); +}); + +describe("Type - getBaseTypes", () => { + test("returns base types for a class type and undefined for a non-class/interface", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +export class Base { + x: number = 0; +} +export class Derived extends Base { + y: string = ""; +} +export const n: number = 0; +`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `\nexport class Base {\n x: number = 0;\n}\nexport class Derived extends Base {\n y: string = "";\n}\nexport const n: number = 0;\n`; + + const derivedSymbol = project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("Derived")); + assert.ok(derivedSymbol); + const derivedType = project.checker.getDeclaredTypeOfSymbol(derivedSymbol); + assert.ok(derivedType.isClassOrInterface(), "Derived should be a class/interface type"); + const baseTypes = derivedType.getBaseTypes(); + assert.ok(baseTypes && baseTypes.length > 0, "class type should have base types"); + const baseSymbol = baseTypes![0].getSymbol(); + assert.equal(baseSymbol?.name, "Base"); + + // A primitive type is not a class/interface, so getBaseTypes() is undefined. + const numberSymbol = project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("n:")); + assert.ok(numberSymbol); + const numberType = project.checker.getTypeOfSymbol(numberSymbol); + assert.ok(numberType); + assert.equal(numberType.isClassOrInterface(), false); + assert.equal(numberType.getBaseTypes(), undefined); + } + finally { + api.close(); + } + }); +}); + +describe("Type - isErrorType", () => { + test("identifies the error type from an unresolvable annotation", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +declare const good: string; +declare const bad: ThisTypeDoesNotExist; +`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `\ndeclare const good: string;\ndeclare const bad: ThisTypeDoesNotExist;\n`; + + const badSymbol = project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("bad")); + assert.ok(badSymbol); + const badType = project.checker.getTypeOfSymbol(badSymbol); + assert.ok(badType); + assert.ok(badType.isErrorType(), "unresolved annotation should yield the error type"); + assert.ok(isErrorType(badType)); + + const goodSymbol = project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("good")); + assert.ok(goodSymbol); + const goodType = project.checker.getTypeOfSymbol(goodSymbol); + assert.ok(goodType); + assert.equal(goodType.isErrorType(), false, "string type is not the error type"); + assert.equal(isErrorType(goodType), false); + } + finally { + api.close(); + } + }); +}); + +describe("Checker - well-known symbols", () => { + test("isUnknownSymbol identifies the aliased unknown symbol", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +export const value = 1; +export type Alias = typeof value; +`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `\nexport const value = 1;\nexport type Alias = typeof value;\n`; + + // A real symbol is not the unknown/undefined symbol. + const valueSymbol = project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("value")); + assert.ok(valueSymbol); + assert.equal(project.checker.isUnknownSymbol(valueSymbol), false); + assert.equal(project.checker.isUndefinedSymbol(valueSymbol), false); + } + finally { + api.close(); + } + }); +}); + +describe("Symbol - escaped names and tables", () => { + test("getExports/getMembers return a cached Map keyed by escaped name", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +export class Animal { + name: string = ""; + speak(): void {} +} +export const value = 1; +`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = project.program.getSourceFile("/src/main.ts"); + assert.ok(sourceFile); + const moduleSymbol = project.checker.getSymbolAtLocation(sourceFile); + assert.ok(moduleSymbol); + + const exports = moduleSymbol.getExports(); + assert.ok(exports.has(escapeLeadingUnderscores("Animal"))); + assert.ok(exports.get(escapeLeadingUnderscores("value"))); + // Calling again returns the same cached Map instance. + assert.strictEqual(moduleSymbol.getExports(), exports); + + const animal = exports.get(escapeLeadingUnderscores("Animal"))!; + const members = animal.getMembers(); + assert.ok(members.get(escapeLeadingUnderscores("name"))); + assert.ok(members.get(escapeLeadingUnderscores("speak"))); + assert.strictEqual(animal.getMembers(), members); + } + finally { + api.close(); + } + }); + + test("anonymous type symbol has a __-escaped name, never the \\xFE sentinel", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +export const obj: { a: number } = { a: 1 }; +`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `\nexport const obj: { a: number } = { a: 1 };\n`; + const objSymbol = project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("obj")); + assert.ok(objSymbol); + const objType = project.checker.getTypeOfSymbol(objSymbol); + assert.ok(objType); + const typeSymbol = objType.getSymbol(); + assert.ok(typeSymbol); + // The anonymous type literal symbol is internally named; over the wire + // it must be the "__type" escaped form, not the raw "\xFE" sentinel. + assert.equal(typeSymbol.escapedName, InternalSymbolName.Type); + assert.ok(!typeSymbol.escapedName.includes("\xFE")); + } + finally { + api.close(); + } + }); +}); + +describe("ast - escapeLeadingUnderscores", () => { + test("round-trips display and escaped names", () => { + assert.equal(escapeLeadingUnderscores("foo"), "foo"); + assert.equal(escapeLeadingUnderscores("_foo"), "_foo"); + assert.equal(escapeLeadingUnderscores("__foo"), "___foo"); + assert.equal(unescapeLeadingUnderscores("foo" as __String), "foo"); + assert.equal(unescapeLeadingUnderscores("__type" as __String), "__type"); + assert.equal(unescapeLeadingUnderscores("___foo" as __String), "__foo"); + }); +}); + +describe("Checker - getPropertiesOfType", () => { + test("returns properties of an object type", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +export interface Person { + name: string; + age: number; + greet(): void; } export declare const p: Person; `, @@ -2332,7 +3012,7 @@ describe("Checker - getTypeArguments", () => { assert.ok(symbol); const type = project.checker.getTypeOfSymbol(symbol); assert.ok(type); - const typeArgs = project.checker.getTypeArguments(type); + const typeArgs = project.checker.getTypeArguments(type as TypeReference); assert.ok(typeArgs.length > 0, "Should have type arguments"); assert.ok(typeArgs[0].flags & TypeFlags.Number, `Expected number type argument, got flags ${typeArgs[0].flags}`); } @@ -2340,6 +3020,338 @@ describe("Checker - getTypeArguments", () => { api.close(); } }); + + test("a wrongly-typed call throws on the client without taking down the server", () => { + const src = `export const s: string = ""; export const arr: Array = [1];`; + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": src, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + + // `string` is not a type reference. When getTypeArguments is reached + // with one, the server panics, but the per-request panic recovery + // converts that into an error response rather than crashing the process. + const sSymbol = project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("s:")); + assert.ok(sSymbol); + const sType = project.checker.getTypeOfSymbol(sSymbol); + assert.ok(sType); + assert.throws(() => project.checker.getTypeArguments(sType as unknown as TypeReference)); + + // The server survived: a subsequent valid request still succeeds. + const arrSymbol = project.checker.getSymbolAtPosition("/src/main.ts", src.indexOf("arr:")); + assert.ok(arrSymbol); + const arrType = project.checker.getTypeOfSymbol(arrSymbol); + assert.ok(arrType); + const typeArgs = project.checker.getTypeArguments(arrType as TypeReference); + assert.ok(typeArgs.length > 0, "Server should still serve valid requests"); + } + finally { + api.close(); + } + }); +}); + +describe("Checker - getBaseConstraintOfType", () => { + test("returns the base constraint of a type parameter", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export function identity(x: T): T { return x; }`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `export function identity(x: T): T { return x; }`; + const pos = src.indexOf("identity<"); + const symbol = project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + const sigs = project.checker.getSignaturesOfType(type, SignatureKind.Call); + assert.ok(sigs.length > 0); + const typeParams = sigs[0].getTypeParameters(); + const constraint = project.checker.getBaseConstraintOfType(typeParams[0]); + assert.ok(constraint, "Should resolve a base constraint"); + assert.ok(constraint.flags & TypeFlags.String, `Expected string constraint, got flags ${constraint.flags}`); + } + finally { + api.close(); + } + }); + + test("returns undefined for a non-instantiable type", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export const x: number = 1;`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const pos = `export const x: number = 1;`.indexOf("x:"); + const symbol = project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + const constraint = project.checker.getBaseConstraintOfType(type); + assert.equal(constraint, undefined); + } + finally { + api.close(); + } + }); +}); + +describe("Checker - getPropertyOfType", () => { + test("returns a named property symbol of a type", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +export interface Person { + name: string; + age: number; +} +export declare const p: Person; +`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const src = `\nexport interface Person {\n name: string;\n age: number;\n}\nexport declare const p: Person;\n`; + const pos = src.indexOf("p: Person"); + const symbol = project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const type = project.checker.getTypeOfSymbol(symbol); + assert.ok(type); + const nameProp = project.checker.getPropertyOfType(type, "name"); + assert.ok(nameProp, "Should find 'name' property"); + assert.equal(nameProp.name, "name"); + const missing = project.checker.getPropertyOfType(type, "doesNotExist"); + assert.equal(missing, undefined); + } + finally { + api.close(); + } + }); +}); + +describe("Checker - getConstantValue", () => { + test("returns numeric value of an enum member", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export enum E { A = 1, B = 2 }`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = project.program.getSourceFile("/src/main.ts"); + assert.ok(sourceFile); + let memberB: Node | undefined; + sourceFile.forEachChild(function visit(node) { + if (node.kind === SyntaxKind.EnumMember) { + const text = sourceFile.text.slice(node.pos, node.end).trim(); + if (text.startsWith("B")) memberB = node; + } + node.forEachChild(visit); + }); + assert.ok(memberB, "Should find enum member B"); + const value = project.checker.getConstantValue(memberB); + assert.equal(value, 2); + } + finally { + api.close(); + } + }); + + test("returns string value of a string-initialized enum member", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export enum Color { Red = "red" }`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = project.program.getSourceFile("/src/main.ts"); + assert.ok(sourceFile); + let member: Node | undefined; + sourceFile.forEachChild(function visit(node) { + if (node.kind === SyntaxKind.EnumMember) member = node; + node.forEachChild(visit); + }); + assert.ok(member); + const value = project.checker.getConstantValue(member); + assert.equal(value, "red"); + } + finally { + api.close(); + } + }); +}); + +describe("Checker - getSignatureFromDeclaration", () => { + test("returns the signature of a function declaration", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": `export function add(a: number, b: number): number { return a + b; }`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = project.program.getSourceFile("/src/main.ts"); + assert.ok(sourceFile); + let funcDecl: Node | undefined; + sourceFile.forEachChild(function visit(node) { + if (isFunctionDeclaration(node)) funcDecl = node; + node.forEachChild(visit); + }); + assert.ok(funcDecl, "Should find the function declaration"); + const sig = project.checker.getSignatureFromDeclaration(funcDecl); + assert.ok(sig, "Should resolve a signature"); + assert.equal(sig.parameters.length, 2); + const returnType = project.checker.getReturnTypeOfSignature(sig); + assert.ok(returnType); + assert.ok(returnType.flags & TypeFlags.Number); + } + finally { + api.close(); + } + }); +}); + +describe("Checker - getExportSpecifierLocalTargetSymbol", () => { + test("resolves the local target of an export specifier", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +const value = 42; +export { value as renamed }; +`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = project.program.getSourceFile("/src/main.ts"); + assert.ok(sourceFile); + let exportSpecifier: Node | undefined; + sourceFile.forEachChild(function visit(node) { + if (node.kind === SyntaxKind.ExportSpecifier) exportSpecifier = node; + node.forEachChild(visit); + }); + assert.ok(exportSpecifier, "Should find the export specifier"); + const target = project.checker.getExportSpecifierLocalTargetSymbol(exportSpecifier); + assert.ok(target, "Should resolve a local target symbol"); + assert.equal(target.name, "value"); + } + finally { + api.close(); + } + }); +}); + +describe("Checker - getAliasedSymbol", () => { + test("resolves an import alias to its target symbol", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/foo.ts": `export const foo = 42;`, + "/src/main.ts": `import { foo } from "./foo";\nexport const usage = foo;`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const pos = `import { foo } from "./foo";`.indexOf("foo }"); + const aliasSymbol = project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(aliasSymbol); + assert.ok(aliasSymbol.flags & SymbolFlags.Alias, "Import binding should be an alias"); + const aliased = project.checker.getAliasedSymbol(aliasSymbol); + assert.ok(aliased, "Should resolve the aliased symbol"); + assert.equal(aliased.name, "foo"); + assert.ok(!(aliased.flags & SymbolFlags.Alias), "Target should not be an alias"); + } + finally { + api.close(); + } + }); +}); + +describe("Checker - getExportsOfModule", () => { + test("returns all exports including re-exports via 'export *'", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/inner.ts": `export const innerValue = 1;`, + "/src/index.ts": ` +export const direct = 1; +export * from "./inner"; +`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const sourceFile = project.program.getSourceFile("/src/index.ts"); + assert.ok(sourceFile); + const moduleSymbol = project.checker.getSymbolAtLocation(sourceFile); + assert.ok(moduleSymbol, "Source file should have a module symbol"); + const exports = project.checker.getExportsOfModule(moduleSymbol); + const names = exports.map(e => e.name); + assert.ok(names.includes("direct"), "should include directly-declared export"); + assert.ok(names.includes("innerValue"), "should include 'export *' re-export"); + } + finally { + api.close(); + } + }); +}); + +describe("Symbol - getDocumentationComment and getJsDocTags", () => { + const docFiles = { + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/main.ts": ` +/** + * Adds two numbers together. + * @param a the first number + * @returns the sum + */ +export function add(a: number, b: number): number { return a + b; } +`, + }; + + test("getDocumentationComment returns the leading comment text", () => { + const api = spawnAPI(docFiles); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const pos = docFiles["/src/main.ts"].indexOf("add(a"); + const symbol = project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const doc = symbol.getDocumentationComment(project.checker); + assert.ok(doc.includes("Adds two numbers together"), `Expected documentation, got: ${doc}`); + assert.ok(!doc.includes("@param"), "Documentation comment should not include tags"); + } + finally { + api.close(); + } + }); + + test("getJsDocTags returns structured tag name/text pairs", () => { + const api = spawnAPI(docFiles); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const pos = docFiles["/src/main.ts"].indexOf("add(a"); + const symbol = project.checker.getSymbolAtPosition("/src/main.ts", pos); + assert.ok(symbol); + const tags = symbol.getJsDocTags(project.checker); + const param = tags.find(t => t.name === "param"); + assert.ok(param, `Expected a @param tag, got: ${JSON.stringify(tags)}`); + assert.equal(param.text, "a the first number"); + const returns = tags.find(t => t.name === "returns"); + assert.ok(returns, `Expected a @returns tag, got: ${JSON.stringify(tags)}`); + assert.equal(returns.text, "the sum"); + } + finally { + api.close(); + } + }); }); describe("TypeParameter - isThisType", () => { @@ -3598,6 +4610,113 @@ describe("Program - diagnostics", () => { api.close(); } }); + + test("getBindDiagnostics", () => { + const source = `let x = 1;\nlet x = 2;`; + const api = spawnAPI({ + "/tsconfig.json": "{}", + "/src/index.ts": source, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const diags = project.program.getBindDiagnostics("/src/index.ts"); + assert.deepEqual(diags, [ + { + fileName: "/src/index.ts", + ...rangeOf(source, "x", 0), + code: 2451, + category: DiagnosticCategory.Error, + text: "Cannot redeclare block-scoped variable 'x'.", + }, + { + fileName: "/src/index.ts", + ...rangeOf(source, "x", 1), + code: 2451, + category: DiagnosticCategory.Error, + text: "Cannot redeclare block-scoped variable 'x'.", + }, + ]); + } + finally { + api.close(); + } + }); + + test("getProgramDiagnostics", () => { + const config = `{ "compilerOptions": { "moduleResolution": "bundler", "module": "nodenext" } }`; + const api = spawnAPI({ + "/tsconfig.json": config, + "/src/index.ts": `export const x = 1;`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const diags = project.program.getProgramDiagnostics(); + assert.deepEqual(diags, [ + { + fileName: "/tsconfig.json", + ...rangeOf(config, `"bundler"`), + code: 5095, + category: DiagnosticCategory.Error, + text: "Option 'bundler' can only be used when 'module' is set to 'preserve', 'commonjs', or 'es2015' or later.", + }, + { + fileName: "/tsconfig.json", + ...rangeOf(config, `"bundler"`), + code: 5109, + category: DiagnosticCategory.Error, + text: "Option 'moduleResolution' must be set to 'NodeNext' (or left unspecified) when option 'module' is set to 'NodeNext'.", + }, + ]); + } + finally { + api.close(); + } + }); + + test("getGlobalDiagnostics", () => { + const api = spawnAPI({ + "/tsconfig.json": "{}", + "/src/index.ts": `export const x = 1;`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const diags = project.program.getGlobalDiagnostics(); + assert.deepEqual(diags, []); + } + finally { + api.close(); + } + }); + + test("getGlobalDiagnostics returns file-less diagnostics from the checker", () => { + const api = spawnAPI({ + "/tsconfig.json": `{ "compilerOptions": { "noLib": true } }`, + "/src/index.ts": `export const x = [1, 2, 3];`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + const diags = project.program.getGlobalDiagnostics(); + // With noLib, the checker reports "Cannot find global type" diagnostics that + // are not associated with any source file. + assert.ok(diags.length > 0, "expected global diagnostics to be reported"); + for (const diag of diags) { + assert.equal(diag.fileName, undefined); + assert.equal(diag.code, 2318); + assert.equal(diag.category, DiagnosticCategory.Error); + } + assert.ok( + diags.some(d => d.text === "Cannot find global type 'Array'."), + "expected a global diagnostic for the 'Array' type", + ); + } + finally { + api.close(); + } + }); }); describe("Checker - getReferencedSymbolsForNode", () => { @@ -3650,6 +4769,138 @@ describe("Checker - getSignatureUsage", () => { }); }); +describe("getDefaultProjectForFile", () => { + test("finds inferred project for d.ts in node_modules after openFiles", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/index.ts": `export const x = 1;`, + "/node_modules/my-lib/package.json": JSON.stringify({ name: "my-lib", types: "./index.d.ts" }), + "/node_modules/my-lib/index.d.ts": `export declare const foo: string;`, + }); + try { + const snapshot = api.updateSnapshot({ openProject: "/tsconfig.json" }); + const project = snapshot.getProject("/tsconfig.json")!; + + // The d.ts is not imported, so it is not in the project's program + const dtsSf = project.program.getSourceFile("/node_modules/my-lib/index.d.ts"); + assert.equal(dtsSf, undefined, "d.ts not in import graph should not be found via project.program.getSourceFile"); + + // Before opening the file, getDefaultProjectForFile returns undefined (no error) + const noProject = snapshot.getDefaultProjectForFile("/node_modules/my-lib/index.d.ts"); + assert.equal(noProject, undefined, "getDefaultProjectForFile returns undefined for unloaded file"); + + // Load the file into the inferred project via updateSnapshot openFiles + const snapshot2 = api.updateSnapshot({ openFiles: ["/node_modules/my-lib/index.d.ts"] }); + const defaultProject = snapshot2.getDefaultProjectForFile("/node_modules/my-lib/index.d.ts"); + assert.ok(defaultProject, "getDefaultProjectForFile should find inferred project after openFiles"); + + const fooPos = `export declare const foo: string;`.indexOf("foo"); + const fooType = defaultProject.checker.getTypeAtPosition("/node_modules/my-lib/index.d.ts", fooPos); + assert.ok(fooType); + assert.ok(fooType.flags & TypeFlags.String); + } + finally { + api.close(); + } + }); + + test("keeps previously opened files open across subsequent openFiles calls", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/index.ts": `export const x = 1;`, + "/node_modules/my-lib/package.json": JSON.stringify({ name: "my-lib", types: "./index.d.ts" }), + "/node_modules/my-lib/index.d.ts": `export declare const foo: string;`, + "/node_modules/other-lib/package.json": JSON.stringify({ name: "other-lib", types: "./index.d.ts" }), + "/node_modules/other-lib/index.d.ts": `export declare const bar: number;`, + }); + try { + api.updateSnapshot({ openProject: "/tsconfig.json" }); + api.updateSnapshot({ openFiles: ["/node_modules/my-lib/index.d.ts"] }); + + // Opening a second file in a later snapshot must not close the first one. + const snapshot = api.updateSnapshot({ openFiles: ["/node_modules/other-lib/index.d.ts"] }); + + const firstProject = snapshot.getDefaultProjectForFile("/node_modules/my-lib/index.d.ts"); + assert.ok(firstProject, "previously opened file should remain in the inferred project"); + const secondProject = snapshot.getDefaultProjectForFile("/node_modules/other-lib/index.d.ts"); + assert.ok(secondProject, "newly opened file should be in the inferred project"); + } + finally { + api.close(); + } + }); + + test("opening a file resolves to a configured project via ancestor search", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/index.ts": `export const x = 1;`, + }); + try { + // Open the file without first opening the project. Like LSP's didOpen, this + // should search ancestor directories for a tsconfig that contains the file. + const snapshot = api.updateSnapshot({ openFiles: ["/src/index.ts"] }); + const defaultProject = snapshot.getDefaultProjectForFile("/src/index.ts"); + assert.ok(defaultProject, "should find a project for the opened file"); + assert.equal( + defaultProject.configFileName, + "/tsconfig.json", + "opened file should resolve to the containing configured project, not the inferred project", + ); + } + finally { + api.close(); + } + }); + + test("closeProjects releases a project opened via openProjects", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/index.ts": `export const x = 1;`, + }); + try { + const opened = api.updateSnapshot({ openProjects: ["/tsconfig.json"] }); + assert.ok(opened.getProject("/tsconfig.json"), "project should be open after openProjects"); + + const closed = api.updateSnapshot({ closeProjects: ["/tsconfig.json"] }); + assert.equal( + closed.getProject("/tsconfig.json"), + undefined, + "project should be unloaded after closeProjects", + ); + } + finally { + api.close(); + } + }); + + test("closeFiles releases a file opened via openFiles", () => { + const api = spawnAPI({ + "/tsconfig.json": JSON.stringify({ compilerOptions: { strict: true } }), + "/src/index.ts": `export const x = 1;`, + "/node_modules/my-lib/package.json": JSON.stringify({ name: "my-lib", types: "./index.d.ts" }), + "/node_modules/my-lib/index.d.ts": `export declare const foo: string;`, + }); + try { + api.updateSnapshot({ openProject: "/tsconfig.json" }); + const opened = api.updateSnapshot({ openFiles: ["/node_modules/my-lib/index.d.ts"] }); + assert.ok( + opened.getDefaultProjectForFile("/node_modules/my-lib/index.d.ts"), + "file should resolve to a project after openFiles", + ); + + const closed = api.updateSnapshot({ closeFiles: ["/node_modules/my-lib/index.d.ts"] }); + assert.equal( + closed.getDefaultProjectForFile("/node_modules/my-lib/index.d.ts"), + undefined, + "file should no longer resolve to a project after closeFiles", + ); + } + finally { + api.close(); + } + }); +}); + test("Benchmarks", () => { runBenchmarks({ singleIteration: true }); }); diff --git a/_packages/native-preview/test/sync/ast.test.ts b/_packages/native-preview/test/sync/ast.test.ts index 076345e3c44..5fa843aaf38 100644 --- a/_packages/native-preview/test/sync/ast.test.ts +++ b/_packages/native-preview/test/sync/ast.test.ts @@ -26,6 +26,7 @@ import { createIfStatement, createNodeArray, createNumericLiteral, + createSourceFile, createStringLiteral, createToken, NodeObject, @@ -530,6 +531,19 @@ describe("RemoteNode + cloneNode", () => { assert.notStrictEqual(clone, sf); assert.ok(clone instanceof NodeObject); assert.strictEqual(clone.statements, sf.statements); + assert.strictEqual(clone.text, sf.text); + assert.strictEqual(clone.fileName, sf.fileName); + assert.strictEqual(clone.path, sf.path); + assert.strictEqual(clone.scriptKind, sf.scriptKind); + assert.strictEqual(clone.languageVariant, sf.languageVariant); + assert.strictEqual(clone.isDeclarationFile, sf.isDeclarationFile); + assert.strictEqual(clone.referencedFiles, sf.referencedFiles); + assert.strictEqual(clone.typeReferenceDirectives, sf.typeReferenceDirectives); + assert.strictEqual(clone.libReferenceDirectives, sf.libReferenceDirectives); + assert.strictEqual(clone.imports, sf.imports); + assert.strictEqual(clone.moduleAugmentations, sf.moduleAugmentations); + assert.strictEqual(clone.ambientModuleNames, sf.ambientModuleNames); + assert.strictEqual(clone.externalModuleIndicator, sf.externalModuleIndicator); assert.strictEqual(clone.kind, sf.kind); assert.strictEqual(clone.pos, sf.pos); @@ -620,6 +634,39 @@ describe("RemoteNode + visitEachChild", () => { }); }); +describe("RemoteNodeList inherited array methods", () => { + test("filter/map/slice return plain arrays without throwing", () => { + const api = spawnAPI(); + try { + const sf = getRemoteSourceFile(api, "/tsconfig.json", "/src/index.ts"); + const statements = sf.statements; + assert.strictEqual(statements.length, 2); + + // These inherited Array methods previously threw + // "this.view.getUint32 is not a function" via ArraySpeciesCreate. + const filtered = statements.filter(() => true); + assert.ok(Array.isArray(filtered)); + assert.strictEqual(Object.getPrototypeOf(filtered), Array.prototype); + assert.strictEqual(filtered.length, 2); + assert.strictEqual(filtered[0], statements[0]); + + const mapped = statements.map(s => s.kind); + assert.ok(Array.isArray(mapped)); + assert.strictEqual(Object.getPrototypeOf(mapped), Array.prototype); + assert.deepStrictEqual(mapped, [statements[0].kind, statements[1].kind]); + + const sliced = statements.slice(1); + assert.ok(Array.isArray(sliced)); + assert.strictEqual(Object.getPrototypeOf(sliced), Array.prototype); + assert.strictEqual(sliced.length, 1); + assert.strictEqual(sliced[0], statements[1]); + } + finally { + api.close(); + } + }); +}); + describe("RemoteNode + getSynthesizedDeepClone", () => { test("deep clones a remote import declaration", () => { const api = spawnAPI(); @@ -663,6 +710,33 @@ describe("RemoteNode + getSynthesizedDeepClone", () => { api.close(); } }); + + test("deep clone of remote SourceFile preserves top-level metadata references", () => { + const api = spawnAPI(); + try { + const sf = getRemoteSourceFile(api, "/tsconfig.json", "/src/foo.ts"); + const referencedFiles = sf.referencedFiles; + const typeReferenceDirectives = sf.typeReferenceDirectives; + const libReferenceDirectives = sf.libReferenceDirectives; + const imports = sf.imports; + const moduleAugmentations = sf.moduleAugmentations; + const ambientModuleNames = sf.ambientModuleNames; + + const clone = getSynthesizedDeepClone(sf); + + assert.notStrictEqual(clone, sf); + assert.strictEqual(clone.referencedFiles, referencedFiles); + assert.strictEqual(clone.typeReferenceDirectives, typeReferenceDirectives); + assert.strictEqual(clone.libReferenceDirectives, libReferenceDirectives); + assert.strictEqual(clone.imports, imports); + assert.strictEqual(clone.moduleAugmentations, moduleAugmentations); + assert.strictEqual(clone.ambientModuleNames, ambientModuleNames); + assert.strictEqual(clone.externalModuleIndicator, sf.externalModuleIndicator); + } + finally { + api.close(); + } + }); }); // --------------------------------------------------------------------------- diff --git a/_packages/native-preview/test/tsconfig.json b/_packages/native-preview/test/tsconfig.json index b1a688b3b88..d1a87c7fd42 100644 --- a/_packages/native-preview/test/tsconfig.json +++ b/_packages/native-preview/test/tsconfig.json @@ -1,5 +1,9 @@ { "extends": "../tsconfig.dev.json", + "compilerOptions": { + // tinybench has errors under exactOptionalPropertyTypes + "skipLibCheck": true + }, "references": [ { "path": ".." } ] diff --git a/_packages/native-preview/test/wtf8.test.ts b/_packages/native-preview/test/wtf8.test.ts new file mode 100644 index 00000000000..8fe8fcd3652 --- /dev/null +++ b/_packages/native-preview/test/wtf8.test.ts @@ -0,0 +1,44 @@ +import assert from "node:assert"; +import { + describe, + test, +} from "node:test"; +import { Wtf8Decoder } from "../src/api/node/wtf8.ts"; + +describe("Wtf8Decoder", () => { + test("decodes standard UTF-8", () => { + const decoder = new Wtf8Decoder(); + assert.strictEqual(decoder.decode(new TextEncoder().encode("hello 🦀")), "hello 🦀"); + }); + + test("preserves WTF-8 encoded lone surrogates", () => { + const decoder = new Wtf8Decoder(); + const text = decoder.decode(Uint8Array.of( + 0xF0, + 0x9F, + 0xA6, + 0x80, + 0xED, + 0x9F, + 0xBF, + 0xED, + 0xA0, + 0x80, + 0xED, + 0xA0, + 0x81, + 0xED, + 0xB0, + 0x80, + 0xF0, + 0x9F, + 0xA6, + 0x80, + )); + + assert.deepStrictEqual( + Array.from({ length: text.length }, (_, i) => text.charCodeAt(i)), + [0xD83E, 0xDD80, 0xD7FF, 0xD800, 0xD801, 0xDC00, 0xD83E, 0xDD80], + ); + }); +}); diff --git a/_packages/native-preview/tsconfig.base.json b/_packages/native-preview/tsconfig.base.json index d32e19eea89..56b14d949e2 100644 --- a/_packages/native-preview/tsconfig.base.json +++ b/_packages/native-preview/tsconfig.base.json @@ -3,6 +3,7 @@ "target": "es2022", "lib": ["es2022"], "strict": true, + "exactOptionalPropertyTypes": true, "composite": true, "forceConsistentCasingInFileNames": true, "rewriteRelativeImportExtensions": true, diff --git a/_scripts/generate-encoder.ts b/_scripts/generate-encoder.ts index caddf3356ae..fd27356feac 100644 --- a/_scripts/generate-encoder.ts +++ b/_scripts/generate-encoder.ts @@ -1511,6 +1511,12 @@ function emitNodeGeneratedImports(w: CodeWriter) { function emitRemoteNodeList(w: CodeWriter) { w.write(`export class RemoteNodeList extends Array implements NodeArray {`); + w.write(` // Inherited Array methods like filter/map/slice use ArraySpeciesCreate, which would`); + w.write(` // otherwise call \`new RemoteNodeList(length)\` and fail. Produce a plain Array instead.`); + w.write(` static get [Symbol.species](): ArrayConstructor {`); + w.write(` return Array;`); + w.write(` }`); + w.write(``); w.write(` parent: RemoteNode;`); w.write(` hasTrailingComma?: boolean;`); w.write(` transformFlags: number = 0;`); @@ -1654,9 +1660,11 @@ function emitRemoteNodeClassOpen(w: CodeWriter) { w.write(` return result;`); w.write(` }`); w.write(` }`); - w.write(` const result = child.forEachNode(visitNode);`); - w.write(` if (result) {`); - w.write(` return result;`); + w.write(` else {`); + w.write(` const result = child.forEachNode(visitNode);`); + w.write(` if (result) {`); + w.write(` return result;`); + w.write(` }`); w.write(` }`); w.write(` }`); w.write(` else if (child.kind !== SyntaxKind.JSDoc) {`); @@ -1757,30 +1765,7 @@ function emitRemoteNodeClassOpen(w: CodeWriter) { w.write(` }`); w.write(``); w.write(` private getNamedChild(propertyName: string): RemoteNode | RemoteNodeList | undefined {`); - w.write(` // JSDocPropertyTag and JSDocParameterTag have runtime-dependent child order based on isNameFirst.`); - w.write(` // Handle them before the general childProperties lookup.`); w.write(` const kind = this.kind;`); - w.write(` if (kind === SyntaxKind.JSDocPropertyTag) {`); - w.write(` let order: number;`); - w.write(` switch (propertyName) {`); - w.write(` case "name": order = this.isNameFirst ? 0 : 1; break;`); - w.write(` case "typeExpression": order = this.isNameFirst ? 1 : 0; break;`); - w.write(` default: return undefined;`); - w.write(` }`); - w.write(` return this.getChildAtOrder(order);`); - w.write(` }`); - w.write(` else if (kind === SyntaxKind.JSDocParameterTag) {`); - w.write(` let order: number;`); - w.write(` switch (propertyName) {`); - w.write(` case "tagName": order = 0; break;`); - w.write(` case "name": order = this.isNameFirst ? 1 : 2; break;`); - w.write(` case "typeExpression": order = this.isNameFirst ? 2 : 1; break;`); - w.write(` case "comment": order = 3; break;`); - w.write(` default: return undefined;`); - w.write(` }`); - w.write(` return this.getChildAtOrder(order);`); - w.write(` }`); - w.write(``); w.write(` const propertyNames = childProperties[kind];`); w.write(` if (!propertyNames) {`); w.write(` return undefined;`); diff --git a/_scripts/generate-go-ast.ts b/_scripts/generate-go-ast.ts index 17075abf067..9309aae0fce 100644 --- a/_scripts/generate-go-ast.ts +++ b/_scripts/generate-go-ast.ts @@ -478,6 +478,54 @@ function generateForEachChild(w: CodeWriter, node: NodeType) { w.write(""); } +// ── Generate ForEachChild dispatch ───────────────────────────────────────── + +// Determines whether a node has a meaningful ForEachChild implementation (i.e. +// one that is not the no-op inherited from NodeDefault). This is true for any +// generated node with child members, or for hand-written nodes (e.g. SourceFile) +// which define ForEachChild manually in ast.go. +function hasForEachChild(node: NodeType): boolean { + if (node.handWritten) return true; + return schemaMembers(node).some(m => m.isChild()); +} + +// Generates a (*Node).ForEachChild method that dispatches on node.Kind to the +// concrete node type's ForEachChild method. +// +// This deliberately avoids calling node.data.ForEachChild(v) through the +// nodeData interface. An interface (or other indirect) call is opaque to escape +// analysis, which must then assume the visitor `v` escapes; that forces caller +// closures — and any locals they capture — onto the heap. Dispatching through a +// Kind switch to a statically-resolved concrete method lets escape analysis +// prove the visitor does not escape, keeping caller closures on the stack. The +// integer switch over Kind also compiles to a jump table, making dispatch +// cheaper than the interface call it replaces. +// +// Kinds whose node has no children fall through to `default` and return false, +// matching NodeDefault.ForEachChild. +function generateForEachChildDispatch(w: CodeWriter) { + w.write("func (n *Node) ForEachChild(v Visitor) bool {"); + w.push(); + w.write("switch n.Kind {"); + for (const node of api.nodes()) { + if (!hasForEachChild(node)) continue; + const kinds = node.allKinds().map(k => k.formatGoConstant()); + if (kinds.length === 0) continue; + w.write(`case ${kinds.join(", ")}:`); + w.push(); + w.write(`return n.data.(*${node.name}).ForEachChild(v)`); + w.pop(); + } + w.write("default:"); + w.push(); + w.write("return false"); + w.pop(); + w.write("}"); + w.pop(); + w.write("}"); + w.write(""); +} + // ── Generate VisitEachChild() ────────────────────────────────────────────── function generateVisitEachChild(w: CodeWriter, node: NodeType) { @@ -819,6 +867,13 @@ function generate(): string { } } + // ForEachChild dispatch + w.write("// ──────────────────────────────────────────────────────────────────────"); + w.write("// ForEachChild dispatch"); + w.write("// ──────────────────────────────────────────────────────────────────────"); + w.write(""); + generateForEachChildDispatch(w); + // As*() casts w.write("// ──────────────────────────────────────────────────────────────────────"); w.write("// As*() cast methods"); diff --git a/_scripts/generate-ts-ast.ts b/_scripts/generate-ts-ast.ts index 73e621b07fe..4b08510b2b3 100644 --- a/_scripts/generate-ts-ast.ts +++ b/_scripts/generate-ts-ast.ts @@ -55,8 +55,22 @@ function tsInterfaceMembers(node: NodeType): MemberInfo[] { // TS-specific naming and typing // ──────────────────────────────────────────────────────────────────────────── -function tsParamTypeFrom(type: Type): string { - return type.kind === "list" ? type.raw().formatTypeScript() : type.formatTypeScript(); +// The JSDoc comment `text` member is stored as a raw []string in Go, but the +// encoder joins it into a single string and both the RemoteNode API and the +// local factory expose it as a scalar string. Collapse just this member to its +// element type in the generated TS. This is intentionally keyed on the property +// name rather than on "raw list of a primitive" so the exception stays narrow +// and explicit; `text` is the only such member. +function collapsedTextType(name: string, type: Type): string | undefined { + if (name === "text" && type.kind === "list" && type.listKind === "raw") { + return type.elementType.formatTypeScript(); + } + return undefined; +} + +function tsParamTypeFrom(name: string, type: Type): string { + return collapsedTextType(name, type) + ?? (type.kind === "list" ? type.raw().formatTypeScript() : type.formatTypeScript()); } function tsParamName(propName: string): string { @@ -146,7 +160,7 @@ function generateBaseFields(base: NodeType): string { for (const field of base.fields) { if (field.noTS) continue; const name = api.uncapitalize(field.name); - const type = field.type.formatTypeScript(); + const type = collapsedTextType(field.name, field.type) ?? field.type.formatTypeScript(); const opt = field.optional ? "?" : ""; result += `\n readonly ${name}${opt}: ${type};`; } @@ -485,7 +499,7 @@ function generateFactory(): string { const kindTypeParam = kindTypeParameter(node); if (kindTypeParam) addType(kindTypeParam.constraint); for (const m of tsMembers(node)) { - addType(tsParamTypeFrom(m.type)); + addType(tsParamTypeFrom(m.name, m.type)); addType(m.type.formatTypeScript()); } } @@ -499,6 +513,9 @@ function generateFactory(): string { for (const t of ["Node", "NodeArray", "KeywordTypeSyntaxKind", "Token", "SourceFile", "KeywordTypeNode", "EndOfFile", "ImportPhaseModifierSyntaxKind", "Path", "Statement"]) { importTypes.add(t); } + const handWrittenCloneHelpers = api.nodes() + .filter(node => node.handWritten && !isVariantNode(node)) + .map(node => ({ node, helperName: `clone${node.name}Data` })); // Remove enum types that are imported separately importTypes.delete("NodeFlags"); importTypes.delete("SyntaxKind"); @@ -518,6 +535,13 @@ function generateFactory(): string { } out.push(`} from "./ast.ts";`); out.push(`import { getTokenPosOfNode } from "./astnav.ts";`); + if (handWrittenCloneHelpers.length > 0) { + out.push(`import {`); + for (const helperName of [...new Set(handWrittenCloneHelpers.map(h => h.helperName))].sort((a, b) => a.localeCompare(b))) { + out.push(` ${helperName},`); + } + out.push(`} from "./utils.ts";`); + } // Import hand-written forEachChild functions const handWrittenForEachChildImports: string[] = []; @@ -660,9 +684,12 @@ function generateFactory(): string { out.push(` case SyntaxKind.${v.syntaxKind}:`); out.push(` return { ${propStr} };`); } - // SourceFile is handWritten so we add its case manually - out.push(` case SyntaxKind.SourceFile:`); - out.push(` return { statements: n.statements, endOfFileToken: n.endOfFileToken, text: n.text, fileName: n.fileName, path: n.path };`); + for (const { node, helperName } of handWrittenCloneHelpers) { + for (const sk of node.allKinds()) { + out.push(` case ${sk.formatTypeScript()}:`); + } + out.push(` return ${helperName}(n);`); + } out.push(` default:`); out.push(` return undefined;`); out.push(` }`); @@ -779,7 +806,7 @@ function generateFactory(): string { const m = members[mi]; const propName = api.uncapitalize(m.name); const paramName = tsParamName(propName); - const paramType = tsParamTypeFrom(m.type); + const paramType = tsParamTypeFrom(m.name, m.type); const memberType = m.type; const isBool = !m.isChild() && memberType.kind === "primitive" && memberType.name === "bool"; @@ -887,7 +914,7 @@ function generateFactory(): string { for (const m of v.members) { const propName = api.uncapitalize(m.name); const paramName = tsParamName(propName); - const paramType = tsParamTypeFrom(m.type); + const paramType = tsParamTypeFrom(m.name, m.type); if (m.optional) { paramParts.push(`${paramName}: ${paramType} | undefined`); } @@ -943,7 +970,7 @@ function generateFactory(): string { const m = updateChildMembers[mi]; const propName = api.uncapitalize(m.name); const paramName = tsParamName(propName); - const paramType = tsParamTypeFrom(m.type); + const paramType = tsParamTypeFrom(m.name, m.type); if (m.optional) { if (mi < updateLastRequiredIdx) { paramParts.push(`${paramName}: ${paramType} | undefined`); @@ -989,7 +1016,7 @@ function generateFactory(): string { for (const m of childMembers) { const propName = api.uncapitalize(m.name); const paramName = tsParamName(propName); - const paramType = tsParamTypeFrom(m.type); + const paramType = tsParamTypeFrom(m.name, m.type); if (m.optional) { paramParts.push(`${paramName}: ${paramType} | undefined`); } @@ -1029,10 +1056,19 @@ function generateFactory(): string { out.push(`}`); out.push(``); + out.push(`function cloneSourceFileWithChanges(source: SourceFile, statements: readonly Statement[], endOfFileToken: EndOfFile): SourceFile {`); + out.push(` return new NodeObject(SyntaxKind.SourceFile, {`); + out.push(` ...cloneSourceFileData(source),`); + out.push(` statements: createNodeArray(statements),`); + out.push(` endOfFileToken,`); + out.push(` }) as unknown as SourceFile;`); + out.push(`}`); + out.push(``); + // ── updateSourceFile (hand-written in schema) ── out.push(`export function updateSourceFile(node: SourceFile, statements: readonly Statement[], endOfFileToken: EndOfFile): SourceFile {`); out.push(` return node.statements !== statements || node.endOfFileToken !== endOfFileToken`); - out.push(` ? createSourceFile(statements, endOfFileToken, node.text, node.fileName, node.path)`); + out.push(` ? cloneSourceFileWithChanges(node, statements, endOfFileToken)`); out.push(` : node;`); out.push(`}`); out.push(``); @@ -1058,7 +1094,6 @@ function generateIsGenerated(): string { const guards: { funcName: string; typeName: string; kindChecks: string[]; kindAliasConstraint?: string; }[] = []; for (const node of api.nodes()) { - if (node.handWritten) continue; if (isVariantNode(node)) continue; const typeName = node.name; diff --git a/_submodules/TypeScript b/_submodules/TypeScript index c3bd12d888b..4d4f005c854 160000 --- a/_submodules/TypeScript +++ b/_submodules/TypeScript @@ -1 +1 @@ -Subproject commit c3bd12d888b86f676718b16e64d7d2abcb423514 +Subproject commit 4d4f005c8541e0255a9d8791205fdce326e462bc diff --git a/_tools/go.mod b/_tools/go.mod index a6b93d24f78..d1073337f10 100644 --- a/_tools/go.mod +++ b/_tools/go.mod @@ -5,11 +5,11 @@ go 1.26 require ( github.com/golangci/plugin-module-register v0.1.2 golang.org/x/mod v0.37.0 - golang.org/x/tools v0.45.0 + golang.org/x/tools v0.47.0 gotest.tools/v3 v3.5.2 ) require ( github.com/google/go-cmp v0.6.0 // indirect - golang.org/x/sync v0.20.0 // indirect + golang.org/x/sync v0.21.0 // indirect ) diff --git a/_tools/go.sum b/_tools/go.sum index 7b990b37334..95e564cc0a1 100644 --- a/_tools/go.sum +++ b/_tools/go.sum @@ -4,9 +4,9 @@ github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= -golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= -golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= -golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8= -golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0= +golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= +golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= +golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= diff --git a/go.mod b/go.mod index 27cc369e8fc..5f8ca54d8dc 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.26 require ( github.com/Microsoft/go-winio v0.6.2 - github.com/go-json-experiment/json v0.0.0-20260601182631-00ed12fed2a6 + github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 github.com/google/go-cmp v0.7.0 github.com/mackerelio/go-osstat v0.2.7 github.com/peter-evans/patience v0.3.0 @@ -19,8 +19,8 @@ require ( require ( github.com/klauspost/cpuid/v2 v2.2.10 // indirect github.com/matryer/moq v0.7.1 // indirect - golang.org/x/mod v0.36.0 // indirect - golang.org/x/tools v0.45.0 // indirect + golang.org/x/mod v0.37.0 // indirect + golang.org/x/tools v0.47.0 // indirect ) tool ( diff --git a/go.sum b/go.sum index 99f6e5a2ced..7c8a1974076 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= -github.com/go-json-experiment/json v0.0.0-20260601182631-00ed12fed2a6 h1:nxP4pPoyqOAgX8lYDFCfl3DyKeXErCvSvhcyzwGV9CE= -github.com/go-json-experiment/json v0.0.0-20260601182631-00ed12fed2a6/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg= +github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68 h1:KZaTBSyshWX3MP5jukJcNSuXDQTO+rNpt0J564dX/eg= +github.com/go-json-experiment/json v0.0.0-20260623181947-01eb4420fa68/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/klauspost/cpuid/v2 v2.2.10 h1:tBs3QSyvjDyFTq3uoc/9xFpCuOsJQFNPiAhYdw2skhE= @@ -18,8 +18,8 @@ github.com/zeebo/assert v1.3.0 h1:g7C04CbJuIDKNPFHmsk4hwZDO5O+kntRxzaUoNXj+IQ= github.com/zeebo/assert v1.3.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0= github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= -golang.org/x/mod v0.36.0 h1:JJjpVx6myfUsUdAzZuOSTTmRE0PfZeNWzzvKrP7amb4= -golang.org/x/mod v0.36.0/go.mod h1:moc6ELqsWcOw5Ef3xVprK5ul/MvtVvkIXLziUOICjUQ= +golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= +golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM= golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw= @@ -28,7 +28,7 @@ golang.org/x/term v0.44.0 h1:0rLvDRCtNj0gZkyIXhCyOb2OAzEhLVqc4B+hrsBhrmc= golang.org/x/term v0.44.0/go.mod h1:7ze4MdzUzLXpSAoFP1H0bOI9aXDqveSvatT5vKcFh2Y= golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE= golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4= -golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8= -golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0= +golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q= +golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA= gotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q= gotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA= diff --git a/internal/api/encoder/encoder.go b/internal/api/encoder/encoder.go index b2818a146cc..dd93a2ea3ba 100644 --- a/internal/api/encoder/encoder.go +++ b/internal/api/encoder/encoder.go @@ -111,10 +111,11 @@ const ( // String data (variable) // ---------------------- // -// The string data section contains UTF-8 encoded string data. In typical cases, the entirety of the string data is the -// source file text, and individual nodes with string properties reference their positional slice of the file text. In -// cases where a node's string property is not equal to the slice of file text at its position, the unique string is -// appended to the string data section after the file text. +// The string data section contains UTF-8 encoded string data, with WTF-8 used for JS strings containing lone UTF-16 +// surrogates. In typical cases, the entirety of the string data is the source file text, and individual nodes with +// string properties reference their positional slice of the file text. In cases where a node's string property is not +// equal to the slice of file text at its position, the unique string is appended to the string data section after the +// file text. // // Extended node data (variable) // ----------------------------- diff --git a/internal/api/proto.go b/internal/api/proto.go index 8128018f3e0..f0b82d60c99 100644 --- a/internal/api/proto.go +++ b/internal/api/proto.go @@ -68,6 +68,8 @@ const ( MethodGetTypesOfSymbols Method = "getTypesOfSymbols" MethodGetDeclaredTypeOfSymbol Method = "getDeclaredTypeOfSymbol" MethodGetSourceFile Method = "getSourceFile" + MethodGetSourceFileNames Method = "getSourceFileNames" + MethodGetSourceFileMetadata Method = "getSourceFileMetadata" MethodResolveName Method = "resolveName" MethodGetSignaturesOfType Method = "getSignaturesOfType" MethodGetResolvedSignature Method = "getResolvedSignature" @@ -126,9 +128,25 @@ const ( MethodGetTypePredicateOfSignature Method = "getTypePredicateOfSignature" MethodGetBaseTypes Method = "getBaseTypes" MethodGetPropertiesOfType Method = "getPropertiesOfType" + MethodGetApparentType Method = "getApparentType" + MethodGetPropertyOfType Method = "getPropertyOfType" MethodGetIndexInfosOfType Method = "getIndexInfosOfType" MethodGetConstraintOfTypeParameter Method = "getConstraintOfTypeParameter" + MethodGetBaseConstraintOfType Method = "getBaseConstraintOfType" MethodGetTypeArguments Method = "getTypeArguments" + MethodGetTrueTypeOfConditionalType Method = "getTrueTypeOfConditionalType" + MethodGetFalseTypeOfConditionalType Method = "getFalseTypeOfConditionalType" + MethodGetConstantValue Method = "getConstantValue" + MethodGetSignatureFromDeclaration Method = "getSignatureFromDeclaration" + MethodGetExportSpecifierLocalTarget Method = "getExportSpecifierLocalTargetSymbol" + MethodGetAliasedSymbol Method = "getAliasedSymbol" + MethodGetImmediateAliasedSymbol Method = "getImmediateAliasedSymbol" + MethodGetExportsOfModule Method = "getExportsOfModule" + MethodGetMemberInModuleExports Method = "getMemberInModuleExports" + MethodGetJSDocTags Method = "getJsDocTags" + MethodGetDocumentationComment Method = "getDocumentationComment" + MethodIsArrayType Method = "isArrayType" + MethodIsTupleType Method = "isTupleType" // Reference methods MethodGetReferencesToSymbolInFile Method = "getReferencesToSymbolInFile" @@ -140,9 +158,12 @@ const ( // Diagnostic methods MethodGetSyntacticDiagnostics Method = "getSyntacticDiagnostics" + MethodGetBindDiagnostics Method = "getBindDiagnostics" MethodGetSemanticDiagnostics Method = "getSemanticDiagnostics" MethodGetSuggestionDiagnostics Method = "getSuggestionDiagnostics" MethodGetDeclarationDiagnostics Method = "getDeclarationDiagnostics" + MethodGetProgramDiagnostics Method = "getProgramDiagnostics" + MethodGetGlobalDiagnostics Method = "getGlobalDiagnostics" MethodGetConfigFileParsingDiagnostics Method = "getConfigFileParsingDiagnostics" // Emitter methods @@ -161,6 +182,9 @@ const ( MethodGetBigIntType Method = "getBigIntType" MethodGetESSymbolType Method = "getESSymbolType" + // Well-known per-checker symbols + MethodGetWellKnownSymbols Method = "getWellKnownSymbols" + // Profiling methods MethodStartCPUProfile Method = "startCPUProfile" MethodStopCPUProfile Method = "stopCPUProfile" @@ -227,11 +251,14 @@ func (d DocumentIdentifier) ToFileName() string { return d.FileName } -func (d DocumentIdentifier) ToURI() lsproto.DocumentUri { +// ToURI returns the document URI for this identifier. An explicitly provided URI +// is returned as-is; a file name is first normalized to an absolute path against +// cwd before being converted to a URI. +func (d DocumentIdentifier) ToURI(cwd string) lsproto.DocumentUri { if d.URI != "" { return d.URI } - return lsconv.FileNameToDocumentURI(d.FileName) + return lsconv.FileNameToDocumentURI(tspath.GetNormalizedAbsolutePath(d.FileName, cwd)) } func (d DocumentIdentifier) ToAbsoluteFileName(cwd string) string { @@ -268,10 +295,24 @@ type APIFileChanges struct { // UpdateSnapshotParams are the parameters for creating a new snapshot. // All fields are optional. With no fields set, the server adopts the latest LSP state. type UpdateSnapshotParams struct { - // OpenProject is the path to a tsconfig.json file to open/load in the new snapshot. - OpenProject string `json:"openProject,omitempty"` + // OpenProjects lists tsconfig.json files to open/load in the new snapshot. + // Opens are ref-counted and persist across snapshots until closed. + OpenProjects []DocumentIdentifier `json:"openProjects,omitempty"` + // CloseProjects lists tsconfig.json files to release in the new snapshot. + // A project is only unloaded once every API client that opened it closes it. + CloseProjects []DocumentIdentifier `json:"closeProjects,omitempty"` // FileChanges describes file system changes since the last snapshot. FileChanges *APIFileChanges `json:"fileChanges,omitempty"` + // OpenFiles lists files to keep open for the API client, mirroring LSP's + // textDocument/didOpen. For each file, ancestor directories are searched for a + // tsconfig that contains it; if found, that configured project is loaded and + // becomes the file's default project. Otherwise the file is loaded into the + // inferred project (e.g. a node_modules d.ts not in any project's import graph). + // Opens persist across snapshots until the file is closed. + OpenFiles []DocumentIdentifier `json:"openFiles,omitempty"` + // CloseFiles lists files to release in the new snapshot. A file is only fully + // closed once every API client that opened it closes it. + CloseFiles []DocumentIdentifier `json:"closeFiles,omitempty"` } // ProjectFileChanges describes what source files changed within a single project. @@ -312,6 +353,8 @@ var unmarshalers = map[Method]func([]byte) (any, error){ MethodParseConfigFile: unmarshallerFor[ParseConfigFileParams], MethodGetDefaultProjectForFile: unmarshallerFor[GetDefaultProjectForFileParams], MethodGetSourceFile: unmarshallerFor[GetSourceFileParams], + MethodGetSourceFileNames: unmarshallerFor[GetSourceFileNamesParams], + MethodGetSourceFileMetadata: unmarshallerFor[GetSourceFileParams], MethodGetSymbolAtPosition: unmarshallerFor[GetSymbolAtPositionParams], MethodGetSymbolsAtPositions: unmarshallerFor[GetSymbolsAtPositionsParams], MethodGetSymbolAtLocation: unmarshallerFor[GetSymbolAtLocationParams], @@ -332,22 +375,24 @@ var unmarshalers = map[Method]func([]byte) (any, error){ MethodGetExportsOfSymbol: unmarshallerFor[GetSymbolPropertyParams], MethodGetExportSymbolOfSymbol: unmarshallerFor[GetSymbolPropertyParams], - MethodGetSymbolOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetTargetOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetFreshTypeOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetRegularTypeOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetTypesOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetTypeParametersOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetOuterTypeParametersOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetLocalTypeParametersOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetAliasTypeArgumentsOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetAliasSymbolOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetObjectTypeOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetIndexTypeOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetCheckTypeOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetExtendsTypeOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetBaseTypeOfType: unmarshallerFor[GetTypePropertyParams], - MethodGetConstraintOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetSymbolOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetTargetOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetFreshTypeOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetRegularTypeOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetTypesOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetTypeParametersOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetOuterTypeParametersOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetLocalTypeParametersOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetAliasTypeArgumentsOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetAliasSymbolOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetObjectTypeOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetIndexTypeOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetCheckTypeOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetExtendsTypeOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetBaseTypeOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetConstraintOfType: unmarshallerFor[GetTypePropertyParams], + MethodGetTrueTypeOfConditionalType: unmarshallerFor[GetTypePropertyParams], + MethodGetFalseTypeOfConditionalType: unmarshallerFor[GetTypePropertyParams], MethodGetTypeParametersOfSignature: unmarshallerFor[GetSignaturePropertyParams], MethodGetParametersOfSignature: unmarshallerFor[GetSignaturePropertyParams], @@ -373,9 +418,23 @@ var unmarshalers = map[Method]func([]byte) (any, error){ MethodGetTypePredicateOfSignature: unmarshallerFor[CheckerSignatureParams], MethodGetBaseTypes: unmarshallerFor[CheckerTypeParams], MethodGetPropertiesOfType: unmarshallerFor[CheckerTypeParams], + MethodGetApparentType: unmarshallerFor[CheckerTypeParams], + MethodGetPropertyOfType: unmarshallerFor[GetPropertyOfTypeParams], MethodGetIndexInfosOfType: unmarshallerFor[CheckerTypeParams], MethodGetConstraintOfTypeParameter: unmarshallerFor[CheckerTypeParams], + MethodGetBaseConstraintOfType: unmarshallerFor[CheckerTypeParams], MethodGetTypeArguments: unmarshallerFor[CheckerTypeParams], + MethodGetConstantValue: unmarshallerFor[CheckerNodeParams], + MethodGetSignatureFromDeclaration: unmarshallerFor[CheckerNodeParams], + MethodGetExportSpecifierLocalTarget: unmarshallerFor[CheckerNodeParams], + MethodGetAliasedSymbol: unmarshallerFor[CheckerSymbolParams], + MethodGetImmediateAliasedSymbol: unmarshallerFor[CheckerSymbolParams], + MethodGetExportsOfModule: unmarshallerFor[CheckerSymbolParams], + MethodGetMemberInModuleExports: unmarshallerFor[GetMemberInModuleExportsParams], + MethodGetJSDocTags: unmarshallerFor[CheckerSymbolParams], + MethodGetDocumentationComment: unmarshallerFor[CheckerSymbolParams], + MethodIsArrayType: unmarshallerFor[CheckerTypeParams], + MethodIsTupleType: unmarshallerFor[CheckerTypeParams], MethodGetReferencesToSymbolInFile: unmarshallerFor[GetReferencesToSymbolInFileParams], MethodGetReferencedSymbolsForNode: unmarshallerFor[GetReferencedSymbolsForNodeParams], MethodGetSignatureUsages: unmarshallerFor[GetSignatureUsagesParams], @@ -392,10 +451,14 @@ var unmarshalers = map[Method]func([]byte) (any, error){ MethodGetUnknownType: unmarshallerFor[GetIntrinsicTypeParams], MethodGetBigIntType: unmarshallerFor[GetIntrinsicTypeParams], MethodGetESSymbolType: unmarshallerFor[GetIntrinsicTypeParams], + MethodGetWellKnownSymbols: unmarshallerFor[GetIntrinsicTypeParams], MethodGetSyntacticDiagnostics: unmarshallerFor[GetDiagnosticsParams], + MethodGetBindDiagnostics: unmarshallerFor[GetDiagnosticsParams], MethodGetSemanticDiagnostics: unmarshallerFor[GetDiagnosticsParams], MethodGetSuggestionDiagnostics: unmarshallerFor[GetDiagnosticsParams], MethodGetDeclarationDiagnostics: unmarshallerFor[GetDiagnosticsParams], + MethodGetProgramDiagnostics: unmarshallerFor[GetProjectDiagnosticsParams], + MethodGetGlobalDiagnostics: unmarshallerFor[GetProjectDiagnosticsParams], MethodGetConfigFileParsingDiagnostics: unmarshallerFor[GetProjectDiagnosticsParams], MethodStartCPUProfile: unmarshallerFor[ProfileParams], MethodStopCPUProfile: noParams, @@ -473,6 +536,7 @@ type GetSymbolsAtLocationsParams struct { type SymbolResponse struct { Id SymbolID `json:"id"` + Project ProjectID `json:"project"` Name string `json:"name"` Flags uint32 `json:"flags"` CheckFlags uint32 `json:"checkFlags"` @@ -689,6 +753,20 @@ type GetSourceFileParams struct { File DocumentIdentifier `json:"file"` } +type GetSourceFileNamesParams struct { + Snapshot SnapshotID `json:"snapshot"` + Project ProjectID `json:"project"` +} + +// SourceFileMetadata carries program-stored metadata about a single source file. +type SourceFileMetadata struct { + IsDefaultLibrary bool `json:"isDefaultLibrary"` + IsFromExternalLibrary bool `json:"isFromExternalLibrary"` + PackageJsonType string `json:"packageJsonType"` + PackageJsonDirectory string `json:"packageJsonDirectory"` + ImpliedNodeFormat core.ResolutionMode `json:"impliedNodeFormat"` +} + type ResolveNameParams struct { Snapshot SnapshotID `json:"snapshot"` Project ProjectID `json:"project"` @@ -710,6 +788,7 @@ type GetTypePropertyParams struct { // GetSymbolPropertyParams is used for all symbol sub-property endpoints. type GetSymbolPropertyParams struct { Snapshot SnapshotID `json:"snapshot"` + Project ProjectID `json:"project"` Symbol SymbolID `json:"objectId"` } @@ -811,6 +890,15 @@ type GetIntrinsicTypeParams struct { Project ProjectID `json:"project"` } +// WellKnownSymbolsResponse carries the handle ids of the per-checker singleton +// symbols (unknown, undefined, arguments) so the client can identify them by id +// without a round-trip on every check. +type WellKnownSymbolsResponse struct { + Unknown SymbolID `json:"unknown"` + Undefined SymbolID `json:"undefined"` + Arguments SymbolID `json:"arguments"` +} + // GetBaseTypeOfLiteralTypeParams returns the base type of a literal type. type GetBaseTypeOfLiteralTypeParams struct { Snapshot SnapshotID `json:"snapshot"` @@ -935,6 +1023,43 @@ type CheckerTypeParams struct { Type TypeID `json:"type"` } +// GetPropertyOfTypeParams are parameters for getPropertyOfType (a named property of a type). +type GetPropertyOfTypeParams struct { + Snapshot SnapshotID `json:"snapshot"` + Project ProjectID `json:"project"` + Type TypeID `json:"type"` + Name string `json:"name"` +} + +// GetMemberInModuleExportsParams are parameters for getMemberInModuleExports. +type GetMemberInModuleExportsParams struct { + Snapshot SnapshotID `json:"snapshot"` + Project ProjectID `json:"project"` + Symbol SymbolID `json:"symbol"` + Name string `json:"name"` +} + +// CheckerNodeParams are parameters for checker methods that operate on a node location. +type CheckerNodeParams struct { + Snapshot SnapshotID `json:"snapshot"` + Project ProjectID `json:"project"` + Location NodeHandle `json:"location"` +} + +// CheckerSymbolParams are parameters for checker methods that operate on a symbol. +type CheckerSymbolParams struct { + Snapshot SnapshotID `json:"snapshot"` + Project ProjectID `json:"project"` + Symbol SymbolID `json:"symbol"` +} + +// JSDocTagInfo is a single JSDoc tag, mirroring Strada's JSDocTagInfo but with the tag text +// rendered as a plain string rather than SymbolDisplayPart[]. +type JSDocTagInfo struct { + Name string `json:"name"` + Text string `json:"text,omitempty"` +} + // CheckerSignatureParams are parameters for checker methods that operate on a signature. type CheckerSignatureParams struct { Snapshot SnapshotID `json:"snapshot"` diff --git a/internal/api/session.go b/internal/api/session.go index 1a8fd17bb3c..ad7550f531a 100644 --- a/internal/api/session.go +++ b/internal/api/session.go @@ -4,6 +4,7 @@ import ( "context" "encoding/base64" "fmt" + "slices" "strconv" "strings" "sync" @@ -18,6 +19,7 @@ import ( "github.com/microsoft/typescript-go/internal/core" "github.com/microsoft/typescript-go/internal/json" "github.com/microsoft/typescript-go/internal/ls" + "github.com/microsoft/typescript-go/internal/lsp/lsproto" "github.com/microsoft/typescript-go/internal/nodebuilder" "github.com/microsoft/typescript-go/internal/pprof" "github.com/microsoft/typescript-go/internal/printer" @@ -43,6 +45,14 @@ type snapshotData struct { symbolRegistry map[SymbolID]*ast.Symbol symbolRegistryMu sync.RWMutex + // symbolCanonicalProjects records, for each registered symbol, the project it was + // first observed in. Because symbols are shared snapshot-wide (binder symbols are + // attached to source files, which can be shared across projects), lookups that need + // a project context (e.g. member/export ordering, node handle resolution) but don't + // receive one from the caller default to this canonical project. First-writer wins so + // the choice is stable. Guarded by symbolRegistryMu. + symbolCanonicalProjects map[SymbolID]ProjectID + projectRegistries map[ProjectID]*projectRegistryData projectRegistriesMu sync.RWMutex } @@ -61,10 +71,9 @@ type projectRegistryData struct { // getProgram looks up a program from a project handle within this snapshot. func (sd *snapshotData) getProgram(projectHandle ProjectID) (*compiler.Program, error) { - projectName := parseProjectHandle(projectHandle) - proj := sd.snapshot.ProjectCollection.GetProjectByPath(projectName) - if proj == nil { - return nil, fmt.Errorf("%w: project %s not found", ErrClientError, projectName) + proj, err := sd.getProject(projectHandle) + if err != nil { + return nil, err } program := proj.GetProgram() @@ -75,6 +84,16 @@ func (sd *snapshotData) getProgram(projectHandle ProjectID) (*compiler.Program, return program, nil } +// getProject looks up a project from a project handle within this snapshot. +func (sd *snapshotData) getProject(projectHandle ProjectID) (*project.Project, error) { + projectName := parseProjectHandle(projectHandle) + proj := sd.snapshot.ProjectCollection.GetProjectByPath(projectName) + if proj == nil { + return nil, fmt.Errorf("%w: project %s not found", ErrClientError, projectName) + } + return proj, nil +} + // nodeHandleFrom creates an index-based node handle (index.kind.path), building a node index table // for the file on-demand if needed. func (sd *snapshotData) nodeHandleFrom(node *ast.Node) NodeHandle { @@ -110,14 +129,19 @@ func (sd *snapshotData) getOrCreateProjectRegistry(projectID ProjectID) *project } // newSymbolResponse registers a symbol in the snapshot's registry and returns the response. -func (sd *snapshotData) newSymbolResponse(symbol *ast.Symbol) *SymbolResponse { +// canonicalProject is the project the symbol was observed in and must be non-empty; it is recorded +// as the symbol's canonical project (first writer wins) and returned to the client so it can default +// project-scoped follow-up lookups (members/exports, node resolution) to it. +func (sd *snapshotData) newSymbolResponse(symbol *ast.Symbol, canonicalProject ProjectID) *SymbolResponse { if symbol == nil { return nil } + id, project := sd.registerSymbol(symbol, canonicalProject) resp := &SymbolResponse{ - Id: sd.registerSymbol(symbol), - Name: symbol.Name, + Id: id, + Project: project, + Name: ast.EscapeSymbolName(symbol.Name), Flags: uint32(symbol.Flags), CheckFlags: uint32(symbol.CheckFlags), } @@ -144,9 +168,17 @@ func (sd *snapshotData) newSymbolResponse(symbol *ast.Symbol) *SymbolResponse { return resp } -func (sd *snapshotData) registerSymbol(symbol *ast.Symbol) SymbolID { +// registerSymbol registers a symbol in the snapshot's registry and returns its handle along with +// its canonical project. The canonical project is the project the symbol was first observed in +// (first writer wins for stability) and is always non-empty: every symbol handed to a client must +// carry a project so that project-scoped follow-up lookups (members/exports, parent, node +// resolution) have a default context. Callers must supply a non-empty project. +func (sd *snapshotData) registerSymbol(symbol *ast.Symbol, canonicalProject ProjectID) (SymbolID, ProjectID) { if symbol == nil { - return 0 + return 0, "" + } + if canonicalProject == "" { + panic("registerSymbol requires a non-empty canonical project") } id := SymbolHandle(symbol) sd.symbolRegistryMu.Lock() @@ -156,10 +188,15 @@ func (sd *snapshotData) registerSymbol(symbol *ast.Symbol) SymbolID { if existing != symbol { panic("duplicate symbol") } - return id + } else { + sd.symbolRegistry[id] = symbol } - sd.symbolRegistry[id] = symbol - return id + project, ok := sd.symbolCanonicalProjects[id] + if !ok { + sd.symbolCanonicalProjects[id] = canonicalProject + project = canonicalProject + } + return id, project } // newTypeResponse registers a type in the project's registry and returns the response. @@ -328,14 +365,41 @@ type Session struct { // This is set to true when using MessagePackProtocol. useBinaryResponses bool - // snapshots maps snapshot handles to their data. - // Each snapshot has its own symbol/type registries. + // snapshots maps snapshot handles to their data. Each snapshot has its own + // symbol/type registries. + // + // snapshotsMu guards the snapshots map and latestSnapshot. It is held only for + // short, map-bounded critical sections, never across slow work like a project + // snapshot update or checker queries. Read handlers (getSnapshotData and the + // language-service handlers built on it) take it for reading; handleRelease and + // the bookkeeping tail of handleUpdateSnapshot take it for writing. This is what + // lets queries against an existing snapshot run concurrently with the building of + // the next one. snapshots map[SnapshotID]*snapshotData snapshotsMu sync.RWMutex - // latestSnapshot tracks the most recently created snapshot for computing diffs. + // latestSnapshot tracks the most recently created snapshot, used as the diff base + // for the next update. Guarded by snapshotsMu. latestSnapshot SnapshotID + // openProjects and openFiles track the projects and files this session + // currently holds open in the project session's API state. The session holds + // at most one ref per project/file (opens are idempotent), so it can release + // exactly those refs on Close and never send a close for a ref it doesn't hold. + // Guarded by updateMu. + openProjects collections.Set[tspath.Path] + openFiles collections.Set[tspath.Path] + + // updateMu serializes the whole of handleUpdateSnapshot (and releaseOpenRefs) + // against other updates. Unlike snapshotsMu it is held across the slow + // projectSession.APIUpdate call, because building the request from + // openProjects/openFiles, applying it, committing the ref tracking, and advancing + // latestSnapshot must be one atomic step; otherwise concurrent updates could + // double-count refs or diff against a non-adjacent snapshot. Read handlers do NOT + // take this lock, so an in-flight update never blocks queries against existing + // snapshots. Lock ordering is updateMu -> snapshotsMu (never the reverse). + updateMu sync.Mutex + cpuProfiler pprof.CPUProfiler } @@ -402,7 +466,7 @@ func (setup checkerSetup) newTypeResponse(t *checker.Type) *TypeResponse { } func (setup checkerSetup) newSymbolResponse(sym *ast.Symbol) *SymbolResponse { - return setup.sd.newSymbolResponse(sym) + return setup.sd.newSymbolResponse(sym, setup.projectID) } func (setup checkerSetup) newSignatureResponse(sig *checker.Signature) *SignatureResponse { @@ -447,6 +511,14 @@ func (s *Session) setupChecker(ctx context.Context, snapshot SnapshotID, project // setupLanguageService creates a LanguageService for the given snapshot/project. // Unlike setupChecker, this does NOT acquire a checker from the pool, so callers that // only need an LS (and not a Checker) can avoid blocking on / holding a pooled checker. +// +// The LS acquires its own checker internally (keyed by the ctx's checker lifetime). +// If a handler returns symbol/type/signature handles the client may later re-query +// on the API checker (e.g. completion with IncludeSymbol -> GetTypeOfSymbol), wrap +// ctx with core.WithCheckerLifetime(ctx, core.CheckerLifetimeAPI) so those handles +// are produced on the persistent API checker and stay resolvable. Only safe when the +// LS operation acquires a checker exactly once; nested acquisitions (e.g. find-all- +// references) would deadlock on the single-slot persistent checker. func (s *Session) setupLanguageService(sd *snapshotData, program *compiler.Program, projectHandle ProjectID, activeFile string) (*ls.LanguageService, error) { projectName := parseProjectHandle(projectHandle) proj := sd.snapshot.ProjectCollection.GetProjectByPath(projectName) @@ -488,6 +560,10 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json. return s.handleGetDefaultProjectForFile(ctx, parsed.(*GetDefaultProjectForFileParams)) case string(MethodGetSourceFile): return s.handleGetSourceFile(ctx, parsed.(*GetSourceFileParams)) + case string(MethodGetSourceFileNames): + return s.handleGetSourceFileNames(ctx, parsed.(*GetSourceFileNamesParams)) + case string(MethodGetSourceFileMetadata): + return s.handleGetSourceFileMetadata(ctx, parsed.(*GetSourceFileParams)) case string(MethodGetSymbolAtPosition): return s.handleGetSymbolAtPosition(ctx, parsed.(*GetSymbolAtPositionParams)) case string(MethodGetSymbolsAtPositions): @@ -556,6 +632,10 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json. return s.handleGetBaseTypeOfType(ctx, parsed.(*GetTypePropertyParams)) case string(MethodGetConstraintOfType): return s.handleGetConstraintOfType(ctx, parsed.(*GetTypePropertyParams)) + case string(MethodGetTrueTypeOfConditionalType): + return s.handleGetTrueTypeOfConditionalType(ctx, parsed.(*GetTypePropertyParams)) + case string(MethodGetFalseTypeOfConditionalType): + return s.handleGetFalseTypeOfConditionalType(ctx, parsed.(*GetTypePropertyParams)) case string(MethodGetTypeParametersOfSignature): return s.handleGetTypeParametersOfSignature(ctx, parsed.(*GetSignaturePropertyParams)) case string(MethodGetParametersOfSignature): @@ -604,12 +684,40 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json. return s.handleGetBaseTypes(ctx, parsed.(*CheckerTypeParams)) case string(MethodGetPropertiesOfType): return s.handleGetPropertiesOfType(ctx, parsed.(*CheckerTypeParams)) + case string(MethodGetApparentType): + return s.handleGetApparentType(ctx, parsed.(*CheckerTypeParams)) + case string(MethodGetPropertyOfType): + return s.handleGetPropertyOfType(ctx, parsed.(*GetPropertyOfTypeParams)) case string(MethodGetIndexInfosOfType): return s.handleGetIndexInfosOfType(ctx, parsed.(*CheckerTypeParams)) case string(MethodGetConstraintOfTypeParameter): return s.handleGetConstraintOfTypeParameter(ctx, parsed.(*CheckerTypeParams)) + case string(MethodGetBaseConstraintOfType): + return s.handleGetBaseConstraintOfType(ctx, parsed.(*CheckerTypeParams)) case string(MethodGetTypeArguments): return s.handleGetTypeArguments(ctx, parsed.(*CheckerTypeParams)) + case string(MethodGetConstantValue): + return s.handleGetConstantValue(ctx, parsed.(*CheckerNodeParams)) + case string(MethodGetSignatureFromDeclaration): + return s.handleGetSignatureFromDeclaration(ctx, parsed.(*CheckerNodeParams)) + case string(MethodGetExportSpecifierLocalTarget): + return s.handleGetExportSpecifierLocalTargetSymbol(ctx, parsed.(*CheckerNodeParams)) + case string(MethodGetAliasedSymbol): + return s.handleGetAliasedSymbol(ctx, parsed.(*CheckerSymbolParams)) + case string(MethodGetImmediateAliasedSymbol): + return s.handleGetImmediateAliasedSymbol(ctx, parsed.(*CheckerSymbolParams)) + case string(MethodGetExportsOfModule): + return s.handleGetExportsOfModule(ctx, parsed.(*CheckerSymbolParams)) + case string(MethodGetMemberInModuleExports): + return s.handleGetMemberInModuleExports(ctx, parsed.(*GetMemberInModuleExportsParams)) + case string(MethodGetJSDocTags): + return s.handleGetJSDocTags(ctx, parsed.(*CheckerSymbolParams)) + case string(MethodGetDocumentationComment): + return s.handleGetDocumentationComment(ctx, parsed.(*CheckerSymbolParams)) + case string(MethodIsArrayType): + return s.handleIsArrayType(ctx, parsed.(*CheckerTypeParams)) + case string(MethodIsTupleType): + return s.handleIsTupleType(ctx, parsed.(*CheckerTypeParams)) case string(MethodGetAnyType): return s.handleGetIntrinsicType(ctx, parsed.(*GetIntrinsicTypeParams), (*checker.Checker).GetAnyType) case string(MethodGetStringType): @@ -632,14 +740,22 @@ func (s *Session) HandleRequest(ctx context.Context, method string, params json. return s.handleGetIntrinsicType(ctx, parsed.(*GetIntrinsicTypeParams), (*checker.Checker).GetBigIntType) case string(MethodGetESSymbolType): return s.handleGetIntrinsicType(ctx, parsed.(*GetIntrinsicTypeParams), (*checker.Checker).GetESSymbolType) + case string(MethodGetWellKnownSymbols): + return s.handleGetWellKnownSymbols(ctx, parsed.(*GetIntrinsicTypeParams)) case string(MethodGetSyntacticDiagnostics): return s.handleGetSyntacticDiagnostics(ctx, parsed.(*GetDiagnosticsParams)) + case string(MethodGetBindDiagnostics): + return s.handleGetBindDiagnostics(ctx, parsed.(*GetDiagnosticsParams)) case string(MethodGetSemanticDiagnostics): return s.handleGetSemanticDiagnostics(ctx, parsed.(*GetDiagnosticsParams)) case string(MethodGetSuggestionDiagnostics): return s.handleGetSuggestionDiagnostics(ctx, parsed.(*GetDiagnosticsParams)) case string(MethodGetDeclarationDiagnostics): return s.handleGetDeclarationDiagnostics(ctx, parsed.(*GetDiagnosticsParams)) + case string(MethodGetProgramDiagnostics): + return s.handleGetProgramDiagnostics(ctx, parsed.(*GetProjectDiagnosticsParams)) + case string(MethodGetGlobalDiagnostics): + return s.handleGetGlobalDiagnostics(ctx, parsed.(*GetProjectDiagnosticsParams)) case string(MethodGetConfigFileParsingDiagnostics): return s.handleGetConfigFileParsingDiagnostics(ctx, parsed.(*GetProjectDiagnosticsParams)) case string(MethodStartCPUProfile): @@ -703,34 +819,111 @@ func (s *Session) handleInitialize(ctx context.Context) (*InitializeResponse, er }, nil } -// handleUpdateSnapshot creates a new snapshot, optionally opening a project. -// With no args, it adopts the latest LSP state. -// With OpenProject set, it opens the specified project in the new snapshot. +// handleUpdateSnapshot creates a new snapshot, optionally opening or closing +// projects and files. With no args, it adopts the latest LSP state. Opens and +// closes are ref-counted per session: the session holds at most one ref per +// project/file, so repeated opens are idempotent and a close only releases a ref +// the session is actually holding. func (s *Session) handleUpdateSnapshot(ctx context.Context, params *UpdateSnapshotParams) (*UpdateSnapshotResponse, error) { - var snapshot *project.Snapshot + // Fully serialize updates: snapshot creation, ref tracking, and the + // latestSnapshot/diff bookkeeping must be atomic with respect to other updates, + // otherwise concurrent updates could compute diffs against a non-adjacent + // snapshot or leave latestSnapshot pointing at a stale snapshot. + s.updateMu.Lock() + defer s.updateMu.Unlock() fileChanges := s.toFileChangeSummary(params.FileChanges) - if params.OpenProject != "" { - configFileName := s.toAbsoluteFileName(params.OpenProject) - _, newSnapshot, err := s.projectSession.APIOpenProject(ctx, configFileName, fileChanges) - if err != nil { - // APIOpenProject returns a ref'd snapshot even on error; release it. - newSnapshot.Deref(s.projectSession) - return nil, fmt.Errorf("%w: failed to load project: %w", ErrClientError, err) + apiRequest := &project.APISnapshotRequest{} + + // Open projects: only take a new ref for projects we aren't already holding open. + var openedProjects []tspath.Path + for _, p := range params.OpenProjects { + configFileName := p.ToAbsoluteFileName(s.projectSession.GetCurrentDirectory()) + configPath := s.toPath(configFileName) + if s.openProjects.Has(configPath) { + continue } - snapshot = newSnapshot - } else { - // Even when fileChanges is empty, APIUpdateWithFileChanges ensures all projects - // opened by the API are up to date. For an API connected to an LSP server, this - // brings the API state up to date with the LSP state and ensures projects the - // API cares about are ready to be queried. - snapshot = s.projectSession.APIUpdateWithFileChanges(ctx, fileChanges) + if apiRequest.OpenProjects == nil { + apiRequest.OpenProjects = collections.NewSetWithSizeHint[string](len(params.OpenProjects)) + } + apiRequest.OpenProjects.Add(configFileName) + openedProjects = append(openedProjects, configPath) + } + + // Close projects: only release a ref we currently hold. + var closedProjects []tspath.Path + for _, p := range params.CloseProjects { + configPath := s.toPath(p.ToAbsoluteFileName(s.projectSession.GetCurrentDirectory())) + if !s.openProjects.Has(configPath) { + continue + } + if apiRequest.CloseProjects == nil { + apiRequest.CloseProjects = collections.NewSetWithSizeHint[tspath.Path](len(params.CloseProjects)) + } + apiRequest.CloseProjects.Add(configPath) + closedProjects = append(closedProjects, configPath) + } + + // Open files: only open files we aren't already holding open, so each file is + // held by at most one API ref from this session. + var openedFiles []tspath.Path + for _, f := range params.OpenFiles { + uri := f.ToURI(s.projectSession.GetCurrentDirectory()) + path := s.toPath(uri.FileName()) + if s.openFiles.Has(path) { + continue + } + if apiRequest.OpenFiles == nil { + apiRequest.OpenFiles = collections.NewSetWithSizeHint[lsproto.DocumentUri](len(params.OpenFiles)) + } + apiRequest.OpenFiles.Add(uri) + openedFiles = append(openedFiles, path) } - // Create or ref-count snapshot data. - // If the same snapshot ID is returned (no changes), we increment the - // ref count so each client-side Snapshot can be disposed independently. + // Close files: only release a ref we currently hold. + var closedFiles []tspath.Path + for _, f := range params.CloseFiles { + path := s.toPath(f.ToURI(s.projectSession.GetCurrentDirectory()).FileName()) + if !s.openFiles.Has(path) { + continue + } + if apiRequest.CloseFiles == nil { + apiRequest.CloseFiles = collections.NewSetWithSizeHint[tspath.Path](len(params.CloseFiles)) + } + apiRequest.CloseFiles.Add(path) + closedFiles = append(closedFiles, path) + } + + // Even when nothing is opened or closed, APIUpdate ensures all projects and + // files opened by the API are up to date. For an API connected to an LSP server, + // this brings the API state up to date with the LSP state and ensures projects + // the API cares about are ready to be queried. + snapshot, err := s.projectSession.APIUpdate(ctx, fileChanges, apiRequest) + if err != nil { + // APIUpdate returns a ref'd snapshot even on error; release it. + snapshot.Deref(s.projectSession) + return nil, fmt.Errorf("%w: failed to update snapshot: %w", ErrClientError, err) + } + + // Commit ref tracking now that the update succeeded. + for _, configPath := range openedProjects { + s.openProjects.Add(configPath) + } + for _, configPath := range closedProjects { + s.openProjects.Delete(configPath) + } + for _, path := range openedFiles { + s.openFiles.Add(path) + } + for _, path := range closedFiles { + s.openFiles.Delete(path) + } + + // Create or ref-count snapshot data, then atomically read the previous latest + // snapshot (the diff base) and advance latestSnapshot to the new handle. + // If the same snapshot ID is returned (no changes), we increment the ref count + // so each client-side Snapshot can be disposed independently. handle := snapshotHandle(snapshot) s.snapshotsMu.Lock() sd, exists := s.snapshots[handle] @@ -741,13 +934,16 @@ func (s *Session) handleUpdateSnapshot(ctx context.Context, params *UpdateSnapsh sd.refCount++ } else { sd = &snapshotData{ - snapshot: snapshot, - refCount: 1, - symbolRegistry: make(map[SymbolID]*ast.Symbol), - projectRegistries: make(map[ProjectID]*projectRegistryData), + snapshot: snapshot, + refCount: 1, + symbolRegistry: make(map[SymbolID]*ast.Symbol), + symbolCanonicalProjects: make(map[SymbolID]ProjectID), + projectRegistries: make(map[ProjectID]*projectRegistryData), } s.snapshots[handle] = sd } + prevSD := s.snapshots[s.latestSnapshot] + s.latestSnapshot = handle s.snapshotsMu.Unlock() // Build projects list @@ -759,18 +955,10 @@ func (s *Session) handleUpdateSnapshot(ctx context.Context, params *UpdateSnapsh // Compute changes from the previous latest snapshot var changes *SnapshotChanges - s.snapshotsMu.RLock() - prevSD := s.snapshots[s.latestSnapshot] - s.snapshotsMu.RUnlock() if prevSD != nil { changes = computeSnapshotChanges(prevSD.snapshot, snapshot) } - // Update the latest snapshot - s.snapshotsMu.Lock() - s.latestSnapshot = handle - s.snapshotsMu.Unlock() - return &UpdateSnapshotResponse{ Snapshot: handle, Projects: projectResponses, @@ -801,17 +989,18 @@ func (s *Session) handleRelease(ctx context.Context, params *ReleaseParams) (any return true, nil } -// handleGetDefaultProjectForFile returns the default project for a given file. +// handleGetDefaultProjectForFile returns the default project for a given file, +// or nil if no project currently contains the file. func (s *Session) handleGetDefaultProjectForFile(ctx context.Context, params *GetDefaultProjectForFileParams) (*ProjectResponse, error) { sd, err := s.getSnapshotData(params.Snapshot) if err != nil { return nil, err } - uri := params.File.ToURI() + uri := params.File.ToURI(s.projectSession.GetCurrentDirectory()) proj := sd.snapshot.GetDefaultProject(uri) if proj == nil { - return nil, fmt.Errorf("%w: no project found for file %v", ErrClientError, params.File) + return nil, nil } return NewProjectResponse(proj), nil @@ -869,7 +1058,7 @@ func (s *Session) handleGetSourceFile(ctx context.Context, params *GetSourceFile return nil, nil } - // Encode the full source file + // Encode the full source file. data, _, err := encoder.EncodeSourceFile(sourceFile) if err != nil { return nil, fmt.Errorf("failed to encode source file: %w", err) @@ -884,6 +1073,54 @@ func (s *Session) handleGetSourceFile(ctx context.Context, params *GetSourceFile }, nil } +// handleGetSourceFileNames returns file names of all source files in a project. +func (s *Session) handleGetSourceFileNames(ctx context.Context, params *GetSourceFileNamesParams) ([]string, error) { + sd, err := s.getSnapshotData(params.Snapshot) + if err != nil { + return nil, err + } + + program, err := sd.getProgram(params.Project) + if err != nil { + return nil, err + } + + sourceFiles := program.GetSourceFiles() + result := make([]string, len(sourceFiles)) + for i, sourceFile := range sourceFiles { + result[i] = sourceFile.FileName() + } + return result, nil +} + +// handleGetSourceFileMetadata returns program-stored metadata for a single source file. +// The client fetches this lazily per file and caches it. +func (s *Session) handleGetSourceFileMetadata(ctx context.Context, params *GetSourceFileParams) (*SourceFileMetadata, error) { + sd, err := s.getSnapshotData(params.Snapshot) + if err != nil { + return nil, err + } + + program, err := sd.getProgram(params.Project) + if err != nil { + return nil, err + } + + sourceFile := program.GetSourceFile(params.File.ToFileName()) + if sourceFile == nil { + return nil, nil + } + + metaData := program.GetSourceFileMetaData(sourceFile.Path()) + return &SourceFileMetadata{ + IsDefaultLibrary: program.IsSourceFileDefaultLibrary(sourceFile.Path()), + IsFromExternalLibrary: program.IsSourceFileFromExternalLibrary(sourceFile), + PackageJsonType: metaData.PackageJsonType, + PackageJsonDirectory: metaData.PackageJsonDirectory, + ImpliedNodeFormat: metaData.ImpliedNodeFormat, + }, nil +} + // handleGetSymbolAtPosition returns the symbol at a position in a file. func (s *Session) handleGetSymbolAtPosition(ctx context.Context, params *GetSymbolAtPositionParams) (*SymbolResponse, error) { setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) @@ -1247,14 +1484,14 @@ func (s *Session) handleGetParentOfSymbol(_ context.Context, params *GetSymbolPr return s.resolveSymbolPropertyOfSymbol(params, func(sym *ast.Symbol) *ast.Symbol { return sym.Parent }) } -func (s *Session) handleGetMembersOfSymbol(_ context.Context, params *GetSymbolPropertyParams) ([]*SymbolResponse, error) { - return s.resolveSymbolTablePropertyOfSymbol(params, func(symbol *ast.Symbol) ast.SymbolTable { +func (s *Session) handleGetMembersOfSymbol(ctx context.Context, params *GetSymbolPropertyParams) ([]*SymbolResponse, error) { + return s.resolveSymbolTablePropertyOfSymbol(ctx, params, func(symbol *ast.Symbol) ast.SymbolTable { return symbol.Members }) } -func (s *Session) handleGetExportsOfSymbol(_ context.Context, params *GetSymbolPropertyParams) ([]*SymbolResponse, error) { - return s.resolveSymbolTablePropertyOfSymbol(params, func(symbol *ast.Symbol) ast.SymbolTable { +func (s *Session) handleGetExportsOfSymbol(ctx context.Context, params *GetSymbolPropertyParams) ([]*SymbolResponse, error) { + return s.resolveSymbolTablePropertyOfSymbol(ctx, params, func(symbol *ast.Symbol) ast.SymbolTable { return symbol.Exports }) } @@ -1413,7 +1650,7 @@ func (s *Session) resolveSymbolPropertyOfType(params *GetTypePropertyParams, get if result == nil { return nil, nil } - return sd.newSymbolResponse(result), nil + return sd.newSymbolResponse(result, params.Project), nil } // resolveSymbolTablePropertyOfSymbol resolves a symbol property of type `Symbol` and returns a symbol response. @@ -1432,11 +1669,13 @@ func (s *Session) resolveSymbolPropertyOfSymbol(params *GetSymbolPropertyParams, if result == nil { return nil, nil } - return sd.newSymbolResponse(result), nil + return sd.newSymbolResponse(result, params.Project), nil } // resolveSymbolTablePropertyOfSymbol resolves a symbol property of type `SymbolTable` and returns an array of symbol responses. -func (s *Session) resolveSymbolTablePropertyOfSymbol(params *GetSymbolPropertyParams, getter func(*ast.Symbol) ast.SymbolTable) ([]*SymbolResponse, error) { +// Results are sorted using the checker's canonical symbol ordering so that API consumers receive +// a stable, deterministic order instead of Go's randomized map iteration order. +func (s *Session) resolveSymbolTablePropertyOfSymbol(ctx context.Context, params *GetSymbolPropertyParams, getter func(*ast.Symbol) ast.SymbolTable) ([]*SymbolResponse, error) { sd, err := s.getSnapshotData(params.Snapshot) if err != nil { return nil, err @@ -1448,13 +1687,31 @@ func (s *Session) resolveSymbolTablePropertyOfSymbol(params *GetSymbolPropertyPa } symbolTable := getter(symbol) - if symbolTable == nil || len(symbolTable) == 0 { + if len(symbolTable) == 0 { return nil, nil } + if len(symbolTable) == 1 { + for _, sub := range symbolTable { + return []*SymbolResponse{sd.newSymbolResponse(sub, params.Project)}, nil + } + } + + // More than one symbol, need a checker to sort + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() - results := make([]*SymbolResponse, 0, len(symbolTable)) + symbols := make([]*ast.Symbol, 0, len(symbolTable)) for _, sub := range symbolTable { - results = append(results, sd.newSymbolResponse(sub)) + symbols = append(symbols, sub) + } + slices.SortFunc(symbols, setup.checker.CompareSymbols) + + results := make([]*SymbolResponse, len(symbols)) + for i, sub := range symbols { + results[i] = setup.newSymbolResponse(sub) } return results, nil } @@ -1478,7 +1735,7 @@ func (s *Session) resolveSymbolArrayPropertyOfSignature(params *GetSignatureProp results := make([]*SymbolResponse, len(symbols)) for i, sym := range symbols { - results[i] = sd.newSymbolResponse(sym) + results[i] = sd.newSymbolResponse(sym, params.Project) } return results, nil } @@ -1499,7 +1756,7 @@ func (s *Session) resolveSymbolPropertyOfSignature(params *GetSignaturePropertyP if result == nil { return nil, nil } - return sd.newSymbolResponse(result), nil + return sd.newSymbolResponse(result, params.Project), nil } func (s *Session) resolveTypeArrayPropertyOfSignature(params *GetSignaturePropertyParams, getter func(signature *checker.Signature) []*checker.Type) ([]*TypeResponse, error) { @@ -1911,6 +2168,25 @@ func (s *Session) handleGetIntrinsicType(ctx context.Context, params *GetIntrins return setup.newTypeResponse(t), nil } +// handleGetWellKnownSymbols returns the handle ids of the per-checker singleton +// symbols (unknown, undefined, arguments) so the client can identify them by id. +func (s *Session) handleGetWellKnownSymbols(ctx context.Context, params *GetIntrinsicTypeParams) (*WellKnownSymbolsResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + unknown, _ := setup.sd.registerSymbol(setup.checker.GetUnknownSymbol(), setup.projectID) + undefined, _ := setup.sd.registerSymbol(setup.checker.GetUndefinedSymbol(), setup.projectID) + arguments, _ := setup.sd.registerSymbol(setup.checker.GetArgumentsSymbol(), setup.projectID) + return &WellKnownSymbolsResponse{ + Unknown: unknown, + Undefined: undefined, + Arguments: arguments, + }, nil +} + // handleIsContextSensitive returns whether a node is context-sensitive. func (s *Session) handleIsContextSensitive(ctx context.Context, params *GetContextualTypeParams) (bool, error) { setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) @@ -2002,6 +2278,38 @@ func (s *Session) handleGetTypePredicateOfSignature(ctx context.Context, params return resp, nil } +// handleIsArrayType returns whether a type is Array or ReadonlyArray. +func (s *Session) handleIsArrayType(ctx context.Context, params *CheckerTypeParams) (bool, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return false, err + } + defer setup.done() + + t, err := setup.resolveTypeHandle(params.Type) + if err != nil { + return false, err + } + + return setup.checker.IsArrayType(t), nil +} + +// handleIsTupleType returns whether a type is a tuple type. +func (s *Session) handleIsTupleType(ctx context.Context, params *CheckerTypeParams) (bool, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return false, err + } + defer setup.done() + + t, err := setup.resolveTypeHandle(params.Type) + if err != nil { + return false, err + } + + return checker.IsTupleType(t), nil +} + // handleGetBaseTypes returns the base types of an interface/class type. func (s *Session) handleGetBaseTypes(ctx context.Context, params *CheckerTypeParams) ([]*TypeResponse, error) { setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) @@ -2054,6 +2362,27 @@ func (s *Session) handleGetPropertiesOfType(ctx context.Context, params *Checker return results, nil } +// handleGetApparentType returns the apparent type of a type. +func (s *Session) handleGetApparentType(ctx context.Context, params *CheckerTypeParams) (*TypeResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + t, err := setup.resolveTypeHandle(params.Type) + if err != nil { + return nil, err + } + + apparent := setup.checker.GetApparentType(t) + if apparent == nil { + return nil, nil + } + + return setup.newTypeResponse(apparent), nil +} + // handleGetIndexInfosOfType returns the index infos of a type. func (s *Session) handleGetIndexInfosOfType(ctx context.Context, params *CheckerTypeParams) ([]*IndexInfoResponse, error) { setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) @@ -2108,6 +2437,274 @@ func (s *Session) handleGetConstraintOfTypeParameter(ctx context.Context, params return setup.newTypeResponse(constraint), nil } +// handleGetBaseConstraintOfType returns the base constraint of an instantiable type. +func (s *Session) handleGetBaseConstraintOfType(ctx context.Context, params *CheckerTypeParams) (*TypeResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + t, err := setup.resolveTypeHandle(params.Type) + if err != nil { + return nil, err + } + + constraint := setup.checker.GetBaseConstraintOfType(t) + if constraint == nil { + return nil, nil + } + + return setup.newTypeResponse(constraint), nil +} + +// handleGetPropertyOfType returns a named property symbol of a type. +func (s *Session) handleGetPropertyOfType(ctx context.Context, params *GetPropertyOfTypeParams) (*SymbolResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + t, err := setup.resolveTypeHandle(params.Type) + if err != nil { + return nil, err + } + + prop := setup.checker.GetPropertyOfType(t, params.Name) + if prop == nil { + return nil, nil + } + + return setup.newSymbolResponse(prop), nil +} + +// handleGetConstantValue returns the constant value of an enum member or const enum access. +func (s *Session) handleGetConstantValue(ctx context.Context, params *CheckerNodeParams) (any, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + node, err := setup.sd.resolveNodeHandle(setup.program, params.Location) + if err != nil { + return nil, err + } + if node == nil { + return nil, nil + } + + return literalValueToJSON(setup.checker.GetConstantValue(node)), nil +} + +// handleGetSignatureFromDeclaration returns the signature of a function-like declaration. +func (s *Session) handleGetSignatureFromDeclaration(ctx context.Context, params *CheckerNodeParams) (*SignatureResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + node, err := setup.sd.resolveNodeHandle(setup.program, params.Location) + if err != nil { + return nil, err + } + if node == nil { + return nil, nil + } + + sig := setup.checker.GetSignatureFromDeclaration(node) + if sig == nil { + return nil, nil + } + + return setup.newSignatureResponse(sig), nil +} + +// handleGetExportSpecifierLocalTargetSymbol returns the local target symbol of an export specifier. +func (s *Session) handleGetExportSpecifierLocalTargetSymbol(ctx context.Context, params *CheckerNodeParams) (*SymbolResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + node, err := setup.sd.resolveNodeHandle(setup.program, params.Location) + if err != nil { + return nil, err + } + if node == nil { + return nil, nil + } + + symbol := setup.checker.GetExportSpecifierLocalTargetSymbol(node) + if symbol == nil { + return nil, nil + } + + return setup.newSymbolResponse(symbol), nil +} + +// handleGetAliasedSymbol resolves an alias symbol to its target. +func (s *Session) handleGetAliasedSymbol(ctx context.Context, params *CheckerSymbolParams) (*SymbolResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + symbol, err := setup.resolveSymbolHandle(params.Symbol) + if err != nil { + return nil, err + } + if symbol == nil { + return nil, nil + } + + aliased := setup.checker.GetAliasedSymbol(symbol) + if aliased == nil { + return nil, nil + } + + return setup.newSymbolResponse(aliased), nil +} + +// handleGetImmediateAliasedSymbol resolves one level of alias indirection. +func (s *Session) handleGetImmediateAliasedSymbol(ctx context.Context, params *CheckerSymbolParams) (*SymbolResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + symbol, err := setup.resolveSymbolHandle(params.Symbol) + if err != nil { + return nil, err + } + if symbol == nil { + return nil, nil + } + + aliased := setup.checker.GetImmediateAliasedSymbol(symbol) + if aliased == nil { + return nil, nil + } + + return setup.newSymbolResponse(aliased), nil +} + +// handleGetExportsOfModule returns the resolved exports of a module symbol, +// including those introduced by `export *` and re-exports. +func (s *Session) handleGetExportsOfModule(ctx context.Context, params *CheckerSymbolParams) ([]*SymbolResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + symbol, err := setup.resolveSymbolHandle(params.Symbol) + if err != nil { + return nil, err + } + if symbol == nil { + return nil, nil + } + + exports := setup.checker.GetExportsOfModule(symbol) + if len(exports) == 0 { + return nil, nil + } + slices.SortFunc(exports, setup.checker.CompareSymbols) + + results := make([]*SymbolResponse, len(exports)) + for i, exp := range exports { + results[i] = setup.newSymbolResponse(exp) + } + + return results, nil +} + +// handleGetMemberInModuleExports returns an export by name from a module symbol. +func (s *Session) handleGetMemberInModuleExports(ctx context.Context, params *GetMemberInModuleExportsParams) (*SymbolResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + symbol, err := setup.resolveSymbolHandle(params.Symbol) + if err != nil { + return nil, err + } + if symbol == nil { + return nil, nil + } + + member := setup.checker.TryGetMemberInModuleExports(params.Name, symbol) + if member == nil { + return nil, nil + } + + return setup.newSymbolResponse(member), nil +} + +// handleGetJSDocTags returns the JSDoc tags of a symbol as structured name/text pairs. +func (s *Session) handleGetJSDocTags(ctx context.Context, params *CheckerSymbolParams) ([]*JSDocTagInfo, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + symbol, err := setup.resolveSymbolHandle(params.Symbol) + if err != nil { + return nil, err + } + if symbol == nil { + return nil, nil + } + + langSvc, err := s.setupLanguageService(setup.sd, setup.program, params.Project, "") + if err != nil { + return nil, err + } + + tags := langSvc.GetSymbolJSDocTags(symbol) + if len(tags) == 0 { + return nil, nil + } + results := make([]*JSDocTagInfo, len(tags)) + for i, tag := range tags { + results[i] = &JSDocTagInfo{Name: tag.Name, Text: tag.Text} + } + return results, nil +} + +// handleGetDocumentationComment returns the rendered documentation comment of a symbol as plain text. +func (s *Session) handleGetDocumentationComment(ctx context.Context, params *CheckerSymbolParams) (string, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return "", err + } + defer setup.done() + + symbol, err := setup.resolveSymbolHandle(params.Symbol) + if err != nil { + return "", err + } + if symbol == nil { + return "", nil + } + + langSvc, err := s.setupLanguageService(setup.sd, setup.program, params.Project, "") + if err != nil { + return "", err + } + + return langSvc.GetSymbolDocumentationComment(setup.checker, symbol), nil +} + // handleGetTypeArguments returns the type arguments of a type reference. func (s *Session) handleGetTypeArguments(ctx context.Context, params *CheckerTypeParams) ([]*TypeResponse, error) { setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) @@ -2134,6 +2731,36 @@ func (s *Session) handleGetTypeArguments(ctx context.Context, params *CheckerTyp return results, nil } +func (s *Session) handleGetTrueTypeOfConditionalType(ctx context.Context, params *GetTypePropertyParams) (*TypeResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + t, err := setup.sd.resolveTypeHandle(params.Project, params.Type) + if err != nil { + return nil, err + } + + return setup.sd.newTypeResponse(params.Project, setup.checker.GetTrueTypeOfConditionalType(t)), nil +} + +func (s *Session) handleGetFalseTypeOfConditionalType(ctx context.Context, params *GetTypePropertyParams) (*TypeResponse, error) { + setup, err := s.setupChecker(ctx, params.Snapshot, params.Project) + if err != nil { + return nil, err + } + defer setup.done() + + t, err := setup.sd.resolveTypeHandle(params.Project, params.Type) + if err != nil { + return nil, err + } + + return setup.sd.newTypeResponse(params.Project, setup.checker.GetFalseTypeOfConditionalType(t)), nil +} + func (sd *snapshotData) resolveNodeHandle(program *compiler.Program, handle NodeHandle) (*ast.Node, error) { s := string(handle) // Format: "index.kind.path" — we need index and path, kind is informational only. @@ -2223,20 +2850,49 @@ func computeSnapshotChanges(prev *project.Snapshot, next *project.Snapshot) *Sna // Close closes the session and releases all active snapshots, // regardless of their ref counts. func (s *Session) Close() { + s.releaseOpenRefs() + s.snapshotsMu.Lock() defer s.snapshotsMu.Unlock() - for handle := range s.snapshots { + for handle, sd := range s.snapshots { + sd.snapshot.Deref(s.projectSession) delete(s.snapshots, handle) } } -func formatSessionID(id uint64) string { - return fmt.Sprintf("api-session-%d", id) +// releaseOpenRefs releases every project and file ref this session is holding open +// in the project session. This keeps the API's ref counts balanced when an API +// session is shut down while sharing a longer-lived project session (e.g. one +// backing an LSP server), so API-opened projects and files aren't leaked. Only +// refs the session currently holds are closed, so it never over-releases. +func (s *Session) releaseOpenRefs() { + s.updateMu.Lock() + defer s.updateMu.Unlock() + + if s.openProjects.Len() == 0 && s.openFiles.Len() == 0 { + return + } + + apiRequest := &project.APISnapshotRequest{} + if s.openProjects.Len() > 0 { + apiRequest.CloseProjects = s.openProjects.Clone() + } + if s.openFiles.Len() > 0 { + apiRequest.CloseFiles = s.openFiles.Clone() + } + snapshot, err := s.projectSession.APIUpdate(context.Background(), project.FileChangeSummary{}, apiRequest) + // APIUpdate returns a ref'd snapshot even on error; always release it. + snapshot.Deref(s.projectSession) + if err != nil { + return + } + + s.openProjects.Clear() + s.openFiles.Clear() } -// toAbsoluteFileName converts a file name to an absolute path. -func (s *Session) toAbsoluteFileName(fileName string) string { - return tspath.GetNormalizedAbsolutePath(fileName, s.projectSession.GetCurrentDirectory()) +func formatSessionID(id uint64) string { + return fmt.Sprintf("api-session-%d", id) } // toPath converts a file name to a normalized path. @@ -2255,16 +2911,17 @@ func (s *Session) toFileChangeSummary(changes *APIFileChanges) project.FileChang summary.IncludesWatchChangeOutsideNodeModules = true return summary } + cwd := s.projectSession.GetCurrentDirectory() for _, doc := range changes.Changed { - uri := doc.ToURI() + uri := doc.ToURI(cwd) summary.Changed.Add(uri) } for _, doc := range changes.Created { - uri := doc.ToURI() + uri := doc.ToURI(cwd) summary.Created.Add(uri) } for _, doc := range changes.Deleted { - uri := doc.ToURI() + uri := doc.ToURI(cwd) summary.Deleted.Add(uri) } if summary.Changed.Len()+summary.Created.Len()+summary.Deleted.Len() > 0 { @@ -2295,6 +2952,28 @@ func (s *Session) handleGetSyntacticDiagnostics(ctx context.Context, params *Get return NewDiagnosticResponses(diags), nil } +// handleGetBindDiagnostics returns bind diagnostics for a file or all files. +func (s *Session) handleGetBindDiagnostics(ctx context.Context, params *GetDiagnosticsParams) ([]*DiagnosticResponse, error) { + ctx = core.WithCheckerLifetime(ctx, core.CheckerLifetimeDiagnostics) + sd, err := s.getSnapshotData(params.Snapshot) + if err != nil { + return nil, err + } + + program, err := sd.getProgram(params.Project) + if err != nil { + return nil, err + } + + sourceFile, err := s.resolveOptionalSourceFile(program, params.File) + if err != nil { + return nil, err + } + + diags := program.GetBindDiagnostics(ctx, sourceFile) + return NewDiagnosticResponses(diags), nil +} + // handleGetSemanticDiagnostics returns semantic diagnostics for a file or all files. func (s *Session) handleGetSemanticDiagnostics(ctx context.Context, params *GetDiagnosticsParams) ([]*DiagnosticResponse, error) { ctx = core.WithCheckerLifetime(ctx, core.CheckerLifetimeDiagnostics) @@ -2377,6 +3056,53 @@ func (s *Session) handleGetConfigFileParsingDiagnostics(ctx context.Context, par return NewDiagnosticResponses(diags), nil } +// handleGetProgramDiagnostics returns program-wide diagnostics, including options diagnostics. +func (s *Session) handleGetProgramDiagnostics(ctx context.Context, params *GetProjectDiagnosticsParams) ([]*DiagnosticResponse, error) { + sd, err := s.getSnapshotData(params.Snapshot) + if err != nil { + return nil, err + } + + program, err := sd.getProgram(params.Project) + if err != nil { + return nil, err + } + + diags := program.GetProgramDiagnostics() + return NewDiagnosticResponses(diags), nil +} + +// handleGetGlobalDiagnostics returns global (non-file-specific) semantic diagnostics. +func (s *Session) handleGetGlobalDiagnostics(ctx context.Context, params *GetProjectDiagnosticsParams) ([]*DiagnosticResponse, error) { + ctx = core.WithCheckerLifetime(ctx, core.CheckerLifetimeDiagnostics) + sd, err := s.getSnapshotData(params.Snapshot) + if err != nil { + return nil, err + } + + proj, err := sd.getProject(params.Project) + if err != nil { + return nil, err + } + + program := proj.GetProgram() + if program == nil { + return nil, fmt.Errorf("%w: project has no program", ErrClientError) + } + + // Global diagnostics are accumulated lazily by the project's checker pool as + // files are checked. Force a full semantic pass so any global (non-file-specific) + // diagnostics are produced; otherwise this would return an empty result for + // projects using an external checker pool (the typical API case), since + // compiler.Program.GetGlobalDiagnostics only reports for the internal pool. + program.GetSemanticDiagnostics(ctx, nil) + + diags := core.Filter(proj.GetProjectDiagnostics(ctx), func(d *ast.Diagnostic) bool { + return d.File() == nil + }) + return NewDiagnosticResponses(diags), nil +} + // resolveOptionalSourceFile resolves an optional DocumentIdentifier to a source file. // Returns nil if the identifier is nil (meaning all files). func (s *Session) resolveOptionalSourceFile(program *compiler.Program, file *DocumentIdentifier) (*ast.SourceFile, error) { @@ -2462,6 +3188,9 @@ func (s *Session) handleGetSignatureUsages(ctx context.Context, params *GetSigna // handleGetCompletionsAtPosition returns completions at a position in a document. func (s *Session) handleGetCompletionsAtPosition(ctx context.Context, params *GetCompletionsAtPositionParams) (*CompletionInfoResponse, error) { + if params.IncludeSymbol { + ctx = core.WithCheckerLifetime(ctx, core.CheckerLifetimeAPI) + } sd, err := s.getSnapshotData(params.Snapshot) if err != nil { return nil, err @@ -2503,7 +3232,7 @@ func (s *Session) handleGetCompletionsAtPosition(ctx context.Context, params *Ge } } if item.Symbol != nil { - entry.Symbol = sd.newSymbolResponse(item.Symbol) + entry.Symbol = sd.newSymbolResponse(item.Symbol, params.Project) } entries = append(entries, entry) } @@ -2560,7 +3289,7 @@ func (s *Session) handleGetReferencedSymbolsForNode(ctx context.Context, params References: refs, } if sym := entry.DefinitionSymbol(); sym != nil { - re.Symbol = sd.newSymbolResponse(sym) + re.Symbol = sd.newSymbolResponse(sym, params.Project) } result = append(result, re) } diff --git a/internal/api/session_apistate_test.go b/internal/api/session_apistate_test.go new file mode 100644 index 00000000000..6dffbf12c5d --- /dev/null +++ b/internal/api/session_apistate_test.go @@ -0,0 +1,194 @@ +package api + +import ( + "context" + "testing" + + "github.com/microsoft/typescript-go/internal/bundled" + "github.com/microsoft/typescript-go/internal/testutil/projecttestutil" + "github.com/microsoft/typescript-go/internal/tspath" + "gotest.tools/v3/assert" +) + +// TestSessionTracksAndReleasesAPIRefs verifies that an API session holds at most +// one ref per opened project/file (opens are idempotent) and releases exactly +// those refs when the session is closed, so it never leaks or over-releases refs +// in the underlying (potentially shared) project session. +func TestSessionTracksAndReleasesAPIRefs(t *testing.T) { + t.Parallel() + if !bundled.Embedded { + t.Skip("bundled files are not embedded") + } + + t.Run("project opens are idempotent and released on close", func(t *testing.T) { + t.Parallel() + const configFileName = "/home/projects/p/tsconfig.json" + files := map[string]any{ + configFileName: `{ "compilerOptions": { "strict": true } }`, + "/home/projects/p/src/index.ts": `export const x = 1;`, + } + projectSession, _ := projecttestutil.Setup(files) + defer projectSession.Close() + session := NewSession(projectSession, nil) + + _, err := session.handleUpdateSnapshot(context.Background(), &UpdateSnapshotParams{ + OpenProjects: []DocumentIdentifier{{FileName: configFileName}}, + }) + assert.NilError(t, err) + assert.Equal(t, session.openProjects.Len(), 1) + + // Opening the same project again must not take an additional ref. + _, err = session.handleUpdateSnapshot(context.Background(), &UpdateSnapshotParams{ + OpenProjects: []DocumentIdentifier{{FileName: configFileName}}, + }) + assert.NilError(t, err) + assert.Equal(t, session.openProjects.Len(), 1) + + assert.Assert(t, projectSession.Snapshot().ProjectCollection.ConfiguredProject(tspath.Path(configFileName)) != nil) + + // Closing the session releases the single API ref, so the project is no + // longer kept loaded. + session.Close() + assert.Equal(t, session.openProjects.Len(), 0) + assert.Assert(t, projectSession.Snapshot().ProjectCollection.ConfiguredProject(tspath.Path(configFileName)) == nil) + }) + + t.Run("explicit close releases the project ref", func(t *testing.T) { + t.Parallel() + const configFileName = "/home/projects/p/tsconfig.json" + files := map[string]any{ + configFileName: `{ "compilerOptions": { "strict": true } }`, + "/home/projects/p/src/index.ts": `export const x = 1;`, + } + projectSession, _ := projecttestutil.Setup(files) + defer projectSession.Close() + session := NewSession(projectSession, nil) + defer session.Close() + + _, err := session.handleUpdateSnapshot(context.Background(), &UpdateSnapshotParams{ + OpenProjects: []DocumentIdentifier{{FileName: configFileName}}, + }) + assert.NilError(t, err) + assert.Equal(t, session.openProjects.Len(), 1) + assert.Assert(t, projectSession.Snapshot().ProjectCollection.ConfiguredProject(tspath.Path(configFileName)) != nil) + + // Closing a project we hold releases the ref and unloads the project. + _, err = session.handleUpdateSnapshot(context.Background(), &UpdateSnapshotParams{ + CloseProjects: []DocumentIdentifier{{FileName: configFileName}}, + }) + assert.NilError(t, err) + assert.Equal(t, session.openProjects.Len(), 0) + assert.Assert(t, projectSession.Snapshot().ProjectCollection.ConfiguredProject(tspath.Path(configFileName)) == nil) + + // Closing a project we don't hold is a no-op (never over-releases). + _, err = session.handleUpdateSnapshot(context.Background(), &UpdateSnapshotParams{ + CloseProjects: []DocumentIdentifier{{FileName: configFileName}}, + }) + assert.NilError(t, err) + assert.Equal(t, session.openProjects.Len(), 0) + }) + + t.Run("file opens are idempotent and released on close", func(t *testing.T) { + t.Parallel() + const fileName = "/home/projects/p/src/index.ts" + files := map[string]any{ + "/home/projects/p/tsconfig.json": `{ "compilerOptions": { "strict": true } }`, + fileName: `export const x = 1;`, + } + projectSession, _ := projecttestutil.Setup(files) + defer projectSession.Close() + session := NewSession(projectSession, nil) + + _, err := session.handleUpdateSnapshot(context.Background(), &UpdateSnapshotParams{ + OpenFiles: []DocumentIdentifier{{FileName: fileName}}, + }) + assert.NilError(t, err) + assert.Equal(t, session.openFiles.Len(), 1) + + // Re-opening the same file must not take an additional ref. + _, err = session.handleUpdateSnapshot(context.Background(), &UpdateSnapshotParams{ + OpenFiles: []DocumentIdentifier{{FileName: fileName}}, + }) + assert.NilError(t, err) + assert.Equal(t, session.openFiles.Len(), 1) + + // The file should resolve to the configured project via ancestor search. + assert.Assert(t, projectSession.Snapshot().ProjectCollection.ConfiguredProject(tspath.Path("/home/projects/p/tsconfig.json")) != nil) + + // Closing a file we don't hold is a no-op (never over-releases). + _, err = session.handleUpdateSnapshot(context.Background(), &UpdateSnapshotParams{ + CloseFiles: []DocumentIdentifier{{FileName: "/home/projects/p/other.ts"}}, + }) + assert.NilError(t, err) + assert.Equal(t, session.openFiles.Len(), 1) + + // Explicitly closing the held file releases the ref. + _, err = session.handleUpdateSnapshot(context.Background(), &UpdateSnapshotParams{ + CloseFiles: []DocumentIdentifier{{FileName: fileName}}, + }) + assert.NilError(t, err) + assert.Equal(t, session.openFiles.Len(), 0) + + // Closing the file also tears down the configured project that was + // auto-loaded to serve it, instead of leaking it. + assert.Assert(t, + projectSession.Snapshot().ProjectCollection.ConfiguredProject(tspath.Path("/home/projects/p/tsconfig.json")) == nil, + "configured project auto-loaded for the API-opened file should be unloaded after close", + ) + + session.Close() + assert.Equal(t, session.openFiles.Len(), 0) + }) + + t.Run("relative file paths normalize consistently for open and close", func(t *testing.T) { + t.Parallel() + // The project session's current directory is "/", so a relative path + // resolves to the corresponding absolute path. + files := map[string]any{ + "/src/tsconfig.json": `{ "compilerOptions": { "strict": true } }`, + "/src/index.ts": `export const x = 1;`, + } + projectSession, _ := projecttestutil.Setup(files) + defer projectSession.Close() + session := NewSession(projectSession, nil) + defer session.Close() + + // Open via a relative path; it should be tracked under the absolute path + // and resolve to the containing configured project. + openResp, err := session.handleUpdateSnapshot(context.Background(), &UpdateSnapshotParams{ + OpenFiles: []DocumentIdentifier{{FileName: "src/index.ts"}}, + }) + assert.NilError(t, err) + assert.Equal(t, session.openFiles.Len(), 1) + assert.Assert(t, session.openFiles.Has(tspath.Path("/src/index.ts"))) + assert.Assert(t, projectSession.Snapshot().ProjectCollection.ConfiguredProject(tspath.Path("/src/tsconfig.json")) != nil) + + // getDefaultProjectForFile must also resolve a relative path to the same + // configured project (it builds a URI from the identifier internally). + proj, err := session.handleGetDefaultProjectForFile(context.Background(), &GetDefaultProjectForFileParams{ + Snapshot: openResp.Snapshot, + File: DocumentIdentifier{FileName: "src/index.ts"}, + }) + assert.NilError(t, err) + assert.Assert(t, proj != nil, "relative path should resolve to a default project") + assert.Equal(t, proj.ConfigFileName, "/src/tsconfig.json") + + // Re-opening via the absolute path must match the relative open (no new ref). + _, err = session.handleUpdateSnapshot(context.Background(), &UpdateSnapshotParams{ + OpenFiles: []DocumentIdentifier{{FileName: "/src/index.ts"}}, + }) + assert.NilError(t, err) + assert.Equal(t, session.openFiles.Len(), 1) + + // Closing via a relative path must match the path stored when opening. + _, err = session.handleUpdateSnapshot(context.Background(), &UpdateSnapshotParams{ + CloseFiles: []DocumentIdentifier{{FileName: "src/index.ts"}}, + }) + assert.NilError(t, err) + assert.Equal(t, session.openFiles.Len(), 0) + assert.Assert(t, + projectSession.Snapshot().ProjectCollection.ConfiguredProject(tspath.Path("/src/tsconfig.json")) == nil, + "configured project should be unloaded after closing the relatively-pathed file", + ) + }) +} diff --git a/internal/api/session_completion_test.go b/internal/api/session_completion_test.go new file mode 100644 index 00000000000..3cd88f1a8cc --- /dev/null +++ b/internal/api/session_completion_test.go @@ -0,0 +1,89 @@ +package api + +import ( + "context" + "testing" + + "github.com/microsoft/typescript-go/internal/bundled" + "github.com/microsoft/typescript-go/internal/testutil/projecttestutil" + "gotest.tools/v3/assert" +) + +// TestCompletionSymbolTypeIsResolvable reproduces a crash where requesting the +// type of a completion-provided symbol panicked with a nil pointer dereference. +// +// Completion ran on an ephemeral query checker (default lifetime), so members of +// a generic type such as `string[]` (= Array) were returned as +// *instantiated* symbols whose per-checker instantiation links live only on that +// query checker. GetTypeOfSymbol runs on the persistent API checker — a +// different instance — where those links are absent, so getTypeOfInstantiatedSymbol +// dereferenced a nil target and brought down the connection. +// +// The fix pins symbol-producing completion to the API checker, so the returned +// handles resolve on the same checker the client re-queries. +func TestCompletionSymbolTypeIsResolvable(t *testing.T) { + t.Parallel() + if !bundled.Embedded { + t.Skip("bundled files are not embedded") + } + + const fileName = "/home/projects/p/src/index.ts" + // The caret sits right after `people.`, requesting members of `string[]`. + const content = "declare const people: string[];\npeople." + + files := map[string]any{ + "/home/projects/p/tsconfig.json": `{ "compilerOptions": { "strict": true } }`, + fileName: content, + } + projectSession, _ := projecttestutil.Setup(files) + defer projectSession.Close() + session := NewSession(projectSession, nil) + defer session.Close() + + ctx := context.Background() + + snapshotResp, err := session.handleUpdateSnapshot(ctx, &UpdateSnapshotParams{ + OpenFiles: []DocumentIdentifier{{FileName: fileName}}, + }) + assert.NilError(t, err) + + proj, err := session.handleGetDefaultProjectForFile(ctx, &GetDefaultProjectForFileParams{ + Snapshot: snapshotResp.Snapshot, + File: DocumentIdentifier{FileName: fileName}, + }) + assert.NilError(t, err) + assert.Assert(t, proj != nil, "file should resolve to a default project") + + // content is pure ASCII, so the UTF-16 caret offset equals the byte length. + completions, err := session.handleGetCompletionsAtPosition(ctx, &GetCompletionsAtPositionParams{ + Snapshot: snapshotResp.Snapshot, + Project: proj.Id, + File: DocumentIdentifier{FileName: fileName}, + Position: uint32(len(content)), + IncludeSymbol: true, + }) + assert.NilError(t, err) + assert.Assert(t, completions != nil, "expected a completion list for array members") + + // Resolving the type of every completion symbol must not panic, and known + // members like `push` must produce a concrete type. + var sawSymbol, sawPush bool + for _, entry := range completions.Entries { + if entry.Symbol == nil { + continue + } + sawSymbol = true + typeResp, err := session.handleGetTypeOfSymbol(ctx, &GetTypeOfSymbolParams{ + Snapshot: snapshotResp.Snapshot, + Project: proj.Id, + Symbol: entry.Symbol.Id, + }) + assert.NilError(t, err) + assert.Assert(t, typeResp != nil, "type of completion symbol %q should resolve", entry.Name) + if entry.Name == "push" { + sawPush = true + } + } + assert.Assert(t, sawSymbol, "completion entries should include resolvable symbols") + assert.Assert(t, sawPush, "array member completions should include `push`") +} diff --git a/internal/ast/ast.go b/internal/ast/ast.go index f4fd6dcde8a..6dcd606b57e 100644 --- a/internal/ast/ast.go +++ b/internal/ast/ast.go @@ -9,6 +9,7 @@ import ( "github.com/microsoft/typescript-go/internal/collections" "github.com/microsoft/typescript-go/internal/core" + "github.com/microsoft/typescript-go/internal/stringutil" "github.com/microsoft/typescript-go/internal/tspath" "github.com/zeebo/xxh3" ) @@ -188,11 +189,21 @@ type Node struct { // type switches. Either approach is fine. Interface methods are likely more performant, but have higher // code size costs because we have hundreds of implementations of the NodeData interface. -func (n *Node) AsNode() *Node { return n } -func (n *Node) Pos() int { return n.Loc.Pos() } -func (n *Node) End() int { return n.Loc.End() } -func (n *Node) ForEachChild(v Visitor) bool { return n.data.ForEachChild(v) } -func (n *Node) IterChildren() iter.Seq[*Node] { return n.data.IterChildren() } +func (n *Node) AsNode() *Node { return n } +func (n *Node) Pos() int { return n.Loc.Pos() } +func (n *Node) End() int { return n.Loc.End() } +func (n *Node) IterChildren() iter.Seq[*Node] { + // Implemented directly (rather than through the nodeData interface) so that the + // returned iterator and the visitor closure it passes to ForEachChild do not + // escape: an interface call is opaque to escape analysis. `true` stops a TS + // visitor early, whereas `false` stops a Go iterator yield, so the result is + // inverted. + return func(yield func(*Node) bool) { + n.ForEachChild(func(child *Node) bool { + return !yield(child) + }) + } +} func (n *Node) Clone(f NodeFactoryCoercible) *Node { return n.data.Clone(f) } func (n *Node) VisitEachChild(v *NodeVisitor) *Node { return n.data.VisitEachChild(v) } func (n *Node) Name() *DeclarationName { return n.data.Name() } @@ -1170,7 +1181,6 @@ func (n *Node) AsFlowReduceLabelData() *FlowReduceLabelData { type nodeData interface { AsNode() *Node ForEachChild(v Visitor) bool - IterChildren() iter.Seq[*Node] VisitEachChild(v *NodeVisitor) *Node Clone(v NodeFactoryCoercible) *Node Name() *DeclarationName @@ -1197,21 +1207,8 @@ type NodeDefault struct { Node } -func invert(yield func(v *Node) bool) Visitor { - return func(n *Node) bool { - return !yield(n) - } -} - func (node *NodeDefault) AsNode() *Node { return &node.Node } func (node *NodeDefault) ForEachChild(v Visitor) bool { return false } -func (node *NodeDefault) forEachChildIter(yield func(v *Node) bool) { - node.data.ForEachChild(invert(yield)) // `true` is return early for a ts visitor, `false` is return early for a go iterator yield function -} - -func (node *NodeDefault) IterChildren() iter.Seq[*Node] { - return node.forEachChildIter -} func (node *NodeDefault) VisitEachChild(v *NodeVisitor) *Node { return node.AsNode() } func (node *NodeDefault) Clone(v NodeFactoryCoercible) *Node { return nil } @@ -2554,6 +2551,7 @@ func (f *NodeFactory) NewSourceFile(opts SourceFileParseOptions, text string, st data.fileName = opts.FileName data.parseOptions = opts data.text = text + data.ContainsNonASCII = stringutil.ContainsNonASCII(text) data.Statements = statements data.EndOfFileToken = endOfFileToken return f.newNode(KindSourceFile, data) diff --git a/internal/ast/ast_generated.go b/internal/ast/ast_generated.go index 1b314eb4d2b..5bc11866374 100644 --- a/internal/ast/ast_generated.go +++ b/internal/ast/ast_generated.go @@ -8673,6 +8673,351 @@ func IsJSDocPropertyTag(node *Node) bool { return node.Kind == KindJSDocPropertyTag } +// ────────────────────────────────────────────────────────────────────── +// ForEachChild dispatch +// ────────────────────────────────────────────────────────────────────── + +func (n *Node) ForEachChild(v Visitor) bool { + switch n.Kind { + case KindQualifiedName: + return n.data.(*QualifiedName).ForEachChild(v) + case KindComputedPropertyName: + return n.data.(*ComputedPropertyName).ForEachChild(v) + case KindDecorator: + return n.data.(*Decorator).ForEachChild(v) + case KindIfStatement: + return n.data.(*IfStatement).ForEachChild(v) + case KindDoStatement: + return n.data.(*DoStatement).ForEachChild(v) + case KindWhileStatement: + return n.data.(*WhileStatement).ForEachChild(v) + case KindForStatement: + return n.data.(*ForStatement).ForEachChild(v) + case KindForInStatement, KindForOfStatement: + return n.data.(*ForInOrOfStatement).ForEachChild(v) + case KindBreakStatement: + return n.data.(*BreakStatement).ForEachChild(v) + case KindContinueStatement: + return n.data.(*ContinueStatement).ForEachChild(v) + case KindReturnStatement: + return n.data.(*ReturnStatement).ForEachChild(v) + case KindWithStatement: + return n.data.(*WithStatement).ForEachChild(v) + case KindSwitchStatement: + return n.data.(*SwitchStatement).ForEachChild(v) + case KindCaseBlock: + return n.data.(*CaseBlock).ForEachChild(v) + case KindCaseClause, KindDefaultClause: + return n.data.(*CaseOrDefaultClause).ForEachChild(v) + case KindThrowStatement: + return n.data.(*ThrowStatement).ForEachChild(v) + case KindTryStatement: + return n.data.(*TryStatement).ForEachChild(v) + case KindCatchClause: + return n.data.(*CatchClause).ForEachChild(v) + case KindLabeledStatement: + return n.data.(*LabeledStatement).ForEachChild(v) + case KindExpressionStatement: + return n.data.(*ExpressionStatement).ForEachChild(v) + case KindBlock: + return n.data.(*Block).ForEachChild(v) + case KindVariableStatement: + return n.data.(*VariableStatement).ForEachChild(v) + case KindVariableDeclaration: + return n.data.(*VariableDeclaration).ForEachChild(v) + case KindVariableDeclarationList: + return n.data.(*VariableDeclarationList).ForEachChild(v) + case KindObjectBindingPattern, KindArrayBindingPattern: + return n.data.(*BindingPattern).ForEachChild(v) + case KindParameter: + return n.data.(*ParameterDeclaration).ForEachChild(v) + case KindBindingElement: + return n.data.(*BindingElement).ForEachChild(v) + case KindMissingDeclaration: + return n.data.(*MissingDeclaration).ForEachChild(v) + case KindFunctionDeclaration: + return n.data.(*FunctionDeclaration).ForEachChild(v) + case KindClassDeclaration: + return n.data.(*ClassDeclaration).ForEachChild(v) + case KindClassExpression: + return n.data.(*ClassExpression).ForEachChild(v) + case KindHeritageClause: + return n.data.(*HeritageClause).ForEachChild(v) + case KindInterfaceDeclaration: + return n.data.(*InterfaceDeclaration).ForEachChild(v) + case KindTypeAliasDeclaration, KindJSTypeAliasDeclaration: + return n.data.(*TypeAliasDeclaration).ForEachChild(v) + case KindEnumMember: + return n.data.(*EnumMember).ForEachChild(v) + case KindEnumDeclaration: + return n.data.(*EnumDeclaration).ForEachChild(v) + case KindModuleBlock: + return n.data.(*ModuleBlock).ForEachChild(v) + case KindImportDeclaration, KindJSImportDeclaration: + return n.data.(*ImportDeclaration).ForEachChild(v) + case KindExternalModuleReference: + return n.data.(*ExternalModuleReference).ForEachChild(v) + case KindNamespaceImport: + return n.data.(*NamespaceImport).ForEachChild(v) + case KindNamedImports: + return n.data.(*NamedImports).ForEachChild(v) + case KindExportAssignment: + return n.data.(*ExportAssignment).ForEachChild(v) + case KindNamespaceExportDeclaration: + return n.data.(*NamespaceExportDeclaration).ForEachChild(v) + case KindNamespaceExport: + return n.data.(*NamespaceExport).ForEachChild(v) + case KindNamedExports: + return n.data.(*NamedExports).ForEachChild(v) + case KindExportSpecifier: + return n.data.(*ExportSpecifier).ForEachChild(v) + case KindCallSignature: + return n.data.(*CallSignatureDeclaration).ForEachChild(v) + case KindConstructSignature: + return n.data.(*ConstructSignatureDeclaration).ForEachChild(v) + case KindConstructor: + return n.data.(*ConstructorDeclaration).ForEachChild(v) + case KindGetAccessor: + return n.data.(*GetAccessorDeclaration).ForEachChild(v) + case KindSetAccessor: + return n.data.(*SetAccessorDeclaration).ForEachChild(v) + case KindIndexSignature: + return n.data.(*IndexSignatureDeclaration).ForEachChild(v) + case KindMethodSignature: + return n.data.(*MethodSignatureDeclaration).ForEachChild(v) + case KindMethodDeclaration: + return n.data.(*MethodDeclaration).ForEachChild(v) + case KindPropertySignature: + return n.data.(*PropertySignatureDeclaration).ForEachChild(v) + case KindPropertyDeclaration: + return n.data.(*PropertyDeclaration).ForEachChild(v) + case KindClassStaticBlockDeclaration: + return n.data.(*ClassStaticBlockDeclaration).ForEachChild(v) + case KindBinaryExpression: + return n.data.(*BinaryExpression).ForEachChild(v) + case KindPrefixUnaryExpression: + return n.data.(*PrefixUnaryExpression).ForEachChild(v) + case KindPostfixUnaryExpression: + return n.data.(*PostfixUnaryExpression).ForEachChild(v) + case KindYieldExpression: + return n.data.(*YieldExpression).ForEachChild(v) + case KindArrowFunction: + return n.data.(*ArrowFunction).ForEachChild(v) + case KindFunctionExpression: + return n.data.(*FunctionExpression).ForEachChild(v) + case KindAsExpression: + return n.data.(*AsExpression).ForEachChild(v) + case KindSatisfiesExpression: + return n.data.(*SatisfiesExpression).ForEachChild(v) + case KindConditionalExpression: + return n.data.(*ConditionalExpression).ForEachChild(v) + case KindPropertyAccessExpression: + return n.data.(*PropertyAccessExpression).ForEachChild(v) + case KindElementAccessExpression: + return n.data.(*ElementAccessExpression).ForEachChild(v) + case KindCallExpression: + return n.data.(*CallExpression).ForEachChild(v) + case KindNewExpression: + return n.data.(*NewExpression).ForEachChild(v) + case KindMetaProperty: + return n.data.(*MetaProperty).ForEachChild(v) + case KindNonNullExpression: + return n.data.(*NonNullExpression).ForEachChild(v) + case KindSpreadElement: + return n.data.(*SpreadElement).ForEachChild(v) + case KindTemplateExpression: + return n.data.(*TemplateExpression).ForEachChild(v) + case KindTemplateSpan: + return n.data.(*TemplateSpan).ForEachChild(v) + case KindTaggedTemplateExpression: + return n.data.(*TaggedTemplateExpression).ForEachChild(v) + case KindParenthesizedExpression: + return n.data.(*ParenthesizedExpression).ForEachChild(v) + case KindArrayLiteralExpression: + return n.data.(*ArrayLiteralExpression).ForEachChild(v) + case KindObjectLiteralExpression: + return n.data.(*ObjectLiteralExpression).ForEachChild(v) + case KindSpreadAssignment: + return n.data.(*SpreadAssignment).ForEachChild(v) + case KindPropertyAssignment: + return n.data.(*PropertyAssignment).ForEachChild(v) + case KindShorthandPropertyAssignment: + return n.data.(*ShorthandPropertyAssignment).ForEachChild(v) + case KindDeleteExpression: + return n.data.(*DeleteExpression).ForEachChild(v) + case KindTypeOfExpression: + return n.data.(*TypeOfExpression).ForEachChild(v) + case KindVoidExpression: + return n.data.(*VoidExpression).ForEachChild(v) + case KindAwaitExpression: + return n.data.(*AwaitExpression).ForEachChild(v) + case KindTypeAssertionExpression: + return n.data.(*TypeAssertion).ForEachChild(v) + case KindUnionType: + return n.data.(*UnionTypeNode).ForEachChild(v) + case KindIntersectionType: + return n.data.(*IntersectionTypeNode).ForEachChild(v) + case KindConditionalType: + return n.data.(*ConditionalTypeNode).ForEachChild(v) + case KindTypeOperator: + return n.data.(*TypeOperatorNode).ForEachChild(v) + case KindInferType: + return n.data.(*InferTypeNode).ForEachChild(v) + case KindArrayType: + return n.data.(*ArrayTypeNode).ForEachChild(v) + case KindIndexedAccessType: + return n.data.(*IndexedAccessTypeNode).ForEachChild(v) + case KindTypeReference: + return n.data.(*TypeReferenceNode).ForEachChild(v) + case KindExpressionWithTypeArguments: + return n.data.(*ExpressionWithTypeArguments).ForEachChild(v) + case KindLiteralType: + return n.data.(*LiteralTypeNode).ForEachChild(v) + case KindTypePredicate: + return n.data.(*TypePredicateNode).ForEachChild(v) + case KindImportAttribute: + return n.data.(*ImportAttribute).ForEachChild(v) + case KindImportAttributes: + return n.data.(*ImportAttributes).ForEachChild(v) + case KindTypeQuery: + return n.data.(*TypeQueryNode).ForEachChild(v) + case KindMappedType: + return n.data.(*MappedTypeNode).ForEachChild(v) + case KindTypeLiteral: + return n.data.(*TypeLiteralNode).ForEachChild(v) + case KindTupleType: + return n.data.(*TupleTypeNode).ForEachChild(v) + case KindNamedTupleMember: + return n.data.(*NamedTupleMember).ForEachChild(v) + case KindOptionalType: + return n.data.(*OptionalTypeNode).ForEachChild(v) + case KindRestType: + return n.data.(*RestTypeNode).ForEachChild(v) + case KindParenthesizedType: + return n.data.(*ParenthesizedTypeNode).ForEachChild(v) + case KindFunctionType: + return n.data.(*FunctionTypeNode).ForEachChild(v) + case KindConstructorType: + return n.data.(*ConstructorTypeNode).ForEachChild(v) + case KindTemplateLiteralType: + return n.data.(*TemplateLiteralTypeNode).ForEachChild(v) + case KindTemplateLiteralTypeSpan: + return n.data.(*TemplateLiteralTypeSpan).ForEachChild(v) + case KindSyntheticExpression: + return n.data.(*SyntheticExpression).ForEachChild(v) + case KindPartiallyEmittedExpression: + return n.data.(*PartiallyEmittedExpression).ForEachChild(v) + case KindJsxElement: + return n.data.(*JsxElement).ForEachChild(v) + case KindJsxAttributes: + return n.data.(*JsxAttributes).ForEachChild(v) + case KindJsxNamespacedName: + return n.data.(*JsxNamespacedName).ForEachChild(v) + case KindJsxOpeningElement: + return n.data.(*JsxOpeningElement).ForEachChild(v) + case KindJsxSelfClosingElement: + return n.data.(*JsxSelfClosingElement).ForEachChild(v) + case KindJsxFragment: + return n.data.(*JsxFragment).ForEachChild(v) + case KindJsxAttribute: + return n.data.(*JsxAttribute).ForEachChild(v) + case KindJsxSpreadAttribute: + return n.data.(*JsxSpreadAttribute).ForEachChild(v) + case KindJsxClosingElement: + return n.data.(*JsxClosingElement).ForEachChild(v) + case KindJsxExpression: + return n.data.(*JsxExpression).ForEachChild(v) + case KindSyntaxList: + return n.data.(*SyntaxList).ForEachChild(v) + case KindJSDoc: + return n.data.(*JSDoc).ForEachChild(v) + case KindJSDocTypeExpression: + return n.data.(*JSDocTypeExpression).ForEachChild(v) + case KindJSDocNonNullableType: + return n.data.(*JSDocNonNullableType).ForEachChild(v) + case KindJSDocNullableType: + return n.data.(*JSDocNullableType).ForEachChild(v) + case KindJSDocVariadicType: + return n.data.(*JSDocVariadicType).ForEachChild(v) + case KindJSDocOptionalType: + return n.data.(*JSDocOptionalType).ForEachChild(v) + case KindJSDocTypeTag: + return n.data.(*JSDocTypeTag).ForEachChild(v) + case KindJSDocUnknownTag: + return n.data.(*JSDocUnknownTag).ForEachChild(v) + case KindJSDocTemplateTag: + return n.data.(*JSDocTemplateTag).ForEachChild(v) + case KindJSDocReturnTag: + return n.data.(*JSDocReturnTag).ForEachChild(v) + case KindJSDocPublicTag: + return n.data.(*JSDocPublicTag).ForEachChild(v) + case KindJSDocPrivateTag: + return n.data.(*JSDocPrivateTag).ForEachChild(v) + case KindJSDocProtectedTag: + return n.data.(*JSDocProtectedTag).ForEachChild(v) + case KindJSDocReadonlyTag: + return n.data.(*JSDocReadonlyTag).ForEachChild(v) + case KindJSDocOverrideTag: + return n.data.(*JSDocOverrideTag).ForEachChild(v) + case KindJSDocDeprecatedTag: + return n.data.(*JSDocDeprecatedTag).ForEachChild(v) + case KindJSDocSeeTag: + return n.data.(*JSDocSeeTag).ForEachChild(v) + case KindJSDocImplementsTag: + return n.data.(*JSDocImplementsTag).ForEachChild(v) + case KindJSDocAugmentsTag: + return n.data.(*JSDocAugmentsTag).ForEachChild(v) + case KindJSDocSatisfiesTag: + return n.data.(*JSDocSatisfiesTag).ForEachChild(v) + case KindJSDocThrowsTag: + return n.data.(*JSDocThrowsTag).ForEachChild(v) + case KindJSDocThisTag: + return n.data.(*JSDocThisTag).ForEachChild(v) + case KindJSDocImportTag: + return n.data.(*JSDocImportTag).ForEachChild(v) + case KindJSDocCallbackTag: + return n.data.(*JSDocCallbackTag).ForEachChild(v) + case KindJSDocOverloadTag: + return n.data.(*JSDocOverloadTag).ForEachChild(v) + case KindJSDocTypedefTag: + return n.data.(*JSDocTypedefTag).ForEachChild(v) + case KindJSDocSignature: + return n.data.(*JSDocSignature).ForEachChild(v) + case KindJSDocNameReference: + return n.data.(*JSDocNameReference).ForEachChild(v) + case KindSourceFile: + return n.data.(*SourceFile).ForEachChild(v) + case KindModuleDeclaration: + return n.data.(*ModuleDeclaration).ForEachChild(v) + case KindImportEqualsDeclaration: + return n.data.(*ImportEqualsDeclaration).ForEachChild(v) + case KindExportDeclaration: + return n.data.(*ExportDeclaration).ForEachChild(v) + case KindImportType: + return n.data.(*ImportTypeNode).ForEachChild(v) + case KindImportClause: + return n.data.(*ImportClause).ForEachChild(v) + case KindImportSpecifier: + return n.data.(*ImportSpecifier).ForEachChild(v) + case KindJSDocLink: + return n.data.(*JSDocLink).ForEachChild(v) + case KindJSDocLinkPlain: + return n.data.(*JSDocLinkPlain).ForEachChild(v) + case KindJSDocLinkCode: + return n.data.(*JSDocLinkCode).ForEachChild(v) + case KindTypeParameter: + return n.data.(*TypeParameterDeclaration).ForEachChild(v) + case KindSyntheticReferenceExpression: + return n.data.(*SyntheticReferenceExpression).ForEachChild(v) + case KindJSDocTypeLiteral: + return n.data.(*JSDocTypeLiteral).ForEachChild(v) + case KindJSDocParameterTag, KindJSDocPropertyTag: + return n.data.(*JSDocParameterOrPropertyTag).ForEachChild(v) + default: + return false + } +} + // ────────────────────────────────────────────────────────────────────── // As*() cast methods // ────────────────────────────────────────────────────────────────────── diff --git a/internal/ast/positionmap.go b/internal/ast/positionmap.go index 6d84a0e983f..a7e6e807b92 100644 --- a/internal/ast/positionmap.go +++ b/internal/ast/positionmap.go @@ -2,6 +2,8 @@ package ast import ( "unicode/utf8" + + "github.com/microsoft/typescript-go/internal/stringutil" ) // PositionMap provides bidirectional mapping between UTF-8 byte offsets (used by Go) @@ -44,7 +46,7 @@ func ComputePositionMap(text string) *PositionMap { i++ continue } - r, size := utf8.DecodeRuneInString(text[i:]) + r, size := stringutil.DecodeJSStringRune(text[i:]) utf16Size := 1 if r >= 0x10000 { utf16Size = 2 diff --git a/internal/ast/positionmap_test.go b/internal/ast/positionmap_test.go index 2f7a5353d1e..f496f367d78 100644 --- a/internal/ast/positionmap_test.go +++ b/internal/ast/positionmap_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/microsoft/typescript-go/internal/ast" + "github.com/microsoft/typescript-go/internal/stringutil" ) func TestPositionMapASCII(t *testing.T) { @@ -119,6 +120,22 @@ func TestPositionMapMultipleNonASCII(t *testing.T) { } } +func TestPositionMapLoneSurrogateSentinel(t *testing.T) { + t.Parallel() + text := "a" + stringutil.EncodeJSStringRune(0xD800) + "b" + pm := ast.ComputePositionMap(text) + if pm.IsAsciiOnly() { + t.Fatal("expected non-ASCII") + } + + if got := pm.UTF8ToUTF16(len(text)); got != 3 { + t.Errorf("UTF8ToUTF16(%d) = %d, want 3", len(text), got) + } + if got := pm.UTF16ToUTF8(2); got != len(text)-1 { + t.Errorf("UTF16ToUTF8(2) = %d, want %d", got, len(text)-1) + } +} + func TestPositionMapRoundtrip(t *testing.T) { t.Parallel() text := "let café = \"🎉\"; // naïve" diff --git a/internal/ast/symbol.go b/internal/ast/symbol.go index f9e0b253611..f4ffd566ea9 100644 --- a/internal/ast/symbol.go +++ b/internal/ast/symbol.go @@ -80,3 +80,24 @@ func SymbolName(symbol *Symbol) string { func EscapeAllInternalSymbolNames(name string) string { return strings.ReplaceAll(name, InternalSymbolNamePrefix, "__") } + +func EscapeInternalSymbolName(name string) string { + if rest, ok := strings.CutPrefix(name, InternalSymbolNamePrefix); ok { + return "__" + rest + } + return name +} + +// EscapeSymbolName converts a binder symbol name into its escaped "__String" +// form. Internal names (prefixed with the "\xFE" sentinel) become "__"-prefixed, +// and user names that already begin with "__" gain an extra leading underscore +// so they can be distinguished from internal names. +func EscapeSymbolName(name string) string { + if rest, ok := strings.CutPrefix(name, InternalSymbolNamePrefix); ok { + return "__" + rest + } + if len(name) >= 2 && name[0] == '_' && name[1] == '_' { + return "_" + name + } + return name +} diff --git a/internal/bundled/libs/lib.es2015.collection.d.ts b/internal/bundled/libs/lib.es2015.collection.d.ts index f495e095e29..225e918b764 100644 --- a/internal/bundled/libs/lib.es2015.collection.d.ts +++ b/internal/bundled/libs/lib.es2015.collection.d.ts @@ -110,7 +110,7 @@ interface Set { */ has(value: T): boolean; /** - * @returns the number of (unique) elements in Set. + * @returns the number of (unique) elements in the Set. */ readonly size: number; } @@ -122,8 +122,17 @@ interface SetConstructor { declare var Set: SetConstructor; interface ReadonlySet { + /** + * Executes a provided function once per each value in the ReadonlySet object, in insertion order. + */ forEach(callbackfn: (value: T, value2: T, set: ReadonlySet) => void, thisArg?: any): void; + /** + * @returns a boolean indicating whether an element with the specified value exists in the Set or not. + */ has(value: T): boolean; + /** + * @returns the number of (unique) elements in the Set. + */ readonly size: number; } diff --git a/internal/bundled/libs/lib.es2015.core.d.ts b/internal/bundled/libs/lib.es2015.core.d.ts index 7e3609dd818..e36b9fbdadd 100644 --- a/internal/bundled/libs/lib.es2015.core.d.ts +++ b/internal/bundled/libs/lib.es2015.core.d.ts @@ -110,7 +110,7 @@ interface Math { imul(x: number, y: number): number; /** - * Returns the sign of the x, indicating whether x is positive, negative or zero. + * Returns the sign of x, indicating whether x is positive, negative, or zero. * @param x The numeric expression to test */ sign(x: number): number; diff --git a/internal/bundled/libs/lib.es2015.symbol.d.ts b/internal/bundled/libs/lib.es2015.symbol.d.ts index 3f36d324307..b2ba22dba66 100644 --- a/internal/bundled/libs/lib.es2015.symbol.d.ts +++ b/internal/bundled/libs/lib.es2015.symbol.d.ts @@ -35,7 +35,7 @@ interface SymbolConstructor { /** * Returns a key from the global symbol registry matching the given Symbol if found. - * Otherwise, returns a undefined. + * Otherwise, returns undefined. * @param sym Symbol to find the key for. */ keyFor(sym: symbol): string | undefined; diff --git a/internal/bundled/libs/lib.es2017.string.d.ts b/internal/bundled/libs/lib.es2017.string.d.ts index dd1c5d28567..6d7f89ee98e 100644 --- a/internal/bundled/libs/lib.es2017.string.d.ts +++ b/internal/bundled/libs/lib.es2017.string.d.ts @@ -16,28 +16,32 @@ and limitations under the License. interface String { /** - * Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. - * The padding is applied from the start (left) of the current string. + * Pads the current string with a given string (repeated and/or truncated, if needed) so that the resulting string has a given length. + * The padding is applied from the start of the current string. * - * @param maxLength The length of the resulting string once the current string has been padded. - * If this parameter is smaller than the current string's length, the current string will be returned as it is. + * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart) * - * @param fillString The string to pad the current string with. - * If this string is too long, it will be truncated and the left-most part will be applied. - * The default value for this parameter is " " (U+0020). + * @param targetLength The length of the resulting string once the current `str` has been padded. + * If the value is less than or equal to `str.length`, then `str` is returned as-is. + * + * @param padString The string to pad the current `str` with. + * If `padString` is too long to stay within `targetLength`, it will be truncated from the end. + * The default value is the space character (U+0020). */ - padStart(maxLength: number, fillString?: string): string; + padStart(targetLength: number, padString?: string): string; /** - * Pads the current string with a given string (possibly repeated) so that the resulting string reaches a given length. - * The padding is applied from the end (right) of the current string. + * Pads the current string with a given string (repeated and/or truncated, if needed) so that the resulting string has a given length. + * The padding is applied from the end of the current string. + * + * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd) * - * @param maxLength The length of the resulting string once the current string has been padded. - * If this parameter is smaller than the current string's length, the current string will be returned as it is. + * @param targetLength The length of the resulting string once the current `str` has been padded. + * If the value is less than or equal to `str.length`, then `str` is returned as-is. * - * @param fillString The string to pad the current string with. - * If this string is too long, it will be truncated and the left-most part will be applied. - * The default value for this parameter is " " (U+0020). + * @param padString The string to pad the current `str` with. + * If `padString` is too long to stay within `targetLength`, it will be truncated from the end. + * The default value is the space character (U+0020). */ - padEnd(maxLength: number, fillString?: string): string; + padEnd(targetLength: number, padString?: string): string; } diff --git a/internal/bundled/libs/lib.es2020.intl.d.ts b/internal/bundled/libs/lib.es2020.intl.d.ts index 055c63b70ca..e6ce42620fb 100644 --- a/internal/bundled/libs/lib.es2020.intl.d.ts +++ b/internal/bundled/libs/lib.es2020.intl.d.ts @@ -169,15 +169,15 @@ declare namespace Intl { format(value: number, unit: RelativeTimeFormatUnit): string; /** - * Returns an array of objects representing the relative time format in parts that can be used for custom locale-aware formatting. + * Returns an array of objects representing the relative time format in parts that can be used for custom locale-aware formatting. * - * @param value - Numeric value to use in the internationalized relative time message + * @param value - Numeric value to use in the internationalized relative time message * - * @param unit - [Unit](https://tc39.es/ecma402/#sec-singularrelativetimeunit) to use in the relative time internationalized message. + * @param unit - [Unit](https://tc39.es/ecma402/#sec-singularrelativetimeunit) to use in the relative time internationalized message. * - * @throws `RangeError` if `unit` was given something other than `unit` possible values + * @throws `RangeError` if `unit` was given something other than `unit` possible values * - * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts). + * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts). */ formatToParts(value: number, unit: RelativeTimeFormatUnit): RelativeTimeFormatPart[]; diff --git a/internal/bundled/libs/lib.es5.d.ts b/internal/bundled/libs/lib.es5.d.ts index 496166ca309..e394111cb0e 100644 --- a/internal/bundled/libs/lib.es5.d.ts +++ b/internal/bundled/libs/lib.es5.d.ts @@ -416,8 +416,8 @@ interface String { charAt(pos: number): string; /** - * Returns the Unicode value of the character at the specified location. - * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. + * Returns the Unicode value of the character at the specified location, or NaN if the index is out of bounds. + * @param index The zero-based index of the desired character. */ charCodeAt(index: number): number; @@ -563,19 +563,19 @@ interface Number { /** * Returns a string representing a number in fixed-point notation. - * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 100, inclusive. */ toFixed(fractionDigits?: number): string; /** * Returns a string containing a number represented in exponential notation. - * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 100, inclusive. */ toExponential(fractionDigits?: number): string; /** * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. - * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. + * @param precision Number of significant digits. Must be in the range 1 - 100, inclusive. */ toPrecision(precision?: number): string; diff --git a/internal/checker/checker.go b/internal/checker/checker.go index a8223d2bac9..34848d64637 100644 --- a/internal/checker/checker.go +++ b/internal/checker/checker.go @@ -287,7 +287,8 @@ type InferenceContext struct { type InferenceInfo struct { typeParameter *Type // Type parameter for which inferences are being made - candidates []*Type // Candidates in covariant positions + candidates []*Type // Candidates in covariant positions in decreasing depth order + candidateDepths []int // Type argument depths of covariant inferences contraCandidates []*Type // Candidates in contravariant positions inferredType *Type // Cache for resolved inferred type priority InferencePriority // Priority of current inference set @@ -590,6 +591,7 @@ type Checker struct { TotalInstantiationCount uint32 instantiationCount uint32 instantiationDepth uint32 + conditionalConstraintDepth uint32 inlineLevel int serializationLevel int currentNode *ast.Node @@ -14091,7 +14093,11 @@ func (c *Checker) mergeSymbol(target *ast.Symbol, source *ast.Symbol, unidirecti // reset flag when merging instantiated module into value module that has only const enums target.Flags &^= ast.SymbolFlagsConstEnumOnlyModule } - target.Flags |= source.Flags + sourceFlags := source.Flags + if target.Flags&ast.SymbolFlagsConstEnumOnlyModule == 0 { + sourceFlags &^= ast.SymbolFlagsConstEnumOnlyModule + } + target.Flags |= sourceFlags if source.ValueDeclaration != nil { binder.SetValueDeclaration(target, source.ValueDeclaration) } @@ -19064,7 +19070,7 @@ func findIndexInfo(indexInfos []*IndexInfo, keyType *Type) *IndexInfo { } func (c *Checker) getBaseTypes(t *Type) []*Type { - if t.objectFlags&(ObjectFlagsClassOrInterface|ObjectFlagsReference) == 0 { + if t.objectFlags&(ObjectFlagsClassOrInterface|ObjectFlagsTuple) == 0 { return nil } data := t.AsInterfaceType() @@ -27420,20 +27426,13 @@ func (c *Checker) computeBaseConstraint(t *Type, stack []RecursionId) *Type { } return c.getNextBaseConstraint(c.getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, t.AsIndexedAccessType().accessFlags, nil, nil), stack) case t.flags&TypeFlagsConditional != 0: - d := t.AsConditionalType() - if d.root.isDistributive && c.cachedTypes[CachedTypeKey{kind: CachedTypeKindRestrictiveInstantiation, typeId: t.id}] != t { - constraint := c.getSimplifiedType(d.checkType, false /*writing*/) - if constraint == d.checkType { - constraint = c.getNextBaseConstraint(constraint, stack) - } - if constraint != nil && constraint != d.checkType { - instantiated := c.getConditionalTypeInstantiation(t, prependTypeMapping(d.root.checkType, constraint, d.mapper), true /*forConstraint*/, nil) - if instantiated.flags&TypeFlagsNever == 0 { - return c.getNextBaseConstraint(instantiated, stack) - } - } + if c.conditionalConstraintDepth >= 100 { + return nil } - return c.getNextBaseConstraint(c.getDefaultConstraintOfConditionalType(t), stack) + c.conditionalConstraintDepth++ + constraint := c.getConstraintFromConditionalType(t) + c.conditionalConstraintDepth-- + return c.getNextBaseConstraint(constraint, stack) case t.flags&TypeFlagsSubstitution != 0: return c.getNextBaseConstraint(c.getSubstitutionIntersection(t), stack) case c.isGenericTupleType(t): diff --git a/internal/checker/emitresolver.go b/internal/checker/emitresolver.go index 7bf3719e58f..f5b68e1434f 100644 --- a/internal/checker/emitresolver.go +++ b/internal/checker/emitresolver.go @@ -1270,9 +1270,20 @@ func (r *EmitResolver) TryJSTypeNodeToTypeNode(emitContext *printer.EmitContext, return requestNodeBuilder.TryJSTypeNodeToTypeNode(typeNode, enclosingDeclaration, flags, internalFlags, tracker) } -func (r *EmitResolver) GetBaseDeclarationsForPropertyDeclaration(node *ast.Node) []*ast.Node { +// IsThisPropertyAssignmentDeclarationRedundant reports whether a JS `this. = ...` expando +// assignment should be omitted from declaration emit because the member it would synthesize is +// already provided by an `extends` base type. This mirrors the skip condition in the checker's +// serializePropertySymbol: an inherited member is redundant when it is identical to the assigned +// one (same readonly-ness, optionality and type). Inherited accessors and methods are always +// treated as redundant here, since accessors merge oddly with value assignments (and run via the +// accessor at runtime), and `this`-expando props carry the ReplaceableByMethod contract, so a +// rebind such as `this.method = this.method.bind(this)` must not override the base method. +// +// Only `extends` base types are considered. Members coming from `implements` clauses are not +// inherited, so the class must redeclare them, and they are always emitted. +func (r *EmitResolver) IsThisPropertyAssignmentDeclarationRedundant(node *ast.Node) bool { if node == nil { - return nil + return false } r.checkerMu.Lock() @@ -1280,19 +1291,25 @@ func (r *EmitResolver) GetBaseDeclarationsForPropertyDeclaration(node *ast.Node) s := r.checker.getSymbolOfDeclaration(node) if s == nil || s.Parent == nil { - return nil + return false } parentType := r.checker.getDeclaredTypeOfSymbol(s.Parent) if parentType == nil { - return nil + return false } - bases := r.checker.getBaseTypes(parentType) - for _, b := range bases { - baseProp := r.checker.getPropertyOfObjectType(b, s.Name) - if baseProp != nil { - return baseProp.Declarations - // TODO: return base declarations from all base types if any callers actually look at the list + for _, base := range r.checker.getBaseTypes(parentType) { + baseProp := r.checker.getPropertyOfType(base, s.Name) + if baseProp == nil { + continue + } + if baseProp.Flags&(ast.SymbolFlagsAccessor|ast.SymbolFlagsMethod|ast.SymbolFlagsFunction) != 0 { + return true + } + if r.checker.isReadonlySymbol(baseProp) == r.checker.isReadonlySymbol(s) && + (s.Flags&ast.SymbolFlagsOptional) == (baseProp.Flags&ast.SymbolFlagsOptional) && + r.checker.isTypeIdenticalTo(r.checker.getTypeOfSymbol(s), r.checker.getTypeOfSymbol(baseProp)) { + return true } } - return nil + return false } diff --git a/internal/checker/exports.go b/internal/checker/exports.go index 516f5f149b6..90162bdaeb6 100644 --- a/internal/checker/exports.go +++ b/internal/checker/exports.go @@ -62,6 +62,14 @@ func (c *Checker) GetUnknownSymbol() *ast.Symbol { return c.unknownSymbol } +func (c *Checker) GetUndefinedSymbol() *ast.Symbol { + return c.undefinedSymbol +} + +func (c *Checker) GetArgumentsSymbol() *ast.Symbol { + return c.argumentsSymbol +} + func (c *Checker) GetUnionType(types []*Type) *Type { return c.getUnionType(types) } @@ -169,6 +177,14 @@ func (c *Checker) GetConstraintOfTypeParameter(typeParameter *Type) *Type { return c.getConstraintOfTypeParameter(typeParameter) } +func (c *Checker) GetTrueTypeOfConditionalType(t *Type) *Type { + return c.getTrueTypeFromConditionalType(t) +} + +func (c *Checker) GetFalseTypeOfConditionalType(t *Type) *Type { + return c.getFalseTypeFromConditionalType(t) +} + func (c *Checker) GetDefaultFromTypeParameter(typeParameter *Type) *Type { return c.getDefaultFromTypeParameter(typeParameter) } @@ -193,6 +209,10 @@ func IsTupleType(t *Type) bool { return isTupleType(t) } +func (c *Checker) IsArrayType(t *Type) bool { + return c.isArrayType(t) +} + func (c *Checker) GetReturnTypeOfSignature(sig *Signature) *Type { return c.getReturnTypeOfSignature(sig) } @@ -329,3 +349,7 @@ func (c *Checker) RemoveMissingOrUndefinedType(t *Type) *Type { func (c *Checker) GetWidenedType(t *Type) *Type { return c.getWidenedType(t) } + +func (c *Checker) CompareSymbols(s1, s2 *ast.Symbol) int { + return c.compareSymbols(s1, s2) +} diff --git a/internal/checker/inference.go b/internal/checker/inference.go index fb5da8b8226..21af42387da 100644 --- a/internal/checker/inference.go +++ b/internal/checker/inference.go @@ -27,6 +27,7 @@ type InferenceState struct { sourceStack []*Type targetStack []*Type next *InferenceState + depth int } func (c *Checker) getInferenceState() *InferenceState { @@ -187,6 +188,7 @@ func (c *Checker) inferFromTypes(n *InferenceState, source *Type, target *Type) } if n.priority < inference.priority { inference.candidates = nil + inference.candidateDepths = nil inference.contraCandidates = nil inference.topLevel = true inference.priority = n.priority @@ -199,9 +201,28 @@ func (c *Checker) inferFromTypes(n *InferenceState, source *Type, target *Type) inference.contraCandidates = append(inference.contraCandidates, candidate) clearCachedInferences(n.inferences) } - } else if !slices.Contains(inference.candidates, candidate) { - inference.candidates = append(inference.candidates, candidate) - clearCachedInferences(n.inferences) + } else { + index := slices.Index(inference.candidates, candidate) + if index < 0 || inference.candidateDepths[index] < n.depth { + // Candidate isn't present or is present with lower depth + if index >= 0 { + // Remove candidate with lower depth + inference.candidates = slices.Delete(inference.candidates, index, index+1) + inference.candidateDepths = slices.Delete(inference.candidateDepths, index, index+1) + } + index = 0 + for index < len(inference.candidateDepths) { + if inference.candidateDepths[index] < n.depth { + break + } + index++ + } + // Insert candidate at end or immediately before first candidate with lower depth. + // This ensures candidates with the highest depth are stored first. + inference.candidates = slices.Insert(inference.candidates, index, candidate) + inference.candidateDepths = slices.Insert(inference.candidateDepths, index, n.depth) + clearCachedInferences(n.inferences) + } } } if n.priority&InferencePriorityReturnType == 0 && target.flags&TypeFlagsTypeParameter != 0 && inference.topLevel && !c.isTypeParameterAtTopLevel(n.originalTarget, target, 0) { @@ -282,6 +303,7 @@ func (c *Checker) inferFromTypes(n *InferenceState, source *Type, target *Type) } func (c *Checker) inferFromTypeArguments(n *InferenceState, sourceTypes []*Type, targetTypes []*Type, variances []VarianceFlags) { + n.depth++ for i := range min(len(sourceTypes), len(targetTypes)) { if i < len(variances) && variances[i]&VarianceFlagsVarianceMask == VarianceFlagsContravariant { c.inferFromContravariantTypes(n, sourceTypes[i], targetTypes[i]) @@ -289,6 +311,7 @@ func (c *Checker) inferFromTypeArguments(n *InferenceState, sourceTypes []*Type, c.inferFromTypes(n, sourceTypes[i], targetTypes[i]) } } + n.depth-- } func (c *Checker) inferWithPriority(n *InferenceState, source *Type, target *Type, newPriority InferencePriority) { @@ -1451,9 +1474,9 @@ func (c *Checker) isTypeParameterAtTopLevelInReturnType(signature *Signature, ty func (c *Checker) getTypeFromInference(inference *InferenceInfo) *Type { switch { - case inference.candidates != nil: + case len(inference.candidates) != 0: return c.getUnionTypeEx(inference.candidates, UnionReductionSubtype, nil, nil) - case inference.contraCandidates != nil: + case len(inference.contraCandidates) != 0: return c.getIntersectionType(inference.contraCandidates) } return nil @@ -1573,6 +1596,7 @@ func cloneInferenceInfo(info *InferenceInfo) *InferenceInfo { return &InferenceInfo{ typeParameter: info.typeParameter, candidates: slices.Clone(info.candidates), + candidateDepths: slices.Clone(info.candidateDepths), contraCandidates: slices.Clone(info.contraCandidates), inferredType: info.inferredType, priority: info.priority, @@ -1595,7 +1619,7 @@ func hasInferenceCandidates(info *InferenceInfo) bool { } func hasInferenceCandidatesOrDefault(info *InferenceInfo) bool { - return info.candidates != nil || info.contraCandidates != nil || hasTypeParameterDefault(info.typeParameter) + return hasInferenceCandidates(info) || hasTypeParameterDefault(info.typeParameter) } func hasTypeParameterDefault(tp *Type) bool { diff --git a/internal/checker/nodebuilderimpl.go b/internal/checker/nodebuilderimpl.go index 188da07aa6e..c51d8672a06 100644 --- a/internal/checker/nodebuilderimpl.go +++ b/internal/checker/nodebuilderimpl.go @@ -492,6 +492,10 @@ func (b *NodeBuilderImpl) typeNodeIsEquivalentToType(annotatedDeclaration *ast.N return false } +func (b *NodeBuilderImpl) canReuseExistingJSTypeNode(existing *ast.TypeNode, t *Type) bool { + return b.ch.getIntendedTypeFromJSDocTypeReference(existing) == nil && b.existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, t) +} + func (b *NodeBuilderImpl) existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing *ast.TypeNode, t *Type) bool { // In JS, you can say something like `Foo` and get a `Foo` implicitly - we don't want to preserve that original `Foo` in these cases, though. if t.objectFlags&ObjectFlagsReference == 0 { @@ -526,7 +530,7 @@ func (b *NodeBuilderImpl) tryReuseExistingNonParameterTypeNode(existing *ast.Typ if annotationType == nil { annotationType = b.getTypeFromTypeNode(existing, true) } - if annotationType != nil && b.typeNodeIsEquivalentToType(host, t, annotationType) && b.existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, t) { + if annotationType != nil && b.typeNodeIsEquivalentToType(host, t, annotationType) && b.canReuseExistingJSTypeNode(existing, t) { result := b.tryReuseExistingNodeHelper(existing) if result != nil { return result @@ -1001,10 +1005,7 @@ func (b *NodeBuilderImpl) getNameOfSymbolAsWritten(symbol *ast.Symbol) string { if len(name) > 0 { return name } - if symbol.Name == ast.InternalSymbolNameMissing { - return "__missing" - } - return symbol.Name + return ast.EscapeInternalSymbolName(symbol.Name) } // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus diff --git a/internal/checker/nodecopy.go b/internal/checker/nodecopy.go index 1d32b853f2f..d47a9a468c8 100644 --- a/internal/checker/nodecopy.go +++ b/internal/checker/nodecopy.go @@ -427,7 +427,12 @@ func getExistingNodeTreeVisitor(b *NodeBuilderImpl, bound *recoveryBoundary) *as return nil // refers to type parameter remapped by context (TODO improvement: just return the remapped param name?) } } - // TODO: further bails in JSdoc - not required anymore due to dropped behavior/reparser? + if !b.canReuseExistingJSTypeNode(node, b.getTypeFromTypeNode(node, false)) { + // fallback to serialization for jsdoc types that have insufficient or incomplete type args, or are remapped by the checker in only jsdoc contexts + // TODO: remappings like `promise` -> `Promise` are static, we *could* statically remap the nodes, too. But that only matters for `isolatedDeclarations` + // in JS, should we enable that. + return nil + } introducesError, newName, _ := trackExistingEntityName(node.AsTypeReferenceNode().TypeName, nil) if !introducesError { typeArguments := visitor.VisitNodes(node.AsTypeReferenceNode().TypeArguments) diff --git a/internal/checker/pseudotypenodebuilder.go b/internal/checker/pseudotypenodebuilder.go index a08187c2478..cf8046803f9 100644 --- a/internal/checker/pseudotypenodebuilder.go +++ b/internal/checker/pseudotypenodebuilder.go @@ -30,7 +30,7 @@ func (b *NodeBuilderImpl) pseudoTypeToNodeWithCheckerFallback(t *pseudochecker.P return result } else if t.Kind == pseudochecker.PseudoTypeKindDirect { existing := t.AsPseudoTypeDirect().TypeNode - if !b.existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, checkerType) { + if !b.canReuseExistingJSTypeNode(existing, checkerType) { if !b.ctx.suppressReportInferenceFallback { b.ctx.tracker.ReportInferenceFallback(existing) } @@ -62,6 +62,9 @@ func (b *NodeBuilderImpl) pseudoTypeToNode(t *pseudochecker.PseudoType) *ast.Nod } else { b.ctx.tracker.ReportInferenceFallback(node) } + if inferred.IsSignatureReturn { + return b.serializeReturnTypeForSignature(b.ch.getSignatureFromDeclaration(node), false) + } // use symbol type from parent declaration to automatically handle expression type widening without duplicating logic if ast.IsReturnStatement(node.Parent) { enclosing := ast.GetContainingFunction(node) @@ -366,9 +369,12 @@ func (b *NodeBuilderImpl) pseudoTypeEquivalentToType(t *pseudochecker.PseudoType if typeFromPseudo == type_ { return true } + undefinedStripped := type_ + if isOptionalAnnotated { + undefinedStripped = b.ch.getTypeWithFacts(type_, TypeFactsNEUndefined) + } if typeFromPseudo != nil && type_ != nil { if isOptionalAnnotated { - undefinedStripped := b.ch.getTypeWithFacts(type_, TypeFactsNEUndefined) if undefinedStripped == typeFromPseudo { return true } @@ -414,7 +420,7 @@ func (b *NodeBuilderImpl) pseudoTypeEquivalentToType(t *pseudochecker.PseudoType if type_ == nil { return false } - targetProps := b.ch.getPropertiesOfType(type_) + targetProps := b.ch.getPropertiesOfType(undefinedStripped) // Count total declarations across all target prop symbols to handle getter/setter pairs, // which are two elements in pt.Elements but only one symbol in targetProps. targetDeclCount := 0 @@ -428,7 +434,7 @@ func (b *NodeBuilderImpl) pseudoTypeEquivalentToType(t *pseudochecker.PseudoType var targetProp *ast.Symbol elemSymbol := e.Name.Parent.Symbol() if elemSymbol != nil { - targetProp = b.ch.getPropertyOfType(type_, elemSymbol.Name) + targetProp = b.ch.getPropertyOfType(undefinedStripped, elemSymbol.Name) } if targetProp == nil { // Name lookup failed or returned no result; search target properties @@ -518,16 +524,16 @@ func (b *NodeBuilderImpl) pseudoTypeEquivalentToType(t *pseudochecker.PseudoType return true case pseudochecker.PseudoTypeKindTuple: pt := t.AsPseudoTypeTuple() - if type_ == nil || !isTupleType(type_) { + if undefinedStripped == nil || !isTupleType(undefinedStripped) { return false } - tupleTarget := type_.TargetTupleType() + tupleTarget := undefinedStripped.TargetTupleType() // Pseudo-tuples come from `as const` array literals, so they only ever have required elements. // If the target tuple has optional, rest, or variadic elements, the structures can't match. if tupleTarget.combinedFlags&ElementFlagsNonRequired != 0 { return false } - elementTypes := b.ch.getTypeArguments(type_) + elementTypes := b.ch.getTypeArguments(undefinedStripped) if len(pt.Elements) != len(elementTypes) { return false } @@ -538,7 +544,7 @@ func (b *NodeBuilderImpl) pseudoTypeEquivalentToType(t *pseudochecker.PseudoType } return true case pseudochecker.PseudoTypeKindSingleCallSignature: - targetSig := b.ch.getSingleCallSignature(type_) + targetSig := b.ch.getSingleCallSignature(undefinedStripped) if targetSig == nil { return false } @@ -689,6 +695,9 @@ func (b *NodeBuilderImpl) pseudoTypeToType(t *pseudochecker.PseudoType) *Type { return b.ch.getTypeFromTypeNode(t.AsPseudoTypeDirect().TypeNode) case pseudochecker.PseudoTypeKindInferred: node := t.AsPseudoTypeInferred().Expression + if t.AsPseudoTypeInferred().IsSignatureReturn { + return b.ch.getReturnTypeOfSignature(b.ch.getSignatureFromDeclaration(node)) + } ty := b.ch.getWidenedType(b.ch.getRegularTypeOfExpression(node)) return ty case pseudochecker.PseudoTypeKindNoResult: diff --git a/internal/compiler/filesparser.go b/internal/compiler/filesparser.go index 74b0583bc90..5817fc6bb86 100644 --- a/internal/compiler/filesparser.go +++ b/internal/compiler/filesparser.go @@ -344,6 +344,14 @@ func (w *filesParser) getProcessedFiles(loader *fileLoader) processedFiles { } var collectFiles func(tasks []*parseTask, seen map[*parseTaskData]string) + // recordedDuplicates tracks, per task data, the set of file-name casings that + // have already been recorded in duplicateSourceFiles. A file that is reached + // from multiple import sites is walked once per site, but each distinct casing + // is only parsed and acquired in the parse cache once. Recording the same casing + // as a duplicate more than once would cause it to be released more times than it + // was acquired when the snapshot is disposed, leaving a dangling cache entry that + // panics the next time it is referenced. + var recordedDuplicates map[*parseTaskData]*collections.Set[string] collectFiles = func(tasks []*parseTask, seen map[*parseTaskData]string) { for _, task := range tasks { includeReason := task.includeReason @@ -364,11 +372,21 @@ func (w *filesParser) getProcessedFiles(loader *fileLoader) processedFiles { // ensure we only walk each task once if checkedName, ok := seen[data]; ok { if task.file != nil && checkedName != task.normalizedFilePath { - duplicateSourceFiles = append(duplicateSourceFiles, &DuplicateSourceFile{ - ParseOptions: task.file.ParseOptions(), - Hash: task.file.Hash, - ScriptKind: task.file.ScriptKind, - }) + if recordedDuplicates == nil { + recordedDuplicates = make(map[*parseTaskData]*collections.Set[string]) + } + dups := recordedDuplicates[data] + if dups == nil { + dups = &collections.Set[string]{} + recordedDuplicates[data] = dups + } + if dups.AddIfAbsent(task.normalizedFilePath) { + duplicateSourceFiles = append(duplicateSourceFiles, &DuplicateSourceFile{ + ParseOptions: task.file.ParseOptions(), + Hash: task.file.Hash, + ScriptKind: task.file.ScriptKind, + }) + } } if !loader.opts.Config.CompilerOptions().ForceConsistentCasingInFileNames.IsFalse() { // Check if it differs only in drive letters its ok to ignore that error: diff --git a/internal/compiler/program.go b/internal/compiler/program.go index 35093fab681..74b2504d9ec 100644 --- a/internal/compiler/program.go +++ b/internal/compiler/program.go @@ -152,6 +152,11 @@ func (p *Program) GetPackageJsonInfo(pkgJsonPath string) *packagejson.InfoCacheE return nil } +// PackageJsonCacheEntries iterates on all package json cache entries. +func (p *Program) PackageJsonCacheEntries(f func(key tspath.Path, value *packagejson.InfoCacheEntry) bool) { + p.resolver.PackageJsonCacheEntries(f) +} + // GetRedirectTargets returns the list of file paths that redirect to the given path. // These are files from the same package (same name@version) installed in different locations. func (p *Program) GetRedirectTargets(path tspath.Path) []string { diff --git a/internal/execute/build/buildtask.go b/internal/execute/build/buildtask.go index 0a64695d947..97381244caa 100644 --- a/internal/execute/build/buildtask.go +++ b/internal/execute/build/buildtask.go @@ -2,6 +2,7 @@ package build import ( "fmt" + "slices" "strings" "sync" "sync/atomic" @@ -63,6 +64,7 @@ type BuildTask struct { buildInfoEntry *buildInfoEntry buildInfoEntryMu sync.Mutex + packageJsons []string errors []*ast.Diagnostic pending atomic.Bool @@ -231,6 +233,7 @@ func (t *BuildTask) compileAndEmit(orchestrator *Orchestrator, path tspath.Path) }) t.result.exitStatus = result.Status t.result.statistics = statistics + t.packageJsons = t.result.program.PackageJsonLookupPaths() if (!program.Options().NoEmitOnError.IsTrue() || len(result.Diagnostics) == 0) && (len(result.EmitResult.EmittedFiles) > 0 || t.status.kind != upToDateStatusTypeOutOfDateBuildInfoWithErrors) { // Update time stamps for rest of the outputs @@ -327,6 +330,9 @@ func (t *BuildTask) getUpToDateStatus(orchestrator *Orchestrator, configPath tsp // Check the build info buildInfoPath := t.resolved.GetBuildInfoFileName() + getBuildInfoDirectory := core.Memoize(func() string { + return tspath.GetDirectoryPath(tspath.GetNormalizedAbsolutePath(buildInfoPath, orchestrator.comparePathsOptions.CurrentDirectory)) + }) buildInfo, buildInfoTime := t.loadOrStoreBuildInfo(orchestrator, configPath, buildInfoPath) if buildInfo == nil { return &upToDateStatus{kind: upToDateStatusTypeOutputMissing, data: buildInfoPath} @@ -363,7 +369,7 @@ func (t *BuildTask) getUpToDateStatus(orchestrator *Orchestrator, configPath tsp } // Some of the emit files like source map or dts etc are not yet done - if buildInfo.IsEmitPending(t.resolved, tspath.GetDirectoryPath(tspath.GetNormalizedAbsolutePath(buildInfoPath, orchestrator.comparePathsOptions.CurrentDirectory))) { + if buildInfo.IsEmitPending(t.resolved, getBuildInfoDirectory()) { return &upToDateStatus{kind: upToDateStatusTypeOutOfDateOptions, data: buildInfoPath} } } @@ -371,7 +377,9 @@ func (t *BuildTask) getUpToDateStatus(orchestrator *Orchestrator, configPath tsp oldestOutputFileAndTime := fileAndTime{buildInfoPath, buildInfoTime} var newestInputFileAndTime fileAndTime var seenRoots collections.Set[tspath.Path] - var buildInfoRootInfoReader *incremental.BuildInfoRootInfoReader + getBuildInfoRootInfoReader := core.Memoize(func() *incremental.BuildInfoRootInfoReader { + return buildInfo.GetBuildInfoRootInfoReader(getBuildInfoDirectory(), orchestrator.comparePathsOptions) + }) for _, inputFile := range t.resolved.FileNames() { inputTime := orchestrator.host.GetMTime(inputFile) if inputTime.IsZero() { @@ -382,10 +390,7 @@ func (t *BuildTask) getUpToDateStatus(orchestrator *Orchestrator, configPath tsp var version string var currentVersion string if buildInfo.IsIncremental() { - if buildInfoRootInfoReader == nil { - buildInfoRootInfoReader = buildInfo.GetBuildInfoRootInfoReader(tspath.GetDirectoryPath(tspath.GetNormalizedAbsolutePath(buildInfoPath, orchestrator.comparePathsOptions.CurrentDirectory)), orchestrator.comparePathsOptions) - } - buildInfoFileInfo, resolvedInputPath := buildInfoRootInfoReader.GetBuildInfoFileInfo(inputPath) + buildInfoFileInfo, resolvedInputPath := getBuildInfoRootInfoReader().GetBuildInfoFileInfo(inputPath) if fileInfo := buildInfoFileInfo.GetFileInfo(); fileInfo != nil && fileInfo.Version() != "" { version = fileInfo.Version() if text, ok := orchestrator.host.FS().ReadFile(string(resolvedInputPath)); ok { @@ -407,16 +412,54 @@ func (t *BuildTask) getUpToDateStatus(orchestrator *Orchestrator, configPath tsp seenRoots.Add(inputPath) } - if buildInfoRootInfoReader == nil { - buildInfoRootInfoReader = buildInfo.GetBuildInfoRootInfoReader(tspath.GetDirectoryPath(tspath.GetNormalizedAbsolutePath(buildInfoPath, orchestrator.comparePathsOptions.CurrentDirectory)), orchestrator.comparePathsOptions) - } - for root := range buildInfoRootInfoReader.Roots() { + for root := range getBuildInfoRootInfoReader().Roots() { if !seenRoots.Has(root) { // File was root file when project was built but its not any more return &upToDateStatus{kind: upToDateStatusTypeOutOfDateRoots, data: &inputOutputName{string(root), buildInfoPath}} } } + if buildInfo.IsIncremental() { + var resolvedRoots collections.Set[tspath.Path] + for root := range getBuildInfoRootInfoReader().Roots() { + if _, resolved := getBuildInfoRootInfoReader().GetBuildInfoFileInfo(root); resolved != "" { + resolvedRoots.Add(resolved) + } + } + for index, buildInfoFileInfo := range buildInfo.FileInfos { + buildInfoFileName := buildInfo.FileNames[index] + // Lib files bundled with the compiler can change only with the version of the compiler, + // which is already verified with buildInfo.Version + if incremental.IsBuildInfoFileNameDefaultLibrary(buildInfoFileName) { + continue + } + inputFile := tspath.GetNormalizedAbsolutePath(buildInfoFileName, getBuildInfoDirectory()) + inputPath := orchestrator.toPath(inputFile) + // Root files are already checked + if seenRoots.Has(inputPath) || resolvedRoots.Has(inputPath) { + continue + } + inputTime := orchestrator.host.GetMTime(inputFile) + if inputTime.IsZero() { + // Input file that was part of the program is missing (eg: dependency was removed) + return &upToDateStatus{kind: upToDateStatusTypeInputFileMissing, data: inputFile} + } + if inputTime.After(oldestOutputFileAndTime.time) { + var currentVersion string + version := buildInfoFileInfo.GetFileInfo().Version() + if version != "" { + if text, ok := orchestrator.host.FS().ReadFile(inputFile); ok { + currentVersion = incremental.ComputeHash(text, orchestrator.opts.Testing != nil) + } + } + if version == "" || version != currentVersion { + return &upToDateStatus{kind: upToDateStatusTypeInputFileNewer, data: &inputOutputName{inputFile, buildInfoPath}} + } + inputTextUnchanged = true + } + } + } + if !t.resolved.CompilerOptions().IsIncremental() { // Check output file stamps for outputFile := range t.resolved.GetOutputFileNames() { @@ -493,14 +536,22 @@ func (t *BuildTask) getUpToDateStatus(orchestrator *Orchestrator, configPath tsp } } - // !!! sheetal TODO : watch?? - // // Check package file time - // const packageJsonLookups = state.lastCachedPackageJsonLookups.get(resolvedPath); - // const dependentPackageFileStatus = packageJsonLookups && forEachKey( - // packageJsonLookups, - // path => checkConfigFileUpToDateStatus(state, path, oldestOutputFileTime, oldestOutputFileName), - // ); - // if (dependentPackageFileStatus) return dependentPackageFileStatus; + for packageJson := range buildInfo.GetPackageJsons(getBuildInfoDirectory()) { + packageJsonTime := orchestrator.host.GetMTime(packageJson) + if packageJsonTime.IsZero() { + return &upToDateStatus{kind: upToDateStatusTypeInputFileMissing, data: packageJson} + } + if packageJsonTime.After(oldestOutputFileAndTime.time) { + return &upToDateStatus{kind: upToDateStatusTypeInputFileNewer, data: &inputOutputName{packageJson, oldestOutputFileAndTime.file}} + } + } + for packageJson := range buildInfo.GetMissingPackageJsons(getBuildInfoDirectory()) { + if !orchestrator.host.GetMTime(packageJson).IsZero() { + return &upToDateStatus{kind: upToDateStatusTypeInputFileNewer, data: &inputOutputName{packageJson, oldestOutputFileAndTime.file}} + } + } + t.packageJsons = slices.Collect(buildInfo.GetPackageJsons(getBuildInfoDirectory())) + t.packageJsons = append(t.packageJsons, slices.Collect(buildInfo.GetMissingPackageJsons(getBuildInfoDirectory()))...) return &upToDateStatus{ kind: core.IfElse( diff --git a/internal/execute/build/orchestrator.go b/internal/execute/build/orchestrator.go index 6afdf077022..8adac69a991 100644 --- a/internal/execute/build/orchestrator.go +++ b/internal/execute/build/orchestrator.go @@ -14,6 +14,7 @@ import ( "github.com/microsoft/typescript-go/internal/compiler" "github.com/microsoft/typescript-go/internal/core" "github.com/microsoft/typescript-go/internal/diagnostics" + "github.com/microsoft/typescript-go/internal/execute/incremental" "github.com/microsoft/typescript-go/internal/execute/tsc" "github.com/microsoft/typescript-go/internal/execute/watchmanager" "github.com/microsoft/typescript-go/internal/fswatch" @@ -86,7 +87,7 @@ func (o *Orchestrator) toPath(fileName string) tspath.Path { } func (o *Orchestrator) resolveBuildInfoFileName(fileName string, buildInfoDir string) string { - if !strings.HasPrefix(fileName, ".") { + if incremental.IsBuildInfoFileNameDefaultLibrary(fileName) { return tspath.CombinePaths(o.host.DefaultLibraryPath(), fileName) } return tspath.GetNormalizedAbsolutePath(fileName, buildInfoDir) @@ -279,9 +280,9 @@ func (o *Orchestrator) resetCaches() { } func (o *Orchestrator) checkTasksForEventChanges(changedPaths map[string]fswatch.EventKind, needsConfigUpdate, needsUpdate *atomic.Bool) { - normalizedPaths := make(map[tspath.Path]struct{}, len(changedPaths)) - for eventPath := range changedPaths { - normalizedPaths[o.toPath(eventPath)] = struct{}{} + normalizedPaths := make(map[tspath.Path]fswatch.EventKind, len(changedPaths)) + for eventPath, kind := range changedPaths { + normalizedPaths[o.toPath(eventPath)] = kind } for i := range o.order { @@ -348,6 +349,27 @@ func (o *Orchestrator) checkTasksForEventChanges(changedPaths map[string]fswatch break } } + for packageJson := range bi.buildInfo.GetPackageJsons(buildInfoDir) { + if o.packageJsonLookupChanged(packageJson, normalizedPaths) { + task.resetStatus() + needsUpdate.Store(true) + break + } + } + for packageJson := range bi.buildInfo.GetMissingPackageJsons(buildInfoDir) { + if o.packageJsonLookupChanged(packageJson, normalizedPaths) { + task.resetStatus() + needsUpdate.Store(true) + break + } + } + } + for _, packageJson := range task.packageJsons { + if o.packageJsonLookupChanged(packageJson, normalizedPaths) { + task.resetStatus() + needsUpdate.Store(true) + break + } } } @@ -381,6 +403,19 @@ func (o *Orchestrator) checkTasksForEventChanges(changedPaths map[string]fswatch } } +func (o *Orchestrator) packageJsonLookupChanged(packageJson string, changedPaths map[tspath.Path]fswatch.EventKind) bool { + packageJsonPath := o.toPath(packageJson) + if _, changed := changedPaths[packageJsonPath]; changed { + return true + } + for changedPath, kind := range changedPaths { + if kind == fswatch.EventDelete && tspath.ContainsPath(string(changedPath), string(packageJsonPath), o.comparePathsOptions) { + return true + } + } + return false +} + func (o *Orchestrator) computeDesiredWatches() map[string]bool { desiredDirs := make(map[string]bool) @@ -438,7 +473,7 @@ func (o *Orchestrator) computeDesiredWatches() map[string]bool { buildInfoDir := tspath.GetDirectoryPath(string(bi.path)) roots := collections.NewSetFromItems(core.Map(task.resolved.FileNames(), o.toPath)...) for _, fileName := range bi.buildInfo.FileNames { - absPath := o.resolveBuildInfoFileName(fileName, buildInfoDir) + absPath := o.host.FS().Realpath(o.resolveBuildInfoFileName(fileName, buildInfoDir)) fp := o.toPath(absPath) if roots.Has(fp) { continue @@ -450,12 +485,56 @@ func (o *Orchestrator) computeDesiredWatches() map[string]bool { } } } + for packageJson := range bi.buildInfo.GetPackageJsons(buildInfoDir) { + o.addPackageJsonWatchDirs(desiredDirs, packageJson) + } + for packageJson := range bi.buildInfo.GetMissingPackageJsons(buildInfoDir) { + o.addPackageJsonWatchDirs(desiredDirs, packageJson) + } + } + for _, packageJson := range task.packageJsons { + o.addPackageJsonWatchDirs(desiredDirs, packageJson) } } return o.wm.ResolveDesiredDirs(desiredDirs) } +func (o *Orchestrator) addWatchDir(desiredDirs map[string]bool, dir string) { + if !watchmanager.IsDirCoveredByWatch(desiredDirs, dir, o.comparePathsOptions) && watchmanager.CanWatchDirectory(dir) { + desiredDirs[dir] = false + } +} + +func (o *Orchestrator) addPackageJsonWatchDirs(desiredDirs map[string]bool, packageJson string) { + dir := tspath.GetDirectoryPath(packageJson) + dirs := []string{dir} + foundNodeModules := false + for current := dir; ; { + parent := tspath.GetDirectoryPath(current) + if parent == "" || parent == current { + break + } + dirs = append(dirs, parent) + if tspath.GetBaseFileName(parent) == "node_modules" { + foundNodeModules = true + if grandparent := tspath.GetDirectoryPath(parent); grandparent != "" && grandparent != parent { + dirs = append(dirs, grandparent) + } + break + } + current = parent + } + + if !foundNodeModules { + o.addWatchDir(desiredDirs, dir) + return + } + for _, dir := range dirs { + o.addWatchDir(desiredDirs, dir) + } +} + func (o *Orchestrator) DoCycle() { o.wm.Lock() defer o.wm.Unlock() diff --git a/internal/execute/incremental/buildInfo.go b/internal/execute/incremental/buildInfo.go index 6c53346f0db..19a308064b7 100644 --- a/internal/execute/incremental/buildInfo.go +++ b/internal/execute/incremental/buildInfo.go @@ -463,9 +463,11 @@ type BuildInfo struct { Version string `json:"version,omitzero"` // Common between incremental and tsc -b buildinfo for non incremental programs - Errors bool `json:"errors,omitzero"` - CheckPending bool `json:"checkPending,omitzero"` - Root []*BuildInfoRoot `json:"root,omitzero"` + Errors bool `json:"errors,omitzero"` + CheckPending bool `json:"checkPending,omitzero"` + Root []*BuildInfoRoot `json:"root,omitzero"` + PackageJsons []string `json:"packageJsons,omitzero"` + MissingPackageJsons []string `json:"missingPackageJsons,omitzero"` // IncrementalProgram info FileNames []string `json:"fileNames,omitzero"` @@ -493,11 +495,21 @@ func (b *BuildInfo) IsIncremental() bool { return b != nil && len(b.FileNames) != 0 } +func IsBuildInfoFileNameDefaultLibrary(fileName string) bool { + return !tspath.PathIsRelative(fileName) && !tspath.PathIsAbsolute(fileName) +} + func (b *BuildInfo) fileName(fileId BuildInfoFileId) string { + if fileId < 1 || int(fileId) > len(b.FileNames) { + return "" + } return b.FileNames[fileId-1] } func (b *BuildInfo) fileInfo(fileId BuildInfoFileId) *BuildInfoFileInfo { + if fileId < 1 || int(fileId) > len(b.FileInfos) { + return nil + } return b.FileInfos[fileId-1] } @@ -529,6 +541,24 @@ func (b *BuildInfo) IsEmitPending(resolved *tsoptions.ParsedCommandLine, buildIn return false } +func (b *BuildInfo) GetPackageJsons(buildInfoDirectory string) iter.Seq[string] { + return getNormalizedPaths(b.PackageJsons, buildInfoDirectory) +} + +func (b *BuildInfo) GetMissingPackageJsons(buildInfoDirectory string) iter.Seq[string] { + return getNormalizedPaths(b.MissingPackageJsons, buildInfoDirectory) +} + +func getNormalizedPaths(paths []string, buildInfoDirectory string) iter.Seq[string] { + return func(yield func(string) bool) { + for _, path := range paths { + if !yield(tspath.GetNormalizedAbsolutePath(path, buildInfoDirectory)) { + return + } + } + } +} + func (b *BuildInfo) GetBuildInfoRootInfoReader(buildInfoDirectory string, comparePathOptions tspath.ComparePathsOptions) *BuildInfoRootInfoReader { resolvedRootFileInfos := make(map[tspath.Path]*BuildInfoFileInfo, len(b.FileNames)) // Roots of the File @@ -540,10 +570,17 @@ func (b *BuildInfo) GetBuildInfoRootInfoReader(buildInfoDirectory string, compar // Create map from resolvedRoot to Root for _, resolved := range b.ResolvedRoot { - resolvedToRoot[toPath(b.fileName(resolved.Resolved))] = toPath(b.fileName(resolved.Root)) + resolvedRoot := b.fileName(resolved.Resolved) + root := b.fileName(resolved.Root) + if resolvedRoot != "" && root != "" { + resolvedToRoot[toPath(resolvedRoot)] = toPath(root) + } } addRoot := func(resolvedRoot string, fileInfo *BuildInfoFileInfo) { + if resolvedRoot == "" { + return + } resolvedRootPath := toPath(resolvedRoot) if rootPath, ok := resolvedToRoot[resolvedRootPath]; ok { rootToResolved.Set(rootPath, resolvedRootPath) diff --git a/internal/execute/incremental/buildinfotosnapshot.go b/internal/execute/incremental/buildinfotosnapshot.go index b3e0edc98fc..edd111dfebe 100644 --- a/internal/execute/incremental/buildinfotosnapshot.go +++ b/internal/execute/incremental/buildinfotosnapshot.go @@ -1,8 +1,6 @@ package incremental import ( - "strings" - "github.com/microsoft/typescript-go/internal/ast" "github.com/microsoft/typescript-go/internal/collections" "github.com/microsoft/typescript-go/internal/compiler" @@ -19,7 +17,7 @@ func buildInfoToSnapshot(buildInfo *BuildInfo, config *tsoptions.ParsedCommandLi filePathSet: make([]*collections.Set[tspath.Path], 0, len(buildInfo.FileIdsList)), } to.filePaths = core.Map(buildInfo.FileNames, func(fileName string) tspath.Path { - if !strings.HasPrefix(fileName, ".") { + if IsBuildInfoFileNameDefaultLibrary(fileName) { return tspath.ToPath(tspath.CombinePaths(host.DefaultLibraryPath(), fileName), host.GetCurrentDirectory(), host.FS().UseCaseSensitiveFileNames()) } return tspath.ToPath(fileName, to.buildInfoDirectory, config.UseCaseSensitiveFileNames()) @@ -44,6 +42,7 @@ func buildInfoToSnapshot(buildInfo *BuildInfo, config *tsoptions.ParsedCommandLi to.snapshot.hasErrors = core.IfElse(buildInfo.Errors, core.TSTrue, core.TSFalse) to.snapshot.hasSemanticErrors = buildInfo.SemanticErrors to.snapshot.checkPending = buildInfo.CheckPending + to.setPackageJsons() return &to.snapshot } @@ -184,3 +183,16 @@ func (t *toSnapshot) setAffectedFilesPendingEmit() { t.snapshot.affectedFilesPendingEmit.Store(t.toFilePath(pendingEmit.FileId), core.IfElse(pendingEmit.EmitKind == 0, ownOptionsEmitKind, pendingEmit.EmitKind)) } } + +func (t *toSnapshot) setPackageJsons() { + if t.buildInfo.PackageJsons != nil { + t.snapshot.packageJsons = core.Map(t.buildInfo.PackageJsons, t.toAbsolutePath) + } else { + t.snapshot.packageJsons = make([]string, 0) + } + if t.buildInfo.MissingPackageJsons != nil { + t.snapshot.missingPackageJsons = core.Map(t.buildInfo.MissingPackageJsons, t.toAbsolutePath) + } else { + t.snapshot.missingPackageJsons = make([]string, 0) + } +} diff --git a/internal/execute/incremental/host.go b/internal/execute/incremental/host.go index 55d6bbc0887..6b1a049ef32 100644 --- a/internal/execute/incremental/host.go +++ b/internal/execute/incremental/host.go @@ -4,9 +4,11 @@ import ( "time" "github.com/microsoft/typescript-go/internal/compiler" + "github.com/microsoft/typescript-go/internal/vfs" ) type Host interface { + FS() vfs.FS GetMTime(fileName string) time.Time SetMTime(fileName string, mTime time.Time) error } @@ -17,12 +19,16 @@ type host struct { var _ Host = (*host)(nil) -func (b *host) GetMTime(fileName string) time.Time { - return GetMTime(b.host, fileName) +func (h *host) FS() vfs.FS { + return h.host.FS() } -func (b *host) SetMTime(fileName string, mTime time.Time) error { - return b.host.FS().Chtimes(fileName, time.Time{}, mTime) +func (h *host) GetMTime(fileName string) time.Time { + return GetMTime(h.host, fileName) +} + +func (h *host) SetMTime(fileName string, mTime time.Time) error { + return h.host.FS().Chtimes(fileName, time.Time{}, mTime) } func CreateHost(compilerHost compiler.CompilerHost) Host { diff --git a/internal/execute/incremental/program.go b/internal/execute/incremental/program.go index fc69fcff488..d57db6fbd6f 100644 --- a/internal/execute/incremental/program.go +++ b/internal/execute/incremental/program.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "slices" + "strings" "github.com/microsoft/typescript-go/internal/ast" "github.com/microsoft/typescript-go/internal/collections" @@ -12,6 +13,7 @@ import ( "github.com/microsoft/typescript-go/internal/diagnostics" "github.com/microsoft/typescript-go/internal/json" "github.com/microsoft/typescript-go/internal/outputpaths" + "github.com/microsoft/typescript-go/internal/packagejson" "github.com/microsoft/typescript-go/internal/tracing" "github.com/microsoft/typescript-go/internal/tspath" ) @@ -290,6 +292,13 @@ func (p *Program) emitBuildInfo(ctx context.Context, options compiler.EmitOption p.snapshot.buildInfoEmitPending.Store(true) } } + if p.snapshot.packageJsons == nil { + p.ensurePackageJsonsForState() + if !slices.Equal(p.snapshot.packageJsons, p.snapshot.packageJsonsFromOldState) || + !slices.Equal(p.snapshot.missingPackageJsons, p.snapshot.missingPackageJsonsFromOldState) { + p.snapshot.buildInfoEmitPending.Store(true) + } + } if !p.snapshot.buildInfoEmitPending.Load() { return nil } @@ -372,7 +381,7 @@ func (p *Program) ensureHasErrorsForState(ctx context.Context, program *compiler p.snapshot.hasErrors = core.TSFalse // Check semantic and emit diagnostics first as we dont need to ask program about it - if slices.ContainsFunc(program.GetSourceFiles(), func(file *ast.SourceFile) bool { + if slices.ContainsFunc(p.program.GetSourceFiles(), func(file *ast.SourceFile) bool { semanticDiagnostics, ok := p.snapshot.semanticDiagnosticsPerFile.Load(file.Path()) if !ok { // Missing semantic diagnostics in cache will be encoded in incremental buildInfo @@ -389,3 +398,56 @@ func (p *Program) ensureHasErrorsForState(ctx context.Context, program *compiler p.snapshot.hasSemanticErrors = !p.snapshot.options.IsIncremental() } } + +func (p *Program) ensurePackageJsonsForState() { + config := tspath.GetDirectoryPath(p.program.CommandLine().ConfigName()) + if config != "" { + p.program.PackageJsonCacheEntries(func(key tspath.Path, value *packagejson.InfoCacheEntry) bool { + if value == nil { + return true + } + packageJson := tspath.CombinePaths(value.PackageDirectory, "package.json") + if value.Exists() || value.DirectoryExists { + packageJson = p.program.Host().FS().Realpath(packageJson) + } + if value.Exists() { + p.snapshot.packageJsons = append(p.snapshot.packageJsons, packageJson) + } else if strings.Contains(packageJson, "/node_modules/") { + p.snapshot.missingPackageJsons = append(p.snapshot.missingPackageJsons, packageJson) + } + return true + }) + } + p.snapshot.packageJsons = normalizePackageJsons(p.snapshot.packageJsons) + p.snapshot.missingPackageJsons = normalizePackageJsons(p.snapshot.missingPackageJsons) +} + +func normalizePackageJsons(packageJsons []string) []string { + if packageJsons == nil { + return make([]string, 0) + } + slices.Sort(packageJsons) + return core.Deduplicate(packageJsons) +} + +func (p *Program) PackageJsonLookupPaths() []string { + config := tspath.GetDirectoryPath(p.program.CommandLine().ConfigName()) + if config == "" { + return nil + } + + var packageJsons []string + p.program.PackageJsonCacheEntries(func(key tspath.Path, value *packagejson.InfoCacheEntry) bool { + if value == nil { + return true + } + packageJson := tspath.CombinePaths(value.PackageDirectory, "package.json") + if value.Exists() || value.DirectoryExists { + packageJson = p.program.Host().FS().Realpath(packageJson) + } + packageJsons = append(packageJsons, packageJson) + return true + }) + slices.Sort(packageJsons) + return core.Deduplicate(packageJsons) +} diff --git a/internal/execute/incremental/programtosnapshot.go b/internal/execute/incremental/programtosnapshot.go index 49ffb300361..44b9b4cbc65 100644 --- a/internal/execute/incremental/programtosnapshot.go +++ b/internal/execute/incremental/programtosnapshot.go @@ -62,6 +62,8 @@ func (t *toProgramSnapshot) reuseFromOldProgram() { t.snapshot.buildInfoEmitPending.Store(t.oldProgram.snapshot.buildInfoEmitPending.Load()) t.snapshot.hasErrorsFromOldState = t.oldProgram.snapshot.hasErrors t.snapshot.hasSemanticErrorsFromOldState = t.oldProgram.snapshot.hasSemanticErrors + t.snapshot.packageJsonsFromOldState = t.oldProgram.snapshot.packageJsons + t.snapshot.missingPackageJsonsFromOldState = t.oldProgram.snapshot.missingPackageJsons } else { t.snapshot.buildInfoEmitPending.Store(t.snapshot.options.IsIncremental()) } diff --git a/internal/execute/incremental/snapshot.go b/internal/execute/incremental/snapshot.go index c76fbbee73d..a4d8cd8b06b 100644 --- a/internal/execute/incremental/snapshot.go +++ b/internal/execute/incremental/snapshot.go @@ -323,6 +323,9 @@ type snapshot struct { hasSemanticErrors bool // If semantic diagnostic check is pending checkPending bool + // Looked up package.json files from + packageJsons []string + missingPackageJsons []string // Additional fields that are not serialized but needed to track state @@ -331,6 +334,8 @@ type snapshot struct { hasErrorsFromOldState core.Tristate hasSemanticErrorsFromOldState bool allFilesExcludingDefaultLibraryFileOnce sync.Once + packageJsonsFromOldState []string + missingPackageJsonsFromOldState []string // Cache of all files excluding default library file for the current program allFilesExcludingDefaultLibraryFile []*ast.SourceFile hasChangedDtsFile bool diff --git a/internal/execute/incremental/snapshottobuildinfo.go b/internal/execute/incremental/snapshottobuildinfo.go index 8622909ca79..3b2c3c7736d 100644 --- a/internal/execute/incremental/snapshottobuildinfo.go +++ b/internal/execute/incremental/snapshottobuildinfo.go @@ -52,6 +52,7 @@ func snapshotToBuildInfo(snapshot *snapshot, program *compiler.Program, buildInf buildInfo.Errors = snapshot.hasErrors.IsTrue() buildInfo.SemanticErrors = snapshot.hasSemanticErrors buildInfo.CheckPending = snapshot.checkPending + to.setPackageJsons() return buildInfo } @@ -369,3 +370,12 @@ func (t *toBuildInfo) setRootOfNonIncrementalProgram() { } }) } + +func (t *toBuildInfo) setPackageJsons() { + if len(t.snapshot.packageJsons) > 0 { + t.buildInfo.PackageJsons = core.Map(t.snapshot.packageJsons, t.relativeToBuildInfo) + } + if len(t.snapshot.missingPackageJsons) > 0 { + t.buildInfo.MissingPackageJsons = core.Map(t.snapshot.missingPackageJsons, t.relativeToBuildInfo) + } +} diff --git a/internal/execute/tsc/emit.go b/internal/execute/tsc/emit.go index 16080d1f807..427115df05b 100644 --- a/internal/execute/tsc/emit.go +++ b/internal/execute/tsc/emit.go @@ -139,7 +139,7 @@ func listFiles(input EmitInput, emitResult *compiler.EmitResult) { options := input.Program.Options() if options.ListEmittedFiles.IsTrue() { for _, file := range emitResult.EmittedFiles { - fmt.Fprintln(input.Writer, "TSFILE: ", tspath.GetNormalizedAbsolutePath(file, input.Program.GetCurrentDirectory())) + fmt.Fprintln(input.Writer, "TSFILE:", tspath.GetNormalizedAbsolutePath(file, input.Program.GetCurrentDirectory())) } } if options.ExplainFiles.IsTrue() { diff --git a/internal/execute/tsctests/mock_watch_backend.go b/internal/execute/tsctests/mock_watch_backend.go index eca507a0772..53b4575189d 100644 --- a/internal/execute/tsctests/mock_watch_backend.go +++ b/internal/execute/tsctests/mock_watch_backend.go @@ -55,14 +55,33 @@ func (w *MockWatch) Close() error { } func (m *MockWatchBackend) WatchDirectory(dir string, fn fswatch.WatchCallback, recursive bool, ignore func(string) bool) (io.Closer, error) { + closers, err := m.WatchDirectories([]watchmanager.WatchDirectoryRequest{{ + Dir: dir, + Callback: fn, + Recursive: recursive, + Ignore: ignore, + }}) + if err != nil { + return nil, err + } + return closers[0], nil +} + +func (m *MockWatchBackend) WatchDirectories(requests []watchmanager.WatchDirectoryRequest) ([]io.Closer, error) { m.mu.Lock() defer m.mu.Unlock() - if m.DirectoryExists != nil && !m.DirectoryExists(dir) { - return nil, fmt.Errorf("directory does not exist: %s", dir) + for _, request := range requests { + if m.DirectoryExists != nil && !m.DirectoryExists(request.Dir) { + return nil, fmt.Errorf("directory does not exist: %s", request.Dir) + } + } + closers := make([]io.Closer, len(requests)) + for i, request := range requests { + w := &MockWatch{Path: request.Dir, Callback: request.Callback, Recursive: request.Recursive, Ignore: request.Ignore} + m.Dirs[request.Dir] = w + closers[i] = w } - w := &MockWatch{Path: dir, Callback: fn, Recursive: recursive, Ignore: ignore} - m.Dirs[dir] = w - return w, nil + return closers, nil } // SendEvents routes events through the registered watch callbacks diff --git a/internal/execute/tsctests/readablebuildinfo.go b/internal/execute/tsctests/readablebuildinfo.go index ada396f4e4d..64c61a77e3a 100644 --- a/internal/execute/tsctests/readablebuildinfo.go +++ b/internal/execute/tsctests/readablebuildinfo.go @@ -16,9 +16,11 @@ type readableBuildInfo struct { Version string `json:"version,omitzero"` // Common between incremental and tsc -b buildinfo for non incremental programs - Errors bool `json:"errors,omitzero"` - CheckPending bool `json:"checkPending,omitzero"` - Root []*readableBuildInfoRoot `json:"root,omitzero"` + Errors bool `json:"errors,omitzero"` + CheckPending bool `json:"checkPending,omitzero"` + Root []*readableBuildInfoRoot `json:"root,omitzero"` + PackageJsons []string `json:"packageJsons,omitzero"` + MissingPackageJsons []string `json:"missingPackageJsons,omitzero"` // IncrementalProgram info FileNames []string `json:"fileNames,omitzero"` @@ -214,6 +216,8 @@ func toReadableBuildInfo(buildInfo *incremental.BuildInfo, buildInfoText string) Options: buildInfo.Options, LatestChangedDtsFile: buildInfo.LatestChangedDtsFile, SemanticErrors: buildInfo.SemanticErrors, + PackageJsons: buildInfo.PackageJsons, + MissingPackageJsons: buildInfo.MissingPackageJsons, Size: len(buildInfoText), } readable.setFileInfos() diff --git a/internal/execute/tsctests/tsc_test.go b/internal/execute/tsctests/tsc_test.go index 46128bbb759..ad73120c05b 100644 --- a/internal/execute/tsctests/tsc_test.go +++ b/internal/execute/tsctests/tsc_test.go @@ -3045,7 +3045,6 @@ func TestTscModuleResolution(t *testing.T) { edit: func(sys *TestSys) { sys.replaceFileText(`/user/username/projects/myproject/packages/pkg1/package.json`, `"module"`, `"commonjs"`) }, - expectedDiff: "Package.json watch pending, so no change detected yet", }, { caption: "removes those errors when a package file is changed back", @@ -3058,7 +3057,6 @@ func TestTscModuleResolution(t *testing.T) { edit: func(sys *TestSys) { sys.replaceFileText(`/user/username/projects/myproject/packages/pkg1/package.json`, `"module"`, `"commonjs"`) }, - expectedDiff: "Package.json watch pending, so no change detected yet", }, { caption: "removes those errors when a package file is changed to cjs extensions", @@ -3114,7 +3112,6 @@ func TestTscModuleResolution(t *testing.T) { edit: func(sys *TestSys) { sys.replaceFileText(`/user/username/projects/myproject/packages/pkg2/package.json`, `index.js`, `other.js`) }, - expectedDiff: "Package.json watch pending, so no change detected yet", }, { caption: "removes those errors when a package file is changed back", @@ -3124,6 +3121,75 @@ func TestTscModuleResolution(t *testing.T) { }, }, }, + { + subScenario: `build mode watches missing package-json lookups`, + files: FileMap{ + `/user/username/projects/myproject/packages/pkg1/index.ts`: stringtestutil.Dedent(` + import type { TheNum } from 'pkg2' + export const theNum: TheNum = 42;`), + `/user/username/projects/myproject/packages/pkg1/tsconfig.json`: stringtestutil.Dedent(` + { + "compilerOptions": { + "outDir": "build", + }, + }`), + }, + cwd: "/user/username/projects/myproject", + commandLineArgs: []string{"-b", "packages/pkg1", "-w", "--verbose", "--traceResolution"}, + edits: []*tscEdit{ + { + caption: "resolves import after package is installed", + edit: func(sys *TestSys) { + sys.writeFileNoError(`/user/username/projects/myproject/node_modules/pkg2/package.json`, stringtestutil.Dedent(` + { + "name": "pkg2", + "version": "1.0.0", + "types": "index.d.ts" + }`)) + sys.writeFileNoError(`/user/username/projects/myproject/node_modules/pkg2/index.d.ts`, `export type TheNum = 42;`) + }, + }, + { + caption: "reports import errors after package is removed", + edit: func(sys *TestSys) { + sys.removeNoError(`/user/username/projects/myproject/node_modules/pkg2/package.json`) + sys.removeNoError(`/user/username/projects/myproject/node_modules/pkg2/index.d.ts`) + }, + }, + }, + }, + { + subScenario: `build mode watches package-json lookups from existing buildinfo`, + files: GetFileMapWithBuild(FileMap{ + `/user/username/projects/myproject/packages/pkg1/index.ts`: stringtestutil.Dedent(` + import type { TheNum } from 'pkg2' + export const theNum: TheNum = 42;`), + `/user/username/projects/myproject/packages/pkg1/tsconfig.json`: stringtestutil.Dedent(` + { + "compilerOptions": { + "outDir": "zzbuild", + }, + }`), + `/user/username/projects/myproject/node_modules/pkg2/package.json`: stringtestutil.Dedent(` + { + "name": "pkg2", + "version": "1.0.0", + "types": "index.d.ts" + }`), + `/user/username/projects/myproject/node_modules/pkg2/index.d.ts`: `export type TheNum = 42;`, + }, []string{"-b", "/user/username/projects/myproject/packages/pkg1", "--verbose", "--traceResolution"}), + cwd: "/user/username/projects/myproject", + commandLineArgs: []string{"-b", "packages/pkg1", "-w", "--verbose", "--traceResolution"}, + edits: []*tscEdit{ + { + caption: "reports import errors after package is removed", + edit: func(sys *TestSys) { + sys.removeNoError(`/user/username/projects/myproject/node_modules/pkg2/package.json`) + sys.removeNoError(`/user/username/projects/myproject/node_modules/pkg2/index.d.ts`) + }, + }, + }, + }, { subScenario: "resolution from d.ts of referenced project", files: FileMap{ diff --git a/internal/execute/tsctests/tscbuild_test.go b/internal/execute/tsctests/tscbuild_test.go index 1381b46d423..8c2339ffb60 100644 --- a/internal/execute/tsctests/tscbuild_test.go +++ b/internal/execute/tsctests/tscbuild_test.go @@ -969,6 +969,213 @@ func TestBuildFileDelete(t *testing.T) { } } +func TestBuildDependencyUpdate(t *testing.T) { + t.Parallel() + testCases := []*tscInput{ + { + // https://github.com/microsoft/typescript-go/issues/2666 + subScenario: "rebuilds when dependency in node_modules is updated", + files: FileMap{ + "/home/src/workspaces/project/tsconfig.json": stringtestutil.Dedent(` + { + "compilerOptions": { + "composite": true, + "outDir": "dist", + "strict": true + }, + "include": ["src/**/*"] + } + `), + "/home/src/workspaces/project/src/index.ts": stringtestutil.Dedent(` + import { myValue } from "my-dep"; + export const value: string = myValue; + `), + "/home/src/workspaces/project/node_modules/my-dep/package.json": stringtestutil.Dedent(` + { + "name": "my-dep", + "version": "1.0.0", + "types": "index.d.ts" + } + `), + "/home/src/workspaces/project/node_modules/my-dep/index.d.ts": "export declare const myValue: string;", + }, + cwd: "/home/src/workspaces/project", + commandLineArgs: []string{"--b", "--verbose"}, + edits: []*tscEdit{ + noChange, + { + caption: "update dependency d.ts with breaking type change", + edit: func(sys *TestSys) { + sys.writeFileNoError("/home/src/workspaces/project/node_modules/my-dep/index.d.ts", "export declare const myValue: number;") + }, + }, + { + caption: "restore dependency d.ts", + edit: func(sys *TestSys) { + sys.writeFileNoError("/home/src/workspaces/project/node_modules/my-dep/index.d.ts", "export declare const myValue: string;") + }, + }, + { + caption: "update dependency d.ts timestamp without changing text", + edit: func(sys *TestSys) { + sys.writeFileNoError("/home/src/workspaces/project/node_modules/my-dep/index.d.ts", "export declare const myValue: string;") + }, + }, + noChange, + { + caption: "delete dependency d.ts", + edit: func(sys *TestSys) { + sys.removeNoError("/home/src/workspaces/project/node_modules/my-dep/index.d.ts") + }, + }, + }, + }, + { + subScenario: "rebuilds when missing dependency package json is added", + files: FileMap{ + "/home/src/workspaces/project/tsconfig.json": stringtestutil.Dedent(` + { + "compilerOptions": { + "composite": true, + "outDir": "dist", + "strict": true + }, + "include": ["src/**/*"] + } + `), + "/home/src/workspaces/project/src/index.ts": stringtestutil.Dedent(` + import { myValue } from "my-dep"; + export const value: string = myValue; + `), + "/home/src/workspaces/project/node_modules/my-dep/index.d.ts": "export declare const myValue: string;", + "/home/src/workspaces/project/node_modules/my-dep/alt.d.ts": "export declare const myValue: number;", + }, + cwd: "/home/src/workspaces/project", + commandLineArgs: []string{"--b", "--verbose"}, + edits: []*tscEdit{ + { + caption: "add package json redirecting types to a declaration file with a breaking type change", + edit: func(sys *TestSys) { + sys.writeFileNoError("/home/src/workspaces/project/node_modules/my-dep/package.json", `{"types":"alt.d.ts"}`) + }, + }, + }, + }, + { + subScenario: "rebuilds when dependency package json redirects to a different declaration file", + files: FileMap{ + "/home/src/workspaces/project/tsconfig.json": stringtestutil.Dedent(` + { + "compilerOptions": { + "composite": true, + "outDir": "dist", + "strict": true + }, + "include": ["src/**/*"] + } + `), + "/home/src/workspaces/project/src/index.ts": stringtestutil.Dedent(` + import { myValue } from "my-dep"; + export const value: string = myValue; + `), + "/home/src/workspaces/project/node_modules/my-dep/package.json": stringtestutil.Dedent(` + { + "name": "my-dep", + "version": "1.0.0", + "types": "index.d.ts" + } + `), + "/home/src/workspaces/project/node_modules/my-dep/index.d.ts": "export declare const myValue: string;", + "/home/src/workspaces/project/node_modules/my-dep/alt.d.ts": "export declare const myValue: number;", + }, + cwd: "/home/src/workspaces/project", + commandLineArgs: []string{"--b", "--verbose"}, + edits: []*tscEdit{ + { + caption: "redirect package types to a declaration file with a breaking type change", + edit: func(sys *TestSys) { + sys.replaceFileText("/home/src/workspaces/project/node_modules/my-dep/package.json", "index.d.ts", "alt.d.ts") + }, + }, + }, + }, + { + subScenario: "rebuilds when absolute non-root dependency is updated", + files: FileMap{ + "C:/work/project/tsconfig.json": stringtestutil.Dedent(` + { + "compilerOptions": { + "composite": true, + "outDir": "dist", + "paths": { + "abs-dep": ["D:/work/deps/dep.d.ts"] + }, + "strict": true + }, + "include": ["src/**/*"] + } + `), + "C:/work/project/src/index.ts": stringtestutil.Dedent(` + import { myValue } from "abs-dep"; + export const value: string = myValue; + `), + "D:/work/deps/dep.d.ts": "export declare const myValue: string;", + }, + cwd: "C:/work/project", + windowsStyleRoot: "C:/", + ignoreCase: true, + commandLineArgs: []string{"--b", "--verbose"}, + edits: []*tscEdit{ + { + caption: "update absolute non-root dependency with breaking type change", + edit: func(sys *TestSys) { + sys.writeFileNoError("D:/work/deps/dep.d.ts", "export declare const myValue: number;") + }, + }, + }, + }, + { + subScenario: "watches absolute non-root dependency updates", + files: FileMap{ + "C:/work/project/tsconfig.json": stringtestutil.Dedent(` + { + "compilerOptions": { + "composite": true, + "outDir": "dist", + "paths": { + "abs-dep": ["D:/work/deps/dep.d.ts"] + }, + "strict": true + }, + "include": ["src/**/*"] + } + `), + "C:/work/project/src/index.ts": stringtestutil.Dedent(` + import { myValue } from "abs-dep"; + export const value: string = myValue; + `), + "D:/work/deps/dep.d.ts": "export declare const myValue: string;", + }, + cwd: "C:/work/project", + windowsStyleRoot: "C:/", + ignoreCase: true, + commandLineArgs: []string{"--b", "--verbose", "--watch"}, + edits: []*tscEdit{ + { + caption: "update absolute non-root dependency with breaking type change", + edit: func(sys *TestSys) { + sys.writeFileNoError("D:/work/deps/dep.d.ts", "export declare const myValue: number;") + }, + }, + }, + }, + } + + for _, test := range testCases { + test.run(t, "dependencyUpdate") + } +} + func TestBuildInferredTypeFromTransitiveModule(t *testing.T) { t.Parallel() getBuildInferredTypeFromTransitiveModuleMap := func(isolatedModules bool, lazyExtraContents string) FileMap { @@ -2338,6 +2545,23 @@ func TestBuildProgramUpdates(t *testing.T) { cwd: "/user/username/projects/project", commandLineArgs: []string{"--b", "-i", "-w"}, }, + { + subScenario: "tsbuildinfo has fewer fileInfos than fileNames", + files: FileMap{ + "/user/username/projects/project/src/a.ts": "export const a = 1;", + "/user/username/projects/project/src/b.ts": "export const b = 2;", + "/user/username/projects/project/tsconfig.json": `{"compilerOptions":{"composite":true,"outDir":"dist"},"files":["src/a.ts","src/b.ts"]}`, + "/user/username/projects/project/dist/tsconfig.tsbuildinfo": `{ + "version": "FakeTSVersion", + "fileNames": ["lib.es2025.full.d.ts", "../src/a.ts", "../src/b.ts"], + "fileInfos": ["abc123"], + "options": {"composite": true, "outDir": "./"}, + "root": [2, 3] + }`, + }, + cwd: "/user/username/projects/project", + commandLineArgs: []string{"--b", "-v"}, + }, { subScenario: "when root is source from project reference", files: FileMap{ diff --git a/internal/execute/tsctests/tscwatch_test.go b/internal/execute/tsctests/tscwatch_test.go index 7650fcea7e9..fdf7ec0302e 100644 --- a/internal/execute/tsctests/tscwatch_test.go +++ b/internal/execute/tsctests/tscwatch_test.go @@ -1,6 +1,7 @@ package tsctests import ( + "fmt" "strings" "testing" @@ -9,6 +10,30 @@ import ( func TestWatch(t *testing.T) { t.Parallel() + bunDependencyTest := func() *tscInput { + files := FileMap{} + var index strings.Builder + var fileNames strings.Builder + fileNames.WriteString(`"index.ts"`) + for i := range 12 { + name := fmt.Sprintf("pkg%d", i) + value := fmt.Sprintf("value%d", i) + index.WriteString(fmt.Sprintf(`import { %[1]s } from "./node_modules/.bun/%[2]s/index"; %[1]s;`, value, name)) + index.WriteString("\n") + files["/home/src/workspaces/project/node_modules/.bun/"+name+"/index.ts"] = fmt.Sprintf("export const %s = %d;", value, i) + fileNames.WriteString(fmt.Sprintf(`, "node_modules/.bun/%s/index.ts"`, name)) + } + files["/home/src/workspaces/project/index.ts"] = index.String() + files["/home/src/workspaces/project/tsconfig.json"] = fmt.Sprintf(`{ + "compilerOptions": {}, + "files": [%s] +}`, fileNames.String()) + return &tscInput{ + subScenario: "watch handles many bun dependency files", + files: files, + commandLineArgs: []string{"--watch"}, + } + } testCases := []*tscInput{ { subScenario: "watch with no tsconfig", @@ -25,6 +50,7 @@ func TestWatch(t *testing.T) { }, commandLineArgs: []string{"--watch", "--incremental"}, }, + bunDependencyTest(), { subScenario: "watch skips build when no files change", files: FileMap{ diff --git a/internal/execute/watchmanager/watchbackend.go b/internal/execute/watchmanager/watchbackend.go index 64551574cb7..46e9420082a 100644 --- a/internal/execute/watchmanager/watchbackend.go +++ b/internal/execute/watchmanager/watchbackend.go @@ -11,6 +11,14 @@ import ( // WatchBackend abstracts fswatch.Watcher for testing type WatchBackend interface { WatchDirectory(dir string, fn fswatch.WatchCallback, recursive bool, ignore func(string) bool) (io.Closer, error) + WatchDirectories(requests []WatchDirectoryRequest) ([]io.Closer, error) +} + +type WatchDirectoryRequest struct { + Dir string + Callback fswatch.WatchCallback + Recursive bool + Ignore func(string) bool } // CommandLineTestingWithWatchBackend is an optional extension of @@ -22,14 +30,43 @@ type CommandLineTestingWithWatchBackend interface { type FSWatchBackend struct{ Inner fswatch.Watcher } func (b *FSWatchBackend) WatchDirectory(dir string, fn fswatch.WatchCallback, recursive bool, ignore func(string) bool) (io.Closer, error) { - var opts []fswatch.WatchOption - if recursive { - opts = append(opts, fswatch.WithRecursive()) + closers, err := b.WatchDirectories([]WatchDirectoryRequest{{ + Dir: dir, + Callback: fn, + Recursive: recursive, + Ignore: ignore, + }}) + if err != nil { + return nil, err + } + return closers[0], nil +} + +func (b *FSWatchBackend) WatchDirectories(requests []WatchDirectoryRequest) ([]io.Closer, error) { + fswatchRequests := make([]fswatch.WatchDirectoryRequest, len(requests)) + for i, request := range requests { + var opts []fswatch.WatchOption + if request.Recursive { + opts = append(opts, fswatch.WithRecursive()) + } + if request.Ignore != nil { + opts = append(opts, fswatch.WithIgnore(request.Ignore)) + } + fswatchRequests[i] = fswatch.WatchDirectoryRequest{ + Dir: request.Dir, + Callback: request.Callback, + Options: opts, + } + } + watches, err := b.Inner.WatchDirectories(fswatchRequests) + if err != nil { + return nil, err } - if ignore != nil { - opts = append(opts, fswatch.WithIgnore(ignore)) + closers := make([]io.Closer, len(watches)) + for i, watch := range watches { + closers[i] = watch } - return b.Inner.WatchDirectory(dir, fn, opts...) + return closers, nil } func ShouldIgnoreWatchPath(path string) bool { diff --git a/internal/execute/watchmanager/watchmanager.go b/internal/execute/watchmanager/watchmanager.go index b5fe9a89bab..46120ac76de 100644 --- a/internal/execute/watchmanager/watchmanager.go +++ b/internal/execute/watchmanager/watchmanager.go @@ -17,6 +17,11 @@ type watchedDir struct { recursive bool } +type dirWatchUpdate struct { + dir string + recursive bool +} + // WatchManager manages fswatch directory watches, event accumulation, // and DoCycle signaling. It is shared by the CLI watcher and the build // mode orchestrator. @@ -174,14 +179,8 @@ func (wm *WatchManager) CloseAllWatches() { func (wm *WatchManager) createDirWatch(dir string, recursive bool) error { entry := &watchedDir{recursive: recursive} - cb := func(events []fswatch.Event, err error) { - if err != nil && errors.Is(err, fswatch.ErrWatchTerminated) { - wm.handleWatchTerminated(dir, entry) - return - } - wm.onWatchEvents(events, err) - } - watch, err := wm.backend.WatchDirectory(dir, cb, recursive, ShouldIgnoreWatchPath) + request := wm.createDirWatchRequest(dir, entry) + watch, err := wm.backend.WatchDirectory(request.Dir, request.Callback, request.Recursive, request.Ignore) if err != nil { if wm.DebugLog != nil { fmt.Fprintf(wm.DebugLog, "[watch] failed to watch directory %s: %v\n", dir, err) @@ -193,6 +192,21 @@ func (wm *WatchManager) createDirWatch(dir string, recursive bool) error { return nil } +func (wm *WatchManager) createDirWatchRequest(dir string, entry *watchedDir) WatchDirectoryRequest { + return WatchDirectoryRequest{ + Dir: dir, + Recursive: entry.recursive, + Ignore: ShouldIgnoreWatchPath, + Callback: func(events []fswatch.Event, err error) { + if err != nil && errors.Is(err, fswatch.ErrWatchTerminated) { + wm.handleWatchTerminated(dir, entry) + return + } + wm.onWatchEvents(events, err) + }, + } +} + func (wm *WatchManager) ResolveDesiredDirs(desiredDirs map[string]bool) map[string]bool { resolved := make(map[string]bool, len(desiredDirs)) for dir, recursive := range desiredDirs { @@ -229,7 +243,9 @@ func (wm *WatchManager) ReconcileWatches(desiredDirs map[string]bool) error { return nil } - var watchErr error + var additions []dirWatchUpdate + var changes []dirWatchUpdate + core.DiffMapsFunc( wm.watchedDirs, desiredDirs, @@ -238,9 +254,7 @@ func (wm *WatchManager) ReconcileWatches(desiredDirs map[string]bool) error { if wm.DebugLog != nil { fmt.Fprintf(wm.DebugLog, "[watch] watching directory %s (recursive=%v)\n", dir, recursive) } - if err := wm.createDirWatch(dir, recursive); err != nil && watchErr == nil { - watchErr = err - } + additions = append(additions, dirWatchUpdate{dir: dir, recursive: recursive}) }, func(dir string, wd *watchedDir) { if wm.DebugLog != nil { @@ -255,12 +269,41 @@ func (wm *WatchManager) ReconcileWatches(desiredDirs map[string]bool) error { } wd.closer.Close() delete(wm.watchedDirs, dir) - if err := wm.createDirWatch(dir, recursive); err != nil && watchErr == nil { - watchErr = err - } + changes = append(changes, dirWatchUpdate{dir: dir, recursive: recursive}) }, ) - return watchErr + additions = append(additions, changes...) + return wm.createDirWatches(additions) +} + +func (wm *WatchManager) createDirWatches(updates []dirWatchUpdate) error { + if len(updates) == 0 { + return nil + } + requests := make([]WatchDirectoryRequest, len(updates)) + entries := make([]*watchedDir, len(updates)) + for i, update := range updates { + entry := &watchedDir{recursive: update.recursive} + entries[i] = entry + requests[i] = wm.createDirWatchRequest(update.dir, entry) + } + closers, err := wm.backend.WatchDirectories(requests) + if err != nil { + for i, update := range updates { + if wm.DebugLog != nil { + fmt.Fprintf(wm.DebugLog, "[watch] failed to watch directory %s: %v\n", update.dir, err) + } + if i < len(closers) && closers[i] != nil { + closers[i].Close() + } + } + return err + } + for i, update := range updates { + entries[i].closer = closers[i] + wm.watchedDirs[update.dir] = entries[i] + } + return nil } func IsDirCoveredByWatch(dirs map[string]bool, dir string, opts tspath.ComparePathsOptions) bool { @@ -269,7 +312,7 @@ func IsDirCoveredByWatch(dirs map[string]bool, dir string, opts tspath.ComparePa if tspath.ContainsPath(wdir, dir, opts) { return true } - } else if dir == wdir { + } else if tspath.ComparePaths(dir, wdir, opts) == 0 { return true } } diff --git a/internal/format/scanner.go b/internal/format/scanner.go index ef9ab0d7270..73a5d098172 100644 --- a/internal/format/scanner.go +++ b/internal/format/scanner.go @@ -118,11 +118,29 @@ func shouldRescanJsxIdentifier(node *ast.Node) bool { ast.KindJsxNamespacedName: // May parse an identifier like `module-layout`; that will be scanned as a keyword at first, but we should parse the whole thing to get an identifier. return ast.IsKeywordKind(node.Kind) || node.Kind == ast.KindIdentifier + case ast.KindPropertyAccessExpression: + // The leftmost name of a dotted JSX tag name (e.g. `a-b` in ``) may contain hyphens, so rescan it as a JSX identifier. + return (ast.IsKeywordKind(node.Kind) || node.Kind == ast.KindIdentifier) && isLeftmostJsxTagName(node) } } return false } +func isLeftmostJsxTagName(node *ast.Node) bool { + return ast.FindAncestorOrQuit(node, func(n *ast.Node) ast.FindAncestorResult { + switch { + case n.Parent == nil: + return ast.FindAncestorQuit + case ast.IsJsxTagName(n): + return ast.FindAncestorTrue + case ast.IsPropertyAccessExpression(n.Parent) && n.Parent.Expression() == n: + return ast.FindAncestorFalse + default: + return ast.FindAncestorQuit + } + }) != nil +} + func (s *formattingScanner) shouldRescanJsxText(node *ast.Node) bool { if ast.IsJsxText(node) { return true diff --git a/internal/fourslash/_scripts/convertFourslash.mts b/internal/fourslash/_scripts/convertFourslash.mts index 9c25c520f66..ab9d9596254 100755 --- a/internal/fourslash/_scripts/convertFourslash.mts +++ b/internal/fourslash/_scripts/convertFourslash.mts @@ -2695,6 +2695,32 @@ function parseOrganizeImportsArgs(args: readonly ts.Expression[]): [VerifyOrgani throw new Error(`Unsupported value for organizeImportsIgnoreCase: ${propValue.getText()}`); } } + else if (propName === "organizeImportsSort") { + if (ts.isStringLiteral(propValue)) { + switch (propValue.text) { + case "auto": + prefsFields.push(`${goFieldName}: lsutil.OrganizeImportsSortAuto`); + break; + case "ordinal": + prefsFields.push(`${goFieldName}: lsutil.OrganizeImportsSortOrdinal`); + break; + case "ordinalIgnoreCase": + prefsFields.push(`${goFieldName}: lsutil.OrganizeImportsSortOrdinalIgnoreCase`); + break; + case "natural": + prefsFields.push(`${goFieldName}: lsutil.OrganizeImportsSortNatural`); + break; + case "naturalIgnoreCase": + prefsFields.push(`${goFieldName}: lsutil.OrganizeImportsSortNaturalIgnoreCase`); + break; + default: + throw new Error(`Unsupported value for organizeImportsSort: ${propValue.text}`); + } + } + else { + throw new Error(`Expected string literal for organizeImportsSort, got ${propValue.getText()}`); + } + } else if (propName === "organizeImportsCollation") { if (ts.isStringLiteral(propValue)) { if (propValue.text === "unicode") { diff --git a/internal/fourslash/_scripts/manualTests.txt b/internal/fourslash/_scripts/manualTests.txt index 05618afd339..31d174381bb 100644 --- a/internal/fourslash/_scripts/manualTests.txt +++ b/internal/fourslash/_scripts/manualTests.txt @@ -110,6 +110,8 @@ navto_excludeLib3 navto_excludeLib4 navto_serverExcludeLib nodeModulesImportCompletions1 +organizeImportsPathsUnicode3 +organizeImportsUnicode3 outliningForNonCompleteInterfaceDeclaration outliningHintSpansForFunction overloadOnConstCallSignature diff --git a/internal/fourslash/fourslash.go b/internal/fourslash/fourslash.go index e1b51d15438..625c76b7304 100644 --- a/internal/fourslash/fourslash.go +++ b/internal/fourslash/fourslash.go @@ -242,8 +242,8 @@ func (f *FourslashTest) handleServerRequest(_ context.Context, req *lsproto.Requ // Return current user preferences for each requested section. // The server requests multiple sections (js/ts, typescript, javascript, editor); // we return user preferences for "js/ts" and nil for others. - params, ok := req.Params.(*lsproto.ConfigurationParams) - if !ok || params == nil || params.Items == nil { + params, err := lsproto.UnmarshalParams[*lsproto.ConfigurationParams](req) + if err != nil || params == nil || params.Items == nil { return &lsproto.ResponseMessage{ ID: req.ID, JSONRPC: req.JSONRPC, @@ -1098,7 +1098,10 @@ func (f *FourslashTest) VerifyCompletions(t *testing.T, markerInput MarkerInput, if item == nil { t.Fatalf("Code action '%s' from source '%s' not found in completions.", expectedAction.Name, expectedAction.Source) } - assert.Check(t, strings.Contains(*item.Detail, expectedAction.Description), "Completion item detail does not contain expected description.") + // Detail and AdditionalTextEdits for auto-import items are populated by + // completionItem/resolve, not in the initial completion list. + item = f.resolveCompletionItem(t, item) + assert.Check(t, item.Detail != nil && strings.Contains(*item.Detail, expectedAction.Description), "Completion item detail does not contain expected description.") f.applyTextEdits(t, *item.AdditionalTextEdits) assert.Equal(t, f.getScriptInfo(f.activeFilename).content, expectedAction.NewFileContent, fmt.Sprintf("File content after applying code action '%s' did not match expected content.", expectedAction.Name)) }, @@ -2532,7 +2535,7 @@ func (f *FourslashTest) verifyBaselineDefinitions( } else if result.DefinitionLinks != nil { var originRange *lsproto.Range resultAsSpans = core.Map(*result.DefinitionLinks, func(link *lsproto.LocationLink) documentSpan { - if originRange != nil && originRange != link.OriginSelectionRange { + if originRange != nil && (link.OriginSelectionRange == nil || *originRange != *link.OriginSelectionRange) { panic("multiple different origin ranges in definition links") } originRange = link.OriginSelectionRange @@ -5487,18 +5490,22 @@ func (f *FourslashTest) VerifyBaselineDocumentSymbol(t *testing.T) { } result := sendRequest(t, f, lsproto.TextDocumentDocumentSymbolInfo, params) uri := lsconv.FileNameToDocumentURI(f.activeFilename) - spansToSymbol := make(map[documentSpan]*lsproto.DocumentSymbol) + symbolBySpan := make(map[documentSpanKey]*lsproto.DocumentSymbol) if result.DocumentSymbols != nil { for _, symbol := range *result.DocumentSymbols { - collectDocumentSymbolSpans(uri, symbol, spansToSymbol) + collectDocumentSymbolSpans(uri, symbol, symbolBySpan) } } + spans := make([]documentSpan, 0, len(symbolBySpan)) + for key, symbol := range symbolBySpan { + spans = append(spans, documentSpan{uri: key.uri, textSpan: key.textSpan, contextSpan: &symbol.Range}) + } f.addResultToBaseline( t, documentSymbolsCmd, - f.getBaselineForSpansWithFileContents(slices.Collect(maps.Keys(spansToSymbol)), baselineFourslashLocationsOptions{ + f.getBaselineForSpansWithFileContents(spans, baselineFourslashLocationsOptions{ getLocationData: func(span documentSpan) string { - symbol := spansToSymbol[span] + symbol := symbolBySpan[documentSpanKey{uri: span.uri, textSpan: span.textSpan, contextSpan: *span.contextSpan}] return fmt.Sprintf("{| name: %s, kind: %s |}", symbol.Name, symbol.Kind.String()) }, }), @@ -5523,21 +5530,32 @@ func writeDocumentSymbolDetails(symbols []*lsproto.DocumentSymbol, indent int, b func collectDocumentSymbolSpans( uri lsproto.DocumentUri, symbol *lsproto.DocumentSymbol, - spansToSymbol map[documentSpan]*lsproto.DocumentSymbol, + symbolBySpan map[documentSpanKey]*lsproto.DocumentSymbol, ) { - span := documentSpan{ - uri: uri, - textSpan: symbol.SelectionRange, - contextSpan: &symbol.Range, + // Deduplicate by value rather than by the documentSpan key, which holds a pointer to + // the symbol's Range. The same logical symbol can be reached more than once + // (e.g. a merged declaration), and depending on transport those occurrences may + // be the same object (shared *Range) or independent copies (distinct *Range + // after a JSON round-trip). A value-based key collapses them consistently. + key := documentSpanKey{uri: uri, textSpan: symbol.SelectionRange, contextSpan: symbol.Range} + if _, ok := symbolBySpan[key]; !ok { + symbolBySpan[key] = symbol } - spansToSymbol[span] = symbol if symbol.Children != nil { for _, child := range *symbol.Children { - collectDocumentSymbolSpans(uri, child, spansToSymbol) + collectDocumentSymbolSpans(uri, child, symbolBySpan) } } } +// documentSpanKey is a value-comparable variant of documentSpan used to deduplicate +// document symbols regardless of pointer identity. +type documentSpanKey struct { + uri lsproto.DocumentUri + textSpan lsproto.Range + contextSpan lsproto.Range +} + // VerifyNumberOfErrorsInCurrentFile verifies that the current file has the expected number of errors. func (f *FourslashTest) VerifyNumberOfErrorsInCurrentFile(t *testing.T, expectedCount int) { diagnostics := f.getDiagnostics(t, f.activeFilename) diff --git a/internal/fourslash/tests/formatJsxDottedTagName_test.go b/internal/fourslash/tests/formatJsxDottedTagName_test.go new file mode 100644 index 00000000000..1679d0e31c7 --- /dev/null +++ b/internal/fourslash/tests/formatJsxDottedTagName_test.go @@ -0,0 +1,27 @@ +package fourslash_test + +import ( + "testing" + + "github.com/microsoft/typescript-go/internal/fourslash" + "github.com/microsoft/typescript-go/internal/testutil" +) + +func TestFormatJsxDottedTagName(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `//@Filename: file.tsx +const x = ( + + + +);` + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.FormatDocument(t, "") + f.VerifyCurrentFileContent(t, `const x = ( + + + +);`) +} diff --git a/internal/fourslash/tests/gen/organizeImportsPathsUnicode3_test.go b/internal/fourslash/tests/manual/organizeImportsPathsUnicode3_test.go similarity index 86% rename from internal/fourslash/tests/gen/organizeImportsPathsUnicode3_test.go rename to internal/fourslash/tests/manual/organizeImportsPathsUnicode3_test.go index 2f9260c263b..41f38684401 100644 --- a/internal/fourslash/tests/gen/organizeImportsPathsUnicode3_test.go +++ b/internal/fourslash/tests/manual/organizeImportsPathsUnicode3_test.go @@ -1,6 +1,3 @@ -// Code generated by convertFourslash; DO NOT EDIT. -// To modify this test, run "npm run makemanual organizeImportsPathsUnicode3" - package fourslash_test import ( @@ -14,7 +11,6 @@ import ( ) func TestOrganizeImportsPathsUnicode3(t *testing.T) { - fourslash.SkipIfFailing(t) t.Parallel() defer testutil.RecoverAndFail(t, "Panic on fourslash test") const content = `import * as B from "./B"; @@ -25,8 +21,8 @@ console.log(A, À, B);` f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) defer done() f.VerifyOrganizeImports(t, - `import * as À from "./À"; -import * as A from "./A"; + `import * as A from "./A"; +import * as À from "./À"; import * as B from "./B"; console.log(A, À, B);`, diff --git a/internal/fourslash/tests/gen/organizeImportsUnicode3_test.go b/internal/fourslash/tests/manual/organizeImportsUnicode3_test.go similarity index 89% rename from internal/fourslash/tests/gen/organizeImportsUnicode3_test.go rename to internal/fourslash/tests/manual/organizeImportsUnicode3_test.go index 97975f81edf..ae1ce80db39 100644 --- a/internal/fourslash/tests/gen/organizeImportsUnicode3_test.go +++ b/internal/fourslash/tests/manual/organizeImportsUnicode3_test.go @@ -1,6 +1,3 @@ -// Code generated by convertFourslash; DO NOT EDIT. -// To modify this test, run "npm run makemanual organizeImportsUnicode3" - package fourslash_test import ( @@ -14,7 +11,6 @@ import ( ) func TestOrganizeImportsUnicode3(t *testing.T) { - fourslash.SkipIfFailing(t) t.Parallel() defer testutil.RecoverAndFail(t, "Panic on fourslash test") const content = `import { @@ -28,8 +24,8 @@ console.log(A, À, B);` defer done() f.VerifyOrganizeImports(t, `import { - À, A, + À, B, } from './foo'; diff --git a/internal/fourslash/tests/organizeImports_coalesceExports_test.go b/internal/fourslash/tests/organizeImports_coalesceExports_test.go index e744b03aac3..c0dfddc9683 100644 --- a/internal/fourslash/tests/organizeImports_coalesceExports_test.go +++ b/internal/fourslash/tests/organizeImports_coalesceExports_test.go @@ -3,7 +3,6 @@ package fourslash_test import ( "testing" - "github.com/microsoft/typescript-go/internal/core" "github.com/microsoft/typescript-go/internal/fourslash" "github.com/microsoft/typescript-go/internal/ls/lsutil" "github.com/microsoft/typescript-go/internal/lsp/lsproto" @@ -22,7 +21,7 @@ void 0;` `export { B, default as M, a as n, Z as O, y } from "lib"; void 0;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -39,7 +38,7 @@ void 0;` `export * from "lib"; void 0;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -58,7 +57,7 @@ void 0;` export { x, z as y }; void 0;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -75,7 +74,7 @@ void 0;` `export { x, y as z } from "lib"; void 0;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -96,7 +95,7 @@ export * from "lib"; export { y } from "lib"; void 0;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -116,7 +115,7 @@ void 0;` export { z as default, q as w, x, w as y }; void 0;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -135,7 +134,7 @@ void 0;` export { x as a, z as b, y } from "lib"; void 0;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -160,7 +159,7 @@ export { x }; export type { y }; void 0;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -181,6 +180,6 @@ type y = number; export type { x, y }; void 0;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } diff --git a/internal/fourslash/tests/organizeImports_coalesceImports_test.go b/internal/fourslash/tests/organizeImports_coalesceImports_test.go index fe0af8a4e76..17ebba013f2 100644 --- a/internal/fourslash/tests/organizeImports_coalesceImports_test.go +++ b/internal/fourslash/tests/organizeImports_coalesceImports_test.go @@ -3,7 +3,6 @@ package fourslash_test import ( "testing" - "github.com/microsoft/typescript-go/internal/core" "github.com/microsoft/typescript-go/internal/fourslash" "github.com/microsoft/typescript-go/internal/ls/lsutil" "github.com/microsoft/typescript-go/internal/lsp/lsproto" @@ -22,7 +21,7 @@ M; n; B; y; O;` `import { B, default as M, a as n, Z as O, y } from "lib"; M; n; B; y; O;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -39,7 +38,7 @@ void 0;` `import "lib"; void 0;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -60,7 +59,7 @@ import * as x from "lib"; import * as y from "lib"; x; y; z;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -77,7 +76,7 @@ x; y;` `import { default as x, default as y } from "lib"; x; y;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -94,7 +93,7 @@ x; z;` `import { x, y as z } from "lib"; x; z;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -115,7 +114,7 @@ import "lib"; import * as x from "lib"; x; z;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -136,7 +135,7 @@ import "lib"; import x from "lib"; x; z;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -157,7 +156,7 @@ import "lib"; import { x } from "lib"; x; z;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -175,7 +174,7 @@ x; y;` `import y, * as x from "lib"; x; y;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -196,7 +195,7 @@ import * as x from "lib"; import { y } from "lib"; x; y; z;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -214,7 +213,7 @@ x; y;` `import x, { y } from "lib"; x; y;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -240,7 +239,7 @@ import * as y from "lib"; import { a, b, default as w, default as z } from "lib"; w; x; y; z; a; b;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -263,7 +262,7 @@ import * as y from "lib"; import z from "lib"; x; y; z; w;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -283,7 +282,7 @@ x; y; z;` import { z } from "lib"; x; y; z;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -304,7 +303,7 @@ import type z from "lib"; import type { x } from "lib"; x; y; z;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -321,8 +320,8 @@ z; y; x; c; b; a;` z; y; x; c; b; a;`, lsproto.CodeActionKindSourceSortImports, &lsutil.UserPreferences{ - OrganizeImportsIgnoreCase: core.TSTrue, - OrganizeImportsTypeOrder: lsutil.OrganizeImportsTypeOrderInline, + OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase, + OrganizeImportsTypeOrder: lsutil.OrganizeImportsTypeOrderInline, }, ) } diff --git a/internal/fourslash/tests/organizeImports_sortModuleSpecifiers_test.go b/internal/fourslash/tests/organizeImports_sortModuleSpecifiers_test.go index 350c7186119..b3eff84f6d6 100644 --- a/internal/fourslash/tests/organizeImports_sortModuleSpecifiers_test.go +++ b/internal/fourslash/tests/organizeImports_sortModuleSpecifiers_test.go @@ -3,7 +3,6 @@ package fourslash_test import ( "testing" - "github.com/microsoft/typescript-go/internal/core" "github.com/microsoft/typescript-go/internal/fourslash" "github.com/microsoft/typescript-go/internal/ls/lsutil" "github.com/microsoft/typescript-go/internal/lsp/lsproto" @@ -24,7 +23,7 @@ x; y;` import x from "lib2"; x; y;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -42,7 +41,7 @@ x; y;` import x from "./lib2"; x; y;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -60,7 +59,7 @@ x; y;` import x from "./lib"; x; y;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -79,7 +78,7 @@ x; y;` import x from "Z"; x; y;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } @@ -98,6 +97,6 @@ x; y;` import x from "z"; x; y;`, lsproto.CodeActionKindSourceSortImports, - &lsutil.UserPreferences{OrganizeImportsIgnoreCase: core.TSTrue}, + &lsutil.UserPreferences{OrganizeImportsSort: lsutil.OrganizeImportsSortOrdinalIgnoreCase}, ) } diff --git a/internal/fourslash/tests/renameNamedImportUseAliasesForRenames_test.go b/internal/fourslash/tests/renameNamedImportUseAliasesForRenames_test.go new file mode 100644 index 00000000000..67755250920 --- /dev/null +++ b/internal/fourslash/tests/renameNamedImportUseAliasesForRenames_test.go @@ -0,0 +1,50 @@ +package fourslash_test + +import ( + "testing" + + "github.com/microsoft/typescript-go/internal/core" + "github.com/microsoft/typescript-go/internal/fourslash" + "github.com/microsoft/typescript-go/internal/ls/lsutil" + "github.com/microsoft/typescript-go/internal/testutil" +) + +func TestRenameNamedImportUseAliasesForRenames(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @Filename: /a.ts +import { /*import*/MyTypeA } from "./b"; +const type: MyTypeA = { foo: "bar" }; +// @Filename: /b.ts +export interface MyTypeA { + foo: string; +}` + + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyBaselineRename(t, &lsutil.UserPreferences{UseAliasesForRename: core.TSFalse}, "import") + f.VerifyBaselineRename(t, &lsutil.UserPreferences{UseAliasesForRename: core.TSTrue}, "import") +} + +func TestRenameNamedImportDefaultInNodeModules(t *testing.T) { + t.Parallel() + defer testutil.RecoverAndFail(t, "Panic on fourslash test") + const content = `// @Filename: /index.ts +import { /*fooImport*/[|Foo|] } from "foo"; +declare const f: Foo; +// @Filename: /tsconfig.json +{} +// @Filename: /node_modules/foo/package.json +{ "types": "index.d.ts" } +// @Filename: /node_modules/foo/index.d.ts +export interface Foo { + bar: string; +}` + + f, done := fourslash.NewFourslash(t, nil /*capabilities*/, content) + defer done() + f.VerifyBaselineRename(t, nil /*preferences*/, "fooImport") + f.VerifyBaselineRename(t, &lsutil.UserPreferences{UseAliasesForRename: core.TSTrue}, "fooImport") + f.GoToMarker(t, "fooImport") + f.VerifyRenameFailed(t, &lsutil.UserPreferences{UseAliasesForRename: core.TSFalse}) +} diff --git a/internal/fswatch/CHANGES.md b/internal/fswatch/CHANGES.md index 01ecfd975d5..5c91172827f 100644 --- a/internal/fswatch/CHANGES.md +++ b/internal/fswatch/CHANGES.md @@ -9,11 +9,12 @@ simplifications, new features, and bugfixes. ### Method naming -| C++ / JS | Go | -| ---------------------- | ---------------------------------- | -| `subscribe(dir, fn)` | `WatchDirectory(dir, fn, opts...)` | -| — | `WatchFile(path, fn)` | -| `unsubscribe(dir, fn)` | `w.Close()` | +| C++ / JS | Go | +| ---------------------- | ------------------------------------------- | +| `subscribe(dir, fn)` | `WatchDirectory(dir, fn, opts...)` | +| — | `WatchDirectories([]WatchDirectoryRequest)` | +| — | `WatchFile(path, fn)` | +| `unsubscribe(dir, fn)` | `w.Close()` | ### Recursion default @@ -55,6 +56,13 @@ Go adds functional options not present in the C++ API: non-recursively and filtering events to the target path. Multiple file watches in the same directory share one OS watch. Not available in the C++ API. +### Batch directory watching + +`WatchDirectories` registers multiple directory watches in one call. It has the +same logical behavior as repeated `WatchDirectory` calls, but lets backends batch +the underlying OS subscription work. On macOS this avoids rebuilding the shared +FSEvents stream once per logical watch during large watch reconciliations. + ### Error delivery C++ delivers errors via a separate error callback or return value. Go delivers @@ -127,6 +135,16 @@ can't starve event delivery on any of the others. In practice most callers will only ever use one backend (`Default()`), so this mainly matters for processes that mix backends, but the cost of the split is essentially nothing. +### Shared FSEvents streams + +Upstream opens one macOS FSEventStream per subscription. Go's FSEvents backend +shares streams across all logical directory watches in a backend instance. The +fast path attempts one stream containing every active physical watch root; if +that stream cannot be started, the backend retries with bounded path chunks. +Events from shared streams are routed back to matching logical watches by path, +so non-recursive and per-subscriber ignore semantics are preserved while using +far fewer system-wide FSEvents stream slots. + ## New backends **fanotify** (Linux, kernel ≥ 5.13) is the default on Linux when available. It diff --git a/internal/fswatch/fsevents_darwin.go b/internal/fswatch/fsevents_darwin.go index fe99bd1f36b..313df74f39f 100644 --- a/internal/fswatch/fsevents_darwin.go +++ b/internal/fswatch/fsevents_darwin.go @@ -7,6 +7,9 @@ import ( "fmt" "os" "runtime" + "slices" + "sort" + "sync" "sync/atomic" "syscall" "unsafe" @@ -31,13 +34,14 @@ import ( // │ fsEventsBackend │ // │ (no event loop; start() just signals readiness) │ // │ │ -// │ subscribe() per directory: │ +// │ subscribe/closeWatch rebuild the shared stream set: │ // │ │ │ // │ ▼ │ // │ ┌─────────────────────────────────────────────────────┐ │ -// │ │ fseventsState │ │ +// │ │ fseventsStream[] │ │ // │ │ │ │ -// │ │ FSEventStream ──► per-stream GCD dispatch queue │ │ +// │ │ each FSEventStream watches up to N paths ────────► │ │ +// │ │ per-stream GCD dispatch queue │ │ // │ │ (UseCFTypes | FileEvents = 0x11) │ │ // │ │ │ │ // │ │ callback fires on GCD thread: │ │ @@ -60,15 +64,14 @@ import ( // that GCD thread in the C calling convention. It never enters Go ABI. // It retains/copies the callback payload and passes it to Go through // eventPipe. -// - One Go goroutine per stream (eventLoop, in fsevents_darwin_ffi.go) +// - One Go goroutine per stream chunk (eventLoop, in fsevents_darwin_ffi.go) // blocks on eventFile.Read(), integrated with Go's netpoll so it parks -// without consuming an OS thread. When woken by the asm callback, it -// calls fsEventsCallback() to classify events and post them to the -// dirWatch's eventList. -// - subscribe/closeWatch and stream lifecycle (startStream/stopStream) -// run on the caller's goroutine under watcherBase.mu. Stream teardown -// uses atomic.Swap on the stream pointer so that only one of -// (Close, callback's deleted-root path) performs cleanup. +// without consuming an OS thread. When woken by the asm callback, it calls +// fsEventsCallback() to classify events and route them to matching +// dirWatch event lists. +// - subscribe/closeWatch rebuild the stream chunks on the caller's goroutine +// under watcherBase.mu. Old streams are swapped out before teardown so a +// callback cannot deadlock against stream teardown while routing events. // // Callback delivery: // dirWatch.notify() posts to the shared process-wide debouncer. After a @@ -79,11 +82,11 @@ import ( // per-subscriber before delivery. // // WatchDirectory flow (caller goroutine): -// subscribe → startStream: create an FSEventStream with -// kFSEventStreamEventIdSinceNow and start it on its own serial GCD -// queue. No directory walk or tree is needed; FSEvents watches -// recursively via the kernel, and event classification uses only the -// flags. +// subscribe/closeWatch snapshots active dirWatches and creates one or more +// FSEventStreams with kFSEventStreamEventIdSinceNow. Each stream receives a +// chunk of physical watch roots. No directory walk or tree is needed; +// FSEvents watches recursively via the kernel, and event classification uses +// only the flags. // // Event classification (fsEventsCallback, on eventLoop goroutine): // Each batch delivers arrays of paths, flags, and event IDs. The flags @@ -97,8 +100,9 @@ import ( // flagMustScanSubDirs → ErrOverflow with detail (user/kernel/too-many). // // Root deletion: -// Detected in the callback; cb.closed is set so future callbacks are -// no-ops. Stream teardown is deferred to Close. +// Detected in the callback; the logical watch is marked terminated and +// receives ErrWatchTerminated. The shared stream remains active for other +// watches until the owner closes or reconciles the terminated watch. // --------------------------------------------------------------------------- // ----- FSEvents flag bits (from FSEvents.h) ------------------------------ @@ -154,12 +158,11 @@ type fsEventStreamContext struct { copyDescription uintptr } -// fseventsState. -// -// stream is claimed by Close with an atomic Swap. Root deletion is detected in -// the callback, but teardown is deferred to Close because the assembly callback -// is still waiting on the done pipe while fsEventsCallback runs. type fseventsState struct { + terminated atomic.Bool +} + +type fseventsStream struct { stream atomic.Uintptr cb *streamCallback pinner runtime.Pinner @@ -170,6 +173,10 @@ type fseventsState struct { // fsEventsBackend. type fsEventsBackend struct { watcherBase + + mu sync.Mutex + watches map[*dirWatch]*fseventsState + streams []*fseventsStream } func init() { @@ -177,7 +184,9 @@ func init() { } func newFSEventsBackend() *fsEventsBackend { - b := &fsEventsBackend{} + b := &fsEventsBackend{ + watches: make(map[*dirWatch]*fseventsState), + } b.watcherBase.init(b) return b } @@ -200,9 +209,10 @@ func checkWatcher(w *dirWatch) error { } var ( - errMissingFSEventsState = errors.New("fsevents: missing state") - errStreamCreateNull = errors.New("FSEventStreamCreate returned NULL") - errStreamStartFailed = errors.New("error starting FSEvents stream") + errCFStringCreateNull = errors.New("CFStringCreate returned NULL") + errCFArrayCreateNull = errors.New("CFArrayCreate returned NULL") + errStreamCreateNull = errors.New("FSEventStreamCreate returned NULL") + errStreamStartFailed = errors.New("error starting FSEvents stream") ) var ( @@ -211,31 +221,114 @@ var ( errFSEventsTooMany = fmt.Errorf("too many events: %w", ErrOverflow) ) -// startStream creates and starts an FSEventStream on its per-stream -// serial dispatch queue. -func (b *fsEventsBackend) startStream(w *dirWatch, since uint64) error { - if err := checkWatcher(w); err != nil { - return err +const fseventsPathsPerStream = 512 + +type fseventsWatchSnapshot struct { + w *dirWatch + state *fseventsState +} + +func (b *fsEventsBackend) activeWatchesLocked() []fseventsWatchSnapshot { + watches := make([]fseventsWatchSnapshot, 0, len(b.watches)) + for w, state := range b.watches { + if state.terminated.Load() { + continue + } + watches = append(watches, fseventsWatchSnapshot{w: w, state: state}) } + return watches +} - state, _ := w.state.(*fseventsState) - if state == nil { - return errMissingFSEventsState +func (b *fsEventsBackend) startStreams(watches []fseventsWatchSnapshot) ([]*fseventsStream, error) { + return startFSEventsStreams(watches, b.startStream) +} + +func startFSEventsStreams(watches []fseventsWatchSnapshot, startStream func([]string, []fseventsWatchSnapshot) (*fseventsStream, error)) ([]*fseventsStream, error) { + if len(watches) == 0 { + return nil, nil + } + seen := make(map[string]struct{}, len(watches)) + paths := make([]string, 0, len(watches)) + for _, watch := range watches { + path := watch.w.physicalDir + if _, ok := seen[path]; ok { + continue + } + seen[path] = struct{}{} + paths = append(paths, path) + } + sort.Strings(paths) + + stream, err := startStream(paths, watches) + if err == nil { + return []*fseventsStream{stream}, nil } - dirCStr := append([]byte(w.physicalDir), 0) - cfDir := cfStringCreate(0, unsafe.Pointer(&dirCStr[0]), cfStringEncodingUTF8) - defer cfRelease(cfDir) + streams := make([]*fseventsStream, 0, (len(paths)+fseventsPathsPerStream-1)/fseventsPathsPerStream) + remainingPaths := paths + for len(remainingPaths) > 0 { + chunkLen := min(len(remainingPaths), fseventsPathsPerStream) + chunkPaths := remainingPaths[:chunkLen] + stream, err := startStream(chunkPaths, watchesForFSEventsPaths(watches, chunkPaths)) + if err != nil { + stopFSEventsStreams(streams) + return nil, err + } + streams = append(streams, stream) + remainingPaths = remainingPaths[chunkLen:] + } + return streams, nil +} + +func watchesForFSEventsPaths(watches []fseventsWatchSnapshot, paths []string) []fseventsWatchSnapshot { + if len(paths) == 0 { + return nil + } + filtered := make([]fseventsWatchSnapshot, 0, len(watches)) + for _, watch := range watches { + if _, ok := slices.BinarySearch(paths, watch.w.physicalDir); ok { + filtered = append(filtered, watch) + } + } + return filtered +} + +// startStream creates and starts one FSEventStream watching all supplied paths. +func (b *fsEventsBackend) startStream(paths []string, watches []fseventsWatchSnapshot) (*fseventsStream, error) { + if len(paths) == 0 { + return nil, nil + } - pathsToWatch := cfArrayCreate(0, unsafe.Pointer(&cfDir), 1, 0) + cfStrings := make([]uintptr, 0, len(paths)) + for _, path := range paths { + dirCStr := append([]byte(path), 0) + cfDir := cfStringCreate(0, unsafe.Pointer(&dirCStr[0]), cfStringEncodingUTF8) + if cfDir == 0 { + for _, cfString := range cfStrings { + cfRelease(cfString) + } + return nil, errCFStringCreateNull + } + cfStrings = append(cfStrings, cfDir) + } + defer func() { + for _, cfString := range cfStrings { + cfRelease(cfString) + } + }() + + pathsToWatch := cfArrayCreate(0, unsafe.Pointer(&cfStrings[0]), len(cfStrings), 0) + if pathsToWatch == 0 { + return nil, errCFArrayCreateNull + } defer cfRelease(pathsToWatch) - cb, err := newStreamCallback(w) + cb, err := newStreamCallback(watches) if err != nil { - return &dirWatchError{err: err, dirWatch: w} + return nil, err } + state := &fseventsStream{cb: cb} state.pinner.Pin(cb) - state.cb = cb ctx := fsEventStreamContext{info: uintptr(unsafe.Pointer(cb))} @@ -244,14 +337,14 @@ func (b *fsEventsBackend) startStream(w *dirWatch, since uint64) error { fsEventsCallbackAsmAddr, unsafe.Pointer(&ctx), pathsToWatch, - since, + eventIDSinceNow, 0.001, ) if stream == 0 { cb.close() state.cb = nil state.pinner.Unpin() - return &dirWatchError{err: errStreamCreateNull, dirWatch: w} + return nil, errStreamCreateNull } fsEventStreamSetDispatchQueue(stream, cb.queue) @@ -261,11 +354,11 @@ func (b *fsEventsBackend) startStream(w *dirWatch, since uint64) error { cb.close() state.cb = nil state.pinner.Unpin() - return &dirWatchError{err: errStreamStartFailed, dirWatch: w} + return nil, errStreamStartFailed } fsEventStreamFlushSync(stream) state.stream.Store(stream) - return nil + return state, nil } // teardownStream performs the full FSEventStream cleanup. Stop and Invalidate @@ -284,10 +377,15 @@ func teardownStream(stream uintptr, cb *streamCallback) { fsEventStreamRelease(stream) } -// stopStream tears down a stream if WatchDirectory successfully started one. // The atomic Swap gates teardown so concurrent or repeated calls are safe: // only the goroutine that observes a non-zero stream performs the cleanup. -func (b *fsEventsBackend) stopStream(state *fseventsState) { +func stopFSEventsStreams(streams []*fseventsStream) { + for _, stream := range streams { + stopFSEventsStream(stream) + } +} + +func stopFSEventsStream(state *fseventsStream) { if state == nil { return } @@ -303,9 +401,48 @@ func (b *fsEventsBackend) stopStream(state *fseventsState) { // subscribe mirrors `fsEventsBackend::subscribe`. func (b *fsEventsBackend) subscribe(w *dirWatch) error { - state := &fseventsState{} - w.state = state - return b.startStream(w, eventIDSinceNow) + return b.subscribeMany([]*dirWatch{w}) +} + +func (b *fsEventsBackend) subscribeMany(watchesToAdd []*dirWatch) error { + if len(watchesToAdd) == 0 { + return nil + } + states := make(map[*dirWatch]*fseventsState, len(watchesToAdd)) + for _, w := range watchesToAdd { + if err := checkWatcher(w); err != nil { + return err + } + states[w] = &fseventsState{} + } + + b.mu.Lock() + for w, state := range states { + w.state = state + b.watches[w] = state + } + watches := b.activeWatchesLocked() + b.mu.Unlock() + + streams, err := b.startStreams(watches) + if err != nil { + b.mu.Lock() + for w, state := range states { + if b.watches[w] == state { + delete(b.watches, w) + w.state = nil + } + } + b.mu.Unlock() + return &dirWatchError{err: err, dirWatch: watchesToAdd[0]} + } + + b.mu.Lock() + oldStreams := b.streams + b.streams = streams + b.mu.Unlock() + stopFSEventsStreams(oldStreams) + return nil } // closeWatch mirrors `fsEventsBackend::closeWatch`. @@ -315,7 +452,23 @@ func (b *fsEventsBackend) closeWatch(w *dirWatch) error { if state == nil { return nil } - b.stopStream(state) + state.terminated.Store(true) + + b.mu.Lock() + delete(b.watches, w) + watches := b.activeWatchesLocked() + b.mu.Unlock() + + streams, err := b.startStreams(watches) + if err != nil { + return err + } + + b.mu.Lock() + oldStreams := b.streams + b.streams = streams + b.mu.Unlock() + stopFSEventsStreams(oldStreams) return nil } @@ -328,10 +481,6 @@ func (b *fsEventsBackend) closeWatch(w *dirWatch) error { func fsEventsCallback(cb *streamCallback, payload *fsEventsCallbackPayload) { defer payload.close() - if cb.closed.Load() { - return - } - const ( flagSize = unsafe.Sizeof(uint32(0)) ) @@ -344,8 +493,8 @@ func fsEventsCallback(cb *streamCallback, payload *fsEventsCallbackPayload) { paths := payload.paths flags := payload.flags - w := cb.dirWatch - deletedRoot := false + watches := cb.watches + touched := map[*dirWatch]struct{}{} for i := range numEvents { flag := *(*uint32)(unsafe.Add(nil, flags+i*flagSize)) @@ -361,18 +510,27 @@ func fsEventsCallback(cb *streamCallback, payload *fsEventsCallbackPayload) { isDone := flag&flagHistoryDone != 0 if flag&flagMustScanSubDirs != 0 { + var overflow error switch { case flag&flagUserDropped != 0: - w.events.setError(errFSEventsUserDropped) + overflow = errFSEventsUserDropped case flag&flagKernelDropped != 0: - w.events.setError(errFSEventsKernelDropped) + overflow = errFSEventsKernelDropped default: - w.events.setError(errFSEventsTooMany) + overflow = errFSEventsTooMany + } + for _, watch := range watches { + if watch.state.terminated.Load() { + continue + } + if fseventsOverflowMatches(watch.w, path) { + watch.w.events.setError(overflow) + touched[watch.w] = struct{}{} + } } } if isDone { - w.notify() break } @@ -380,58 +538,77 @@ func fsEventsCallback(cb *streamCallback, payload *fsEventsCallbackPayload) { continue } - // Skip events for the watched directory itself unless it's been - // removed. fseventsd reports a change on the watched dir when a - // child is added or removed; subscribers observe changes *within* - // the directory, not the dir's own metadata churn. - // (A removal of the dir is still propagated because Watcher - // relies on it to tear down the stream.) rawPath := path - path = w.displayPath(path) + pathExists := false + pathExistsKnown := false - if path == w.dir && !isRemoved && !isRenamed { - continue - } + for _, watch := range watches { + if watch.state.terminated.Load() { + continue + } + w := watch.w + displayPath, ok := fseventsDisplayPath(w, rawPath) + if !ok { + continue + } - switch { - case isRemoved && !isCreated: - // Pure remove, or remove+rename: file is gone. - w.events.remove(path) - if path == w.dir { - deletedRoot = true + // Skip events for the watched directory itself unless it's been + // removed. fseventsd reports a change on the watched dir when a + // child is added or removed; subscribers observe changes *within* + // the directory, not the dir's own metadata churn. + // (A removal of the dir is still propagated because Watcher + // relies on it to tear down the stream.) + if displayPath == w.dir && !isRemoved && !isRenamed { + continue } - case isRenamed || (isRemoved && isCreated): - // Ambiguous: rename could mean moved away (delete) or - // moved in (update); remove+create could mean replaced. - // Stat to check existence. - var st unix.Stat_t - if unix.Lstat(rawPath, &st) != nil { - w.events.remove(path) - if path == w.dir { - deletedRoot = true + + switch { + case isRemoved && !isCreated: + w.events.remove(displayPath) + if displayPath == w.dir { + watch.state.terminated.Store(true) + w.events.setError(fmt.Errorf("%w: watched directory removed", ErrWatchTerminated)) + } + case isRenamed || (isRemoved && isCreated): + if !pathExistsKnown { + var st unix.Stat_t + pathExists = unix.Lstat(rawPath, &st) == nil + pathExistsKnown = true + } + if pathExists { + w.events.update(displayPath) + } else { + w.events.remove(displayPath) + if displayPath == w.dir { + watch.state.terminated.Store(true) + w.events.setError(fmt.Errorf("%w: watched directory removed", ErrWatchTerminated)) + } } - } else { - w.events.update(path) + default: + w.events.update(displayPath) } - default: - // Create, modify, or any other flag combo. - w.events.update(path) + touched[w] = struct{}{} } } - if deletedRoot { - // Surface ErrWatchTerminated alongside the delete event so the - // caller knows no further events will arrive. Stream teardown is - // still deferred to Close. - w.events.setError(fmt.Errorf("%w: watched directory removed", ErrWatchTerminated)) + for w := range touched { + w.notify() } +} - w.notify() +func fseventsDisplayPath(w *dirWatch, rawPath string) (string, bool) { + if isInDirectoryOrSelf(w.physicalDir, rawPath) { + return w.displayPath(rawPath), true + } + if w.physicalDir != w.dir && isInDirectoryOrSelf(w.dir, rawPath) { + return rawPath, true + } + return "", false +} - if deletedRoot { - // The watched root was deleted. Mark the callback as closed so - // future callbacks are no-ops. Stream teardown and pipe cleanup - // are deferred to Close. - cb.closed.Store(true) +func fseventsOverflowMatches(w *dirWatch, rawPath string) bool { + if isInDirectoryOrSelf(w.physicalDir, rawPath) || isInDirectoryOrSelf(rawPath, w.physicalDir) { + return true } + return w.physicalDir != w.dir && (isInDirectoryOrSelf(w.dir, rawPath) || isInDirectoryOrSelf(rawPath, w.dir)) } diff --git a/internal/fswatch/fsevents_darwin_ffi.go b/internal/fswatch/fsevents_darwin_ffi.go index cd580789602..43877c0c8b5 100644 --- a/internal/fswatch/fsevents_darwin_ffi.go +++ b/internal/fswatch/fsevents_darwin_ffi.go @@ -7,7 +7,7 @@ import ( "math" "os" "runtime" - "sync/atomic" + "slices" "syscall" "unsafe" @@ -75,7 +75,7 @@ import ( // asm: return to FSEvents fsEventsCallback(cb, payload) // classifies events, // frees payload, -// posts to dirWatch.events +// routes to matching dirWatch events // // The assembly callback never enters Go ABI; it stays entirely in C // context. One pipe per stream hands retained/copied callback payloads from @@ -452,8 +452,7 @@ type streamCallback struct { eventFile *os.File queue uintptr // per-stream serial dispatch queue done chan struct{} - dirWatch *dirWatch - closed atomic.Bool + watches []fseventsWatchSnapshot } type fsEventsCallbackPayload struct { @@ -478,7 +477,7 @@ func (p *fsEventsCallbackPayload) close() { // callbacks. The per-stream serial queue serializes this stream's callbacks // and prevents cross-stream head-of-line blocking that a process-wide serial // queue would cause. -func newStreamCallback(w *dirWatch) (*streamCallback, error) { +func newStreamCallback(watches []fseventsWatchSnapshot) (*streamCallback, error) { var eventPipe [2]int if err := unix.Pipe(eventPipe[:]); err != nil { return nil, err @@ -500,7 +499,7 @@ func newStreamCallback(w *dirWatch) (*streamCallback, error) { eventFile: os.NewFile(uintptr(eventPipe[0]), "fsevents-event"), queue: queue, done: make(chan struct{}), - dirWatch: w, + watches: slices.Clone(watches), } go cb.eventLoop() return cb, nil diff --git a/internal/fswatch/fsevents_darwin_shared_test.go b/internal/fswatch/fsevents_darwin_shared_test.go new file mode 100644 index 00000000000..1f03e9a2f6e --- /dev/null +++ b/internal/fswatch/fsevents_darwin_shared_test.go @@ -0,0 +1,200 @@ +//go:build darwin && (amd64 || arm64) + +package fswatch + +import ( + "fmt" + "os" + "path/filepath" + "slices" + "testing" + "time" +) + +func newTestFSEventsWatcher(impl **fsEventsBackend) Watcher { + return &watcher{ + name: "fsevents", + factory: func() watcherImpl { + *impl = newFSEventsBackend() + return *impl + }, + } +} + +func TestFSEventsSharedStreamAcrossWatches(t *testing.T) { + t.Parallel() + + var impl *fsEventsBackend + watcherImpl := newTestFSEventsWatcher(&impl) + root := newTmpDir(t) + + var subs []Watch + for i := range 5 { + dir := filepath.Join(root, fmt.Sprintf("dir%d", i)) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + sub, err := watcherImpl.WatchDirectory(dir, func([]Event, error) {}) + if err != nil { + t.Fatal(err) + } + subs = append(subs, sub) + } + t.Cleanup(func() { + for _, sub := range subs { + _ = sub.Close() + } + }) + + impl.mu.Lock() + streamCount := len(impl.streams) + watchCount := len(impl.watches) + impl.mu.Unlock() + if streamCount != 1 { + t.Fatalf("expected one shared FSEvents stream, got %d", streamCount) + } + if watchCount != len(subs) { + t.Fatalf("expected %d logical watches, got %d", len(subs), watchCount) + } +} + +func TestFSEventsSharedStreamRoutesEvents(t *testing.T) { + t.Parallel() + + var impl *fsEventsBackend + watcherImpl := newTestFSEventsWatcher(&impl) + root := newTmpDir(t) + dirA := filepath.Join(root, "a") + dirB := filepath.Join(root, "b") + if err := os.MkdirAll(dirA, 0o755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(dirB, 0o755); err != nil { + t.Fatal(err) + } + + time.Sleep(preSubscribeSleep(watcherImpl)) + recA := newRecorder(t) + recA.watcher = watcherImpl + subA, err := watcherImpl.WatchDirectory(dirA, recA.callback) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = subA.Close() }) + + recB := newRecorder(t) + recB.watcher = watcherImpl + subB, err := watcherImpl.WatchDirectory(dirB, recB.callback) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = subB.Close() }) + time.Sleep(settleSleep(watcherImpl)) + + fileA := filepath.Join(dirA, "file.ts") + if err := os.WriteFile(fileA, []byte("export {}"), 0o644); err != nil { + t.Fatal(err) + } + expectContains(t, recA, EventUpdate, fileA) + assertNoEventsForPath(t, recB.drainQuiet(500*time.Millisecond), fileA, "sibling watch saw event") + + fileB := filepath.Join(dirB, "file.ts") + if err := os.WriteFile(fileB, []byte("export {}"), 0o644); err != nil { + t.Fatal(err) + } + expectContains(t, recB, EventUpdate, fileB) + assertNoEventsForPath(t, recA.drainQuiet(500*time.Millisecond), fileB, "sibling watch saw event") +} + +func TestFSEventsSharedStreamFallsBackToChunks(t *testing.T) { + t.Parallel() + + const count = fseventsPathsPerStream*2 + 1 + watches := make([]fseventsWatchSnapshot, 0, count) + for i := range count { + watches = append(watches, fseventsWatchSnapshot{ + w: &dirWatch{physicalDir: fmt.Sprintf("/watch/dir%04d", i)}, + state: &fseventsState{}, + }) + } + + var calls []int + var watchCalls []int + streams, err := startFSEventsStreams(watches, func(paths []string, streamWatches []fseventsWatchSnapshot) (*fseventsStream, error) { + calls = append(calls, len(paths)) + watchCalls = append(watchCalls, len(streamWatches)) + if len(calls) == 1 { + return nil, errStreamStartFailed + } + return &fseventsStream{}, nil + }) + if err != nil { + t.Fatal(err) + } + if len(streams) != 3 { + t.Fatalf("expected 3 chunked streams, got %d", len(streams)) + } + wantCalls := []int{count, fseventsPathsPerStream, fseventsPathsPerStream, 1} + if !slices.Equal(calls, wantCalls) { + t.Fatalf("startStream calls = %v, want %v", calls, wantCalls) + } + if !slices.Equal(watchCalls, wantCalls) { + t.Fatalf("startStream watch calls = %v, want %v", watchCalls, wantCalls) + } +} + +func TestWatchesForFSEventsPaths(t *testing.T) { + t.Parallel() + + watchA := &dirWatch{physicalDir: "/watch/a"} + watchB := &dirWatch{physicalDir: "/watch/b"} + watchC := &dirWatch{physicalDir: "/watch/c"} + watches := []fseventsWatchSnapshot{ + {w: watchA, state: &fseventsState{}}, + {w: watchB, state: &fseventsState{}}, + {w: watchC, state: &fseventsState{}}, + } + + got := watchesForFSEventsPaths(watches, []string{"/watch/a", "/watch/c"}) + gotPaths := make([]string, 0, len(got)) + for _, watch := range got { + gotPaths = append(gotPaths, watch.w.physicalDir) + } + slices.Sort(gotPaths) + + want := []string{"/watch/a", "/watch/c"} + if !slices.Equal(gotPaths, want) { + t.Fatalf("watchesForFSEventsPaths = %v, want %v", gotPaths, want) + } +} + +func TestFSEventsOverflowMatchesWatch(t *testing.T) { + t.Parallel() + + w := &dirWatch{ + dir: "/logical/root", + physicalDir: "/physical/root", + } + cases := []struct { + name string + rawPath string + want bool + }{ + {name: "physical root", rawPath: "/physical/root", want: true}, + {name: "physical descendant", rawPath: "/physical/root/sub", want: true}, + {name: "physical ancestor", rawPath: "/physical", want: true}, + {name: "logical root", rawPath: "/logical/root", want: true}, + {name: "logical descendant", rawPath: "/logical/root/sub", want: true}, + {name: "logical ancestor", rawPath: "/logical", want: true}, + {name: "unrelated", rawPath: "/other/root", want: false}, + {name: "sibling prefix", rawPath: "/physical/root2", want: false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + if got := fseventsOverflowMatches(w, c.rawPath); got != c.want { + t.Fatalf("fseventsOverflowMatches(%q) = %v, want %v", c.rawPath, got, c.want) + } + }) + } +} diff --git a/internal/fswatch/watcher.go b/internal/fswatch/watcher.go index 1500417c3e4..490c7c43175 100644 --- a/internal/fswatch/watcher.go +++ b/internal/fswatch/watcher.go @@ -67,6 +67,11 @@ type Watcher interface { // Returns [ErrUnavailable] if the watcher is not supported on // the current platform. WatchDirectory(dir string, fn WatchCallback, opts ...WatchOption) (Watch, error) + // WatchDirectories watches multiple directories as a batch. It has the + // same semantics as calling [Watcher.WatchDirectory] for each request, but + // lets backends arm the underlying OS watches once for the whole batch. + // Returned watches are in the same order as requests. + WatchDirectories(requests []WatchDirectoryRequest) ([]Watch, error) // WatchFile watches a single file for changes, calling fn with // batched events. path must be an absolute path. The file does not // need to exist at subscribe time; its creation will be reported. @@ -93,6 +98,14 @@ type WatchOption interface { applyWatchOption(opts *watchOptions) } +// WatchDirectoryRequest describes one directory subscription in a +// [Watcher.WatchDirectories] batch. +type WatchDirectoryRequest struct { + Dir string + Callback WatchCallback + Options []WatchOption +} + type watchOptions struct { ignore func(path string) bool recursive bool @@ -221,6 +234,8 @@ type watcher struct { debounce *debounce // lazily created in getOrCreateDirWatch } +const recursiveConsolidateThreshold = 10 + func (w *watcher) Name() string { return w.name } func (w *watcher) String() string { return w.name } func (w *watcher) Available() bool { return w.factory != nil } @@ -236,6 +251,10 @@ func (w *watcher) HasFastRecursiveBackend() bool { } } +func (w *watcher) canShareRecursiveDirWatches() bool { + return w.name == "fsevents" +} + func (w *watcher) getImpl() (watcherImpl, error) { w.mu.Lock() if w.impl != nil { @@ -266,6 +285,54 @@ func (w *watcher) getImpl() (watcherImpl, error) { return impl, nil } +func (w *watcher) keyForDirWatch(dir string, recursive bool) string { + if recursive { + return dir + "\x00recursive" + } + return dir +} + +func (w *watcher) findCoveringRecursiveWatchLocked(dir string) *dirWatch { + var best *dirWatch + for _, dw := range w.dirWatches { + if !dw.recursive || !isInDirectoryOrSelf(dw.dir, dir) { + continue + } + if best == nil || len(dw.dir) > len(best.dir) { + best = dw + } + } + return best +} + +func (w *watcher) findConsolidationDirLocked(dir string) string { + if !w.canShareRecursiveDirWatches() { + return "" + } + parent := filepath.Dir(dir) + for parent != dir && parent != "." { + if filepath.Dir(parent) == parent { + break + } + count := 1 + for _, dw := range w.dirWatches { + if isInDirectoryOrSelf(parent, dw.dir) { + count++ + if count >= recursiveConsolidateThreshold { + return parent + } + } + } + next := filepath.Dir(parent) + if next == parent { + break + } + dir = parent + parent = next + } + return "" +} + func (w *watcher) getOrCreateDirWatch(dir string, physicalDir string, recursive bool) *dirWatch { w.mu.Lock() defer w.mu.Unlock() @@ -275,10 +342,22 @@ func (w *watcher) getOrCreateDirWatch(dir string, physicalDir string, recursive if w.debounce == nil { w.debounce = newDebounce() } - key := dir - if recursive { - key = dir + "\x00recursive" + + if w.canShareRecursiveDirWatches() { + if dw := w.findCoveringRecursiveWatchLocked(dir); dw != nil { + return dw + } + if consolidationDir := w.findConsolidationDirLocked(dir); consolidationDir != "" { + dir = consolidationDir + physicalDir = physicalDirFor(dir) + recursive = true + if dw := w.findCoveringRecursiveWatchLocked(dir); dw != nil { + return dw + } + } } + + key := w.keyForDirWatch(dir, recursive) if dw, ok := w.dirWatches[key]; ok { return dw } @@ -291,10 +370,7 @@ func (w *watcher) getOrCreateDirWatch(dir string, physicalDir string, recursive func (w *watcher) removeDirWatch(dw *dirWatch) { w.mu.Lock() defer w.mu.Unlock() - key := dw.dir - if dw.recursive { - key = dw.dir + "\x00recursive" - } + key := w.keyForDirWatch(dw.dir, dw.recursive) if existing, ok := w.dirWatches[key]; ok && existing == dw { delete(w.dirWatches, key) dw.destroyDebounce() @@ -302,39 +378,86 @@ func (w *watcher) removeDirWatch(dw *dirWatch) { } func (w *watcher) WatchDirectory(dir string, fn WatchCallback, opts ...WatchOption) (Watch, error) { - if fn == nil { - return nil, errNilCallback + watches, err := w.WatchDirectories([]WatchDirectoryRequest{{ + Dir: dir, + Callback: fn, + Options: opts, + }}) + if err != nil { + return nil, err } + return watches[0], nil +} + +func (w *watcher) WatchDirectories(requests []WatchDirectoryRequest) ([]Watch, error) { if !w.Available() { return nil, ErrUnavailable } - dir = filepath.Clean(dir) - if !filepath.IsAbs(dir) { - return nil, errNotAbsolute + if len(requests) == 0 { + return nil, nil } - dir = canonicalizePath(dir) - physicalDir := physicalDirFor(dir) - var sopts watchOptions - for _, o := range opts { - o.applyWatchOption(&sopts) + type preparedWatch struct { + dw *dirWatch + id uint64 + recursive bool + dir string } + prepared := make([]preparedWatch, 0, len(requests)) + uniqueDirWatches := make([]*dirWatch, 0, len(requests)) + seenDirWatches := make(map[*dirWatch]struct{}, len(requests)) + rollback := func() { + for i := len(prepared) - 1; i >= 0; i-- { + p := prepared[i] + p.dw.unwatch(p.id) + p.dw.unref(w) + } + } + + for _, request := range requests { + dir := request.Dir + fn := request.Callback + if fn == nil { + rollback() + return nil, errNilCallback + } + dir = filepath.Clean(dir) + if !filepath.IsAbs(dir) { + rollback() + return nil, errNotAbsolute + } + dir = canonicalizePath(dir) + physicalDir := physicalDirFor(dir) - dw := w.getOrCreateDirWatch(dir, physicalDir, sopts.recursive) - id, _ := dw.watch(fn, sopts.ignore) + var sopts watchOptions + for _, o := range request.Options { + o.applyWatchOption(&sopts) + } + + dw := w.getOrCreateDirWatch(dir, physicalDir, sopts.recursive) + id, _ := dw.watch(dir, sopts.recursive, fn, sopts.ignore) + prepared = append(prepared, preparedWatch{dw: dw, id: id, recursive: sopts.recursive, dir: dir}) + if _, ok := seenDirWatches[dw]; !ok { + seenDirWatches[dw] = struct{}{} + uniqueDirWatches = append(uniqueDirWatches, dw) + } + } impl, err := w.getImpl() if err != nil { - dw.unwatch(id) - dw.unref(w) + rollback() return nil, err } - if err := impl.watchAdd(dw); err != nil { - dw.unwatch(id) - dw.unref(w) + if err := impl.watchAddMany(uniqueDirWatches); err != nil { + rollback() return nil, err } - return &watch{w: w, dw: dw, impl: impl, id: id}, nil + + watches := make([]Watch, len(prepared)) + for i, p := range prepared { + watches[i] = &watch{w: w, dw: p.dw, impl: impl, id: p.id} + } + return watches, nil } func (w *watcher) WatchFile(path string, fn WatchCallback) (Watch, error) { @@ -408,6 +531,7 @@ type watcherImpl interface { shutdown() watchAdd(w *dirWatch) error + watchAddMany(watches []*dirWatch) error watchRemove(w *dirWatch) handleWatcherError(err *dirWatchError) @@ -479,16 +603,50 @@ func (b *watcherBase) handleStartError(err error) { } func (b *watcherBase) watchAdd(w *dirWatch) error { + return b.watchAddMany([]*dirWatch{w}) +} + +func (b *watcherBase) watchAddMany(watches []*dirWatch) error { b.mu.Lock() - if _, ok := b.subscriptions[w]; ok { + toAdd := make([]*dirWatch, 0, len(watches)) + for _, w := range watches { + if _, ok := b.subscriptions[w]; ok { + continue + } + toAdd = append(toAdd, w) + } + if len(toAdd) == 0 { b.mu.Unlock() return nil } - if err := b.self.subscribe(w); err != nil { + + if subscriber, ok := b.self.(interface { + subscribeMany(watches []*dirWatch) error + }); ok { + if err := subscriber.subscribeMany(toAdd); err != nil { + b.mu.Unlock() + return err + } + for _, w := range toAdd { + b.subscriptions[w] = struct{}{} + } b.mu.Unlock() - return err + return nil + } + + added := make([]*dirWatch, 0, len(toAdd)) + for _, w := range toAdd { + if err := b.self.subscribe(w); err != nil { + for _, addedWatch := range added { + delete(b.subscriptions, addedWatch) + _ = b.self.closeWatch(addedWatch) + } + b.mu.Unlock() + return err + } + b.subscriptions[w] = struct{}{} + added = append(added, w) } - b.subscriptions[w] = struct{}{} b.mu.Unlock() return nil } @@ -512,9 +670,11 @@ func (b *watcherBase) handleWatcherError(werr *dirWatchError) { // ----- dirWatch: per-directory watch state ------------------------- type callback struct { - id uint64 - fn WatchCallback - ignore func(path string) bool + id uint64 + dir string + recursive bool + fn WatchCallback + ignore func(path string) bool } // dirWatchError associates an error with a specific directory watch. @@ -532,7 +692,7 @@ type dirWatch struct { // dir is the caller-visible watch root used in delivered event paths. dir string // physicalDir is the path passed to OS watcher APIs. It differs from dir - // only when dir is a symlink or reparse point to a directory. + // when dir or an ancestor is a symlink or reparse point to a directory. physicalDir string recursive bool events eventList @@ -553,13 +713,10 @@ func newDirWatch(dir string, physicalDir string, db *debounce) *dirWatch { return dw } -// physicalDirFor returns the physical path to watch for dir. If dir is a -// symlink or reparse point, events are subscribed on its realpath while -// callbacks still use dir. +// physicalDirFor returns the physical path to watch for dir. If dir, or an +// ancestor of dir, is a symlink or reparse point, events are subscribed on its +// realpath while callbacks still use dir. func physicalDirFor(dir string) string { - if !nativepath.IsSymlinkOrReparsePoint(dir) { - return dir - } realpath, err := nativepath.Realpath(dir) if err != nil { return dir @@ -663,18 +820,21 @@ func (dw *dirWatch) triggerCallbacks() { } events, err := dw.events.drain() cbs := slices.Clone(dw.callbacks) - recursive := dw.recursive dw.mu.Unlock() for _, cb := range cbs { cbEvents := events - if cb.ignore != nil || !recursive { + if cb.ignore != nil || !cb.recursive || cb.dir != dw.dir { filtered := make([]Event, 0, len(events)) for _, e := range events { if cb.ignore != nil && cb.ignore(e.Path) { continue } - if !recursive && !isDirectChild(dw.dir, e.Path) { + if cb.recursive { + if cb.dir != dw.dir && !isInDirectoryOrSelf(cb.dir, e.Path) { + continue + } + } else if !isDirectChild(cb.dir, e.Path) && !(cb.dir != dw.dir && e.Path == cb.dir) { continue } filtered = append(filtered, e) @@ -687,6 +847,26 @@ func (dw *dirWatch) triggerCallbacks() { } } +func isInDirectoryOrSelf(dir, path string) bool { + if dir == "" { + return false + } + if path == dir { + return true + } + if !strings.HasPrefix(path, dir) { + return false + } + rest := path[len(dir):] + if len(rest) == 0 { + return false + } + if os.IsPathSeparator(dir[len(dir)-1]) { + return true + } + return os.IsPathSeparator(rest[0]) +} + // isDirectChild reports whether path is an immediate child of dir. // Both paths must be absolute. Returns false for path == dir. func isDirectChild(dir, path string) bool { @@ -704,12 +884,12 @@ func isDirectChild(dir, path string) bool { return len(rest) > 0 && !strings.ContainsRune(rest, '/') && !strings.ContainsRune(rest, filepath.Separator) } -func (dw *dirWatch) watch(fn WatchCallback, ignore func(path string) bool) (uint64, bool) { +func (dw *dirWatch) watch(dir string, recursive bool, fn WatchCallback, ignore func(path string) bool) (uint64, bool) { dw.mu.Lock() defer dw.mu.Unlock() dw.nextCBID++ id := dw.nextCBID - dw.callbacks = append(dw.callbacks, callback{id: id, fn: fn, ignore: ignore}) + dw.callbacks = append(dw.callbacks, callback{id: id, dir: dir, recursive: recursive, fn: fn, ignore: ignore}) return id, true } diff --git a/internal/fswatch/watcher_test.go b/internal/fswatch/watcher_test.go index a051ff7c197..aa7970f355a 100644 --- a/internal/fswatch/watcher_test.go +++ b/internal/fswatch/watcher_test.go @@ -637,6 +637,59 @@ func TestRebasePath(t *testing.T) { } } +func TestPhysicalDirForResolvesSymlinkAncestor(t *testing.T) { + t.Parallel() + + root := t.TempDir() + target := filepath.Join(root, "target") + if err := os.MkdirAll(filepath.Join(target, "nested"), 0o755); err != nil { + t.Fatal(err) + } + link := filepath.Join(root, "link") + makeDirSymlink(t, target, link) + + dir := filepath.Join(link, "nested") + want := physicalDirFor(filepath.Join(target, "nested")) + if got := physicalDirFor(dir); got != want { + t.Fatalf("physicalDirFor(%q) = %q, want %q", dir, got, want) + } +} + +func TestIsInDirectoryOrSelf(t *testing.T) { + t.Parallel() + + volume := filepath.VolumeName(os.TempDir()) + root := volume + string(filepath.Separator) + parent := filepath.Join(root, "parent") + child := filepath.Join(parent, "child") + nested := filepath.Join(child, "nested") + siblingPrefix := filepath.Join(root, "parent-sibling") + + tests := []struct { + name string + dir string + path string + want bool + }{ + {name: "exact", dir: parent, path: parent, want: true}, + {name: "child", dir: parent, path: child, want: true}, + {name: "nested", dir: parent, path: nested, want: true}, + {name: "sibling prefix", dir: parent, path: siblingPrefix, want: false}, + {name: "root self", dir: root, path: root, want: true}, + {name: "root child", dir: root, path: filepath.Join(root, "child"), want: true}, + {name: "empty dir", dir: "", path: child, want: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if got := isInDirectoryOrSelf(tt.dir, tt.path); got != tt.want { + t.Fatalf("isInDirectoryOrSelf(%q, %q) = %v, want %v", tt.dir, tt.path, got, tt.want) + } + }) + } +} + // filterEventsForPaths returns only the events whose Path is in the // allowed set. Used to discard incidental dir-update events that some // backends emit for the parent dir of a touched file. @@ -1313,6 +1366,181 @@ func TestSubscribeMultipleDifferentDirs(t *testing.T) { }) } +func TestWatchDirectoriesBatch(t *testing.T) { + t.Parallel() + runForEachWatcher(t, func(t testingT, watcherImpl Watcher) { + dir1 := newTmpDir(t) + dir2 := newTmpDir(t) + r1 := newRecorder(t) + r1.watcher = watcherImpl + r2 := newRecorder(t) + r2.watcher = watcherImpl + + watches, err := watcherImpl.WatchDirectories([]WatchDirectoryRequest{ + {Dir: dir1, Callback: r1.callback, Options: []WatchOption{WithRecursive()}}, + {Dir: dir2, Callback: r2.callback, Options: []WatchOption{WithRecursive()}}, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + for _, watch := range watches { + _ = watch.Close() + } + }) + time.Sleep(settleSleep(watcherImpl)) + + f1 := subPath(dir1) + f2 := subPath(dir2) + if err := os.WriteFile(f1, []byte("a"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(f2, []byte("b"), 0o644); err != nil { + t.Fatal(err) + } + assertEventSequence(t, r1.next(r1.deadline()), []wantEvent{{EventUpdate, f1}}) + assertEventSequence(t, r2.next(r2.deadline()), []wantEvent{{EventUpdate, f2}}) + }) +} + +type countingWatcherImpl struct { + watcherBase + subscribed []*dirWatch + closed []*dirWatch +} + +func newCountingWatcherImpl() *countingWatcherImpl { + impl := &countingWatcherImpl{} + impl.watcherBase.init(impl) + return impl +} + +func (b *countingWatcherImpl) start() error { + b.notifyStarted() + return nil +} + +func (b *countingWatcherImpl) subscribe(w *dirWatch) error { + b.subscribed = append(b.subscribed, w) + return nil +} + +func (b *countingWatcherImpl) closeWatch(w *dirWatch) error { + b.closed = append(b.closed, w) + return nil +} + +func TestFastRecursiveWatcherConsolidatesSiblingDirectories(t *testing.T) { + t.Parallel() + + root := t.TempDir() + parent := filepath.Join(root, "node_modules", ".bun") + if err := os.MkdirAll(parent, 0o755); err != nil { + t.Fatal(err) + } + + var impl *countingWatcherImpl + watcherImpl := &watcher{ + name: "fsevents", + factory: func() watcherImpl { + impl = newCountingWatcherImpl() + return impl + }, + } + + var subs []Watch + for i := range recursiveConsolidateThreshold + 2 { + dir := filepath.Join(parent, fmt.Sprintf("pkg%d", i)) + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + sub, err := watcherImpl.WatchDirectory(dir, func([]Event, error) {}) + if err != nil { + t.Fatal(err) + } + subs = append(subs, sub) + } + t.Cleanup(func() { + for _, sub := range subs { + _ = sub.Close() + } + }) + + if got := len(impl.subscribed); got != recursiveConsolidateThreshold { + t.Fatalf("expected %d subscriptions after consolidation, got %d", recursiveConsolidateThreshold, got) + } + consolidated := impl.subscribed[len(impl.subscribed)-1] + if consolidated.dir != parent || !consolidated.recursive { + t.Fatalf("expected consolidated recursive watch on %s, got dir=%s recursive=%v", parent, consolidated.dir, consolidated.recursive) + } + + watcherImpl.mu.Lock() + _, hasPkgWatch := watcherImpl.dirWatches[watcherImpl.keyForDirWatch(filepath.Join(parent, "pkg11"), false)] + watcherImpl.mu.Unlock() + if hasPkgWatch { + t.Fatal("expected later package watch to reuse consolidated parent instead of creating its own stream") + } +} + +func TestConsolidatedChildWatchFiltersAgainstRequestedDir(t *testing.T) { + t.Parallel() + + parent := filepath.Join(t.TempDir(), "parent") + child := filepath.Join(parent, "child") + sibling := filepath.Join(parent, "sibling") + dw := newDirectWatcher(t, parent) + + var got []Event + dw.watch(child, false, func(events []Event, err error) { + if err != nil { + t.Fatal(err) + } + got = append(got, events...) + }, nil) + dw.events.update(child) + dw.events.update(filepath.Join(child, "file.ts")) + dw.events.update(filepath.Join(child, "nested", "file.ts")) + dw.events.update(filepath.Join(sibling, "file.ts")) + dw.triggerCallbacks() + + gotW := toWantEvents(got) + want := []wantEvent{ + {EventUpdate, child}, + {EventUpdate, filepath.Join(child, "file.ts")}, + } + cmpEvents := func(a, b wantEvent) int { + if a.Kind != b.Kind { + return cmp.Compare(a.Kind, b.Kind) + } + return cmp.Compare(a.Path, b.Path) + } + slices.SortFunc(gotW, cmpEvents) + slices.SortFunc(want, cmpEvents) + if !equalWantEvents(gotW, want) { + t.Fatalf("event mismatch\nwant: %v\n got: %v", want, gotW) + } +} + +func TestRecursiveWatchWithIgnoreDoesNotFilterByLogicalRoot(t *testing.T) { + t.Parallel() + + dir := filepath.Join(t.TempDir(), "root") + dw := newDirectWatcher(t, dir) + + var got []Event + outsidePath := filepath.Join(t.TempDir(), "outside", "pkg", "index.ts") + dw.watch(dir, true, func(events []Event, err error) { + if err != nil { + t.Fatal(err) + } + got = append(got, events...) + }, func(string) bool { return false }) + dw.events.update(outsidePath) + dw.triggerCallbacks() + + assertEventSequence(t, got, []wantEvent{{EventUpdate, outsidePath}}) +} + // ----- errors ------------------------------------------------------------ func TestSubscribeMissingDirError(t *testing.T) { diff --git a/internal/ls/findallreferences.go b/internal/ls/findallreferences.go index b01fc659547..28043f859dd 100644 --- a/internal/ls/findallreferences.go +++ b/internal/ls/findallreferences.go @@ -686,7 +686,7 @@ func (l *LanguageService) getSymbolAndEntries( } } else { options.use = referenceUseRename - options.useAliasesForRename = true + options.useAliasesForRename = l.UserPreferences().UseAliasesForRename.IsTrueOrUnknown() } return l.getReferencedSymbolsForNode(ctx, position, node, program, program.GetSourceFiles(), options) } diff --git a/internal/ls/jsdoc.go b/internal/ls/jsdoc.go new file mode 100644 index 00000000000..a5992fa7358 --- /dev/null +++ b/internal/ls/jsdoc.go @@ -0,0 +1,161 @@ +package ls + +import ( + "slices" + "strings" + + "github.com/microsoft/typescript-go/internal/ast" + "github.com/microsoft/typescript-go/internal/checker" + "github.com/microsoft/typescript-go/internal/collections" + "github.com/microsoft/typescript-go/internal/core" + "github.com/microsoft/typescript-go/internal/lsp/lsproto" + "github.com/microsoft/typescript-go/internal/scanner" +) + +// JSDocTagInfo mirrors Strada's `JSDocTagInfo`, but renders the tag's text as a +// plain string instead of `SymbolDisplayPart[]`. +type JSDocTagInfo struct { + Name string + Text string +} + +// GetSymbolDocumentationComment renders a symbol's documentation comment as plain text. +// It backs the API's Symbol.getDocumentationComment and mirrors Strada's +// getJsDocCommentsFromDeclarations: comments are gathered from each unique declaration, +// deduplicated, and joined with line breaks. Like Strada, it does not resolve aliases — +// consumers resolve aliases themselves (via getAliasedSymbol) and re-query if desired. +func (l *LanguageService) GetSymbolDocumentationComment(c *checker.Checker, symbol *ast.Symbol) string { + if symbol == nil { + return "" + } + var parts []string + var seen collections.Set[*ast.Node] + for _, decl := range symbol.Declarations { + if decl == nil { + continue + } + if !seen.AddIfAbsent(decl) { + continue + } + if doc := l.getDocumentationFromDeclaration(c, symbol, decl, decl, lsproto.MarkupKindPlainText, true /*commentOnly*/); doc != "" && !slices.Contains(parts, doc) { + parts = append(parts, doc) + } + } + return strings.Join(parts, "\n") +} + +// GetSymbolJSDocTags collects a symbol's JSDoc tags. It backs the API's Symbol.getJsDocTags +// and mirrors Strada's getJsDocTagsFromDeclarations, except each tag's text is rendered as a +// plain string rather than SymbolDisplayPart[]. Tags with no text have an empty Text field. +func (l *LanguageService) GetSymbolJSDocTags(symbol *ast.Symbol) []JSDocTagInfo { + if symbol == nil { + return nil + } + var infos []JSDocTagInfo + var seen collections.Set[*ast.Node] + for _, decl := range symbol.Declarations { + if decl == nil { + continue + } + if !seen.AddIfAbsent(decl) { + continue + } + tags := declarationJSDocTags(decl) + // Skip comments containing @typedef/@callback since they're not associated with a + // particular declaration, unless they also carry @param/@return (treated as local docs). + hasTypedef := core.Some(tags, func(t *ast.Node) bool { + return t.Kind == ast.KindJSDocTypedefTag || t.Kind == ast.KindJSDocCallbackTag + }) + hasParamOrReturn := core.Some(tags, func(t *ast.Node) bool { + return t.Kind == ast.KindJSDocParameterTag || t.Kind == ast.KindJSDocReturnTag + }) + if hasTypedef && !hasParamOrReturn { + continue + } + for _, tag := range tags { + infos = append(infos, JSDocTagInfo{Name: tag.TagName().Text(), Text: getJSDocTagText(tag)}) + } + } + return infos +} + +// declarationJSDocTags returns the JSDoc tags associated with a declaration, walking the +// JSDoc comment location chain like the checker's getAllJSDocTags. +func declarationJSDocTags(node *ast.Node) []*ast.Node { + if node.Flags&ast.NodeFlagsJSDoc == 0 { + for current := node; current != nil; current = ast.GetNextJSDocCommentLocation(current) { + jsdocs := current.JSDoc(nil) + if len(jsdocs) == 0 { + continue + } + lastJSDoc := jsdocs[len(jsdocs)-1].AsJSDoc() + if lastJSDoc.Tags != nil { + return lastJSDoc.Tags.Nodes + } + } + } + return nil +} + +// getJSDocTagText renders the text of a single JSDoc tag as a plain string, mirroring +// Strada's getCommentDisplayParts collapsed from SymbolDisplayPart[] to a string. +func getJSDocTagText(tag *ast.Node) string { + comment := scanner.GetTextOfJSDocComment(tag.CommentList()) + addComment := func(s string) string { + if comment == "" { + return s + } + return s + " " + comment + } + switch tag.Kind { + case ast.KindJSDocThrowsTag: + if te := tag.AsJSDocThrowsTag().TypeExpression; te != nil { + return addComment(scanner.GetTextOfNode(te)) + } + return comment + case ast.KindJSDocImplementsTag: + return addComment(scanner.GetTextOfNode(tag.AsJSDocImplementsTag().ClassName)) + case ast.KindJSDocAugmentsTag: + return addComment(scanner.GetTextOfNode(tag.AsJSDocAugmentsTag().ClassName)) + case ast.KindJSDocTemplateTag: + templateTag := tag.AsJSDocTemplateTag() + var b strings.Builder + if templateTag.Constraint != nil { + b.WriteString(scanner.GetTextOfNode(templateTag.Constraint)) + } + if templateTag.TypeParameters != nil { + for i, tp := range templateTag.TypeParameters.Nodes { + if i == 0 && b.Len() != 0 { + b.WriteString(" ") + } + if i != 0 { + b.WriteString(", ") + } + b.WriteString(scanner.GetTextOfNode(tp)) + } + } + if comment != "" { + if b.Len() != 0 { + b.WriteString(" ") + } + b.WriteString(comment) + } + return b.String() + case ast.KindJSDocTypeTag: + return addComment(scanner.GetTextOfNode(tag.AsJSDocTypeTag().TypeExpression)) + case ast.KindJSDocSatisfiesTag: + return addComment(scanner.GetTextOfNode(tag.AsJSDocSatisfiesTag().TypeExpression)) + case ast.KindJSDocSeeTag: + if ne := tag.AsJSDocSeeTag().NameExpression; ne != nil { + return addComment(scanner.GetTextOfNode(ne)) + } + return comment + case ast.KindJSDocParameterTag, ast.KindJSDocPropertyTag: + if name := tag.Name(); name != nil { + return addComment(scanner.GetTextOfNode(name)) + } + return comment + default: + return comment + } +} diff --git a/internal/ls/lsutil/organizeimports.go b/internal/ls/lsutil/organizeimports.go index 9ae778810aa..08176faabd2 100644 --- a/internal/ls/lsutil/organizeimports.go +++ b/internal/ls/lsutil/organizeimports.go @@ -3,24 +3,15 @@ package lsutil import ( "cmp" "math" + "strings" "unicode" + "unicode/utf8" "github.com/microsoft/typescript-go/internal/ast" "github.com/microsoft/typescript-go/internal/core" - "github.com/microsoft/typescript-go/internal/locale" "github.com/microsoft/typescript-go/internal/stringutil" "github.com/microsoft/typescript-go/internal/tspath" - "golang.org/x/text/collate" - "golang.org/x/text/language" -) - -var ( - caseInsensitiveOrganizeImportsComparer = []func(a, b string) int{getOrganizeImportsOrdinalStringComparer(true)} - caseSensitiveOrganizeImportsComparer = []func(a, b string) int{getOrganizeImportsOrdinalStringComparer(false)} - organizeImportsComparers = []func(a, b string) int{ - caseInsensitiveOrganizeImportsComparer[0], - caseSensitiveOrganizeImportsComparer[0], - } + "golang.org/x/text/unicode/norm" ) // FilterImportDeclarations filters out non-import declarations from a list of statements. @@ -32,9 +23,10 @@ func FilterImportDeclarations(statements []*ast.Statement) []*ast.Statement { // GetDetectionLists returns the lists of comparers and type orders to test for organize imports detection. func GetDetectionLists(preferences UserPreferences) (comparersToTest []func(a, b string) int, typeOrdersToTest []OrganizeImportsTypeOrder) { - if !preferences.OrganizeImportsIgnoreCase.IsUnknown() { - ignoreCase := preferences.OrganizeImportsIgnoreCase.IsTrue() - comparersToTest = []func(a, b string) int{getOrganizeImportsStringComparer(preferences, ignoreCase)} + if preferences.OrganizeImportsSort != OrganizeImportsSortAuto { + comparersToTest = []func(a, b string) int{getOrganizeImportsPresetStringComparer(preferences.OrganizeImportsSort)} + } else if !preferences.OrganizeImportsIgnoreCase.IsUnknown() { + comparersToTest = []func(a, b string) int{getOrganizeImportsStringComparer(preferences, preferences.OrganizeImportsIgnoreCase.IsTrue())} } else { comparersToTest = []func(a, b string) int{ getOrganizeImportsStringComparer(preferences, true), @@ -55,6 +47,32 @@ func GetDetectionLists(preferences UserPreferences) (comparersToTest []func(a, b return comparersToTest, typeOrdersToTest } +func ResolveOrganizeImportsSort(preferences UserPreferences) OrganizeImportsSort { + if preferences.OrganizeImportsSort != OrganizeImportsSortAuto { + return preferences.OrganizeImportsSort + } + + if preferences.OrganizeImportsCollation == OrganizeImportsCollationUnicode { + switch preferences.OrganizeImportsIgnoreCase { + case core.TSTrue: + return OrganizeImportsSortNaturalIgnoreCase + case core.TSFalse: + return OrganizeImportsSortNatural + default: + return OrganizeImportsSortAuto + } + } + + switch preferences.OrganizeImportsIgnoreCase { + case core.TSTrue: + return OrganizeImportsSortOrdinalIgnoreCase + case core.TSFalse: + return OrganizeImportsSortOrdinal + default: + return OrganizeImportsSortAuto + } +} + func getOrganizeImportsOrdinalStringComparer(ignoreCase bool) func(a, b string) int { if ignoreCase { return stringutil.CompareStringsCaseInsensitiveEslintCompatible @@ -62,122 +80,189 @@ func getOrganizeImportsOrdinalStringComparer(ignoreCase bool) func(a, b string) return stringutil.CompareStringsCaseSensitive } -func getOrganizeImportsUnicodeStringComparer(ignoreCase bool, preferences UserPreferences) func(a, b string) int { - resolvedLocale := getOrganizeImportsLocale(preferences) +func getOrganizeImportsNaturalStringComparer(caseSensitive bool) func(a, b string) int { + return func(a, b string) int { + return compareOrganizeImportsNaturalStrings(a, b, caseSensitive) + } +} +func getOrganizeImportsUnicodeStringComparer(ignoreCase bool, preferences UserPreferences) func(a, b string) int { caseFirst := preferences.OrganizeImportsCaseFirst numeric := preferences.OrganizeImportsNumericCollation.IsTrue() accents := !preferences.OrganizeImportsAccentCollation.IsFalse() - tag, _ := language.Parse(resolvedLocale) + return func(a, b string) int { + return compareOrganizeImportsUnicodeStrings(a, b, ignoreCase, caseFirst, numeric, accents) + } +} + +func compareOrganizeImportsNaturalStrings(a string, b string, caseSensitive bool) int { + if cmp := compareStringsNumeric(naturalCollationKey(a), naturalCollationKey(b)); cmp != 0 { + return cmp + } + + if caseSensitive { + if cmp := compareOrganizeImportsCaseUpperFirst(a, b); cmp != 0 { + return cmp + } + } - var opts []collate.Option + return strings.Compare(a, b) +} - if numeric { - opts = append(opts, collate.Numeric) +func compareOrganizeImportsUnicodeStrings(a string, b string, ignoreCase bool, caseFirst OrganizeImportsCaseFirst, numeric bool, accents bool) int { + if cmp := compareOrganizeImportsUnicodeKeys(naturalCollationKey(a), naturalCollationKey(b), numeric); cmp != 0 { + return cmp } - looseOpts := append([]collate.Option{}, opts...) - looseOpts = append(looseOpts, collate.Loose) - looseCollator := collate.New(tag, looseOpts...) + if accents { + if cmp := compareOrganizeImportsUnicodeKeys(strings.ToLower(a), strings.ToLower(b), numeric); cmp != 0 { + return cmp + } + } if !ignoreCase { - caseInsensitiveOpts := append([]collate.Option{}, opts...) - caseInsensitiveOpts = append(caseInsensitiveOpts, collate.IgnoreCase) - caseInsensitiveCollator := collate.New(tag, caseInsensitiveOpts...) + if cmp := compareOrganizeImportsCase(a, b, caseFirst); cmp != 0 { + return cmp + } + } - fullCollator := collate.New(tag, opts...) + return strings.Compare(a, b) +} - return func(a, b string) int { - var primaryCmp int - if !accents { - primaryCmp = looseCollator.CompareString(a, b) - } else { - primaryCmp = caseInsensitiveCollator.CompareString(a, b) - } - if primaryCmp != 0 { - return primaryCmp - } +func naturalCollationKey(s string) string { + return strings.ToLower(removeDiacritics(s)) +} - aRunes := []rune(a) - bRunes := []rune(b) - minLen := min(len(aRunes), len(bRunes)) - - for i := range minLen { - aUpper := unicode.IsUpper(aRunes[i]) - bUpper := unicode.IsUpper(bRunes[i]) - if aUpper != bUpper { - switch caseFirst { - case OrganizeImportsCaseFirstUpper: - if aUpper { - return -1 - } - return 1 - case OrganizeImportsCaseFirstLower: - if !aUpper { - return -1 - } - return 1 - default: - if aUpper { - return 1 - } - return -1 - } - } - } +func removeDiacritics(s string) string { + return strings.Map(func(r rune) rune { + if unicode.Is(unicode.Mn, r) { + return -1 + } + return r + }, norm.NFD.String(s)) +} - if !accents { - if len(aRunes) != len(bRunes) { - return len(aRunes) - len(bRunes) - } - return 0 +func compareOrganizeImportsUnicodeKeys(a string, b string, numeric bool) int { + if numeric { + return compareStringsNumeric(a, b) + } + return strings.Compare(a, b) +} + +func compareStringsNumeric(a string, b string) int { + for len(a) > 0 && len(b) > 0 { + if isASCIIDigit(a[0]) && isASCIIDigit(b[0]) { + aRunEnd := asciiDigitRunEnd(a) + bRunEnd := asciiDigitRunEnd(b) + + if cmp := compareNumericText(a[:aRunEnd], b[:bRunEnd]); cmp != 0 { + return cmp } - return fullCollator.CompareString(a, b) + a = a[aRunEnd:] + b = b[bRunEnd:] + continue } - } - if ignoreCase { - opts = append(opts, collate.IgnoreCase) - if !accents { - opts = append(opts, collate.Loose) + aRune, aSize := utf8.DecodeRuneInString(a) + bRune, bSize := utf8.DecodeRuneInString(b) + if aRune != bRune { + return cmp.Compare(aRune, bRune) } + + a = a[aSize:] + b = b[bSize:] } - collator := collate.New(tag, opts...) + return cmp.Compare(len(a), len(b)) +} - return func(a, b string) int { - return collator.CompareString(a, b) +func isASCIIDigit(ch byte) bool { + return ch >= '0' && ch <= '9' +} + +func asciiDigitRunEnd(s string) int { + i := 0 + for i < len(s) && isASCIIDigit(s[i]) { + i++ } + return i } -func getOrganizeImportsLocale(preferences UserPreferences) string { - localeStr := "en" - if preferences.OrganizeImportsLocale != "" { - localeStr = preferences.OrganizeImportsLocale +func compareNumericText(a string, b string) int { + aDigits := strings.TrimLeft(a, "0") + bDigits := strings.TrimLeft(b, "0") + if aDigits == "" { + aDigits = "0" + } + if bDigits == "" { + bDigits = "0" } - if localeStr == "auto" { - if locale.Default != (locale.Locale{}) { - tag := language.Tag(locale.Default) - return tag.String() - } - return "en" + if len(aDigits) != len(bDigits) { + return cmp.Compare(len(aDigits), len(bDigits)) } + if cmp := strings.Compare(aDigits, bDigits); cmp != 0 { + return cmp + } + return strings.Compare(a, b) +} - if locale, ok := locale.Parse(localeStr); ok { - tag := language.Tag(locale) - return tag.String() +func compareOrganizeImportsCaseUpperFirst(a string, b string) int { + return compareOrganizeImportsCase(a, b, OrganizeImportsCaseFirstUpper) +} + +func compareOrganizeImportsCase(a string, b string, caseFirst OrganizeImportsCaseFirst) int { + aRunes := []rune(a) + bRunes := []rune(b) + minLen := min(len(aRunes), len(bRunes)) + + for i := range minLen { + aUpper := unicode.IsUpper(aRunes[i]) + bUpper := unicode.IsUpper(bRunes[i]) + if aUpper != bUpper { + switch caseFirst { + case OrganizeImportsCaseFirstUpper: + if aUpper { + return -1 + } + return 1 + case OrganizeImportsCaseFirstLower: + if !aUpper { + return -1 + } + return 1 + default: + if aUpper { + return 1 + } + return -1 + } + } } - return "en" + return cmp.Compare(len(aRunes), len(bRunes)) } -func getOrganizeImportsStringComparer(preferences UserPreferences, ignoreCase bool) func(a, b string) int { - collation := preferences.OrganizeImportsCollation +func getOrganizeImportsPresetStringComparer(sort OrganizeImportsSort) func(a, b string) int { + switch sort { + case OrganizeImportsSortOrdinalIgnoreCase: + return getOrganizeImportsOrdinalStringComparer(true) + case OrganizeImportsSortNatural: + return getOrganizeImportsNaturalStringComparer(true) + case OrganizeImportsSortNaturalIgnoreCase: + return getOrganizeImportsNaturalStringComparer(false) + default: + return getOrganizeImportsOrdinalStringComparer(false) + } +} - if collation == OrganizeImportsCollationUnicode { +func getOrganizeImportsStringComparer(preferences UserPreferences, ignoreCase bool) func(a, b string) int { + if preferences.OrganizeImportsSort != OrganizeImportsSortAuto { + return getOrganizeImportsPresetStringComparer(preferences.OrganizeImportsSort) + } + if preferences.OrganizeImportsCollation == OrganizeImportsCollationUnicode { return getOrganizeImportsUnicodeStringComparer(ignoreCase, preferences) } return getOrganizeImportsOrdinalStringComparer(ignoreCase) @@ -318,7 +403,7 @@ func GetNamedImportSpecifierComparer(preferences UserPreferences, comparer func( if !preferences.OrganizeImportsIgnoreCase.IsUnknown() { ignoreCase = preferences.OrganizeImportsIgnoreCase.IsTrue() } - comparer = getOrganizeImportsOrdinalStringComparer(ignoreCase) + comparer = getOrganizeImportsStringComparer(preferences, ignoreCase) } return func(s1, s2 *ast.Node) int { return compareImportOrExportSpecifiers(s1, s2, comparer, preferences) @@ -346,14 +431,17 @@ func GetOrganizeImportsStringComparerWithDetection(originalImportDecls []*ast.St } func getComparers(preferences UserPreferences) []func(a string, b string) int { - switch preferences.OrganizeImportsIgnoreCase { - case core.TSTrue: - return caseInsensitiveOrganizeImportsComparer - case core.TSFalse: - return caseSensitiveOrganizeImportsComparer + if preferences.OrganizeImportsSort != OrganizeImportsSortAuto || !preferences.OrganizeImportsIgnoreCase.IsUnknown() { + ignoreCase := false + if !preferences.OrganizeImportsIgnoreCase.IsUnknown() { + ignoreCase = preferences.OrganizeImportsIgnoreCase.IsTrue() + } + return []func(a, b string) int{getOrganizeImportsStringComparer(preferences, ignoreCase)} + } + return []func(a, b string) int{ + getOrganizeImportsStringComparer(preferences, true), + getOrganizeImportsStringComparer(preferences, false), } - - return organizeImportsComparers } type namedImportSortResult struct { @@ -582,7 +670,7 @@ func GetNamedImportSpecifierComparerWithDetection(importDecl *ast.Node, sourceFi specifierComparer = GetNamedImportSpecifierComparer(preferences, comparersToTest[0]) isSorted = core.TSUnknown - if (preferences.OrganizeImportsIgnoreCase.IsUnknown() || preferences.OrganizeImportsTypeOrder == OrganizeImportsTypeOrderAuto) && importStmt != nil { + if (ResolveOrganizeImportsSort(preferences) == OrganizeImportsSortAuto || preferences.OrganizeImportsTypeOrder == OrganizeImportsTypeOrderAuto) && importStmt != nil { detectFromDecl := detectNamedImportOrganizationBySort([]*ast.Statement{importStmt}, comparersToTest, typeOrdersToTest) if detectFromDecl != nil { isSorted = core.BoolToTristate(detectFromDecl.isSorted) diff --git a/internal/ls/lsutil/userpreferences.go b/internal/ls/lsutil/userpreferences.go index 2b54bda0158..5536a4df532 100644 --- a/internal/ls/lsutil/userpreferences.go +++ b/internal/ls/lsutil/userpreferences.go @@ -84,19 +84,21 @@ type UserPreferences struct { // ------- OrganizeImports ------- + // Indicates which deterministic preset should be used to sort imports. + // "auto" detects the existing ordinal case sensitivity where possible. + OrganizeImportsSort OrganizeImportsSort `raw:"organizeImportsSort" config:"preferences.organizeImports.sort"` // !!! // Indicates whether imports should be organized in a case-insensitive manner. // // Default: TSUnknown ("auto" in strada), will perform detection OrganizeImportsIgnoreCase core.Tristate `raw:"organizeImportsIgnoreCase" config:"preferences.organizeImports.caseSensitivity"` // !!! // Indicates whether imports should be organized via an "ordinal" (binary) comparison using the numeric value of their - // code points, or via "unicode" collation (via the Unicode Collation Algorithm (https://unicode.org/reports/tr10/#Scope)) - // - // using rules associated with the locale specified in organizeImportsCollationLocale. + // code points, or via "unicode" natural sorting. This implementation is locale-agnostic and approximates the practical + // import-sorting behavior rather than the full Unicode Collation Algorithm. // // Default: Ordinal OrganizeImportsCollation OrganizeImportsCollation `raw:"organizeImportsCollation" config:"preferences.organizeImports.unicodeCollation"` // !!! - // Indicates the locale to use for "unicode" collation. If not specified, the locale `"en"` is used as an invariant - // for the sake of consistent sorting. Use `"auto"` to use the detected UI locale. + // Indicates the locale to use for "unicode" collation in legacy clients. This is accepted for compatibility, but + // currently ignored because organize-import sorting is deterministic and locale-agnostic. // // This preference is ignored if organizeImportsCollation is not `unicode`. // @@ -109,16 +111,13 @@ type UserPreferences struct { // // Default: `false` OrganizeImportsNumericCollation core.Tristate `raw:"organizeImportsNumericCollation" config:"preferences.organizeImports.numericCollation"` // !!! - // Indicates whether accents and other diacritic marks are considered unequal for the purpose of collation. When - // `true`, characters with accents and other diacritics will be collated in the order defined by the locale specified - // in organizeImportsCollationLocale. + // Indicates whether accents and other diacritic marks are considered unequal for the purpose of sorting. // // This preference is ignored if organizeImportsCollation is not `unicode`. // // Default: `true` OrganizeImportsAccentCollation core.Tristate `raw:"organizeImportsAccentCollation" config:"preferences.organizeImports.accentCollation"` // !!! - // Indicates whether upper case or lower case should sort first. When `false`, the default order for the locale - // specified in organizeImportsCollationLocale is used. + // Indicates whether upper case or lower case should sort first. // // This permission is ignored if: // - organizeImportsCollation is not `unicode` @@ -166,7 +165,7 @@ type UserPreferences struct { DisableSuggestions core.Tristate `raw:"disableSuggestions"` // !!! DisableLineTextInReferences core.Tristate `raw:"disableLineTextInReferences"` // !!! DisplayPartsForJSDoc core.Tristate `raw:"displayPartsForJSDoc"` // !!! - ReportStyleChecksAsWarnings core.Tristate `raw:"reportStyleChecksAsWarnings"` // !!! If this changes, we need to ask the client to recompute diagnostics + ReportStyleChecksAsWarnings core.Tristate `raw:"reportStyleChecksAsWarnings" config:"reportStyleChecksAsWarnings"` // ------- ATA ------- @@ -240,6 +239,16 @@ const ( IncludeInlayParameterNameHintsLiterals IncludeInlayParameterNameHints = "literals" ) +type OrganizeImportsSort int + +const ( + OrganizeImportsSortAuto OrganizeImportsSort = iota + OrganizeImportsSortOrdinal + OrganizeImportsSortOrdinalIgnoreCase + OrganizeImportsSortNatural + OrganizeImportsSortNaturalIgnoreCase +) + type OrganizeImportsCollation bool const ( @@ -318,6 +327,21 @@ var typeParsers = map[reflect.Type]func(any) any{ } return IncludeInlayParameterNameHintsNone }, + reflect.TypeFor[OrganizeImportsSort](): func(val any) any { + if s, ok := val.(string); ok { + switch strings.ToLower(s) { + case "ordinal": + return OrganizeImportsSortOrdinal + case "ordinalignorecase": + return OrganizeImportsSortOrdinalIgnoreCase + case "natural": + return OrganizeImportsSortNatural + case "naturalignorecase": + return OrganizeImportsSortNaturalIgnoreCase + } + } + return OrganizeImportsSortAuto + }, reflect.TypeFor[OrganizeImportsCollation](): func(val any) any { if s, ok := val.(string); ok && strings.ToLower(s) == "unicode" { return OrganizeImportsCollationUnicode @@ -389,6 +413,20 @@ var typeSerializers = map[reflect.Type]func(any) any{ return nil } }, + reflect.TypeFor[OrganizeImportsSort](): func(val any) any { + switch val.(OrganizeImportsSort) { + case OrganizeImportsSortOrdinal: + return "ordinal" + case OrganizeImportsSortOrdinalIgnoreCase: + return "ordinalIgnoreCase" + case OrganizeImportsSortNatural: + return "natural" + case OrganizeImportsSortNaturalIgnoreCase: + return "naturalIgnoreCase" + default: + return "auto" + } + }, reflect.TypeFor[OrganizeImportsCollation](): func(val any) any { if val.(OrganizeImportsCollation) == OrganizeImportsCollationUnicode { return "unicode" @@ -417,6 +455,48 @@ var typeSerializers = map[reflect.Type]func(any) any{ return "auto" } }, + // These enums distinguish an unset zero value (e.g. "") from their effective + // default (e.g. "auto"): the parser promotes unset/unknown input to the + // non-zero default. Plain string serialization would therefore write "" for + // an unset field and the parser would read it back as the non-zero default, + // breaking round-tripping. Mirror the core.Tristate serializer above and omit + // the unset value (return nil) so it decodes back to the zero value. (Enums + // whose default already is their zero value, like the OrganizeImports* ones, + // round-trip without this.) + // + // TODO: These three are the only parsers whose fallback is a non-zero value; + // every other parser returns its zero value as the fallback. They should be + // made consistent: change the parser fallback to return the zero value and + // remove this serializer (relying on the default string serialization, which + // already omits ""). The consumer must then treat the zero value as the + // effective default. The two module-specifier enums are safe to convert (all + // read sites already treat the "" zero identically to the promoted default). + reflect.TypeFor[JsxAttributeCompletionStyle](): func(val any) any { + // TODO: make consistent with other enums (see note above). Unlike the + // module-specifier enums, the consumer in completions.go distinguishes + // JsxAttributeCompletionStyleUnknown from ...Auto, so converting this one + // requires updating that consumer to treat the zero value as "auto". + if v := val.(JsxAttributeCompletionStyle); v != JsxAttributeCompletionStyleUnknown { + return string(v) + } + return nil + }, + reflect.TypeFor[modulespecifiers.ImportModuleSpecifierPreference](): func(val any) any { + // TODO: make consistent with other enums (see note above): have the parser + // return the zero value (None) as its fallback and drop this serializer. + if v := val.(modulespecifiers.ImportModuleSpecifierPreference); v != "" { + return string(v) + } + return nil + }, + reflect.TypeFor[modulespecifiers.ImportModuleSpecifierEndingPreference](): func(val any) any { + // TODO: make consistent with other enums (see note above): have the parser + // return the zero value (None) as its fallback and drop this serializer. + if v := val.(modulespecifiers.ImportModuleSpecifierEndingPreference); v != "" { + return string(v) + } + return nil + }, } // configPathParsers provides field-specific config value parsers that override the default @@ -546,27 +626,34 @@ func setNestedValue(config map[string]any, path string, value any) { current[parts[len(parts)-1]] = value } +func setRawFieldsFromConfig(v reflect.Value, infos []fieldInfo, settings map[string]any) { + index := unstableNameIndex() + for name, value := range settings { + if idx, found := index[name]; found { + info := infos[idx] + field := getFieldByPath(v, info.fieldPath) + if info.rawInvert { + if b, ok := value.(bool); ok { + value = !b + } + } + setFieldFromValue(field, value) + } + } +} + func (p UserPreferences) withConfig(config map[string]any) UserPreferences { v := reflect.ValueOf(&p).Elem() infos := fieldInfoCache() + // Raw UserPreferences can be provided directly, notably via LSP initializationOptions. + setRawFieldsFromConfig(v, infos, config) + // Process "unstable" section first - allows any field to be set by raw name. // This mirrors VS Code's behavior: { ...config.get('unstable'), ...stableOptions } // where stable options are spread after and take precedence. if unstable, ok := config["unstable"].(map[string]any); ok { - index := unstableNameIndex() - for name, value := range unstable { - if idx, found := index[name]; found { - info := infos[idx] - field := getFieldByPath(v, info.fieldPath) - if info.rawInvert { - if b, ok := value.(bool); ok { - value = !b - } - } - setFieldFromValue(field, value) - } - } + setRawFieldsFromConfig(v, infos, unstable) } // Process path-based config (VS Code style nested paths). @@ -618,7 +705,7 @@ func setFieldFromValue(field reflect.Value, val any) { return } - // Check custom parsers first (for types like Tristate, OrganizeImportsCollation, etc.) + // Check custom parsers first (for types like Tristate, enums, etc.) if parser, ok := typeParsers[field.Type()]; ok { field.Set(reflect.ValueOf(parser(val))) return @@ -687,7 +774,7 @@ func (p *UserPreferences) MarshalJSONTo(enc *json.Encoder) error { } func serializeField(field reflect.Value) any { - // Check custom serializers first (for types like Tristate, OrganizeImportsCollation, etc.) + // Check custom serializers first (for types like Tristate, enums, etc.) if serializer, ok := typeSerializers[field.Type()]; ok { return serializer(field.Interface()) } @@ -696,9 +783,21 @@ func serializeField(field reflect.Value) any { case reflect.Bool: return field.Bool() case reflect.Int: - return int(field.Int()) + // Zero means "unset" for these preference fields. Omit it so a partial + // config does not clobber defaults with zeros when round-tripped through + // withConfig. + i := field.Int() + if i == 0 { + return nil + } + return int(i) case reflect.String: - return field.String() + // Zero ("") means "unset"; omit it for the same reason as int above. + s := field.String() + if s == "" { + return nil + } + return s case reflect.Slice: if field.IsNil() { return nil @@ -725,28 +824,6 @@ func (p *UserPreferences) UnmarshalJSONFrom(dec *json.Decoder) error { // --- Helper methods --- -// WithOverrides returns a copy of p with non-zero fields from overrides applied on top. -// This is safe because all preference fields use types where zero = "not set": -// Tristate (TSUnknown=0), int (0), string (""), slice (nil). -func (p UserPreferences) WithOverrides(overrides UserPreferences) UserPreferences { - mergeNonZeroFields(reflect.ValueOf(&p).Elem(), reflect.ValueOf(&overrides).Elem()) - return p -} - -func mergeNonZeroFields(dst, src reflect.Value) { - for i := range dst.NumField() { - srcField := src.Field(i) - dstField := dst.Field(i) - if srcField.Kind() == reflect.Struct { - mergeNonZeroFields(dstField, srcField) - continue - } - if !srcField.IsZero() { - dstField.Set(srcField) - } - } -} - func (p UserPreferences) ModuleSpecifierPreferences() modulespecifiers.UserPreferences { return modulespecifiers.UserPreferences{ ImportModuleSpecifierPreference: p.ImportModuleSpecifierPreference, @@ -776,11 +853,8 @@ func ParseUserPreferences(items map[string]any) UserPreferences { // Apply javascript, then typescript, then js/ts (highest precedence). for _, section := range []string{"javascript", "typescript", "js/ts"} { if item, ok := items[section]; ok && item != nil { - switch settings := item.(type) { - case map[string]any: + if settings, ok := item.(map[string]any); ok { prefs = prefs.withConfig(settings) - case UserPreferences: - prefs = prefs.WithOverrides(settings) } } } diff --git a/internal/ls/lsutil/userpreferences_test.go b/internal/ls/lsutil/userpreferences_test.go index d7ea9dcc6ea..d40a4489b4d 100644 --- a/internal/ls/lsutil/userpreferences_test.go +++ b/internal/ls/lsutil/userpreferences_test.go @@ -309,6 +309,105 @@ func TestUserPreferencesParseUnstable(t *testing.T) { }, }, }, + { + name: "old raw organize imports unicode preferences load as raw state", + json: `{ + "unstable": { + "organizeImportsCollation": "unicode", + "organizeImportsCaseFirst": "upper", + "organizeImportsIgnoreCase": false, + "organizeImportsNumericCollation": true + } + }`, + expected: UserPreferences{ + OrganizeImportsCollation: OrganizeImportsCollationUnicode, + OrganizeImportsCaseFirst: OrganizeImportsCaseFirstUpper, + OrganizeImportsIgnoreCase: core.TSFalse, + OrganizeImportsNumericCollation: core.TSTrue, + }, + }, + { + name: "old top-level raw organize imports unicode preferences load as raw state", + json: `{ + "organizeImportsCollation": "unicode", + "organizeImportsIgnoreCase": true + }`, + expected: UserPreferences{ + OrganizeImportsCollation: OrganizeImportsCollationUnicode, + OrganizeImportsIgnoreCase: core.TSTrue, + }, + }, + { + name: "new top-level raw organize imports sort is accepted", + json: `{ + "organizeImportsSort": "natural" + }`, + expected: UserPreferences{ + OrganizeImportsSort: OrganizeImportsSortNatural, + }, + }, + { + name: "old raw organize imports ignore case loads as raw state", + json: `{ + "unstable": { + "organizeImportsIgnoreCase": true + } + }`, + expected: UserPreferences{ + OrganizeImportsIgnoreCase: core.TSTrue, + }, + }, + { + name: "new raw organize imports sort loads alongside old raw preferences", + json: `{ + "unstable": { + "organizeImportsSort": "ordinal", + "organizeImportsCollation": "unicode", + "organizeImportsIgnoreCase": true + } + }`, + expected: UserPreferences{ + OrganizeImportsSort: OrganizeImportsSortOrdinal, + OrganizeImportsCollation: OrganizeImportsCollationUnicode, + OrganizeImportsIgnoreCase: core.TSTrue, + }, + }, + { + name: "old nested organize imports unicode preferences load as raw state", + json: `{ + "preferences": { + "organizeImports": { + "unicodeCollation": "unicode", + "caseSensitivity": "caseSensitive", + "numericCollation": true, + "caseFirst": "upper" + } + } + }`, + expected: UserPreferences{ + OrganizeImportsCollation: OrganizeImportsCollationUnicode, + OrganizeImportsIgnoreCase: core.TSFalse, + OrganizeImportsNumericCollation: core.TSTrue, + OrganizeImportsCaseFirst: OrganizeImportsCaseFirstUpper, + }, + }, + { + name: "new nested organize imports sort loads alongside old nested preferences", + json: `{ + "preferences": { + "organizeImports": { + "sort": "ordinalIgnoreCase", + "unicodeCollation": "unicode", + "caseSensitivity": "caseSensitive" + } + } + }`, + expected: UserPreferences{ + OrganizeImportsSort: OrganizeImportsSortOrdinalIgnoreCase, + OrganizeImportsCollation: OrganizeImportsCollationUnicode, + OrganizeImportsIgnoreCase: core.TSFalse, + }, + }, } for _, tt := range tests { @@ -325,6 +424,38 @@ func TestUserPreferencesParseUnstable(t *testing.T) { } } +func TestUserPreferencesReportStyleChecksAsWarnings(t *testing.T) { + t.Parallel() + + t.Run("reportStyleChecksAsWarnings via config path", func(t *testing.T) { + t.Parallel() + prefs := ParseUserPreferences(map[string]any{ + "js/ts": map[string]any{ + "reportStyleChecksAsWarnings": false, + }, + }) + assert.Equal(t, prefs.ReportStyleChecksAsWarnings, core.TSFalse) + }) + + t.Run("reportStyleChecksAsWarnings defaults to true", func(t *testing.T) { + t.Parallel() + prefs := NewDefaultUserPreferences() + assert.Equal(t, prefs.ReportStyleChecksAsWarnings, core.TSTrue) + }) + + t.Run("reportStyleChecksAsWarnings via unstable section", func(t *testing.T) { + t.Parallel() + prefs := ParseUserPreferences(map[string]any{ + "js/ts": map[string]any{ + "unstable": map[string]any{ + "reportStyleChecksAsWarnings": false, + }, + }, + }) + assert.Equal(t, prefs.ReportStyleChecksAsWarnings, core.TSFalse) + }) +} + func TestUserPreferencesParseATA(t *testing.T) { t.Parallel() diff --git a/internal/ls/lsutil/utilities_test.go b/internal/ls/lsutil/utilities_test.go index 51292adfbbb..1f5b67426c3 100644 --- a/internal/ls/lsutil/utilities_test.go +++ b/internal/ls/lsutil/utilities_test.go @@ -65,3 +65,136 @@ let c = 3; }) } } + +func TestResolveOrganizeImportsSort(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + preferences UserPreferences + want OrganizeImportsSort + }{ + { + name: "explicit sort wins", + preferences: UserPreferences{ + OrganizeImportsSort: OrganizeImportsSortOrdinal, + OrganizeImportsCollation: OrganizeImportsCollationUnicode, + OrganizeImportsIgnoreCase: core.TSTrue, + }, + want: OrganizeImportsSortOrdinal, + }, + { + name: "unicode case-sensitive maps to natural", + preferences: UserPreferences{ + OrganizeImportsCollation: OrganizeImportsCollationUnicode, + OrganizeImportsIgnoreCase: core.TSFalse, + }, + want: OrganizeImportsSortNatural, + }, + { + name: "unicode ignore case maps to natural ignore case", + preferences: UserPreferences{ + OrganizeImportsCollation: OrganizeImportsCollationUnicode, + OrganizeImportsIgnoreCase: core.TSTrue, + }, + want: OrganizeImportsSortNaturalIgnoreCase, + }, + { + name: "unicode unknown case sensitivity stays auto for detection", + preferences: UserPreferences{ + OrganizeImportsCollation: OrganizeImportsCollationUnicode, + }, + want: OrganizeImportsSortAuto, + }, + { + name: "ordinal ignore case maps to ordinal ignore case", + preferences: UserPreferences{ + OrganizeImportsIgnoreCase: core.TSTrue, + }, + want: OrganizeImportsSortOrdinalIgnoreCase, + }, + { + name: "ordinal case sensitive maps to ordinal", + preferences: UserPreferences{ + OrganizeImportsIgnoreCase: core.TSFalse, + }, + want: OrganizeImportsSortOrdinal, + }, + { + name: "unknown ordinal stays auto", + want: OrganizeImportsSortAuto, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if got := ResolveOrganizeImportsSort(tt.preferences); got != tt.want { + t.Fatalf("ResolveOrganizeImportsSort() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestCompareOrganizeImportsNaturalStrings(t *testing.T) { + t.Parallel() + + comparer := getOrganizeImportsPresetStringComparer(OrganizeImportsSortNaturalIgnoreCase) + tests := []struct { + name string + a string + b string + want int + }{ + { + name: "numeric runs sort by numeric value", + a: "a2", + b: "a100", + want: -1, + }, + { + name: "numeric runs with equal value use raw tie break", + a: "a02", + b: "a2", + want: -1, + }, + { + name: "accents are folded for primary comparison", + a: "À", + b: "B", + want: -1, + }, + { + name: "raw comparison breaks accent ties", + a: "A", + b: "À", + want: -1, + }, + { + name: "hyphen sorts before slash like Intl.Collator fallback", + a: "app-init", + b: "app/app", + want: -1, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if got := cmpSign(comparer(tt.a, tt.b)); got != tt.want { + t.Fatalf("comparer(%q, %q) = %v, want sign %v", tt.a, tt.b, got, tt.want) + } + }) + } +} + +func cmpSign(value int) int { + switch { + case value < 0: + return -1 + case value > 0: + return 1 + default: + return 0 + } +} diff --git a/internal/ls/organizeimports.go b/internal/ls/organizeimports.go index ea558136d66..ddea88bffd1 100644 --- a/internal/ls/organizeimports.go +++ b/internal/ls/organizeimports.go @@ -37,24 +37,25 @@ func (l *LanguageService) OrganizeImports( preferences := l.UserPreferences() comparersToTest, typeOrdersToTest := lsutil.GetDetectionLists(preferences) defaultComparer := comparersToTest[0] + sort := lsutil.ResolveOrganizeImportsSort(preferences) var moduleSpecifierComparer func(a, b string) int var namedImportComparer func(a, b string) int - if !preferences.OrganizeImportsIgnoreCase.IsUnknown() { + if sort != lsutil.OrganizeImportsSortAuto { moduleSpecifierComparer = defaultComparer namedImportComparer = defaultComparer } typeOrder := preferences.OrganizeImportsTypeOrder - if preferences.OrganizeImportsIgnoreCase.IsUnknown() { + if sort == lsutil.OrganizeImportsSortAuto { result, _ := lsutil.DetectModuleSpecifierCaseBySort(topLevelImportGroupDecls, comparersToTest) moduleSpecifierComparer = result } - if typeOrder == lsutil.OrganizeImportsTypeOrderAuto || preferences.OrganizeImportsIgnoreCase.IsUnknown() { + if typeOrder == lsutil.OrganizeImportsTypeOrderAuto || sort == lsutil.OrganizeImportsSortAuto { namedImportComparer2, typeOrder2, found := lsutil.DetectNamedImportOrganizationBySort(topLevelImportDecls, comparersToTest, typeOrdersToTest) if found { - if namedImportComparer == nil || preferences.OrganizeImportsIgnoreCase.IsUnknown() { + if namedImportComparer == nil || sort == lsutil.OrganizeImportsSortAuto { namedImportComparer = namedImportComparer2 } if typeOrder == lsutil.OrganizeImportsTypeOrderAuto { diff --git a/internal/ls/rename.go b/internal/ls/rename.go index a6007159300..b1ef362666c 100644 --- a/internal/ls/rename.go +++ b/internal/ls/rename.go @@ -80,6 +80,7 @@ func (l *LanguageService) symbolAndEntriesToRename(ctx context.Context, params * defer done() quotePreference := lsutil.GetQuotePreference(sourceFile, l.UserPreferences()) + useAliasesForRename := l.UserPreferences().UseAliasesForRename.IsTrueOrUnknown() for _, entry := range entries { uri := l.getFileNameOfEntry(entry) @@ -88,7 +89,7 @@ func (l *LanguageService) symbolAndEntriesToRename(ctx context.Context, params * } textEdit := &lsproto.TextEdit{ Range: l.getRangeOfEntry(entry), - NewText: l.getTextForRename(data.OriginalNode, entry, params.NewName, ch, quotePreference), + NewText: l.getTextForRename(data.OriginalNode, entry, params.NewName, ch, quotePreference, useAliasesForRename), } changes[uri] = append(changes[uri], textEdit) } @@ -186,7 +187,7 @@ func isDefinedInLibraryFile(program *compiler.Program, declaration *ast.Node) bo // wouldRenameInOtherNodeModules checks if renaming the symbol would affect node_modules. func wouldRenameInOtherNodeModules(originalFile *ast.SourceFile, symbol *ast.Symbol, ch *checker.Checker, preferences lsutil.UserPreferences) *diagnostics.Message { sym := symbol - if !preferences.UseAliasesForRename.IsTrue() && sym.Flags&ast.SymbolFlagsAlias != 0 { + if !preferences.UseAliasesForRename.IsTrueOrUnknown() && sym.Flags&ast.SymbolFlagsAlias != 0 { importSpecifier := core.Find(sym.Declarations, ast.IsImportSpecifier) if importSpecifier != nil && importSpecifier.AsImportSpecifier().PropertyName == nil { sym = ch.GetAliasedSymbol(sym) @@ -293,8 +294,8 @@ func (l *LanguageService) getNewFileNameForModuleRename(oldPath, specifierText, return newPath } -func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *ReferenceEntry, newText string, ch *checker.Checker, quotePreference lsutil.QuotePreference) string { - if entry.kind != entryKindRange && (ast.IsIdentifier(originalNode) || ast.IsStringLiteralLike(originalNode)) { +func (l *LanguageService) getTextForRename(originalNode *ast.Node, entry *ReferenceEntry, newText string, ch *checker.Checker, quotePreference lsutil.QuotePreference, useAliasesForRename bool) string { + if useAliasesForRename && entry.kind != entryKindRange && (ast.IsIdentifier(originalNode) || ast.IsStringLiteralLike(originalNode)) { node := ast.GetReparsedNodeForNode(entry.node) kind := entry.kind parent := node.Parent diff --git a/internal/ls/signaturehelp.go b/internal/ls/signaturehelp.go index 25ebb329f3e..c837656666e 100644 --- a/internal/ls/signaturehelp.go +++ b/internal/ls/signaturehelp.go @@ -294,7 +294,12 @@ func (l *LanguageService) createSignatureHelpItems(ctx context.Context, candidat } var callTargetDisplayParts strings.Builder - if callTargetSymbol != nil { + // A contextual signature for an anonymous inline function type (e.g. a callback + // argument) has a synthetic symbol whose name is an internal marker such as + // "\xFEtype". There is no meaningful name to show, so render the signature with + // no prefix (as we already do when there is no call target symbol) rather than + // leaking the internal name. + if callTargetSymbol != nil && !strings.HasPrefix(callTargetSymbol.Name, ast.InternalSymbolNamePrefix) { if useFullPrefix { callTargetDisplayParts.WriteString(c.SymbolToStringEx(callTargetSymbol, sourceFile.AsNode(), ast.SymbolFlagsNone, checker.SymbolFormatFlagsUseAliasDefinedOutsideCurrentScope)) } else { diff --git a/internal/lsp/lsproto/_generate/generate.mts b/internal/lsp/lsproto/_generate/generate.mts index 7ca90a895b9..651c9cecfb6 100755 --- a/internal/lsp/lsproto/_generate/generate.mts +++ b/internal/lsp/lsproto/_generate/generate.mts @@ -2296,7 +2296,17 @@ function generateCode() { const useOmitzero = prop.optional || prop.omitzeroValue; const goType = (prop.optional || type.needsPointer) && !prop.omitzeroValue ? `*${type.name}` : type.name; - writeLine(`\t${goFieldName(prop)} ${goType} \`json:"${prop.name}${useOmitzero ? ",omitzero" : ""}"\``); + // Strictness markers for the shared unmarshalStruct interpreter: + // required = must be present. A nilable field (pointer/slice/map, + // not omitzero) rejects an explicit JSON null by default; mark the + // rare spec-nullable ones with `nullable` so the interpreter allows it. + const required = !prop.optional && !prop.omitzeroValue; + const nilable = prop.optional || type.needsPointer || type.name.startsWith("[]") || type.name.startsWith("map[") || !!prop.omitzeroValue; + const nullable = nilable && (typeCanBeNull(prop.type) || !!prop.omitzeroValue); + const lspMarkers = [required ? "required" : "", nullable ? "nullable" : ""].filter(Boolean).join(","); + const lspTag = lspMarkers ? ` lsp:"${lspMarkers}"` : ""; + + writeLine(`\t${goFieldName(prop)} ${goType} \`json:"${prop.name}${useOmitzero ? ",omitzero" : ""}"${lspTag}\``); if (includeDocumentation) { writeLine(""); @@ -2372,82 +2382,8 @@ function generateCode() { if ((requiredProps.length > 0 || hasNullRejectableFields) && structure.name !== "Registration") { writeLine(`\tvar _ json.UnmarshalerFrom = (*${structure.name})(nil)`); writeLine(""); - writeLine(`func (s *${structure.name}) UnmarshalJSONFrom(dec *json.Decoder) error {`); - if (requiredProps.length > 0) { - writeLine(`\tconst (`); - for (let i = 0; i < requiredProps.length; i++) { - const prop = requiredProps[i]; - const iotaPrefix = i === 0 ? " uint = 1 << iota" : ""; - writeLine(`\t\tmissing${goFieldName(prop)}${iotaPrefix}`); - } - writeLine(`\t\t_missingLast`); - writeLine(`\t)`); - writeLine(`\tmissing := _missingLast - 1`); - writeLine(""); - } - - writeLine(`\tif k := dec.PeekKind(); k != '{' {`); - writeLine(`\t\treturn errNotObject(k)`); - writeLine(`\t}`); - writeLine(`\tif _, err := dec.ReadToken(); err != nil {`); - writeLine(`\t\treturn err`); - writeLine(`\t}`); - writeLine(""); - - writeLine(`\tfor dec.PeekKind() != '}' {`); - writeLine(`\t\tname, err := dec.ReadValue()`); - writeLine(`\t\tif err != nil {`); - writeLine(`\t\t\treturn err`); - writeLine(`\t\t}`); - writeLine(`\t\tswitch string(name) {`); - - for (const prop of structure.properties) { - writeLine(`\t\tcase \`"${prop.name}"\`:`); - if (!prop.optional && !prop.omitzeroValue) { - writeLine(`\t\t\tmissing &^= missing${goFieldName(prop)}`); - } - // Reject null for fields whose types cannot represent null but whose Go types - // silently accept it (pointers, slices, maps). - const resolvedType = resolveType(prop.type); - const goTypeAcceptsNull = (prop.optional || resolvedType.needsPointer || resolvedType.name.startsWith("[]") || resolvedType.name.startsWith("map[")) && !prop.omitzeroValue; - if (goTypeAcceptsNull && !typeCanBeNull(prop.type)) { - writeLine(`\t\t\tif dec.PeekKind() == 'n' {`); - writeLine(`\t\t\t\treturn errNull("${prop.name}")`); - writeLine(`\t\t\t}`); - } - writeLine(`\t\t\tif err := json.UnmarshalDecode(dec, &s.${goFieldName(prop)}); err != nil {`); - writeLine(`\t\t\t\treturn err`); - writeLine(`\t\t\t}`); - } - - writeLine(`\t\tdefault:`); - writeLine(`\t\t\tif err := dec.SkipValue(); err != nil {`); - writeLine(`\t\t\t\treturn err`); - writeLine(`\t\t\t}`); - writeLine(`\t\t}`); - writeLine(`\t}`); - writeLine(""); - - writeLine(`\tif _, err := dec.ReadToken(); err != nil {`); - writeLine(`\t\treturn err`); - writeLine(`\t}`); - writeLine(""); - - if (requiredProps.length > 0) { - writeLine(`\tif missing != 0 {`); - writeLine(`\t\tvar missingProps []string`); - for (const prop of requiredProps) { - writeLine(`\t\tif missing&missing${goFieldName(prop)} != 0 {`); - writeLine(`\t\t\tmissingProps = append(missingProps, "${prop.name}")`); - writeLine(`\t\t}`); - } - writeLine(`\t\treturn errMissing(missingProps)`); - writeLine(`\t}`); - writeLine(""); - } - - writeLine(`\treturn nil`); + writeLine(`\treturn unmarshalStruct(s, dec)`); writeLine(`}`); writeLine(""); } @@ -2474,9 +2410,7 @@ function generateCode() { writeLine(`\tif s.RegisterOptions == nil {`); writeLine(`\t\tpanic("RegisterOptions must be set")`); writeLine(`\t}`); - const regParts = registrationMethods.map(r => `boolToInt(s.RegisterOptions.${r.fieldName} != nil)`); - const regSum = regParts.join(" +\n\t\t"); - writeLine(`\tassertOnlyOne("exactly one element of RegisterOptions should be set", ${regSum})`); + writeLine(`\tassertOnlyOne("exactly one element of RegisterOptions should be set", countNonNil(s.RegisterOptions))`); writeLine(""); writeLine(`\tif err := enc.WriteToken(json.BeginObject); err != nil {`); @@ -2920,70 +2854,6 @@ function generateCode() { const requestsAndNotifications: (Request | Notification)[] = [...model.requests, ...model.notifications]; - // Generate unmarshalParams function - writeLine("func unmarshalParams(method Method, data []byte) (any, error) {"); - writeLine("\tswitch method {"); - - // Requests and notifications - for (const request of requestsAndNotifications) { - const methodName = methodNameIdentifier(request.method); - - if (!request.params) { - writeLine(`\tcase Method${methodName}:`); - writeLine(`\t\treturn unmarshalEmpty(data)`); - continue; - } - if (Array.isArray(request.params)) { - throw new Error("Unexpected array type for request params: " + JSON.stringify(request.params)); - } - - const resolvedType = resolveType(request.params); - - writeLine(`\tcase Method${methodName}:`); - if (resolvedType.name === "any") { - writeLine(`\t\treturn unmarshalAny(data)`); - } - else { - writeLine(`\t\treturn unmarshalPtrTo[${resolvedType.name}](data)`); - } - } - - writeLine("\tdefault:"); - writeLine(`\t\treturn unmarshalAny(data)`); - writeLine("\t}"); - writeLine("}"); - writeLine(""); - - // Generate unmarshalResult function - writeLine("func unmarshalResult(method Method, data []byte) (any, error) {"); - writeLine("\tswitch method {"); - - // Only requests have results, not notifications - for (const request of model.requests) { - const methodName = methodNameIdentifier(request.method); - - if (!("result" in request)) { - continue; - } - - let responseTypeName: string; - if (request.typeName && request.typeName.endsWith("Request")) { - responseTypeName = request.typeName.replace(/Request$/, "Response"); - } - else { - responseTypeName = `${methodName}Response`; - } - - writeLine(`\tcase Method${methodName}:`); - writeLine(`\t\treturn unmarshalValue[${responseTypeName}](data)`); - } - - writeLine("\tdefault:"); - writeLine(`\t\treturn unmarshalAny(data)`); - writeLine("\t}"); - writeLine("}"); - writeLine(""); - writeLine("// Methods"); writeLine("const ("); for (const request of requestsAndNotifications) { @@ -3099,37 +2969,9 @@ function generateCode() { // Marshal method writeLine(`var _ json.MarshalerTo = (*${name})(nil)`); writeLine(""); - - writeLine(`func (o *${name}) MarshalJSONTo(enc *json.Encoder) error {`); - - // Determine if this union contained null (check if any member has containedNull = true) const unionContainedNull = members.some(member => member.containedNull); - // Always assert for non-nullable unions; for nullable unions, only when there are multiple fields. - if (!unionContainedNull || fieldEntries.length > 1) { - const parts = fieldEntries.map(e => `boolToInt(o.${e.fieldName} != nil)`); - const sum = parts.length > 3 ? parts.join(" +\n\t\t") : parts.join(" + "); - if (unionContainedNull) { - writeLine(`\tassertAtMostOne("more than one element of ${name} is set", ${sum})`); - } - else { - writeLine(`\tassertOnlyOne("exactly one element of ${name} should be set", ${sum})`); - } - writeLine(""); - } - - for (const entry of fieldEntries) { - writeLine(`\tif o.${entry.fieldName} != nil {`); - writeLine(`\t\treturn json.MarshalEncode(enc, o.${entry.fieldName})`); - writeLine(`\t}`); - } - - // If all fields are nil, marshal as null (only for unions that can contain null) - if (unionContainedNull) { - writeLine(`\treturn enc.WriteToken(json.Null)`); - } - else { - writeLine(`\tpanic("unreachable")`); - } + writeLine(`func (o *${name}) MarshalJSONTo(enc *json.Encoder) error {`); + writeLine(`\treturn marshalUnion(o, enc, "${name}", ${unionContainedNull})`); writeLine(`}`); writeLine(""); diff --git a/internal/lsp/lsproto/jsonrpc.go b/internal/lsp/lsproto/jsonrpc.go index a780322dc49..5e0715d351d 100644 --- a/internal/lsp/lsproto/jsonrpc.go +++ b/internal/lsp/lsproto/jsonrpc.go @@ -54,9 +54,8 @@ func (m *Message) UnmarshalJSON(data []byte) error { } var params any - var err error if len(raw.Params) > 0 { - params, err = unmarshalParams(raw.Method, raw.Params) + params = raw.Params } if raw.ID == nil { @@ -71,9 +70,6 @@ func (m *Message) UnmarshalJSON(data []byte) error { Params: params, } - if err != nil { - return fmt.Errorf("%w: %w", ErrorCodeInvalidParams, err) - } return nil } @@ -112,11 +108,8 @@ func (r *RequestMessage) UnmarshalJSON(data []byte) error { r.ID = raw.ID r.Method = raw.Method - - var err error - r.Params, err = unmarshalParams(raw.Method, raw.Params) - if err != nil { - return fmt.Errorf("%w: %w", ErrorCodeInvalidRequest, err) + if len(raw.Params) > 0 { + r.Params = raw.Params } return nil diff --git a/internal/lsp/lsproto/lsp.go b/internal/lsp/lsproto/lsp.go index 60c4b447797..152820346cc 100644 --- a/internal/lsp/lsproto/lsp.go +++ b/internal/lsp/lsproto/lsp.go @@ -84,44 +84,6 @@ type URI string // !!! type Method string -func unmarshalPtrTo[T any](data []byte) (*T, error) { - var v T - if err := json.Unmarshal(data, &v); err != nil { - return nil, fmt.Errorf("failed to unmarshal %T: %w", (*T)(nil), err) - } - return &v, nil -} - -func unmarshalValue[T any](data []byte) (T, error) { - var v T - if err := json.Unmarshal(data, &v); err != nil { - return *new(T), fmt.Errorf("failed to unmarshal %T: %w", (*T)(nil), err) - } - return v, nil -} - -func unmarshalAny(data []byte) (any, error) { - var v any - if err := json.Unmarshal(data, &v); err != nil { - return nil, fmt.Errorf("failed to unmarshal any: %w", err) - } - return v, nil -} - -func unmarshalEmpty(data []byte) (any, error) { - if len(data) != 0 { - return nil, fmt.Errorf("expected empty, got: %s", string(data)) - } - return nil, nil -} - -func boolToInt(b bool) int { - if b { - return 1 - } - return 0 -} - func errNotObject(k json.Kind) error { return fmt.Errorf("expected object start, but encountered %v", k) } @@ -230,20 +192,16 @@ type RequestInfo[Params, Resp any] struct { } func (info RequestInfo[Params, Resp]) UnmarshalResult(result any) (Resp, error) { - if r, ok := result.(Resp); ok { - return r, nil - } - raw, ok := result.(json.Value) if !ok { return *new(Resp), fmt.Errorf("expected json.Value, got %T", result) } - r, err := unmarshalResult(info.Method, raw) - if err != nil { + var r Resp + if err := json.Unmarshal(raw, &r); err != nil { return *new(Resp), err } - return r.(Resp), nil + return r, nil } func (info RequestInfo[Params, Resp]) NewRequestMessage(id *jsonrpc.ID, params Params) *RequestMessage { @@ -266,6 +224,45 @@ func (info NotificationInfo[Params]) NewNotificationMessage(params Params) *Requ } } +// UnmarshalParams decodes the params of an inbound request or notification +// message into the requested type. Inbound messages store their params as a +// raw [json.Value] (see [Message.UnmarshalJSON]); decoding is deferred to the +// point of dispatch so that param types for methods the server never handles +// are not forced into the binary. +// +// A [NoParams] method must be given no params; every other method must be given +// params as an object or array. A violation returns [ErrorCodeInvalidParams]. +func UnmarshalParams[T any](req *RequestMessage) (T, error) { + var params T + var raw json.Value + if req.Params != nil { + v, ok := req.Params.(json.Value) + if !ok { + return params, fmt.Errorf("%w: unexpected params type %T", ErrorCodeInvalidParams, req.Params) + } + raw = v + } + + // params is the zero value of T; this asserts on its type, i.e. whether the + // method was declared with NoParams. + if _, declaresNoParams := any(params).(NoParams); declaresNoParams { + if len(raw) != 0 { + return params, fmt.Errorf("%w: expected no params, got %s", ErrorCodeInvalidParams, raw) + } + return params, nil + } + + // The base protocol defines params as `array | object`; reject anything else + // (absent, null, or a scalar). + if k := raw.Kind(); k != '{' && k != '[' { + return params, fmt.Errorf("%w: params must be an object or array", ErrorCodeInvalidParams) + } + if err := json.Unmarshal(raw, ¶ms); err != nil { + return params, fmt.Errorf("%w: %w", ErrorCodeInvalidParams, err) + } + return params, nil +} + type Null struct{} func (Null) UnmarshalJSONFrom(dec *json.Decoder) error { diff --git a/internal/lsp/lsproto/lsp_generated.go b/internal/lsp/lsproto/lsp_generated.go index ce399920a81..481c2c8534f 100644 --- a/internal/lsp/lsproto/lsp_generated.go +++ b/internal/lsp/lsproto/lsp_generated.go @@ -16,10 +16,10 @@ import ( type ImplementationParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -40,81 +40,15 @@ func (s *ImplementationParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*ImplementationParams)(nil) func (s *ImplementationParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Represents a location inside a resource, such as a line // inside a text file. type Location struct { - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` } func (s Location) GetLocation() Location { @@ -124,65 +58,13 @@ func (s Location) GetLocation() Location { var _ json.UnmarshalerFrom = (*Location)(nil) func (s *Location) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - missingRange - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type ImplementationRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -194,72 +76,15 @@ type ImplementationRegistrationOptions struct { var _ json.UnmarshalerFrom = (*ImplementationRegistrationOptions)(nil) func (s *ImplementationRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type TypeDefinitionParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -280,79 +105,13 @@ func (s *TypeDefinitionParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*TypeDefinitionParams)(nil) func (s *TypeDefinitionParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type TypeDefinitionRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -364,247 +123,46 @@ type TypeDefinitionRegistrationOptions struct { var _ json.UnmarshalerFrom = (*TypeDefinitionRegistrationOptions)(nil) func (s *TypeDefinitionRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A workspace folder inside a client. type WorkspaceFolder struct { // The associated URI for this workspace folder. - Uri URI `json:"uri"` + Uri URI `json:"uri" lsp:"required"` // The name of the workspace folder. Used to refer to this // workspace folder in the user interface. - Name string `json:"name"` + Name string `json:"name" lsp:"required"` } var _ json.UnmarshalerFrom = (*WorkspaceFolder)(nil) func (s *WorkspaceFolder) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - missingName - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"name"`: - missing &^= missingName - if err := json.UnmarshalDecode(dec, &s.Name); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - if missing&missingName != 0 { - missingProps = append(missingProps, "name") - } - return errMissing(missingProps) - } - - return nil -} - -// The parameters of a `workspace/didChangeWorkspaceFolders` notification. -type DidChangeWorkspaceFoldersParams struct { - // The actual workspace folder change event. - Event *WorkspaceFoldersChangeEvent `json:"event"` -} +// The parameters of a `workspace/didChangeWorkspaceFolders` notification. +type DidChangeWorkspaceFoldersParams struct { + // The actual workspace folder change event. + Event *WorkspaceFoldersChangeEvent `json:"event" lsp:"required"` +} var _ json.UnmarshalerFrom = (*DidChangeWorkspaceFoldersParams)(nil) func (s *DidChangeWorkspaceFoldersParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingEvent uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"event"`: - missing &^= missingEvent - if dec.PeekKind() == 'n' { - return errNull("event") - } - if err := json.UnmarshalDecode(dec, &s.Event); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingEvent != 0 { - missingProps = append(missingProps, "event") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters of a configuration request. type ConfigurationParams struct { - Items []*ConfigurationItem `json:"items"` + Items []*ConfigurationItem `json:"items" lsp:"required"` } var _ json.UnmarshalerFrom = (*ConfigurationParams)(nil) func (s *ConfigurationParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingItems uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"items"`: - missing &^= missingItems - if dec.PeekKind() == 'n' { - return errNull("items") - } - if err := json.UnmarshalDecode(dec, &s.Items); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingItems != 0 { - missingProps = append(missingProps, "items") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters for a DocumentColorRequest. @@ -617,7 +175,7 @@ type DocumentColorParams struct { PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` } func (s *DocumentColorParams) TextDocumentURI() DocumentUri { @@ -627,137 +185,28 @@ func (s *DocumentColorParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*DocumentColorParams)(nil) func (s *DocumentColorParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Represents a color range from a document. type ColorInformation struct { // The range in the document where this color appears. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The actual color value for this color range. - Color Color `json:"color"` + Color Color `json:"color" lsp:"required"` } var _ json.UnmarshalerFrom = (*ColorInformation)(nil) func (s *ColorInformation) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - missingColor - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"color"`: - missing &^= missingColor - if err := json.UnmarshalDecode(dec, &s.Color); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingColor != 0 { - missingProps = append(missingProps, "color") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type DocumentColorRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -769,64 +218,7 @@ type DocumentColorRegistrationOptions struct { var _ json.UnmarshalerFrom = (*DocumentColorRegistrationOptions)(nil) func (s *DocumentColorRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters for a ColorPresentationRequest. @@ -839,13 +231,13 @@ type ColorPresentationParams struct { PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The color to request presentations for. - Color Color `json:"color"` + Color Color `json:"color" lsp:"required"` // The range where the color would be inserted. Serves as a context. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` } func (s *ColorPresentationParams) TextDocumentURI() DocumentUri { @@ -855,89 +247,14 @@ func (s *ColorPresentationParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*ColorPresentationParams)(nil) func (s *ColorPresentationParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingColor - missingRange - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"color"`: - missing &^= missingColor - if err := json.UnmarshalDecode(dec, &s.Color); err != nil { - return err - } - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingColor != 0 { - missingProps = append(missingProps, "color") - } - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - return errMissing(missingProps) - } - - return nil -} - -type ColorPresentation struct { - // The label of this color presentation. It will be shown on the color - // picker header. By default this is also the text that is inserted when selecting - // this color presentation. - Label string `json:"label"` +type ColorPresentation struct { + // The label of this color presentation. It will be shown on the color + // picker header. By default this is also the text that is inserted when selecting + // this color presentation. + Label string `json:"label" lsp:"required"` // An edit which is applied to a document when selecting // this presentation for the color. When `falsy` the label @@ -952,64 +269,7 @@ type ColorPresentation struct { var _ json.UnmarshalerFrom = (*ColorPresentation)(nil) func (s *ColorPresentation) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingLabel uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"label"`: - missing &^= missingLabel - if err := json.UnmarshalDecode(dec, &s.Label); err != nil { - return err - } - case `"textEdit"`: - if dec.PeekKind() == 'n' { - return errNull("textEdit") - } - if err := json.UnmarshalDecode(dec, &s.TextEdit); err != nil { - return err - } - case `"additionalTextEdits"`: - if dec.PeekKind() == 'n' { - return errNull("additionalTextEdits") - } - if err := json.UnmarshalDecode(dec, &s.AdditionalTextEdits); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingLabel != 0 { - missingProps = append(missingProps, "label") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type WorkDoneProgressOptions struct { @@ -1019,94 +279,20 @@ type WorkDoneProgressOptions struct { var _ json.UnmarshalerFrom = (*WorkDoneProgressOptions)(nil) func (s *WorkDoneProgressOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // General text document registration options. type TextDocumentRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` } var _ json.UnmarshalerFrom = (*TextDocumentRegistrationOptions)(nil) func (s *TextDocumentRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters for a FoldingRangeRequest. @@ -1119,7 +305,7 @@ type FoldingRangeParams struct { PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` } func (s *FoldingRangeParams) TextDocumentURI() DocumentUri { @@ -1129,64 +315,7 @@ func (s *FoldingRangeParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*FoldingRangeParams)(nil) func (s *FoldingRangeParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Represents a folding range. To be valid, start and end line must be bigger than zero and smaller @@ -1194,14 +323,14 @@ func (s *FoldingRangeParams) UnmarshalJSONFrom(dec *json.Decoder) error { type FoldingRange struct { // The zero-based start line of the range to fold. The folded area starts after the line's last character. // To be valid, the end must be zero or larger and smaller than the number of lines in the document. - StartLine uint32 `json:"startLine"` + StartLine uint32 `json:"startLine" lsp:"required"` // The zero-based character offset from where the folded range starts. If not defined, defaults to the length of the start line. StartCharacter *uint32 `json:"startCharacter,omitzero"` // The zero-based end line of the range to fold. The folded area ends with the line's last character. // To be valid, the end must be zero or larger and smaller than the number of lines in the document. - EndLine uint32 `json:"endLine"` + EndLine uint32 `json:"endLine" lsp:"required"` // The zero-based character offset before the folded range ends. If not defined, defaults to the length of the end line. EndCharacter *uint32 `json:"endCharacter,omitzero"` @@ -1222,93 +351,13 @@ type FoldingRange struct { var _ json.UnmarshalerFrom = (*FoldingRange)(nil) func (s *FoldingRange) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingStartLine uint = 1 << iota - missingEndLine - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"startLine"`: - missing &^= missingStartLine - if err := json.UnmarshalDecode(dec, &s.StartLine); err != nil { - return err - } - case `"startCharacter"`: - if dec.PeekKind() == 'n' { - return errNull("startCharacter") - } - if err := json.UnmarshalDecode(dec, &s.StartCharacter); err != nil { - return err - } - case `"endLine"`: - missing &^= missingEndLine - if err := json.UnmarshalDecode(dec, &s.EndLine); err != nil { - return err - } - case `"endCharacter"`: - if dec.PeekKind() == 'n' { - return errNull("endCharacter") - } - if err := json.UnmarshalDecode(dec, &s.EndCharacter); err != nil { - return err - } - case `"kind"`: - if dec.PeekKind() == 'n' { - return errNull("kind") - } - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"collapsedText"`: - if dec.PeekKind() == 'n' { - return errNull("collapsedText") - } - if err := json.UnmarshalDecode(dec, &s.CollapsedText); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingStartLine != 0 { - missingProps = append(missingProps, "startLine") - } - if missing&missingEndLine != 0 { - missingProps = append(missingProps, "endLine") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type FoldingRangeRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -1320,72 +369,15 @@ type FoldingRangeRegistrationOptions struct { var _ json.UnmarshalerFrom = (*FoldingRangeRegistrationOptions)(nil) func (s *FoldingRangeRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil -} - -type DeclarationParams struct { - // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` +type DeclarationParams struct { + // The text document. + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -1406,73 +398,7 @@ func (s *DeclarationParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*DeclarationParams)(nil) func (s *DeclarationParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type DeclarationRegistrationOptions struct { @@ -1480,7 +406,7 @@ type DeclarationRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` // The id used to register the request. The id can be used to deregister // the request again. See also Registration#id. @@ -1490,64 +416,7 @@ type DeclarationRegistrationOptions struct { var _ json.UnmarshalerFrom = (*DeclarationRegistrationOptions)(nil) func (s *DeclarationRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A parameter literal used in selection range requests. @@ -1560,10 +429,10 @@ type SelectionRangeParams struct { PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The positions inside the text document. - Positions []Position `json:"positions"` + Positions []Position `json:"positions" lsp:"required"` } func (s *SelectionRangeParams) TextDocumentURI() DocumentUri { @@ -1573,83 +442,14 @@ func (s *SelectionRangeParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*SelectionRangeParams)(nil) func (s *SelectionRangeParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPositions - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"positions"`: - missing &^= missingPositions - if dec.PeekKind() == 'n' { - return errNull("positions") - } - if err := json.UnmarshalDecode(dec, &s.Positions); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPositions != 0 { - missingProps = append(missingProps, "positions") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A selection range represents a part of a selection hierarchy. A selection range // may have a parent selection range that contains it. type SelectionRange struct { // The range of this selection range. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The parent selection range containing this range. Therefore `parent.range` must contain `this.range`. Parent *SelectionRange `json:"parent,omitzero"` @@ -1658,57 +458,7 @@ type SelectionRange struct { var _ json.UnmarshalerFrom = (*SelectionRange)(nil) func (s *SelectionRange) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"parent"`: - if dec.PeekKind() == 'n' { - return errNull("parent") - } - if err := json.UnmarshalDecode(dec, &s.Parent); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type SelectionRangeRegistrationOptions struct { @@ -1716,7 +466,7 @@ type SelectionRangeRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` // The id used to register the request. The id can be used to deregister // the request again. See also Registration#id. @@ -1726,172 +476,29 @@ type SelectionRangeRegistrationOptions struct { var _ json.UnmarshalerFrom = (*SelectionRangeRegistrationOptions)(nil) func (s *SelectionRangeRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil -} - -type WorkDoneProgressCreateParams struct { - // The token to be used to report progress. - Token IntegerOrString `json:"token"` -} +type WorkDoneProgressCreateParams struct { + // The token to be used to report progress. + Token IntegerOrString `json:"token" lsp:"required"` +} var _ json.UnmarshalerFrom = (*WorkDoneProgressCreateParams)(nil) func (s *WorkDoneProgressCreateParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingToken uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"token"`: - missing &^= missingToken - if err := json.UnmarshalDecode(dec, &s.Token); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingToken != 0 { - missingProps = append(missingProps, "token") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type WorkDoneProgressCancelParams struct { // The token to be used to report progress. - Token IntegerOrString `json:"token"` + Token IntegerOrString `json:"token" lsp:"required"` } var _ json.UnmarshalerFrom = (*WorkDoneProgressCancelParams)(nil) func (s *WorkDoneProgressCancelParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingToken uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"token"`: - missing &^= missingToken - if err := json.UnmarshalDecode(dec, &s.Token); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingToken != 0 { - missingProps = append(missingProps, "token") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameter of a `textDocument/prepareCallHierarchy` request. @@ -1899,10 +506,10 @@ func (s *WorkDoneProgressCancelParams) UnmarshalJSONFrom(dec *json.Decoder) erro // Since: 3.16.0 type CallHierarchyPrepareParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -1919,66 +526,7 @@ func (s *CallHierarchyPrepareParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*CallHierarchyPrepareParams)(nil) func (s *CallHierarchyPrepareParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Represents programming constructs like functions or constructors in the context @@ -1987,10 +535,10 @@ func (s *CallHierarchyPrepareParams) UnmarshalJSONFrom(dec *json.Decoder) error // Since: 3.16.0 type CallHierarchyItem struct { // The name of this item. - Name string `json:"name"` + Name string `json:"name" lsp:"required"` // The kind of this item. - Kind SymbolKind `json:"kind"` + Kind SymbolKind `json:"kind" lsp:"required"` // Tags for this item. Tags *[]SymbolTag `json:"tags,omitzero"` @@ -1999,14 +547,14 @@ type CallHierarchyItem struct { Detail *string `json:"detail,omitzero"` // The resource identifier of this item. - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` // The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g. comments and code. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The range that should be selected and revealed when this symbol is being picked, e.g. the name of a function. // Must be contained by the `range`. - SelectionRange Range `json:"selectionRange"` + SelectionRange Range `json:"selectionRange" lsp:"required"` // A data entry field that is preserved between a call hierarchy prepare and // incoming calls or outgoing calls requests. @@ -2023,107 +571,7 @@ func (s CallHierarchyItem) GetLocation() Location { var _ json.UnmarshalerFrom = (*CallHierarchyItem)(nil) func (s *CallHierarchyItem) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingName uint = 1 << iota - missingKind - missingUri - missingRange - missingSelectionRange - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"name"`: - missing &^= missingName - if err := json.UnmarshalDecode(dec, &s.Name); err != nil { - return err - } - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"tags"`: - if dec.PeekKind() == 'n' { - return errNull("tags") - } - if err := json.UnmarshalDecode(dec, &s.Tags); err != nil { - return err - } - case `"detail"`: - if dec.PeekKind() == 'n' { - return errNull("detail") - } - if err := json.UnmarshalDecode(dec, &s.Detail); err != nil { - return err - } - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"selectionRange"`: - missing &^= missingSelectionRange - if err := json.UnmarshalDecode(dec, &s.SelectionRange); err != nil { - return err - } - case `"data"`: - if dec.PeekKind() == 'n' { - return errNull("data") - } - if err := json.UnmarshalDecode(dec, &s.Data); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingName != 0 { - missingProps = append(missingProps, "name") - } - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingSelectionRange != 0 { - missingProps = append(missingProps, "selectionRange") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Call hierarchy options used during static or dynamic registration. @@ -2132,7 +580,7 @@ func (s *CallHierarchyItem) UnmarshalJSONFrom(dec *json.Decoder) error { type CallHierarchyRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -2144,64 +592,7 @@ type CallHierarchyRegistrationOptions struct { var _ json.UnmarshalerFrom = (*CallHierarchyRegistrationOptions)(nil) func (s *CallHierarchyRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameter of a `callHierarchy/incomingCalls` request. @@ -2215,149 +606,31 @@ type CallHierarchyIncomingCallsParams struct { // the client. PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` - Item *CallHierarchyItem `json:"item"` + Item *CallHierarchyItem `json:"item" lsp:"required"` } var _ json.UnmarshalerFrom = (*CallHierarchyIncomingCallsParams)(nil) func (s *CallHierarchyIncomingCallsParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingItem uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"item"`: - missing &^= missingItem - if dec.PeekKind() == 'n' { - return errNull("item") - } - if err := json.UnmarshalDecode(dec, &s.Item); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingItem != 0 { - missingProps = append(missingProps, "item") - } - return errMissing(missingProps) - } - - return nil -} + return unmarshalStruct(s, dec) +} // Represents an incoming call, e.g. a caller of a method or constructor. // // Since: 3.16.0 type CallHierarchyIncomingCall struct { // The item that makes the call. - From *CallHierarchyItem `json:"from"` + From *CallHierarchyItem `json:"from" lsp:"required"` // The ranges at which the calls appear. This is relative to the caller // denoted by `this.from`. - FromRanges []Range `json:"fromRanges"` + FromRanges []Range `json:"fromRanges" lsp:"required"` } var _ json.UnmarshalerFrom = (*CallHierarchyIncomingCall)(nil) func (s *CallHierarchyIncomingCall) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingFrom uint = 1 << iota - missingFromRanges - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"from"`: - missing &^= missingFrom - if dec.PeekKind() == 'n' { - return errNull("from") - } - if err := json.UnmarshalDecode(dec, &s.From); err != nil { - return err - } - case `"fromRanges"`: - missing &^= missingFromRanges - if dec.PeekKind() == 'n' { - return errNull("fromRanges") - } - if err := json.UnmarshalDecode(dec, &s.FromRanges); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingFrom != 0 { - missingProps = append(missingProps, "from") - } - if missing&missingFromRanges != 0 { - missingProps = append(missingProps, "fromRanges") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameter of a `callHierarchy/outgoingCalls` request. @@ -2371,73 +644,13 @@ type CallHierarchyOutgoingCallsParams struct { // the client. PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` - Item *CallHierarchyItem `json:"item"` + Item *CallHierarchyItem `json:"item" lsp:"required"` } var _ json.UnmarshalerFrom = (*CallHierarchyOutgoingCallsParams)(nil) func (s *CallHierarchyOutgoingCallsParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingItem uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"item"`: - missing &^= missingItem - if dec.PeekKind() == 'n' { - return errNull("item") - } - if err := json.UnmarshalDecode(dec, &s.Item); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingItem != 0 { - missingProps = append(missingProps, "item") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Represents an outgoing call, e.g. calling a getter from a method or a method from a constructor etc. @@ -2445,76 +658,18 @@ func (s *CallHierarchyOutgoingCallsParams) UnmarshalJSONFrom(dec *json.Decoder) // Since: 3.16.0 type CallHierarchyOutgoingCall struct { // The item that is called. - To *CallHierarchyItem `json:"to"` + To *CallHierarchyItem `json:"to" lsp:"required"` // The range at which this item is called. This is the range relative to the caller, e.g the item // passed to `provideCallHierarchyOutgoingCalls` // and not `this.to`. - FromRanges []Range `json:"fromRanges"` + FromRanges []Range `json:"fromRanges" lsp:"required"` } var _ json.UnmarshalerFrom = (*CallHierarchyOutgoingCall)(nil) func (s *CallHierarchyOutgoingCall) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTo uint = 1 << iota - missingFromRanges - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"to"`: - missing &^= missingTo - if dec.PeekKind() == 'n' { - return errNull("to") - } - if err := json.UnmarshalDecode(dec, &s.To); err != nil { - return err - } - case `"fromRanges"`: - missing &^= missingFromRanges - if dec.PeekKind() == 'n' { - return errNull("fromRanges") - } - if err := json.UnmarshalDecode(dec, &s.FromRanges); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTo != 0 { - missingProps = append(missingProps, "to") - } - if missing&missingFromRanges != 0 { - missingProps = append(missingProps, "fromRanges") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.16.0 @@ -2527,7 +682,7 @@ type SemanticTokensParams struct { PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` } func (s *SemanticTokensParams) TextDocumentURI() DocumentUri { @@ -2537,64 +692,7 @@ func (s *SemanticTokensParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*SemanticTokensParams)(nil) func (s *SemanticTokensParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.16.0 @@ -2606,135 +704,36 @@ type SemanticTokens struct { ResultId *string `json:"resultId,omitzero"` // The actual tokens. - Data []uint32 `json:"data"` + Data []uint32 `json:"data" lsp:"required"` } var _ json.UnmarshalerFrom = (*SemanticTokens)(nil) func (s *SemanticTokens) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingData uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"resultId"`: - if dec.PeekKind() == 'n' { - return errNull("resultId") - } - if err := json.UnmarshalDecode(dec, &s.ResultId); err != nil { - return err - } - case `"data"`: - missing &^= missingData - if dec.PeekKind() == 'n' { - return errNull("data") - } - if err := json.UnmarshalDecode(dec, &s.Data); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingData != 0 { - missingProps = append(missingProps, "data") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.16.0 type SemanticTokensPartialResult struct { - Data []uint32 `json:"data"` + Data []uint32 `json:"data" lsp:"required"` } var _ json.UnmarshalerFrom = (*SemanticTokensPartialResult)(nil) func (s *SemanticTokensPartialResult) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingData uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"data"`: - missing &^= missingData - if dec.PeekKind() == 'n' { - return errNull("data") - } - if err := json.UnmarshalDecode(dec, &s.Data); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingData != 0 { - missingProps = append(missingProps, "data") - } - return errMissing(missingProps) - } - - return nil -} + return unmarshalStruct(s, dec) +} // Since: 3.16.0 type SemanticTokensRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` // The legend used by the server - Legend *SemanticTokensLegend `json:"legend"` + Legend *SemanticTokensLegend `json:"legend" lsp:"required"` // Server supports providing semantic tokens for a specific range // of a document. @@ -2751,90 +750,7 @@ type SemanticTokensRegistrationOptions struct { var _ json.UnmarshalerFrom = (*SemanticTokensRegistrationOptions)(nil) func (s *SemanticTokensRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - missingLegend - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"legend"`: - missing &^= missingLegend - if dec.PeekKind() == 'n' { - return errNull("legend") - } - if err := json.UnmarshalDecode(dec, &s.Legend); err != nil { - return err - } - case `"range"`: - if dec.PeekKind() == 'n' { - return errNull("range") - } - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"full"`: - if dec.PeekKind() == 'n' { - return errNull("full") - } - if err := json.UnmarshalDecode(dec, &s.Full); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - if missing&missingLegend != 0 { - missingProps = append(missingProps, "legend") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.16.0 @@ -2847,11 +763,11 @@ type SemanticTokensDeltaParams struct { PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The result id of a previous response. The result Id can either point to a full response // or a delta response depending on what was received last. - PreviousResultId string `json:"previousResultId"` + PreviousResultId string `json:"previousResultId" lsp:"required"` } func (s *SemanticTokensDeltaParams) TextDocumentURI() DocumentUri { @@ -2861,73 +777,7 @@ func (s *SemanticTokensDeltaParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*SemanticTokensDeltaParams)(nil) func (s *SemanticTokensDeltaParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPreviousResultId - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"previousResultId"`: - missing &^= missingPreviousResultId - if err := json.UnmarshalDecode(dec, &s.PreviousResultId); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPreviousResultId != 0 { - missingProps = append(missingProps, "previousResultId") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.16.0 @@ -2935,123 +785,24 @@ type SemanticTokensDelta struct { ResultId *string `json:"resultId,omitzero"` // The semantic token edits to transform a previous result into a new result. - Edits []*SemanticTokensEdit `json:"edits"` + Edits []*SemanticTokensEdit `json:"edits" lsp:"required"` } var _ json.UnmarshalerFrom = (*SemanticTokensDelta)(nil) func (s *SemanticTokensDelta) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingEdits uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"resultId"`: - if dec.PeekKind() == 'n' { - return errNull("resultId") - } - if err := json.UnmarshalDecode(dec, &s.ResultId); err != nil { - return err - } - case `"edits"`: - missing &^= missingEdits - if dec.PeekKind() == 'n' { - return errNull("edits") - } - if err := json.UnmarshalDecode(dec, &s.Edits); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingEdits != 0 { - missingProps = append(missingProps, "edits") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.16.0 type SemanticTokensDeltaPartialResult struct { - Edits []*SemanticTokensEdit `json:"edits"` + Edits []*SemanticTokensEdit `json:"edits" lsp:"required"` } var _ json.UnmarshalerFrom = (*SemanticTokensDeltaPartialResult)(nil) func (s *SemanticTokensDeltaPartialResult) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingEdits uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"edits"`: - missing &^= missingEdits - if dec.PeekKind() == 'n' { - return errNull("edits") - } - if err := json.UnmarshalDecode(dec, &s.Edits); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingEdits != 0 { - missingProps = append(missingProps, "edits") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.16.0 @@ -3064,10 +815,10 @@ type SemanticTokensRangeParams struct { PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The range the semantic tokens are requested for. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` } func (s *SemanticTokensRangeParams) TextDocumentURI() DocumentUri { @@ -3077,81 +828,15 @@ func (s *SemanticTokensRangeParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*SemanticTokensRangeParams)(nil) func (s *SemanticTokensRangeParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingRange - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - return errMissing(missingProps) - } - - return nil -} - -// Params to show a resource in the UI. -// -// Since: 3.16.0 -type ShowDocumentParams struct { - // The uri to show. - Uri URI `json:"uri"` +// Params to show a resource in the UI. +// +// Since: 3.16.0 +type ShowDocumentParams struct { + // The uri to show. + Uri URI `json:"uri" lsp:"required"` // Indicates to show the resource in an external program. // To show, for example, `https://code.visualstudio.com/` @@ -3174,71 +859,7 @@ type ShowDocumentParams struct { var _ json.UnmarshalerFrom = (*ShowDocumentParams)(nil) func (s *ShowDocumentParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"external"`: - if dec.PeekKind() == 'n' { - return errNull("external") - } - if err := json.UnmarshalDecode(dec, &s.External); err != nil { - return err - } - case `"takeFocus"`: - if dec.PeekKind() == 'n' { - return errNull("takeFocus") - } - if err := json.UnmarshalDecode(dec, &s.TakeFocus); err != nil { - return err - } - case `"selection"`: - if dec.PeekKind() == 'n' { - return errNull("selection") - } - if err := json.UnmarshalDecode(dec, &s.Selection); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The result of a showDocument request. @@ -3246,64 +867,21 @@ func (s *ShowDocumentParams) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.16.0 type ShowDocumentResult struct { // A boolean indicating if the show was successful. - Success bool `json:"success"` + Success bool `json:"success" lsp:"required"` } var _ json.UnmarshalerFrom = (*ShowDocumentResult)(nil) func (s *ShowDocumentResult) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingSuccess uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"success"`: - missing &^= missingSuccess - if err := json.UnmarshalDecode(dec, &s.Success); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingSuccess != 0 { - missingProps = append(missingProps, "success") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type LinkedEditingRangeParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -3320,66 +898,7 @@ func (s *LinkedEditingRangeParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*LinkedEditingRangeParams)(nil) func (s *LinkedEditingRangeParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The result of a linked editing range request. @@ -3388,7 +907,7 @@ func (s *LinkedEditingRangeParams) UnmarshalJSONFrom(dec *json.Decoder) error { type LinkedEditingRanges struct { // A list of ranges that can be edited together. The ranges must have // identical length and contain identical text content. The ranges cannot overlap. - Ranges []Range `json:"ranges"` + Ranges []Range `json:"ranges" lsp:"required"` // An optional word pattern (regular expression) that describes valid contents for // the given ranges. If no pattern is provided, the client configuration's word @@ -3399,66 +918,13 @@ type LinkedEditingRanges struct { var _ json.UnmarshalerFrom = (*LinkedEditingRanges)(nil) func (s *LinkedEditingRanges) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRanges uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"ranges"`: - missing &^= missingRanges - if dec.PeekKind() == 'n' { - return errNull("ranges") - } - if err := json.UnmarshalDecode(dec, &s.Ranges); err != nil { - return err - } - case `"wordPattern"`: - if dec.PeekKind() == 'n' { - return errNull("wordPattern") - } - if err := json.UnmarshalDecode(dec, &s.WordPattern); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRanges != 0 { - missingProps = append(missingProps, "ranges") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type LinkedEditingRangeRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -3470,64 +936,7 @@ type LinkedEditingRangeRegistrationOptions struct { var _ json.UnmarshalerFrom = (*LinkedEditingRangeRegistrationOptions)(nil) func (s *LinkedEditingRangeRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters sent in notifications/requests for user-initiated creation of @@ -3536,60 +945,14 @@ func (s *LinkedEditingRangeRegistrationOptions) UnmarshalJSONFrom(dec *json.Deco // Since: 3.16.0 type CreateFilesParams struct { // An array of all files/folders created in this operation. - Files []*FileCreate `json:"files"` + Files []*FileCreate `json:"files" lsp:"required"` } var _ json.UnmarshalerFrom = (*CreateFilesParams)(nil) func (s *CreateFilesParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingFiles uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"files"`: - missing &^= missingFiles - if dec.PeekKind() == 'n' { - return errNull("files") - } - if err := json.UnmarshalDecode(dec, &s.Files); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingFiles != 0 { - missingProps = append(missingProps, "files") - } - return errMissing(missingProps) - } - - return nil -} + return unmarshalStruct(s, dec) +} // A workspace edit represents changes to many resources managed in the workspace. The edit // should either provide `changes` or `documentChanges`. If documentChanges are present @@ -3631,52 +994,7 @@ type WorkspaceEdit struct { var _ json.UnmarshalerFrom = (*WorkspaceEdit)(nil) func (s *WorkspaceEdit) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"changes"`: - if dec.PeekKind() == 'n' { - return errNull("changes") - } - if err := json.UnmarshalDecode(dec, &s.Changes); err != nil { - return err - } - case `"documentChanges"`: - if dec.PeekKind() == 'n' { - return errNull("documentChanges") - } - if err := json.UnmarshalDecode(dec, &s.DocumentChanges); err != nil { - return err - } - case `"changeAnnotations"`: - if dec.PeekKind() == 'n' { - return errNull("changeAnnotations") - } - if err := json.UnmarshalDecode(dec, &s.ChangeAnnotations); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // The options to register for file operations. @@ -3684,59 +1002,13 @@ func (s *WorkspaceEdit) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.16.0 type FileOperationRegistrationOptions struct { // The actual filters. - Filters []*FileOperationFilter `json:"filters"` + Filters []*FileOperationFilter `json:"filters" lsp:"required"` } var _ json.UnmarshalerFrom = (*FileOperationRegistrationOptions)(nil) func (s *FileOperationRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingFilters uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"filters"`: - missing &^= missingFilters - if dec.PeekKind() == 'n' { - return errNull("filters") - } - if err := json.UnmarshalDecode(dec, &s.Filters); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingFilters != 0 { - missingProps = append(missingProps, "filters") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters sent in notifications/requests for user-initiated renames of @@ -3746,59 +1018,13 @@ func (s *FileOperationRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) type RenameFilesParams struct { // An array of all files/folders renamed in this operation. When a folder is renamed, only // the folder will be included, and not its children. - Files []*FileRename `json:"files"` + Files []*FileRename `json:"files" lsp:"required"` } var _ json.UnmarshalerFrom = (*RenameFilesParams)(nil) func (s *RenameFilesParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingFiles uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"files"`: - missing &^= missingFiles - if dec.PeekKind() == 'n' { - return errNull("files") - } - if err := json.UnmarshalDecode(dec, &s.Files); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingFiles != 0 { - missingProps = append(missingProps, "files") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters sent in notifications/requests for user-initiated deletes of @@ -3807,67 +1033,21 @@ func (s *RenameFilesParams) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.16.0 type DeleteFilesParams struct { // An array of all files/folders deleted in this operation. - Files []*FileDelete `json:"files"` + Files []*FileDelete `json:"files" lsp:"required"` } var _ json.UnmarshalerFrom = (*DeleteFilesParams)(nil) func (s *DeleteFilesParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingFiles uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"files"`: - missing &^= missingFiles - if dec.PeekKind() == 'n' { - return errNull("files") - } - if err := json.UnmarshalDecode(dec, &s.Files); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingFiles != 0 { - missingProps = append(missingProps, "files") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type MonikerParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -3888,73 +1068,7 @@ func (s *MonikerParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*MonikerParams)(nil) func (s *MonikerParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Moniker definition to match LSIF 0.5 moniker definition. @@ -3962,14 +1076,14 @@ func (s *MonikerParams) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.16.0 type Moniker struct { // The scheme of the moniker. For example tsc or .Net - Scheme string `json:"scheme"` + Scheme string `json:"scheme" lsp:"required"` // The identifier of the moniker. The value is opaque in LSIF however // schema owners are allowed to define the structure if they want. - Identifier string `json:"identifier"` + Identifier string `json:"identifier" lsp:"required"` // The scope in which the moniker is unique - Unique UniquenessLevel `json:"unique"` + Unique UniquenessLevel `json:"unique" lsp:"required"` // The moniker kind if known. Kind *MonikerKind `json:"kind,omitzero"` @@ -3978,81 +1092,13 @@ type Moniker struct { var _ json.UnmarshalerFrom = (*Moniker)(nil) func (s *Moniker) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingScheme uint = 1 << iota - missingIdentifier - missingUnique - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"scheme"`: - missing &^= missingScheme - if err := json.UnmarshalDecode(dec, &s.Scheme); err != nil { - return err - } - case `"identifier"`: - missing &^= missingIdentifier - if err := json.UnmarshalDecode(dec, &s.Identifier); err != nil { - return err - } - case `"unique"`: - missing &^= missingUnique - if err := json.UnmarshalDecode(dec, &s.Unique); err != nil { - return err - } - case `"kind"`: - if dec.PeekKind() == 'n' { - return errNull("kind") - } - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingScheme != 0 { - missingProps = append(missingProps, "scheme") - } - if missing&missingIdentifier != 0 { - missingProps = append(missingProps, "identifier") - } - if missing&missingUnique != 0 { - missingProps = append(missingProps, "unique") - } - return errMissing(missingProps) - } - - return nil -} - -type MonikerRegistrationOptions struct { - // A document selector to identify the scope of the registration. If set to null - // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` +type MonikerRegistrationOptions struct { + // A document selector to identify the scope of the registration. If set to null + // the document selector provided on the client side will be used. + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` } @@ -4060,57 +1106,7 @@ type MonikerRegistrationOptions struct { var _ json.UnmarshalerFrom = (*MonikerRegistrationOptions)(nil) func (s *MonikerRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameter of a `textDocument/prepareTypeHierarchy` request. @@ -4118,10 +1114,10 @@ func (s *MonikerRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error // Since: 3.17.0 type TypeHierarchyPrepareParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -4138,75 +1134,16 @@ func (s *TypeHierarchyPrepareParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*TypeHierarchyPrepareParams)(nil) func (s *TypeHierarchyPrepareParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.17.0 type TypeHierarchyItem struct { // The name of this item. - Name string `json:"name"` + Name string `json:"name" lsp:"required"` // The kind of this item. - Kind SymbolKind `json:"kind"` + Kind SymbolKind `json:"kind" lsp:"required"` // Tags for this item. Tags *[]SymbolTag `json:"tags,omitzero"` @@ -4215,16 +1152,16 @@ type TypeHierarchyItem struct { Detail *string `json:"detail,omitzero"` // The resource identifier of this item. - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` // The range enclosing this symbol not including leading/trailing whitespace // but everything else, e.g. comments and code. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The range that should be selected and revealed when this symbol is being // picked, e.g. the name of a function. Must be contained by the // `range`. - SelectionRange Range `json:"selectionRange"` + SelectionRange Range `json:"selectionRange" lsp:"required"` // A data entry field that is preserved between a type hierarchy prepare and // supertypes or subtypes requests. It could also be used to identify the @@ -4243,107 +1180,7 @@ func (s TypeHierarchyItem) GetLocation() Location { var _ json.UnmarshalerFrom = (*TypeHierarchyItem)(nil) func (s *TypeHierarchyItem) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingName uint = 1 << iota - missingKind - missingUri - missingRange - missingSelectionRange - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"name"`: - missing &^= missingName - if err := json.UnmarshalDecode(dec, &s.Name); err != nil { - return err - } - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"tags"`: - if dec.PeekKind() == 'n' { - return errNull("tags") - } - if err := json.UnmarshalDecode(dec, &s.Tags); err != nil { - return err - } - case `"detail"`: - if dec.PeekKind() == 'n' { - return errNull("detail") - } - if err := json.UnmarshalDecode(dec, &s.Detail); err != nil { - return err - } - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"selectionRange"`: - missing &^= missingSelectionRange - if err := json.UnmarshalDecode(dec, &s.SelectionRange); err != nil { - return err - } - case `"data"`: - if dec.PeekKind() == 'n' { - return errNull("data") - } - if err := json.UnmarshalDecode(dec, &s.Data); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingName != 0 { - missingProps = append(missingProps, "name") - } - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingSelectionRange != 0 { - missingProps = append(missingProps, "selectionRange") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Type hierarchy options used during static or dynamic registration. @@ -4352,7 +1189,7 @@ func (s *TypeHierarchyItem) UnmarshalJSONFrom(dec *json.Decoder) error { type TypeHierarchyRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -4364,64 +1201,7 @@ type TypeHierarchyRegistrationOptions struct { var _ json.UnmarshalerFrom = (*TypeHierarchyRegistrationOptions)(nil) func (s *TypeHierarchyRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameter of a `typeHierarchy/supertypes` request. @@ -4435,153 +1215,33 @@ type TypeHierarchySupertypesParams struct { // the client. PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` - Item *TypeHierarchyItem `json:"item"` + Item *TypeHierarchyItem `json:"item" lsp:"required"` } var _ json.UnmarshalerFrom = (*TypeHierarchySupertypesParams)(nil) func (s *TypeHierarchySupertypesParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingItem uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } +// The parameter of a `typeHierarchy/subtypes` request. +// +// Since: 3.17.0 +type TypeHierarchySubtypesParams struct { + // An optional token that a server can use to report work done progress. + WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"item"`: - missing &^= missingItem - if dec.PeekKind() == 'n' { - return errNull("item") - } - if err := json.UnmarshalDecode(dec, &s.Item); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + // An optional token that a server can use to report partial results (e.g. streaming) to + // the client. + PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingItem != 0 { - missingProps = append(missingProps, "item") - } - return errMissing(missingProps) - } - - return nil -} - -// The parameter of a `typeHierarchy/subtypes` request. -// -// Since: 3.17.0 -type TypeHierarchySubtypesParams struct { - // An optional token that a server can use to report work done progress. - WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` - - // An optional token that a server can use to report partial results (e.g. streaming) to - // the client. - PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` - - Item *TypeHierarchyItem `json:"item"` + Item *TypeHierarchyItem `json:"item" lsp:"required"` } var _ json.UnmarshalerFrom = (*TypeHierarchySubtypesParams)(nil) func (s *TypeHierarchySubtypesParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingItem uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"item"`: - missing &^= missingItem - if dec.PeekKind() == 'n' { - return errNull("item") - } - if err := json.UnmarshalDecode(dec, &s.Item); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingItem != 0 { - missingProps = append(missingProps, "item") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A parameter literal used in inline value requests. @@ -4592,14 +1252,14 @@ type InlineValueParams struct { WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The document range for which inline values information will be returned. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // Additional information about the context in which inline values information was // requested. - Context *InlineValueContext `json:"context"` + Context *InlineValueContext `json:"context" lsp:"required"` } func (s *InlineValueParams) TextDocumentURI() DocumentUri { @@ -4609,78 +1269,7 @@ func (s *InlineValueParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*InlineValueParams)(nil) func (s *InlineValueParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingRange - missingContext - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"context"`: - missing &^= missingContext - if dec.PeekKind() == 'n' { - return errNull("context") - } - if err := json.UnmarshalDecode(dec, &s.Context); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingContext != 0 { - missingProps = append(missingProps, "context") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Inline value options used during static or dynamic registration. @@ -4691,7 +1280,7 @@ type InlineValueRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` // The id used to register the request. The id can be used to deregister // the request again. See also Registration#id. @@ -4701,64 +1290,7 @@ type InlineValueRegistrationOptions struct { var _ json.UnmarshalerFrom = (*InlineValueRegistrationOptions)(nil) func (s *InlineValueRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A parameter literal used in inlay hint requests. @@ -4769,10 +1301,10 @@ type InlayHintParams struct { WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The document range for which inlay hints should be computed. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` } func (s *InlayHintParams) TextDocumentURI() DocumentUri { @@ -4782,66 +1314,7 @@ func (s *InlayHintParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*InlayHintParams)(nil) func (s *InlayHintParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingRange - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Inlay hint information. @@ -4852,13 +1325,13 @@ type InlayHint struct { // // If multiple hints have the same position, they will be shown in the order // they appear in the response. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // The label of this hint. A human readable string or an array of // InlayHintLabelPart label parts. // // *Note* that neither the string nor the label part can be empty. - Label StringOrInlayHintLabelParts `json:"label"` + Label StringOrInlayHintLabelParts `json:"label" lsp:"required"` // The kind of this hint. Can be omitted in which case the client // should fall back to a reasonable default. @@ -4896,108 +1369,14 @@ type InlayHint struct { var _ json.UnmarshalerFrom = (*InlayHint)(nil) func (s *InlayHint) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingPosition uint = 1 << iota - missingLabel - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } + return unmarshalStruct(s, dec) +} - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"label"`: - missing &^= missingLabel - if err := json.UnmarshalDecode(dec, &s.Label); err != nil { - return err - } - case `"kind"`: - if dec.PeekKind() == 'n' { - return errNull("kind") - } - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"textEdits"`: - if dec.PeekKind() == 'n' { - return errNull("textEdits") - } - if err := json.UnmarshalDecode(dec, &s.TextEdits); err != nil { - return err - } - case `"tooltip"`: - if dec.PeekKind() == 'n' { - return errNull("tooltip") - } - if err := json.UnmarshalDecode(dec, &s.Tooltip); err != nil { - return err - } - case `"paddingLeft"`: - if dec.PeekKind() == 'n' { - return errNull("paddingLeft") - } - if err := json.UnmarshalDecode(dec, &s.PaddingLeft); err != nil { - return err - } - case `"paddingRight"`: - if dec.PeekKind() == 'n' { - return errNull("paddingRight") - } - if err := json.UnmarshalDecode(dec, &s.PaddingRight); err != nil { - return err - } - case `"data"`: - if dec.PeekKind() == 'n' { - return errNull("data") - } - if err := json.UnmarshalDecode(dec, &s.Data); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - if missing&missingLabel != 0 { - missingProps = append(missingProps, "label") - } - return errMissing(missingProps) - } - - return nil -} - -// Inlay hint options used during static or dynamic registration. -// -// Since: 3.17.0 -type InlayHintRegistrationOptions struct { - WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` +// Inlay hint options used during static or dynamic registration. +// +// Since: 3.17.0 +type InlayHintRegistrationOptions struct { + WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` // The server provides support to resolve additional // information for an inlay hint item. @@ -5005,7 +1384,7 @@ type InlayHintRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` // The id used to register the request. The id can be used to deregister // the request again. See also Registration#id. @@ -5015,71 +1394,7 @@ type InlayHintRegistrationOptions struct { var _ json.UnmarshalerFrom = (*InlayHintRegistrationOptions)(nil) func (s *InlayHintRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"resolveProvider"`: - if dec.PeekKind() == 'n' { - return errNull("resolveProvider") - } - if err := json.UnmarshalDecode(dec, &s.ResolveProvider); err != nil { - return err - } - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters of the document diagnostic request. @@ -5094,7 +1409,7 @@ type DocumentDiagnosticParams struct { PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The additional identifier provided during registration. Identifier *string `json:"identifier,omitzero"` @@ -5110,193 +1425,20 @@ func (s *DocumentDiagnosticParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*DocumentDiagnosticParams)(nil) func (s *DocumentDiagnosticParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"identifier"`: - if dec.PeekKind() == 'n' { - return errNull("identifier") - } - if err := json.UnmarshalDecode(dec, &s.Identifier); err != nil { - return err - } - case `"previousResultId"`: - if dec.PeekKind() == 'n' { - return errNull("previousResultId") - } - if err := json.UnmarshalDecode(dec, &s.PreviousResultId); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - return errMissing(missingProps) - } - - return nil -} - -// A partial result for a document diagnostic report. -// -// Since: 3.17.0 -type DocumentDiagnosticReportPartialResult struct { - RelatedDocuments map[DocumentUri]FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport `json:"relatedDocuments"` -} - -var _ json.UnmarshalerFrom = (*DocumentDiagnosticReportPartialResult)(nil) - -func (s *DocumentDiagnosticReportPartialResult) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRelatedDocuments uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"relatedDocuments"`: - missing &^= missingRelatedDocuments - if dec.PeekKind() == 'n' { - return errNull("relatedDocuments") - } - if err := json.UnmarshalDecode(dec, &s.RelatedDocuments); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRelatedDocuments != 0 { - missingProps = append(missingProps, "relatedDocuments") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Cancellation data returned from a diagnostic request. // // Since: 3.17.0 type DiagnosticServerCancellationData struct { - RetriggerRequest bool `json:"retriggerRequest"` + RetriggerRequest bool `json:"retriggerRequest" lsp:"required"` } var _ json.UnmarshalerFrom = (*DiagnosticServerCancellationData)(nil) func (s *DiagnosticServerCancellationData) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRetriggerRequest uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"retriggerRequest"`: - missing &^= missingRetriggerRequest - if err := json.UnmarshalDecode(dec, &s.RetriggerRequest); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRetriggerRequest != 0 { - missingProps = append(missingProps, "retriggerRequest") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Diagnostic registration options. @@ -5305,7 +1447,7 @@ func (s *DiagnosticServerCancellationData) UnmarshalJSONFrom(dec *json.Decoder) type DiagnosticRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -5317,10 +1459,10 @@ type DiagnosticRegistrationOptions struct { // editing code in one file can result in a different diagnostic // set in another file. Inter file dependencies are common for // most programming languages and typically uncommon for linters. - InterFileDependencies bool `json:"interFileDependencies"` + InterFileDependencies bool `json:"interFileDependencies" lsp:"required"` // The server provides support for workspace diagnostics as well. - WorkspaceDiagnostics bool `json:"workspaceDiagnostics"` + WorkspaceDiagnostics bool `json:"workspaceDiagnostics" lsp:"required"` // The id used to register the request. The id can be used to deregister // the request again. See also Registration#id. @@ -5330,299 +1472,58 @@ type DiagnosticRegistrationOptions struct { var _ json.UnmarshalerFrom = (*DiagnosticRegistrationOptions)(nil) func (s *DiagnosticRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - missingInterFileDependencies - missingWorkspaceDiagnostics - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } +// Parameters of the workspace diagnostic request. +// +// Since: 3.17.0 +type WorkspaceDiagnosticParams struct { + // An optional token that a server can use to report work done progress. + WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"identifier"`: - if dec.PeekKind() == 'n' { - return errNull("identifier") - } - if err := json.UnmarshalDecode(dec, &s.Identifier); err != nil { - return err - } - case `"interFileDependencies"`: - missing &^= missingInterFileDependencies - if err := json.UnmarshalDecode(dec, &s.InterFileDependencies); err != nil { - return err - } - case `"workspaceDiagnostics"`: - missing &^= missingWorkspaceDiagnostics - if err := json.UnmarshalDecode(dec, &s.WorkspaceDiagnostics); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - if missing&missingInterFileDependencies != 0 { - missingProps = append(missingProps, "interFileDependencies") - } - if missing&missingWorkspaceDiagnostics != 0 { - missingProps = append(missingProps, "workspaceDiagnostics") - } - return errMissing(missingProps) - } - - return nil -} - -// Parameters of the workspace diagnostic request. -// -// Since: 3.17.0 -type WorkspaceDiagnosticParams struct { - // An optional token that a server can use to report work done progress. - WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` - - // An optional token that a server can use to report partial results (e.g. streaming) to - // the client. - PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` + // An optional token that a server can use to report partial results (e.g. streaming) to + // the client. + PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` // The additional identifier provided during registration. Identifier *string `json:"identifier,omitzero"` // The currently known diagnostic reports with their // previous result ids. - PreviousResultIds []PreviousResultId `json:"previousResultIds"` + PreviousResultIds []PreviousResultId `json:"previousResultIds" lsp:"required"` } var _ json.UnmarshalerFrom = (*WorkspaceDiagnosticParams)(nil) func (s *WorkspaceDiagnosticParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingPreviousResultIds uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"identifier"`: - if dec.PeekKind() == 'n' { - return errNull("identifier") - } - if err := json.UnmarshalDecode(dec, &s.Identifier); err != nil { - return err - } - case `"previousResultIds"`: - missing &^= missingPreviousResultIds - if dec.PeekKind() == 'n' { - return errNull("previousResultIds") - } - if err := json.UnmarshalDecode(dec, &s.PreviousResultIds); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingPreviousResultIds != 0 { - missingProps = append(missingProps, "previousResultIds") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A workspace diagnostic report. // // Since: 3.17.0 type WorkspaceDiagnosticReport struct { - Items []WorkspaceFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport `json:"items"` + Items []WorkspaceFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport `json:"items" lsp:"required"` } var _ json.UnmarshalerFrom = (*WorkspaceDiagnosticReport)(nil) func (s *WorkspaceDiagnosticReport) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingItems uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"items"`: - missing &^= missingItems - if dec.PeekKind() == 'n' { - return errNull("items") - } - if err := json.UnmarshalDecode(dec, &s.Items); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingItems != 0 { - missingProps = append(missingProps, "items") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A partial result for a workspace diagnostic report. // // Since: 3.17.0 type WorkspaceDiagnosticReportPartialResult struct { - Items []WorkspaceFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport `json:"items"` + Items []WorkspaceFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport `json:"items" lsp:"required"` } var _ json.UnmarshalerFrom = (*WorkspaceDiagnosticReportPartialResult)(nil) func (s *WorkspaceDiagnosticReportPartialResult) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingItems uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"items"`: - missing &^= missingItems - if dec.PeekKind() == 'n' { - return errNull("items") - } - if err := json.UnmarshalDecode(dec, &s.Items); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingItems != 0 { - missingProps = append(missingProps, "items") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A parameter literal used in inline completion requests. @@ -5630,17 +1531,17 @@ func (s *WorkspaceDiagnosticReportPartialResult) UnmarshalJSONFrom(dec *json.Dec // Since: 3.18.0 type InlineCompletionParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` // Additional information about the context in which inline completions were // requested. - Context *InlineCompletionContext `json:"context"` + Context *InlineCompletionContext `json:"context" lsp:"required"` } func (s *InlineCompletionParams) TextDocumentURI() DocumentUri { @@ -5654,78 +1555,7 @@ func (s *InlineCompletionParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*InlineCompletionParams)(nil) func (s *InlineCompletionParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - missingContext - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"context"`: - missing &^= missingContext - if dec.PeekKind() == 'n' { - return errNull("context") - } - if err := json.UnmarshalDecode(dec, &s.Context); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - if missing&missingContext != 0 { - missingProps = append(missingProps, "context") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Represents a collection of items to be presented in the editor. @@ -5733,59 +1563,13 @@ func (s *InlineCompletionParams) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.18.0 type InlineCompletionList struct { // The inline completion items - Items []*InlineCompletionItem `json:"items"` + Items []*InlineCompletionItem `json:"items" lsp:"required"` } var _ json.UnmarshalerFrom = (*InlineCompletionList)(nil) func (s *InlineCompletionList) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingItems uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"items"`: - missing &^= missingItems - if dec.PeekKind() == 'n' { - return errNull("items") - } - if err := json.UnmarshalDecode(dec, &s.Items); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingItems != 0 { - missingProps = append(missingProps, "items") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // An inline completion item represents a text snippet that is proposed inline to complete text that is being typed. @@ -5793,7 +1577,7 @@ func (s *InlineCompletionList) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.18.0 type InlineCompletionItem struct { // The text to replace the range with. Must be set. - InsertText StringOrStringValue `json:"insertText"` + InsertText StringOrStringValue `json:"insertText" lsp:"required"` // A text that is used to decide if this inline completion should be shown. When `falsy` the InlineCompletionItem.insertText is used. FilterText *string `json:"filterText,omitzero"` @@ -5808,82 +1592,18 @@ type InlineCompletionItem struct { var _ json.UnmarshalerFrom = (*InlineCompletionItem)(nil) func (s *InlineCompletionItem) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingInsertText uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"insertText"`: - missing &^= missingInsertText - if err := json.UnmarshalDecode(dec, &s.InsertText); err != nil { - return err - } - case `"filterText"`: - if dec.PeekKind() == 'n' { - return errNull("filterText") - } - if err := json.UnmarshalDecode(dec, &s.FilterText); err != nil { - return err - } - case `"range"`: - if dec.PeekKind() == 'n' { - return errNull("range") - } - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"command"`: - if dec.PeekKind() == 'n' { - return errNull("command") - } - if err := json.UnmarshalDecode(dec, &s.Command); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingInsertText != 0 { - missingProps = append(missingProps, "insertText") - } - return errMissing(missingProps) - } - - return nil -} - -// Inline completion options used during static or dynamic registration. -// -// Since: 3.18.0 -type InlineCompletionRegistrationOptions struct { - WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` +// Inline completion options used during static or dynamic registration. +// +// Since: 3.18.0 +type InlineCompletionRegistrationOptions struct { + WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` // The id used to register the request. The id can be used to deregister // the request again. See also Registration#id. @@ -5893,64 +1613,7 @@ type InlineCompletionRegistrationOptions struct { var _ json.UnmarshalerFrom = (*InlineCompletionRegistrationOptions)(nil) func (s *InlineCompletionRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters for the `workspace/textDocumentContent` request. @@ -5958,56 +1621,13 @@ func (s *InlineCompletionRegistrationOptions) UnmarshalJSONFrom(dec *json.Decode // Since: 3.18.0 type TextDocumentContentParams struct { // The uri of the text document. - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` } var _ json.UnmarshalerFrom = (*TextDocumentContentParams)(nil) func (s *TextDocumentContentParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Result of the `workspace/textDocumentContent` request. @@ -6018,56 +1638,13 @@ type TextDocumentContentResult struct { // any subsequent open notifications for the text document might differ // from the returned content due to whitespace and line ending // normalizations done on the client - Text string `json:"text"` + Text string `json:"text" lsp:"required"` } var _ json.UnmarshalerFrom = (*TextDocumentContentResult)(nil) func (s *TextDocumentContentResult) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingText uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"text"`: - missing &^= missingText - if err := json.UnmarshalDecode(dec, &s.Text); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingText != 0 { - missingProps = append(missingProps, "text") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Text document content provider registration options. @@ -6075,7 +1652,7 @@ func (s *TextDocumentContentResult) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.18.0 type TextDocumentContentRegistrationOptions struct { // The schemes for which the server provides content. - Schemes []string `json:"schemes"` + Schemes []string `json:"schemes" lsp:"required"` // The id used to register the request. The id can be used to deregister // the request again. See also Registration#id. @@ -6085,60 +1662,7 @@ type TextDocumentContentRegistrationOptions struct { var _ json.UnmarshalerFrom = (*TextDocumentContentRegistrationOptions)(nil) func (s *TextDocumentContentRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingSchemes uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"schemes"`: - missing &^= missingSchemes - if dec.PeekKind() == 'n' { - return errNull("schemes") - } - if err := json.UnmarshalDecode(dec, &s.Schemes); err != nil { - return err - } - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingSchemes != 0 { - missingProps = append(missingProps, "schemes") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters for the `workspace/textDocumentContent/refresh` request. @@ -6146,168 +1670,33 @@ func (s *TextDocumentContentRegistrationOptions) UnmarshalJSONFrom(dec *json.Dec // Since: 3.18.0 type TextDocumentContentRefreshParams struct { // The uri of the text document to refresh. - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` } var _ json.UnmarshalerFrom = (*TextDocumentContentRefreshParams)(nil) func (s *TextDocumentContentRefreshParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type RegistrationParams struct { - Registrations []*Registration `json:"registrations"` + Registrations []*Registration `json:"registrations" lsp:"required"` } var _ json.UnmarshalerFrom = (*RegistrationParams)(nil) func (s *RegistrationParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRegistrations uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"registrations"`: - missing &^= missingRegistrations - if dec.PeekKind() == 'n' { - return errNull("registrations") - } - if err := json.UnmarshalDecode(dec, &s.Registrations); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRegistrations != 0 { - missingProps = append(missingProps, "registrations") - } - return errMissing(missingProps) - } - - return nil -} + return unmarshalStruct(s, dec) +} type UnregistrationParams struct { - Unregisterations []*Unregistration `json:"unregisterations"` + Unregisterations []*Unregistration `json:"unregisterations" lsp:"required"` } var _ json.UnmarshalerFrom = (*UnregistrationParams)(nil) func (s *UnregistrationParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUnregisterations uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"unregisterations"`: - missing &^= missingUnregisterations - if dec.PeekKind() == 'n' { - return errNull("unregisterations") - } - if err := json.UnmarshalDecode(dec, &s.Unregisterations); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUnregisterations != 0 { - missingProps = append(missingProps, "unregisterations") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type InitializeParams struct { @@ -6319,7 +1708,7 @@ type InitializeParams struct { // // Is `null` if the process has not been started by another process. // If the parent process is not alive then the server should exit. - ProcessId IntegerOrNull `json:"processId"` + ProcessId IntegerOrNull `json:"processId" lsp:"required"` // Information about the client // @@ -6340,20 +1729,20 @@ type InitializeParams struct { // if no folder is open. // // Deprecated: in favour of rootUri. - RootPath *StringOrNull `json:"rootPath,omitzero"` + RootPath *StringOrNull `json:"rootPath,omitzero" lsp:"nullable"` // The rootUri of the workspace. Is null if no // folder is open. If both `rootPath` and `rootUri` are set // `rootUri` wins. // // Deprecated: in favour of workspaceFolders. - RootUri DocumentUriOrNull `json:"rootUri"` + RootUri DocumentUriOrNull `json:"rootUri" lsp:"required"` // The capabilities provided by the client (editor or tool) - Capabilities *ClientCapabilities `json:"capabilities"` + Capabilities *ClientCapabilities `json:"capabilities" lsp:"required"` // User provided initialization options. - InitializationOptions *InitializationOptionsOrNull `json:"initializationOptions,omitzero"` + InitializationOptions *InitializationOptionsOrNull `json:"initializationOptions,omitzero" lsp:"nullable"` // The initial trace setting. If omitted trace is disabled ('off'). Trace *TraceValue `json:"trace,omitzero"` @@ -6365,123 +1754,19 @@ type InitializeParams struct { // configured. // // Since: 3.6.0 - WorkspaceFolders *WorkspaceFoldersOrNull `json:"workspaceFolders,omitzero"` + WorkspaceFolders *WorkspaceFoldersOrNull `json:"workspaceFolders,omitzero" lsp:"nullable"` } var _ json.UnmarshalerFrom = (*InitializeParams)(nil) func (s *InitializeParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingProcessId uint = 1 << iota - missingRootUri - missingCapabilities - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"processId"`: - missing &^= missingProcessId - if err := json.UnmarshalDecode(dec, &s.ProcessId); err != nil { - return err - } - case `"clientInfo"`: - if dec.PeekKind() == 'n' { - return errNull("clientInfo") - } - if err := json.UnmarshalDecode(dec, &s.ClientInfo); err != nil { - return err - } - case `"locale"`: - if dec.PeekKind() == 'n' { - return errNull("locale") - } - if err := json.UnmarshalDecode(dec, &s.Locale); err != nil { - return err - } - case `"rootPath"`: - if err := json.UnmarshalDecode(dec, &s.RootPath); err != nil { - return err - } - case `"rootUri"`: - missing &^= missingRootUri - if err := json.UnmarshalDecode(dec, &s.RootUri); err != nil { - return err - } - case `"capabilities"`: - missing &^= missingCapabilities - if dec.PeekKind() == 'n' { - return errNull("capabilities") - } - if err := json.UnmarshalDecode(dec, &s.Capabilities); err != nil { - return err - } - case `"initializationOptions"`: - if err := json.UnmarshalDecode(dec, &s.InitializationOptions); err != nil { - return err - } - case `"trace"`: - if dec.PeekKind() == 'n' { - return errNull("trace") - } - if err := json.UnmarshalDecode(dec, &s.Trace); err != nil { - return err - } - case `"workspaceFolders"`: - if err := json.UnmarshalDecode(dec, &s.WorkspaceFolders); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingProcessId != 0 { - missingProps = append(missingProps, "processId") - } - if missing&missingRootUri != 0 { - missingProps = append(missingProps, "rootUri") - } - if missing&missingCapabilities != 0 { - missingProps = append(missingProps, "capabilities") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The result returned from an initialize request. type InitializeResult struct { // The capabilities the language server provides. - Capabilities *ServerCapabilities `json:"capabilities"` + Capabilities *ServerCapabilities `json:"capabilities" lsp:"required"` // Information about the server. // @@ -6492,60 +1777,7 @@ type InitializeResult struct { var _ json.UnmarshalerFrom = (*InitializeResult)(nil) func (s *InitializeResult) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingCapabilities uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"capabilities"`: - missing &^= missingCapabilities - if dec.PeekKind() == 'n' { - return errNull("capabilities") - } - if err := json.UnmarshalDecode(dec, &s.Capabilities); err != nil { - return err - } - case `"serverInfo"`: - if dec.PeekKind() == 'n' { - return errNull("serverInfo") - } - if err := json.UnmarshalDecode(dec, &s.ServerInfo); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingCapabilities != 0 { - missingProps = append(missingProps, "capabilities") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The data type of the ResponseError if the @@ -6555,56 +1787,13 @@ type InitializeError struct { // (1) show the message provided by the ResponseError to the user // (2) user selects retry or cancel // (3) if user selected retry the initialize method is sent again. - Retry bool `json:"retry"` + Retry bool `json:"retry" lsp:"required"` } var _ json.UnmarshalerFrom = (*InitializeError)(nil) func (s *InitializeError) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRetry uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"retry"`: - missing &^= missingRetry - if err := json.UnmarshalDecode(dec, &s.Retry); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRetry != 0 { - missingProps = append(missingProps, "retry") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type InitializedParams struct{} @@ -6612,56 +1801,13 @@ type InitializedParams struct{} // The parameters of a change configuration notification. type DidChangeConfigurationParams struct { // The actual changed settings - Settings any `json:"settings"` + Settings any `json:"settings" lsp:"required"` } var _ json.UnmarshalerFrom = (*DidChangeConfigurationParams)(nil) func (s *DidChangeConfigurationParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingSettings uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"settings"`: - missing &^= missingSettings - if err := json.UnmarshalDecode(dec, &s.Settings); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingSettings != 0 { - missingProps = append(missingProps, "settings") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type DidChangeConfigurationRegistrationOptions struct { @@ -6671,113 +1817,30 @@ type DidChangeConfigurationRegistrationOptions struct { var _ json.UnmarshalerFrom = (*DidChangeConfigurationRegistrationOptions)(nil) func (s *DidChangeConfigurationRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"section"`: - if dec.PeekKind() == 'n' { - return errNull("section") - } - if err := json.UnmarshalDecode(dec, &s.Section); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // The parameters of a notification message. type ShowMessageParams struct { // The message type. See MessageType - Type MessageType `json:"type"` + Type MessageType `json:"type" lsp:"required"` // The actual message. - Message string `json:"message"` + Message string `json:"message" lsp:"required"` } var _ json.UnmarshalerFrom = (*ShowMessageParams)(nil) func (s *ShowMessageParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingType uint = 1 << iota - missingMessage - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"type"`: - missing &^= missingType - if err := json.UnmarshalDecode(dec, &s.Type); err != nil { - return err - } - case `"message"`: - missing &^= missingMessage - if err := json.UnmarshalDecode(dec, &s.Message); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingType != 0 { - missingProps = append(missingProps, "type") - } - if missing&missingMessage != 0 { - missingProps = append(missingProps, "message") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type ShowMessageRequestParams struct { // The message type. See MessageType - Type MessageType `json:"type"` + Type MessageType `json:"type" lsp:"required"` // The actual message. - Message string `json:"message"` + Message string `json:"message" lsp:"required"` // The message action items to present. Actions *[]*MessageActionItem `json:"actions,omitzero"` @@ -6786,245 +1849,45 @@ type ShowMessageRequestParams struct { var _ json.UnmarshalerFrom = (*ShowMessageRequestParams)(nil) func (s *ShowMessageRequestParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingType uint = 1 << iota - missingMessage - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"type"`: - missing &^= missingType - if err := json.UnmarshalDecode(dec, &s.Type); err != nil { - return err - } - case `"message"`: - missing &^= missingMessage - if err := json.UnmarshalDecode(dec, &s.Message); err != nil { - return err - } - case `"actions"`: - if dec.PeekKind() == 'n' { - return errNull("actions") - } - if err := json.UnmarshalDecode(dec, &s.Actions); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingType != 0 { - missingProps = append(missingProps, "type") - } - if missing&missingMessage != 0 { - missingProps = append(missingProps, "message") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type MessageActionItem struct { // A short title like 'Retry', 'Open Log' etc. - Title string `json:"title"` + Title string `json:"title" lsp:"required"` } var _ json.UnmarshalerFrom = (*MessageActionItem)(nil) func (s *MessageActionItem) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTitle uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"title"`: - missing &^= missingTitle - if err := json.UnmarshalDecode(dec, &s.Title); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTitle != 0 { - missingProps = append(missingProps, "title") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The log message parameters. type LogMessageParams struct { // The message type. See MessageType - Type MessageType `json:"type"` + Type MessageType `json:"type" lsp:"required"` // The actual message. - Message string `json:"message"` + Message string `json:"message" lsp:"required"` } var _ json.UnmarshalerFrom = (*LogMessageParams)(nil) func (s *LogMessageParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingType uint = 1 << iota - missingMessage - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"type"`: - missing &^= missingType - if err := json.UnmarshalDecode(dec, &s.Type); err != nil { - return err - } - case `"message"`: - missing &^= missingMessage - if err := json.UnmarshalDecode(dec, &s.Message); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingType != 0 { - missingProps = append(missingProps, "type") - } - if missing&missingMessage != 0 { - missingProps = append(missingProps, "message") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters sent in an open text document notification type DidOpenTextDocumentParams struct { // The document that was opened. - TextDocument *TextDocumentItem `json:"textDocument"` + TextDocument *TextDocumentItem `json:"textDocument" lsp:"required"` } var _ json.UnmarshalerFrom = (*DidOpenTextDocumentParams)(nil) func (s *DidOpenTextDocumentParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if dec.PeekKind() == 'n' { - return errNull("textDocument") - } - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The change text document notification's parameters. @@ -7032,7 +1895,7 @@ type DidChangeTextDocumentParams struct { // The document that did change. The version number points // to the version after all provided content changes have // been applied. - TextDocument VersionedTextDocumentIdentifier `json:"textDocument"` + TextDocument VersionedTextDocumentIdentifier `json:"textDocument" lsp:"required"` // The actual content changes. The content changes describe single state changes // to the document. So if there are two content changes c1 (at array index 0) and @@ -7045,142 +1908,35 @@ type DidChangeTextDocumentParams struct { // - apply the 'textDocument/didChange' notifications in the order you receive them. // - apply the `TextDocumentContentChangeEvent`s in a single notification in the order // you receive them. - ContentChanges []TextDocumentContentChangePartialOrWholeDocument `json:"contentChanges"` + ContentChanges []TextDocumentContentChangePartialOrWholeDocument `json:"contentChanges" lsp:"required"` } var _ json.UnmarshalerFrom = (*DidChangeTextDocumentParams)(nil) func (s *DidChangeTextDocumentParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingContentChanges - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"contentChanges"`: - missing &^= missingContentChanges - if dec.PeekKind() == 'n' { - return errNull("contentChanges") - } - if err := json.UnmarshalDecode(dec, &s.ContentChanges); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingContentChanges != 0 { - missingProps = append(missingProps, "contentChanges") - } - return errMissing(missingProps) - } - - return nil -} - -// Describe options to be used when registered for text document change events. -type TextDocumentChangeRegistrationOptions struct { - // A document selector to identify the scope of the registration. If set to null - // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` +// Describe options to be used when registered for text document change events. +type TextDocumentChangeRegistrationOptions struct { + // A document selector to identify the scope of the registration. If set to null + // the document selector provided on the client side will be used. + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` // How documents are synced to the server. - SyncKind TextDocumentSyncKind `json:"syncKind"` + SyncKind TextDocumentSyncKind `json:"syncKind" lsp:"required"` } var _ json.UnmarshalerFrom = (*TextDocumentChangeRegistrationOptions)(nil) func (s *TextDocumentChangeRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - missingSyncKind - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"syncKind"`: - missing &^= missingSyncKind - if err := json.UnmarshalDecode(dec, &s.SyncKind); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - if missing&missingSyncKind != 0 { - missingProps = append(missingProps, "syncKind") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters sent in a close text document notification type DidCloseTextDocumentParams struct { // The document that was closed. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` } func (s *DidCloseTextDocumentParams) TextDocumentURI() DocumentUri { @@ -7190,56 +1946,13 @@ func (s *DidCloseTextDocumentParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*DidCloseTextDocumentParams)(nil) func (s *DidCloseTextDocumentParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters sent in a save text document notification type DidSaveTextDocumentParams struct { // The document that was saved. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // Optional the content when saved. Depends on the includeText value // when the save notification was requested. @@ -7253,64 +1966,14 @@ func (s *DidSaveTextDocumentParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*DidSaveTextDocumentParams)(nil) func (s *DidSaveTextDocumentParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"text"`: - if dec.PeekKind() == 'n' { - return errNull("text") - } - if err := json.UnmarshalDecode(dec, &s.Text); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Save registration options. type TextDocumentSaveRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` // The client is supposed to include the content on save. IncludeText *bool `json:"includeText,omitzero"` @@ -7319,66 +1982,16 @@ type TextDocumentSaveRegistrationOptions struct { var _ json.UnmarshalerFrom = (*TextDocumentSaveRegistrationOptions)(nil) func (s *TextDocumentSaveRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"includeText"`: - if dec.PeekKind() == 'n' { - return errNull("includeText") - } - if err := json.UnmarshalDecode(dec, &s.IncludeText); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters sent in a will save text document notification. type WillSaveTextDocumentParams struct { // The document that will be saved. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The 'TextDocumentSaveReason'. - Reason TextDocumentSaveReason `json:"reason"` + Reason TextDocumentSaveReason `json:"reason" lsp:"required"` } func (s *WillSaveTextDocumentParams) TextDocumentURI() DocumentUri { @@ -7388,257 +2001,61 @@ func (s *WillSaveTextDocumentParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*WillSaveTextDocumentParams)(nil) func (s *WillSaveTextDocumentParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingReason - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"reason"`: - missing &^= missingReason - if err := json.UnmarshalDecode(dec, &s.Reason); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingReason != 0 { - missingProps = append(missingProps, "reason") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A text edit applicable to a text document. type TextEdit struct { // The range of the text document to be manipulated. To insert // text into a document create a range where start === end. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The string to be inserted. For delete operations use an // empty string. - NewText string `json:"newText"` + NewText string `json:"newText" lsp:"required"` } var _ json.UnmarshalerFrom = (*TextEdit)(nil) func (s *TextEdit) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - missingNewText - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } + return unmarshalStruct(s, dec) +} - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"newText"`: - missing &^= missingNewText - if err := json.UnmarshalDecode(dec, &s.NewText); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } +func (s *TextEdit) Compare(other *TextEdit) int { + if c := s.Range.Compare(&other.Range); c != 0 { + return c } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingNewText != 0 { - missingProps = append(missingProps, "newText") - } - return errMissing(missingProps) - } - - return nil -} - -func (s *TextEdit) Compare(other *TextEdit) int { - if c := s.Range.Compare(&other.Range); c != 0 { - return c - } - return cmp.Compare(s.NewText, other.NewText) -} + return cmp.Compare(s.NewText, other.NewText) +} // The watched files change notification's parameters. type DidChangeWatchedFilesParams struct { // The actual file events. - Changes []*FileEvent `json:"changes"` + Changes []*FileEvent `json:"changes" lsp:"required"` } var _ json.UnmarshalerFrom = (*DidChangeWatchedFilesParams)(nil) func (s *DidChangeWatchedFilesParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingChanges uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"changes"`: - missing &^= missingChanges - if dec.PeekKind() == 'n' { - return errNull("changes") - } - if err := json.UnmarshalDecode(dec, &s.Changes); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingChanges != 0 { - missingProps = append(missingProps, "changes") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Describe options to be used when registered for text document change events. type DidChangeWatchedFilesRegistrationOptions struct { // The watchers to register. - Watchers []*FileSystemWatcher `json:"watchers"` + Watchers []*FileSystemWatcher `json:"watchers" lsp:"required"` } var _ json.UnmarshalerFrom = (*DidChangeWatchedFilesRegistrationOptions)(nil) func (s *DidChangeWatchedFilesRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingWatchers uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"watchers"`: - missing &^= missingWatchers - if dec.PeekKind() == 'n' { - return errNull("watchers") - } - if err := json.UnmarshalDecode(dec, &s.Watchers); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingWatchers != 0 { - missingProps = append(missingProps, "watchers") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The publish diagnostic notification's parameters. type PublishDiagnosticsParams struct { // The URI for which diagnostic information is reported. - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` // Optional the version number of the document the diagnostics are published for. // @@ -7646,84 +2063,22 @@ type PublishDiagnosticsParams struct { Version *int32 `json:"version,omitzero"` // An array of diagnostic information items. - Diagnostics []*Diagnostic `json:"diagnostics"` + Diagnostics []*Diagnostic `json:"diagnostics" lsp:"required"` } var _ json.UnmarshalerFrom = (*PublishDiagnosticsParams)(nil) func (s *PublishDiagnosticsParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - missingDiagnostics - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"version"`: - if dec.PeekKind() == 'n' { - return errNull("version") - } - if err := json.UnmarshalDecode(dec, &s.Version); err != nil { - return err - } - case `"diagnostics"`: - missing &^= missingDiagnostics - if dec.PeekKind() == 'n' { - return errNull("diagnostics") - } - if err := json.UnmarshalDecode(dec, &s.Diagnostics); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - if missing&missingDiagnostics != 0 { - missingProps = append(missingProps, "diagnostics") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Completion parameters type CompletionParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -7748,80 +2103,7 @@ func (s *CompletionParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*CompletionParams)(nil) func (s *CompletionParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"context"`: - if dec.PeekKind() == 'n' { - return errNull("context") - } - if err := json.UnmarshalDecode(dec, &s.Context); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A completion item represents a text snippet that is @@ -7834,7 +2116,7 @@ type CompletionItem struct { // // If label details are provided the label itself should // be an unqualified name of the completion item. - Label string `json:"label"` + Label string `json:"label" lsp:"required"` // Additional details for the label // @@ -7968,186 +2250,17 @@ type CompletionItem struct { var _ json.UnmarshalerFrom = (*CompletionItem)(nil) func (s *CompletionItem) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingLabel uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"label"`: - missing &^= missingLabel - if err := json.UnmarshalDecode(dec, &s.Label); err != nil { - return err - } - case `"labelDetails"`: - if dec.PeekKind() == 'n' { - return errNull("labelDetails") - } - if err := json.UnmarshalDecode(dec, &s.LabelDetails); err != nil { - return err - } - case `"kind"`: - if dec.PeekKind() == 'n' { - return errNull("kind") - } - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"tags"`: - if dec.PeekKind() == 'n' { - return errNull("tags") - } - if err := json.UnmarshalDecode(dec, &s.Tags); err != nil { - return err - } - case `"detail"`: - if dec.PeekKind() == 'n' { - return errNull("detail") - } - if err := json.UnmarshalDecode(dec, &s.Detail); err != nil { - return err - } - case `"documentation"`: - if dec.PeekKind() == 'n' { - return errNull("documentation") - } - if err := json.UnmarshalDecode(dec, &s.Documentation); err != nil { - return err - } - case `"deprecated"`: - if dec.PeekKind() == 'n' { - return errNull("deprecated") - } - if err := json.UnmarshalDecode(dec, &s.Deprecated); err != nil { - return err - } - case `"preselect"`: - if dec.PeekKind() == 'n' { - return errNull("preselect") - } - if err := json.UnmarshalDecode(dec, &s.Preselect); err != nil { - return err - } - case `"sortText"`: - if dec.PeekKind() == 'n' { - return errNull("sortText") - } - if err := json.UnmarshalDecode(dec, &s.SortText); err != nil { - return err - } - case `"filterText"`: - if dec.PeekKind() == 'n' { - return errNull("filterText") - } - if err := json.UnmarshalDecode(dec, &s.FilterText); err != nil { - return err - } - case `"insertText"`: - if dec.PeekKind() == 'n' { - return errNull("insertText") - } - if err := json.UnmarshalDecode(dec, &s.InsertText); err != nil { - return err - } - case `"insertTextFormat"`: - if dec.PeekKind() == 'n' { - return errNull("insertTextFormat") - } - if err := json.UnmarshalDecode(dec, &s.InsertTextFormat); err != nil { - return err - } - case `"insertTextMode"`: - if dec.PeekKind() == 'n' { - return errNull("insertTextMode") - } - if err := json.UnmarshalDecode(dec, &s.InsertTextMode); err != nil { - return err - } - case `"textEdit"`: - if dec.PeekKind() == 'n' { - return errNull("textEdit") - } - if err := json.UnmarshalDecode(dec, &s.TextEdit); err != nil { - return err - } - case `"textEditText"`: - if dec.PeekKind() == 'n' { - return errNull("textEditText") - } - if err := json.UnmarshalDecode(dec, &s.TextEditText); err != nil { - return err - } - case `"additionalTextEdits"`: - if dec.PeekKind() == 'n' { - return errNull("additionalTextEdits") - } - if err := json.UnmarshalDecode(dec, &s.AdditionalTextEdits); err != nil { - return err - } - case `"commitCharacters"`: - if dec.PeekKind() == 'n' { - return errNull("commitCharacters") - } - if err := json.UnmarshalDecode(dec, &s.CommitCharacters); err != nil { - return err - } - case `"command"`: - if dec.PeekKind() == 'n' { - return errNull("command") - } - if err := json.UnmarshalDecode(dec, &s.Command); err != nil { - return err - } - case `"data"`: - if dec.PeekKind() == 'n' { - return errNull("data") - } - if err := json.UnmarshalDecode(dec, &s.Data); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingLabel != 0 { - missingProps = append(missingProps, "label") - } - return errMissing(missingProps) - } - - return nil -} - -// Represents a collection of items to be presented -// in the editor. -type CompletionList struct { - // This list it not complete. Further typing results in recomputing this list. - // - // Recomputed lists have all their items replaced (not appended) in the - // incomplete completion sessions. - IsIncomplete bool `json:"isIncomplete"` +// Represents a collection of items to be presented +// in the editor. +type CompletionList struct { + // This list it not complete. Further typing results in recomputing this list. + // + // Recomputed lists have all their items replaced (not appended) in the + // incomplete completion sessions. + IsIncomplete bool `json:"isIncomplete" lsp:"required"` // In many cases the items of an actual completion result share the same // value for properties like `commitCharacters` or the range of a text @@ -8186,89 +2299,20 @@ type CompletionList struct { ApplyKind *CompletionItemApplyKinds `json:"applyKind,omitzero"` // The completion items. - Items []*CompletionItem `json:"items"` + Items []*CompletionItem `json:"items" lsp:"required"` } var _ json.UnmarshalerFrom = (*CompletionList)(nil) func (s *CompletionList) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingIsIncomplete uint = 1 << iota - missingItems - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"isIncomplete"`: - missing &^= missingIsIncomplete - if err := json.UnmarshalDecode(dec, &s.IsIncomplete); err != nil { - return err - } - case `"itemDefaults"`: - if dec.PeekKind() == 'n' { - return errNull("itemDefaults") - } - if err := json.UnmarshalDecode(dec, &s.ItemDefaults); err != nil { - return err - } - case `"applyKind"`: - if dec.PeekKind() == 'n' { - return errNull("applyKind") - } - if err := json.UnmarshalDecode(dec, &s.ApplyKind); err != nil { - return err - } - case `"items"`: - missing &^= missingItems - if dec.PeekKind() == 'n' { - return errNull("items") - } - if err := json.UnmarshalDecode(dec, &s.Items); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingIsIncomplete != 0 { - missingProps = append(missingProps, "isIncomplete") - } - if missing&missingItems != 0 { - missingProps = append(missingProps, "items") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a CompletionRequest. type CompletionRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -8306,94 +2350,16 @@ type CompletionRegistrationOptions struct { var _ json.UnmarshalerFrom = (*CompletionRegistrationOptions)(nil) func (s *CompletionRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"triggerCharacters"`: - if dec.PeekKind() == 'n' { - return errNull("triggerCharacters") - } - if err := json.UnmarshalDecode(dec, &s.TriggerCharacters); err != nil { - return err - } - case `"allCommitCharacters"`: - if dec.PeekKind() == 'n' { - return errNull("allCommitCharacters") - } - if err := json.UnmarshalDecode(dec, &s.AllCommitCharacters); err != nil { - return err - } - case `"resolveProvider"`: - if dec.PeekKind() == 'n' { - return errNull("resolveProvider") - } - if err := json.UnmarshalDecode(dec, &s.ResolveProvider); err != nil { - return err - } - case `"completionItem"`: - if dec.PeekKind() == 'n' { - return errNull("completionItem") - } - if err := json.UnmarshalDecode(dec, &s.CompletionItem); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters for a HoverRequest. type HoverParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -8413,153 +2379,33 @@ func (s *HoverParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*HoverParams)(nil) func (s *HoverParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"verbosityLevel"`: - if dec.PeekKind() == 'n' { - return errNull("verbosityLevel") - } - if err := json.UnmarshalDecode(dec, &s.VerbosityLevel); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The result of a hover request. type Hover struct { // The hover's content - Contents MarkupContentOrStringOrMarkedStringWithLanguageOrMarkedStrings `json:"contents"` + Contents MarkupContentOrStringOrMarkedStringWithLanguageOrMarkedStrings `json:"contents" lsp:"required"` // An optional range inside the text document that is used to // visualize the hover, e.g. by changing the background color. Range *Range `json:"range,omitzero"` // Whether the verbosity level can be increased for this hover. - CanIncreaseVerbosity bool `json:"canIncreaseVerbosity,omitzero"` + CanIncreaseVerbosity bool `json:"canIncreaseVerbosity,omitzero" lsp:"nullable"` } var _ json.UnmarshalerFrom = (*Hover)(nil) func (s *Hover) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingContents uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"contents"`: - missing &^= missingContents - if err := json.UnmarshalDecode(dec, &s.Contents); err != nil { - return err - } - case `"range"`: - if dec.PeekKind() == 'n' { - return errNull("range") - } - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"canIncreaseVerbosity"`: - if err := json.UnmarshalDecode(dec, &s.CanIncreaseVerbosity); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingContents != 0 { - missingProps = append(missingProps, "contents") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a HoverRequest. type HoverRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` } @@ -8567,66 +2413,16 @@ type HoverRegistrationOptions struct { var _ json.UnmarshalerFrom = (*HoverRegistrationOptions)(nil) func (s *HoverRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil -} - -// Parameters for a SignatureHelpRequest. -type SignatureHelpParams struct { - // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` +// Parameters for a SignatureHelpRequest. +type SignatureHelpParams struct { + // The text document. + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -8649,73 +2445,7 @@ func (s *SignatureHelpParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*SignatureHelpParams)(nil) func (s *SignatureHelpParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"context"`: - if dec.PeekKind() == 'n' { - return errNull("context") - } - if err := json.UnmarshalDecode(dec, &s.Context); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Signature help represents the signature of something @@ -8723,7 +2453,7 @@ func (s *SignatureHelpParams) UnmarshalJSONFrom(dec *json.Decoder) error { // active and only one active parameter. type SignatureHelp struct { // One or more signatures. - Signatures []*SignatureInformation `json:"signatures"` + Signatures []*SignatureInformation `json:"signatures" lsp:"required"` // The active signature. If omitted or the value lies outside the // range of `signatures` the value defaults to zero or is ignored if @@ -8755,77 +2485,20 @@ type SignatureHelp struct { // // Since version 3.16.0 the `SignatureInformation` itself provides a // `activeParameter` property and it should be used instead of this one. - ActiveParameter *UintegerOrNull `json:"activeParameter,omitzero"` + ActiveParameter *UintegerOrNull `json:"activeParameter,omitzero" lsp:"nullable"` } var _ json.UnmarshalerFrom = (*SignatureHelp)(nil) func (s *SignatureHelp) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingSignatures uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"signatures"`: - missing &^= missingSignatures - if dec.PeekKind() == 'n' { - return errNull("signatures") - } - if err := json.UnmarshalDecode(dec, &s.Signatures); err != nil { - return err - } - case `"activeSignature"`: - if dec.PeekKind() == 'n' { - return errNull("activeSignature") - } - if err := json.UnmarshalDecode(dec, &s.ActiveSignature); err != nil { - return err - } - case `"activeParameter"`: - if err := json.UnmarshalDecode(dec, &s.ActiveParameter); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingSignatures != 0 { - missingProps = append(missingProps, "signatures") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a SignatureHelpRequest. type SignatureHelpRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -8844,80 +2517,16 @@ type SignatureHelpRegistrationOptions struct { var _ json.UnmarshalerFrom = (*SignatureHelpRegistrationOptions)(nil) func (s *SignatureHelpRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"triggerCharacters"`: - if dec.PeekKind() == 'n' { - return errNull("triggerCharacters") - } - if err := json.UnmarshalDecode(dec, &s.TriggerCharacters); err != nil { - return err - } - case `"retriggerCharacters"`: - if dec.PeekKind() == 'n' { - return errNull("retriggerCharacters") - } - if err := json.UnmarshalDecode(dec, &s.RetriggerCharacters); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters for a DefinitionRequest. type DefinitionParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -8938,80 +2547,14 @@ func (s *DefinitionParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*DefinitionParams)(nil) func (s *DefinitionParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a DefinitionRequest. type DefinitionRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` } @@ -9019,66 +2562,16 @@ type DefinitionRegistrationOptions struct { var _ json.UnmarshalerFrom = (*DefinitionRegistrationOptions)(nil) func (s *DefinitionRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters for a ReferencesRequest. type ReferenceParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -9087,7 +2580,7 @@ type ReferenceParams struct { // the client. PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` - Context *ReferenceContext `json:"context"` + Context *ReferenceContext `json:"context" lsp:"required"` } func (s *ReferenceParams) TextDocumentURI() DocumentUri { @@ -9101,92 +2594,14 @@ func (s *ReferenceParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*ReferenceParams)(nil) func (s *ReferenceParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - missingContext - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"context"`: - missing &^= missingContext - if dec.PeekKind() == 'n' { - return errNull("context") - } - if err := json.UnmarshalDecode(dec, &s.Context); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - if missing&missingContext != 0 { - missingProps = append(missingProps, "context") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a ReferencesRequest. type ReferenceRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` } @@ -9194,66 +2609,16 @@ type ReferenceRegistrationOptions struct { var _ json.UnmarshalerFrom = (*ReferenceRegistrationOptions)(nil) func (s *ReferenceRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters for a DocumentHighlightRequest. type DocumentHighlightParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -9274,73 +2639,7 @@ func (s *DocumentHighlightParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*DocumentHighlightParams)(nil) func (s *DocumentHighlightParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A document highlight is a range inside a text document which deserves @@ -9348,7 +2647,7 @@ func (s *DocumentHighlightParams) UnmarshalJSONFrom(dec *json.Decoder) error { // the background color of its range. type DocumentHighlight struct { // The range this highlight applies to. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The highlight kind, default is text. Kind *DocumentHighlightKind `json:"kind,omitzero"` @@ -9357,64 +2656,14 @@ type DocumentHighlight struct { var _ json.UnmarshalerFrom = (*DocumentHighlight)(nil) func (s *DocumentHighlight) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"kind"`: - if dec.PeekKind() == 'n' { - return errNull("kind") - } - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a DocumentHighlightRequest. type DocumentHighlightRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` } @@ -9422,57 +2671,7 @@ type DocumentHighlightRegistrationOptions struct { var _ json.UnmarshalerFrom = (*DocumentHighlightRegistrationOptions)(nil) func (s *DocumentHighlightRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters for a DocumentSymbolRequest. @@ -9485,7 +2684,7 @@ type DocumentSymbolParams struct { PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` } func (s *DocumentSymbolParams) TextDocumentURI() DocumentUri { @@ -9495,74 +2694,17 @@ func (s *DocumentSymbolParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*DocumentSymbolParams)(nil) func (s *DocumentSymbolParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } +// Represents information about programming constructs like variables, classes, +// interfaces etc. +type SymbolInformation struct { + // The name of this symbol. + Name string `json:"name" lsp:"required"` - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - return errMissing(missingProps) - } - - return nil -} - -// Represents information about programming constructs like variables, classes, -// interfaces etc. -type SymbolInformation struct { - // The name of this symbol. - Name string `json:"name"` - - // The kind of this symbol. - Kind SymbolKind `json:"kind"` + // The kind of this symbol. + Kind SymbolKind `json:"kind" lsp:"required"` // Tags for this symbol. // @@ -9589,95 +2731,13 @@ type SymbolInformation struct { // The range doesn't have to denote a node range in the sense of an abstract // syntax tree. It can therefore not be used to re-construct a hierarchy of // the symbols. - Location Location `json:"location"` + Location Location `json:"location" lsp:"required"` } var _ json.UnmarshalerFrom = (*SymbolInformation)(nil) func (s *SymbolInformation) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingName uint = 1 << iota - missingKind - missingLocation - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"name"`: - missing &^= missingName - if err := json.UnmarshalDecode(dec, &s.Name); err != nil { - return err - } - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"tags"`: - if dec.PeekKind() == 'n' { - return errNull("tags") - } - if err := json.UnmarshalDecode(dec, &s.Tags); err != nil { - return err - } - case `"containerName"`: - if dec.PeekKind() == 'n' { - return errNull("containerName") - } - if err := json.UnmarshalDecode(dec, &s.ContainerName); err != nil { - return err - } - case `"deprecated"`: - if dec.PeekKind() == 'n' { - return errNull("deprecated") - } - if err := json.UnmarshalDecode(dec, &s.Deprecated); err != nil { - return err - } - case `"location"`: - missing &^= missingLocation - if err := json.UnmarshalDecode(dec, &s.Location); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingName != 0 { - missingProps = append(missingProps, "name") - } - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingLocation != 0 { - missingProps = append(missingProps, "location") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Represents programming constructs like variables, classes, interfaces etc. @@ -9687,13 +2747,13 @@ func (s *SymbolInformation) UnmarshalJSONFrom(dec *json.Decoder) error { type DocumentSymbol struct { // The name of this symbol. Will be displayed in the user interface and therefore must not be // an empty string or a string only consisting of white spaces. - Name string `json:"name"` + Name string `json:"name" lsp:"required"` // More detail for this symbol, e.g the signature of a function. Detail *string `json:"detail,omitzero"` // The kind of this symbol. - Kind SymbolKind `json:"kind"` + Kind SymbolKind `json:"kind" lsp:"required"` // Tags for this document symbol. // @@ -9708,11 +2768,11 @@ type DocumentSymbol struct { // The range enclosing this symbol not including leading/trailing whitespace but everything else // like comments. This information is typically used to determine if the clients cursor is // inside the symbol to reveal in the symbol in the UI. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The range that should be selected and revealed when this symbol is being picked, e.g the name of a function. // Must be contained by the `range`. - SelectionRange Range `json:"selectionRange"` + SelectionRange Range `json:"selectionRange" lsp:"required"` // Children of this symbol, e.g. properties of a class. Children *[]*DocumentSymbol `json:"children,omitzero"` @@ -9721,112 +2781,14 @@ type DocumentSymbol struct { var _ json.UnmarshalerFrom = (*DocumentSymbol)(nil) func (s *DocumentSymbol) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingName uint = 1 << iota - missingKind - missingRange - missingSelectionRange - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"name"`: - missing &^= missingName - if err := json.UnmarshalDecode(dec, &s.Name); err != nil { - return err - } - case `"detail"`: - if dec.PeekKind() == 'n' { - return errNull("detail") - } - if err := json.UnmarshalDecode(dec, &s.Detail); err != nil { - return err - } - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"tags"`: - if dec.PeekKind() == 'n' { - return errNull("tags") - } - if err := json.UnmarshalDecode(dec, &s.Tags); err != nil { - return err - } - case `"deprecated"`: - if dec.PeekKind() == 'n' { - return errNull("deprecated") - } - if err := json.UnmarshalDecode(dec, &s.Deprecated); err != nil { - return err - } - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"selectionRange"`: - missing &^= missingSelectionRange - if err := json.UnmarshalDecode(dec, &s.SelectionRange); err != nil { - return err - } - case `"children"`: - if dec.PeekKind() == 'n' { - return errNull("children") - } - if err := json.UnmarshalDecode(dec, &s.Children); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingName != 0 { - missingProps = append(missingProps, "name") - } - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingSelectionRange != 0 { - missingProps = append(missingProps, "selectionRange") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a DocumentSymbolRequest. type DocumentSymbolRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -9840,64 +2802,7 @@ type DocumentSymbolRegistrationOptions struct { var _ json.UnmarshalerFrom = (*DocumentSymbolRegistrationOptions)(nil) func (s *DocumentSymbolRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"label"`: - if dec.PeekKind() == 'n' { - return errNull("label") - } - if err := json.UnmarshalDecode(dec, &s.Label); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters of a CodeActionRequest. @@ -9910,13 +2815,13 @@ type CodeActionParams struct { PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` // The document in which the command was invoked. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The range for which the command was invoked. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // Context carrying additional information. - Context *CodeActionContext `json:"context"` + Context *CodeActionContext `json:"context" lsp:"required"` } func (s *CodeActionParams) TextDocumentURI() DocumentUri { @@ -9926,85 +2831,7 @@ func (s *CodeActionParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*CodeActionParams)(nil) func (s *CodeActionParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingRange - missingContext - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"context"`: - missing &^= missingContext - if dec.PeekKind() == 'n' { - return errNull("context") - } - if err := json.UnmarshalDecode(dec, &s.Context); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingContext != 0 { - missingProps = append(missingProps, "context") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Represents a reference to a command. Provides a title which @@ -10013,7 +2840,7 @@ func (s *CodeActionParams) UnmarshalJSONFrom(dec *json.Decoder) error { // function when invoked. type Command struct { // Title of the command, like `save`. - Title string `json:"title"` + Title string `json:"title" lsp:"required"` // An optional tooltip. // @@ -10021,7 +2848,7 @@ type Command struct { Tooltip *string `json:"tooltip,omitzero"` // The identifier of the actual command handler. - Command string `json:"command"` + Command string `json:"command" lsp:"required"` // Arguments that the command handler should be // invoked with. @@ -10031,82 +2858,16 @@ type Command struct { var _ json.UnmarshalerFrom = (*Command)(nil) func (s *Command) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTitle uint = 1 << iota - missingCommand - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"title"`: - missing &^= missingTitle - if err := json.UnmarshalDecode(dec, &s.Title); err != nil { - return err - } - case `"tooltip"`: - if dec.PeekKind() == 'n' { - return errNull("tooltip") - } - if err := json.UnmarshalDecode(dec, &s.Tooltip); err != nil { - return err - } - case `"command"`: - missing &^= missingCommand - if err := json.UnmarshalDecode(dec, &s.Command); err != nil { - return err - } - case `"arguments"`: - if dec.PeekKind() == 'n' { - return errNull("arguments") - } - if err := json.UnmarshalDecode(dec, &s.Arguments); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTitle != 0 { - missingProps = append(missingProps, "title") - } - if missing&missingCommand != 0 { - missingProps = append(missingProps, "command") - } - return errMissing(missingProps) - } - - return nil -} - -// A code action represents a change that can be performed in code, e.g. to fix a problem or -// to refactor code. -// -// A CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed. -type CodeAction struct { - // A short, human-readable, title for this code action. - Title string `json:"title"` +// A code action represents a change that can be performed in code, e.g. to fix a problem or +// to refactor code. +// +// A CodeAction must set either `edit` and/or a `command`. If both are supplied, the `edit` is applied first, then the `command` is executed. +type CodeAction struct { + // A short, human-readable, title for this code action. + Title string `json:"title" lsp:"required"` // The kind of the code action. // @@ -10165,113 +2926,14 @@ type CodeAction struct { var _ json.UnmarshalerFrom = (*CodeAction)(nil) func (s *CodeAction) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTitle uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"title"`: - missing &^= missingTitle - if err := json.UnmarshalDecode(dec, &s.Title); err != nil { - return err - } - case `"kind"`: - if dec.PeekKind() == 'n' { - return errNull("kind") - } - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"diagnostics"`: - if dec.PeekKind() == 'n' { - return errNull("diagnostics") - } - if err := json.UnmarshalDecode(dec, &s.Diagnostics); err != nil { - return err - } - case `"isPreferred"`: - if dec.PeekKind() == 'n' { - return errNull("isPreferred") - } - if err := json.UnmarshalDecode(dec, &s.IsPreferred); err != nil { - return err - } - case `"disabled"`: - if dec.PeekKind() == 'n' { - return errNull("disabled") - } - if err := json.UnmarshalDecode(dec, &s.Disabled); err != nil { - return err - } - case `"edit"`: - if dec.PeekKind() == 'n' { - return errNull("edit") - } - if err := json.UnmarshalDecode(dec, &s.Edit); err != nil { - return err - } - case `"command"`: - if dec.PeekKind() == 'n' { - return errNull("command") - } - if err := json.UnmarshalDecode(dec, &s.Command); err != nil { - return err - } - case `"data"`: - if dec.PeekKind() == 'n' { - return errNull("data") - } - if err := json.UnmarshalDecode(dec, &s.Data); err != nil { - return err - } - case `"tags"`: - if dec.PeekKind() == 'n' { - return errNull("tags") - } - if err := json.UnmarshalDecode(dec, &s.Tags); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTitle != 0 { - missingProps = append(missingProps, "title") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a CodeActionRequest. type CodeActionRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -10307,78 +2969,7 @@ type CodeActionRegistrationOptions struct { var _ json.UnmarshalerFrom = (*CodeActionRegistrationOptions)(nil) func (s *CodeActionRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"codeActionKinds"`: - if dec.PeekKind() == 'n' { - return errNull("codeActionKinds") - } - if err := json.UnmarshalDecode(dec, &s.CodeActionKinds); err != nil { - return err - } - case `"documentation"`: - if dec.PeekKind() == 'n' { - return errNull("documentation") - } - if err := json.UnmarshalDecode(dec, &s.Documentation); err != nil { - return err - } - case `"resolveProvider"`: - if dec.PeekKind() == 'n' { - return errNull("resolveProvider") - } - if err := json.UnmarshalDecode(dec, &s.ResolveProvider); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters of a WorkspaceSymbolRequest. @@ -10398,70 +2989,13 @@ type WorkspaceSymbolParams struct { // of thumb is to match case-insensitive and to simply check that the // characters of *query* appear in their order in a candidate symbol. // Servers shouldn't use prefix, substring, or similar strict matching. - Query string `json:"query"` + Query string `json:"query" lsp:"required"` } var _ json.UnmarshalerFrom = (*WorkspaceSymbolParams)(nil) func (s *WorkspaceSymbolParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingQuery uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"query"`: - missing &^= missingQuery - if err := json.UnmarshalDecode(dec, &s.Query); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingQuery != 0 { - missingProps = append(missingProps, "query") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A special workspace symbol that supports locations without a range. @@ -10471,10 +3005,10 @@ func (s *WorkspaceSymbolParams) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.17.0 type WorkspaceSymbol struct { // The name of this symbol. - Name string `json:"name"` + Name string `json:"name" lsp:"required"` // The kind of this symbol. - Kind SymbolKind `json:"kind"` + Kind SymbolKind `json:"kind" lsp:"required"` // Tags for this symbol. // @@ -10492,7 +3026,7 @@ type WorkspaceSymbol struct { // capability `workspace.symbol.resolveSupport`. // // See SymbolInformation#location for more details. - Location LocationOrLocationUriOnly `json:"location"` + Location LocationOrLocationUriOnly `json:"location" lsp:"required"` // A data entry field that is preserved on a workspace symbol between a // workspace symbol request and a workspace symbol resolve request. @@ -10502,89 +3036,7 @@ type WorkspaceSymbol struct { var _ json.UnmarshalerFrom = (*WorkspaceSymbol)(nil) func (s *WorkspaceSymbol) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingName uint = 1 << iota - missingKind - missingLocation - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"name"`: - missing &^= missingName - if err := json.UnmarshalDecode(dec, &s.Name); err != nil { - return err - } - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"tags"`: - if dec.PeekKind() == 'n' { - return errNull("tags") - } - if err := json.UnmarshalDecode(dec, &s.Tags); err != nil { - return err - } - case `"containerName"`: - if dec.PeekKind() == 'n' { - return errNull("containerName") - } - if err := json.UnmarshalDecode(dec, &s.ContainerName); err != nil { - return err - } - case `"location"`: - missing &^= missingLocation - if err := json.UnmarshalDecode(dec, &s.Location); err != nil { - return err - } - case `"data"`: - if dec.PeekKind() == 'n' { - return errNull("data") - } - if err := json.UnmarshalDecode(dec, &s.Data); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingName != 0 { - missingProps = append(missingProps, "name") - } - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingLocation != 0 { - missingProps = append(missingProps, "location") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a WorkspaceSymbolRequest. @@ -10601,46 +3053,8 @@ type WorkspaceSymbolRegistrationOptions struct { var _ json.UnmarshalerFrom = (*WorkspaceSymbolRegistrationOptions)(nil) func (s *WorkspaceSymbolRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"resolveProvider"`: - if dec.PeekKind() == 'n' { - return errNull("resolveProvider") - } - if err := json.UnmarshalDecode(dec, &s.ResolveProvider); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil -} + return unmarshalStruct(s, dec) +} // The parameters of a CodeLensRequest. type CodeLensParams struct { @@ -10652,7 +3066,7 @@ type CodeLensParams struct { PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` // The document to request code lens for. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` } func (s *CodeLensParams) TextDocumentURI() DocumentUri { @@ -10662,64 +3076,7 @@ func (s *CodeLensParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*CodeLensParams)(nil) func (s *CodeLensParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A code lens represents a command that should be shown along with @@ -10729,7 +3086,7 @@ func (s *CodeLensParams) UnmarshalJSONFrom(dec *json.Decoder) error { // reasons the creation of a code lens and resolving should be done in two stages. type CodeLens struct { // The range in which this code lens is valid. Should only span a single line. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The command this code lens represents. Command *Command `json:"command,omitzero"` @@ -10742,71 +3099,14 @@ type CodeLens struct { var _ json.UnmarshalerFrom = (*CodeLens)(nil) func (s *CodeLens) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"command"`: - if dec.PeekKind() == 'n' { - return errNull("command") - } - if err := json.UnmarshalDecode(dec, &s.Command); err != nil { - return err - } - case `"data"`: - if dec.PeekKind() == 'n' { - return errNull("data") - } - if err := json.UnmarshalDecode(dec, &s.Data); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a CodeLensRequest. type CodeLensRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -10817,64 +3117,7 @@ type CodeLensRegistrationOptions struct { var _ json.UnmarshalerFrom = (*CodeLensRegistrationOptions)(nil) func (s *CodeLensRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"resolveProvider"`: - if dec.PeekKind() == 'n' { - return errNull("resolveProvider") - } - if err := json.UnmarshalDecode(dec, &s.ResolveProvider); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters of a DocumentLinkRequest. @@ -10887,7 +3130,7 @@ type DocumentLinkParams struct { PartialResultToken *IntegerOrString `json:"partialResultToken,omitzero"` // The document to provide document links for. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` } func (s *DocumentLinkParams) TextDocumentURI() DocumentUri { @@ -10897,71 +3140,14 @@ func (s *DocumentLinkParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*DocumentLinkParams)(nil) func (s *DocumentLinkParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A document link is a range in a text document that links to an internal or external resource, like another // text document or a web site. type DocumentLink struct { // The range this link applies to. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The uri this link points to. If missing a resolve request is sent later. Target *URI `json:"target,omitzero"` @@ -10983,78 +3169,14 @@ type DocumentLink struct { var _ json.UnmarshalerFrom = (*DocumentLink)(nil) func (s *DocumentLink) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"target"`: - if dec.PeekKind() == 'n' { - return errNull("target") - } - if err := json.UnmarshalDecode(dec, &s.Target); err != nil { - return err - } - case `"tooltip"`: - if dec.PeekKind() == 'n' { - return errNull("tooltip") - } - if err := json.UnmarshalDecode(dec, &s.Tooltip); err != nil { - return err - } - case `"data"`: - if dec.PeekKind() == 'n' { - return errNull("data") - } - if err := json.UnmarshalDecode(dec, &s.Data); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a DocumentLinkRequest. type DocumentLinkRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -11065,76 +3187,19 @@ type DocumentLinkRegistrationOptions struct { var _ json.UnmarshalerFrom = (*DocumentLinkRegistrationOptions)(nil) func (s *DocumentLinkRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"resolveProvider"`: - if dec.PeekKind() == 'n' { - return errNull("resolveProvider") - } - if err := json.UnmarshalDecode(dec, &s.ResolveProvider); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil -} - -// The parameters of a DocumentFormattingRequest. -type DocumentFormattingParams struct { - // An optional token that a server can use to report work done progress. - WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` +// The parameters of a DocumentFormattingRequest. +type DocumentFormattingParams struct { + // An optional token that a server can use to report work done progress. + WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` // The document to format. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The format options. - Options *FormattingOptions `json:"options"` + Options *FormattingOptions `json:"options" lsp:"required"` } func (s *DocumentFormattingParams) TextDocumentURI() DocumentUri { @@ -11144,76 +3209,14 @@ func (s *DocumentFormattingParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*DocumentFormattingParams)(nil) func (s *DocumentFormattingParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingOptions - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"options"`: - missing &^= missingOptions - if dec.PeekKind() == 'n' { - return errNull("options") - } - if err := json.UnmarshalDecode(dec, &s.Options); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingOptions != 0 { - missingProps = append(missingProps, "options") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a DocumentFormattingRequest. type DocumentFormattingRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` } @@ -11221,57 +3224,7 @@ type DocumentFormattingRegistrationOptions struct { var _ json.UnmarshalerFrom = (*DocumentFormattingRegistrationOptions)(nil) func (s *DocumentFormattingRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters of a DocumentRangeFormattingRequest. @@ -11280,13 +3233,13 @@ type DocumentRangeFormattingParams struct { WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` // The document to format. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The range to format - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The format options - Options *FormattingOptions `json:"options"` + Options *FormattingOptions `json:"options" lsp:"required"` } func (s *DocumentRangeFormattingParams) TextDocumentURI() DocumentUri { @@ -11296,85 +3249,14 @@ func (s *DocumentRangeFormattingParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*DocumentRangeFormattingParams)(nil) func (s *DocumentRangeFormattingParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingRange - missingOptions - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"options"`: - missing &^= missingOptions - if dec.PeekKind() == 'n' { - return errNull("options") - } - if err := json.UnmarshalDecode(dec, &s.Options); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingOptions != 0 { - missingProps = append(missingProps, "options") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a DocumentRangeFormattingRequest. type DocumentRangeFormattingRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -11387,64 +3269,7 @@ type DocumentRangeFormattingRegistrationOptions struct { var _ json.UnmarshalerFrom = (*DocumentRangeFormattingRegistrationOptions)(nil) func (s *DocumentRangeFormattingRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"rangesSupport"`: - if dec.PeekKind() == 'n' { - return errNull("rangesSupport") - } - if err := json.UnmarshalDecode(dec, &s.RangesSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters of a DocumentRangesFormattingRequest. @@ -11455,13 +3280,13 @@ type DocumentRangesFormattingParams struct { WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` // The document to format. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The ranges to format - Ranges []Range `json:"ranges"` + Ranges []Range `json:"ranges" lsp:"required"` // The format options - Options *FormattingOptions `json:"options"` + Options *FormattingOptions `json:"options" lsp:"required"` } func (s *DocumentRangesFormattingParams) TextDocumentURI() DocumentUri { @@ -11471,101 +3296,27 @@ func (s *DocumentRangesFormattingParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*DocumentRangesFormattingParams)(nil) func (s *DocumentRangesFormattingParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingRanges - missingOptions - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } + return unmarshalStruct(s, dec) +} - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"ranges"`: - missing &^= missingRanges - if dec.PeekKind() == 'n' { - return errNull("ranges") - } - if err := json.UnmarshalDecode(dec, &s.Ranges); err != nil { - return err - } - case `"options"`: - missing &^= missingOptions - if dec.PeekKind() == 'n' { - return errNull("options") - } - if err := json.UnmarshalDecode(dec, &s.Options); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingRanges != 0 { - missingProps = append(missingProps, "ranges") - } - if missing&missingOptions != 0 { - missingProps = append(missingProps, "options") - } - return errMissing(missingProps) - } - - return nil -} - -// The parameters of a DocumentOnTypeFormattingRequest. -type DocumentOnTypeFormattingParams struct { - // The document to format. - TextDocument TextDocumentIdentifier `json:"textDocument"` +// The parameters of a DocumentOnTypeFormattingRequest. +type DocumentOnTypeFormattingParams struct { + // The document to format. + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position around which the on type formatting should happen. // This is not necessarily the exact position where the character denoted // by the property `ch` got typed. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // The character that has been typed that triggered the formatting // on type request. That is not necessarily the last character that // got inserted into the document since the client could auto insert // characters as well (e.g. like automatic brace completion). - Ch string `json:"ch"` + Ch string `json:"ch" lsp:"required"` // The formatting options. - Options *FormattingOptions `json:"options"` + Options *FormattingOptions `json:"options" lsp:"required"` } func (s *DocumentOnTypeFormattingParams) TextDocumentURI() DocumentUri { @@ -11579,90 +3330,17 @@ func (s *DocumentOnTypeFormattingParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*DocumentOnTypeFormattingParams)(nil) func (s *DocumentOnTypeFormattingParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - missingCh - missingOptions - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"ch"`: - missing &^= missingCh - if err := json.UnmarshalDecode(dec, &s.Ch); err != nil { - return err - } - case `"options"`: - missing &^= missingOptions - if dec.PeekKind() == 'n' { - return errNull("options") - } - if err := json.UnmarshalDecode(dec, &s.Options); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - if missing&missingCh != 0 { - missingProps = append(missingProps, "ch") - } - if missing&missingOptions != 0 { - missingProps = append(missingProps, "options") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a DocumentOnTypeFormattingRequest. type DocumentOnTypeFormattingRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` // A character on which formatting should be triggered, like `{`. - FirstTriggerCharacter string `json:"firstTriggerCharacter"` + FirstTriggerCharacter string `json:"firstTriggerCharacter" lsp:"required"` // More trigger characters. MoreTriggerCharacter *[]string `json:"moreTriggerCharacter,omitzero"` @@ -11671,75 +3349,16 @@ type DocumentOnTypeFormattingRegistrationOptions struct { var _ json.UnmarshalerFrom = (*DocumentOnTypeFormattingRegistrationOptions)(nil) func (s *DocumentOnTypeFormattingRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - missingFirstTriggerCharacter - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"firstTriggerCharacter"`: - missing &^= missingFirstTriggerCharacter - if err := json.UnmarshalDecode(dec, &s.FirstTriggerCharacter); err != nil { - return err - } - case `"moreTriggerCharacter"`: - if dec.PeekKind() == 'n' { - return errNull("moreTriggerCharacter") - } - if err := json.UnmarshalDecode(dec, &s.MoreTriggerCharacter); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - if missing&missingFirstTriggerCharacter != 0 { - missingProps = append(missingProps, "firstTriggerCharacter") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters of a RenameRequest. type RenameParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -11747,7 +3366,7 @@ type RenameParams struct { // The new name of the symbol. If the given name is not valid the // request must return a ResponseError with an // appropriate message set. - NewName string `json:"newName"` + NewName string `json:"newName" lsp:"required"` } func (s *RenameParams) TextDocumentURI() DocumentUri { @@ -11761,82 +3380,14 @@ func (s *RenameParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*RenameParams)(nil) func (s *RenameParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - missingNewName - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"newName"`: - missing &^= missingNewName - if err := json.UnmarshalDecode(dec, &s.NewName); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - if missing&missingNewName != 0 { - missingProps = append(missingProps, "newName") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Registration options for a RenameRequest. type RenameRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -11849,72 +3400,15 @@ type RenameRegistrationOptions struct { var _ json.UnmarshalerFrom = (*RenameRegistrationOptions)(nil) func (s *RenameRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"prepareProvider"`: - if dec.PeekKind() == 'n' { - return errNull("prepareProvider") - } - if err := json.UnmarshalDecode(dec, &s.PrepareProvider); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type PrepareRenameParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // An optional token that a server can use to report work done progress. WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` @@ -11931,66 +3425,7 @@ func (s *PrepareRenameParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*PrepareRenameParams)(nil) func (s *PrepareRenameParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters of a ExecuteCommandRequest. @@ -11999,7 +3434,7 @@ type ExecuteCommandParams struct { WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` // The identifier of the actual command handler. - Command string `json:"command"` + Command string `json:"command" lsp:"required"` // Arguments that the command should be invoked with. Arguments *[]any `json:"arguments,omitzero"` @@ -12008,131 +3443,21 @@ type ExecuteCommandParams struct { var _ json.UnmarshalerFrom = (*ExecuteCommandParams)(nil) func (s *ExecuteCommandParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingCommand uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - case `"command"`: - missing &^= missingCommand - if err := json.UnmarshalDecode(dec, &s.Command); err != nil { - return err - } - case `"arguments"`: - if dec.PeekKind() == 'n' { - return errNull("arguments") - } - if err := json.UnmarshalDecode(dec, &s.Arguments); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingCommand != 0 { - missingProps = append(missingProps, "command") - } - return errMissing(missingProps) - } - - return nil -} + return unmarshalStruct(s, dec) +} // Registration options for a ExecuteCommandRequest. type ExecuteCommandRegistrationOptions struct { WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` // The commands to be executed on the server - Commands []string `json:"commands"` + Commands []string `json:"commands" lsp:"required"` } var _ json.UnmarshalerFrom = (*ExecuteCommandRegistrationOptions)(nil) func (s *ExecuteCommandRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingCommands uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"commands"`: - missing &^= missingCommands - if dec.PeekKind() == 'n' { - return errNull("commands") - } - if err := json.UnmarshalDecode(dec, &s.Commands); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingCommands != 0 { - missingProps = append(missingProps, "commands") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The parameters passed via an apply workspace edit request. @@ -12143,7 +3468,7 @@ type ApplyWorkspaceEditParams struct { Label *string `json:"label,omitzero"` // The edits to apply. - Edit *WorkspaceEdit `json:"edit"` + Edit *WorkspaceEdit `json:"edit" lsp:"required"` // Additional data about the edit. // @@ -12154,67 +3479,7 @@ type ApplyWorkspaceEditParams struct { var _ json.UnmarshalerFrom = (*ApplyWorkspaceEditParams)(nil) func (s *ApplyWorkspaceEditParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingEdit uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"label"`: - if dec.PeekKind() == 'n' { - return errNull("label") - } - if err := json.UnmarshalDecode(dec, &s.Label); err != nil { - return err - } - case `"edit"`: - missing &^= missingEdit - if dec.PeekKind() == 'n' { - return errNull("edit") - } - if err := json.UnmarshalDecode(dec, &s.Edit); err != nil { - return err - } - case `"metadata"`: - if dec.PeekKind() == 'n' { - return errNull("metadata") - } - if err := json.UnmarshalDecode(dec, &s.Metadata); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingEdit != 0 { - missingProps = append(missingProps, "edit") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The result returned from the apply workspace edit request. @@ -12222,7 +3487,7 @@ func (s *ApplyWorkspaceEditParams) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.17 renamed from ApplyWorkspaceEditResponse type ApplyWorkspaceEditResult struct { // Indicates whether the edit was applied or not. - Applied bool `json:"applied"` + Applied bool `json:"applied" lsp:"required"` // An optional textual description for why the edit was not applied. // This may be used by the server for diagnostic logging or to provide @@ -12238,74 +3503,17 @@ type ApplyWorkspaceEditResult struct { var _ json.UnmarshalerFrom = (*ApplyWorkspaceEditResult)(nil) func (s *ApplyWorkspaceEditResult) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingApplied uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"applied"`: - missing &^= missingApplied - if err := json.UnmarshalDecode(dec, &s.Applied); err != nil { - return err - } - case `"failureReason"`: - if dec.PeekKind() == 'n' { - return errNull("failureReason") - } - if err := json.UnmarshalDecode(dec, &s.FailureReason); err != nil { - return err - } - case `"failedChange"`: - if dec.PeekKind() == 'n' { - return errNull("failedChange") - } - if err := json.UnmarshalDecode(dec, &s.FailedChange); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingApplied != 0 { - missingProps = append(missingProps, "applied") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type WorkDoneProgressBegin struct { - Kind StringLiteralBegin `json:"kind"` + Kind StringLiteralBegin `json:"kind" lsp:"required"` // Mandatory title of the progress operation. Used to briefly inform about // the kind of operation being performed. // // Examples: "Indexing" or "Linking dependencies". - Title string `json:"title"` + Title string `json:"title" lsp:"required"` // Controls if a cancel button should show to allow the user to cancel the // long running operation. Clients that don't support cancellation are allowed @@ -12331,84 +3539,11 @@ type WorkDoneProgressBegin struct { var _ json.UnmarshalerFrom = (*WorkDoneProgressBegin)(nil) func (s *WorkDoneProgressBegin) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - missingTitle - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"title"`: - missing &^= missingTitle - if err := json.UnmarshalDecode(dec, &s.Title); err != nil { - return err - } - case `"cancellable"`: - if dec.PeekKind() == 'n' { - return errNull("cancellable") - } - if err := json.UnmarshalDecode(dec, &s.Cancellable); err != nil { - return err - } - case `"message"`: - if dec.PeekKind() == 'n' { - return errNull("message") - } - if err := json.UnmarshalDecode(dec, &s.Message); err != nil { - return err - } - case `"percentage"`: - if dec.PeekKind() == 'n' { - return errNull("percentage") - } - if err := json.UnmarshalDecode(dec, &s.Percentage); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingTitle != 0 { - missingProps = append(missingProps, "title") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type WorkDoneProgressReport struct { - Kind StringLiteralReport `json:"kind"` + Kind StringLiteralReport `json:"kind" lsp:"required"` // Controls enablement state of a cancel button. // @@ -12435,192 +3570,35 @@ type WorkDoneProgressReport struct { var _ json.UnmarshalerFrom = (*WorkDoneProgressReport)(nil) func (s *WorkDoneProgressReport) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } +type WorkDoneProgressEnd struct { + Kind StringLiteralEnd `json:"kind" lsp:"required"` - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"cancellable"`: - if dec.PeekKind() == 'n' { - return errNull("cancellable") - } - if err := json.UnmarshalDecode(dec, &s.Cancellable); err != nil { - return err - } - case `"message"`: - if dec.PeekKind() == 'n' { - return errNull("message") - } - if err := json.UnmarshalDecode(dec, &s.Message); err != nil { - return err - } - case `"percentage"`: - if dec.PeekKind() == 'n' { - return errNull("percentage") - } - if err := json.UnmarshalDecode(dec, &s.Percentage); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - return errMissing(missingProps) - } - - return nil -} - -type WorkDoneProgressEnd struct { - Kind StringLiteralEnd `json:"kind"` - - // Optional, a final message indicating to for example indicate the outcome - // of the operation. - Message *string `json:"message,omitzero"` -} + // Optional, a final message indicating to for example indicate the outcome + // of the operation. + Message *string `json:"message,omitzero"` +} var _ json.UnmarshalerFrom = (*WorkDoneProgressEnd)(nil) func (s *WorkDoneProgressEnd) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"message"`: - if dec.PeekKind() == 'n' { - return errNull("message") - } - if err := json.UnmarshalDecode(dec, &s.Message); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type SetTraceParams struct { - Value TraceValue `json:"value"` + Value TraceValue `json:"value" lsp:"required"` } var _ json.UnmarshalerFrom = (*SetTraceParams)(nil) func (s *SetTraceParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingValue uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"value"`: - missing &^= missingValue - if err := json.UnmarshalDecode(dec, &s.Value); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingValue != 0 { - missingProps = append(missingProps, "value") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type LogTraceParams struct { - Message string `json:"message"` + Message string `json:"message" lsp:"required"` Verbose *string `json:"verbose,omitzero"` } @@ -12628,187 +3606,42 @@ type LogTraceParams struct { var _ json.UnmarshalerFrom = (*LogTraceParams)(nil) func (s *LogTraceParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingMessage uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"message"`: - missing &^= missingMessage - if err := json.UnmarshalDecode(dec, &s.Message); err != nil { - return err - } - case `"verbose"`: - if dec.PeekKind() == 'n' { - return errNull("verbose") - } - if err := json.UnmarshalDecode(dec, &s.Verbose); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingMessage != 0 { - missingProps = append(missingProps, "message") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type CancelParams struct { // The request id to cancel. - Id IntegerOrString `json:"id"` + Id IntegerOrString `json:"id" lsp:"required"` } var _ json.UnmarshalerFrom = (*CancelParams)(nil) func (s *CancelParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingId uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"id"`: - missing &^= missingId - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingId != 0 { - missingProps = append(missingProps, "id") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type ProgressParams struct { // The progress token provided by the client or server. - Token IntegerOrString `json:"token"` + Token IntegerOrString `json:"token" lsp:"required"` // The progress data. - Value WorkDoneProgressBeginOrReportOrEnd `json:"value"` + Value WorkDoneProgressBeginOrReportOrEnd `json:"value" lsp:"required"` } var _ json.UnmarshalerFrom = (*ProgressParams)(nil) func (s *ProgressParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingToken uint = 1 << iota - missingValue - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"token"`: - missing &^= missingToken - if err := json.UnmarshalDecode(dec, &s.Token); err != nil { - return err - } - case `"value"`: - missing &^= missingValue - if err := json.UnmarshalDecode(dec, &s.Value); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingToken != 0 { - missingProps = append(missingProps, "token") - } - if missing&missingValue != 0 { - missingProps = append(missingProps, "value") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A parameter literal used in requests to pass a text document and a position inside that // document. type TextDocumentPositionParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` } func (s *TextDocumentPositionParams) TextDocumentURI() DocumentUri { @@ -12822,101 +3655,18 @@ func (s *TextDocumentPositionParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*TextDocumentPositionParams)(nil) func (s *TextDocumentPositionParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } +type WorkDoneProgressParams struct { + // An optional token that a server can use to report work done progress. + WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` +} - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - return errMissing(missingProps) - } - - return nil -} - -type WorkDoneProgressParams struct { - // An optional token that a server can use to report work done progress. - WorkDoneToken *IntegerOrString `json:"workDoneToken,omitzero"` -} - -var _ json.UnmarshalerFrom = (*WorkDoneProgressParams)(nil) +var _ json.UnmarshalerFrom = (*WorkDoneProgressParams)(nil) func (s *WorkDoneProgressParams) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneToken"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneToken") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneToken); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } type PartialResultParams struct { @@ -12928,38 +3678,7 @@ type PartialResultParams struct { var _ json.UnmarshalerFrom = (*PartialResultParams)(nil) func (s *PartialResultParams) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"partialResultToken"`: - if dec.PeekKind() == 'n' { - return errNull("partialResultToken") - } - if err := json.UnmarshalDecode(dec, &s.PartialResultToken); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Represents the connection of two locations. Provides additional metadata over normal locations, @@ -12972,16 +3691,16 @@ type LocationLink struct { OriginSelectionRange *Range `json:"originSelectionRange,omitzero"` // The target resource identifier of this link. - TargetUri DocumentUri `json:"targetUri"` + TargetUri DocumentUri `json:"targetUri" lsp:"required"` // The full target range of this link. If the target for example is a symbol then target range is the // range enclosing this symbol not including leading/trailing whitespace but everything else // like comments. This information is typically used to highlight the range in the editor. - TargetRange Range `json:"targetRange"` + TargetRange Range `json:"targetRange" lsp:"required"` // The range that should be selected and revealed when this link is being followed, e.g the name of a function. // Must be contained by the `targetRange`. See also `DocumentSymbol#range` - TargetSelectionRange Range `json:"targetSelectionRange"` + TargetSelectionRange Range `json:"targetSelectionRange" lsp:"required"` } func (s LocationLink) GetLocation() Location { @@ -12994,75 +3713,7 @@ func (s LocationLink) GetLocation() Location { var _ json.UnmarshalerFrom = (*LocationLink)(nil) func (s *LocationLink) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTargetUri uint = 1 << iota - missingTargetRange - missingTargetSelectionRange - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"originSelectionRange"`: - if dec.PeekKind() == 'n' { - return errNull("originSelectionRange") - } - if err := json.UnmarshalDecode(dec, &s.OriginSelectionRange); err != nil { - return err - } - case `"targetUri"`: - missing &^= missingTargetUri - if err := json.UnmarshalDecode(dec, &s.TargetUri); err != nil { - return err - } - case `"targetRange"`: - missing &^= missingTargetRange - if err := json.UnmarshalDecode(dec, &s.TargetRange); err != nil { - return err - } - case `"targetSelectionRange"`: - missing &^= missingTargetSelectionRange - if err := json.UnmarshalDecode(dec, &s.TargetSelectionRange); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTargetUri != 0 { - missingProps = append(missingProps, "targetUri") - } - if missing&missingTargetRange != 0 { - missingProps = append(missingProps, "targetRange") - } - if missing&missingTargetSelectionRange != 0 { - missingProps = append(missingProps, "targetSelectionRange") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A range in a text document expressed as (zero-based) start and end positions. @@ -13080,68 +3731,16 @@ func (s *LocationLink) UnmarshalJSONFrom(dec *json.Decoder) error { // ``` type Range struct { // The range's start position. - Start Position `json:"start"` + Start Position `json:"start" lsp:"required"` // The range's end position. - End Position `json:"end"` + End Position `json:"end" lsp:"required"` } var _ json.UnmarshalerFrom = (*Range)(nil) func (s *Range) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingStart uint = 1 << iota - missingEnd - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"start"`: - missing &^= missingStart - if err := json.UnmarshalDecode(dec, &s.Start); err != nil { - return err - } - case `"end"`: - missing &^= missingEnd - if err := json.UnmarshalDecode(dec, &s.End); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingStart != 0 { - missingProps = append(missingProps, "start") - } - if missing&missingEnd != 0 { - missingProps = append(missingProps, "end") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } func (s *Range) Compare(other *Range) int { @@ -13158,38 +3757,7 @@ type ImplementationOptions struct { var _ json.UnmarshalerFrom = (*ImplementationOptions)(nil) func (s *ImplementationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Static registration options to be returned in the initialize @@ -13203,38 +3771,7 @@ type StaticRegistrationOptions struct { var _ json.UnmarshalerFrom = (*StaticRegistrationOptions)(nil) func (s *StaticRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"id"`: - if dec.PeekKind() == 'n' { - return errNull("id") - } - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } type TypeDefinitionOptions struct { @@ -13244,112 +3781,23 @@ type TypeDefinitionOptions struct { var _ json.UnmarshalerFrom = (*TypeDefinitionOptions)(nil) func (s *TypeDefinitionOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // The workspace folder change event. type WorkspaceFoldersChangeEvent struct { // The array of added workspace folders - Added []*WorkspaceFolder `json:"added"` + Added []*WorkspaceFolder `json:"added" lsp:"required"` // The array of the removed workspace folders - Removed []*WorkspaceFolder `json:"removed"` + Removed []*WorkspaceFolder `json:"removed" lsp:"required"` } var _ json.UnmarshalerFrom = (*WorkspaceFoldersChangeEvent)(nil) func (s *WorkspaceFoldersChangeEvent) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingAdded uint = 1 << iota - missingRemoved - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"added"`: - missing &^= missingAdded - if dec.PeekKind() == 'n' { - return errNull("added") - } - if err := json.UnmarshalDecode(dec, &s.Added); err != nil { - return err - } - case `"removed"`: - missing &^= missingRemoved - if dec.PeekKind() == 'n' { - return errNull("removed") - } - if err := json.UnmarshalDecode(dec, &s.Removed); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingAdded != 0 { - missingProps = append(missingProps, "added") - } - if missing&missingRemoved != 0 { - missingProps = append(missingProps, "removed") - } - return errMissing(missingProps) - } - - return nil -} + return unmarshalStruct(s, dec) +} type ConfigurationItem struct { // The scope to get the configuration section for. @@ -13362,191 +3810,40 @@ type ConfigurationItem struct { var _ json.UnmarshalerFrom = (*ConfigurationItem)(nil) func (s *ConfigurationItem) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"scopeUri"`: - if dec.PeekKind() == 'n' { - return errNull("scopeUri") - } - if err := json.UnmarshalDecode(dec, &s.ScopeUri); err != nil { - return err - } - case `"section"`: - if dec.PeekKind() == 'n' { - return errNull("section") - } - if err := json.UnmarshalDecode(dec, &s.Section); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // A literal to identify a text document in the client. type TextDocumentIdentifier struct { // The text document's uri. - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` } var _ json.UnmarshalerFrom = (*TextDocumentIdentifier)(nil) func (s *TextDocumentIdentifier) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Represents a color in RGBA space. type Color struct { // The red component of this color in the range [0-1]. - Red float64 `json:"red"` + Red float64 `json:"red" lsp:"required"` // The green component of this color in the range [0-1]. - Green float64 `json:"green"` + Green float64 `json:"green" lsp:"required"` // The blue component of this color in the range [0-1]. - Blue float64 `json:"blue"` + Blue float64 `json:"blue" lsp:"required"` // The alpha component of this color in the range [0-1]. - Alpha float64 `json:"alpha"` + Alpha float64 `json:"alpha" lsp:"required"` } var _ json.UnmarshalerFrom = (*Color)(nil) func (s *Color) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRed uint = 1 << iota - missingGreen - missingBlue - missingAlpha - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"red"`: - missing &^= missingRed - if err := json.UnmarshalDecode(dec, &s.Red); err != nil { - return err - } - case `"green"`: - missing &^= missingGreen - if err := json.UnmarshalDecode(dec, &s.Green); err != nil { - return err - } - case `"blue"`: - missing &^= missingBlue - if err := json.UnmarshalDecode(dec, &s.Blue); err != nil { - return err - } - case `"alpha"`: - missing &^= missingAlpha - if err := json.UnmarshalDecode(dec, &s.Alpha); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRed != 0 { - missingProps = append(missingProps, "red") - } - if missing&missingGreen != 0 { - missingProps = append(missingProps, "green") - } - if missing&missingBlue != 0 { - missingProps = append(missingProps, "blue") - } - if missing&missingAlpha != 0 { - missingProps = append(missingProps, "alpha") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type DocumentColorOptions struct { @@ -13556,38 +3853,7 @@ type DocumentColorOptions struct { var _ json.UnmarshalerFrom = (*DocumentColorOptions)(nil) func (s *DocumentColorOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } type FoldingRangeOptions struct { @@ -13597,38 +3863,7 @@ type FoldingRangeOptions struct { var _ json.UnmarshalerFrom = (*FoldingRangeOptions)(nil) func (s *FoldingRangeOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } type DeclarationOptions struct { @@ -13638,38 +3873,7 @@ type DeclarationOptions struct { var _ json.UnmarshalerFrom = (*DeclarationOptions)(nil) func (s *DeclarationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Position in a text document expressed as zero-based line and character @@ -13701,79 +3905,27 @@ func (s *DeclarationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.17.0 - support for negotiated position encoding. type Position struct { // Line position in a document (zero-based). - Line uint32 `json:"line"` + Line uint32 `json:"line" lsp:"required"` // Character offset on a line in a document (zero-based). // // The meaning of this offset is determined by the negotiated // `PositionEncodingKind`. - Character uint32 `json:"character"` + Character uint32 `json:"character" lsp:"required"` } var _ json.UnmarshalerFrom = (*Position)(nil) func (s *Position) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingLine uint = 1 << iota - missingCharacter - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err +func (s *Position) Compare(other *Position) int { + if c := cmp.Compare(s.Line, other.Line); c != 0 { + return c } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"line"`: - missing &^= missingLine - if err := json.UnmarshalDecode(dec, &s.Line); err != nil { - return err - } - case `"character"`: - missing &^= missingCharacter - if err := json.UnmarshalDecode(dec, &s.Character); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingLine != 0 { - missingProps = append(missingProps, "line") - } - if missing&missingCharacter != 0 { - missingProps = append(missingProps, "character") - } - return errMissing(missingProps) - } - - return nil -} - -func (s *Position) Compare(other *Position) int { - if c := cmp.Compare(s.Line, other.Line); c != 0 { - return c - } - return cmp.Compare(s.Character, other.Character) -} + return cmp.Compare(s.Character, other.Character) +} type SelectionRangeOptions struct { WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` @@ -13782,38 +3934,7 @@ type SelectionRangeOptions struct { var _ json.UnmarshalerFrom = (*SelectionRangeOptions)(nil) func (s *SelectionRangeOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Call hierarchy options used during static registration. @@ -13826,38 +3947,7 @@ type CallHierarchyOptions struct { var _ json.UnmarshalerFrom = (*CallHierarchyOptions)(nil) func (s *CallHierarchyOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.16.0 @@ -13865,7 +3955,7 @@ type SemanticTokensOptions struct { WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` // The legend used by the server - Legend *SemanticTokensLegend `json:"legend"` + Legend *SemanticTokensLegend `json:"legend" lsp:"required"` // Server supports providing semantic tokens for a specific range // of a document. @@ -13878,83 +3968,16 @@ type SemanticTokensOptions struct { var _ json.UnmarshalerFrom = (*SemanticTokensOptions)(nil) func (s *SemanticTokensOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingLegend uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"legend"`: - missing &^= missingLegend - if dec.PeekKind() == 'n' { - return errNull("legend") - } - if err := json.UnmarshalDecode(dec, &s.Legend); err != nil { - return err - } - case `"range"`: - if dec.PeekKind() == 'n' { - return errNull("range") - } - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"full"`: - if dec.PeekKind() == 'n' { - return errNull("full") - } - if err := json.UnmarshalDecode(dec, &s.Full); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingLegend != 0 { - missingProps = append(missingProps, "legend") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.16.0 type SemanticTokensEdit struct { // The start offset of the edit. - Start uint32 `json:"start"` + Start uint32 `json:"start" lsp:"required"` // The count of elements to remove. - DeleteCount uint32 `json:"deleteCount"` + DeleteCount uint32 `json:"deleteCount" lsp:"required"` // The elements to insert. Data *[]uint32 `json:"data,omitzero"` @@ -13963,66 +3986,7 @@ type SemanticTokensEdit struct { var _ json.UnmarshalerFrom = (*SemanticTokensEdit)(nil) func (s *SemanticTokensEdit) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingStart uint = 1 << iota - missingDeleteCount - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"start"`: - missing &^= missingStart - if err := json.UnmarshalDecode(dec, &s.Start); err != nil { - return err - } - case `"deleteCount"`: - missing &^= missingDeleteCount - if err := json.UnmarshalDecode(dec, &s.DeleteCount); err != nil { - return err - } - case `"data"`: - if dec.PeekKind() == 'n' { - return errNull("data") - } - if err := json.UnmarshalDecode(dec, &s.Data); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingStart != 0 { - missingProps = append(missingProps, "start") - } - if missing&missingDeleteCount != 0 { - missingProps = append(missingProps, "deleteCount") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type LinkedEditingRangeOptions struct { @@ -14032,38 +3996,7 @@ type LinkedEditingRangeOptions struct { var _ json.UnmarshalerFrom = (*LinkedEditingRangeOptions)(nil) func (s *LinkedEditingRangeOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Represents information on a file/folder create. @@ -14071,56 +4004,13 @@ func (s *LinkedEditingRangeOptions) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.16.0 type FileCreate struct { // A file:// URI for the location of the file/folder being created. - Uri string `json:"uri"` + Uri string `json:"uri" lsp:"required"` } var _ json.UnmarshalerFrom = (*FileCreate)(nil) func (s *FileCreate) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Describes textual changes on a text document. A TextDocumentEdit describes all changes @@ -14129,7 +4019,7 @@ func (s *FileCreate) UnmarshalJSONFrom(dec *json.Decoder) error { // kind of ordering. However the edits must be non overlapping. type TextDocumentEdit struct { // The text document to change. - TextDocument OptionalVersionedTextDocumentIdentifier `json:"textDocument"` + TextDocument OptionalVersionedTextDocumentIdentifier `json:"textDocument" lsp:"required"` // The edits to be applied. // @@ -14138,74 +4028,19 @@ type TextDocumentEdit struct { // // Since: 3.18.0 - support for SnippetTextEdit. This is guarded using a // client capability. - Edits []TextEditOrAnnotatedTextEditOrSnippetTextEdit `json:"edits"` + Edits []TextEditOrAnnotatedTextEditOrSnippetTextEdit `json:"edits" lsp:"required"` } var _ json.UnmarshalerFrom = (*TextDocumentEdit)(nil) func (s *TextDocumentEdit) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingEdits - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"edits"`: - missing &^= missingEdits - if dec.PeekKind() == 'n' { - return errNull("edits") - } - if err := json.UnmarshalDecode(dec, &s.Edits); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingEdits != 0 { - missingProps = append(missingProps, "edits") - } - return errMissing(missingProps) - } - - return nil -} + return unmarshalStruct(s, dec) +} // Create file operation. type CreateFile struct { // A create - Kind StringLiteralCreate `json:"kind"` + Kind StringLiteralCreate `json:"kind" lsp:"required"` // An optional annotation identifier describing the operation. // @@ -14213,7 +4048,7 @@ type CreateFile struct { AnnotationId *string `json:"annotationId,omitzero"` // The resource to create. - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` // Additional options Options *CreateFileOptions `json:"options,omitzero"` @@ -14222,79 +4057,13 @@ type CreateFile struct { var _ json.UnmarshalerFrom = (*CreateFile)(nil) func (s *CreateFile) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - missingUri - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"annotationId"`: - if dec.PeekKind() == 'n' { - return errNull("annotationId") - } - if err := json.UnmarshalDecode(dec, &s.AnnotationId); err != nil { - return err - } - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"options"`: - if dec.PeekKind() == 'n' { - return errNull("options") - } - if err := json.UnmarshalDecode(dec, &s.Options); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Rename file operation type RenameFile struct { // A rename - Kind StringLiteralRename `json:"kind"` + Kind StringLiteralRename `json:"kind" lsp:"required"` // An optional annotation identifier describing the operation. // @@ -14302,10 +4071,10 @@ type RenameFile struct { AnnotationId *string `json:"annotationId,omitzero"` // The old (existing) location. - OldUri DocumentUri `json:"oldUri"` + OldUri DocumentUri `json:"oldUri" lsp:"required"` // The new location. - NewUri DocumentUri `json:"newUri"` + NewUri DocumentUri `json:"newUri" lsp:"required"` // Rename options. Options *RenameFileOptions `json:"options,omitzero"` @@ -14314,88 +4083,13 @@ type RenameFile struct { var _ json.UnmarshalerFrom = (*RenameFile)(nil) func (s *RenameFile) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - missingOldUri - missingNewUri - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"annotationId"`: - if dec.PeekKind() == 'n' { - return errNull("annotationId") - } - if err := json.UnmarshalDecode(dec, &s.AnnotationId); err != nil { - return err - } - case `"oldUri"`: - missing &^= missingOldUri - if err := json.UnmarshalDecode(dec, &s.OldUri); err != nil { - return err - } - case `"newUri"`: - missing &^= missingNewUri - if err := json.UnmarshalDecode(dec, &s.NewUri); err != nil { - return err - } - case `"options"`: - if dec.PeekKind() == 'n' { - return errNull("options") - } - if err := json.UnmarshalDecode(dec, &s.Options); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingOldUri != 0 { - missingProps = append(missingProps, "oldUri") - } - if missing&missingNewUri != 0 { - missingProps = append(missingProps, "newUri") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Delete file operation type DeleteFile struct { // A delete - Kind StringLiteralDelete `json:"kind"` + Kind StringLiteralDelete `json:"kind" lsp:"required"` // An optional annotation identifier describing the operation. // @@ -14403,7 +4097,7 @@ type DeleteFile struct { AnnotationId *string `json:"annotationId,omitzero"` // The file to delete. - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` // Delete options. Options *DeleteFileOptions `json:"options,omitzero"` @@ -14412,73 +4106,7 @@ type DeleteFile struct { var _ json.UnmarshalerFrom = (*DeleteFile)(nil) func (s *DeleteFile) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - missingUri - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"annotationId"`: - if dec.PeekKind() == 'n' { - return errNull("annotationId") - } - if err := json.UnmarshalDecode(dec, &s.AnnotationId); err != nil { - return err - } - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"options"`: - if dec.PeekKind() == 'n' { - return errNull("options") - } - if err := json.UnmarshalDecode(dec, &s.Options); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Additional information that describes document changes. @@ -14487,7 +4115,7 @@ func (s *DeleteFile) UnmarshalJSONFrom(dec *json.Decoder) error { type ChangeAnnotation struct { // A human-readable string describing the actual change. The string // is rendered prominent in the user interface. - Label string `json:"label"` + Label string `json:"label" lsp:"required"` // A flag which indicates that user confirmation is needed // before applying the change. @@ -14501,64 +4129,7 @@ type ChangeAnnotation struct { var _ json.UnmarshalerFrom = (*ChangeAnnotation)(nil) func (s *ChangeAnnotation) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingLabel uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"label"`: - missing &^= missingLabel - if err := json.UnmarshalDecode(dec, &s.Label); err != nil { - return err - } - case `"needsConfirmation"`: - if dec.PeekKind() == 'n' { - return errNull("needsConfirmation") - } - if err := json.UnmarshalDecode(dec, &s.NeedsConfirmation); err != nil { - return err - } - case `"description"`: - if dec.PeekKind() == 'n' { - return errNull("description") - } - if err := json.UnmarshalDecode(dec, &s.Description); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingLabel != 0 { - missingProps = append(missingProps, "label") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A filter to describe in which file operation requests or notifications @@ -14570,135 +4141,30 @@ type FileOperationFilter struct { Scheme *string `json:"scheme,omitzero"` // The actual file operation pattern. - Pattern *FileOperationPattern `json:"pattern"` + Pattern *FileOperationPattern `json:"pattern" lsp:"required"` } var _ json.UnmarshalerFrom = (*FileOperationFilter)(nil) func (s *FileOperationFilter) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingPattern uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"scheme"`: - if dec.PeekKind() == 'n' { - return errNull("scheme") - } - if err := json.UnmarshalDecode(dec, &s.Scheme); err != nil { - return err - } - case `"pattern"`: - missing &^= missingPattern - if dec.PeekKind() == 'n' { - return errNull("pattern") - } - if err := json.UnmarshalDecode(dec, &s.Pattern); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingPattern != 0 { - missingProps = append(missingProps, "pattern") - } - return errMissing(missingProps) - } - - return nil -} - -// Represents information on a file/folder rename. -// -// Since: 3.16.0 -type FileRename struct { - // A file:// URI for the original location of the file/folder being renamed. - OldUri string `json:"oldUri"` +// Represents information on a file/folder rename. +// +// Since: 3.16.0 +type FileRename struct { + // A file:// URI for the original location of the file/folder being renamed. + OldUri string `json:"oldUri" lsp:"required"` // A file:// URI for the new location of the file/folder being renamed. - NewUri string `json:"newUri"` + NewUri string `json:"newUri" lsp:"required"` } var _ json.UnmarshalerFrom = (*FileRename)(nil) func (s *FileRename) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingOldUri uint = 1 << iota - missingNewUri - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"oldUri"`: - missing &^= missingOldUri - if err := json.UnmarshalDecode(dec, &s.OldUri); err != nil { - return err - } - case `"newUri"`: - missing &^= missingNewUri - if err := json.UnmarshalDecode(dec, &s.NewUri); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingOldUri != 0 { - missingProps = append(missingProps, "oldUri") - } - if missing&missingNewUri != 0 { - missingProps = append(missingProps, "newUri") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Represents information on a file/folder delete. @@ -14706,56 +4172,13 @@ func (s *FileRename) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.16.0 type FileDelete struct { // A file:// URI for the location of the file/folder being deleted. - Uri string `json:"uri"` + Uri string `json:"uri" lsp:"required"` } var _ json.UnmarshalerFrom = (*FileDelete)(nil) func (s *FileDelete) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type MonikerOptions struct { @@ -14765,38 +4188,7 @@ type MonikerOptions struct { var _ json.UnmarshalerFrom = (*MonikerOptions)(nil) func (s *MonikerOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Type hierarchy options used during static registration. @@ -14809,106 +4201,23 @@ type TypeHierarchyOptions struct { var _ json.UnmarshalerFrom = (*TypeHierarchyOptions)(nil) func (s *TypeHierarchyOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.17.0 type InlineValueContext struct { // The stack frame (as a DAP Id) where the execution has stopped. - FrameId int32 `json:"frameId"` + FrameId int32 `json:"frameId" lsp:"required"` // The document range where execution has stopped. // Typically the end position of the range denotes the line where the inline values are shown. - StoppedLocation Range `json:"stoppedLocation"` + StoppedLocation Range `json:"stoppedLocation" lsp:"required"` } var _ json.UnmarshalerFrom = (*InlineValueContext)(nil) func (s *InlineValueContext) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingFrameId uint = 1 << iota - missingStoppedLocation - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"frameId"`: - missing &^= missingFrameId - if err := json.UnmarshalDecode(dec, &s.FrameId); err != nil { - return err - } - case `"stoppedLocation"`: - missing &^= missingStoppedLocation - if err := json.UnmarshalDecode(dec, &s.StoppedLocation); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingFrameId != 0 { - missingProps = append(missingProps, "frameId") - } - if missing&missingStoppedLocation != 0 { - missingProps = append(missingProps, "stoppedLocation") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Returns inline value information as the complete text to be shown. @@ -14916,68 +4225,16 @@ func (s *InlineValueContext) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.17.0 type InlineValueText struct { // The document range for which the inline value applies. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The text of the inline value. - Text string `json:"text"` + Text string `json:"text" lsp:"required"` } var _ json.UnmarshalerFrom = (*InlineValueText)(nil) func (s *InlineValueText) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - missingText - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"text"`: - missing &^= missingText - if err := json.UnmarshalDecode(dec, &s.Text); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingText != 0 { - missingProps = append(missingProps, "text") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // To compute inline value through a variable lookup. @@ -14994,79 +4251,20 @@ type InlineValueVariableLookup struct { // // The range could be used to extract the variable name // from the underlying document. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // If specified the name of the variable to look up. VariableName *string `json:"variableName,omitzero"` // How to perform the lookup. - CaseSensitiveLookup bool `json:"caseSensitiveLookup"` + CaseSensitiveLookup bool `json:"caseSensitiveLookup" lsp:"required"` } var _ json.UnmarshalerFrom = (*InlineValueVariableLookup)(nil) func (s *InlineValueVariableLookup) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - missingCaseSensitiveLookup - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"variableName"`: - if dec.PeekKind() == 'n' { - return errNull("variableName") - } - if err := json.UnmarshalDecode(dec, &s.VariableName); err != nil { - return err - } - case `"caseSensitiveLookup"`: - missing &^= missingCaseSensitiveLookup - if err := json.UnmarshalDecode(dec, &s.CaseSensitiveLookup); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingCaseSensitiveLookup != 0 { - missingProps = append(missingProps, "caseSensitiveLookup") - } - return errMissing(missingProps) - } - - return nil -} + return unmarshalStruct(s, dec) +} // To compute an inline value through an expression evaluation. // @@ -15082,7 +4280,7 @@ type InlineValueEvaluatableExpression struct { // // The range could be used to extract the evaluatable expression // from the underlying document. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // If specified the expression could be evaluated instead. Expression *string `json:"expression,omitzero"` @@ -15091,57 +4289,7 @@ type InlineValueEvaluatableExpression struct { var _ json.UnmarshalerFrom = (*InlineValueEvaluatableExpression)(nil) func (s *InlineValueEvaluatableExpression) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"expression"`: - if dec.PeekKind() == 'n' { - return errNull("expression") - } - if err := json.UnmarshalDecode(dec, &s.Expression); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Inline value options used during static registration. @@ -15154,38 +4302,7 @@ type InlineValueOptions struct { var _ json.UnmarshalerFrom = (*InlineValueOptions)(nil) func (s *InlineValueOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // An inlay hint label part allows for interactive and composite labels @@ -15194,7 +4311,7 @@ func (s *InlineValueOptions) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.17.0 type InlayHintLabelPart struct { // The value of this label part. - Value string `json:"value"` + Value string `json:"value" lsp:"required"` // The tooltip text when you hover over this label part. Depending on // the client capability `inlayHint.resolveSupport` clients might resolve @@ -15224,71 +4341,7 @@ type InlayHintLabelPart struct { var _ json.UnmarshalerFrom = (*InlayHintLabelPart)(nil) func (s *InlayHintLabelPart) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingValue uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"value"`: - missing &^= missingValue - if err := json.UnmarshalDecode(dec, &s.Value); err != nil { - return err - } - case `"tooltip"`: - if dec.PeekKind() == 'n' { - return errNull("tooltip") - } - if err := json.UnmarshalDecode(dec, &s.Tooltip); err != nil { - return err - } - case `"location"`: - if dec.PeekKind() == 'n' { - return errNull("location") - } - if err := json.UnmarshalDecode(dec, &s.Location); err != nil { - return err - } - case `"command"`: - if dec.PeekKind() == 'n' { - return errNull("command") - } - if err := json.UnmarshalDecode(dec, &s.Command); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingValue != 0 { - missingProps = append(missingProps, "value") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A `MarkupContent` literal represents a string value which content is interpreted base on its @@ -15317,68 +4370,16 @@ func (s *InlayHintLabelPart) UnmarshalJSONFrom(dec *json.Decoder) error { // remove HTML from the markdown to avoid script execution. type MarkupContent struct { // The type of the Markup - Kind MarkupKind `json:"kind"` + Kind MarkupKind `json:"kind" lsp:"required"` // The content itself - Value string `json:"value"` + Value string `json:"value" lsp:"required"` } var _ json.UnmarshalerFrom = (*MarkupContent)(nil) func (s *MarkupContent) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - missingValue - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"value"`: - missing &^= missingValue - if err := json.UnmarshalDecode(dec, &s.Value); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingValue != 0 { - missingProps = append(missingProps, "value") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Inlay hint options used during static registration. @@ -15395,45 +4396,7 @@ type InlayHintOptions struct { var _ json.UnmarshalerFrom = (*InlayHintOptions)(nil) func (s *InlayHintOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"resolveProvider"`: - if dec.PeekKind() == 'n' { - return errNull("resolveProvider") - } - if err := json.UnmarshalDecode(dec, &s.ResolveProvider); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // A full diagnostic report with a set of related documents. @@ -15441,7 +4404,7 @@ func (s *InlayHintOptions) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.17.0 type RelatedFullDocumentDiagnosticReport struct { // A full document diagnostic report. - Kind StringLiteralFull `json:"kind"` + Kind StringLiteralFull `json:"kind" lsp:"required"` // An optional result id. If provided it will // be sent on the next diagnostic request for the @@ -15449,7 +4412,7 @@ type RelatedFullDocumentDiagnosticReport struct { ResultId *string `json:"resultId,omitzero"` // The actual items. - Items []*Diagnostic `json:"items"` + Items []*Diagnostic `json:"items" lsp:"required"` // Diagnostics of related documents. This information is useful // in programming languages where code in a file A can generate @@ -15464,91 +4427,22 @@ type RelatedFullDocumentDiagnosticReport struct { var _ json.UnmarshalerFrom = (*RelatedFullDocumentDiagnosticReport)(nil) func (s *RelatedFullDocumentDiagnosticReport) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - missingItems - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"resultId"`: - if dec.PeekKind() == 'n' { - return errNull("resultId") - } - if err := json.UnmarshalDecode(dec, &s.ResultId); err != nil { - return err - } - case `"items"`: - missing &^= missingItems - if dec.PeekKind() == 'n' { - return errNull("items") - } - if err := json.UnmarshalDecode(dec, &s.Items); err != nil { - return err - } - case `"relatedDocuments"`: - if dec.PeekKind() == 'n' { - return errNull("relatedDocuments") - } - if err := json.UnmarshalDecode(dec, &s.RelatedDocuments); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingItems != 0 { - missingProps = append(missingProps, "items") - } - return errMissing(missingProps) - } - - return nil -} - -// An unchanged diagnostic report with a set of related documents. -// -// Since: 3.17.0 -type RelatedUnchangedDocumentDiagnosticReport struct { - // A document diagnostic report indicating - // no changes to the last result. A server can - // only return `unchanged` if result ids are - // provided. - Kind StringLiteralUnchanged `json:"kind"` +// An unchanged diagnostic report with a set of related documents. +// +// Since: 3.17.0 +type RelatedUnchangedDocumentDiagnosticReport struct { + // A document diagnostic report indicating + // no changes to the last result. A server can + // only return `unchanged` if result ids are + // provided. + Kind StringLiteralUnchanged `json:"kind" lsp:"required"` // A result id which will be sent on the next // diagnostic request for the same document. - ResultId string `json:"resultId"` + ResultId string `json:"resultId" lsp:"required"` // Diagnostics of related documents. This information is useful // in programming languages where code in a file A can generate @@ -15563,224 +4457,20 @@ type RelatedUnchangedDocumentDiagnosticReport struct { var _ json.UnmarshalerFrom = (*RelatedUnchangedDocumentDiagnosticReport)(nil) func (s *RelatedUnchangedDocumentDiagnosticReport) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - missingResultId - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"resultId"`: - missing &^= missingResultId - if err := json.UnmarshalDecode(dec, &s.ResultId); err != nil { - return err - } - case `"relatedDocuments"`: - if dec.PeekKind() == 'n' { - return errNull("relatedDocuments") - } - if err := json.UnmarshalDecode(dec, &s.RelatedDocuments); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingResultId != 0 { - missingProps = append(missingProps, "resultId") - } - return errMissing(missingProps) - } - - return nil -} - -// A diagnostic report with a full set of problems. -// -// Since: 3.17.0 -type FullDocumentDiagnosticReport struct { - // A full document diagnostic report. - Kind StringLiteralFull `json:"kind"` - - // An optional result id. If provided it will - // be sent on the next diagnostic request for the - // same document. - ResultId *string `json:"resultId,omitzero"` - - // The actual items. - Items []*Diagnostic `json:"items"` -} - -var _ json.UnmarshalerFrom = (*FullDocumentDiagnosticReport)(nil) - -func (s *FullDocumentDiagnosticReport) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - missingItems - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"resultId"`: - if dec.PeekKind() == 'n' { - return errNull("resultId") - } - if err := json.UnmarshalDecode(dec, &s.ResultId); err != nil { - return err - } - case `"items"`: - missing &^= missingItems - if dec.PeekKind() == 'n' { - return errNull("items") - } - if err := json.UnmarshalDecode(dec, &s.Items); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingItems != 0 { - missingProps = append(missingProps, "items") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } -// A diagnostic report indicating that the last returned -// report is still accurate. +// A partial result for a document diagnostic report. // // Since: 3.17.0 -type UnchangedDocumentDiagnosticReport struct { - // A document diagnostic report indicating - // no changes to the last result. A server can - // only return `unchanged` if result ids are - // provided. - Kind StringLiteralUnchanged `json:"kind"` - - // A result id which will be sent on the next - // diagnostic request for the same document. - ResultId string `json:"resultId"` +type DocumentDiagnosticReportPartialResult struct { + RelatedDocuments map[DocumentUri]FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport `json:"relatedDocuments" lsp:"required"` } -var _ json.UnmarshalerFrom = (*UnchangedDocumentDiagnosticReport)(nil) - -func (s *UnchangedDocumentDiagnosticReport) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - missingResultId - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"resultId"`: - missing &^= missingResultId - if err := json.UnmarshalDecode(dec, &s.ResultId); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingResultId != 0 { - missingProps = append(missingProps, "resultId") - } - return errMissing(missingProps) - } +var _ json.UnmarshalerFrom = (*DocumentDiagnosticReportPartialResult)(nil) - return nil +func (s *DocumentDiagnosticReportPartialResult) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Diagnostic options. @@ -15797,82 +4487,16 @@ type DiagnosticOptions struct { // editing code in one file can result in a different diagnostic // set in another file. Inter file dependencies are common for // most programming languages and typically uncommon for linters. - InterFileDependencies bool `json:"interFileDependencies"` + InterFileDependencies bool `json:"interFileDependencies" lsp:"required"` // The server provides support for workspace diagnostics as well. - WorkspaceDiagnostics bool `json:"workspaceDiagnostics"` + WorkspaceDiagnostics bool `json:"workspaceDiagnostics" lsp:"required"` } var _ json.UnmarshalerFrom = (*DiagnosticOptions)(nil) func (s *DiagnosticOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingInterFileDependencies uint = 1 << iota - missingWorkspaceDiagnostics - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"identifier"`: - if dec.PeekKind() == 'n' { - return errNull("identifier") - } - if err := json.UnmarshalDecode(dec, &s.Identifier); err != nil { - return err - } - case `"interFileDependencies"`: - missing &^= missingInterFileDependencies - if err := json.UnmarshalDecode(dec, &s.InterFileDependencies); err != nil { - return err - } - case `"workspaceDiagnostics"`: - missing &^= missingWorkspaceDiagnostics - if err := json.UnmarshalDecode(dec, &s.WorkspaceDiagnostics); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingInterFileDependencies != 0 { - missingProps = append(missingProps, "interFileDependencies") - } - if missing&missingWorkspaceDiagnostics != 0 { - missingProps = append(missingProps, "workspaceDiagnostics") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A previous result id in a workspace pull request. @@ -15881,161 +4505,39 @@ func (s *DiagnosticOptions) UnmarshalJSONFrom(dec *json.Decoder) error { type PreviousResultId struct { // The URI for which the client knowns a // result id. - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` // The value of the previous result id. - Value string `json:"value"` + Value string `json:"value" lsp:"required"` } var _ json.UnmarshalerFrom = (*PreviousResultId)(nil) func (s *PreviousResultId) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - missingValue - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"value"`: - missing &^= missingValue - if err := json.UnmarshalDecode(dec, &s.Value); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - if missing&missingValue != 0 { - missingProps = append(missingProps, "value") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // An item to transfer a text document from the client to the // server. type TextDocumentItem struct { // The text document's uri. - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` // The text document's language identifier. - LanguageId LanguageKind `json:"languageId"` + LanguageId LanguageKind `json:"languageId" lsp:"required"` // The version number of this document (it will increase after each // change, including undo/redo). - Version int32 `json:"version"` + Version int32 `json:"version" lsp:"required"` // The content of the opened text document. - Text string `json:"text"` + Text string `json:"text" lsp:"required"` } var _ json.UnmarshalerFrom = (*TextDocumentItem)(nil) func (s *TextDocumentItem) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - missingLanguageId - missingVersion - missingText - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"languageId"`: - missing &^= missingLanguageId - if err := json.UnmarshalDecode(dec, &s.LanguageId); err != nil { - return err - } - case `"version"`: - missing &^= missingVersion - if err := json.UnmarshalDecode(dec, &s.Version); err != nil { - return err - } - case `"text"`: - missing &^= missingText - if err := json.UnmarshalDecode(dec, &s.Text); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - if missing&missingLanguageId != 0 { - missingProps = append(missingProps, "languageId") - } - if missing&missingVersion != 0 { - missingProps = append(missingProps, "version") - } - if missing&missingText != 0 { - missingProps = append(missingProps, "text") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Provides information about the context in which an inline completion was requested. @@ -16043,7 +4545,7 @@ func (s *TextDocumentItem) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.18.0 type InlineCompletionContext struct { // Describes how the inline completion was triggered. - TriggerKind InlineCompletionTriggerKind `json:"triggerKind"` + TriggerKind InlineCompletionTriggerKind `json:"triggerKind" lsp:"required"` // Provides information about the currently selected item in the autocomplete widget if it is visible. SelectedCompletionInfo *SelectedCompletionInfo `json:"selectedCompletionInfo,omitzero"` @@ -16052,57 +4554,7 @@ type InlineCompletionContext struct { var _ json.UnmarshalerFrom = (*InlineCompletionContext)(nil) func (s *InlineCompletionContext) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTriggerKind uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"triggerKind"`: - missing &^= missingTriggerKind - if err := json.UnmarshalDecode(dec, &s.TriggerKind); err != nil { - return err - } - case `"selectedCompletionInfo"`: - if dec.PeekKind() == 'n' { - return errNull("selectedCompletionInfo") - } - if err := json.UnmarshalDecode(dec, &s.SelectedCompletionInfo); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTriggerKind != 0 { - missingProps = append(missingProps, "triggerKind") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A string value used as a snippet is a template which allows to insert text @@ -16116,68 +4568,16 @@ func (s *InlineCompletionContext) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.18.0 type StringValue struct { // The kind of string value. - Kind StringLiteralSnippet `json:"kind"` + Kind StringLiteralSnippet `json:"kind" lsp:"required"` // The snippet string. - Value string `json:"value"` + Value string `json:"value" lsp:"required"` } var _ json.UnmarshalerFrom = (*StringValue)(nil) func (s *StringValue) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - missingValue - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"value"`: - missing &^= missingValue - if err := json.UnmarshalDecode(dec, &s.Value); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingValue != 0 { - missingProps = append(missingProps, "value") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Inline completion options used during static registration. @@ -16190,38 +4590,7 @@ type InlineCompletionOptions struct { var _ json.UnmarshalerFrom = (*InlineCompletionOptions)(nil) func (s *InlineCompletionOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Text document content provider options. @@ -16229,66 +4598,20 @@ func (s *InlineCompletionOptions) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.18.0 type TextDocumentContentOptions struct { // The schemes for which the server provides content. - Schemes []string `json:"schemes"` -} - -var _ json.UnmarshalerFrom = (*TextDocumentContentOptions)(nil) - -func (s *TextDocumentContentOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingSchemes uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"schemes"`: - missing &^= missingSchemes - if dec.PeekKind() == 'n' { - return errNull("schemes") - } - if err := json.UnmarshalDecode(dec, &s.Schemes); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } + Schemes []string `json:"schemes" lsp:"required"` +} - if missing != 0 { - var missingProps []string - if missing&missingSchemes != 0 { - missingProps = append(missingProps, "schemes") - } - return errMissing(missingProps) - } +var _ json.UnmarshalerFrom = (*TextDocumentContentOptions)(nil) - return nil +func (s *TextDocumentContentOptions) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // General parameters to register for a notification or to register a provider. type Registration struct { // The id used to register the request. The id can be used to deregister // the request again. - Id string `json:"id"` + Id string `json:"id" lsp:"required"` // Options necessary for the registration. Determines the method. RegisterOptions *RegisterOptions `json:"-"` @@ -16353,54 +4676,7 @@ func (s *Registration) MarshalJSONTo(enc *json.Encoder) error { if s.RegisterOptions == nil { panic("RegisterOptions must be set") } - assertOnlyOne("exactly one element of RegisterOptions should be set", boolToInt(s.RegisterOptions.TextDocumentImplementation != nil)+ - boolToInt(s.RegisterOptions.TextDocumentTypeDefinition != nil)+ - boolToInt(s.RegisterOptions.TextDocumentDocumentColor != nil)+ - boolToInt(s.RegisterOptions.TextDocumentColorPresentation != nil)+ - boolToInt(s.RegisterOptions.TextDocumentFoldingRange != nil)+ - boolToInt(s.RegisterOptions.TextDocumentDeclaration != nil)+ - boolToInt(s.RegisterOptions.TextDocumentSelectionRange != nil)+ - boolToInt(s.RegisterOptions.TextDocumentPrepareCallHierarchy != nil)+ - boolToInt(s.RegisterOptions.TextDocumentSemanticTokens != nil)+ - boolToInt(s.RegisterOptions.TextDocumentLinkedEditingRange != nil)+ - boolToInt(s.RegisterOptions.WorkspaceWillCreateFiles != nil)+ - boolToInt(s.RegisterOptions.WorkspaceWillRenameFiles != nil)+ - boolToInt(s.RegisterOptions.WorkspaceWillDeleteFiles != nil)+ - boolToInt(s.RegisterOptions.TextDocumentMoniker != nil)+ - boolToInt(s.RegisterOptions.TextDocumentPrepareTypeHierarchy != nil)+ - boolToInt(s.RegisterOptions.TextDocumentInlineValue != nil)+ - boolToInt(s.RegisterOptions.TextDocumentInlayHint != nil)+ - boolToInt(s.RegisterOptions.TextDocumentDiagnostic != nil)+ - boolToInt(s.RegisterOptions.TextDocumentInlineCompletion != nil)+ - boolToInt(s.RegisterOptions.WorkspaceTextDocumentContent != nil)+ - boolToInt(s.RegisterOptions.TextDocumentWillSaveWaitUntil != nil)+ - boolToInt(s.RegisterOptions.TextDocumentCompletion != nil)+ - boolToInt(s.RegisterOptions.TextDocumentHover != nil)+ - boolToInt(s.RegisterOptions.TextDocumentSignatureHelp != nil)+ - boolToInt(s.RegisterOptions.TextDocumentDefinition != nil)+ - boolToInt(s.RegisterOptions.TextDocumentReferences != nil)+ - boolToInt(s.RegisterOptions.TextDocumentDocumentHighlight != nil)+ - boolToInt(s.RegisterOptions.TextDocumentDocumentSymbol != nil)+ - boolToInt(s.RegisterOptions.TextDocumentCodeAction != nil)+ - boolToInt(s.RegisterOptions.WorkspaceSymbol != nil)+ - boolToInt(s.RegisterOptions.TextDocumentCodeLens != nil)+ - boolToInt(s.RegisterOptions.TextDocumentDocumentLink != nil)+ - boolToInt(s.RegisterOptions.TextDocumentFormatting != nil)+ - boolToInt(s.RegisterOptions.TextDocumentRangeFormatting != nil)+ - boolToInt(s.RegisterOptions.TextDocumentRangesFormatting != nil)+ - boolToInt(s.RegisterOptions.TextDocumentOnTypeFormatting != nil)+ - boolToInt(s.RegisterOptions.TextDocumentRename != nil)+ - boolToInt(s.RegisterOptions.WorkspaceExecuteCommand != nil)+ - boolToInt(s.RegisterOptions.WorkspaceDidCreateFiles != nil)+ - boolToInt(s.RegisterOptions.WorkspaceDidRenameFiles != nil)+ - boolToInt(s.RegisterOptions.WorkspaceDidDeleteFiles != nil)+ - boolToInt(s.RegisterOptions.WorkspaceDidChangeConfiguration != nil)+ - boolToInt(s.RegisterOptions.TextDocumentDidOpen != nil)+ - boolToInt(s.RegisterOptions.TextDocumentDidChange != nil)+ - boolToInt(s.RegisterOptions.TextDocumentDidClose != nil)+ - boolToInt(s.RegisterOptions.TextDocumentDidSave != nil)+ - boolToInt(s.RegisterOptions.TextDocumentWillSave != nil)+ - boolToInt(s.RegisterOptions.WorkspaceDidChangeWatchedFiles != nil)) + assertOnlyOne("exactly one element of RegisterOptions should be set", countNonNil(s.RegisterOptions)) if err := enc.WriteToken(json.BeginObject); err != nil { return err @@ -16944,68 +5220,16 @@ func (s *Registration) UnmarshalJSONFrom(dec *json.Decoder) error { type Unregistration struct { // The id used to unregister the request or notification. Usually an id // provided during the register request. - Id string `json:"id"` + Id string `json:"id" lsp:"required"` // The method to unregister for. - Method string `json:"method"` + Method string `json:"method" lsp:"required"` } var _ json.UnmarshalerFrom = (*Unregistration)(nil) func (s *Unregistration) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingId uint = 1 << iota - missingMethod - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"id"`: - missing &^= missingId - if err := json.UnmarshalDecode(dec, &s.Id); err != nil { - return err - } - case `"method"`: - missing &^= missingMethod - if err := json.UnmarshalDecode(dec, &s.Method); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingId != 0 { - missingProps = append(missingProps, "id") - } - if missing&missingMethod != 0 { - missingProps = append(missingProps, "method") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type WorkspaceFoldersInitializeParams struct { @@ -17016,7 +5240,7 @@ type WorkspaceFoldersInitializeParams struct { // configured. // // Since: 3.6.0 - WorkspaceFolders *WorkspaceFoldersOrNull `json:"workspaceFolders,omitzero"` + WorkspaceFolders *WorkspaceFoldersOrNull `json:"workspaceFolders,omitzero" lsp:"nullable"` } // Defines the capabilities provided by a language @@ -17156,439 +5380,54 @@ type ServerCapabilities struct { // Workspace specific server capabilities. Workspace *WorkspaceOptions `json:"workspace,omitzero"` - // Experimental server capabilities. - Experimental *ExperimentalServerCapabilities `json:"experimental,omitzero"` - - // Provider options for the VS auto-insert feature via textDocument/_vs_onAutoInsert. - VSOnAutoInsertProvider *VSOnAutoInsertOptions `json:"_vs_onAutoInsertProvider,omitzero"` - - // The server provides VS-specific grouped references via textDocument/_vs_references. - VSReferencesProvider *bool `json:"_vs_referencesProvider,omitzero"` -} - -var _ json.UnmarshalerFrom = (*ServerCapabilities)(nil) - -func (s *ServerCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"positionEncoding"`: - if dec.PeekKind() == 'n' { - return errNull("positionEncoding") - } - if err := json.UnmarshalDecode(dec, &s.PositionEncoding); err != nil { - return err - } - case `"textDocumentSync"`: - if dec.PeekKind() == 'n' { - return errNull("textDocumentSync") - } - if err := json.UnmarshalDecode(dec, &s.TextDocumentSync); err != nil { - return err - } - case `"completionProvider"`: - if dec.PeekKind() == 'n' { - return errNull("completionProvider") - } - if err := json.UnmarshalDecode(dec, &s.CompletionProvider); err != nil { - return err - } - case `"hoverProvider"`: - if dec.PeekKind() == 'n' { - return errNull("hoverProvider") - } - if err := json.UnmarshalDecode(dec, &s.HoverProvider); err != nil { - return err - } - case `"signatureHelpProvider"`: - if dec.PeekKind() == 'n' { - return errNull("signatureHelpProvider") - } - if err := json.UnmarshalDecode(dec, &s.SignatureHelpProvider); err != nil { - return err - } - case `"declarationProvider"`: - if dec.PeekKind() == 'n' { - return errNull("declarationProvider") - } - if err := json.UnmarshalDecode(dec, &s.DeclarationProvider); err != nil { - return err - } - case `"definitionProvider"`: - if dec.PeekKind() == 'n' { - return errNull("definitionProvider") - } - if err := json.UnmarshalDecode(dec, &s.DefinitionProvider); err != nil { - return err - } - case `"typeDefinitionProvider"`: - if dec.PeekKind() == 'n' { - return errNull("typeDefinitionProvider") - } - if err := json.UnmarshalDecode(dec, &s.TypeDefinitionProvider); err != nil { - return err - } - case `"implementationProvider"`: - if dec.PeekKind() == 'n' { - return errNull("implementationProvider") - } - if err := json.UnmarshalDecode(dec, &s.ImplementationProvider); err != nil { - return err - } - case `"referencesProvider"`: - if dec.PeekKind() == 'n' { - return errNull("referencesProvider") - } - if err := json.UnmarshalDecode(dec, &s.ReferencesProvider); err != nil { - return err - } - case `"documentHighlightProvider"`: - if dec.PeekKind() == 'n' { - return errNull("documentHighlightProvider") - } - if err := json.UnmarshalDecode(dec, &s.DocumentHighlightProvider); err != nil { - return err - } - case `"documentSymbolProvider"`: - if dec.PeekKind() == 'n' { - return errNull("documentSymbolProvider") - } - if err := json.UnmarshalDecode(dec, &s.DocumentSymbolProvider); err != nil { - return err - } - case `"codeActionProvider"`: - if dec.PeekKind() == 'n' { - return errNull("codeActionProvider") - } - if err := json.UnmarshalDecode(dec, &s.CodeActionProvider); err != nil { - return err - } - case `"codeLensProvider"`: - if dec.PeekKind() == 'n' { - return errNull("codeLensProvider") - } - if err := json.UnmarshalDecode(dec, &s.CodeLensProvider); err != nil { - return err - } - case `"documentLinkProvider"`: - if dec.PeekKind() == 'n' { - return errNull("documentLinkProvider") - } - if err := json.UnmarshalDecode(dec, &s.DocumentLinkProvider); err != nil { - return err - } - case `"colorProvider"`: - if dec.PeekKind() == 'n' { - return errNull("colorProvider") - } - if err := json.UnmarshalDecode(dec, &s.ColorProvider); err != nil { - return err - } - case `"workspaceSymbolProvider"`: - if dec.PeekKind() == 'n' { - return errNull("workspaceSymbolProvider") - } - if err := json.UnmarshalDecode(dec, &s.WorkspaceSymbolProvider); err != nil { - return err - } - case `"documentFormattingProvider"`: - if dec.PeekKind() == 'n' { - return errNull("documentFormattingProvider") - } - if err := json.UnmarshalDecode(dec, &s.DocumentFormattingProvider); err != nil { - return err - } - case `"documentRangeFormattingProvider"`: - if dec.PeekKind() == 'n' { - return errNull("documentRangeFormattingProvider") - } - if err := json.UnmarshalDecode(dec, &s.DocumentRangeFormattingProvider); err != nil { - return err - } - case `"documentOnTypeFormattingProvider"`: - if dec.PeekKind() == 'n' { - return errNull("documentOnTypeFormattingProvider") - } - if err := json.UnmarshalDecode(dec, &s.DocumentOnTypeFormattingProvider); err != nil { - return err - } - case `"renameProvider"`: - if dec.PeekKind() == 'n' { - return errNull("renameProvider") - } - if err := json.UnmarshalDecode(dec, &s.RenameProvider); err != nil { - return err - } - case `"foldingRangeProvider"`: - if dec.PeekKind() == 'n' { - return errNull("foldingRangeProvider") - } - if err := json.UnmarshalDecode(dec, &s.FoldingRangeProvider); err != nil { - return err - } - case `"selectionRangeProvider"`: - if dec.PeekKind() == 'n' { - return errNull("selectionRangeProvider") - } - if err := json.UnmarshalDecode(dec, &s.SelectionRangeProvider); err != nil { - return err - } - case `"executeCommandProvider"`: - if dec.PeekKind() == 'n' { - return errNull("executeCommandProvider") - } - if err := json.UnmarshalDecode(dec, &s.ExecuteCommandProvider); err != nil { - return err - } - case `"callHierarchyProvider"`: - if dec.PeekKind() == 'n' { - return errNull("callHierarchyProvider") - } - if err := json.UnmarshalDecode(dec, &s.CallHierarchyProvider); err != nil { - return err - } - case `"linkedEditingRangeProvider"`: - if dec.PeekKind() == 'n' { - return errNull("linkedEditingRangeProvider") - } - if err := json.UnmarshalDecode(dec, &s.LinkedEditingRangeProvider); err != nil { - return err - } - case `"semanticTokensProvider"`: - if dec.PeekKind() == 'n' { - return errNull("semanticTokensProvider") - } - if err := json.UnmarshalDecode(dec, &s.SemanticTokensProvider); err != nil { - return err - } - case `"monikerProvider"`: - if dec.PeekKind() == 'n' { - return errNull("monikerProvider") - } - if err := json.UnmarshalDecode(dec, &s.MonikerProvider); err != nil { - return err - } - case `"typeHierarchyProvider"`: - if dec.PeekKind() == 'n' { - return errNull("typeHierarchyProvider") - } - if err := json.UnmarshalDecode(dec, &s.TypeHierarchyProvider); err != nil { - return err - } - case `"inlineValueProvider"`: - if dec.PeekKind() == 'n' { - return errNull("inlineValueProvider") - } - if err := json.UnmarshalDecode(dec, &s.InlineValueProvider); err != nil { - return err - } - case `"inlayHintProvider"`: - if dec.PeekKind() == 'n' { - return errNull("inlayHintProvider") - } - if err := json.UnmarshalDecode(dec, &s.InlayHintProvider); err != nil { - return err - } - case `"diagnosticProvider"`: - if dec.PeekKind() == 'n' { - return errNull("diagnosticProvider") - } - if err := json.UnmarshalDecode(dec, &s.DiagnosticProvider); err != nil { - return err - } - case `"inlineCompletionProvider"`: - if dec.PeekKind() == 'n' { - return errNull("inlineCompletionProvider") - } - if err := json.UnmarshalDecode(dec, &s.InlineCompletionProvider); err != nil { - return err - } - case `"workspace"`: - if dec.PeekKind() == 'n' { - return errNull("workspace") - } - if err := json.UnmarshalDecode(dec, &s.Workspace); err != nil { - return err - } - case `"experimental"`: - if dec.PeekKind() == 'n' { - return errNull("experimental") - } - if err := json.UnmarshalDecode(dec, &s.Experimental); err != nil { - return err - } - case `"_vs_onAutoInsertProvider"`: - if dec.PeekKind() == 'n' { - return errNull("_vs_onAutoInsertProvider") - } - if err := json.UnmarshalDecode(dec, &s.VSOnAutoInsertProvider); err != nil { - return err - } - case `"_vs_referencesProvider"`: - if dec.PeekKind() == 'n' { - return errNull("_vs_referencesProvider") - } - if err := json.UnmarshalDecode(dec, &s.VSReferencesProvider); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil -} - -// Information about the server -// -// Since: 3.15.0 -// -// Since: 3.18.0 ServerInfo type name added. -type ServerInfo struct { - // The name of the server as defined by the server. - Name string `json:"name"` - - // The server's version as defined by the server. - Version *string `json:"version,omitzero"` -} - -var _ json.UnmarshalerFrom = (*ServerInfo)(nil) - -func (s *ServerInfo) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingName uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"name"`: - missing &^= missingName - if err := json.UnmarshalDecode(dec, &s.Name); err != nil { - return err - } - case `"version"`: - if dec.PeekKind() == 'n' { - return errNull("version") - } - if err := json.UnmarshalDecode(dec, &s.Version); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + // Experimental server capabilities. + Experimental *ExperimentalServerCapabilities `json:"experimental,omitzero"` - if _, err := dec.ReadToken(); err != nil { - return err - } + // Provider options for the VS auto-insert feature via textDocument/_vs_onAutoInsert. + VSOnAutoInsertProvider *VSOnAutoInsertOptions `json:"_vs_onAutoInsertProvider,omitzero"` - if missing != 0 { - var missingProps []string - if missing&missingName != 0 { - missingProps = append(missingProps, "name") - } - return errMissing(missingProps) - } + // The server provides VS-specific grouped references via textDocument/_vs_references. + VSReferencesProvider *bool `json:"_vs_referencesProvider,omitzero"` +} - return nil +var _ json.UnmarshalerFrom = (*ServerCapabilities)(nil) + +func (s *ServerCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) +} + +// Information about the server +// +// Since: 3.15.0 +// +// Since: 3.18.0 ServerInfo type name added. +type ServerInfo struct { + // The name of the server as defined by the server. + Name string `json:"name" lsp:"required"` + + // The server's version as defined by the server. + Version *string `json:"version,omitzero"` +} + +var _ json.UnmarshalerFrom = (*ServerInfo)(nil) + +func (s *ServerInfo) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // A text document identifier to denote a specific version of a text document. type VersionedTextDocumentIdentifier struct { // The text document's uri. - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` // The version number of this document. - Version int32 `json:"version"` + Version int32 `json:"version" lsp:"required"` } var _ json.UnmarshalerFrom = (*VersionedTextDocumentIdentifier)(nil) func (s *VersionedTextDocumentIdentifier) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - missingVersion - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"version"`: - missing &^= missingVersion - if err := json.UnmarshalDecode(dec, &s.Version); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - if missing&missingVersion != 0 { - missingProps = append(missingProps, "version") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Save options. @@ -17600,112 +5439,29 @@ type SaveOptions struct { var _ json.UnmarshalerFrom = (*SaveOptions)(nil) func (s *SaveOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"includeText"`: - if dec.PeekKind() == 'n' { - return errNull("includeText") - } - if err := json.UnmarshalDecode(dec, &s.IncludeText); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // An event describing a file change. type FileEvent struct { // The file's uri. - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` // The change type. - Type FileChangeType `json:"type"` + Type FileChangeType `json:"type" lsp:"required"` } var _ json.UnmarshalerFrom = (*FileEvent)(nil) func (s *FileEvent) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - missingType - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"type"`: - missing &^= missingType - if err := json.UnmarshalDecode(dec, &s.Type); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - if missing&missingType != 0 { - missingProps = append(missingProps, "type") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } type FileSystemWatcher struct { // The glob pattern to watch. See pattern for more detail. // // Since: 3.17.0 support for relative patterns. - GlobPattern PatternOrRelativePattern `json:"globPattern"` + GlobPattern PatternOrRelativePattern `json:"globPattern" lsp:"required"` // The kind of events of interest. If omitted it defaults // to WatchKind.Create | WatchKind.Change | WatchKind.Delete @@ -17716,64 +5472,14 @@ type FileSystemWatcher struct { var _ json.UnmarshalerFrom = (*FileSystemWatcher)(nil) func (s *FileSystemWatcher) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingGlobPattern uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"globPattern"`: - missing &^= missingGlobPattern - if err := json.UnmarshalDecode(dec, &s.GlobPattern); err != nil { - return err - } - case `"kind"`: - if dec.PeekKind() == 'n' { - return errNull("kind") - } - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingGlobPattern != 0 { - missingProps = append(missingProps, "globPattern") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Represents a diagnostic, such as a compiler error or warning. Diagnostic objects // are only valid in the scope of a resource. type Diagnostic struct { // The range at which the message applies - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The diagnostic's severity. To avoid interpretation mismatches when a // server is used with different clients it is highly recommended that servers @@ -17798,135 +5504,34 @@ type Diagnostic struct { // // Since: 3.18.0 - support for MarkupContent. This is guarded by the client // capability `textDocument.diagnostic.markupMessageSupport`. - Message StringOrMarkupContent `json:"message"` - - // Additional metadata about the diagnostic. - // - // Since: 3.15.0 - Tags *[]DiagnosticTag `json:"tags,omitzero"` - - // An array of related diagnostic information, e.g. when symbol-names within - // a scope collide all definitions can be marked via this property. - RelatedInformation *[]*DiagnosticRelatedInformation `json:"relatedInformation,omitzero"` - - // A data entry field that is preserved between a `textDocument/publishDiagnostics` - // notification and `textDocument/codeAction` request. - // - // Since: 3.16.0 - Data *DiagnosticData `json:"data,omitzero"` -} - -var _ json.UnmarshalerFrom = (*Diagnostic)(nil) - -func (s *Diagnostic) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - missingMessage - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"severity"`: - if dec.PeekKind() == 'n' { - return errNull("severity") - } - if err := json.UnmarshalDecode(dec, &s.Severity); err != nil { - return err - } - case `"code"`: - if dec.PeekKind() == 'n' { - return errNull("code") - } - if err := json.UnmarshalDecode(dec, &s.Code); err != nil { - return err - } - case `"codeDescription"`: - if dec.PeekKind() == 'n' { - return errNull("codeDescription") - } - if err := json.UnmarshalDecode(dec, &s.CodeDescription); err != nil { - return err - } - case `"source"`: - if dec.PeekKind() == 'n' { - return errNull("source") - } - if err := json.UnmarshalDecode(dec, &s.Source); err != nil { - return err - } - case `"message"`: - missing &^= missingMessage - if err := json.UnmarshalDecode(dec, &s.Message); err != nil { - return err - } - case `"tags"`: - if dec.PeekKind() == 'n' { - return errNull("tags") - } - if err := json.UnmarshalDecode(dec, &s.Tags); err != nil { - return err - } - case `"relatedInformation"`: - if dec.PeekKind() == 'n' { - return errNull("relatedInformation") - } - if err := json.UnmarshalDecode(dec, &s.RelatedInformation); err != nil { - return err - } - case `"data"`: - if dec.PeekKind() == 'n' { - return errNull("data") - } - if err := json.UnmarshalDecode(dec, &s.Data); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + Message StringOrMarkupContent `json:"message" lsp:"required"` - if _, err := dec.ReadToken(); err != nil { - return err - } + // Additional metadata about the diagnostic. + // + // Since: 3.15.0 + Tags *[]DiagnosticTag `json:"tags,omitzero"` - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingMessage != 0 { - missingProps = append(missingProps, "message") - } - return errMissing(missingProps) - } + // An array of related diagnostic information, e.g. when symbol-names within + // a scope collide all definitions can be marked via this property. + RelatedInformation *[]*DiagnosticRelatedInformation `json:"relatedInformation,omitzero"` - return nil + // A data entry field that is preserved between a `textDocument/publishDiagnostics` + // notification and `textDocument/codeAction` request. + // + // Since: 3.16.0 + Data *DiagnosticData `json:"data,omitzero"` +} + +var _ json.UnmarshalerFrom = (*Diagnostic)(nil) + +func (s *Diagnostic) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Contains additional information about the context in which a completion request is triggered. type CompletionContext struct { // How the completion was triggered. - TriggerKind CompletionTriggerKind `json:"triggerKind"` + TriggerKind CompletionTriggerKind `json:"triggerKind" lsp:"required"` // The trigger character (a single character) that has trigger code complete. // Is undefined if `triggerKind !== CompletionTriggerKind.TriggerCharacter` @@ -17936,57 +5541,7 @@ type CompletionContext struct { var _ json.UnmarshalerFrom = (*CompletionContext)(nil) func (s *CompletionContext) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTriggerKind uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"triggerKind"`: - missing &^= missingTriggerKind - if err := json.UnmarshalDecode(dec, &s.TriggerKind); err != nil { - return err - } - case `"triggerCharacter"`: - if dec.PeekKind() == 'n' { - return errNull("triggerCharacter") - } - if err := json.UnmarshalDecode(dec, &s.TriggerCharacter); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTriggerKind != 0 { - missingProps = append(missingProps, "triggerKind") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Additional details for a completion item label. @@ -18005,45 +5560,7 @@ type CompletionItemLabelDetails struct { var _ json.UnmarshalerFrom = (*CompletionItemLabelDetails)(nil) func (s *CompletionItemLabelDetails) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"detail"`: - if dec.PeekKind() == 'n' { - return errNull("detail") - } - if err := json.UnmarshalDecode(dec, &s.Detail); err != nil { - return err - } - case `"description"`: - if dec.PeekKind() == 'n' { - return errNull("description") - } - if err := json.UnmarshalDecode(dec, &s.Description); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // A special text edit to provide an insert and a replace operation. @@ -18051,80 +5568,19 @@ func (s *CompletionItemLabelDetails) UnmarshalJSONFrom(dec *json.Decoder) error // Since: 3.16.0 type InsertReplaceEdit struct { // The string to be inserted. - NewText string `json:"newText"` + NewText string `json:"newText" lsp:"required"` // The range if the insert is requested - Insert Range `json:"insert"` + Insert Range `json:"insert" lsp:"required"` // The range if the replace is requested. - Replace Range `json:"replace"` + Replace Range `json:"replace" lsp:"required"` } var _ json.UnmarshalerFrom = (*InsertReplaceEdit)(nil) func (s *InsertReplaceEdit) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingNewText uint = 1 << iota - missingInsert - missingReplace - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"newText"`: - missing &^= missingNewText - if err := json.UnmarshalDecode(dec, &s.NewText); err != nil { - return err - } - case `"insert"`: - missing &^= missingInsert - if err := json.UnmarshalDecode(dec, &s.Insert); err != nil { - return err - } - case `"replace"`: - missing &^= missingReplace - if err := json.UnmarshalDecode(dec, &s.Replace); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingNewText != 0 { - missingProps = append(missingProps, "newText") - } - if missing&missingInsert != 0 { - missingProps = append(missingProps, "insert") - } - if missing&missingReplace != 0 { - missingProps = append(missingProps, "replace") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // In many cases the items of an actual completion result share the same @@ -18172,66 +5628,7 @@ type CompletionItemDefaults struct { var _ json.UnmarshalerFrom = (*CompletionItemDefaults)(nil) func (s *CompletionItemDefaults) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"commitCharacters"`: - if dec.PeekKind() == 'n' { - return errNull("commitCharacters") - } - if err := json.UnmarshalDecode(dec, &s.CommitCharacters); err != nil { - return err - } - case `"editRange"`: - if dec.PeekKind() == 'n' { - return errNull("editRange") - } - if err := json.UnmarshalDecode(dec, &s.EditRange); err != nil { - return err - } - case `"insertTextFormat"`: - if dec.PeekKind() == 'n' { - return errNull("insertTextFormat") - } - if err := json.UnmarshalDecode(dec, &s.InsertTextFormat); err != nil { - return err - } - case `"insertTextMode"`: - if dec.PeekKind() == 'n' { - return errNull("insertTextMode") - } - if err := json.UnmarshalDecode(dec, &s.InsertTextMode); err != nil { - return err - } - case `"data"`: - if dec.PeekKind() == 'n' { - return errNull("data") - } - if err := json.UnmarshalDecode(dec, &s.Data); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Specifies how fields from a completion item should be combined with those @@ -18297,45 +5694,7 @@ type CompletionItemApplyKinds struct { var _ json.UnmarshalerFrom = (*CompletionItemApplyKinds)(nil) func (s *CompletionItemApplyKinds) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"commitCharacters"`: - if dec.PeekKind() == 'n' { - return errNull("commitCharacters") - } - if err := json.UnmarshalDecode(dec, &s.CommitCharacters); err != nil { - return err - } - case `"data"`: - if dec.PeekKind() == 'n' { - return errNull("data") - } - if err := json.UnmarshalDecode(dec, &s.Data); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Completion options. @@ -18373,69 +5732,10 @@ type CompletionOptions struct { CompletionItem *ServerCompletionItemOptions `json:"completionItem,omitzero"` } -var _ json.UnmarshalerFrom = (*CompletionOptions)(nil) - -func (s *CompletionOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"triggerCharacters"`: - if dec.PeekKind() == 'n' { - return errNull("triggerCharacters") - } - if err := json.UnmarshalDecode(dec, &s.TriggerCharacters); err != nil { - return err - } - case `"allCommitCharacters"`: - if dec.PeekKind() == 'n' { - return errNull("allCommitCharacters") - } - if err := json.UnmarshalDecode(dec, &s.AllCommitCharacters); err != nil { - return err - } - case `"resolveProvider"`: - if dec.PeekKind() == 'n' { - return errNull("resolveProvider") - } - if err := json.UnmarshalDecode(dec, &s.ResolveProvider); err != nil { - return err - } - case `"completionItem"`: - if dec.PeekKind() == 'n' { - return errNull("completionItem") - } - if err := json.UnmarshalDecode(dec, &s.CompletionItem); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil +var _ json.UnmarshalerFrom = (*CompletionOptions)(nil) + +func (s *CompletionOptions) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Hover options. @@ -18446,38 +5746,7 @@ type HoverOptions struct { var _ json.UnmarshalerFrom = (*HoverOptions)(nil) func (s *HoverOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Additional information about the context in which a signature help request was triggered. @@ -18485,7 +5754,7 @@ func (s *HoverOptions) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.15.0 type SignatureHelpContext struct { // Action that caused signature help to be triggered. - TriggerKind SignatureHelpTriggerKind `json:"triggerKind"` + TriggerKind SignatureHelpTriggerKind `json:"triggerKind" lsp:"required"` // Character that caused signature help to be triggered. // @@ -18496,7 +5765,7 @@ type SignatureHelpContext struct { // // Retriggers occurs when the signature help is already active and can be caused by actions such as // typing a trigger character, a cursor move, or document content changes. - IsRetrigger bool `json:"isRetrigger"` + IsRetrigger bool `json:"isRetrigger" lsp:"required"` // The currently active `SignatureHelp`. // @@ -18508,73 +5777,7 @@ type SignatureHelpContext struct { var _ json.UnmarshalerFrom = (*SignatureHelpContext)(nil) func (s *SignatureHelpContext) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTriggerKind uint = 1 << iota - missingIsRetrigger - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"triggerKind"`: - missing &^= missingTriggerKind - if err := json.UnmarshalDecode(dec, &s.TriggerKind); err != nil { - return err - } - case `"triggerCharacter"`: - if dec.PeekKind() == 'n' { - return errNull("triggerCharacter") - } - if err := json.UnmarshalDecode(dec, &s.TriggerCharacter); err != nil { - return err - } - case `"isRetrigger"`: - missing &^= missingIsRetrigger - if err := json.UnmarshalDecode(dec, &s.IsRetrigger); err != nil { - return err - } - case `"activeSignatureHelp"`: - if dec.PeekKind() == 'n' { - return errNull("activeSignatureHelp") - } - if err := json.UnmarshalDecode(dec, &s.ActiveSignatureHelp); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTriggerKind != 0 { - missingProps = append(missingProps, "triggerKind") - } - if missing&missingIsRetrigger != 0 { - missingProps = append(missingProps, "isRetrigger") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Represents the signature of something callable. A signature @@ -18583,7 +5786,7 @@ func (s *SignatureHelpContext) UnmarshalJSONFrom(dec *json.Decoder) error { type SignatureInformation struct { // The label of this signature. Will be shown in // the UI. - Label string `json:"label"` + Label string `json:"label" lsp:"required"` // The human-readable doc-comment of this signature. Will be shown // in the UI but can be omitted. @@ -18603,7 +5806,7 @@ type SignatureInformation struct { // `SignatureHelp.activeParameter`. // // Since: 3.16.0 - ActiveParameter *UintegerOrNull `json:"activeParameter,omitzero"` + ActiveParameter *UintegerOrNull `json:"activeParameter,omitzero" lsp:"nullable"` // A colorized label for the signature, providing classified text runs for VS syntax coloring. VSColorizedLabel *VSClassifiedTextElement `json:"_vs_colorizedLabel,omitzero"` @@ -18612,75 +5815,7 @@ type SignatureInformation struct { var _ json.UnmarshalerFrom = (*SignatureInformation)(nil) func (s *SignatureInformation) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingLabel uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"label"`: - missing &^= missingLabel - if err := json.UnmarshalDecode(dec, &s.Label); err != nil { - return err - } - case `"documentation"`: - if dec.PeekKind() == 'n' { - return errNull("documentation") - } - if err := json.UnmarshalDecode(dec, &s.Documentation); err != nil { - return err - } - case `"parameters"`: - if dec.PeekKind() == 'n' { - return errNull("parameters") - } - if err := json.UnmarshalDecode(dec, &s.Parameters); err != nil { - return err - } - case `"activeParameter"`: - if err := json.UnmarshalDecode(dec, &s.ActiveParameter); err != nil { - return err - } - case `"_vs_colorizedLabel"`: - if dec.PeekKind() == 'n' { - return errNull("_vs_colorizedLabel") - } - if err := json.UnmarshalDecode(dec, &s.VSColorizedLabel); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingLabel != 0 { - missingProps = append(missingProps, "label") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Server Capabilities for a SignatureHelpRequest. @@ -18702,52 +5837,7 @@ type SignatureHelpOptions struct { var _ json.UnmarshalerFrom = (*SignatureHelpOptions)(nil) func (s *SignatureHelpOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"triggerCharacters"`: - if dec.PeekKind() == 'n' { - return errNull("triggerCharacters") - } - if err := json.UnmarshalDecode(dec, &s.TriggerCharacters); err != nil { - return err - } - case `"retriggerCharacters"`: - if dec.PeekKind() == 'n' { - return errNull("retriggerCharacters") - } - if err := json.UnmarshalDecode(dec, &s.RetriggerCharacters); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Server Capabilities for a DefinitionRequest. @@ -18758,136 +5848,31 @@ type DefinitionOptions struct { var _ json.UnmarshalerFrom = (*DefinitionOptions)(nil) func (s *DefinitionOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Value-object that contains additional information when // requesting references. type ReferenceContext struct { // Include the declaration of the current symbol. - IncludeDeclaration bool `json:"includeDeclaration"` + IncludeDeclaration bool `json:"includeDeclaration" lsp:"required"` } var _ json.UnmarshalerFrom = (*ReferenceContext)(nil) func (s *ReferenceContext) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingIncludeDeclaration uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"includeDeclaration"`: - missing &^= missingIncludeDeclaration - if err := json.UnmarshalDecode(dec, &s.IncludeDeclaration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingIncludeDeclaration != 0 { - missingProps = append(missingProps, "includeDeclaration") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Reference options. type ReferenceOptions struct { - WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` -} - -var _ json.UnmarshalerFrom = (*ReferenceOptions)(nil) - -func (s *ReferenceOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` +} - if _, err := dec.ReadToken(); err != nil { - return err - } +var _ json.UnmarshalerFrom = (*ReferenceOptions)(nil) - return nil +func (s *ReferenceOptions) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Provider options for a DocumentHighlightRequest. @@ -18898,47 +5883,16 @@ type DocumentHighlightOptions struct { var _ json.UnmarshalerFrom = (*DocumentHighlightOptions)(nil) func (s *DocumentHighlightOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // A base for all symbol information. type BaseSymbolInformation struct { // The name of this symbol. - Name string `json:"name"` + Name string `json:"name" lsp:"required"` // The kind of this symbol. - Kind SymbolKind `json:"kind"` + Kind SymbolKind `json:"kind" lsp:"required"` // Tags for this symbol. // @@ -18955,73 +5909,7 @@ type BaseSymbolInformation struct { var _ json.UnmarshalerFrom = (*BaseSymbolInformation)(nil) func (s *BaseSymbolInformation) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingName uint = 1 << iota - missingKind - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"name"`: - missing &^= missingName - if err := json.UnmarshalDecode(dec, &s.Name); err != nil { - return err - } - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"tags"`: - if dec.PeekKind() == 'n' { - return errNull("tags") - } - if err := json.UnmarshalDecode(dec, &s.Tags); err != nil { - return err - } - case `"containerName"`: - if dec.PeekKind() == 'n' { - return errNull("containerName") - } - if err := json.UnmarshalDecode(dec, &s.ContainerName); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingName != 0 { - missingProps = append(missingProps, "name") - } - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Provider options for a DocumentSymbolRequest. @@ -19038,45 +5926,7 @@ type DocumentSymbolOptions struct { var _ json.UnmarshalerFrom = (*DocumentSymbolOptions)(nil) func (s *DocumentSymbolOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"label"`: - if dec.PeekKind() == 'n' { - return errNull("label") - } - if err := json.UnmarshalDecode(dec, &s.Label); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Contains additional diagnostic information about the context in which @@ -19087,7 +5937,7 @@ type CodeActionContext struct { // errors are currently presented to the user for the given range. There is no guarantee // that these accurately reflect the error state of the resource. The primary parameter // to compute code actions is the provided range. - Diagnostics []*Diagnostic `json:"diagnostics"` + Diagnostics []*Diagnostic `json:"diagnostics" lsp:"required"` // Requested kind of actions to return. // @@ -19104,67 +5954,7 @@ type CodeActionContext struct { var _ json.UnmarshalerFrom = (*CodeActionContext)(nil) func (s *CodeActionContext) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDiagnostics uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"diagnostics"`: - missing &^= missingDiagnostics - if dec.PeekKind() == 'n' { - return errNull("diagnostics") - } - if err := json.UnmarshalDecode(dec, &s.Diagnostics); err != nil { - return err - } - case `"only"`: - if dec.PeekKind() == 'n' { - return errNull("only") - } - if err := json.UnmarshalDecode(dec, &s.Only); err != nil { - return err - } - case `"triggerKind"`: - if dec.PeekKind() == 'n' { - return errNull("triggerKind") - } - if err := json.UnmarshalDecode(dec, &s.TriggerKind); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDiagnostics != 0 { - missingProps = append(missingProps, "diagnostics") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Captures why the code action is currently disabled. @@ -19174,56 +5964,13 @@ type CodeActionDisabled struct { // Human readable description of why the code action is currently disabled. // // This is displayed in the code actions UI. - Reason string `json:"reason"` + Reason string `json:"reason" lsp:"required"` } var _ json.UnmarshalerFrom = (*CodeActionDisabled)(nil) func (s *CodeActionDisabled) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingReason uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"reason"`: - missing &^= missingReason - if err := json.UnmarshalDecode(dec, &s.Reason); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingReason != 0 { - missingProps = append(missingProps, "reason") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Provider options for a CodeActionRequest. @@ -19234,143 +5981,48 @@ type CodeActionOptions struct { // // The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the server // may list out every specific kind they provide. - CodeActionKinds *[]CodeActionKind `json:"codeActionKinds,omitzero"` - - // Static documentation for a class of code actions. - // - // Documentation from the provider should be shown in the code actions menu if either: - // - // - Code actions of `kind` are requested by the editor. In this case, the editor will show the documentation that - // most closely matches the requested code action kind. For example, if a provider has documentation for - // both `Refactor` and `RefactorExtract`, when the user requests code actions for `RefactorExtract`, - // the editor will use the documentation for `RefactorExtract` instead of the documentation for `Refactor`. - // - // - Any code actions of `kind` are returned by the provider. - // - // At most one documentation entry should be shown per provider. - // - // Since: 3.18.0 - Documentation *[]*CodeActionKindDocumentation `json:"documentation,omitzero"` - - // The server provides support to resolve additional - // information for a code action. - // - // Since: 3.16.0 - ResolveProvider *bool `json:"resolveProvider,omitzero"` -} - -var _ json.UnmarshalerFrom = (*CodeActionOptions)(nil) - -func (s *CodeActionOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"codeActionKinds"`: - if dec.PeekKind() == 'n' { - return errNull("codeActionKinds") - } - if err := json.UnmarshalDecode(dec, &s.CodeActionKinds); err != nil { - return err - } - case `"documentation"`: - if dec.PeekKind() == 'n' { - return errNull("documentation") - } - if err := json.UnmarshalDecode(dec, &s.Documentation); err != nil { - return err - } - case `"resolveProvider"`: - if dec.PeekKind() == 'n' { - return errNull("resolveProvider") - } - if err := json.UnmarshalDecode(dec, &s.ResolveProvider); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + CodeActionKinds *[]CodeActionKind `json:"codeActionKinds,omitzero"` - if _, err := dec.ReadToken(); err != nil { - return err - } + // Static documentation for a class of code actions. + // + // Documentation from the provider should be shown in the code actions menu if either: + // + // - Code actions of `kind` are requested by the editor. In this case, the editor will show the documentation that + // most closely matches the requested code action kind. For example, if a provider has documentation for + // both `Refactor` and `RefactorExtract`, when the user requests code actions for `RefactorExtract`, + // the editor will use the documentation for `RefactorExtract` instead of the documentation for `Refactor`. + // + // - Any code actions of `kind` are returned by the provider. + // + // At most one documentation entry should be shown per provider. + // + // Since: 3.18.0 + Documentation *[]*CodeActionKindDocumentation `json:"documentation,omitzero"` - return nil + // The server provides support to resolve additional + // information for a code action. + // + // Since: 3.16.0 + ResolveProvider *bool `json:"resolveProvider,omitzero"` +} + +var _ json.UnmarshalerFrom = (*CodeActionOptions)(nil) + +func (s *CodeActionOptions) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Location with only uri and does not include range. // // Since: 3.18.0 type LocationUriOnly struct { - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` } var _ json.UnmarshalerFrom = (*LocationUriOnly)(nil) func (s *LocationUriOnly) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Server capabilities for a WorkspaceSymbolRequest. @@ -19387,45 +6039,7 @@ type WorkspaceSymbolOptions struct { var _ json.UnmarshalerFrom = (*WorkspaceSymbolOptions)(nil) func (s *WorkspaceSymbolOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"resolveProvider"`: - if dec.PeekKind() == 'n' { - return errNull("resolveProvider") - } - if err := json.UnmarshalDecode(dec, &s.ResolveProvider); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Code Lens provider options of a CodeLensRequest. @@ -19439,45 +6053,7 @@ type CodeLensOptions struct { var _ json.UnmarshalerFrom = (*CodeLensOptions)(nil) func (s *CodeLensOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"resolveProvider"`: - if dec.PeekKind() == 'n' { - return errNull("resolveProvider") - } - if err := json.UnmarshalDecode(dec, &s.ResolveProvider); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Provider options for a DocumentLinkRequest. @@ -19491,54 +6067,16 @@ type DocumentLinkOptions struct { var _ json.UnmarshalerFrom = (*DocumentLinkOptions)(nil) func (s *DocumentLinkOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"resolveProvider"`: - if dec.PeekKind() == 'n' { - return errNull("resolveProvider") - } - if err := json.UnmarshalDecode(dec, &s.ResolveProvider); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Value-object describing what options formatting should use. type FormattingOptions struct { // Size of a tab in spaces. - TabSize uint32 `json:"tabSize"` + TabSize uint32 `json:"tabSize" lsp:"required"` // Prefer spaces over tabs. - InsertSpaces bool `json:"insertSpaces"` + InsertSpaces bool `json:"insertSpaces" lsp:"required"` // Trim trailing whitespace on a line. // @@ -19559,80 +6097,7 @@ type FormattingOptions struct { var _ json.UnmarshalerFrom = (*FormattingOptions)(nil) func (s *FormattingOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTabSize uint = 1 << iota - missingInsertSpaces - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"tabSize"`: - missing &^= missingTabSize - if err := json.UnmarshalDecode(dec, &s.TabSize); err != nil { - return err - } - case `"insertSpaces"`: - missing &^= missingInsertSpaces - if err := json.UnmarshalDecode(dec, &s.InsertSpaces); err != nil { - return err - } - case `"trimTrailingWhitespace"`: - if dec.PeekKind() == 'n' { - return errNull("trimTrailingWhitespace") - } - if err := json.UnmarshalDecode(dec, &s.TrimTrailingWhitespace); err != nil { - return err - } - case `"insertFinalNewline"`: - if dec.PeekKind() == 'n' { - return errNull("insertFinalNewline") - } - if err := json.UnmarshalDecode(dec, &s.InsertFinalNewline); err != nil { - return err - } - case `"trimFinalNewlines"`: - if dec.PeekKind() == 'n' { - return errNull("trimFinalNewlines") - } - if err := json.UnmarshalDecode(dec, &s.TrimFinalNewlines); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTabSize != 0 { - missingProps = append(missingProps, "tabSize") - } - if missing&missingInsertSpaces != 0 { - missingProps = append(missingProps, "insertSpaces") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Provider options for a DocumentFormattingRequest. @@ -19643,98 +6108,29 @@ type DocumentFormattingOptions struct { var _ json.UnmarshalerFrom = (*DocumentFormattingOptions)(nil) func (s *DocumentFormattingOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Provider options for a DocumentRangeFormattingRequest. type DocumentRangeFormattingOptions struct { - WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` - - // Whether the server supports formatting multiple ranges at once. - // - // Since: 3.18.0 - RangesSupport *bool `json:"rangesSupport,omitzero"` -} - -var _ json.UnmarshalerFrom = (*DocumentRangeFormattingOptions)(nil) - -func (s *DocumentRangeFormattingOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } + WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"rangesSupport"`: - if dec.PeekKind() == 'n' { - return errNull("rangesSupport") - } - if err := json.UnmarshalDecode(dec, &s.RangesSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + // Whether the server supports formatting multiple ranges at once. + // + // Since: 3.18.0 + RangesSupport *bool `json:"rangesSupport,omitzero"` +} - if _, err := dec.ReadToken(); err != nil { - return err - } +var _ json.UnmarshalerFrom = (*DocumentRangeFormattingOptions)(nil) - return nil +func (s *DocumentRangeFormattingOptions) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Provider options for a DocumentOnTypeFormattingRequest. type DocumentOnTypeFormattingOptions struct { // A character on which formatting should be triggered, like `{`. - FirstTriggerCharacter string `json:"firstTriggerCharacter"` + FirstTriggerCharacter string `json:"firstTriggerCharacter" lsp:"required"` // More trigger characters. MoreTriggerCharacter *[]string `json:"moreTriggerCharacter,omitzero"` @@ -19743,57 +6139,7 @@ type DocumentOnTypeFormattingOptions struct { var _ json.UnmarshalerFrom = (*DocumentOnTypeFormattingOptions)(nil) func (s *DocumentOnTypeFormattingOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingFirstTriggerCharacter uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"firstTriggerCharacter"`: - missing &^= missingFirstTriggerCharacter - if err := json.UnmarshalDecode(dec, &s.FirstTriggerCharacter); err != nil { - return err - } - case `"moreTriggerCharacter"`: - if dec.PeekKind() == 'n' { - return errNull("moreTriggerCharacter") - } - if err := json.UnmarshalDecode(dec, &s.MoreTriggerCharacter); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingFirstTriggerCharacter != 0 { - missingProps = append(missingProps, "firstTriggerCharacter") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Provider options for a RenameRequest. @@ -19809,164 +6155,31 @@ type RenameOptions struct { var _ json.UnmarshalerFrom = (*RenameOptions)(nil) func (s *RenameOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"prepareProvider"`: - if dec.PeekKind() == 'n' { - return errNull("prepareProvider") - } - if err := json.UnmarshalDecode(dec, &s.PrepareProvider); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 type PrepareRenamePlaceholder struct { - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` - Placeholder string `json:"placeholder"` + Placeholder string `json:"placeholder" lsp:"required"` } var _ json.UnmarshalerFrom = (*PrepareRenamePlaceholder)(nil) func (s *PrepareRenamePlaceholder) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - missingPlaceholder - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"placeholder"`: - missing &^= missingPlaceholder - if err := json.UnmarshalDecode(dec, &s.Placeholder); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingPlaceholder != 0 { - missingProps = append(missingProps, "placeholder") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 type PrepareRenameDefaultBehavior struct { - DefaultBehavior bool `json:"defaultBehavior"` + DefaultBehavior bool `json:"defaultBehavior" lsp:"required"` } var _ json.UnmarshalerFrom = (*PrepareRenameDefaultBehavior)(nil) func (s *PrepareRenameDefaultBehavior) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDefaultBehavior uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"defaultBehavior"`: - missing &^= missingDefaultBehavior - if err := json.UnmarshalDecode(dec, &s.DefaultBehavior); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDefaultBehavior != 0 { - missingProps = append(missingProps, "defaultBehavior") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // The server capabilities of a ExecuteCommandRequest. @@ -19974,184 +6187,42 @@ type ExecuteCommandOptions struct { WorkDoneProgress *bool `json:"workDoneProgress,omitzero"` // The commands to be executed on the server - Commands []string `json:"commands"` + Commands []string `json:"commands" lsp:"required"` } var _ json.UnmarshalerFrom = (*ExecuteCommandOptions)(nil) func (s *ExecuteCommandOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingCommands uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"commands"`: - missing &^= missingCommands - if dec.PeekKind() == 'n' { - return errNull("commands") - } - if err := json.UnmarshalDecode(dec, &s.Commands); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingCommands != 0 { - missingProps = append(missingProps, "commands") - } - return errMissing(missingProps) - } - - return nil -} - -// Additional data about a workspace edit. -// -// Since: 3.18.0 -type WorkspaceEditMetadata struct { - // Signal to the editor that this edit is a refactoring. - IsRefactoring *bool `json:"isRefactoring,omitzero"` + return unmarshalStruct(s, dec) } -var _ json.UnmarshalerFrom = (*WorkspaceEditMetadata)(nil) - -func (s *WorkspaceEditMetadata) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"isRefactoring"`: - if dec.PeekKind() == 'n' { - return errNull("isRefactoring") - } - if err := json.UnmarshalDecode(dec, &s.IsRefactoring); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } +// Additional data about a workspace edit. +// +// Since: 3.18.0 +type WorkspaceEditMetadata struct { + // Signal to the editor that this edit is a refactoring. + IsRefactoring *bool `json:"isRefactoring,omitzero"` +} - if _, err := dec.ReadToken(); err != nil { - return err - } +var _ json.UnmarshalerFrom = (*WorkspaceEditMetadata)(nil) - return nil +func (s *WorkspaceEditMetadata) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Since: 3.16.0 type SemanticTokensLegend struct { // The token types a server uses. - TokenTypes []string `json:"tokenTypes"` + TokenTypes []string `json:"tokenTypes" lsp:"required"` // The token modifiers a server uses. - TokenModifiers []string `json:"tokenModifiers"` + TokenModifiers []string `json:"tokenModifiers" lsp:"required"` } var _ json.UnmarshalerFrom = (*SemanticTokensLegend)(nil) func (s *SemanticTokensLegend) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTokenTypes uint = 1 << iota - missingTokenModifiers - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"tokenTypes"`: - missing &^= missingTokenTypes - if dec.PeekKind() == 'n' { - return errNull("tokenTypes") - } - if err := json.UnmarshalDecode(dec, &s.TokenTypes); err != nil { - return err - } - case `"tokenModifiers"`: - missing &^= missingTokenModifiers - if dec.PeekKind() == 'n' { - return errNull("tokenModifiers") - } - if err := json.UnmarshalDecode(dec, &s.TokenModifiers); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTokenTypes != 0 { - missingProps = append(missingProps, "tokenTypes") - } - if missing&missingTokenModifiers != 0 { - missingProps = append(missingProps, "tokenModifiers") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Semantic tokens options to support deltas for full documents @@ -20165,109 +6236,26 @@ type SemanticTokensFullDelta struct { var _ json.UnmarshalerFrom = (*SemanticTokensFullDelta)(nil) func (s *SemanticTokensFullDelta) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"delta"`: - if dec.PeekKind() == 'n' { - return errNull("delta") - } - if err := json.UnmarshalDecode(dec, &s.Delta); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // A text document identifier to optionally denote a specific version of a text document. type OptionalVersionedTextDocumentIdentifier struct { // The text document's uri. - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` // The version number of this document. If a versioned text document identifier // is sent from the server to the client and the file is not open in the editor // (the server has not received an open notification before) the server can send // `null` to indicate that the version is unknown and the content on disk is the // truth (as specified with document content ownership). - Version IntegerOrNull `json:"version"` + Version IntegerOrNull `json:"version" lsp:"required"` } var _ json.UnmarshalerFrom = (*OptionalVersionedTextDocumentIdentifier)(nil) func (s *OptionalVersionedTextDocumentIdentifier) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - missingVersion - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"version"`: - missing &^= missingVersion - if err := json.UnmarshalDecode(dec, &s.Version); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - if missing&missingVersion != 0 { - missingProps = append(missingProps, "version") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A special text edit with an additional change annotation. @@ -20276,81 +6264,20 @@ func (s *OptionalVersionedTextDocumentIdentifier) UnmarshalJSONFrom(dec *json.De type AnnotatedTextEdit struct { // The range of the text document to be manipulated. To insert // text into a document create a range where start === end. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The string to be inserted. For delete operations use an // empty string. - NewText string `json:"newText"` + NewText string `json:"newText" lsp:"required"` // The actual identifier of the change annotation - AnnotationId string `json:"annotationId"` + AnnotationId string `json:"annotationId" lsp:"required"` } var _ json.UnmarshalerFrom = (*AnnotatedTextEdit)(nil) func (s *AnnotatedTextEdit) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - missingNewText - missingAnnotationId - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"newText"`: - missing &^= missingNewText - if err := json.UnmarshalDecode(dec, &s.NewText); err != nil { - return err - } - case `"annotationId"`: - missing &^= missingAnnotationId - if err := json.UnmarshalDecode(dec, &s.AnnotationId); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingNewText != 0 { - missingProps = append(missingProps, "newText") - } - if missing&missingAnnotationId != 0 { - missingProps = append(missingProps, "annotationId") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // An interactive text edit. @@ -20358,10 +6285,10 @@ func (s *AnnotatedTextEdit) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.18.0 type SnippetTextEdit struct { // The range of the text document to be manipulated. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The snippet to be inserted. - Snippet *StringValue `json:"snippet"` + Snippet *StringValue `json:"snippet" lsp:"required"` // The actual identifier of the snippet edit. AnnotationId *string `json:"annotationId,omitzero"` @@ -20370,136 +6297,24 @@ type SnippetTextEdit struct { var _ json.UnmarshalerFrom = (*SnippetTextEdit)(nil) func (s *SnippetTextEdit) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - missingSnippet - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"snippet"`: - missing &^= missingSnippet - if dec.PeekKind() == 'n' { - return errNull("snippet") - } - if err := json.UnmarshalDecode(dec, &s.Snippet); err != nil { - return err - } - case `"annotationId"`: - if dec.PeekKind() == 'n' { - return errNull("annotationId") - } - if err := json.UnmarshalDecode(dec, &s.AnnotationId); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingSnippet != 0 { - missingProps = append(missingProps, "snippet") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A generic resource operation. type ResourceOperation struct { // The resource operation kind. - Kind string `json:"kind"` - - // An optional annotation identifier describing the operation. - // - // Since: 3.16.0 - AnnotationId *string `json:"annotationId,omitzero"` -} - -var _ json.UnmarshalerFrom = (*ResourceOperation)(nil) - -func (s *ResourceOperation) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"annotationId"`: - if dec.PeekKind() == 'n' { - return errNull("annotationId") - } - if err := json.UnmarshalDecode(dec, &s.AnnotationId); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + Kind string `json:"kind" lsp:"required"` - if _, err := dec.ReadToken(); err != nil { - return err - } + // An optional annotation identifier describing the operation. + // + // Since: 3.16.0 + AnnotationId *string `json:"annotationId,omitzero"` +} - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - return errMissing(missingProps) - } +var _ json.UnmarshalerFrom = (*ResourceOperation)(nil) - return nil +func (s *ResourceOperation) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Options to create a file. @@ -20514,45 +6329,7 @@ type CreateFileOptions struct { var _ json.UnmarshalerFrom = (*CreateFileOptions)(nil) func (s *CreateFileOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"overwrite"`: - if dec.PeekKind() == 'n' { - return errNull("overwrite") - } - if err := json.UnmarshalDecode(dec, &s.Overwrite); err != nil { - return err - } - case `"ignoreIfExists"`: - if dec.PeekKind() == 'n' { - return errNull("ignoreIfExists") - } - if err := json.UnmarshalDecode(dec, &s.IgnoreIfExists); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Rename file options @@ -20567,45 +6344,7 @@ type RenameFileOptions struct { var _ json.UnmarshalerFrom = (*RenameFileOptions)(nil) func (s *RenameFileOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"overwrite"`: - if dec.PeekKind() == 'n' { - return errNull("overwrite") - } - if err := json.UnmarshalDecode(dec, &s.Overwrite); err != nil { - return err - } - case `"ignoreIfExists"`: - if dec.PeekKind() == 'n' { - return errNull("ignoreIfExists") - } - if err := json.UnmarshalDecode(dec, &s.IgnoreIfExists); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Delete file options @@ -20620,45 +6359,7 @@ type DeleteFileOptions struct { var _ json.UnmarshalerFrom = (*DeleteFileOptions)(nil) func (s *DeleteFileOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"recursive"`: - if dec.PeekKind() == 'n' { - return errNull("recursive") - } - if err := json.UnmarshalDecode(dec, &s.Recursive); err != nil { - return err - } - case `"ignoreIfNotExists"`: - if dec.PeekKind() == 'n' { - return errNull("ignoreIfNotExists") - } - if err := json.UnmarshalDecode(dec, &s.IgnoreIfNotExists); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // A pattern to describe in which file operation requests or notifications @@ -20673,7 +6374,7 @@ type FileOperationPattern struct { // - `{}` to group sub patterns into an OR expression. (e.g. `**​ .{ts,js}` matches all TypeScript and JavaScript files) // - `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …) // - `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`) - Glob string `json:"glob"` + Glob string `json:"glob" lsp:"required"` // Whether to match files or folders with this pattern. // @@ -20687,64 +6388,51 @@ type FileOperationPattern struct { var _ json.UnmarshalerFrom = (*FileOperationPattern)(nil) func (s *FileOperationPattern) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingGlob uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 + return unmarshalStruct(s, dec) +} - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } +// A diagnostic report with a full set of problems. +// +// Since: 3.17.0 +type FullDocumentDiagnosticReport struct { + // A full document diagnostic report. + Kind StringLiteralFull `json:"kind" lsp:"required"` - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"glob"`: - missing &^= missingGlob - if err := json.UnmarshalDecode(dec, &s.Glob); err != nil { - return err - } - case `"matches"`: - if dec.PeekKind() == 'n' { - return errNull("matches") - } - if err := json.UnmarshalDecode(dec, &s.Matches); err != nil { - return err - } - case `"options"`: - if dec.PeekKind() == 'n' { - return errNull("options") - } - if err := json.UnmarshalDecode(dec, &s.Options); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + // An optional result id. If provided it will + // be sent on the next diagnostic request for the + // same document. + ResultId *string `json:"resultId,omitzero"` - if _, err := dec.ReadToken(); err != nil { - return err - } + // The actual items. + Items []*Diagnostic `json:"items" lsp:"required"` +} - if missing != 0 { - var missingProps []string - if missing&missingGlob != 0 { - missingProps = append(missingProps, "glob") - } - return errMissing(missingProps) - } +var _ json.UnmarshalerFrom = (*FullDocumentDiagnosticReport)(nil) - return nil +func (s *FullDocumentDiagnosticReport) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) +} + +// A diagnostic report indicating that the last returned +// report is still accurate. +// +// Since: 3.17.0 +type UnchangedDocumentDiagnosticReport struct { + // A document diagnostic report indicating + // no changes to the last result. A server can + // only return `unchanged` if result ids are + // provided. + Kind StringLiteralUnchanged `json:"kind" lsp:"required"` + + // A result id which will be sent on the next + // diagnostic request for the same document. + ResultId string `json:"resultId" lsp:"required"` +} + +var _ json.UnmarshalerFrom = (*UnchangedDocumentDiagnosticReport)(nil) + +func (s *UnchangedDocumentDiagnosticReport) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // A full document diagnostic report for a workspace diagnostic result. @@ -20752,7 +6440,7 @@ func (s *FileOperationPattern) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.17.0 type WorkspaceFullDocumentDiagnosticReport struct { // A full document diagnostic report. - Kind StringLiteralFull `json:"kind"` + Kind StringLiteralFull `json:"kind" lsp:"required"` // An optional result id. If provided it will // be sent on the next diagnostic request for the @@ -20760,100 +6448,20 @@ type WorkspaceFullDocumentDiagnosticReport struct { ResultId *string `json:"resultId,omitzero"` // The actual items. - Items []*Diagnostic `json:"items"` + Items []*Diagnostic `json:"items" lsp:"required"` // The URI for which diagnostic information is reported. - Uri DocumentUri `json:"uri"` + Uri DocumentUri `json:"uri" lsp:"required"` // The version number for which the diagnostics are reported. // If the document is not marked as open `null` can be provided. - Version IntegerOrNull `json:"version"` + Version IntegerOrNull `json:"version" lsp:"required"` } var _ json.UnmarshalerFrom = (*WorkspaceFullDocumentDiagnosticReport)(nil) func (s *WorkspaceFullDocumentDiagnosticReport) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - missingItems - missingUri - missingVersion - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"resultId"`: - if dec.PeekKind() == 'n' { - return errNull("resultId") - } - if err := json.UnmarshalDecode(dec, &s.ResultId); err != nil { - return err - } - case `"items"`: - missing &^= missingItems - if dec.PeekKind() == 'n' { - return errNull("items") - } - if err := json.UnmarshalDecode(dec, &s.Items); err != nil { - return err - } - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"version"`: - missing &^= missingVersion - if err := json.UnmarshalDecode(dec, &s.Version); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingItems != 0 { - missingProps = append(missingProps, "items") - } - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - if missing&missingVersion != 0 { - missingProps = append(missingProps, "version") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // An unchanged document diagnostic report for a workspace diagnostic result. @@ -20861,97 +6469,27 @@ func (s *WorkspaceFullDocumentDiagnosticReport) UnmarshalJSONFrom(dec *json.Deco // Since: 3.17.0 type WorkspaceUnchangedDocumentDiagnosticReport struct { // A document diagnostic report indicating - // no changes to the last result. A server can - // only return `unchanged` if result ids are - // provided. - Kind StringLiteralUnchanged `json:"kind"` - - // A result id which will be sent on the next - // diagnostic request for the same document. - ResultId string `json:"resultId"` - - // The URI for which diagnostic information is reported. - Uri DocumentUri `json:"uri"` - - // The version number for which the diagnostics are reported. - // If the document is not marked as open `null` can be provided. - Version IntegerOrNull `json:"version"` -} - -var _ json.UnmarshalerFrom = (*WorkspaceUnchangedDocumentDiagnosticReport)(nil) - -func (s *WorkspaceUnchangedDocumentDiagnosticReport) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - missingResultId - missingUri - missingVersion - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } + // no changes to the last result. A server can + // only return `unchanged` if result ids are + // provided. + Kind StringLiteralUnchanged `json:"kind" lsp:"required"` - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"resultId"`: - missing &^= missingResultId - if err := json.UnmarshalDecode(dec, &s.ResultId); err != nil { - return err - } - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"version"`: - missing &^= missingVersion - if err := json.UnmarshalDecode(dec, &s.Version); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + // A result id which will be sent on the next + // diagnostic request for the same document. + ResultId string `json:"resultId" lsp:"required"` - if _, err := dec.ReadToken(); err != nil { - return err - } + // The URI for which diagnostic information is reported. + Uri DocumentUri `json:"uri" lsp:"required"` - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingResultId != 0 { - missingProps = append(missingProps, "resultId") - } - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - if missing&missingVersion != 0 { - missingProps = append(missingProps, "version") - } - return errMissing(missingProps) - } + // The version number for which the diagnostics are reported. + // If the document is not marked as open `null` can be provided. + Version IntegerOrNull `json:"version" lsp:"required"` +} - return nil +var _ json.UnmarshalerFrom = (*WorkspaceUnchangedDocumentDiagnosticReport)(nil) + +func (s *WorkspaceUnchangedDocumentDiagnosticReport) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Describes the currently selected completion item. @@ -20959,68 +6497,16 @@ func (s *WorkspaceUnchangedDocumentDiagnosticReport) UnmarshalJSONFrom(dec *json // Since: 3.18.0 type SelectedCompletionInfo struct { // The range that will be replaced if this completion item is accepted. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The text the range will be replaced with if this completion is accepted. - Text string `json:"text"` + Text string `json:"text" lsp:"required"` } var _ json.UnmarshalerFrom = (*SelectedCompletionInfo)(nil) func (s *SelectedCompletionInfo) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - missingText - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"text"`: - missing &^= missingText - if err := json.UnmarshalDecode(dec, &s.Text); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingText != 0 { - missingProps = append(missingProps, "text") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Information about the client @@ -21030,7 +6516,7 @@ func (s *SelectedCompletionInfo) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.18.0 ClientInfo type name added. type ClientInfo struct { // The name of the client as defined by the client. - Name string `json:"name"` + Name string `json:"name" lsp:"required"` // The client's version as defined by the client. Version *string `json:"version,omitzero"` @@ -21039,57 +6525,7 @@ type ClientInfo struct { var _ json.UnmarshalerFrom = (*ClientInfo)(nil) func (s *ClientInfo) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingName uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"name"`: - missing &^= missingName - if err := json.UnmarshalDecode(dec, &s.Name); err != nil { - return err - } - case `"version"`: - if dec.PeekKind() == 'n' { - return errNull("version") - } - if err := json.UnmarshalDecode(dec, &s.Version); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingName != 0 { - missingProps = append(missingProps, "name") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Defines the capabilities provided by the client. @@ -21130,101 +6566,7 @@ type ClientCapabilities struct { var _ json.UnmarshalerFrom = (*ClientCapabilities)(nil) func (s *ClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workspace"`: - if dec.PeekKind() == 'n' { - return errNull("workspace") - } - if err := json.UnmarshalDecode(dec, &s.Workspace); err != nil { - return err - } - case `"textDocument"`: - if dec.PeekKind() == 'n' { - return errNull("textDocument") - } - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"window"`: - if dec.PeekKind() == 'n' { - return errNull("window") - } - if err := json.UnmarshalDecode(dec, &s.Window); err != nil { - return err - } - case `"general"`: - if dec.PeekKind() == 'n' { - return errNull("general") - } - if err := json.UnmarshalDecode(dec, &s.General); err != nil { - return err - } - case `"experimental"`: - if dec.PeekKind() == 'n' { - return errNull("experimental") - } - if err := json.UnmarshalDecode(dec, &s.Experimental); err != nil { - return err - } - case `"_vs_supportsVisualStudioExtensions"`: - if dec.PeekKind() == 'n' { - return errNull("_vs_supportsVisualStudioExtensions") - } - if err := json.UnmarshalDecode(dec, &s.VSSupportsVisualStudioExtensions); err != nil { - return err - } - case `"_vs_supportedSnippetVersion"`: - if dec.PeekKind() == 'n' { - return errNull("_vs_supportedSnippetVersion") - } - if err := json.UnmarshalDecode(dec, &s.VSSupportedSnippetVersion); err != nil { - return err - } - case `"_vs_supportsNotIncludingTextInTextDocumentDidOpen"`: - if dec.PeekKind() == 'n' { - return errNull("_vs_supportsNotIncludingTextInTextDocumentDidOpen") - } - if err := json.UnmarshalDecode(dec, &s.VSSupportsNotIncludingTextInTextDocumentDidOpen); err != nil { - return err - } - case `"_vs_supportsIconExtensions"`: - if dec.PeekKind() == 'n' { - return errNull("_vs_supportsIconExtensions") - } - if err := json.UnmarshalDecode(dec, &s.VSSupportsIconExtensions); err != nil { - return err - } - case `"_vs_supportsDiagnosticRequests"`: - if dec.PeekKind() == 'n' { - return errNull("_vs_supportsDiagnosticRequests") - } - if err := json.UnmarshalDecode(dec, &s.VSSupportsDiagnosticRequests); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } type TextDocumentSyncOptions struct { @@ -21252,66 +6594,7 @@ type TextDocumentSyncOptions struct { var _ json.UnmarshalerFrom = (*TextDocumentSyncOptions)(nil) func (s *TextDocumentSyncOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"openClose"`: - if dec.PeekKind() == 'n' { - return errNull("openClose") - } - if err := json.UnmarshalDecode(dec, &s.OpenClose); err != nil { - return err - } - case `"change"`: - if dec.PeekKind() == 'n' { - return errNull("change") - } - if err := json.UnmarshalDecode(dec, &s.Change); err != nil { - return err - } - case `"willSave"`: - if dec.PeekKind() == 'n' { - return errNull("willSave") - } - if err := json.UnmarshalDecode(dec, &s.WillSave); err != nil { - return err - } - case `"willSaveWaitUntil"`: - if dec.PeekKind() == 'n' { - return errNull("willSaveWaitUntil") - } - if err := json.UnmarshalDecode(dec, &s.WillSaveWaitUntil); err != nil { - return err - } - case `"save"`: - if dec.PeekKind() == 'n' { - return errNull("save") - } - if err := json.UnmarshalDecode(dec, &s.Save); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Defines workspace specific capabilities of the server. @@ -21336,59 +6619,14 @@ type WorkspaceOptions struct { var _ json.UnmarshalerFrom = (*WorkspaceOptions)(nil) -func (s *WorkspaceOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workspaceFolders"`: - if dec.PeekKind() == 'n' { - return errNull("workspaceFolders") - } - if err := json.UnmarshalDecode(dec, &s.WorkspaceFolders); err != nil { - return err - } - case `"fileOperations"`: - if dec.PeekKind() == 'n' { - return errNull("fileOperations") - } - if err := json.UnmarshalDecode(dec, &s.FileOperations); err != nil { - return err - } - case `"textDocumentContent"`: - if dec.PeekKind() == 'n' { - return errNull("textDocumentContent") - } - if err := json.UnmarshalDecode(dec, &s.TextDocumentContent); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil +func (s *WorkspaceOptions) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Since: 3.18.0 type TextDocumentContentChangePartial struct { // The range of the document that changed. - Range Range `json:"range"` + Range Range `json:"range" lsp:"required"` // The optional length of the range that got replaced. // @@ -21396,127 +6634,25 @@ type TextDocumentContentChangePartial struct { RangeLength *uint32 `json:"rangeLength,omitzero"` // The new text for the provided range. - Text string `json:"text"` + Text string `json:"text" lsp:"required"` } var _ json.UnmarshalerFrom = (*TextDocumentContentChangePartial)(nil) func (s *TextDocumentContentChangePartial) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRange uint = 1 << iota - missingText - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - missing &^= missingRange - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"rangeLength"`: - if dec.PeekKind() == 'n' { - return errNull("rangeLength") - } - if err := json.UnmarshalDecode(dec, &s.RangeLength); err != nil { - return err - } - case `"text"`: - missing &^= missingText - if err := json.UnmarshalDecode(dec, &s.Text); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRange != 0 { - missingProps = append(missingProps, "range") - } - if missing&missingText != 0 { - missingProps = append(missingProps, "text") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 type TextDocumentContentChangeWholeDocument struct { // The new text of the whole document. - Text string `json:"text"` + Text string `json:"text" lsp:"required"` } var _ json.UnmarshalerFrom = (*TextDocumentContentChangeWholeDocument)(nil) func (s *TextDocumentContentChangeWholeDocument) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingText uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"text"`: - missing &^= missingText - if err := json.UnmarshalDecode(dec, &s.Text); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingText != 0 { - missingProps = append(missingProps, "text") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Structure to capture a description for an error code. @@ -21524,56 +6660,13 @@ func (s *TextDocumentContentChangeWholeDocument) UnmarshalJSONFrom(dec *json.Dec // Since: 3.16.0 type CodeDescription struct { // An URI to open with more information about the diagnostic error. - Href URI `json:"href"` + Href URI `json:"href" lsp:"required"` } var _ json.UnmarshalerFrom = (*CodeDescription)(nil) func (s *CodeDescription) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingHref uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"href"`: - missing &^= missingHref - if err := json.UnmarshalDecode(dec, &s.Href); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingHref != 0 { - missingProps = append(missingProps, "href") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Represents a related message and source code location for a diagnostic. This should be @@ -21581,135 +6674,31 @@ func (s *CodeDescription) UnmarshalJSONFrom(dec *json.Decoder) error { // a symbol in a scope. type DiagnosticRelatedInformation struct { // The location of this related diagnostic information. - Location Location `json:"location"` + Location Location `json:"location" lsp:"required"` // The message of this related diagnostic information. - Message string `json:"message"` + Message string `json:"message" lsp:"required"` } var _ json.UnmarshalerFrom = (*DiagnosticRelatedInformation)(nil) func (s *DiagnosticRelatedInformation) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingLocation uint = 1 << iota - missingMessage - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"location"`: - missing &^= missingLocation - if err := json.UnmarshalDecode(dec, &s.Location); err != nil { - return err - } - case `"message"`: - missing &^= missingMessage - if err := json.UnmarshalDecode(dec, &s.Message); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingLocation != 0 { - missingProps = append(missingProps, "location") - } - if missing&missingMessage != 0 { - missingProps = append(missingProps, "message") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Edit range variant that includes ranges for insert and replace operations. // // Since: 3.18.0 type EditRangeWithInsertReplace struct { - Insert Range `json:"insert"` + Insert Range `json:"insert" lsp:"required"` - Replace Range `json:"replace"` + Replace Range `json:"replace" lsp:"required"` } var _ json.UnmarshalerFrom = (*EditRangeWithInsertReplace)(nil) func (s *EditRangeWithInsertReplace) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingInsert uint = 1 << iota - missingReplace - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"insert"`: - missing &^= missingInsert - if err := json.UnmarshalDecode(dec, &s.Insert); err != nil { - return err - } - case `"replace"`: - missing &^= missingReplace - if err := json.UnmarshalDecode(dec, &s.Replace); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingInsert != 0 { - missingProps = append(missingProps, "insert") - } - if missing&missingReplace != 0 { - missingProps = append(missingProps, "replace") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 @@ -21724,106 +6713,23 @@ type ServerCompletionItemOptions struct { var _ json.UnmarshalerFrom = (*ServerCompletionItemOptions)(nil) -func (s *ServerCompletionItemOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"labelDetailsSupport"`: - if dec.PeekKind() == 'n' { - return errNull("labelDetailsSupport") - } - if err := json.UnmarshalDecode(dec, &s.LabelDetailsSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil -} - -// Since: 3.18.0 -// -// Deprecated: use MarkupContent instead. -type MarkedStringWithLanguage struct { - Language string `json:"language"` - - Value string `json:"value"` -} - -var _ json.UnmarshalerFrom = (*MarkedStringWithLanguage)(nil) - -func (s *MarkedStringWithLanguage) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingLanguage uint = 1 << iota - missingValue - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"language"`: - missing &^= missingLanguage - if err := json.UnmarshalDecode(dec, &s.Language); err != nil { - return err - } - case `"value"`: - missing &^= missingValue - if err := json.UnmarshalDecode(dec, &s.Value); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } +func (s *ServerCompletionItemOptions) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) +} - if _, err := dec.ReadToken(); err != nil { - return err - } +// Since: 3.18.0 +// +// Deprecated: use MarkupContent instead. +type MarkedStringWithLanguage struct { + Language string `json:"language" lsp:"required"` - if missing != 0 { - var missingProps []string - if missing&missingLanguage != 0 { - missingProps = append(missingProps, "language") - } - if missing&missingValue != 0 { - missingProps = append(missingProps, "value") - } - return errMissing(missingProps) - } + Value string `json:"value" lsp:"required"` +} - return nil +var _ json.UnmarshalerFrom = (*MarkedStringWithLanguage)(nil) + +func (s *MarkedStringWithLanguage) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Represents a parameter of a callable-signature. A parameter can @@ -21841,7 +6747,7 @@ type ParameterInformation struct { // // *Note*: a label of type string should be a substring of its containing signature label. // Its intended use case is to highlight the parameter label part in the `SignatureInformation.label`. - Label StringOrTuple `json:"label"` + Label StringOrTuple `json:"label" lsp:"required"` // The human-readable doc-comment of this parameter. Will be shown // in the UI but can be omitted. @@ -21851,57 +6757,7 @@ type ParameterInformation struct { var _ json.UnmarshalerFrom = (*ParameterInformation)(nil) func (s *ParameterInformation) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingLabel uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"label"`: - missing &^= missingLabel - if err := json.UnmarshalDecode(dec, &s.Label); err != nil { - return err - } - case `"documentation"`: - if dec.PeekKind() == 'n' { - return errNull("documentation") - } - if err := json.UnmarshalDecode(dec, &s.Documentation); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingLabel != 0 { - missingProps = append(missingProps, "label") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Documentation for a class of code actions. @@ -21913,73 +6769,18 @@ type CodeActionKindDocumentation struct { // If the kind is generic, such as `CodeActionKind.Refactor`, the documentation will be shown whenever any // refactorings are returned. If the kind if more specific, such as `CodeActionKind.RefactorExtract`, the // documentation will only be shown when extract refactoring code actions are returned. - Kind CodeActionKind `json:"kind"` + Kind CodeActionKind `json:"kind" lsp:"required"` // Command that is ued to display the documentation to the user. // // The title of this documentation code action is taken from Command.title - Command *Command `json:"command"` + Command *Command `json:"command" lsp:"required"` } var _ json.UnmarshalerFrom = (*CodeActionKindDocumentation)(nil) func (s *CodeActionKindDocumentation) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - missingCommand - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"command"`: - missing &^= missingCommand - if dec.PeekKind() == 'n' { - return errNull("command") - } - if err := json.UnmarshalDecode(dec, &s.Command); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingCommand != 0 { - missingProps = append(missingProps, "command") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Matching options for the file operation pattern. @@ -21993,38 +6794,7 @@ type FileOperationPatternOptions struct { var _ json.UnmarshalerFrom = (*FileOperationPatternOptions)(nil) func (s *FileOperationPatternOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"ignoreCase"`: - if dec.PeekKind() == 'n' { - return errNull("ignoreCase") - } - if err := json.UnmarshalDecode(dec, &s.IgnoreCase); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Workspace specific client capabilities. @@ -22066,185 +6836,49 @@ type WorkspaceClientCapabilities struct { SemanticTokens *SemanticTokensWorkspaceClientCapabilities `json:"semanticTokens,omitzero"` // Capabilities specific to the code lens requests scoped to the - // workspace. - // - // Since: 3.16.0. - CodeLens *CodeLensWorkspaceClientCapabilities `json:"codeLens,omitzero"` - - // The client has support for file notifications/requests for user operations on files. - // - // Since 3.16.0 - FileOperations *FileOperationClientCapabilities `json:"fileOperations,omitzero"` - - // Capabilities specific to the inline values requests scoped to the - // workspace. - // - // Since: 3.17.0. - InlineValue *InlineValueWorkspaceClientCapabilities `json:"inlineValue,omitzero"` - - // Capabilities specific to the inlay hint requests scoped to the - // workspace. - // - // Since: 3.17.0. - InlayHint *InlayHintWorkspaceClientCapabilities `json:"inlayHint,omitzero"` - - // Capabilities specific to the diagnostic requests scoped to the - // workspace. - // - // Since: 3.17.0. - Diagnostics *DiagnosticWorkspaceClientCapabilities `json:"diagnostics,omitzero"` - - // Capabilities specific to the folding range requests scoped to the workspace. - // - // Since: 3.18.0 - FoldingRange *FoldingRangeWorkspaceClientCapabilities `json:"foldingRange,omitzero"` - - // Capabilities specific to the `workspace/textDocumentContent` request. - // - // Since: 3.18.0 - TextDocumentContent *TextDocumentContentClientCapabilities `json:"textDocumentContent,omitzero"` -} - -var _ json.UnmarshalerFrom = (*WorkspaceClientCapabilities)(nil) - -func (s *WorkspaceClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"applyEdit"`: - if dec.PeekKind() == 'n' { - return errNull("applyEdit") - } - if err := json.UnmarshalDecode(dec, &s.ApplyEdit); err != nil { - return err - } - case `"workspaceEdit"`: - if dec.PeekKind() == 'n' { - return errNull("workspaceEdit") - } - if err := json.UnmarshalDecode(dec, &s.WorkspaceEdit); err != nil { - return err - } - case `"didChangeConfiguration"`: - if dec.PeekKind() == 'n' { - return errNull("didChangeConfiguration") - } - if err := json.UnmarshalDecode(dec, &s.DidChangeConfiguration); err != nil { - return err - } - case `"didChangeWatchedFiles"`: - if dec.PeekKind() == 'n' { - return errNull("didChangeWatchedFiles") - } - if err := json.UnmarshalDecode(dec, &s.DidChangeWatchedFiles); err != nil { - return err - } - case `"symbol"`: - if dec.PeekKind() == 'n' { - return errNull("symbol") - } - if err := json.UnmarshalDecode(dec, &s.Symbol); err != nil { - return err - } - case `"executeCommand"`: - if dec.PeekKind() == 'n' { - return errNull("executeCommand") - } - if err := json.UnmarshalDecode(dec, &s.ExecuteCommand); err != nil { - return err - } - case `"workspaceFolders"`: - if dec.PeekKind() == 'n' { - return errNull("workspaceFolders") - } - if err := json.UnmarshalDecode(dec, &s.WorkspaceFolders); err != nil { - return err - } - case `"configuration"`: - if dec.PeekKind() == 'n' { - return errNull("configuration") - } - if err := json.UnmarshalDecode(dec, &s.Configuration); err != nil { - return err - } - case `"semanticTokens"`: - if dec.PeekKind() == 'n' { - return errNull("semanticTokens") - } - if err := json.UnmarshalDecode(dec, &s.SemanticTokens); err != nil { - return err - } - case `"codeLens"`: - if dec.PeekKind() == 'n' { - return errNull("codeLens") - } - if err := json.UnmarshalDecode(dec, &s.CodeLens); err != nil { - return err - } - case `"fileOperations"`: - if dec.PeekKind() == 'n' { - return errNull("fileOperations") - } - if err := json.UnmarshalDecode(dec, &s.FileOperations); err != nil { - return err - } - case `"inlineValue"`: - if dec.PeekKind() == 'n' { - return errNull("inlineValue") - } - if err := json.UnmarshalDecode(dec, &s.InlineValue); err != nil { - return err - } - case `"inlayHint"`: - if dec.PeekKind() == 'n' { - return errNull("inlayHint") - } - if err := json.UnmarshalDecode(dec, &s.InlayHint); err != nil { - return err - } - case `"diagnostics"`: - if dec.PeekKind() == 'n' { - return errNull("diagnostics") - } - if err := json.UnmarshalDecode(dec, &s.Diagnostics); err != nil { - return err - } - case `"foldingRange"`: - if dec.PeekKind() == 'n' { - return errNull("foldingRange") - } - if err := json.UnmarshalDecode(dec, &s.FoldingRange); err != nil { - return err - } - case `"textDocumentContent"`: - if dec.PeekKind() == 'n' { - return errNull("textDocumentContent") - } - if err := json.UnmarshalDecode(dec, &s.TextDocumentContent); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + // workspace. + // + // Since: 3.16.0. + CodeLens *CodeLensWorkspaceClientCapabilities `json:"codeLens,omitzero"` - if _, err := dec.ReadToken(); err != nil { - return err - } + // The client has support for file notifications/requests for user operations on files. + // + // Since 3.16.0 + FileOperations *FileOperationClientCapabilities `json:"fileOperations,omitzero"` - return nil + // Capabilities specific to the inline values requests scoped to the + // workspace. + // + // Since: 3.17.0. + InlineValue *InlineValueWorkspaceClientCapabilities `json:"inlineValue,omitzero"` + + // Capabilities specific to the inlay hint requests scoped to the + // workspace. + // + // Since: 3.17.0. + InlayHint *InlayHintWorkspaceClientCapabilities `json:"inlayHint,omitzero"` + + // Capabilities specific to the diagnostic requests scoped to the + // workspace. + // + // Since: 3.17.0. + Diagnostics *DiagnosticWorkspaceClientCapabilities `json:"diagnostics,omitzero"` + + // Capabilities specific to the folding range requests scoped to the workspace. + // + // Since: 3.18.0 + FoldingRange *FoldingRangeWorkspaceClientCapabilities `json:"foldingRange,omitzero"` + + // Capabilities specific to the `workspace/textDocumentContent` request. + // + // Since: 3.18.0 + TextDocumentContent *TextDocumentContentClientCapabilities `json:"textDocumentContent,omitzero"` +} + +var _ json.UnmarshalerFrom = (*WorkspaceClientCapabilities)(nil) + +func (s *WorkspaceClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Text document specific client capabilities. @@ -22382,255 +7016,7 @@ type TextDocumentClientCapabilities struct { var _ json.UnmarshalerFrom = (*TextDocumentClientCapabilities)(nil) func (s *TextDocumentClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"synchronization"`: - if dec.PeekKind() == 'n' { - return errNull("synchronization") - } - if err := json.UnmarshalDecode(dec, &s.Synchronization); err != nil { - return err - } - case `"filters"`: - if dec.PeekKind() == 'n' { - return errNull("filters") - } - if err := json.UnmarshalDecode(dec, &s.Filters); err != nil { - return err - } - case `"completion"`: - if dec.PeekKind() == 'n' { - return errNull("completion") - } - if err := json.UnmarshalDecode(dec, &s.Completion); err != nil { - return err - } - case `"hover"`: - if dec.PeekKind() == 'n' { - return errNull("hover") - } - if err := json.UnmarshalDecode(dec, &s.Hover); err != nil { - return err - } - case `"signatureHelp"`: - if dec.PeekKind() == 'n' { - return errNull("signatureHelp") - } - if err := json.UnmarshalDecode(dec, &s.SignatureHelp); err != nil { - return err - } - case `"declaration"`: - if dec.PeekKind() == 'n' { - return errNull("declaration") - } - if err := json.UnmarshalDecode(dec, &s.Declaration); err != nil { - return err - } - case `"definition"`: - if dec.PeekKind() == 'n' { - return errNull("definition") - } - if err := json.UnmarshalDecode(dec, &s.Definition); err != nil { - return err - } - case `"typeDefinition"`: - if dec.PeekKind() == 'n' { - return errNull("typeDefinition") - } - if err := json.UnmarshalDecode(dec, &s.TypeDefinition); err != nil { - return err - } - case `"implementation"`: - if dec.PeekKind() == 'n' { - return errNull("implementation") - } - if err := json.UnmarshalDecode(dec, &s.Implementation); err != nil { - return err - } - case `"references"`: - if dec.PeekKind() == 'n' { - return errNull("references") - } - if err := json.UnmarshalDecode(dec, &s.References); err != nil { - return err - } - case `"documentHighlight"`: - if dec.PeekKind() == 'n' { - return errNull("documentHighlight") - } - if err := json.UnmarshalDecode(dec, &s.DocumentHighlight); err != nil { - return err - } - case `"documentSymbol"`: - if dec.PeekKind() == 'n' { - return errNull("documentSymbol") - } - if err := json.UnmarshalDecode(dec, &s.DocumentSymbol); err != nil { - return err - } - case `"codeAction"`: - if dec.PeekKind() == 'n' { - return errNull("codeAction") - } - if err := json.UnmarshalDecode(dec, &s.CodeAction); err != nil { - return err - } - case `"codeLens"`: - if dec.PeekKind() == 'n' { - return errNull("codeLens") - } - if err := json.UnmarshalDecode(dec, &s.CodeLens); err != nil { - return err - } - case `"documentLink"`: - if dec.PeekKind() == 'n' { - return errNull("documentLink") - } - if err := json.UnmarshalDecode(dec, &s.DocumentLink); err != nil { - return err - } - case `"colorProvider"`: - if dec.PeekKind() == 'n' { - return errNull("colorProvider") - } - if err := json.UnmarshalDecode(dec, &s.ColorProvider); err != nil { - return err - } - case `"formatting"`: - if dec.PeekKind() == 'n' { - return errNull("formatting") - } - if err := json.UnmarshalDecode(dec, &s.Formatting); err != nil { - return err - } - case `"rangeFormatting"`: - if dec.PeekKind() == 'n' { - return errNull("rangeFormatting") - } - if err := json.UnmarshalDecode(dec, &s.RangeFormatting); err != nil { - return err - } - case `"onTypeFormatting"`: - if dec.PeekKind() == 'n' { - return errNull("onTypeFormatting") - } - if err := json.UnmarshalDecode(dec, &s.OnTypeFormatting); err != nil { - return err - } - case `"rename"`: - if dec.PeekKind() == 'n' { - return errNull("rename") - } - if err := json.UnmarshalDecode(dec, &s.Rename); err != nil { - return err - } - case `"foldingRange"`: - if dec.PeekKind() == 'n' { - return errNull("foldingRange") - } - if err := json.UnmarshalDecode(dec, &s.FoldingRange); err != nil { - return err - } - case `"selectionRange"`: - if dec.PeekKind() == 'n' { - return errNull("selectionRange") - } - if err := json.UnmarshalDecode(dec, &s.SelectionRange); err != nil { - return err - } - case `"publishDiagnostics"`: - if dec.PeekKind() == 'n' { - return errNull("publishDiagnostics") - } - if err := json.UnmarshalDecode(dec, &s.PublishDiagnostics); err != nil { - return err - } - case `"callHierarchy"`: - if dec.PeekKind() == 'n' { - return errNull("callHierarchy") - } - if err := json.UnmarshalDecode(dec, &s.CallHierarchy); err != nil { - return err - } - case `"semanticTokens"`: - if dec.PeekKind() == 'n' { - return errNull("semanticTokens") - } - if err := json.UnmarshalDecode(dec, &s.SemanticTokens); err != nil { - return err - } - case `"linkedEditingRange"`: - if dec.PeekKind() == 'n' { - return errNull("linkedEditingRange") - } - if err := json.UnmarshalDecode(dec, &s.LinkedEditingRange); err != nil { - return err - } - case `"moniker"`: - if dec.PeekKind() == 'n' { - return errNull("moniker") - } - if err := json.UnmarshalDecode(dec, &s.Moniker); err != nil { - return err - } - case `"typeHierarchy"`: - if dec.PeekKind() == 'n' { - return errNull("typeHierarchy") - } - if err := json.UnmarshalDecode(dec, &s.TypeHierarchy); err != nil { - return err - } - case `"inlineValue"`: - if dec.PeekKind() == 'n' { - return errNull("inlineValue") - } - if err := json.UnmarshalDecode(dec, &s.InlineValue); err != nil { - return err - } - case `"inlayHint"`: - if dec.PeekKind() == 'n' { - return errNull("inlayHint") - } - if err := json.UnmarshalDecode(dec, &s.InlayHint); err != nil { - return err - } - case `"diagnostic"`: - if dec.PeekKind() == 'n' { - return errNull("diagnostic") - } - if err := json.UnmarshalDecode(dec, &s.Diagnostic); err != nil { - return err - } - case `"inlineCompletion"`: - if dec.PeekKind() == 'n' { - return errNull("inlineCompletion") - } - if err := json.UnmarshalDecode(dec, &s.InlineCompletion); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } type WindowClientCapabilities struct { @@ -22659,52 +7045,7 @@ type WindowClientCapabilities struct { var _ json.UnmarshalerFrom = (*WindowClientCapabilities)(nil) func (s *WindowClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"showMessage"`: - if dec.PeekKind() == 'n' { - return errNull("showMessage") - } - if err := json.UnmarshalDecode(dec, &s.ShowMessage); err != nil { - return err - } - case `"showDocument"`: - if dec.PeekKind() == 'n' { - return errNull("showDocument") - } - if err := json.UnmarshalDecode(dec, &s.ShowDocument); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // General client capabilities. @@ -22727,85 +7068,33 @@ type GeneralClientCapabilities struct { // Client capabilities specific to the client's markdown parser. // // Since: 3.16.0 - Markdown *MarkdownClientCapabilities `json:"markdown,omitzero"` - - // The position encodings supported by the client. Client and server - // have to agree on the same position encoding to ensure that offsets - // (e.g. character position in a line) are interpreted the same on both - // sides. - // - // To keep the protocol backwards compatible the following applies: if - // the value 'utf-16' is missing from the array of position encodings - // servers can assume that the client supports UTF-16. UTF-16 is - // therefore a mandatory encoding. - // - // If omitted it defaults to ['utf-16']. - // - // Implementation considerations: since the conversion from one encoding - // into another requires the content of the file / line the conversion - // is best done where the file is read which is usually on the server - // side. - // - // Since: 3.17.0 - PositionEncodings *[]PositionEncodingKind `json:"positionEncodings,omitzero"` -} - -var _ json.UnmarshalerFrom = (*GeneralClientCapabilities)(nil) - -func (s *GeneralClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"staleRequestSupport"`: - if dec.PeekKind() == 'n' { - return errNull("staleRequestSupport") - } - if err := json.UnmarshalDecode(dec, &s.StaleRequestSupport); err != nil { - return err - } - case `"regularExpressions"`: - if dec.PeekKind() == 'n' { - return errNull("regularExpressions") - } - if err := json.UnmarshalDecode(dec, &s.RegularExpressions); err != nil { - return err - } - case `"markdown"`: - if dec.PeekKind() == 'n' { - return errNull("markdown") - } - if err := json.UnmarshalDecode(dec, &s.Markdown); err != nil { - return err - } - case `"positionEncodings"`: - if dec.PeekKind() == 'n' { - return errNull("positionEncodings") - } - if err := json.UnmarshalDecode(dec, &s.PositionEncodings); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + Markdown *MarkdownClientCapabilities `json:"markdown,omitzero"` - if _, err := dec.ReadToken(); err != nil { - return err - } + // The position encodings supported by the client. Client and server + // have to agree on the same position encoding to ensure that offsets + // (e.g. character position in a line) are interpreted the same on both + // sides. + // + // To keep the protocol backwards compatible the following applies: if + // the value 'utf-16' is missing from the array of position encodings + // servers can assume that the client supports UTF-16. UTF-16 is + // therefore a mandatory encoding. + // + // If omitted it defaults to ['utf-16']. + // + // Implementation considerations: since the conversion from one encoding + // into another requires the content of the file / line the conversion + // is best done where the file is read which is usually on the server + // side. + // + // Since: 3.17.0 + PositionEncodings *[]PositionEncodingKind `json:"positionEncodings,omitzero"` +} - return nil +var _ json.UnmarshalerFrom = (*GeneralClientCapabilities)(nil) + +func (s *GeneralClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } type WorkspaceFoldersServerCapabilities struct { @@ -22825,45 +7114,7 @@ type WorkspaceFoldersServerCapabilities struct { var _ json.UnmarshalerFrom = (*WorkspaceFoldersServerCapabilities)(nil) func (s *WorkspaceFoldersServerCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"supported"`: - if dec.PeekKind() == 'n' { - return errNull("supported") - } - if err := json.UnmarshalDecode(dec, &s.Supported); err != nil { - return err - } - case `"changeNotifications"`: - if dec.PeekKind() == 'n' { - return errNull("changeNotifications") - } - if err := json.UnmarshalDecode(dec, &s.ChangeNotifications); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Options for notifications/requests for user operations on files. @@ -22892,73 +7143,7 @@ type FileOperationOptions struct { var _ json.UnmarshalerFrom = (*FileOperationOptions)(nil) func (s *FileOperationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"didCreate"`: - if dec.PeekKind() == 'n' { - return errNull("didCreate") - } - if err := json.UnmarshalDecode(dec, &s.DidCreate); err != nil { - return err - } - case `"willCreate"`: - if dec.PeekKind() == 'n' { - return errNull("willCreate") - } - if err := json.UnmarshalDecode(dec, &s.WillCreate); err != nil { - return err - } - case `"didRename"`: - if dec.PeekKind() == 'n' { - return errNull("didRename") - } - if err := json.UnmarshalDecode(dec, &s.DidRename); err != nil { - return err - } - case `"willRename"`: - if dec.PeekKind() == 'n' { - return errNull("willRename") - } - if err := json.UnmarshalDecode(dec, &s.WillRename); err != nil { - return err - } - case `"didDelete"`: - if dec.PeekKind() == 'n' { - return errNull("didDelete") - } - if err := json.UnmarshalDecode(dec, &s.DidDelete); err != nil { - return err - } - case `"willDelete"`: - if dec.PeekKind() == 'n' { - return errNull("willDelete") - } - if err := json.UnmarshalDecode(dec, &s.WillDelete); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // A relative pattern is a helper to construct glob patterns that are matched @@ -22969,68 +7154,16 @@ func (s *FileOperationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { type RelativePattern struct { // A workspace folder or a base URI to which this pattern will be matched // against relatively. - BaseUri WorkspaceFolderOrURI `json:"baseUri"` + BaseUri WorkspaceFolderOrURI `json:"baseUri" lsp:"required"` // The actual glob pattern; - Pattern string `json:"pattern"` + Pattern string `json:"pattern" lsp:"required"` } var _ json.UnmarshalerFrom = (*RelativePattern)(nil) func (s *RelativePattern) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingBaseUri uint = 1 << iota - missingPattern - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"baseUri"`: - missing &^= missingBaseUri - if err := json.UnmarshalDecode(dec, &s.BaseUri); err != nil { - return err - } - case `"pattern"`: - missing &^= missingPattern - if err := json.UnmarshalDecode(dec, &s.Pattern); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingBaseUri != 0 { - missingProps = append(missingProps, "baseUri") - } - if missing&missingPattern != 0 { - missingProps = append(missingProps, "pattern") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A document filter where `language` is required field. @@ -23038,7 +7171,7 @@ func (s *RelativePattern) UnmarshalJSONFrom(dec *json.Decoder) error { // Since: 3.18.0 type TextDocumentFilterLanguage struct { // A language id, like `typescript`. - Language string `json:"language"` + Language string `json:"language" lsp:"required"` // A Uri scheme, like `file` or `untitled`. Scheme *string `json:"scheme,omitzero"` @@ -23054,64 +7187,7 @@ type TextDocumentFilterLanguage struct { var _ json.UnmarshalerFrom = (*TextDocumentFilterLanguage)(nil) func (s *TextDocumentFilterLanguage) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingLanguage uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"language"`: - missing &^= missingLanguage - if err := json.UnmarshalDecode(dec, &s.Language); err != nil { - return err - } - case `"scheme"`: - if dec.PeekKind() == 'n' { - return errNull("scheme") - } - if err := json.UnmarshalDecode(dec, &s.Scheme); err != nil { - return err - } - case `"pattern"`: - if dec.PeekKind() == 'n' { - return errNull("pattern") - } - if err := json.UnmarshalDecode(dec, &s.Pattern); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingLanguage != 0 { - missingProps = append(missingProps, "language") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A document filter where `scheme` is required field. @@ -23122,7 +7198,7 @@ type TextDocumentFilterScheme struct { Language *string `json:"language,omitzero"` // A Uri scheme, like `file` or `untitled`. - Scheme string `json:"scheme"` + Scheme string `json:"scheme" lsp:"required"` // A glob pattern, like **​ .{ts,js}. See TextDocumentFilter for examples. // @@ -23135,64 +7211,7 @@ type TextDocumentFilterScheme struct { var _ json.UnmarshalerFrom = (*TextDocumentFilterScheme)(nil) func (s *TextDocumentFilterScheme) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingScheme uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"language"`: - if dec.PeekKind() == 'n' { - return errNull("language") - } - if err := json.UnmarshalDecode(dec, &s.Language); err != nil { - return err - } - case `"scheme"`: - missing &^= missingScheme - if err := json.UnmarshalDecode(dec, &s.Scheme); err != nil { - return err - } - case `"pattern"`: - if dec.PeekKind() == 'n' { - return errNull("pattern") - } - if err := json.UnmarshalDecode(dec, &s.Pattern); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingScheme != 0 { - missingProps = append(missingProps, "scheme") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A document filter where `pattern` is required field. @@ -23202,78 +7221,21 @@ type TextDocumentFilterPattern struct { // A language id, like `typescript`. Language *string `json:"language,omitzero"` - // A Uri scheme, like `file` or `untitled`. - Scheme *string `json:"scheme,omitzero"` - - // A glob pattern, like **​ .{ts,js}. See TextDocumentFilter for examples. - // - // Since: 3.18.0 - support for relative patterns. Whether clients support - // relative patterns depends on the client capability - // `textDocuments.filters.relativePatternSupport`. - Pattern PatternOrRelativePattern `json:"pattern"` -} - -var _ json.UnmarshalerFrom = (*TextDocumentFilterPattern)(nil) - -func (s *TextDocumentFilterPattern) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingPattern uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"language"`: - if dec.PeekKind() == 'n' { - return errNull("language") - } - if err := json.UnmarshalDecode(dec, &s.Language); err != nil { - return err - } - case `"scheme"`: - if dec.PeekKind() == 'n' { - return errNull("scheme") - } - if err := json.UnmarshalDecode(dec, &s.Scheme); err != nil { - return err - } - case `"pattern"`: - missing &^= missingPattern - if err := json.UnmarshalDecode(dec, &s.Pattern); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + // A Uri scheme, like `file` or `untitled`. + Scheme *string `json:"scheme,omitzero"` - if _, err := dec.ReadToken(); err != nil { - return err - } + // A glob pattern, like **​ .{ts,js}. See TextDocumentFilter for examples. + // + // Since: 3.18.0 - support for relative patterns. Whether clients support + // relative patterns depends on the client capability + // `textDocuments.filters.relativePatternSupport`. + Pattern PatternOrRelativePattern `json:"pattern" lsp:"required"` +} - if missing != 0 { - var missingProps []string - if missing&missingPattern != 0 { - missingProps = append(missingProps, "pattern") - } - return errMissing(missingProps) - } +var _ json.UnmarshalerFrom = (*TextDocumentFilterPattern)(nil) - return nil +func (s *TextDocumentFilterPattern) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } type WorkspaceEditClientCapabilities struct { @@ -23321,80 +7283,7 @@ type WorkspaceEditClientCapabilities struct { var _ json.UnmarshalerFrom = (*WorkspaceEditClientCapabilities)(nil) func (s *WorkspaceEditClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentChanges"`: - if dec.PeekKind() == 'n' { - return errNull("documentChanges") - } - if err := json.UnmarshalDecode(dec, &s.DocumentChanges); err != nil { - return err - } - case `"resourceOperations"`: - if dec.PeekKind() == 'n' { - return errNull("resourceOperations") - } - if err := json.UnmarshalDecode(dec, &s.ResourceOperations); err != nil { - return err - } - case `"failureHandling"`: - if dec.PeekKind() == 'n' { - return errNull("failureHandling") - } - if err := json.UnmarshalDecode(dec, &s.FailureHandling); err != nil { - return err - } - case `"normalizesLineEndings"`: - if dec.PeekKind() == 'n' { - return errNull("normalizesLineEndings") - } - if err := json.UnmarshalDecode(dec, &s.NormalizesLineEndings); err != nil { - return err - } - case `"changeAnnotationSupport"`: - if dec.PeekKind() == 'n' { - return errNull("changeAnnotationSupport") - } - if err := json.UnmarshalDecode(dec, &s.ChangeAnnotationSupport); err != nil { - return err - } - case `"metadataSupport"`: - if dec.PeekKind() == 'n' { - return errNull("metadataSupport") - } - if err := json.UnmarshalDecode(dec, &s.MetadataSupport); err != nil { - return err - } - case `"snippetEditSupport"`: - if dec.PeekKind() == 'n' { - return errNull("snippetEditSupport") - } - if err := json.UnmarshalDecode(dec, &s.SnippetEditSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } type DidChangeConfigurationClientCapabilities struct { @@ -23405,38 +7294,7 @@ type DidChangeConfigurationClientCapabilities struct { var _ json.UnmarshalerFrom = (*DidChangeConfigurationClientCapabilities)(nil) func (s *DidChangeConfigurationClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } type DidChangeWatchedFilesClientCapabilities struct { @@ -23455,45 +7313,7 @@ type DidChangeWatchedFilesClientCapabilities struct { var _ json.UnmarshalerFrom = (*DidChangeWatchedFilesClientCapabilities)(nil) func (s *DidChangeWatchedFilesClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"relativePatternSupport"`: - if dec.PeekKind() == 'n' { - return errNull("relativePatternSupport") - } - if err := json.UnmarshalDecode(dec, &s.RelativePatternSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client capabilities for a WorkspaceSymbolRequest. @@ -23521,151 +7341,37 @@ type WorkspaceSymbolClientCapabilities struct { var _ json.UnmarshalerFrom = (*WorkspaceSymbolClientCapabilities)(nil) func (s *WorkspaceSymbolClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"symbolKind"`: - if dec.PeekKind() == 'n' { - return errNull("symbolKind") - } - if err := json.UnmarshalDecode(dec, &s.SymbolKind); err != nil { - return err - } - case `"tagSupport"`: - if dec.PeekKind() == 'n' { - return errNull("tagSupport") - } - if err := json.UnmarshalDecode(dec, &s.TagSupport); err != nil { - return err - } - case `"resolveSupport"`: - if dec.PeekKind() == 'n' { - return errNull("resolveSupport") - } - if err := json.UnmarshalDecode(dec, &s.ResolveSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // The client capabilities of a ExecuteCommandRequest. -type ExecuteCommandClientCapabilities struct { - // Execute command supports dynamic registration. - DynamicRegistration *bool `json:"dynamicRegistration,omitzero"` -} - -var _ json.UnmarshalerFrom = (*ExecuteCommandClientCapabilities)(nil) - -func (s *ExecuteCommandClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil -} - -// Since: 3.16.0 -type SemanticTokensWorkspaceClientCapabilities struct { - // Whether the client implementation supports a refresh request sent from - // the server to the client. - // - // Note that this event is global and will force the client to refresh all - // semantic tokens currently shown. It should be used with absolute care - // and is useful for situation where a server for example detects a project - // wide change that requires such a calculation. - RefreshSupport *bool `json:"refreshSupport,omitzero"` -} - -var _ json.UnmarshalerFrom = (*SemanticTokensWorkspaceClientCapabilities)(nil) - -func (s *SemanticTokensWorkspaceClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"refreshSupport"`: - if dec.PeekKind() == 'n' { - return errNull("refreshSupport") - } - if err := json.UnmarshalDecode(dec, &s.RefreshSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } +type ExecuteCommandClientCapabilities struct { + // Execute command supports dynamic registration. + DynamicRegistration *bool `json:"dynamicRegistration,omitzero"` +} - if _, err := dec.ReadToken(); err != nil { - return err - } +var _ json.UnmarshalerFrom = (*ExecuteCommandClientCapabilities)(nil) - return nil +func (s *ExecuteCommandClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) +} + +// Since: 3.16.0 +type SemanticTokensWorkspaceClientCapabilities struct { + // Whether the client implementation supports a refresh request sent from + // the server to the client. + // + // Note that this event is global and will force the client to refresh all + // semantic tokens currently shown. It should be used with absolute care + // and is useful for situation where a server for example detects a project + // wide change that requires such a calculation. + RefreshSupport *bool `json:"refreshSupport,omitzero"` +} + +var _ json.UnmarshalerFrom = (*SemanticTokensWorkspaceClientCapabilities)(nil) + +func (s *SemanticTokensWorkspaceClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Since: 3.16.0 @@ -23683,38 +7389,7 @@ type CodeLensWorkspaceClientCapabilities struct { var _ json.UnmarshalerFrom = (*CodeLensWorkspaceClientCapabilities)(nil) func (s *CodeLensWorkspaceClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"refreshSupport"`: - if dec.PeekKind() == 'n' { - return errNull("refreshSupport") - } - if err := json.UnmarshalDecode(dec, &s.RefreshSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Capabilities relating to events from file operations by the user in the client. @@ -23749,80 +7424,7 @@ type FileOperationClientCapabilities struct { var _ json.UnmarshalerFrom = (*FileOperationClientCapabilities)(nil) func (s *FileOperationClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"didCreate"`: - if dec.PeekKind() == 'n' { - return errNull("didCreate") - } - if err := json.UnmarshalDecode(dec, &s.DidCreate); err != nil { - return err - } - case `"willCreate"`: - if dec.PeekKind() == 'n' { - return errNull("willCreate") - } - if err := json.UnmarshalDecode(dec, &s.WillCreate); err != nil { - return err - } - case `"didRename"`: - if dec.PeekKind() == 'n' { - return errNull("didRename") - } - if err := json.UnmarshalDecode(dec, &s.DidRename); err != nil { - return err - } - case `"willRename"`: - if dec.PeekKind() == 'n' { - return errNull("willRename") - } - if err := json.UnmarshalDecode(dec, &s.WillRename); err != nil { - return err - } - case `"didDelete"`: - if dec.PeekKind() == 'n' { - return errNull("didDelete") - } - if err := json.UnmarshalDecode(dec, &s.DidDelete); err != nil { - return err - } - case `"willDelete"`: - if dec.PeekKind() == 'n' { - return errNull("willDelete") - } - if err := json.UnmarshalDecode(dec, &s.WillDelete); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client workspace capabilities specific to inline values. @@ -23842,38 +7444,7 @@ type InlineValueWorkspaceClientCapabilities struct { var _ json.UnmarshalerFrom = (*InlineValueWorkspaceClientCapabilities)(nil) func (s *InlineValueWorkspaceClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"refreshSupport"`: - if dec.PeekKind() == 'n' { - return errNull("refreshSupport") - } - if err := json.UnmarshalDecode(dec, &s.RefreshSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client workspace capabilities specific to inlay hints. @@ -23893,38 +7464,7 @@ type InlayHintWorkspaceClientCapabilities struct { var _ json.UnmarshalerFrom = (*InlayHintWorkspaceClientCapabilities)(nil) func (s *InlayHintWorkspaceClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"refreshSupport"`: - if dec.PeekKind() == 'n' { - return errNull("refreshSupport") - } - if err := json.UnmarshalDecode(dec, &s.RefreshSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Workspace client capabilities specific to diagnostic pull requests. @@ -23944,38 +7484,7 @@ type DiagnosticWorkspaceClientCapabilities struct { var _ json.UnmarshalerFrom = (*DiagnosticWorkspaceClientCapabilities)(nil) func (s *DiagnosticWorkspaceClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"refreshSupport"`: - if dec.PeekKind() == 'n' { - return errNull("refreshSupport") - } - if err := json.UnmarshalDecode(dec, &s.RefreshSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client workspace capabilities specific to folding ranges @@ -23989,91 +7498,29 @@ type FoldingRangeWorkspaceClientCapabilities struct { // folding ranges currently shown. It should be used with absolute care and is // useful for situation where a server for example detects a project wide // change that requires such a calculation. - // - // Since: 3.18.0 - RefreshSupport *bool `json:"refreshSupport,omitzero"` -} - -var _ json.UnmarshalerFrom = (*FoldingRangeWorkspaceClientCapabilities)(nil) - -func (s *FoldingRangeWorkspaceClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"refreshSupport"`: - if dec.PeekKind() == 'n' { - return errNull("refreshSupport") - } - if err := json.UnmarshalDecode(dec, &s.RefreshSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil -} - -// Client capabilities for a text document content provider. -// -// Since: 3.18.0 -type TextDocumentContentClientCapabilities struct { - // Text document content provider supports dynamic registration. - DynamicRegistration *bool `json:"dynamicRegistration,omitzero"` -} - -var _ json.UnmarshalerFrom = (*TextDocumentContentClientCapabilities)(nil) - -func (s *TextDocumentContentClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + // + // Since: 3.18.0 + RefreshSupport *bool `json:"refreshSupport,omitzero"` +} - if _, err := dec.ReadToken(); err != nil { - return err - } +var _ json.UnmarshalerFrom = (*FoldingRangeWorkspaceClientCapabilities)(nil) - return nil +func (s *FoldingRangeWorkspaceClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) +} + +// Client capabilities for a text document content provider. +// +// Since: 3.18.0 +type TextDocumentContentClientCapabilities struct { + // Text document content provider supports dynamic registration. + DynamicRegistration *bool `json:"dynamicRegistration,omitzero"` +} + +var _ json.UnmarshalerFrom = (*TextDocumentContentClientCapabilities)(nil) + +func (s *TextDocumentContentClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } type TextDocumentSyncClientCapabilities struct { @@ -24095,59 +7542,7 @@ type TextDocumentSyncClientCapabilities struct { var _ json.UnmarshalerFrom = (*TextDocumentSyncClientCapabilities)(nil) func (s *TextDocumentSyncClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"willSave"`: - if dec.PeekKind() == 'n' { - return errNull("willSave") - } - if err := json.UnmarshalDecode(dec, &s.WillSave); err != nil { - return err - } - case `"willSaveWaitUntil"`: - if dec.PeekKind() == 'n' { - return errNull("willSaveWaitUntil") - } - if err := json.UnmarshalDecode(dec, &s.WillSaveWaitUntil); err != nil { - return err - } - case `"didSave"`: - if dec.PeekKind() == 'n' { - return errNull("didSave") - } - if err := json.UnmarshalDecode(dec, &s.DidSave); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } type TextDocumentFilterClientCapabilities struct { @@ -24160,38 +7555,7 @@ type TextDocumentFilterClientCapabilities struct { var _ json.UnmarshalerFrom = (*TextDocumentFilterClientCapabilities)(nil) func (s *TextDocumentFilterClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"relativePatternSupport"`: - if dec.PeekKind() == 'n' { - return errNull("relativePatternSupport") - } - if err := json.UnmarshalDecode(dec, &s.RelativePatternSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Completion client capabilities @@ -24227,73 +7591,7 @@ type CompletionClientCapabilities struct { var _ json.UnmarshalerFrom = (*CompletionClientCapabilities)(nil) func (s *CompletionClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"completionItem"`: - if dec.PeekKind() == 'n' { - return errNull("completionItem") - } - if err := json.UnmarshalDecode(dec, &s.CompletionItem); err != nil { - return err - } - case `"completionItemKind"`: - if dec.PeekKind() == 'n' { - return errNull("completionItemKind") - } - if err := json.UnmarshalDecode(dec, &s.CompletionItemKind); err != nil { - return err - } - case `"insertTextMode"`: - if dec.PeekKind() == 'n' { - return errNull("insertTextMode") - } - if err := json.UnmarshalDecode(dec, &s.InsertTextMode); err != nil { - return err - } - case `"contextSupport"`: - if dec.PeekKind() == 'n' { - return errNull("contextSupport") - } - if err := json.UnmarshalDecode(dec, &s.ContextSupport); err != nil { - return err - } - case `"completionList"`: - if dec.PeekKind() == 'n' { - return errNull("completionList") - } - if err := json.UnmarshalDecode(dec, &s.CompletionList); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } type HoverClientCapabilities struct { @@ -24308,45 +7606,7 @@ type HoverClientCapabilities struct { var _ json.UnmarshalerFrom = (*HoverClientCapabilities)(nil) func (s *HoverClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"contentFormat"`: - if dec.PeekKind() == 'n' { - return errNull("contentFormat") - } - if err := json.UnmarshalDecode(dec, &s.ContentFormat); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client Capabilities for a SignatureHelpRequest. @@ -24370,52 +7630,7 @@ type SignatureHelpClientCapabilities struct { var _ json.UnmarshalerFrom = (*SignatureHelpClientCapabilities)(nil) func (s *SignatureHelpClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"signatureInformation"`: - if dec.PeekKind() == 'n' { - return errNull("signatureInformation") - } - if err := json.UnmarshalDecode(dec, &s.SignatureInformation); err != nil { - return err - } - case `"contextSupport"`: - if dec.PeekKind() == 'n' { - return errNull("contextSupport") - } - if err := json.UnmarshalDecode(dec, &s.ContextSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.14.0 @@ -24432,45 +7647,7 @@ type DeclarationClientCapabilities struct { var _ json.UnmarshalerFrom = (*DeclarationClientCapabilities)(nil) func (s *DeclarationClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"linkSupport"`: - if dec.PeekKind() == 'n' { - return errNull("linkSupport") - } - if err := json.UnmarshalDecode(dec, &s.LinkSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client Capabilities for a DefinitionRequest. @@ -24484,48 +7661,10 @@ type DefinitionClientCapabilities struct { LinkSupport *bool `json:"linkSupport,omitzero"` } -var _ json.UnmarshalerFrom = (*DefinitionClientCapabilities)(nil) - -func (s *DefinitionClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"linkSupport"`: - if dec.PeekKind() == 'n' { - return errNull("linkSupport") - } - if err := json.UnmarshalDecode(dec, &s.LinkSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } +var _ json.UnmarshalerFrom = (*DefinitionClientCapabilities)(nil) - return nil +func (s *DefinitionClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Since 3.6.0 @@ -24544,45 +7683,7 @@ type TypeDefinitionClientCapabilities struct { var _ json.UnmarshalerFrom = (*TypeDefinitionClientCapabilities)(nil) func (s *TypeDefinitionClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"linkSupport"`: - if dec.PeekKind() == 'n' { - return errNull("linkSupport") - } - if err := json.UnmarshalDecode(dec, &s.LinkSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.6.0 @@ -24601,45 +7702,7 @@ type ImplementationClientCapabilities struct { var _ json.UnmarshalerFrom = (*ImplementationClientCapabilities)(nil) func (s *ImplementationClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"linkSupport"`: - if dec.PeekKind() == 'n' { - return errNull("linkSupport") - } - if err := json.UnmarshalDecode(dec, &s.LinkSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client Capabilities for a ReferencesRequest. @@ -24651,38 +7714,7 @@ type ReferenceClientCapabilities struct { var _ json.UnmarshalerFrom = (*ReferenceClientCapabilities)(nil) func (s *ReferenceClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client Capabilities for a DocumentHighlightRequest. @@ -24694,38 +7726,7 @@ type DocumentHighlightClientCapabilities struct { var _ json.UnmarshalerFrom = (*DocumentHighlightClientCapabilities)(nil) func (s *DocumentHighlightClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client Capabilities for a DocumentSymbolRequest. @@ -24757,66 +7758,7 @@ type DocumentSymbolClientCapabilities struct { var _ json.UnmarshalerFrom = (*DocumentSymbolClientCapabilities)(nil) func (s *DocumentSymbolClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"symbolKind"`: - if dec.PeekKind() == 'n' { - return errNull("symbolKind") - } - if err := json.UnmarshalDecode(dec, &s.SymbolKind); err != nil { - return err - } - case `"hierarchicalDocumentSymbolSupport"`: - if dec.PeekKind() == 'n' { - return errNull("hierarchicalDocumentSymbolSupport") - } - if err := json.UnmarshalDecode(dec, &s.HierarchicalDocumentSymbolSupport); err != nil { - return err - } - case `"tagSupport"`: - if dec.PeekKind() == 'n' { - return errNull("tagSupport") - } - if err := json.UnmarshalDecode(dec, &s.TagSupport); err != nil { - return err - } - case `"labelSupport"`: - if dec.PeekKind() == 'n' { - return errNull("labelSupport") - } - if err := json.UnmarshalDecode(dec, &s.LabelSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // The Client Capabilities of a CodeActionRequest. @@ -24879,150 +7821,25 @@ type CodeActionClientCapabilities struct { var _ json.UnmarshalerFrom = (*CodeActionClientCapabilities)(nil) func (s *CodeActionClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"codeActionLiteralSupport"`: - if dec.PeekKind() == 'n' { - return errNull("codeActionLiteralSupport") - } - if err := json.UnmarshalDecode(dec, &s.CodeActionLiteralSupport); err != nil { - return err - } - case `"isPreferredSupport"`: - if dec.PeekKind() == 'n' { - return errNull("isPreferredSupport") - } - if err := json.UnmarshalDecode(dec, &s.IsPreferredSupport); err != nil { - return err - } - case `"disabledSupport"`: - if dec.PeekKind() == 'n' { - return errNull("disabledSupport") - } - if err := json.UnmarshalDecode(dec, &s.DisabledSupport); err != nil { - return err - } - case `"dataSupport"`: - if dec.PeekKind() == 'n' { - return errNull("dataSupport") - } - if err := json.UnmarshalDecode(dec, &s.DataSupport); err != nil { - return err - } - case `"resolveSupport"`: - if dec.PeekKind() == 'n' { - return errNull("resolveSupport") - } - if err := json.UnmarshalDecode(dec, &s.ResolveSupport); err != nil { - return err - } - case `"honorsChangeAnnotations"`: - if dec.PeekKind() == 'n' { - return errNull("honorsChangeAnnotations") - } - if err := json.UnmarshalDecode(dec, &s.HonorsChangeAnnotations); err != nil { - return err - } - case `"documentationSupport"`: - if dec.PeekKind() == 'n' { - return errNull("documentationSupport") - } - if err := json.UnmarshalDecode(dec, &s.DocumentationSupport); err != nil { - return err - } - case `"tagSupport"`: - if dec.PeekKind() == 'n' { - return errNull("tagSupport") - } - if err := json.UnmarshalDecode(dec, &s.TagSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil -} - -// The client capabilities of a CodeLensRequest. -type CodeLensClientCapabilities struct { - // Whether code lens supports dynamic registration. - DynamicRegistration *bool `json:"dynamicRegistration,omitzero"` - - // Whether the client supports resolving additional code lens - // properties via a separate `codeLens/resolve` request. - // - // Since: 3.18.0 - ResolveSupport *ClientCodeLensResolveOptions `json:"resolveSupport,omitzero"` + return unmarshalStruct(s, dec) } -var _ json.UnmarshalerFrom = (*CodeLensClientCapabilities)(nil) - -func (s *CodeLensClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"resolveSupport"`: - if dec.PeekKind() == 'n' { - return errNull("resolveSupport") - } - if err := json.UnmarshalDecode(dec, &s.ResolveSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } +// The client capabilities of a CodeLensRequest. +type CodeLensClientCapabilities struct { + // Whether code lens supports dynamic registration. + DynamicRegistration *bool `json:"dynamicRegistration,omitzero"` - if _, err := dec.ReadToken(); err != nil { - return err - } + // Whether the client supports resolving additional code lens + // properties via a separate `codeLens/resolve` request. + // + // Since: 3.18.0 + ResolveSupport *ClientCodeLensResolveOptions `json:"resolveSupport,omitzero"` +} - return nil +var _ json.UnmarshalerFrom = (*CodeLensClientCapabilities)(nil) + +func (s *CodeLensClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // The client capabilities of a DocumentLinkRequest. @@ -25039,45 +7856,7 @@ type DocumentLinkClientCapabilities struct { var _ json.UnmarshalerFrom = (*DocumentLinkClientCapabilities)(nil) func (s *DocumentLinkClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"tooltipSupport"`: - if dec.PeekKind() == 'n' { - return errNull("tooltipSupport") - } - if err := json.UnmarshalDecode(dec, &s.TooltipSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } type DocumentColorClientCapabilities struct { @@ -25090,38 +7869,7 @@ type DocumentColorClientCapabilities struct { var _ json.UnmarshalerFrom = (*DocumentColorClientCapabilities)(nil) func (s *DocumentColorClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client capabilities of a DocumentFormattingRequest. @@ -25133,38 +7881,7 @@ type DocumentFormattingClientCapabilities struct { var _ json.UnmarshalerFrom = (*DocumentFormattingClientCapabilities)(nil) func (s *DocumentFormattingClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client capabilities of a DocumentRangeFormattingRequest. @@ -25181,45 +7898,7 @@ type DocumentRangeFormattingClientCapabilities struct { var _ json.UnmarshalerFrom = (*DocumentRangeFormattingClientCapabilities)(nil) func (s *DocumentRangeFormattingClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"rangesSupport"`: - if dec.PeekKind() == 'n' { - return errNull("rangesSupport") - } - if err := json.UnmarshalDecode(dec, &s.RangesSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client capabilities of a DocumentOnTypeFormattingRequest. @@ -25231,38 +7910,7 @@ type DocumentOnTypeFormattingClientCapabilities struct { var _ json.UnmarshalerFrom = (*DocumentOnTypeFormattingClientCapabilities)(nil) func (s *DocumentOnTypeFormattingClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } type RenameClientCapabilities struct { @@ -25296,59 +7944,7 @@ type RenameClientCapabilities struct { var _ json.UnmarshalerFrom = (*RenameClientCapabilities)(nil) func (s *RenameClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"prepareSupport"`: - if dec.PeekKind() == 'n' { - return errNull("prepareSupport") - } - if err := json.UnmarshalDecode(dec, &s.PrepareSupport); err != nil { - return err - } - case `"prepareSupportDefaultBehavior"`: - if dec.PeekKind() == 'n' { - return errNull("prepareSupportDefaultBehavior") - } - if err := json.UnmarshalDecode(dec, &s.PrepareSupportDefaultBehavior); err != nil { - return err - } - case `"honorsChangeAnnotations"`: - if dec.PeekKind() == 'n' { - return errNull("honorsChangeAnnotations") - } - if err := json.UnmarshalDecode(dec, &s.HonorsChangeAnnotations); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } type FoldingRangeClientCapabilities struct { @@ -25360,88 +7956,29 @@ type FoldingRangeClientCapabilities struct { // The maximum number of folding ranges that the client prefers to receive // per document. The value serves as a hint, servers are free to follow the - // limit. - RangeLimit *uint32 `json:"rangeLimit,omitzero"` - - // If set, the client signals that it only supports folding complete lines. - // If set, client will ignore specified `startCharacter` and `endCharacter` - // properties in a FoldingRange. - LineFoldingOnly *bool `json:"lineFoldingOnly,omitzero"` - - // Specific options for the folding range kind. - // - // Since: 3.17.0 - FoldingRangeKind *ClientFoldingRangeKindOptions `json:"foldingRangeKind,omitzero"` - - // Specific options for the folding range. - // - // Since: 3.17.0 - FoldingRange *ClientFoldingRangeOptions `json:"foldingRange,omitzero"` -} - -var _ json.UnmarshalerFrom = (*FoldingRangeClientCapabilities)(nil) - -func (s *FoldingRangeClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"rangeLimit"`: - if dec.PeekKind() == 'n' { - return errNull("rangeLimit") - } - if err := json.UnmarshalDecode(dec, &s.RangeLimit); err != nil { - return err - } - case `"lineFoldingOnly"`: - if dec.PeekKind() == 'n' { - return errNull("lineFoldingOnly") - } - if err := json.UnmarshalDecode(dec, &s.LineFoldingOnly); err != nil { - return err - } - case `"foldingRangeKind"`: - if dec.PeekKind() == 'n' { - return errNull("foldingRangeKind") - } - if err := json.UnmarshalDecode(dec, &s.FoldingRangeKind); err != nil { - return err - } - case `"foldingRange"`: - if dec.PeekKind() == 'n' { - return errNull("foldingRange") - } - if err := json.UnmarshalDecode(dec, &s.FoldingRange); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + // limit. + RangeLimit *uint32 `json:"rangeLimit,omitzero"` - if _, err := dec.ReadToken(); err != nil { - return err - } + // If set, the client signals that it only supports folding complete lines. + // If set, client will ignore specified `startCharacter` and `endCharacter` + // properties in a FoldingRange. + LineFoldingOnly *bool `json:"lineFoldingOnly,omitzero"` - return nil + // Specific options for the folding range kind. + // + // Since: 3.17.0 + FoldingRangeKind *ClientFoldingRangeKindOptions `json:"foldingRangeKind,omitzero"` + + // Specific options for the folding range. + // + // Since: 3.17.0 + FoldingRange *ClientFoldingRangeOptions `json:"foldingRange,omitzero"` +} + +var _ json.UnmarshalerFrom = (*FoldingRangeClientCapabilities)(nil) + +func (s *FoldingRangeClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } type SelectionRangeClientCapabilities struct { @@ -25454,38 +7991,7 @@ type SelectionRangeClientCapabilities struct { var _ json.UnmarshalerFrom = (*SelectionRangeClientCapabilities)(nil) func (s *SelectionRangeClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // The publish diagnostic client capabilities. @@ -25521,66 +8027,7 @@ type PublishDiagnosticsClientCapabilities struct { var _ json.UnmarshalerFrom = (*PublishDiagnosticsClientCapabilities)(nil) func (s *PublishDiagnosticsClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"relatedInformation"`: - if dec.PeekKind() == 'n' { - return errNull("relatedInformation") - } - if err := json.UnmarshalDecode(dec, &s.RelatedInformation); err != nil { - return err - } - case `"tagSupport"`: - if dec.PeekKind() == 'n' { - return errNull("tagSupport") - } - if err := json.UnmarshalDecode(dec, &s.TagSupport); err != nil { - return err - } - case `"codeDescriptionSupport"`: - if dec.PeekKind() == 'n' { - return errNull("codeDescriptionSupport") - } - if err := json.UnmarshalDecode(dec, &s.CodeDescriptionSupport); err != nil { - return err - } - case `"dataSupport"`: - if dec.PeekKind() == 'n' { - return errNull("dataSupport") - } - if err := json.UnmarshalDecode(dec, &s.DataSupport); err != nil { - return err - } - case `"versionSupport"`: - if dec.PeekKind() == 'n' { - return errNull("versionSupport") - } - if err := json.UnmarshalDecode(dec, &s.VersionSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.16.0 @@ -25594,38 +8041,7 @@ type CallHierarchyClientCapabilities struct { var _ json.UnmarshalerFrom = (*CallHierarchyClientCapabilities)(nil) func (s *CallHierarchyClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.16.0 @@ -25643,16 +8059,16 @@ type SemanticTokensClientCapabilities struct { // `request.range` are both set to true but the server only provides a // range provider the client might not render a minimap correctly or might // even decide to not show any semantic tokens at all. - Requests *ClientSemanticTokensRequestOptions `json:"requests"` + Requests *ClientSemanticTokensRequestOptions `json:"requests" lsp:"required"` // The token types that the client supports. - TokenTypes []string `json:"tokenTypes"` + TokenTypes []string `json:"tokenTypes" lsp:"required"` // The token modifiers that the client supports. - TokenModifiers []string `json:"tokenModifiers"` + TokenModifiers []string `json:"tokenModifiers" lsp:"required"` // The token formats the clients supports. - Formats []TokenFormat `json:"formats"` + Formats []TokenFormat `json:"formats" lsp:"required"` // Whether the client supports tokens that can overlap each other. OverlappingTokenSupport *bool `json:"overlappingTokenSupport,omitzero"` @@ -25684,124 +8100,7 @@ type SemanticTokensClientCapabilities struct { var _ json.UnmarshalerFrom = (*SemanticTokensClientCapabilities)(nil) func (s *SemanticTokensClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRequests uint = 1 << iota - missingTokenTypes - missingTokenModifiers - missingFormats - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"requests"`: - missing &^= missingRequests - if dec.PeekKind() == 'n' { - return errNull("requests") - } - if err := json.UnmarshalDecode(dec, &s.Requests); err != nil { - return err - } - case `"tokenTypes"`: - missing &^= missingTokenTypes - if dec.PeekKind() == 'n' { - return errNull("tokenTypes") - } - if err := json.UnmarshalDecode(dec, &s.TokenTypes); err != nil { - return err - } - case `"tokenModifiers"`: - missing &^= missingTokenModifiers - if dec.PeekKind() == 'n' { - return errNull("tokenModifiers") - } - if err := json.UnmarshalDecode(dec, &s.TokenModifiers); err != nil { - return err - } - case `"formats"`: - missing &^= missingFormats - if dec.PeekKind() == 'n' { - return errNull("formats") - } - if err := json.UnmarshalDecode(dec, &s.Formats); err != nil { - return err - } - case `"overlappingTokenSupport"`: - if dec.PeekKind() == 'n' { - return errNull("overlappingTokenSupport") - } - if err := json.UnmarshalDecode(dec, &s.OverlappingTokenSupport); err != nil { - return err - } - case `"multilineTokenSupport"`: - if dec.PeekKind() == 'n' { - return errNull("multilineTokenSupport") - } - if err := json.UnmarshalDecode(dec, &s.MultilineTokenSupport); err != nil { - return err - } - case `"serverCancelSupport"`: - if dec.PeekKind() == 'n' { - return errNull("serverCancelSupport") - } - if err := json.UnmarshalDecode(dec, &s.ServerCancelSupport); err != nil { - return err - } - case `"augmentsSyntaxTokens"`: - if dec.PeekKind() == 'n' { - return errNull("augmentsSyntaxTokens") - } - if err := json.UnmarshalDecode(dec, &s.AugmentsSyntaxTokens); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRequests != 0 { - missingProps = append(missingProps, "requests") - } - if missing&missingTokenTypes != 0 { - missingProps = append(missingProps, "tokenTypes") - } - if missing&missingTokenModifiers != 0 { - missingProps = append(missingProps, "tokenModifiers") - } - if missing&missingFormats != 0 { - missingProps = append(missingProps, "formats") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Client capabilities for the linked editing range request. @@ -25812,90 +8111,28 @@ type LinkedEditingRangeClientCapabilities struct { // the client supports the new `(TextDocumentRegistrationOptions & StaticRegistrationOptions)` // return value for the corresponding server capability as well. DynamicRegistration *bool `json:"dynamicRegistration,omitzero"` -} - -var _ json.UnmarshalerFrom = (*LinkedEditingRangeClientCapabilities)(nil) - -func (s *LinkedEditingRangeClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil -} - -// Client capabilities specific to the moniker request. -// -// Since: 3.16.0 -type MonikerClientCapabilities struct { - // Whether moniker supports dynamic registration. If this is set to `true` - // the client supports the new `MonikerRegistrationOptions` return value - // for the corresponding server capability as well. - DynamicRegistration *bool `json:"dynamicRegistration,omitzero"` -} - -var _ json.UnmarshalerFrom = (*MonikerClientCapabilities)(nil) - -func (s *MonikerClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } +} - if _, err := dec.ReadToken(); err != nil { - return err - } +var _ json.UnmarshalerFrom = (*LinkedEditingRangeClientCapabilities)(nil) - return nil +func (s *LinkedEditingRangeClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) +} + +// Client capabilities specific to the moniker request. +// +// Since: 3.16.0 +type MonikerClientCapabilities struct { + // Whether moniker supports dynamic registration. If this is set to `true` + // the client supports the new `MonikerRegistrationOptions` return value + // for the corresponding server capability as well. + DynamicRegistration *bool `json:"dynamicRegistration,omitzero"` +} + +var _ json.UnmarshalerFrom = (*MonikerClientCapabilities)(nil) + +func (s *MonikerClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Since: 3.17.0 @@ -25909,38 +8146,7 @@ type TypeHierarchyClientCapabilities struct { var _ json.UnmarshalerFrom = (*TypeHierarchyClientCapabilities)(nil) func (s *TypeHierarchyClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client capabilities specific to inline values. @@ -25954,38 +8160,7 @@ type InlineValueClientCapabilities struct { var _ json.UnmarshalerFrom = (*InlineValueClientCapabilities)(nil) func (s *InlineValueClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Inlay hint client capabilities. @@ -26003,45 +8178,7 @@ type InlayHintClientCapabilities struct { var _ json.UnmarshalerFrom = (*InlayHintClientCapabilities)(nil) func (s *InlayHintClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"resolveSupport"`: - if dec.PeekKind() == 'n' { - return errNull("resolveSupport") - } - if err := json.UnmarshalDecode(dec, &s.ResolveSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client capabilities specific to diagnostic pull requests. @@ -26086,80 +8223,7 @@ type DiagnosticClientCapabilities struct { var _ json.UnmarshalerFrom = (*DiagnosticClientCapabilities)(nil) func (s *DiagnosticClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"relatedInformation"`: - if dec.PeekKind() == 'n' { - return errNull("relatedInformation") - } - if err := json.UnmarshalDecode(dec, &s.RelatedInformation); err != nil { - return err - } - case `"tagSupport"`: - if dec.PeekKind() == 'n' { - return errNull("tagSupport") - } - if err := json.UnmarshalDecode(dec, &s.TagSupport); err != nil { - return err - } - case `"codeDescriptionSupport"`: - if dec.PeekKind() == 'n' { - return errNull("codeDescriptionSupport") - } - if err := json.UnmarshalDecode(dec, &s.CodeDescriptionSupport); err != nil { - return err - } - case `"dataSupport"`: - if dec.PeekKind() == 'n' { - return errNull("dataSupport") - } - if err := json.UnmarshalDecode(dec, &s.DataSupport); err != nil { - return err - } - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - case `"relatedDocumentSupport"`: - if dec.PeekKind() == 'n' { - return errNull("relatedDocumentSupport") - } - if err := json.UnmarshalDecode(dec, &s.RelatedDocumentSupport); err != nil { - return err - } - case `"markupMessageSupport"`: - if dec.PeekKind() == 'n' { - return errNull("markupMessageSupport") - } - if err := json.UnmarshalDecode(dec, &s.MarkupMessageSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Client capabilities specific to inline completions. @@ -26173,211 +8237,51 @@ type InlineCompletionClientCapabilities struct { var _ json.UnmarshalerFrom = (*InlineCompletionClientCapabilities)(nil) func (s *InlineCompletionClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dynamicRegistration"`: - if dec.PeekKind() == 'n' { - return errNull("dynamicRegistration") - } - if err := json.UnmarshalDecode(dec, &s.DynamicRegistration); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Show message request client capabilities type ShowMessageRequestClientCapabilities struct { // Capabilities specific to the `MessageActionItem` type. - MessageActionItem *ClientShowMessageActionItemOptions `json:"messageActionItem,omitzero"` -} - -var _ json.UnmarshalerFrom = (*ShowMessageRequestClientCapabilities)(nil) - -func (s *ShowMessageRequestClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"messageActionItem"`: - if dec.PeekKind() == 'n' { - return errNull("messageActionItem") - } - if err := json.UnmarshalDecode(dec, &s.MessageActionItem); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil -} - -// Client capabilities for the showDocument request. -// -// Since: 3.16.0 -type ShowDocumentClientCapabilities struct { - // The client has support for the showDocument - // request. - Support bool `json:"support"` -} - -var _ json.UnmarshalerFrom = (*ShowDocumentClientCapabilities)(nil) - -func (s *ShowDocumentClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingSupport uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"support"`: - missing &^= missingSupport - if err := json.UnmarshalDecode(dec, &s.Support); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + MessageActionItem *ClientShowMessageActionItemOptions `json:"messageActionItem,omitzero"` +} - if _, err := dec.ReadToken(); err != nil { - return err - } +var _ json.UnmarshalerFrom = (*ShowMessageRequestClientCapabilities)(nil) - if missing != 0 { - var missingProps []string - if missing&missingSupport != 0 { - missingProps = append(missingProps, "support") - } - return errMissing(missingProps) - } +func (s *ShowMessageRequestClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) +} - return nil +// Client capabilities for the showDocument request. +// +// Since: 3.16.0 +type ShowDocumentClientCapabilities struct { + // The client has support for the showDocument + // request. + Support bool `json:"support" lsp:"required"` +} + +var _ json.UnmarshalerFrom = (*ShowDocumentClientCapabilities)(nil) + +func (s *ShowDocumentClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Since: 3.18.0 type StaleRequestSupportOptions struct { // The client will actively cancel the request. - Cancel bool `json:"cancel"` + Cancel bool `json:"cancel" lsp:"required"` // The list of requests for which the client // will retry the request if it receives a // response with error code `ContentModified` - RetryOnContentModified []string `json:"retryOnContentModified"` + RetryOnContentModified []string `json:"retryOnContentModified" lsp:"required"` } var _ json.UnmarshalerFrom = (*StaleRequestSupportOptions)(nil) func (s *StaleRequestSupportOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingCancel uint = 1 << iota - missingRetryOnContentModified - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"cancel"`: - missing &^= missingCancel - if err := json.UnmarshalDecode(dec, &s.Cancel); err != nil { - return err - } - case `"retryOnContentModified"`: - missing &^= missingRetryOnContentModified - if dec.PeekKind() == 'n' { - return errNull("retryOnContentModified") - } - if err := json.UnmarshalDecode(dec, &s.RetryOnContentModified); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingCancel != 0 { - missingProps = append(missingProps, "cancel") - } - if missing&missingRetryOnContentModified != 0 { - missingProps = append(missingProps, "retryOnContentModified") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Client capabilities specific to regular expressions. @@ -26385,7 +8289,7 @@ func (s *StaleRequestSupportOptions) UnmarshalJSONFrom(dec *json.Decoder) error // Since: 3.16.0 type RegularExpressionsClientCapabilities struct { // The engine's name. - Engine string `json:"engine"` + Engine string `json:"engine" lsp:"required"` // The engine's version. Version *string `json:"version,omitzero"` @@ -26394,57 +8298,7 @@ type RegularExpressionsClientCapabilities struct { var _ json.UnmarshalerFrom = (*RegularExpressionsClientCapabilities)(nil) func (s *RegularExpressionsClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingEngine uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"engine"`: - missing &^= missingEngine - if err := json.UnmarshalDecode(dec, &s.Engine); err != nil { - return err - } - case `"version"`: - if dec.PeekKind() == 'n' { - return errNull("version") - } - if err := json.UnmarshalDecode(dec, &s.Version); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingEngine != 0 { - missingProps = append(missingProps, "engine") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Client capabilities specific to the used markdown parser. @@ -26452,7 +8306,7 @@ func (s *RegularExpressionsClientCapabilities) UnmarshalJSONFrom(dec *json.Decod // Since: 3.16.0 type MarkdownClientCapabilities struct { // The name of the parser. - Parser string `json:"parser"` + Parser string `json:"parser" lsp:"required"` // The version of the parser. Version *string `json:"version,omitzero"` @@ -26467,64 +8321,7 @@ type MarkdownClientCapabilities struct { var _ json.UnmarshalerFrom = (*MarkdownClientCapabilities)(nil) func (s *MarkdownClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingParser uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"parser"`: - missing &^= missingParser - if err := json.UnmarshalDecode(dec, &s.Parser); err != nil { - return err - } - case `"version"`: - if dec.PeekKind() == 'n' { - return errNull("version") - } - if err := json.UnmarshalDecode(dec, &s.Version); err != nil { - return err - } - case `"allowedTags"`: - if dec.PeekKind() == 'n' { - return errNull("allowedTags") - } - if err := json.UnmarshalDecode(dec, &s.AllowedTags); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingParser != 0 { - missingProps = append(missingProps, "parser") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 @@ -26538,38 +8335,7 @@ type ChangeAnnotationsSupportOptions struct { var _ json.UnmarshalerFrom = (*ChangeAnnotationsSupportOptions)(nil) func (s *ChangeAnnotationsSupportOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"groupsOnLabel"`: - if dec.PeekKind() == 'n' { - return errNull("groupsOnLabel") - } - if err := json.UnmarshalDecode(dec, &s.GroupsOnLabel); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 @@ -26577,166 +8343,43 @@ type ClientSymbolKindOptions struct { // The symbol kind values the client supports. When this // property exists the client also guarantees that it will // handle values outside its set gracefully and falls back - // to a default value when unknown. - // - // If this property is not present the client only supports - // the symbol kinds from `File` to `Array` as defined in - // the initial version of the protocol. - ValueSet *[]SymbolKind `json:"valueSet,omitzero"` -} - -var _ json.UnmarshalerFrom = (*ClientSymbolKindOptions)(nil) - -func (s *ClientSymbolKindOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"valueSet"`: - if dec.PeekKind() == 'n' { - return errNull("valueSet") - } - if err := json.UnmarshalDecode(dec, &s.ValueSet); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil -} - -// Since: 3.18.0 -type ClientSymbolTagOptions struct { - // The tags supported by the client. - ValueSet []SymbolTag `json:"valueSet"` -} - -var _ json.UnmarshalerFrom = (*ClientSymbolTagOptions)(nil) - -func (s *ClientSymbolTagOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingValueSet uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"valueSet"`: - missing &^= missingValueSet - if dec.PeekKind() == 'n' { - return errNull("valueSet") - } - if err := json.UnmarshalDecode(dec, &s.ValueSet); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + // to a default value when unknown. + // + // If this property is not present the client only supports + // the symbol kinds from `File` to `Array` as defined in + // the initial version of the protocol. + ValueSet *[]SymbolKind `json:"valueSet,omitzero"` +} - if _, err := dec.ReadToken(); err != nil { - return err - } +var _ json.UnmarshalerFrom = (*ClientSymbolKindOptions)(nil) - if missing != 0 { - var missingProps []string - if missing&missingValueSet != 0 { - missingProps = append(missingProps, "valueSet") - } - return errMissing(missingProps) - } +func (s *ClientSymbolKindOptions) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) +} - return nil +// Since: 3.18.0 +type ClientSymbolTagOptions struct { + // The tags supported by the client. + ValueSet []SymbolTag `json:"valueSet" lsp:"required"` +} + +var _ json.UnmarshalerFrom = (*ClientSymbolTagOptions)(nil) + +func (s *ClientSymbolTagOptions) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Since: 3.18.0 type ClientSymbolResolveOptions struct { // The properties that a client can resolve lazily. Usually // `location.range` - Properties []string `json:"properties"` + Properties []string `json:"properties" lsp:"required"` } var _ json.UnmarshalerFrom = (*ClientSymbolResolveOptions)(nil) func (s *ClientSymbolResolveOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingProperties uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"properties"`: - missing &^= missingProperties - if dec.PeekKind() == 'n' { - return errNull("properties") - } - if err := json.UnmarshalDecode(dec, &s.Properties); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingProperties != 0 { - missingProps = append(missingProps, "properties") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 @@ -26800,101 +8443,7 @@ type ClientCompletionItemOptions struct { var _ json.UnmarshalerFrom = (*ClientCompletionItemOptions)(nil) func (s *ClientCompletionItemOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"snippetSupport"`: - if dec.PeekKind() == 'n' { - return errNull("snippetSupport") - } - if err := json.UnmarshalDecode(dec, &s.SnippetSupport); err != nil { - return err - } - case `"commitCharactersSupport"`: - if dec.PeekKind() == 'n' { - return errNull("commitCharactersSupport") - } - if err := json.UnmarshalDecode(dec, &s.CommitCharactersSupport); err != nil { - return err - } - case `"documentationFormat"`: - if dec.PeekKind() == 'n' { - return errNull("documentationFormat") - } - if err := json.UnmarshalDecode(dec, &s.DocumentationFormat); err != nil { - return err - } - case `"deprecatedSupport"`: - if dec.PeekKind() == 'n' { - return errNull("deprecatedSupport") - } - if err := json.UnmarshalDecode(dec, &s.DeprecatedSupport); err != nil { - return err - } - case `"preselectSupport"`: - if dec.PeekKind() == 'n' { - return errNull("preselectSupport") - } - if err := json.UnmarshalDecode(dec, &s.PreselectSupport); err != nil { - return err - } - case `"tagSupport"`: - if dec.PeekKind() == 'n' { - return errNull("tagSupport") - } - if err := json.UnmarshalDecode(dec, &s.TagSupport); err != nil { - return err - } - case `"insertReplaceSupport"`: - if dec.PeekKind() == 'n' { - return errNull("insertReplaceSupport") - } - if err := json.UnmarshalDecode(dec, &s.InsertReplaceSupport); err != nil { - return err - } - case `"resolveSupport"`: - if dec.PeekKind() == 'n' { - return errNull("resolveSupport") - } - if err := json.UnmarshalDecode(dec, &s.ResolveSupport); err != nil { - return err - } - case `"insertTextModeSupport"`: - if dec.PeekKind() == 'n' { - return errNull("insertTextModeSupport") - } - if err := json.UnmarshalDecode(dec, &s.InsertTextModeSupport); err != nil { - return err - } - case `"labelDetailsSupport"`: - if dec.PeekKind() == 'n' { - return errNull("labelDetailsSupport") - } - if err := json.UnmarshalDecode(dec, &s.LabelDetailsSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 @@ -26913,38 +8462,7 @@ type ClientCompletionItemOptionsKind struct { var _ json.UnmarshalerFrom = (*ClientCompletionItemOptionsKind)(nil) func (s *ClientCompletionItemOptionsKind) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"valueSet"`: - if dec.PeekKind() == 'n' { - return errNull("valueSet") - } - if err := json.UnmarshalDecode(dec, &s.ValueSet); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // The client supports the following `CompletionList` specific @@ -26979,45 +8497,7 @@ type CompletionListCapabilities struct { var _ json.UnmarshalerFrom = (*CompletionListCapabilities)(nil) func (s *CompletionListCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"itemDefaults"`: - if dec.PeekKind() == 'n' { - return errNull("itemDefaults") - } - if err := json.UnmarshalDecode(dec, &s.ItemDefaults); err != nil { - return err - } - case `"applyKindSupport"`: - if dec.PeekKind() == 'n' { - return errNull("applyKindSupport") - } - if err := json.UnmarshalDecode(dec, &s.ApplyKindSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 @@ -27046,292 +8526,56 @@ type ClientSignatureInformationOptions struct { var _ json.UnmarshalerFrom = (*ClientSignatureInformationOptions)(nil) func (s *ClientSignatureInformationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"documentationFormat"`: - if dec.PeekKind() == 'n' { - return errNull("documentationFormat") - } - if err := json.UnmarshalDecode(dec, &s.DocumentationFormat); err != nil { - return err - } - case `"parameterInformation"`: - if dec.PeekKind() == 'n' { - return errNull("parameterInformation") - } - if err := json.UnmarshalDecode(dec, &s.ParameterInformation); err != nil { - return err - } - case `"activeParameterSupport"`: - if dec.PeekKind() == 'n' { - return errNull("activeParameterSupport") - } - if err := json.UnmarshalDecode(dec, &s.ActiveParameterSupport); err != nil { - return err - } - case `"noActiveParameterSupport"`: - if dec.PeekKind() == 'n' { - return errNull("noActiveParameterSupport") - } - if err := json.UnmarshalDecode(dec, &s.NoActiveParameterSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 -type ClientCodeActionLiteralOptions struct { - // The code action kind is support with the following value - // set. - CodeActionKind *ClientCodeActionKindOptions `json:"codeActionKind"` -} - -var _ json.UnmarshalerFrom = (*ClientCodeActionLiteralOptions)(nil) - -func (s *ClientCodeActionLiteralOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingCodeActionKind uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"codeActionKind"`: - missing &^= missingCodeActionKind - if dec.PeekKind() == 'n' { - return errNull("codeActionKind") - } - if err := json.UnmarshalDecode(dec, &s.CodeActionKind); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } +type ClientCodeActionLiteralOptions struct { + // The code action kind is support with the following value + // set. + CodeActionKind *ClientCodeActionKindOptions `json:"codeActionKind" lsp:"required"` +} - if missing != 0 { - var missingProps []string - if missing&missingCodeActionKind != 0 { - missingProps = append(missingProps, "codeActionKind") - } - return errMissing(missingProps) - } +var _ json.UnmarshalerFrom = (*ClientCodeActionLiteralOptions)(nil) - return nil +func (s *ClientCodeActionLiteralOptions) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Since: 3.18.0 type ClientCodeActionResolveOptions struct { // The properties that a client can resolve lazily. - Properties []string `json:"properties"` + Properties []string `json:"properties" lsp:"required"` } var _ json.UnmarshalerFrom = (*ClientCodeActionResolveOptions)(nil) func (s *ClientCodeActionResolveOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingProperties uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"properties"`: - missing &^= missingProperties - if dec.PeekKind() == 'n' { - return errNull("properties") - } - if err := json.UnmarshalDecode(dec, &s.Properties); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingProperties != 0 { - missingProps = append(missingProps, "properties") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 - proposed type CodeActionTagOptions struct { // The tags supported by the client. - ValueSet []CodeActionTag `json:"valueSet"` + ValueSet []CodeActionTag `json:"valueSet" lsp:"required"` } var _ json.UnmarshalerFrom = (*CodeActionTagOptions)(nil) func (s *CodeActionTagOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingValueSet uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"valueSet"`: - missing &^= missingValueSet - if dec.PeekKind() == 'n' { - return errNull("valueSet") - } - if err := json.UnmarshalDecode(dec, &s.ValueSet); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingValueSet != 0 { - missingProps = append(missingProps, "valueSet") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 type ClientCodeLensResolveOptions struct { // The properties that a client can resolve lazily. - Properties []string `json:"properties"` + Properties []string `json:"properties" lsp:"required"` } var _ json.UnmarshalerFrom = (*ClientCodeLensResolveOptions)(nil) func (s *ClientCodeLensResolveOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingProperties uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"properties"`: - missing &^= missingProperties - if dec.PeekKind() == 'n' { - return errNull("properties") - } - if err := json.UnmarshalDecode(dec, &s.Properties); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingProperties != 0 { - missingProps = append(missingProps, "properties") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 @@ -27346,38 +8590,7 @@ type ClientFoldingRangeKindOptions struct { var _ json.UnmarshalerFrom = (*ClientFoldingRangeKindOptions)(nil) func (s *ClientFoldingRangeKindOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"valueSet"`: - if dec.PeekKind() == 'n' { - return errNull("valueSet") - } - if err := json.UnmarshalDecode(dec, &s.ValueSet); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 @@ -27392,38 +8605,7 @@ type ClientFoldingRangeOptions struct { var _ json.UnmarshalerFrom = (*ClientFoldingRangeOptions)(nil) func (s *ClientFoldingRangeOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"collapsedText"`: - if dec.PeekKind() == 'n' { - return errNull("collapsedText") - } - if err := json.UnmarshalDecode(dec, &s.CollapsedText); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // General diagnostics capabilities for pull and push model. @@ -27453,59 +8635,7 @@ type DiagnosticsCapabilities struct { var _ json.UnmarshalerFrom = (*DiagnosticsCapabilities)(nil) func (s *DiagnosticsCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"relatedInformation"`: - if dec.PeekKind() == 'n' { - return errNull("relatedInformation") - } - if err := json.UnmarshalDecode(dec, &s.RelatedInformation); err != nil { - return err - } - case `"tagSupport"`: - if dec.PeekKind() == 'n' { - return errNull("tagSupport") - } - if err := json.UnmarshalDecode(dec, &s.TagSupport); err != nil { - return err - } - case `"codeDescriptionSupport"`: - if dec.PeekKind() == 'n' { - return errNull("codeDescriptionSupport") - } - if err := json.UnmarshalDecode(dec, &s.CodeDescriptionSupport); err != nil { - return err - } - case `"dataSupport"`: - if dec.PeekKind() == 'n' { - return errNull("dataSupport") - } - if err := json.UnmarshalDecode(dec, &s.DataSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 @@ -27517,108 +8647,24 @@ type ClientSemanticTokensRequestOptions struct { // The client will send the `textDocument/semanticTokens/full` request if // the server provides a corresponding handler. Full *BooleanOrClientSemanticTokensRequestFullDelta `json:"full,omitzero"` -} - -var _ json.UnmarshalerFrom = (*ClientSemanticTokensRequestOptions)(nil) - -func (s *ClientSemanticTokensRequestOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"range"`: - if dec.PeekKind() == 'n' { - return errNull("range") - } - if err := json.UnmarshalDecode(dec, &s.Range); err != nil { - return err - } - case `"full"`: - if dec.PeekKind() == 'n' { - return errNull("full") - } - if err := json.UnmarshalDecode(dec, &s.Full); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } +} - return nil +var _ json.UnmarshalerFrom = (*ClientSemanticTokensRequestOptions)(nil) + +func (s *ClientSemanticTokensRequestOptions) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Since: 3.18.0 type ClientInlayHintResolveOptions struct { // The properties that a client can resolve lazily. - Properties []string `json:"properties"` + Properties []string `json:"properties" lsp:"required"` } var _ json.UnmarshalerFrom = (*ClientInlayHintResolveOptions)(nil) func (s *ClientInlayHintResolveOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingProperties uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"properties"`: - missing &^= missingProperties - if dec.PeekKind() == 'n' { - return errNull("properties") - } - if err := json.UnmarshalDecode(dec, &s.Properties); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingProperties != 0 { - missingProps = append(missingProps, "properties") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 @@ -27632,211 +8678,42 @@ type ClientShowMessageActionItemOptions struct { var _ json.UnmarshalerFrom = (*ClientShowMessageActionItemOptions)(nil) func (s *ClientShowMessageActionItemOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"additionalPropertiesSupport"`: - if dec.PeekKind() == 'n' { - return errNull("additionalPropertiesSupport") - } - if err := json.UnmarshalDecode(dec, &s.AdditionalPropertiesSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 type CompletionItemTagOptions struct { // The tags supported by the client. - ValueSet []CompletionItemTag `json:"valueSet"` + ValueSet []CompletionItemTag `json:"valueSet" lsp:"required"` } var _ json.UnmarshalerFrom = (*CompletionItemTagOptions)(nil) func (s *CompletionItemTagOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingValueSet uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"valueSet"`: - missing &^= missingValueSet - if dec.PeekKind() == 'n' { - return errNull("valueSet") - } - if err := json.UnmarshalDecode(dec, &s.ValueSet); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingValueSet != 0 { - missingProps = append(missingProps, "valueSet") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 type ClientCompletionItemResolveOptions struct { // The properties that a client can resolve lazily. - Properties []string `json:"properties"` + Properties []string `json:"properties" lsp:"required"` } var _ json.UnmarshalerFrom = (*ClientCompletionItemResolveOptions)(nil) func (s *ClientCompletionItemResolveOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingProperties uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"properties"`: - missing &^= missingProperties - if dec.PeekKind() == 'n' { - return errNull("properties") - } - if err := json.UnmarshalDecode(dec, &s.Properties); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingProperties != 0 { - missingProps = append(missingProps, "properties") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 type ClientCompletionItemInsertTextModeOptions struct { - ValueSet []InsertTextMode `json:"valueSet"` + ValueSet []InsertTextMode `json:"valueSet" lsp:"required"` } var _ json.UnmarshalerFrom = (*ClientCompletionItemInsertTextModeOptions)(nil) func (s *ClientCompletionItemInsertTextModeOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingValueSet uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"valueSet"`: - missing &^= missingValueSet - if dec.PeekKind() == 'n' { - return errNull("valueSet") - } - if err := json.UnmarshalDecode(dec, &s.ValueSet); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingValueSet != 0 { - missingProps = append(missingProps, "valueSet") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 @@ -27851,157 +8728,34 @@ type ClientSignatureParameterInformationOptions struct { var _ json.UnmarshalerFrom = (*ClientSignatureParameterInformationOptions)(nil) func (s *ClientSignatureParameterInformationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"labelOffsetSupport"`: - if dec.PeekKind() == 'n' { - return errNull("labelOffsetSupport") - } - if err := json.UnmarshalDecode(dec, &s.LabelOffsetSupport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil -} - -// Since: 3.18.0 -type ClientCodeActionKindOptions struct { - // The code action kind values the client supports. When this - // property exists the client also guarantees that it will - // handle values outside its set gracefully and falls back - // to a default value when unknown. - ValueSet []CodeActionKind `json:"valueSet"` + return unmarshalStruct(s, dec) } -var _ json.UnmarshalerFrom = (*ClientCodeActionKindOptions)(nil) - -func (s *ClientCodeActionKindOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingValueSet uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"valueSet"`: - missing &^= missingValueSet - if dec.PeekKind() == 'n' { - return errNull("valueSet") - } - if err := json.UnmarshalDecode(dec, &s.ValueSet); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } +// Since: 3.18.0 +type ClientCodeActionKindOptions struct { + // The code action kind values the client supports. When this + // property exists the client also guarantees that it will + // handle values outside its set gracefully and falls back + // to a default value when unknown. + ValueSet []CodeActionKind `json:"valueSet" lsp:"required"` +} - if missing != 0 { - var missingProps []string - if missing&missingValueSet != 0 { - missingProps = append(missingProps, "valueSet") - } - return errMissing(missingProps) - } +var _ json.UnmarshalerFrom = (*ClientCodeActionKindOptions)(nil) - return nil +func (s *ClientCodeActionKindOptions) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Since: 3.18.0 type ClientDiagnosticsTagOptions struct { // The tags supported by the client. - ValueSet []DiagnosticTag `json:"valueSet"` + ValueSet []DiagnosticTag `json:"valueSet" lsp:"required"` } var _ json.UnmarshalerFrom = (*ClientDiagnosticsTagOptions)(nil) func (s *ClientDiagnosticsTagOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingValueSet uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"valueSet"`: - missing &^= missingValueSet - if dec.PeekKind() == 'n' { - return errNull("valueSet") - } - if err := json.UnmarshalDecode(dec, &s.ValueSet); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingValueSet != 0 { - missingProps = append(missingProps, "valueSet") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Since: 3.18.0 @@ -28014,38 +8768,7 @@ type ClientSemanticTokensRequestFullDelta struct { var _ json.UnmarshalerFrom = (*ClientSemanticTokensRequestFullDelta)(nil) func (s *ClientSemanticTokensRequestFullDelta) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"delta"`: - if dec.PeekKind() == 'n' { - return errNull("delta") - } - if err := json.UnmarshalDecode(dec, &s.Delta); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // InitializationOptions contains user-provided initialization options. @@ -28057,7 +8780,7 @@ type InitializationOptions struct { CodeLensShowLocationsCommandName *string `json:"codeLensShowLocationsCommandName,omitzero"` // userPreferences and/or formatting options if provided at initialization. - UserPreferences *any `json:"userPreferences,omitzero"` + UserPreferences *any `json:"userPreferences,omitzero" lsp:"nullable"` // EnableTelemetry enables sending telemetry events from the server to the client. EnableTelemetry *bool `json:"enableTelemetry,omitzero"` @@ -28069,195 +8792,51 @@ type InitializationOptions struct { var _ json.UnmarshalerFrom = (*InitializationOptions)(nil) func (s *InitializationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"disablePushDiagnostics"`: - if dec.PeekKind() == 'n' { - return errNull("disablePushDiagnostics") - } - if err := json.UnmarshalDecode(dec, &s.DisablePushDiagnostics); err != nil { - return err - } - case `"codeLensShowLocationsCommandName"`: - if dec.PeekKind() == 'n' { - return errNull("codeLensShowLocationsCommandName") - } - if err := json.UnmarshalDecode(dec, &s.CodeLensShowLocationsCommandName); err != nil { - return err - } - case `"userPreferences"`: - if err := json.UnmarshalDecode(dec, &s.UserPreferences); err != nil { - return err - } - case `"enableTelemetry"`: - if dec.PeekKind() == 'n' { - return errNull("enableTelemetry") - } - if err := json.UnmarshalDecode(dec, &s.EnableTelemetry); err != nil { - return err - } - case `"logVerbosity"`: - if dec.PeekKind() == 'n' { - return errNull("logVerbosity") - } - if err := json.UnmarshalDecode(dec, &s.LogVerbosity); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // AutoImportFix contains information about an auto-import suggestion. type AutoImportFix struct { - Kind AutoImportFixKind `json:"kind,omitzero"` + Kind AutoImportFixKind `json:"kind,omitzero" lsp:"nullable"` - Name string `json:"name,omitzero"` + Name string `json:"name,omitzero" lsp:"nullable"` - ImportKind ImportKind `json:"importKind"` + ImportKind ImportKind `json:"importKind" lsp:"required"` - UseRequire bool `json:"useRequire,omitzero"` + UseRequire bool `json:"useRequire,omitzero" lsp:"nullable"` - AddAsTypeOnly AddAsTypeOnly `json:"addAsTypeOnly"` + AddAsTypeOnly AddAsTypeOnly `json:"addAsTypeOnly" lsp:"required"` // The module specifier for this auto-import. - ModuleSpecifier string `json:"moduleSpecifier,omitzero"` + ModuleSpecifier string `json:"moduleSpecifier,omitzero" lsp:"nullable"` // Index of the import to modify when adding to an existing import declaration. - ImportIndex int32 `json:"importIndex"` + ImportIndex int32 `json:"importIndex" lsp:"required"` UsagePosition *Position `json:"usagePosition,omitzero"` - NamespacePrefix string `json:"namespacePrefix,omitzero"` + NamespacePrefix string `json:"namespacePrefix,omitzero" lsp:"nullable"` } var _ json.UnmarshalerFrom = (*AutoImportFix)(nil) func (s *AutoImportFix) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingImportKind uint = 1 << iota - missingAddAsTypeOnly - missingImportIndex - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"name"`: - if err := json.UnmarshalDecode(dec, &s.Name); err != nil { - return err - } - case `"importKind"`: - missing &^= missingImportKind - if err := json.UnmarshalDecode(dec, &s.ImportKind); err != nil { - return err - } - case `"useRequire"`: - if err := json.UnmarshalDecode(dec, &s.UseRequire); err != nil { - return err - } - case `"addAsTypeOnly"`: - missing &^= missingAddAsTypeOnly - if err := json.UnmarshalDecode(dec, &s.AddAsTypeOnly); err != nil { - return err - } - case `"moduleSpecifier"`: - if err := json.UnmarshalDecode(dec, &s.ModuleSpecifier); err != nil { - return err - } - case `"importIndex"`: - missing &^= missingImportIndex - if err := json.UnmarshalDecode(dec, &s.ImportIndex); err != nil { - return err - } - case `"usagePosition"`: - if dec.PeekKind() == 'n' { - return errNull("usagePosition") - } - if err := json.UnmarshalDecode(dec, &s.UsagePosition); err != nil { - return err - } - case `"namespacePrefix"`: - if err := json.UnmarshalDecode(dec, &s.NamespacePrefix); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingImportKind != 0 { - missingProps = append(missingProps, "importKind") - } - if missing&missingAddAsTypeOnly != 0 { - missingProps = append(missingProps, "addAsTypeOnly") - } - if missing&missingImportIndex != 0 { - missingProps = append(missingProps, "importIndex") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // CompletionItemData is preserved on a CompletionItem between CompletionRequest and CompletionResolveRequest. type CompletionItemData struct { // The file name where the completion was requested. - FileName string `json:"fileName,omitzero"` + FileName string `json:"fileName,omitzero" lsp:"nullable"` // The position where the completion was requested. - Position int32 `json:"position,omitzero"` + Position int32 `json:"position,omitzero" lsp:"nullable"` // Special source value for disambiguation. - Source string `json:"source,omitzero"` + Source string `json:"source,omitzero" lsp:"nullable"` // The name of the completion item. - Name string `json:"name,omitzero"` + Name string `json:"name,omitzero" lsp:"nullable"` // Auto-import data for this completion item. AutoImport *AutoImportFix `json:"autoImport,omitzero"` @@ -28266,120 +8845,21 @@ type CompletionItemData struct { var _ json.UnmarshalerFrom = (*CompletionItemData)(nil) func (s *CompletionItemData) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"fileName"`: - if err := json.UnmarshalDecode(dec, &s.FileName); err != nil { - return err - } - case `"position"`: - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"source"`: - if err := json.UnmarshalDecode(dec, &s.Source); err != nil { - return err - } - case `"name"`: - if err := json.UnmarshalDecode(dec, &s.Name); err != nil { - return err - } - case `"autoImport"`: - if dec.PeekKind() == 'n' { - return errNull("autoImport") - } - if err := json.UnmarshalDecode(dec, &s.AutoImport); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil -} - -type CodeLensData struct { - // The kind of the code lens ("references" or "implementations"). - Kind CodeLensKind `json:"kind"` - - // The document in which the code lens and its range are located. - Uri DocumentUri `json:"uri"` -} - -var _ json.UnmarshalerFrom = (*CodeLensData)(nil) - -func (s *CodeLensData) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingKind uint = 1 << iota - missingUri - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"kind"`: - missing &^= missingKind - if err := json.UnmarshalDecode(dec, &s.Kind); err != nil { - return err - } - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + return unmarshalStruct(s, dec) +} - if _, err := dec.ReadToken(); err != nil { - return err - } +type CodeLensData struct { + // The kind of the code lens ("references" or "implementations"). + Kind CodeLensKind `json:"kind" lsp:"required"` - if missing != 0 { - var missingProps []string - if missing&missingKind != 0 { - missingProps = append(missingProps, "kind") - } - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - return errMissing(missingProps) - } + // The document in which the code lens and its range are located. + Uri DocumentUri `json:"uri" lsp:"required"` +} - return nil +var _ json.UnmarshalerFrom = (*CodeLensData)(nil) + +func (s *CodeLensData) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // ExperimentalServerCapabilities contains experimental capabilities under development. @@ -28394,45 +8874,7 @@ type ExperimentalServerCapabilities struct { var _ json.UnmarshalerFrom = (*ExperimentalServerCapabilities)(nil) func (s *ExperimentalServerCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"customSourceDefinitionProvider"`: - if dec.PeekKind() == 'n' { - return errNull("customSourceDefinitionProvider") - } - if err := json.UnmarshalDecode(dec, &s.CustomSourceDefinitionProvider); err != nil { - return err - } - case `"customMultiDocumentHighlightProvider"`: - if dec.PeekKind() == 'n' { - return errNull("customMultiDocumentHighlightProvider") - } - if err := json.UnmarshalDecode(dec, &s.CustomMultiDocumentHighlightProvider); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // ExperimentalClientCapabilities contains experimental capabilities under development. @@ -28444,102 +8886,25 @@ type ExperimentalClientCapabilities struct { var _ json.UnmarshalerFrom = (*ExperimentalClientCapabilities)(nil) func (s *ExperimentalClientCapabilities) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"hoverVerbosityLevel"`: - if dec.PeekKind() == 'n' { - return errNull("hoverVerbosityLevel") - } - if err := json.UnmarshalDecode(dec, &s.HoverVerbosityLevel); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Options for the textDocument/_vs_onAutoInsert provider capability. type VSOnAutoInsertOptions struct { // List of trigger characters that trigger auto-insert. - VSTriggerCharacters []string `json:"_vs_triggerCharacters"` + VSTriggerCharacters []string `json:"_vs_triggerCharacters" lsp:"required"` } var _ json.UnmarshalerFrom = (*VSOnAutoInsertOptions)(nil) func (s *VSOnAutoInsertOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingVSTriggerCharacters uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"_vs_triggerCharacters"`: - missing &^= missingVSTriggerCharacters - if dec.PeekKind() == 'n' { - return errNull("_vs_triggerCharacters") - } - if err := json.UnmarshalDecode(dec, &s.VSTriggerCharacters); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingVSTriggerCharacters != 0 { - missingProps = append(missingProps, "_vs_triggerCharacters") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A VS-specific reference item with grouping support for Find All References. type VSReferenceItem struct { // Unique identifier for this reference item. - VSId int32 `json:"_vs_id"` + VSId int32 `json:"_vs_id" lsp:"required"` // The ID of the definition item this reference belongs to. Absent for definition items themselves. VSDefinitionId *int32 `json:"_vs_definitionId,omitzero"` @@ -28548,7 +8913,7 @@ type VSReferenceItem struct { VSKind *[]VSReferenceKind `json:"_vs_kind,omitzero"` // The location of this reference. - VSLocation Location `json:"_vs_location"` + VSLocation Location `json:"_vs_location" lsp:"required"` // Classified display text for the definition (used for grouping headers in the UI). VSDefinitionText *VSClassifiedTextElement `json:"_vs_definitionText,omitzero"` @@ -28563,106 +8928,19 @@ type VSReferenceItem struct { var _ json.UnmarshalerFrom = (*VSReferenceItem)(nil) func (s *VSReferenceItem) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingVSId uint = 1 << iota - missingVSLocation - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"_vs_id"`: - missing &^= missingVSId - if err := json.UnmarshalDecode(dec, &s.VSId); err != nil { - return err - } - case `"_vs_definitionId"`: - if dec.PeekKind() == 'n' { - return errNull("_vs_definitionId") - } - if err := json.UnmarshalDecode(dec, &s.VSDefinitionId); err != nil { - return err - } - case `"_vs_kind"`: - if dec.PeekKind() == 'n' { - return errNull("_vs_kind") - } - if err := json.UnmarshalDecode(dec, &s.VSKind); err != nil { - return err - } - case `"_vs_location"`: - missing &^= missingVSLocation - if err := json.UnmarshalDecode(dec, &s.VSLocation); err != nil { - return err - } - case `"_vs_definitionText"`: - if dec.PeekKind() == 'n' { - return errNull("_vs_definitionText") - } - if err := json.UnmarshalDecode(dec, &s.VSDefinitionText); err != nil { - return err - } - case `"_vs_projectName"`: - if dec.PeekKind() == 'n' { - return errNull("_vs_projectName") - } - if err := json.UnmarshalDecode(dec, &s.VSProjectName); err != nil { - return err - } - case `"_vs_containingType"`: - if dec.PeekKind() == 'n' { - return errNull("_vs_containingType") - } - if err := json.UnmarshalDecode(dec, &s.VSContainingType); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingVSId != 0 { - missingProps = append(missingProps, "_vs_id") - } - if missing&missingVSLocation != 0 { - missingProps = append(missingProps, "_vs_location") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters for the textDocument/_vs_onAutoInsert request. type VSOnAutoInsertParams struct { // The text document. - VSTextDocument TextDocumentIdentifier `json:"_vs_textDocument"` + VSTextDocument TextDocumentIdentifier `json:"_vs_textDocument" lsp:"required"` // The position inside the text document. - VSPosition Position `json:"_vs_position"` + VSPosition Position `json:"_vs_position" lsp:"required"` // The character that triggered the auto-insert. - VSCh string `json:"_vs_ch"` + VSCh string `json:"_vs_ch" lsp:"required"` } func (s *VSOnAutoInsertParams) TextDocumentURI() DocumentUri { @@ -28676,409 +8954,82 @@ func (s *VSOnAutoInsertParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*VSOnAutoInsertParams)(nil) func (s *VSOnAutoInsertParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingVSTextDocument uint = 1 << iota - missingVSPosition - missingVSCh - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"_vs_textDocument"`: - missing &^= missingVSTextDocument - if err := json.UnmarshalDecode(dec, &s.VSTextDocument); err != nil { - return err - } - case `"_vs_position"`: - missing &^= missingVSPosition - if err := json.UnmarshalDecode(dec, &s.VSPosition); err != nil { - return err - } - case `"_vs_ch"`: - missing &^= missingVSCh - if err := json.UnmarshalDecode(dec, &s.VSCh); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingVSTextDocument != 0 { - missingProps = append(missingProps, "_vs_textDocument") - } - if missing&missingVSPosition != 0 { - missingProps = append(missingProps, "_vs_position") - } - if missing&missingVSCh != 0 { - missingProps = append(missingProps, "_vs_ch") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } -// Response item for the textDocument/_vs_onAutoInsert request. -type VSOnAutoInsertResponseItem struct { - // The format of the text edit (plaintext or snippet). - VSTextEditFormat InsertTextFormat `json:"_vs_textEditFormat"` - - // The text edit to apply for the auto-insertion. - VSTextEdit *TextEdit `json:"_vs_textEdit"` -} - -var _ json.UnmarshalerFrom = (*VSOnAutoInsertResponseItem)(nil) - -func (s *VSOnAutoInsertResponseItem) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingVSTextEditFormat uint = 1 << iota - missingVSTextEdit - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"_vs_textEditFormat"`: - missing &^= missingVSTextEditFormat - if err := json.UnmarshalDecode(dec, &s.VSTextEditFormat); err != nil { - return err - } - case `"_vs_textEdit"`: - missing &^= missingVSTextEdit - if dec.PeekKind() == 'n' { - return errNull("_vs_textEdit") - } - if err := json.UnmarshalDecode(dec, &s.VSTextEdit); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } +// Response item for the textDocument/_vs_onAutoInsert request. +type VSOnAutoInsertResponseItem struct { + // The format of the text edit (plaintext or snippet). + VSTextEditFormat InsertTextFormat `json:"_vs_textEditFormat" lsp:"required"` - if missing != 0 { - var missingProps []string - if missing&missingVSTextEditFormat != 0 { - missingProps = append(missingProps, "_vs_textEditFormat") - } - if missing&missingVSTextEdit != 0 { - missingProps = append(missingProps, "_vs_textEdit") - } - return errMissing(missingProps) - } + // The text edit to apply for the auto-insertion. + VSTextEdit *TextEdit `json:"_vs_textEdit" lsp:"required"` +} - return nil +var _ json.UnmarshalerFrom = (*VSOnAutoInsertResponseItem)(nil) + +func (s *VSOnAutoInsertResponseItem) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // A RequestFailureTelemetryEvent is sent when a request fails and the server recovers. type RequestFailureTelemetryEvent struct { // The name of the telemetry event. - EventName StringLiteralLanguageServerErrorResponse `json:"eventName"` + EventName StringLiteralLanguageServerErrorResponse `json:"eventName" lsp:"required"` // Indicates whether the reason for generating the event (e.g. general usage telemetry or errors). - TelemetryPurpose StringLiteralError `json:"telemetryPurpose"` + TelemetryPurpose StringLiteralError `json:"telemetryPurpose" lsp:"required"` // The properties associated with the event. - Properties *RequestFailureTelemetryProperties `json:"properties"` + Properties *RequestFailureTelemetryProperties `json:"properties" lsp:"required"` } var _ json.UnmarshalerFrom = (*RequestFailureTelemetryEvent)(nil) func (s *RequestFailureTelemetryEvent) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingEventName uint = 1 << iota - missingTelemetryPurpose - missingProperties - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"eventName"`: - missing &^= missingEventName - if err := json.UnmarshalDecode(dec, &s.EventName); err != nil { - return err - } - case `"telemetryPurpose"`: - missing &^= missingTelemetryPurpose - if err := json.UnmarshalDecode(dec, &s.TelemetryPurpose); err != nil { - return err - } - case `"properties"`: - missing &^= missingProperties - if dec.PeekKind() == 'n' { - return errNull("properties") - } - if err := json.UnmarshalDecode(dec, &s.Properties); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingEventName != 0 { - missingProps = append(missingProps, "eventName") - } - if missing&missingTelemetryPurpose != 0 { - missingProps = append(missingProps, "telemetryPurpose") - } - if missing&missingProperties != 0 { - missingProps = append(missingProps, "properties") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // RequestFailureTelemetryProperties contains failure information when an LSP request manages to recover. type RequestFailureTelemetryProperties struct { // The error code associated with the event. - ErrorCode string `json:"errorCode"` + ErrorCode string `json:"errorCode" lsp:"required"` // The method of the request that caused the event. - RequestMethod string `json:"requestMethod"` + RequestMethod string `json:"requestMethod" lsp:"required"` // The stack trace associated with the event. - Stack string `json:"stack"` + Stack string `json:"stack" lsp:"required"` } var _ json.UnmarshalerFrom = (*RequestFailureTelemetryProperties)(nil) func (s *RequestFailureTelemetryProperties) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingErrorCode uint = 1 << iota - missingRequestMethod - missingStack - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"errorCode"`: - missing &^= missingErrorCode - if err := json.UnmarshalDecode(dec, &s.ErrorCode); err != nil { - return err - } - case `"requestMethod"`: - missing &^= missingRequestMethod - if err := json.UnmarshalDecode(dec, &s.RequestMethod); err != nil { - return err - } - case `"stack"`: - missing &^= missingStack - if err := json.UnmarshalDecode(dec, &s.Stack); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingErrorCode != 0 { - missingProps = append(missingProps, "errorCode") - } - if missing&missingRequestMethod != 0 { - missingProps = append(missingProps, "requestMethod") - } - if missing&missingStack != 0 { - missingProps = append(missingProps, "stack") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters for profiling requests. type ProfileParams struct { // The directory path where the profile should be saved. - Dir string `json:"dir"` + Dir string `json:"dir" lsp:"required"` } var _ json.UnmarshalerFrom = (*ProfileParams)(nil) func (s *ProfileParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDir uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"dir"`: - missing &^= missingDir - if err := json.UnmarshalDecode(dec, &s.Dir); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDir != 0 { - missingProps = append(missingProps, "dir") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Result of a profiling request. type ProfileResult struct { // The file path where the profile was saved. - File string `json:"file"` + File string `json:"file" lsp:"required"` } var _ json.UnmarshalerFrom = (*ProfileResult)(nil) func (s *ProfileResult) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingFile uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"file"`: - missing &^= missingFile - if err := json.UnmarshalDecode(dec, &s.File); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingFile != 0 { - missingProps = append(missingProps, "file") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters for the initializeAPISession request. @@ -29090,111 +9041,28 @@ type InitializeAPISessionParams struct { var _ json.UnmarshalerFrom = (*InitializeAPISessionParams)(nil) func (s *InitializeAPISessionParams) UnmarshalJSONFrom(dec *json.Decoder) error { - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"pipe"`: - if dec.PeekKind() == 'n' { - return errNull("pipe") - } - if err := json.UnmarshalDecode(dec, &s.Pipe); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - return nil + return unmarshalStruct(s, dec) } // Result for the initializeAPISession request. type InitializeAPISessionResult struct { // The unique identifier for this API session. - SessionId string `json:"sessionId"` - - // The path to the named pipe or Unix domain socket for API communication. - Pipe string `json:"pipe"` -} - -var _ json.UnmarshalerFrom = (*InitializeAPISessionResult)(nil) - -func (s *InitializeAPISessionResult) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingSessionId uint = 1 << iota - missingPipe - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"sessionId"`: - missing &^= missingSessionId - if err := json.UnmarshalDecode(dec, &s.SessionId); err != nil { - return err - } - case `"pipe"`: - missing &^= missingPipe - if err := json.UnmarshalDecode(dec, &s.Pipe); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } + SessionId string `json:"sessionId" lsp:"required"` - if missing != 0 { - var missingProps []string - if missing&missingSessionId != 0 { - missingProps = append(missingProps, "sessionId") - } - if missing&missingPipe != 0 { - missingProps = append(missingProps, "pipe") - } - return errMissing(missingProps) - } + // The path to the named pipe or Unix domain socket for API communication. + Pipe string `json:"pipe" lsp:"required"` +} - return nil +var _ json.UnmarshalerFrom = (*InitializeAPISessionResult)(nil) + +func (s *InitializeAPISessionResult) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Parameters for the custom/projectInfo request. type ProjectInfoParams struct { // The text document to get project info for. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` } func (s *ProjectInfoParams) TextDocumentURI() DocumentUri { @@ -29204,537 +9072,213 @@ func (s *ProjectInfoParams) TextDocumentURI() DocumentUri { var _ json.UnmarshalerFrom = (*ProjectInfoParams)(nil) func (s *ProjectInfoParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Result for the custom/projectInfo request. type ProjectInfoResult struct { // The absolute path to the config file (e.g. /path/to/tsconfig.json) for the project that contains this file, or an empty string if the file is in an inferred project. - ConfigFilePath string `json:"configFilePath"` + ConfigFilePath string `json:"configFilePath" lsp:"required"` } var _ json.UnmarshalerFrom = (*ProjectInfoResult)(nil) func (s *ProjectInfoResult) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingConfigFilePath uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"configFilePath"`: - missing &^= missingConfigFilePath - if err := json.UnmarshalDecode(dec, &s.ConfigFilePath); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingConfigFilePath != 0 { - missingProps = append(missingProps, "configFilePath") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Parameters for the custom/setLogVerbosity notification. type SetLogVerbosityParams struct { // The log verbosity level. - Verbosity LogVerbosity `json:"verbosity"` + Verbosity LogVerbosity `json:"verbosity" lsp:"required"` } var _ json.UnmarshalerFrom = (*SetLogVerbosityParams)(nil) func (s *SetLogVerbosityParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingVerbosity uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"verbosity"`: - missing &^= missingVerbosity - if err := json.UnmarshalDecode(dec, &s.Verbosity); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingVerbosity != 0 { - missingProps = append(missingProps, "verbosity") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A PerformanceStatsTelemetryEvent is sent periodically with performance and resource usage statistics. type PerformanceStatsTelemetryEvent struct { // The name of the telemetry event. - EventName StringLiteralLanguageServerPerformanceStats `json:"eventName"` + EventName StringLiteralLanguageServerPerformanceStats `json:"eventName" lsp:"required"` // Indicates this is a usage telemetry event. - TelemetryPurpose StringLiteralUsage `json:"telemetryPurpose"` + TelemetryPurpose StringLiteralUsage `json:"telemetryPurpose" lsp:"required"` // Numeric measurements for this telemetry event. - Measurements *PerformanceStatsTelemetryMeasurements `json:"measurements"` + Measurements *PerformanceStatsTelemetryMeasurements `json:"measurements" lsp:"required"` } var _ json.UnmarshalerFrom = (*PerformanceStatsTelemetryEvent)(nil) func (s *PerformanceStatsTelemetryEvent) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingEventName uint = 1 << iota - missingTelemetryPurpose - missingMeasurements - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"eventName"`: - missing &^= missingEventName - if err := json.UnmarshalDecode(dec, &s.EventName); err != nil { - return err - } - case `"telemetryPurpose"`: - missing &^= missingTelemetryPurpose - if err := json.UnmarshalDecode(dec, &s.TelemetryPurpose); err != nil { - return err - } - case `"measurements"`: - missing &^= missingMeasurements - if dec.PeekKind() == 'n' { - return errNull("measurements") - } - if err := json.UnmarshalDecode(dec, &s.Measurements); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingEventName != 0 { - missingProps = append(missingProps, "eventName") - } - if missing&missingTelemetryPurpose != 0 { - missingProps = append(missingProps, "telemetryPurpose") - } - if missing&missingMeasurements != 0 { - missingProps = append(missingProps, "measurements") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Numeric measurements for PerformanceStatsTelemetryEvent. type PerformanceStatsTelemetryMeasurements struct { // Number of files currently open in the editor. - OpenFileCount float64 `json:"openFileCount,omitzero"` + OpenFileCount float64 `json:"openFileCount,omitzero" lsp:"nullable"` // Seconds since the session was initialized. - UptimeSeconds float64 `json:"uptimeSeconds,omitzero"` + UptimeSeconds float64 `json:"uptimeSeconds,omitzero" lsp:"nullable"` // Number of loaded projects. - ProjectCount float64 `json:"projectCount,omitzero"` + ProjectCount float64 `json:"projectCount,omitzero" lsp:"nullable"` // Number of loaded config files. - ConfigCount float64 `json:"configCount,omitzero"` + ConfigCount float64 `json:"configCount,omitzero" lsp:"nullable"` // Number of files cached from disk. - CachedDiskFileCount float64 `json:"cachedDiskFileCount,omitzero"` + CachedDiskFileCount float64 `json:"cachedDiskFileCount,omitzero" lsp:"nullable"` // Total memory mapped by the Go runtime in bytes. - MemoryUsedBytes float64 `json:"memoryUsedBytes,omitzero"` + MemoryUsedBytes float64 `json:"memoryUsedBytes,omitzero" lsp:"nullable"` // GOMEMLIMIT value in bytes, or 0 if not set. - GoMemLimit float64 `json:"goMemLimit,omitzero"` + GoMemLimit float64 `json:"goMemLimit,omitzero" lsp:"nullable"` // GOGC percentage value configured for the GC. - GoGCPercent float64 `json:"goGCPercent,omitzero"` + GoGCPercent float64 `json:"goGCPercent,omitzero" lsp:"nullable"` // Heap size target the GC is working toward in bytes. - HeapGoalBytes float64 `json:"heapGoalBytes,omitzero"` + HeapGoalBytes float64 `json:"heapGoalBytes,omitzero" lsp:"nullable"` // Bytes of live (reachable) heap objects. - HeapLiveBytes float64 `json:"heapLiveBytes,omitzero"` + HeapLiveBytes float64 `json:"heapLiveBytes,omitzero" lsp:"nullable"` // Number of live or unswept objects occupying heap memory. - HeapObjectCount float64 `json:"heapObjectCount,omitzero"` + HeapObjectCount float64 `json:"heapObjectCount,omitzero" lsp:"nullable"` // Heap memory reserved for goroutine stacks. - HeapStackBytes float64 `json:"heapStackBytes,omitzero"` + HeapStackBytes float64 `json:"heapStackBytes,omitzero" lsp:"nullable"` // Heap memory returned to the OS. - HeapReleasedBytes float64 `json:"heapReleasedBytes,omitzero"` + HeapReleasedBytes float64 `json:"heapReleasedBytes,omitzero" lsp:"nullable"` // Heap memory that is free and eligible to be returned to the OS. - HeapFreeBytes float64 `json:"heapFreeBytes,omitzero"` + HeapFreeBytes float64 `json:"heapFreeBytes,omitzero" lsp:"nullable"` // Total scannable heap bytes — how much the GC must traverse. - GcScanHeapBytes float64 `json:"gcScanHeapBytes,omitzero"` + GcScanHeapBytes float64 `json:"gcScanHeapBytes,omitzero" lsp:"nullable"` // The current GOMAXPROCS value. - GoMaxProcs float64 `json:"goMaxProcs,omitzero"` + GoMaxProcs float64 `json:"goMaxProcs,omitzero" lsp:"nullable"` // Current number of goroutines. - GoroutineCount float64 `json:"goroutineCount,omitzero"` + GoroutineCount float64 `json:"goroutineCount,omitzero" lsp:"nullable"` // Total completed GC cycles. - GcCyclesTotal float64 `json:"gcCyclesTotal,omitzero"` + GcCyclesTotal float64 `json:"gcCyclesTotal,omitzero" lsp:"nullable"` // Cumulative CPU time spent in GC in seconds. - GcCPUSeconds float64 `json:"gcCPUSeconds,omitzero"` + GcCPUSeconds float64 `json:"gcCPUSeconds,omitzero" lsp:"nullable"` // Cumulative CPU time spent in user Go code in seconds. - UserCPUSeconds float64 `json:"userCPUSeconds,omitzero"` + UserCPUSeconds float64 `json:"userCPUSeconds,omitzero" lsp:"nullable"` // Total physical memory on the system in bytes. - SystemMemTotal float64 `json:"systemMemTotal,omitzero"` + SystemMemTotal float64 `json:"systemMemTotal,omitzero" lsp:"nullable"` // Used physical memory on the system in bytes. - SystemMemUsed float64 `json:"systemMemUsed,omitzero"` + SystemMemUsed float64 `json:"systemMemUsed,omitzero" lsp:"nullable"` // Number of auto-import project buckets. - AutoImportProjectBucketCount float64 `json:"autoImportProjectBucketCount,omitzero"` + AutoImportProjectBucketCount float64 `json:"autoImportProjectBucketCount,omitzero" lsp:"nullable"` // Number of auto-import node_modules buckets. - AutoImportNodeModulesBucketCount float64 `json:"autoImportNodeModulesBucketCount,omitzero"` + AutoImportNodeModulesBucketCount float64 `json:"autoImportNodeModulesBucketCount,omitzero" lsp:"nullable"` // Unique packages across all node_modules buckets. - AutoImportUniquePackageCount float64 `json:"autoImportUniquePackageCount,omitzero"` + AutoImportUniquePackageCount float64 `json:"autoImportUniquePackageCount,omitzero" lsp:"nullable"` // Total indexed exports from project files. - AutoImportProjectExportCount float64 `json:"autoImportProjectExportCount,omitzero"` + AutoImportProjectExportCount float64 `json:"autoImportProjectExportCount,omitzero" lsp:"nullable"` // Total indexed exports from node_modules. - AutoImportNodeModulesExportCount float64 `json:"autoImportNodeModulesExportCount,omitzero"` + AutoImportNodeModulesExportCount float64 `json:"autoImportNodeModulesExportCount,omitzero" lsp:"nullable"` // Total files tracked across project buckets. - AutoImportProjectFileCount float64 `json:"autoImportProjectFileCount,omitzero"` + AutoImportProjectFileCount float64 `json:"autoImportProjectFileCount,omitzero" lsp:"nullable"` // Total files tracked across node_modules buckets. - AutoImportNodeModulesFileCount float64 `json:"autoImportNodeModulesFileCount,omitzero"` + AutoImportNodeModulesFileCount float64 `json:"autoImportNodeModulesFileCount,omitzero" lsp:"nullable"` // Number of node_modules buckets with no package.json filter. - AutoImportNodeModulesUnfilteredBucketCount float64 `json:"autoImportNodeModulesUnfilteredBucketCount,omitzero"` + AutoImportNodeModulesUnfilteredBucketCount float64 `json:"autoImportNodeModulesUnfilteredBucketCount,omitzero" lsp:"nullable"` } // A ProjectInfoTelemetryEvent is sent once per project when it is first loaded. type ProjectInfoTelemetryEvent struct { // The name of the telemetry event. - EventName StringLiteralLanguageServerProjectInfo `json:"eventName"` + EventName StringLiteralLanguageServerProjectInfo `json:"eventName" lsp:"required"` // Indicates this is a usage telemetry event. - TelemetryPurpose StringLiteralUsage `json:"telemetryPurpose"` + TelemetryPurpose StringLiteralUsage `json:"telemetryPurpose" lsp:"required"` // String properties for this telemetry event. Complex values (compilerOptions, fileStats) are JSON-stringified. - Properties map[string]string `json:"properties"` + Properties map[string]string `json:"properties" lsp:"required"` // Numeric measurements for this telemetry event. - Measurements *ProjectInfoTelemetryMeasurements `json:"measurements"` + Measurements *ProjectInfoTelemetryMeasurements `json:"measurements" lsp:"required"` } var _ json.UnmarshalerFrom = (*ProjectInfoTelemetryEvent)(nil) func (s *ProjectInfoTelemetryEvent) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingEventName uint = 1 << iota - missingTelemetryPurpose - missingProperties - missingMeasurements - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"eventName"`: - missing &^= missingEventName - if err := json.UnmarshalDecode(dec, &s.EventName); err != nil { - return err - } - case `"telemetryPurpose"`: - missing &^= missingTelemetryPurpose - if err := json.UnmarshalDecode(dec, &s.TelemetryPurpose); err != nil { - return err - } - case `"properties"`: - missing &^= missingProperties - if dec.PeekKind() == 'n' { - return errNull("properties") - } - if err := json.UnmarshalDecode(dec, &s.Properties); err != nil { - return err - } - case `"measurements"`: - missing &^= missingMeasurements - if dec.PeekKind() == 'n' { - return errNull("measurements") - } - if err := json.UnmarshalDecode(dec, &s.Measurements); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingEventName != 0 { - missingProps = append(missingProps, "eventName") - } - if missing&missingTelemetryPurpose != 0 { - missingProps = append(missingProps, "telemetryPurpose") - } - if missing&missingProperties != 0 { - missingProps = append(missingProps, "properties") - } - if missing&missingMeasurements != 0 { - missingProps = append(missingProps, "measurements") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Numeric measurements for ProjectInfoTelemetryEvent. type ProjectInfoTelemetryMeasurements struct { - JsFileCount float64 `json:"jsFileCount,omitzero"` - - JsFileSize float64 `json:"jsFileSize,omitzero"` - - JsxFileCount float64 `json:"jsxFileCount,omitzero"` + JsFileCount float64 `json:"jsFileCount,omitzero" lsp:"nullable"` - JsxFileSize float64 `json:"jsxFileSize,omitzero"` + JsFileSize float64 `json:"jsFileSize,omitzero" lsp:"nullable"` - TsFileCount float64 `json:"tsFileCount,omitzero"` + JsxFileCount float64 `json:"jsxFileCount,omitzero" lsp:"nullable"` - TsFileSize float64 `json:"tsFileSize,omitzero"` - - TsxFileCount float64 `json:"tsxFileCount,omitzero"` - - TsxFileSize float64 `json:"tsxFileSize,omitzero"` - - DtsFileCount float64 `json:"dtsFileCount,omitzero"` - - DtsFileSize float64 `json:"dtsFileSize,omitzero"` -} - -// Represents a collection of document highlights from a single document, used in multi-document highlight responses. -type MultiDocumentHighlight struct { - // The URI of the document containing the highlights. - Uri DocumentUri `json:"uri"` + JsxFileSize float64 `json:"jsxFileSize,omitzero" lsp:"nullable"` - // The highlights for the document. - Highlights []*DocumentHighlight `json:"highlights"` -} + TsFileCount float64 `json:"tsFileCount,omitzero" lsp:"nullable"` -var _ json.UnmarshalerFrom = (*MultiDocumentHighlight)(nil) + TsFileSize float64 `json:"tsFileSize,omitzero" lsp:"nullable"` -func (s *MultiDocumentHighlight) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingUri uint = 1 << iota - missingHighlights - _missingLast - ) - missing := _missingLast - 1 + TsxFileCount float64 `json:"tsxFileCount,omitzero" lsp:"nullable"` - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } + TsxFileSize float64 `json:"tsxFileSize,omitzero" lsp:"nullable"` - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"uri"`: - missing &^= missingUri - if err := json.UnmarshalDecode(dec, &s.Uri); err != nil { - return err - } - case `"highlights"`: - missing &^= missingHighlights - if dec.PeekKind() == 'n' { - return errNull("highlights") - } - if err := json.UnmarshalDecode(dec, &s.Highlights); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } + DtsFileCount float64 `json:"dtsFileCount,omitzero" lsp:"nullable"` - if _, err := dec.ReadToken(); err != nil { - return err - } + DtsFileSize float64 `json:"dtsFileSize,omitzero" lsp:"nullable"` +} - if missing != 0 { - var missingProps []string - if missing&missingUri != 0 { - missingProps = append(missingProps, "uri") - } - if missing&missingHighlights != 0 { - missingProps = append(missingProps, "highlights") - } - return errMissing(missingProps) - } +// Represents a collection of document highlights from a single document, used in multi-document highlight responses. +type MultiDocumentHighlight struct { + // The URI of the document containing the highlights. + Uri DocumentUri `json:"uri" lsp:"required"` - return nil + // The highlights for the document. + Highlights []*DocumentHighlight `json:"highlights" lsp:"required"` +} + +var _ json.UnmarshalerFrom = (*MultiDocumentHighlight)(nil) + +func (s *MultiDocumentHighlight) UnmarshalJSONFrom(dec *json.Decoder) error { + return unmarshalStruct(s, dec) } // Parameters for the custom/textDocument/multiDocumentHighlight request. type MultiDocumentHighlightParams struct { // The text document. - TextDocument TextDocumentIdentifier `json:"textDocument"` + TextDocument TextDocumentIdentifier `json:"textDocument" lsp:"required"` // The position inside the text document. - Position Position `json:"position"` + Position Position `json:"position" lsp:"required"` // The list of file URIs to search for highlights across. - FilesToSearch []DocumentUri `json:"filesToSearch"` + FilesToSearch []DocumentUri `json:"filesToSearch" lsp:"required"` } func (s *MultiDocumentHighlightParams) TextDocumentURI() DocumentUri { @@ -29748,237 +9292,46 @@ func (s *MultiDocumentHighlightParams) TextDocumentPosition() Position { var _ json.UnmarshalerFrom = (*MultiDocumentHighlightParams)(nil) func (s *MultiDocumentHighlightParams) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingTextDocument uint = 1 << iota - missingPosition - missingFilesToSearch - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"textDocument"`: - missing &^= missingTextDocument - if err := json.UnmarshalDecode(dec, &s.TextDocument); err != nil { - return err - } - case `"position"`: - missing &^= missingPosition - if err := json.UnmarshalDecode(dec, &s.Position); err != nil { - return err - } - case `"filesToSearch"`: - missing &^= missingFilesToSearch - if dec.PeekKind() == 'n' { - return errNull("filesToSearch") - } - if err := json.UnmarshalDecode(dec, &s.FilesToSearch); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingTextDocument != 0 { - missingProps = append(missingProps, "textDocument") - } - if missing&missingPosition != 0 { - missingProps = append(missingProps, "position") - } - if missing&missingFilesToSearch != 0 { - missingProps = append(missingProps, "filesToSearch") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A classified text run with text and classification type, used for colorized display in VS. type VSClassifiedTextRun struct { // The classification type name (e.g. 'keyword', 'class name', 'parameter name'). - ClassificationTypeName string `json:"ClassificationTypeName"` + ClassificationTypeName string `json:"ClassificationTypeName" lsp:"required"` // The text content of this run. - Text string `json:"Text"` + Text string `json:"Text" lsp:"required"` // Optional marker tag type. MarkerTagType *string `json:"MarkerTagType,omitzero"` // The style of this text run. - Style int32 `json:"Style,omitzero"` + Style int32 `json:"Style,omitzero" lsp:"nullable"` // VS type discriminator required by ObjectContentConverter for deserialization. - VSType StringLiteralClassifiedTextRun `json:"_vs_type"` + VSType StringLiteralClassifiedTextRun `json:"_vs_type" lsp:"required"` } var _ json.UnmarshalerFrom = (*VSClassifiedTextRun)(nil) func (s *VSClassifiedTextRun) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingClassificationTypeName uint = 1 << iota - missingText - missingVSType - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"ClassificationTypeName"`: - missing &^= missingClassificationTypeName - if err := json.UnmarshalDecode(dec, &s.ClassificationTypeName); err != nil { - return err - } - case `"Text"`: - missing &^= missingText - if err := json.UnmarshalDecode(dec, &s.Text); err != nil { - return err - } - case `"MarkerTagType"`: - if dec.PeekKind() == 'n' { - return errNull("MarkerTagType") - } - if err := json.UnmarshalDecode(dec, &s.MarkerTagType); err != nil { - return err - } - case `"Style"`: - if err := json.UnmarshalDecode(dec, &s.Style); err != nil { - return err - } - case `"_vs_type"`: - missing &^= missingVSType - if err := json.UnmarshalDecode(dec, &s.VSType); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingClassificationTypeName != 0 { - missingProps = append(missingProps, "ClassificationTypeName") - } - if missing&missingText != 0 { - missingProps = append(missingProps, "Text") - } - if missing&missingVSType != 0 { - missingProps = append(missingProps, "_vs_type") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // A classified text element containing an array of classified text runs, used for colorized labels in VS. type VSClassifiedTextElement struct { // The classified text runs that make up this element. - Runs []*VSClassifiedTextRun `json:"Runs"` + Runs []*VSClassifiedTextRun `json:"Runs" lsp:"required"` // VS type discriminator required by ObjectContentConverter for deserialization. - VSType StringLiteralClassifiedTextElement `json:"_vs_type"` + VSType StringLiteralClassifiedTextElement `json:"_vs_type" lsp:"required"` } var _ json.UnmarshalerFrom = (*VSClassifiedTextElement)(nil) func (s *VSClassifiedTextElement) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingRuns uint = 1 << iota - missingVSType - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"Runs"`: - missing &^= missingRuns - if dec.PeekKind() == 'n' { - return errNull("Runs") - } - if err := json.UnmarshalDecode(dec, &s.Runs); err != nil { - return err - } - case `"_vs_type"`: - missing &^= missingVSType - if err := json.UnmarshalDecode(dec, &s.VSType); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingRuns != 0 { - missingProps = append(missingProps, "Runs") - } - if missing&missingVSType != 0 { - missingProps = append(missingProps, "_vs_type") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // CallHierarchyItemData is a placeholder for custom data preserved on a CallHierarchyItem. @@ -30011,63 +9364,13 @@ type ColorPresentationRegistrationOptions struct { // A document selector to identify the scope of the registration. If set to null // the document selector provided on the client side will be used. - DocumentSelector DocumentSelectorOrNull `json:"documentSelector"` + DocumentSelector DocumentSelectorOrNull `json:"documentSelector" lsp:"required"` } var _ json.UnmarshalerFrom = (*ColorPresentationRegistrationOptions)(nil) func (s *ColorPresentationRegistrationOptions) UnmarshalJSONFrom(dec *json.Decoder) error { - const ( - missingDocumentSelector uint = 1 << iota - _missingLast - ) - missing := _missingLast - 1 - - if k := dec.PeekKind(); k != '{' { - return errNotObject(k) - } - if _, err := dec.ReadToken(); err != nil { - return err - } - - for dec.PeekKind() != '}' { - name, err := dec.ReadValue() - if err != nil { - return err - } - switch string(name) { - case `"workDoneProgress"`: - if dec.PeekKind() == 'n' { - return errNull("workDoneProgress") - } - if err := json.UnmarshalDecode(dec, &s.WorkDoneProgress); err != nil { - return err - } - case `"documentSelector"`: - missing &^= missingDocumentSelector - if err := json.UnmarshalDecode(dec, &s.DocumentSelector); err != nil { - return err - } - default: - if err := dec.SkipValue(); err != nil { - return err - } - } - } - - if _, err := dec.ReadToken(); err != nil { - return err - } - - if missing != 0 { - var missingProps []string - if missing&missingDocumentSelector != 0 { - missingProps = append(missingProps, "documentSelector") - } - return errMissing(missingProps) - } - - return nil + return unmarshalStruct(s, dec) } // Enumerations @@ -31307,386 +10610,6 @@ const ( ClassificationTypeNameIdentifier ClassificationTypeName = "identifier" ) -func unmarshalParams(method Method, data []byte) (any, error) { - switch method { - case MethodTextDocumentImplementation: - return unmarshalPtrTo[ImplementationParams](data) - case MethodTextDocumentTypeDefinition: - return unmarshalPtrTo[TypeDefinitionParams](data) - case MethodWorkspaceWorkspaceFolders: - return unmarshalEmpty(data) - case MethodWorkspaceConfiguration: - return unmarshalPtrTo[ConfigurationParams](data) - case MethodTextDocumentDocumentColor: - return unmarshalPtrTo[DocumentColorParams](data) - case MethodTextDocumentColorPresentation: - return unmarshalPtrTo[ColorPresentationParams](data) - case MethodTextDocumentFoldingRange: - return unmarshalPtrTo[FoldingRangeParams](data) - case MethodWorkspaceFoldingRangeRefresh: - return unmarshalEmpty(data) - case MethodTextDocumentDeclaration: - return unmarshalPtrTo[DeclarationParams](data) - case MethodTextDocumentSelectionRange: - return unmarshalPtrTo[SelectionRangeParams](data) - case MethodWindowWorkDoneProgressCreate: - return unmarshalPtrTo[WorkDoneProgressCreateParams](data) - case MethodTextDocumentPrepareCallHierarchy: - return unmarshalPtrTo[CallHierarchyPrepareParams](data) - case MethodCallHierarchyIncomingCalls: - return unmarshalPtrTo[CallHierarchyIncomingCallsParams](data) - case MethodCallHierarchyOutgoingCalls: - return unmarshalPtrTo[CallHierarchyOutgoingCallsParams](data) - case MethodTextDocumentSemanticTokensFull: - return unmarshalPtrTo[SemanticTokensParams](data) - case MethodTextDocumentSemanticTokensFullDelta: - return unmarshalPtrTo[SemanticTokensDeltaParams](data) - case MethodTextDocumentSemanticTokensRange: - return unmarshalPtrTo[SemanticTokensRangeParams](data) - case MethodWorkspaceSemanticTokensRefresh: - return unmarshalEmpty(data) - case MethodWindowShowDocument: - return unmarshalPtrTo[ShowDocumentParams](data) - case MethodTextDocumentLinkedEditingRange: - return unmarshalPtrTo[LinkedEditingRangeParams](data) - case MethodWorkspaceWillCreateFiles: - return unmarshalPtrTo[CreateFilesParams](data) - case MethodWorkspaceWillRenameFiles: - return unmarshalPtrTo[RenameFilesParams](data) - case MethodWorkspaceWillDeleteFiles: - return unmarshalPtrTo[DeleteFilesParams](data) - case MethodTextDocumentMoniker: - return unmarshalPtrTo[MonikerParams](data) - case MethodTextDocumentPrepareTypeHierarchy: - return unmarshalPtrTo[TypeHierarchyPrepareParams](data) - case MethodTypeHierarchySupertypes: - return unmarshalPtrTo[TypeHierarchySupertypesParams](data) - case MethodTypeHierarchySubtypes: - return unmarshalPtrTo[TypeHierarchySubtypesParams](data) - case MethodTextDocumentInlineValue: - return unmarshalPtrTo[InlineValueParams](data) - case MethodWorkspaceInlineValueRefresh: - return unmarshalEmpty(data) - case MethodTextDocumentInlayHint: - return unmarshalPtrTo[InlayHintParams](data) - case MethodInlayHintResolve: - return unmarshalPtrTo[InlayHint](data) - case MethodWorkspaceInlayHintRefresh: - return unmarshalEmpty(data) - case MethodTextDocumentDiagnostic: - return unmarshalPtrTo[DocumentDiagnosticParams](data) - case MethodWorkspaceDiagnostic: - return unmarshalPtrTo[WorkspaceDiagnosticParams](data) - case MethodWorkspaceDiagnosticRefresh: - return unmarshalEmpty(data) - case MethodTextDocumentInlineCompletion: - return unmarshalPtrTo[InlineCompletionParams](data) - case MethodWorkspaceTextDocumentContent: - return unmarshalPtrTo[TextDocumentContentParams](data) - case MethodWorkspaceTextDocumentContentRefresh: - return unmarshalPtrTo[TextDocumentContentRefreshParams](data) - case MethodClientRegisterCapability: - return unmarshalPtrTo[RegistrationParams](data) - case MethodClientUnregisterCapability: - return unmarshalPtrTo[UnregistrationParams](data) - case MethodInitialize: - return unmarshalPtrTo[InitializeParams](data) - case MethodShutdown: - return unmarshalEmpty(data) - case MethodWindowShowMessageRequest: - return unmarshalPtrTo[ShowMessageRequestParams](data) - case MethodTextDocumentWillSaveWaitUntil: - return unmarshalPtrTo[WillSaveTextDocumentParams](data) - case MethodTextDocumentCompletion: - return unmarshalPtrTo[CompletionParams](data) - case MethodCompletionItemResolve: - return unmarshalPtrTo[CompletionItem](data) - case MethodTextDocumentHover: - return unmarshalPtrTo[HoverParams](data) - case MethodTextDocumentSignatureHelp: - return unmarshalPtrTo[SignatureHelpParams](data) - case MethodTextDocumentDefinition: - return unmarshalPtrTo[DefinitionParams](data) - case MethodTextDocumentReferences: - return unmarshalPtrTo[ReferenceParams](data) - case MethodTextDocumentDocumentHighlight: - return unmarshalPtrTo[DocumentHighlightParams](data) - case MethodTextDocumentDocumentSymbol: - return unmarshalPtrTo[DocumentSymbolParams](data) - case MethodTextDocumentCodeAction: - return unmarshalPtrTo[CodeActionParams](data) - case MethodCodeActionResolve: - return unmarshalPtrTo[CodeAction](data) - case MethodWorkspaceSymbol: - return unmarshalPtrTo[WorkspaceSymbolParams](data) - case MethodWorkspaceSymbolResolve: - return unmarshalPtrTo[WorkspaceSymbol](data) - case MethodTextDocumentCodeLens: - return unmarshalPtrTo[CodeLensParams](data) - case MethodCodeLensResolve: - return unmarshalPtrTo[CodeLens](data) - case MethodWorkspaceCodeLensRefresh: - return unmarshalEmpty(data) - case MethodTextDocumentDocumentLink: - return unmarshalPtrTo[DocumentLinkParams](data) - case MethodDocumentLinkResolve: - return unmarshalPtrTo[DocumentLink](data) - case MethodTextDocumentFormatting: - return unmarshalPtrTo[DocumentFormattingParams](data) - case MethodTextDocumentRangeFormatting: - return unmarshalPtrTo[DocumentRangeFormattingParams](data) - case MethodTextDocumentRangesFormatting: - return unmarshalPtrTo[DocumentRangesFormattingParams](data) - case MethodTextDocumentOnTypeFormatting: - return unmarshalPtrTo[DocumentOnTypeFormattingParams](data) - case MethodTextDocumentRename: - return unmarshalPtrTo[RenameParams](data) - case MethodTextDocumentPrepareRename: - return unmarshalPtrTo[PrepareRenameParams](data) - case MethodWorkspaceExecuteCommand: - return unmarshalPtrTo[ExecuteCommandParams](data) - case MethodWorkspaceApplyEdit: - return unmarshalPtrTo[ApplyWorkspaceEditParams](data) - case MethodCustomRunGC: - return unmarshalEmpty(data) - case MethodCustomSaveHeapProfile: - return unmarshalPtrTo[ProfileParams](data) - case MethodCustomSaveAllocProfile: - return unmarshalPtrTo[ProfileParams](data) - case MethodCustomStartCPUProfile: - return unmarshalPtrTo[ProfileParams](data) - case MethodCustomStopCPUProfile: - return unmarshalEmpty(data) - case MethodCustomInitializeAPISession: - return unmarshalPtrTo[InitializeAPISessionParams](data) - case MethodCustomProjectInfo: - return unmarshalPtrTo[ProjectInfoParams](data) - case MethodCustomTextDocumentSourceDefinition: - return unmarshalPtrTo[TextDocumentPositionParams](data) - case MethodCustomTextDocumentMultiDocumentHighlight: - return unmarshalPtrTo[MultiDocumentHighlightParams](data) - case MethodTextDocumentVSOnAutoInsert: - return unmarshalPtrTo[VSOnAutoInsertParams](data) - case MethodTextDocumentVSReferences: - return unmarshalPtrTo[ReferenceParams](data) - case MethodWorkspaceDidChangeWorkspaceFolders: - return unmarshalPtrTo[DidChangeWorkspaceFoldersParams](data) - case MethodWindowWorkDoneProgressCancel: - return unmarshalPtrTo[WorkDoneProgressCancelParams](data) - case MethodWorkspaceDidCreateFiles: - return unmarshalPtrTo[CreateFilesParams](data) - case MethodWorkspaceDidRenameFiles: - return unmarshalPtrTo[RenameFilesParams](data) - case MethodWorkspaceDidDeleteFiles: - return unmarshalPtrTo[DeleteFilesParams](data) - case MethodInitialized: - return unmarshalPtrTo[InitializedParams](data) - case MethodExit: - return unmarshalEmpty(data) - case MethodWorkspaceDidChangeConfiguration: - return unmarshalPtrTo[DidChangeConfigurationParams](data) - case MethodWindowShowMessage: - return unmarshalPtrTo[ShowMessageParams](data) - case MethodWindowLogMessage: - return unmarshalPtrTo[LogMessageParams](data) - case MethodTelemetryEvent: - return unmarshalPtrTo[TelemetryEvent](data) - case MethodTextDocumentDidOpen: - return unmarshalPtrTo[DidOpenTextDocumentParams](data) - case MethodTextDocumentDidChange: - return unmarshalPtrTo[DidChangeTextDocumentParams](data) - case MethodTextDocumentDidClose: - return unmarshalPtrTo[DidCloseTextDocumentParams](data) - case MethodTextDocumentDidSave: - return unmarshalPtrTo[DidSaveTextDocumentParams](data) - case MethodTextDocumentWillSave: - return unmarshalPtrTo[WillSaveTextDocumentParams](data) - case MethodWorkspaceDidChangeWatchedFiles: - return unmarshalPtrTo[DidChangeWatchedFilesParams](data) - case MethodTextDocumentPublishDiagnostics: - return unmarshalPtrTo[PublishDiagnosticsParams](data) - case MethodSetTrace: - return unmarshalPtrTo[SetTraceParams](data) - case MethodLogTrace: - return unmarshalPtrTo[LogTraceParams](data) - case MethodCancelRequest: - return unmarshalPtrTo[CancelParams](data) - case MethodProgress: - return unmarshalPtrTo[ProgressParams](data) - case MethodCustomSetLogVerbosity: - return unmarshalPtrTo[SetLogVerbosityParams](data) - default: - return unmarshalAny(data) - } -} - -func unmarshalResult(method Method, data []byte) (any, error) { - switch method { - case MethodTextDocumentImplementation: - return unmarshalValue[ImplementationResponse](data) - case MethodTextDocumentTypeDefinition: - return unmarshalValue[TypeDefinitionResponse](data) - case MethodWorkspaceWorkspaceFolders: - return unmarshalValue[WorkspaceFoldersResponse](data) - case MethodWorkspaceConfiguration: - return unmarshalValue[ConfigurationResponse](data) - case MethodTextDocumentDocumentColor: - return unmarshalValue[DocumentColorResponse](data) - case MethodTextDocumentColorPresentation: - return unmarshalValue[ColorPresentationResponse](data) - case MethodTextDocumentFoldingRange: - return unmarshalValue[FoldingRangeResponse](data) - case MethodWorkspaceFoldingRangeRefresh: - return unmarshalValue[FoldingRangeRefreshResponse](data) - case MethodTextDocumentDeclaration: - return unmarshalValue[DeclarationResponse](data) - case MethodTextDocumentSelectionRange: - return unmarshalValue[SelectionRangeResponse](data) - case MethodWindowWorkDoneProgressCreate: - return unmarshalValue[WorkDoneProgressCreateResponse](data) - case MethodTextDocumentPrepareCallHierarchy: - return unmarshalValue[CallHierarchyPrepareResponse](data) - case MethodCallHierarchyIncomingCalls: - return unmarshalValue[CallHierarchyIncomingCallsResponse](data) - case MethodCallHierarchyOutgoingCalls: - return unmarshalValue[CallHierarchyOutgoingCallsResponse](data) - case MethodTextDocumentSemanticTokensFull: - return unmarshalValue[SemanticTokensResponse](data) - case MethodTextDocumentSemanticTokensFullDelta: - return unmarshalValue[SemanticTokensDeltaResponse](data) - case MethodTextDocumentSemanticTokensRange: - return unmarshalValue[SemanticTokensRangeResponse](data) - case MethodWorkspaceSemanticTokensRefresh: - return unmarshalValue[SemanticTokensRefreshResponse](data) - case MethodWindowShowDocument: - return unmarshalValue[ShowDocumentResponse](data) - case MethodTextDocumentLinkedEditingRange: - return unmarshalValue[LinkedEditingRangeResponse](data) - case MethodWorkspaceWillCreateFiles: - return unmarshalValue[WillCreateFilesResponse](data) - case MethodWorkspaceWillRenameFiles: - return unmarshalValue[WillRenameFilesResponse](data) - case MethodWorkspaceWillDeleteFiles: - return unmarshalValue[WillDeleteFilesResponse](data) - case MethodTextDocumentMoniker: - return unmarshalValue[MonikerResponse](data) - case MethodTextDocumentPrepareTypeHierarchy: - return unmarshalValue[TypeHierarchyPrepareResponse](data) - case MethodTypeHierarchySupertypes: - return unmarshalValue[TypeHierarchySupertypesResponse](data) - case MethodTypeHierarchySubtypes: - return unmarshalValue[TypeHierarchySubtypesResponse](data) - case MethodTextDocumentInlineValue: - return unmarshalValue[InlineValueResponse](data) - case MethodWorkspaceInlineValueRefresh: - return unmarshalValue[InlineValueRefreshResponse](data) - case MethodTextDocumentInlayHint: - return unmarshalValue[InlayHintResponse](data) - case MethodInlayHintResolve: - return unmarshalValue[InlayHintResolveResponse](data) - case MethodWorkspaceInlayHintRefresh: - return unmarshalValue[InlayHintRefreshResponse](data) - case MethodTextDocumentDiagnostic: - return unmarshalValue[DocumentDiagnosticResponse](data) - case MethodWorkspaceDiagnostic: - return unmarshalValue[WorkspaceDiagnosticResponse](data) - case MethodWorkspaceDiagnosticRefresh: - return unmarshalValue[DiagnosticRefreshResponse](data) - case MethodTextDocumentInlineCompletion: - return unmarshalValue[InlineCompletionResponse](data) - case MethodWorkspaceTextDocumentContent: - return unmarshalValue[TextDocumentContentResponse](data) - case MethodWorkspaceTextDocumentContentRefresh: - return unmarshalValue[TextDocumentContentRefreshResponse](data) - case MethodClientRegisterCapability: - return unmarshalValue[RegistrationResponse](data) - case MethodClientUnregisterCapability: - return unmarshalValue[UnregistrationResponse](data) - case MethodInitialize: - return unmarshalValue[InitializeResponse](data) - case MethodShutdown: - return unmarshalValue[ShutdownResponse](data) - case MethodWindowShowMessageRequest: - return unmarshalValue[ShowMessageResponse](data) - case MethodTextDocumentWillSaveWaitUntil: - return unmarshalValue[WillSaveTextDocumentWaitUntilResponse](data) - case MethodTextDocumentCompletion: - return unmarshalValue[CompletionResponse](data) - case MethodCompletionItemResolve: - return unmarshalValue[CompletionResolveResponse](data) - case MethodTextDocumentHover: - return unmarshalValue[HoverResponse](data) - case MethodTextDocumentSignatureHelp: - return unmarshalValue[SignatureHelpResponse](data) - case MethodTextDocumentDefinition: - return unmarshalValue[DefinitionResponse](data) - case MethodTextDocumentReferences: - return unmarshalValue[ReferencesResponse](data) - case MethodTextDocumentDocumentHighlight: - return unmarshalValue[DocumentHighlightResponse](data) - case MethodTextDocumentDocumentSymbol: - return unmarshalValue[DocumentSymbolResponse](data) - case MethodTextDocumentCodeAction: - return unmarshalValue[CodeActionResponse](data) - case MethodCodeActionResolve: - return unmarshalValue[CodeActionResolveResponse](data) - case MethodWorkspaceSymbol: - return unmarshalValue[WorkspaceSymbolResponse](data) - case MethodWorkspaceSymbolResolve: - return unmarshalValue[WorkspaceSymbolResolveResponse](data) - case MethodTextDocumentCodeLens: - return unmarshalValue[CodeLensResponse](data) - case MethodCodeLensResolve: - return unmarshalValue[CodeLensResolveResponse](data) - case MethodWorkspaceCodeLensRefresh: - return unmarshalValue[CodeLensRefreshResponse](data) - case MethodTextDocumentDocumentLink: - return unmarshalValue[DocumentLinkResponse](data) - case MethodDocumentLinkResolve: - return unmarshalValue[DocumentLinkResolveResponse](data) - case MethodTextDocumentFormatting: - return unmarshalValue[DocumentFormattingResponse](data) - case MethodTextDocumentRangeFormatting: - return unmarshalValue[DocumentRangeFormattingResponse](data) - case MethodTextDocumentRangesFormatting: - return unmarshalValue[DocumentRangesFormattingResponse](data) - case MethodTextDocumentOnTypeFormatting: - return unmarshalValue[DocumentOnTypeFormattingResponse](data) - case MethodTextDocumentRename: - return unmarshalValue[RenameResponse](data) - case MethodTextDocumentPrepareRename: - return unmarshalValue[PrepareRenameResponse](data) - case MethodWorkspaceExecuteCommand: - return unmarshalValue[ExecuteCommandResponse](data) - case MethodWorkspaceApplyEdit: - return unmarshalValue[ApplyWorkspaceEditResponse](data) - case MethodCustomRunGC: - return unmarshalValue[RunGCResponse](data) - case MethodCustomSaveHeapProfile: - return unmarshalValue[SaveHeapProfileResponse](data) - case MethodCustomSaveAllocProfile: - return unmarshalValue[SaveAllocProfileResponse](data) - case MethodCustomStartCPUProfile: - return unmarshalValue[StartCPUProfileResponse](data) - case MethodCustomStopCPUProfile: - return unmarshalValue[StopCPUProfileResponse](data) - case MethodCustomInitializeAPISession: - return unmarshalValue[CustomInitializeAPISessionResponse](data) - case MethodCustomProjectInfo: - return unmarshalValue[CustomProjectInfoResponse](data) - case MethodCustomTextDocumentSourceDefinition: - return unmarshalValue[CustomTextDocumentSourceDefinitionResponse](data) - case MethodCustomTextDocumentMultiDocumentHighlight: - return unmarshalValue[CustomMultiDocumentHighlightResponse](data) - case MethodTextDocumentVSOnAutoInsert: - return unmarshalValue[VSOnAutoInsertResponse](data) - case MethodTextDocumentVSReferences: - return unmarshalValue[VSReferencesResponse](data) - default: - return unmarshalAny(data) - } -} - // Methods const ( // A request to resolve the implementation locations of a symbol at a given text @@ -32648,15 +11571,7 @@ type IntegerOrString struct { var _ json.MarshalerTo = (*IntegerOrString)(nil) func (o *IntegerOrString) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of IntegerOrString should be set", boolToInt(o.Integer != nil)+boolToInt(o.String != nil)) - - if o.Integer != nil { - return json.MarshalEncode(enc, o.Integer) - } - if o.String != nil { - return json.MarshalEncode(enc, o.String) - } - panic("unreachable") + return marshalUnion(o, enc, "IntegerOrString", false) } var _ json.UnmarshalerFrom = (*IntegerOrString)(nil) @@ -32683,10 +11598,7 @@ type DocumentSelectorOrNull struct { var _ json.MarshalerTo = (*DocumentSelectorOrNull)(nil) func (o *DocumentSelectorOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.DocumentSelector != nil { - return json.MarshalEncode(enc, o.DocumentSelector) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "DocumentSelectorOrNull", true) } var _ json.UnmarshalerFrom = (*DocumentSelectorOrNull)(nil) @@ -32714,15 +11626,7 @@ type BooleanOrEmptyObject struct { var _ json.MarshalerTo = (*BooleanOrEmptyObject)(nil) func (o *BooleanOrEmptyObject) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrEmptyObject should be set", boolToInt(o.Boolean != nil)+boolToInt(o.EmptyObject != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.EmptyObject != nil { - return json.MarshalEncode(enc, o.EmptyObject) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrEmptyObject", false) } var _ json.UnmarshalerFrom = (*BooleanOrEmptyObject)(nil) @@ -32751,15 +11655,7 @@ type BooleanOrSemanticTokensFullDelta struct { var _ json.MarshalerTo = (*BooleanOrSemanticTokensFullDelta)(nil) func (o *BooleanOrSemanticTokensFullDelta) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrSemanticTokensFullDelta should be set", boolToInt(o.Boolean != nil)+boolToInt(o.SemanticTokensFullDelta != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.SemanticTokensFullDelta != nil { - return json.MarshalEncode(enc, o.SemanticTokensFullDelta) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrSemanticTokensFullDelta", false) } var _ json.UnmarshalerFrom = (*BooleanOrSemanticTokensFullDelta)(nil) @@ -32790,24 +11686,7 @@ type TextDocumentEditOrCreateFileOrRenameFileOrDeleteFile struct { var _ json.MarshalerTo = (*TextDocumentEditOrCreateFileOrRenameFileOrDeleteFile)(nil) func (o *TextDocumentEditOrCreateFileOrRenameFileOrDeleteFile) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of TextDocumentEditOrCreateFileOrRenameFileOrDeleteFile should be set", boolToInt(o.TextDocumentEdit != nil)+ - boolToInt(o.CreateFile != nil)+ - boolToInt(o.RenameFile != nil)+ - boolToInt(o.DeleteFile != nil)) - - if o.TextDocumentEdit != nil { - return json.MarshalEncode(enc, o.TextDocumentEdit) - } - if o.CreateFile != nil { - return json.MarshalEncode(enc, o.CreateFile) - } - if o.RenameFile != nil { - return json.MarshalEncode(enc, o.RenameFile) - } - if o.DeleteFile != nil { - return json.MarshalEncode(enc, o.DeleteFile) - } - panic("unreachable") + return marshalUnion(o, enc, "TextDocumentEditOrCreateFileOrRenameFileOrDeleteFile", false) } var _ json.UnmarshalerFrom = (*TextDocumentEditOrCreateFileOrRenameFileOrDeleteFile)(nil) @@ -32843,15 +11722,7 @@ type StringOrInlayHintLabelParts struct { var _ json.MarshalerTo = (*StringOrInlayHintLabelParts)(nil) func (o *StringOrInlayHintLabelParts) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of StringOrInlayHintLabelParts should be set", boolToInt(o.String != nil)+boolToInt(o.InlayHintLabelParts != nil)) - - if o.String != nil { - return json.MarshalEncode(enc, o.String) - } - if o.InlayHintLabelParts != nil { - return json.MarshalEncode(enc, o.InlayHintLabelParts) - } - panic("unreachable") + return marshalUnion(o, enc, "StringOrInlayHintLabelParts", false) } var _ json.UnmarshalerFrom = (*StringOrInlayHintLabelParts)(nil) @@ -32879,15 +11750,7 @@ type StringOrMarkupContent struct { var _ json.MarshalerTo = (*StringOrMarkupContent)(nil) func (o *StringOrMarkupContent) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of StringOrMarkupContent should be set", boolToInt(o.String != nil)+boolToInt(o.MarkupContent != nil)) - - if o.String != nil { - return json.MarshalEncode(enc, o.String) - } - if o.MarkupContent != nil { - return json.MarshalEncode(enc, o.MarkupContent) - } - panic("unreachable") + return marshalUnion(o, enc, "StringOrMarkupContent", false) } var _ json.UnmarshalerFrom = (*StringOrMarkupContent)(nil) @@ -32903,47 +11766,8 @@ func (o *StringOrMarkupContent) UnmarshalJSONFrom(dec *json.Decoder) error { o.MarkupContent = new(MarkupContent) return json.UnmarshalDecode(dec, o.MarkupContent) default: - return errInvalidKind("StringOrMarkupContent", dec.PeekKind()) - } -} - -type FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport struct { - FullDocumentDiagnosticReport *FullDocumentDiagnosticReport - UnchangedDocumentDiagnosticReport *UnchangedDocumentDiagnosticReport -} - -var _ json.MarshalerTo = (*FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport)(nil) - -func (o *FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport should be set", boolToInt(o.FullDocumentDiagnosticReport != nil)+boolToInt(o.UnchangedDocumentDiagnosticReport != nil)) - - if o.FullDocumentDiagnosticReport != nil { - return json.MarshalEncode(enc, o.FullDocumentDiagnosticReport) - } - if o.UnchangedDocumentDiagnosticReport != nil { - return json.MarshalEncode(enc, o.UnchangedDocumentDiagnosticReport) - } - panic("unreachable") -} - -var _ json.UnmarshalerFrom = (*FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport)(nil) - -func (o *FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport) UnmarshalJSONFrom(dec *json.Decoder) error { - *o = FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport{} - - data, err := dec.ReadValue() - if err != nil { - return err - } - switch string(jsonObjectRawField(data, "kind")) { - case `"full"`: - o.FullDocumentDiagnosticReport = new(FullDocumentDiagnosticReport) - return json.Unmarshal(data, o.FullDocumentDiagnosticReport) - case `"unchanged"`: - o.UnchangedDocumentDiagnosticReport = new(UnchangedDocumentDiagnosticReport) - return json.Unmarshal(data, o.UnchangedDocumentDiagnosticReport) + return errInvalidKind("StringOrMarkupContent", dec.PeekKind()) } - return errInvalidValue("FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport", data) } type WorkspaceFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport struct { @@ -32954,15 +11778,7 @@ type WorkspaceFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport st var _ json.MarshalerTo = (*WorkspaceFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport)(nil) func (o *WorkspaceFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of WorkspaceFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport should be set", boolToInt(o.FullDocumentDiagnosticReport != nil)+boolToInt(o.UnchangedDocumentDiagnosticReport != nil)) - - if o.FullDocumentDiagnosticReport != nil { - return json.MarshalEncode(enc, o.FullDocumentDiagnosticReport) - } - if o.UnchangedDocumentDiagnosticReport != nil { - return json.MarshalEncode(enc, o.UnchangedDocumentDiagnosticReport) - } - panic("unreachable") + return marshalUnion(o, enc, "WorkspaceFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport", false) } var _ json.UnmarshalerFrom = (*WorkspaceFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport)(nil) @@ -32993,15 +11809,7 @@ type StringOrStringValue struct { var _ json.MarshalerTo = (*StringOrStringValue)(nil) func (o *StringOrStringValue) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of StringOrStringValue should be set", boolToInt(o.String != nil)+boolToInt(o.StringValue != nil)) - - if o.String != nil { - return json.MarshalEncode(enc, o.String) - } - if o.StringValue != nil { - return json.MarshalEncode(enc, o.StringValue) - } - panic("unreachable") + return marshalUnion(o, enc, "StringOrStringValue", false) } var _ json.UnmarshalerFrom = (*StringOrStringValue)(nil) @@ -33028,10 +11836,7 @@ type IntegerOrNull struct { var _ json.MarshalerTo = (*IntegerOrNull)(nil) func (o *IntegerOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.Integer != nil { - return json.MarshalEncode(enc, o.Integer) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "IntegerOrNull", true) } var _ json.UnmarshalerFrom = (*IntegerOrNull)(nil) @@ -33058,10 +11863,7 @@ type StringOrNull struct { var _ json.MarshalerTo = (*StringOrNull)(nil) func (o *StringOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.String != nil { - return json.MarshalEncode(enc, o.String) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "StringOrNull", true) } var _ json.UnmarshalerFrom = (*StringOrNull)(nil) @@ -33088,10 +11890,7 @@ type DocumentUriOrNull struct { var _ json.MarshalerTo = (*DocumentUriOrNull)(nil) func (o *DocumentUriOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.DocumentUri != nil { - return json.MarshalEncode(enc, o.DocumentUri) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "DocumentUriOrNull", true) } var _ json.UnmarshalerFrom = (*DocumentUriOrNull)(nil) @@ -33118,10 +11917,7 @@ type InitializationOptionsOrNull struct { var _ json.MarshalerTo = (*InitializationOptionsOrNull)(nil) func (o *InitializationOptionsOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.InitializationOptions != nil { - return json.MarshalEncode(enc, o.InitializationOptions) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "InitializationOptionsOrNull", true) } var _ json.UnmarshalerFrom = (*InitializationOptionsOrNull)(nil) @@ -33148,10 +11944,7 @@ type WorkspaceFoldersOrNull struct { var _ json.MarshalerTo = (*WorkspaceFoldersOrNull)(nil) func (o *WorkspaceFoldersOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.WorkspaceFolders != nil { - return json.MarshalEncode(enc, o.WorkspaceFolders) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "WorkspaceFoldersOrNull", true) } var _ json.UnmarshalerFrom = (*WorkspaceFoldersOrNull)(nil) @@ -33179,15 +11972,7 @@ type StringOrStrings struct { var _ json.MarshalerTo = (*StringOrStrings)(nil) func (o *StringOrStrings) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of StringOrStrings should be set", boolToInt(o.String != nil)+boolToInt(o.Strings != nil)) - - if o.String != nil { - return json.MarshalEncode(enc, o.String) - } - if o.Strings != nil { - return json.MarshalEncode(enc, o.Strings) - } - panic("unreachable") + return marshalUnion(o, enc, "StringOrStrings", false) } var _ json.UnmarshalerFrom = (*StringOrStrings)(nil) @@ -33215,15 +12000,7 @@ type TextDocumentContentChangePartialOrWholeDocument struct { var _ json.MarshalerTo = (*TextDocumentContentChangePartialOrWholeDocument)(nil) func (o *TextDocumentContentChangePartialOrWholeDocument) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of TextDocumentContentChangePartialOrWholeDocument should be set", boolToInt(o.Partial != nil)+boolToInt(o.WholeDocument != nil)) - - if o.Partial != nil { - return json.MarshalEncode(enc, o.Partial) - } - if o.WholeDocument != nil { - return json.MarshalEncode(enc, o.WholeDocument) - } - panic("unreachable") + return marshalUnion(o, enc, "TextDocumentContentChangePartialOrWholeDocument", false) } var _ json.UnmarshalerFrom = (*TextDocumentContentChangePartialOrWholeDocument)(nil) @@ -33253,15 +12030,7 @@ type TextEditOrInsertReplaceEdit struct { var _ json.MarshalerTo = (*TextEditOrInsertReplaceEdit)(nil) func (o *TextEditOrInsertReplaceEdit) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of TextEditOrInsertReplaceEdit should be set", boolToInt(o.TextEdit != nil)+boolToInt(o.InsertReplaceEdit != nil)) - - if o.TextEdit != nil { - return json.MarshalEncode(enc, o.TextEdit) - } - if o.InsertReplaceEdit != nil { - return json.MarshalEncode(enc, o.InsertReplaceEdit) - } - panic("unreachable") + return marshalUnion(o, enc, "TextEditOrInsertReplaceEdit", false) } var _ json.UnmarshalerFrom = (*TextEditOrInsertReplaceEdit)(nil) @@ -33294,24 +12063,7 @@ type MarkupContentOrStringOrMarkedStringWithLanguageOrMarkedStrings struct { var _ json.MarshalerTo = (*MarkupContentOrStringOrMarkedStringWithLanguageOrMarkedStrings)(nil) func (o *MarkupContentOrStringOrMarkedStringWithLanguageOrMarkedStrings) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of MarkupContentOrStringOrMarkedStringWithLanguageOrMarkedStrings should be set", boolToInt(o.MarkupContent != nil)+ - boolToInt(o.String != nil)+ - boolToInt(o.MarkedStringWithLanguage != nil)+ - boolToInt(o.MarkedStrings != nil)) - - if o.MarkupContent != nil { - return json.MarshalEncode(enc, o.MarkupContent) - } - if o.String != nil { - return json.MarshalEncode(enc, o.String) - } - if o.MarkedStringWithLanguage != nil { - return json.MarshalEncode(enc, o.MarkedStringWithLanguage) - } - if o.MarkedStrings != nil { - return json.MarshalEncode(enc, o.MarkedStrings) - } - panic("unreachable") + return marshalUnion(o, enc, "MarkupContentOrStringOrMarkedStringWithLanguageOrMarkedStrings", false) } var _ json.UnmarshalerFrom = (*MarkupContentOrStringOrMarkedStringWithLanguageOrMarkedStrings)(nil) @@ -33352,10 +12104,7 @@ type UintegerOrNull struct { var _ json.MarshalerTo = (*UintegerOrNull)(nil) func (o *UintegerOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.Uinteger != nil { - return json.MarshalEncode(enc, o.Uinteger) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "UintegerOrNull", true) } var _ json.UnmarshalerFrom = (*UintegerOrNull)(nil) @@ -33383,15 +12132,7 @@ type LocationOrLocationUriOnly struct { var _ json.MarshalerTo = (*LocationOrLocationUriOnly)(nil) func (o *LocationOrLocationUriOnly) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of LocationOrLocationUriOnly should be set", boolToInt(o.Location != nil)+boolToInt(o.LocationUriOnly != nil)) - - if o.Location != nil { - return json.MarshalEncode(enc, o.Location) - } - if o.LocationUriOnly != nil { - return json.MarshalEncode(enc, o.LocationUriOnly) - } - panic("unreachable") + return marshalUnion(o, enc, "LocationOrLocationUriOnly", false) } var _ json.UnmarshalerFrom = (*LocationOrLocationUriOnly)(nil) @@ -33422,18 +12163,7 @@ type WorkDoneProgressBeginOrReportOrEnd struct { var _ json.MarshalerTo = (*WorkDoneProgressBeginOrReportOrEnd)(nil) func (o *WorkDoneProgressBeginOrReportOrEnd) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of WorkDoneProgressBeginOrReportOrEnd should be set", boolToInt(o.Begin != nil)+boolToInt(o.Report != nil)+boolToInt(o.End != nil)) - - if o.Begin != nil { - return json.MarshalEncode(enc, o.Begin) - } - if o.Report != nil { - return json.MarshalEncode(enc, o.Report) - } - if o.End != nil { - return json.MarshalEncode(enc, o.End) - } - panic("unreachable") + return marshalUnion(o, enc, "WorkDoneProgressBeginOrReportOrEnd", false) } var _ json.UnmarshalerFrom = (*WorkDoneProgressBeginOrReportOrEnd)(nil) @@ -33468,18 +12198,7 @@ type TextEditOrAnnotatedTextEditOrSnippetTextEdit struct { var _ json.MarshalerTo = (*TextEditOrAnnotatedTextEditOrSnippetTextEdit)(nil) func (o *TextEditOrAnnotatedTextEditOrSnippetTextEdit) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of TextEditOrAnnotatedTextEditOrSnippetTextEdit should be set", boolToInt(o.TextEdit != nil)+boolToInt(o.AnnotatedTextEdit != nil)+boolToInt(o.SnippetTextEdit != nil)) - - if o.TextEdit != nil { - return json.MarshalEncode(enc, o.TextEdit) - } - if o.AnnotatedTextEdit != nil { - return json.MarshalEncode(enc, o.AnnotatedTextEdit) - } - if o.SnippetTextEdit != nil { - return json.MarshalEncode(enc, o.SnippetTextEdit) - } - panic("unreachable") + return marshalUnion(o, enc, "TextEditOrAnnotatedTextEditOrSnippetTextEdit", false) } var _ json.UnmarshalerFrom = (*TextEditOrAnnotatedTextEditOrSnippetTextEdit)(nil) @@ -33504,6 +12223,37 @@ func (o *TextEditOrAnnotatedTextEditOrSnippetTextEdit) UnmarshalJSONFrom(dec *js } } +type FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport struct { + FullDocumentDiagnosticReport *FullDocumentDiagnosticReport + UnchangedDocumentDiagnosticReport *UnchangedDocumentDiagnosticReport +} + +var _ json.MarshalerTo = (*FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport)(nil) + +func (o *FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport) MarshalJSONTo(enc *json.Encoder) error { + return marshalUnion(o, enc, "FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport", false) +} + +var _ json.UnmarshalerFrom = (*FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport)(nil) + +func (o *FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport) UnmarshalJSONFrom(dec *json.Decoder) error { + *o = FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport{} + + data, err := dec.ReadValue() + if err != nil { + return err + } + switch string(jsonObjectRawField(data, "kind")) { + case `"full"`: + o.FullDocumentDiagnosticReport = new(FullDocumentDiagnosticReport) + return json.Unmarshal(data, o.FullDocumentDiagnosticReport) + case `"unchanged"`: + o.UnchangedDocumentDiagnosticReport = new(UnchangedDocumentDiagnosticReport) + return json.Unmarshal(data, o.UnchangedDocumentDiagnosticReport) + } + return errInvalidValue("FullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport", data) +} + type TextDocumentSyncOptionsOrKind struct { Options *TextDocumentSyncOptions Kind *TextDocumentSyncKind @@ -33512,15 +12262,7 @@ type TextDocumentSyncOptionsOrKind struct { var _ json.MarshalerTo = (*TextDocumentSyncOptionsOrKind)(nil) func (o *TextDocumentSyncOptionsOrKind) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of TextDocumentSyncOptionsOrKind should be set", boolToInt(o.Options != nil)+boolToInt(o.Kind != nil)) - - if o.Options != nil { - return json.MarshalEncode(enc, o.Options) - } - if o.Kind != nil { - return json.MarshalEncode(enc, o.Kind) - } - panic("unreachable") + return marshalUnion(o, enc, "TextDocumentSyncOptionsOrKind", false) } var _ json.UnmarshalerFrom = (*TextDocumentSyncOptionsOrKind)(nil) @@ -33548,15 +12290,7 @@ type BooleanOrHoverOptions struct { var _ json.MarshalerTo = (*BooleanOrHoverOptions)(nil) func (o *BooleanOrHoverOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrHoverOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.HoverOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.HoverOptions != nil { - return json.MarshalEncode(enc, o.HoverOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrHoverOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrHoverOptions)(nil) @@ -33586,18 +12320,7 @@ type BooleanOrDeclarationOptionsOrDeclarationRegistrationOptions struct { var _ json.MarshalerTo = (*BooleanOrDeclarationOptionsOrDeclarationRegistrationOptions)(nil) func (o *BooleanOrDeclarationOptionsOrDeclarationRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrDeclarationOptionsOrDeclarationRegistrationOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.DeclarationOptions != nil)+boolToInt(o.DeclarationRegistrationOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.DeclarationOptions != nil { - return json.MarshalEncode(enc, o.DeclarationOptions) - } - if o.DeclarationRegistrationOptions != nil { - return json.MarshalEncode(enc, o.DeclarationRegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrDeclarationOptionsOrDeclarationRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrDeclarationOptionsOrDeclarationRegistrationOptions)(nil) @@ -33636,15 +12359,7 @@ type BooleanOrDefinitionOptions struct { var _ json.MarshalerTo = (*BooleanOrDefinitionOptions)(nil) func (o *BooleanOrDefinitionOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrDefinitionOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.DefinitionOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.DefinitionOptions != nil { - return json.MarshalEncode(enc, o.DefinitionOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrDefinitionOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrDefinitionOptions)(nil) @@ -33674,18 +12389,7 @@ type BooleanOrTypeDefinitionOptionsOrTypeDefinitionRegistrationOptions struct { var _ json.MarshalerTo = (*BooleanOrTypeDefinitionOptionsOrTypeDefinitionRegistrationOptions)(nil) func (o *BooleanOrTypeDefinitionOptionsOrTypeDefinitionRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrTypeDefinitionOptionsOrTypeDefinitionRegistrationOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.TypeDefinitionOptions != nil)+boolToInt(o.TypeDefinitionRegistrationOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.TypeDefinitionOptions != nil { - return json.MarshalEncode(enc, o.TypeDefinitionOptions) - } - if o.TypeDefinitionRegistrationOptions != nil { - return json.MarshalEncode(enc, o.TypeDefinitionRegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrTypeDefinitionOptionsOrTypeDefinitionRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrTypeDefinitionOptionsOrTypeDefinitionRegistrationOptions)(nil) @@ -33725,18 +12429,7 @@ type BooleanOrImplementationOptionsOrImplementationRegistrationOptions struct { var _ json.MarshalerTo = (*BooleanOrImplementationOptionsOrImplementationRegistrationOptions)(nil) func (o *BooleanOrImplementationOptionsOrImplementationRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrImplementationOptionsOrImplementationRegistrationOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.ImplementationOptions != nil)+boolToInt(o.ImplementationRegistrationOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.ImplementationOptions != nil { - return json.MarshalEncode(enc, o.ImplementationOptions) - } - if o.ImplementationRegistrationOptions != nil { - return json.MarshalEncode(enc, o.ImplementationRegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrImplementationOptionsOrImplementationRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrImplementationOptionsOrImplementationRegistrationOptions)(nil) @@ -33775,15 +12468,7 @@ type BooleanOrReferenceOptions struct { var _ json.MarshalerTo = (*BooleanOrReferenceOptions)(nil) func (o *BooleanOrReferenceOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrReferenceOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.ReferenceOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.ReferenceOptions != nil { - return json.MarshalEncode(enc, o.ReferenceOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrReferenceOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrReferenceOptions)(nil) @@ -33812,15 +12497,7 @@ type BooleanOrDocumentHighlightOptions struct { var _ json.MarshalerTo = (*BooleanOrDocumentHighlightOptions)(nil) func (o *BooleanOrDocumentHighlightOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrDocumentHighlightOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.DocumentHighlightOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.DocumentHighlightOptions != nil { - return json.MarshalEncode(enc, o.DocumentHighlightOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrDocumentHighlightOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrDocumentHighlightOptions)(nil) @@ -33849,15 +12526,7 @@ type BooleanOrDocumentSymbolOptions struct { var _ json.MarshalerTo = (*BooleanOrDocumentSymbolOptions)(nil) func (o *BooleanOrDocumentSymbolOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrDocumentSymbolOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.DocumentSymbolOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.DocumentSymbolOptions != nil { - return json.MarshalEncode(enc, o.DocumentSymbolOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrDocumentSymbolOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrDocumentSymbolOptions)(nil) @@ -33886,15 +12555,7 @@ type BooleanOrCodeActionOptions struct { var _ json.MarshalerTo = (*BooleanOrCodeActionOptions)(nil) func (o *BooleanOrCodeActionOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrCodeActionOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.CodeActionOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.CodeActionOptions != nil { - return json.MarshalEncode(enc, o.CodeActionOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrCodeActionOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrCodeActionOptions)(nil) @@ -33924,18 +12585,7 @@ type BooleanOrDocumentColorOptionsOrDocumentColorRegistrationOptions struct { var _ json.MarshalerTo = (*BooleanOrDocumentColorOptionsOrDocumentColorRegistrationOptions)(nil) func (o *BooleanOrDocumentColorOptionsOrDocumentColorRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrDocumentColorOptionsOrDocumentColorRegistrationOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.DocumentColorOptions != nil)+boolToInt(o.DocumentColorRegistrationOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.DocumentColorOptions != nil { - return json.MarshalEncode(enc, o.DocumentColorOptions) - } - if o.DocumentColorRegistrationOptions != nil { - return json.MarshalEncode(enc, o.DocumentColorRegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrDocumentColorOptionsOrDocumentColorRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrDocumentColorOptionsOrDocumentColorRegistrationOptions)(nil) @@ -33974,15 +12624,7 @@ type BooleanOrWorkspaceSymbolOptions struct { var _ json.MarshalerTo = (*BooleanOrWorkspaceSymbolOptions)(nil) func (o *BooleanOrWorkspaceSymbolOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrWorkspaceSymbolOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.WorkspaceSymbolOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.WorkspaceSymbolOptions != nil { - return json.MarshalEncode(enc, o.WorkspaceSymbolOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrWorkspaceSymbolOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrWorkspaceSymbolOptions)(nil) @@ -34011,15 +12653,7 @@ type BooleanOrDocumentFormattingOptions struct { var _ json.MarshalerTo = (*BooleanOrDocumentFormattingOptions)(nil) func (o *BooleanOrDocumentFormattingOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrDocumentFormattingOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.DocumentFormattingOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.DocumentFormattingOptions != nil { - return json.MarshalEncode(enc, o.DocumentFormattingOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrDocumentFormattingOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrDocumentFormattingOptions)(nil) @@ -34048,15 +12682,7 @@ type BooleanOrDocumentRangeFormattingOptions struct { var _ json.MarshalerTo = (*BooleanOrDocumentRangeFormattingOptions)(nil) func (o *BooleanOrDocumentRangeFormattingOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrDocumentRangeFormattingOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.DocumentRangeFormattingOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.DocumentRangeFormattingOptions != nil { - return json.MarshalEncode(enc, o.DocumentRangeFormattingOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrDocumentRangeFormattingOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrDocumentRangeFormattingOptions)(nil) @@ -34085,15 +12711,7 @@ type BooleanOrRenameOptions struct { var _ json.MarshalerTo = (*BooleanOrRenameOptions)(nil) func (o *BooleanOrRenameOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrRenameOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.RenameOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.RenameOptions != nil { - return json.MarshalEncode(enc, o.RenameOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrRenameOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrRenameOptions)(nil) @@ -34123,18 +12741,7 @@ type BooleanOrFoldingRangeOptionsOrFoldingRangeRegistrationOptions struct { var _ json.MarshalerTo = (*BooleanOrFoldingRangeOptionsOrFoldingRangeRegistrationOptions)(nil) func (o *BooleanOrFoldingRangeOptionsOrFoldingRangeRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrFoldingRangeOptionsOrFoldingRangeRegistrationOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.FoldingRangeOptions != nil)+boolToInt(o.FoldingRangeRegistrationOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.FoldingRangeOptions != nil { - return json.MarshalEncode(enc, o.FoldingRangeOptions) - } - if o.FoldingRangeRegistrationOptions != nil { - return json.MarshalEncode(enc, o.FoldingRangeRegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrFoldingRangeOptionsOrFoldingRangeRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrFoldingRangeOptionsOrFoldingRangeRegistrationOptions)(nil) @@ -34174,18 +12781,7 @@ type BooleanOrSelectionRangeOptionsOrSelectionRangeRegistrationOptions struct { var _ json.MarshalerTo = (*BooleanOrSelectionRangeOptionsOrSelectionRangeRegistrationOptions)(nil) func (o *BooleanOrSelectionRangeOptionsOrSelectionRangeRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrSelectionRangeOptionsOrSelectionRangeRegistrationOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.SelectionRangeOptions != nil)+boolToInt(o.SelectionRangeRegistrationOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.SelectionRangeOptions != nil { - return json.MarshalEncode(enc, o.SelectionRangeOptions) - } - if o.SelectionRangeRegistrationOptions != nil { - return json.MarshalEncode(enc, o.SelectionRangeRegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrSelectionRangeOptionsOrSelectionRangeRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrSelectionRangeOptionsOrSelectionRangeRegistrationOptions)(nil) @@ -34225,18 +12821,7 @@ type BooleanOrCallHierarchyOptionsOrCallHierarchyRegistrationOptions struct { var _ json.MarshalerTo = (*BooleanOrCallHierarchyOptionsOrCallHierarchyRegistrationOptions)(nil) func (o *BooleanOrCallHierarchyOptionsOrCallHierarchyRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrCallHierarchyOptionsOrCallHierarchyRegistrationOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.CallHierarchyOptions != nil)+boolToInt(o.CallHierarchyRegistrationOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.CallHierarchyOptions != nil { - return json.MarshalEncode(enc, o.CallHierarchyOptions) - } - if o.CallHierarchyRegistrationOptions != nil { - return json.MarshalEncode(enc, o.CallHierarchyRegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrCallHierarchyOptionsOrCallHierarchyRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrCallHierarchyOptionsOrCallHierarchyRegistrationOptions)(nil) @@ -34276,18 +12861,7 @@ type BooleanOrLinkedEditingRangeOptionsOrLinkedEditingRangeRegistrationOptions s var _ json.MarshalerTo = (*BooleanOrLinkedEditingRangeOptionsOrLinkedEditingRangeRegistrationOptions)(nil) func (o *BooleanOrLinkedEditingRangeOptionsOrLinkedEditingRangeRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrLinkedEditingRangeOptionsOrLinkedEditingRangeRegistrationOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.LinkedEditingRangeOptions != nil)+boolToInt(o.LinkedEditingRangeRegistrationOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.LinkedEditingRangeOptions != nil { - return json.MarshalEncode(enc, o.LinkedEditingRangeOptions) - } - if o.LinkedEditingRangeRegistrationOptions != nil { - return json.MarshalEncode(enc, o.LinkedEditingRangeRegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrLinkedEditingRangeOptionsOrLinkedEditingRangeRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrLinkedEditingRangeOptionsOrLinkedEditingRangeRegistrationOptions)(nil) @@ -34326,15 +12900,7 @@ type SemanticTokensOptionsOrRegistrationOptions struct { var _ json.MarshalerTo = (*SemanticTokensOptionsOrRegistrationOptions)(nil) func (o *SemanticTokensOptionsOrRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of SemanticTokensOptionsOrRegistrationOptions should be set", boolToInt(o.Options != nil)+boolToInt(o.RegistrationOptions != nil)) - - if o.Options != nil { - return json.MarshalEncode(enc, o.Options) - } - if o.RegistrationOptions != nil { - return json.MarshalEncode(enc, o.RegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "SemanticTokensOptionsOrRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*SemanticTokensOptionsOrRegistrationOptions)(nil) @@ -34365,18 +12931,7 @@ type BooleanOrMonikerOptionsOrMonikerRegistrationOptions struct { var _ json.MarshalerTo = (*BooleanOrMonikerOptionsOrMonikerRegistrationOptions)(nil) func (o *BooleanOrMonikerOptionsOrMonikerRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrMonikerOptionsOrMonikerRegistrationOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.MonikerOptions != nil)+boolToInt(o.MonikerRegistrationOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.MonikerOptions != nil { - return json.MarshalEncode(enc, o.MonikerOptions) - } - if o.MonikerRegistrationOptions != nil { - return json.MarshalEncode(enc, o.MonikerRegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrMonikerOptionsOrMonikerRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrMonikerOptionsOrMonikerRegistrationOptions)(nil) @@ -34416,18 +12971,7 @@ type BooleanOrTypeHierarchyOptionsOrTypeHierarchyRegistrationOptions struct { var _ json.MarshalerTo = (*BooleanOrTypeHierarchyOptionsOrTypeHierarchyRegistrationOptions)(nil) func (o *BooleanOrTypeHierarchyOptionsOrTypeHierarchyRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrTypeHierarchyOptionsOrTypeHierarchyRegistrationOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.TypeHierarchyOptions != nil)+boolToInt(o.TypeHierarchyRegistrationOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.TypeHierarchyOptions != nil { - return json.MarshalEncode(enc, o.TypeHierarchyOptions) - } - if o.TypeHierarchyRegistrationOptions != nil { - return json.MarshalEncode(enc, o.TypeHierarchyRegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrTypeHierarchyOptionsOrTypeHierarchyRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrTypeHierarchyOptionsOrTypeHierarchyRegistrationOptions)(nil) @@ -34467,18 +13011,7 @@ type BooleanOrInlineValueOptionsOrInlineValueRegistrationOptions struct { var _ json.MarshalerTo = (*BooleanOrInlineValueOptionsOrInlineValueRegistrationOptions)(nil) func (o *BooleanOrInlineValueOptionsOrInlineValueRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrInlineValueOptionsOrInlineValueRegistrationOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.InlineValueOptions != nil)+boolToInt(o.InlineValueRegistrationOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.InlineValueOptions != nil { - return json.MarshalEncode(enc, o.InlineValueOptions) - } - if o.InlineValueRegistrationOptions != nil { - return json.MarshalEncode(enc, o.InlineValueRegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrInlineValueOptionsOrInlineValueRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrInlineValueOptionsOrInlineValueRegistrationOptions)(nil) @@ -34518,18 +13051,7 @@ type BooleanOrInlayHintOptionsOrInlayHintRegistrationOptions struct { var _ json.MarshalerTo = (*BooleanOrInlayHintOptionsOrInlayHintRegistrationOptions)(nil) func (o *BooleanOrInlayHintOptionsOrInlayHintRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrInlayHintOptionsOrInlayHintRegistrationOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.InlayHintOptions != nil)+boolToInt(o.InlayHintRegistrationOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.InlayHintOptions != nil { - return json.MarshalEncode(enc, o.InlayHintOptions) - } - if o.InlayHintRegistrationOptions != nil { - return json.MarshalEncode(enc, o.InlayHintRegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrInlayHintOptionsOrInlayHintRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrInlayHintOptionsOrInlayHintRegistrationOptions)(nil) @@ -34568,15 +13090,7 @@ type DiagnosticOptionsOrRegistrationOptions struct { var _ json.MarshalerTo = (*DiagnosticOptionsOrRegistrationOptions)(nil) func (o *DiagnosticOptionsOrRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of DiagnosticOptionsOrRegistrationOptions should be set", boolToInt(o.Options != nil)+boolToInt(o.RegistrationOptions != nil)) - - if o.Options != nil { - return json.MarshalEncode(enc, o.Options) - } - if o.RegistrationOptions != nil { - return json.MarshalEncode(enc, o.RegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "DiagnosticOptionsOrRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*DiagnosticOptionsOrRegistrationOptions)(nil) @@ -34606,15 +13120,7 @@ type BooleanOrInlineCompletionOptions struct { var _ json.MarshalerTo = (*BooleanOrInlineCompletionOptions)(nil) func (o *BooleanOrInlineCompletionOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrInlineCompletionOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.InlineCompletionOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.InlineCompletionOptions != nil { - return json.MarshalEncode(enc, o.InlineCompletionOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrInlineCompletionOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrInlineCompletionOptions)(nil) @@ -34643,15 +13149,7 @@ type PatternOrRelativePattern struct { var _ json.MarshalerTo = (*PatternOrRelativePattern)(nil) func (o *PatternOrRelativePattern) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of PatternOrRelativePattern should be set", boolToInt(o.Pattern != nil)+boolToInt(o.RelativePattern != nil)) - - if o.Pattern != nil { - return json.MarshalEncode(enc, o.Pattern) - } - if o.RelativePattern != nil { - return json.MarshalEncode(enc, o.RelativePattern) - } - panic("unreachable") + return marshalUnion(o, enc, "PatternOrRelativePattern", false) } var _ json.UnmarshalerFrom = (*PatternOrRelativePattern)(nil) @@ -34679,15 +13177,7 @@ type RangeOrEditRangeWithInsertReplace struct { var _ json.MarshalerTo = (*RangeOrEditRangeWithInsertReplace)(nil) func (o *RangeOrEditRangeWithInsertReplace) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of RangeOrEditRangeWithInsertReplace should be set", boolToInt(o.Range != nil)+boolToInt(o.EditRangeWithInsertReplace != nil)) - - if o.Range != nil { - return json.MarshalEncode(enc, o.Range) - } - if o.EditRangeWithInsertReplace != nil { - return json.MarshalEncode(enc, o.EditRangeWithInsertReplace) - } - panic("unreachable") + return marshalUnion(o, enc, "RangeOrEditRangeWithInsertReplace", false) } var _ json.UnmarshalerFrom = (*RangeOrEditRangeWithInsertReplace)(nil) @@ -34718,15 +13208,7 @@ type BooleanOrSaveOptions struct { var _ json.MarshalerTo = (*BooleanOrSaveOptions)(nil) func (o *BooleanOrSaveOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrSaveOptions should be set", boolToInt(o.Boolean != nil)+boolToInt(o.SaveOptions != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.SaveOptions != nil { - return json.MarshalEncode(enc, o.SaveOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrSaveOptions", false) } var _ json.UnmarshalerFrom = (*BooleanOrSaveOptions)(nil) @@ -34755,15 +13237,7 @@ type TextDocumentContentOptionsOrRegistrationOptions struct { var _ json.MarshalerTo = (*TextDocumentContentOptionsOrRegistrationOptions)(nil) func (o *TextDocumentContentOptionsOrRegistrationOptions) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of TextDocumentContentOptionsOrRegistrationOptions should be set", boolToInt(o.Options != nil)+boolToInt(o.RegistrationOptions != nil)) - - if o.Options != nil { - return json.MarshalEncode(enc, o.Options) - } - if o.RegistrationOptions != nil { - return json.MarshalEncode(enc, o.RegistrationOptions) - } - panic("unreachable") + return marshalUnion(o, enc, "TextDocumentContentOptionsOrRegistrationOptions", false) } var _ json.UnmarshalerFrom = (*TextDocumentContentOptionsOrRegistrationOptions)(nil) @@ -34796,15 +13270,7 @@ type StringOrTuple struct { var _ json.MarshalerTo = (*StringOrTuple)(nil) func (o *StringOrTuple) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of StringOrTuple should be set", boolToInt(o.String != nil)+boolToInt(o.Tuple != nil)) - - if o.String != nil { - return json.MarshalEncode(enc, o.String) - } - if o.Tuple != nil { - return json.MarshalEncode(enc, o.Tuple) - } - panic("unreachable") + return marshalUnion(o, enc, "StringOrTuple", false) } var _ json.UnmarshalerFrom = (*StringOrTuple)(nil) @@ -34832,15 +13298,7 @@ type StringOrBoolean struct { var _ json.MarshalerTo = (*StringOrBoolean)(nil) func (o *StringOrBoolean) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of StringOrBoolean should be set", boolToInt(o.String != nil)+boolToInt(o.Boolean != nil)) - - if o.String != nil { - return json.MarshalEncode(enc, o.String) - } - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - panic("unreachable") + return marshalUnion(o, enc, "StringOrBoolean", false) } var _ json.UnmarshalerFrom = (*StringOrBoolean)(nil) @@ -34869,15 +13327,7 @@ type WorkspaceFolderOrURI struct { var _ json.MarshalerTo = (*WorkspaceFolderOrURI)(nil) func (o *WorkspaceFolderOrURI) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of WorkspaceFolderOrURI should be set", boolToInt(o.WorkspaceFolder != nil)+boolToInt(o.URI != nil)) - - if o.WorkspaceFolder != nil { - return json.MarshalEncode(enc, o.WorkspaceFolder) - } - if o.URI != nil { - return json.MarshalEncode(enc, o.URI) - } - panic("unreachable") + return marshalUnion(o, enc, "WorkspaceFolderOrURI", false) } var _ json.UnmarshalerFrom = (*WorkspaceFolderOrURI)(nil) @@ -34905,15 +13355,7 @@ type BooleanOrClientSemanticTokensRequestFullDelta struct { var _ json.MarshalerTo = (*BooleanOrClientSemanticTokensRequestFullDelta)(nil) func (o *BooleanOrClientSemanticTokensRequestFullDelta) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of BooleanOrClientSemanticTokensRequestFullDelta should be set", boolToInt(o.Boolean != nil)+boolToInt(o.ClientSemanticTokensRequestFullDelta != nil)) - - if o.Boolean != nil { - return json.MarshalEncode(enc, o.Boolean) - } - if o.ClientSemanticTokensRequestFullDelta != nil { - return json.MarshalEncode(enc, o.ClientSemanticTokensRequestFullDelta) - } - panic("unreachable") + return marshalUnion(o, enc, "BooleanOrClientSemanticTokensRequestFullDelta", false) } var _ json.UnmarshalerFrom = (*BooleanOrClientSemanticTokensRequestFullDelta)(nil) @@ -34943,18 +13385,7 @@ type LocationOrLocationsOrDefinitionLinksOrNull struct { var _ json.MarshalerTo = (*LocationOrLocationsOrDefinitionLinksOrNull)(nil) func (o *LocationOrLocationsOrDefinitionLinksOrNull) MarshalJSONTo(enc *json.Encoder) error { - assertAtMostOne("more than one element of LocationOrLocationsOrDefinitionLinksOrNull is set", boolToInt(o.Location != nil)+boolToInt(o.Locations != nil)+boolToInt(o.DefinitionLinks != nil)) - - if o.Location != nil { - return json.MarshalEncode(enc, o.Location) - } - if o.Locations != nil { - return json.MarshalEncode(enc, o.Locations) - } - if o.DefinitionLinks != nil { - return json.MarshalEncode(enc, o.DefinitionLinks) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "LocationOrLocationsOrDefinitionLinksOrNull", true) } var _ json.UnmarshalerFrom = (*LocationOrLocationsOrDefinitionLinksOrNull)(nil) @@ -35001,10 +13432,7 @@ type FoldingRangesOrNull struct { var _ json.MarshalerTo = (*FoldingRangesOrNull)(nil) func (o *FoldingRangesOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.FoldingRanges != nil { - return json.MarshalEncode(enc, o.FoldingRanges) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "FoldingRangesOrNull", true) } var _ json.UnmarshalerFrom = (*FoldingRangesOrNull)(nil) @@ -35033,18 +13461,7 @@ type LocationOrLocationsOrDeclarationLinksOrNull struct { var _ json.MarshalerTo = (*LocationOrLocationsOrDeclarationLinksOrNull)(nil) func (o *LocationOrLocationsOrDeclarationLinksOrNull) MarshalJSONTo(enc *json.Encoder) error { - assertAtMostOne("more than one element of LocationOrLocationsOrDeclarationLinksOrNull is set", boolToInt(o.Location != nil)+boolToInt(o.Locations != nil)+boolToInt(o.DeclarationLinks != nil)) - - if o.Location != nil { - return json.MarshalEncode(enc, o.Location) - } - if o.Locations != nil { - return json.MarshalEncode(enc, o.Locations) - } - if o.DeclarationLinks != nil { - return json.MarshalEncode(enc, o.DeclarationLinks) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "LocationOrLocationsOrDeclarationLinksOrNull", true) } var _ json.UnmarshalerFrom = (*LocationOrLocationsOrDeclarationLinksOrNull)(nil) @@ -35091,10 +13508,7 @@ type SelectionRangesOrNull struct { var _ json.MarshalerTo = (*SelectionRangesOrNull)(nil) func (o *SelectionRangesOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.SelectionRanges != nil { - return json.MarshalEncode(enc, o.SelectionRanges) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "SelectionRangesOrNull", true) } var _ json.UnmarshalerFrom = (*SelectionRangesOrNull)(nil) @@ -35121,10 +13535,7 @@ type CallHierarchyItemsOrNull struct { var _ json.MarshalerTo = (*CallHierarchyItemsOrNull)(nil) func (o *CallHierarchyItemsOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.CallHierarchyItems != nil { - return json.MarshalEncode(enc, o.CallHierarchyItems) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "CallHierarchyItemsOrNull", true) } var _ json.UnmarshalerFrom = (*CallHierarchyItemsOrNull)(nil) @@ -35151,10 +13562,7 @@ type CallHierarchyIncomingCallsOrNull struct { var _ json.MarshalerTo = (*CallHierarchyIncomingCallsOrNull)(nil) func (o *CallHierarchyIncomingCallsOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.CallHierarchyIncomingCalls != nil { - return json.MarshalEncode(enc, o.CallHierarchyIncomingCalls) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "CallHierarchyIncomingCallsOrNull", true) } var _ json.UnmarshalerFrom = (*CallHierarchyIncomingCallsOrNull)(nil) @@ -35181,10 +13589,7 @@ type CallHierarchyOutgoingCallsOrNull struct { var _ json.MarshalerTo = (*CallHierarchyOutgoingCallsOrNull)(nil) func (o *CallHierarchyOutgoingCallsOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.CallHierarchyOutgoingCalls != nil { - return json.MarshalEncode(enc, o.CallHierarchyOutgoingCalls) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "CallHierarchyOutgoingCallsOrNull", true) } var _ json.UnmarshalerFrom = (*CallHierarchyOutgoingCallsOrNull)(nil) @@ -35211,10 +13616,7 @@ type SemanticTokensOrNull struct { var _ json.MarshalerTo = (*SemanticTokensOrNull)(nil) func (o *SemanticTokensOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.SemanticTokens != nil { - return json.MarshalEncode(enc, o.SemanticTokens) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "SemanticTokensOrNull", true) } var _ json.UnmarshalerFrom = (*SemanticTokensOrNull)(nil) @@ -35242,15 +13644,7 @@ type SemanticTokensOrSemanticTokensDeltaOrNull struct { var _ json.MarshalerTo = (*SemanticTokensOrSemanticTokensDeltaOrNull)(nil) func (o *SemanticTokensOrSemanticTokensDeltaOrNull) MarshalJSONTo(enc *json.Encoder) error { - assertAtMostOne("more than one element of SemanticTokensOrSemanticTokensDeltaOrNull is set", boolToInt(o.SemanticTokens != nil)+boolToInt(o.SemanticTokensDelta != nil)) - - if o.SemanticTokens != nil { - return json.MarshalEncode(enc, o.SemanticTokens) - } - if o.SemanticTokensDelta != nil { - return json.MarshalEncode(enc, o.SemanticTokensDelta) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "SemanticTokensOrSemanticTokensDeltaOrNull", true) } var _ json.UnmarshalerFrom = (*SemanticTokensOrSemanticTokensDeltaOrNull)(nil) @@ -35288,10 +13682,7 @@ type LinkedEditingRangesOrNull struct { var _ json.MarshalerTo = (*LinkedEditingRangesOrNull)(nil) func (o *LinkedEditingRangesOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.LinkedEditingRanges != nil { - return json.MarshalEncode(enc, o.LinkedEditingRanges) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "LinkedEditingRangesOrNull", true) } var _ json.UnmarshalerFrom = (*LinkedEditingRangesOrNull)(nil) @@ -35318,10 +13709,7 @@ type WorkspaceEditOrNull struct { var _ json.MarshalerTo = (*WorkspaceEditOrNull)(nil) func (o *WorkspaceEditOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.WorkspaceEdit != nil { - return json.MarshalEncode(enc, o.WorkspaceEdit) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "WorkspaceEditOrNull", true) } var _ json.UnmarshalerFrom = (*WorkspaceEditOrNull)(nil) @@ -35348,10 +13736,7 @@ type MonikersOrNull struct { var _ json.MarshalerTo = (*MonikersOrNull)(nil) func (o *MonikersOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.Monikers != nil { - return json.MarshalEncode(enc, o.Monikers) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "MonikersOrNull", true) } var _ json.UnmarshalerFrom = (*MonikersOrNull)(nil) @@ -35378,10 +13763,7 @@ type TypeHierarchyItemsOrNull struct { var _ json.MarshalerTo = (*TypeHierarchyItemsOrNull)(nil) func (o *TypeHierarchyItemsOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.TypeHierarchyItems != nil { - return json.MarshalEncode(enc, o.TypeHierarchyItems) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "TypeHierarchyItemsOrNull", true) } var _ json.UnmarshalerFrom = (*TypeHierarchyItemsOrNull)(nil) @@ -35408,10 +13790,7 @@ type InlineValuesOrNull struct { var _ json.MarshalerTo = (*InlineValuesOrNull)(nil) func (o *InlineValuesOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.InlineValues != nil { - return json.MarshalEncode(enc, o.InlineValues) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "InlineValuesOrNull", true) } var _ json.UnmarshalerFrom = (*InlineValuesOrNull)(nil) @@ -35438,10 +13817,7 @@ type InlayHintsOrNull struct { var _ json.MarshalerTo = (*InlayHintsOrNull)(nil) func (o *InlayHintsOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.InlayHints != nil { - return json.MarshalEncode(enc, o.InlayHints) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "InlayHintsOrNull", true) } var _ json.UnmarshalerFrom = (*InlayHintsOrNull)(nil) @@ -35469,15 +13845,7 @@ type RelatedFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport stru var _ json.MarshalerTo = (*RelatedFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport)(nil) func (o *RelatedFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of RelatedFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport should be set", boolToInt(o.FullDocumentDiagnosticReport != nil)+boolToInt(o.UnchangedDocumentDiagnosticReport != nil)) - - if o.FullDocumentDiagnosticReport != nil { - return json.MarshalEncode(enc, o.FullDocumentDiagnosticReport) - } - if o.UnchangedDocumentDiagnosticReport != nil { - return json.MarshalEncode(enc, o.UnchangedDocumentDiagnosticReport) - } - panic("unreachable") + return marshalUnion(o, enc, "RelatedFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport", false) } var _ json.UnmarshalerFrom = (*RelatedFullDocumentDiagnosticReportOrUnchangedDocumentDiagnosticReport)(nil) @@ -35508,15 +13876,7 @@ type InlineCompletionListOrItemsOrNull struct { var _ json.MarshalerTo = (*InlineCompletionListOrItemsOrNull)(nil) func (o *InlineCompletionListOrItemsOrNull) MarshalJSONTo(enc *json.Encoder) error { - assertAtMostOne("more than one element of InlineCompletionListOrItemsOrNull is set", boolToInt(o.List != nil)+boolToInt(o.Items != nil)) - - if o.List != nil { - return json.MarshalEncode(enc, o.List) - } - if o.Items != nil { - return json.MarshalEncode(enc, o.Items) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "InlineCompletionListOrItemsOrNull", true) } var _ json.UnmarshalerFrom = (*InlineCompletionListOrItemsOrNull)(nil) @@ -35546,10 +13906,7 @@ type MessageActionItemOrNull struct { var _ json.MarshalerTo = (*MessageActionItemOrNull)(nil) func (o *MessageActionItemOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.MessageActionItem != nil { - return json.MarshalEncode(enc, o.MessageActionItem) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "MessageActionItemOrNull", true) } var _ json.UnmarshalerFrom = (*MessageActionItemOrNull)(nil) @@ -35576,10 +13933,7 @@ type TextEditsOrNull struct { var _ json.MarshalerTo = (*TextEditsOrNull)(nil) func (o *TextEditsOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.TextEdits != nil { - return json.MarshalEncode(enc, o.TextEdits) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "TextEditsOrNull", true) } var _ json.UnmarshalerFrom = (*TextEditsOrNull)(nil) @@ -35607,15 +13961,7 @@ type CompletionItemsOrListOrNull struct { var _ json.MarshalerTo = (*CompletionItemsOrListOrNull)(nil) func (o *CompletionItemsOrListOrNull) MarshalJSONTo(enc *json.Encoder) error { - assertAtMostOne("more than one element of CompletionItemsOrListOrNull is set", boolToInt(o.Items != nil)+boolToInt(o.List != nil)) - - if o.Items != nil { - return json.MarshalEncode(enc, o.Items) - } - if o.List != nil { - return json.MarshalEncode(enc, o.List) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "CompletionItemsOrListOrNull", true) } var _ json.UnmarshalerFrom = (*CompletionItemsOrListOrNull)(nil) @@ -35645,10 +13991,7 @@ type HoverOrNull struct { var _ json.MarshalerTo = (*HoverOrNull)(nil) func (o *HoverOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.Hover != nil { - return json.MarshalEncode(enc, o.Hover) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "HoverOrNull", true) } var _ json.UnmarshalerFrom = (*HoverOrNull)(nil) @@ -35675,10 +14018,7 @@ type SignatureHelpOrNull struct { var _ json.MarshalerTo = (*SignatureHelpOrNull)(nil) func (o *SignatureHelpOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.SignatureHelp != nil { - return json.MarshalEncode(enc, o.SignatureHelp) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "SignatureHelpOrNull", true) } var _ json.UnmarshalerFrom = (*SignatureHelpOrNull)(nil) @@ -35705,10 +14045,7 @@ type LocationsOrNull struct { var _ json.MarshalerTo = (*LocationsOrNull)(nil) func (o *LocationsOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.Locations != nil { - return json.MarshalEncode(enc, o.Locations) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "LocationsOrNull", true) } var _ json.UnmarshalerFrom = (*LocationsOrNull)(nil) @@ -35739,10 +14076,7 @@ type DocumentHighlightsOrNull struct { var _ json.MarshalerTo = (*DocumentHighlightsOrNull)(nil) func (o *DocumentHighlightsOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.DocumentHighlights != nil { - return json.MarshalEncode(enc, o.DocumentHighlights) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "DocumentHighlightsOrNull", true) } var _ json.UnmarshalerFrom = (*DocumentHighlightsOrNull)(nil) @@ -35770,15 +14104,7 @@ type SymbolInformationsOrDocumentSymbolsOrNull struct { var _ json.MarshalerTo = (*SymbolInformationsOrDocumentSymbolsOrNull)(nil) func (o *SymbolInformationsOrDocumentSymbolsOrNull) MarshalJSONTo(enc *json.Encoder) error { - assertAtMostOne("more than one element of SymbolInformationsOrDocumentSymbolsOrNull is set", boolToInt(o.SymbolInformations != nil)+boolToInt(o.DocumentSymbols != nil)) - - if o.SymbolInformations != nil { - return json.MarshalEncode(enc, o.SymbolInformations) - } - if o.DocumentSymbols != nil { - return json.MarshalEncode(enc, o.DocumentSymbols) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "SymbolInformationsOrDocumentSymbolsOrNull", true) } var _ json.UnmarshalerFrom = (*SymbolInformationsOrDocumentSymbolsOrNull)(nil) @@ -35819,15 +14145,7 @@ type CommandOrCodeAction struct { var _ json.MarshalerTo = (*CommandOrCodeAction)(nil) func (o *CommandOrCodeAction) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of CommandOrCodeAction should be set", boolToInt(o.Command != nil)+boolToInt(o.CodeAction != nil)) - - if o.Command != nil { - return json.MarshalEncode(enc, o.Command) - } - if o.CodeAction != nil { - return json.MarshalEncode(enc, o.CodeAction) - } - panic("unreachable") + return marshalUnion(o, enc, "CommandOrCodeAction", false) } var _ json.UnmarshalerFrom = (*CommandOrCodeAction)(nil) @@ -35859,10 +14177,7 @@ type CommandOrCodeActionArrayOrNull struct { var _ json.MarshalerTo = (*CommandOrCodeActionArrayOrNull)(nil) func (o *CommandOrCodeActionArrayOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.CommandOrCodeActionArray != nil { - return json.MarshalEncode(enc, o.CommandOrCodeActionArray) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "CommandOrCodeActionArrayOrNull", true) } var _ json.UnmarshalerFrom = (*CommandOrCodeActionArrayOrNull)(nil) @@ -35890,15 +14205,7 @@ type SymbolInformationsOrWorkspaceSymbolsOrNull struct { var _ json.MarshalerTo = (*SymbolInformationsOrWorkspaceSymbolsOrNull)(nil) func (o *SymbolInformationsOrWorkspaceSymbolsOrNull) MarshalJSONTo(enc *json.Encoder) error { - assertAtMostOne("more than one element of SymbolInformationsOrWorkspaceSymbolsOrNull is set", boolToInt(o.SymbolInformations != nil)+boolToInt(o.WorkspaceSymbols != nil)) - - if o.SymbolInformations != nil { - return json.MarshalEncode(enc, o.SymbolInformations) - } - if o.WorkspaceSymbols != nil { - return json.MarshalEncode(enc, o.WorkspaceSymbols) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "SymbolInformationsOrWorkspaceSymbolsOrNull", true) } var _ json.UnmarshalerFrom = (*SymbolInformationsOrWorkspaceSymbolsOrNull)(nil) @@ -35938,10 +14245,7 @@ type CodeLensesOrNull struct { var _ json.MarshalerTo = (*CodeLensesOrNull)(nil) func (o *CodeLensesOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.CodeLenses != nil { - return json.MarshalEncode(enc, o.CodeLenses) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "CodeLensesOrNull", true) } var _ json.UnmarshalerFrom = (*CodeLensesOrNull)(nil) @@ -35968,10 +14272,7 @@ type DocumentLinksOrNull struct { var _ json.MarshalerTo = (*DocumentLinksOrNull)(nil) func (o *DocumentLinksOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.DocumentLinks != nil { - return json.MarshalEncode(enc, o.DocumentLinks) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "DocumentLinksOrNull", true) } var _ json.UnmarshalerFrom = (*DocumentLinksOrNull)(nil) @@ -36000,18 +14301,7 @@ type RangeOrPrepareRenamePlaceholderOrPrepareRenameDefaultBehaviorOrNull struct var _ json.MarshalerTo = (*RangeOrPrepareRenamePlaceholderOrPrepareRenameDefaultBehaviorOrNull)(nil) func (o *RangeOrPrepareRenamePlaceholderOrPrepareRenameDefaultBehaviorOrNull) MarshalJSONTo(enc *json.Encoder) error { - assertAtMostOne("more than one element of RangeOrPrepareRenamePlaceholderOrPrepareRenameDefaultBehaviorOrNull is set", boolToInt(o.Range != nil)+boolToInt(o.PrepareRenamePlaceholder != nil)+boolToInt(o.PrepareRenameDefaultBehavior != nil)) - - if o.Range != nil { - return json.MarshalEncode(enc, o.Range) - } - if o.PrepareRenamePlaceholder != nil { - return json.MarshalEncode(enc, o.PrepareRenamePlaceholder) - } - if o.PrepareRenameDefaultBehavior != nil { - return json.MarshalEncode(enc, o.PrepareRenameDefaultBehavior) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "RangeOrPrepareRenamePlaceholderOrPrepareRenameDefaultBehaviorOrNull", true) } var _ json.UnmarshalerFrom = (*RangeOrPrepareRenamePlaceholderOrPrepareRenameDefaultBehaviorOrNull)(nil) @@ -36052,10 +14342,7 @@ type LSPAnyOrNull struct { var _ json.MarshalerTo = (*LSPAnyOrNull)(nil) func (o *LSPAnyOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.LSPAny != nil { - return json.MarshalEncode(enc, o.LSPAny) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "LSPAnyOrNull", true) } var _ json.UnmarshalerFrom = (*LSPAnyOrNull)(nil) @@ -36086,10 +14373,7 @@ type MultiDocumentHighlightsOrNull struct { var _ json.MarshalerTo = (*MultiDocumentHighlightsOrNull)(nil) func (o *MultiDocumentHighlightsOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.MultiDocumentHighlights != nil { - return json.MarshalEncode(enc, o.MultiDocumentHighlights) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "MultiDocumentHighlightsOrNull", true) } var _ json.UnmarshalerFrom = (*MultiDocumentHighlightsOrNull)(nil) @@ -36116,10 +14400,7 @@ type VSOnAutoInsertResponseItemOrNull struct { var _ json.MarshalerTo = (*VSOnAutoInsertResponseItemOrNull)(nil) func (o *VSOnAutoInsertResponseItemOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.VSOnAutoInsertResponseItem != nil { - return json.MarshalEncode(enc, o.VSOnAutoInsertResponseItem) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "VSOnAutoInsertResponseItemOrNull", true) } var _ json.UnmarshalerFrom = (*VSOnAutoInsertResponseItemOrNull)(nil) @@ -36146,10 +14427,7 @@ type VSReferenceItemsOrNull struct { var _ json.MarshalerTo = (*VSReferenceItemsOrNull)(nil) func (o *VSReferenceItemsOrNull) MarshalJSONTo(enc *json.Encoder) error { - if o.VSReferenceItems != nil { - return json.MarshalEncode(enc, o.VSReferenceItems) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "VSReferenceItemsOrNull", true) } var _ json.UnmarshalerFrom = (*VSReferenceItemsOrNull)(nil) @@ -36178,18 +14456,7 @@ type RequestFailureTelemetryEventOrPerformanceStatsTelemetryEventOrProjectInfoTe var _ json.MarshalerTo = (*RequestFailureTelemetryEventOrPerformanceStatsTelemetryEventOrProjectInfoTelemetryEventOrNull)(nil) func (o *RequestFailureTelemetryEventOrPerformanceStatsTelemetryEventOrProjectInfoTelemetryEventOrNull) MarshalJSONTo(enc *json.Encoder) error { - assertAtMostOne("more than one element of RequestFailureTelemetryEventOrPerformanceStatsTelemetryEventOrProjectInfoTelemetryEventOrNull is set", boolToInt(o.RequestFailureTelemetryEvent != nil)+boolToInt(o.PerformanceStatsTelemetryEvent != nil)+boolToInt(o.ProjectInfoTelemetryEvent != nil)) - - if o.RequestFailureTelemetryEvent != nil { - return json.MarshalEncode(enc, o.RequestFailureTelemetryEvent) - } - if o.PerformanceStatsTelemetryEvent != nil { - return json.MarshalEncode(enc, o.PerformanceStatsTelemetryEvent) - } - if o.ProjectInfoTelemetryEvent != nil { - return json.MarshalEncode(enc, o.ProjectInfoTelemetryEvent) - } - return enc.WriteToken(json.Null) + return marshalUnion(o, enc, "RequestFailureTelemetryEventOrPerformanceStatsTelemetryEventOrProjectInfoTelemetryEventOrNull", true) } var _ json.UnmarshalerFrom = (*RequestFailureTelemetryEventOrPerformanceStatsTelemetryEventOrProjectInfoTelemetryEventOrNull)(nil) @@ -36232,18 +14499,7 @@ type TextDocumentFilterLanguageOrSchemeOrPattern struct { var _ json.MarshalerTo = (*TextDocumentFilterLanguageOrSchemeOrPattern)(nil) func (o *TextDocumentFilterLanguageOrSchemeOrPattern) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of TextDocumentFilterLanguageOrSchemeOrPattern should be set", boolToInt(o.Language != nil)+boolToInt(o.Scheme != nil)+boolToInt(o.Pattern != nil)) - - if o.Language != nil { - return json.MarshalEncode(enc, o.Language) - } - if o.Scheme != nil { - return json.MarshalEncode(enc, o.Scheme) - } - if o.Pattern != nil { - return json.MarshalEncode(enc, o.Pattern) - } - panic("unreachable") + return marshalUnion(o, enc, "TextDocumentFilterLanguageOrSchemeOrPattern", false) } var _ json.UnmarshalerFrom = (*TextDocumentFilterLanguageOrSchemeOrPattern)(nil) @@ -36281,15 +14537,7 @@ type StringOrMarkedStringWithLanguage struct { var _ json.MarshalerTo = (*StringOrMarkedStringWithLanguage)(nil) func (o *StringOrMarkedStringWithLanguage) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of StringOrMarkedStringWithLanguage should be set", boolToInt(o.String != nil)+boolToInt(o.MarkedStringWithLanguage != nil)) - - if o.String != nil { - return json.MarshalEncode(enc, o.String) - } - if o.MarkedStringWithLanguage != nil { - return json.MarshalEncode(enc, o.MarkedStringWithLanguage) - } - panic("unreachable") + return marshalUnion(o, enc, "StringOrMarkedStringWithLanguage", false) } var _ json.UnmarshalerFrom = (*StringOrMarkedStringWithLanguage)(nil) @@ -36318,18 +14566,7 @@ type InlineValueTextOrVariableLookupOrEvaluatableExpression struct { var _ json.MarshalerTo = (*InlineValueTextOrVariableLookupOrEvaluatableExpression)(nil) func (o *InlineValueTextOrVariableLookupOrEvaluatableExpression) MarshalJSONTo(enc *json.Encoder) error { - assertOnlyOne("exactly one element of InlineValueTextOrVariableLookupOrEvaluatableExpression should be set", boolToInt(o.Text != nil)+boolToInt(o.VariableLookup != nil)+boolToInt(o.EvaluatableExpression != nil)) - - if o.Text != nil { - return json.MarshalEncode(enc, o.Text) - } - if o.VariableLookup != nil { - return json.MarshalEncode(enc, o.VariableLookup) - } - if o.EvaluatableExpression != nil { - return json.MarshalEncode(enc, o.EvaluatableExpression) - } - panic("unreachable") + return marshalUnion(o, enc, "InlineValueTextOrVariableLookupOrEvaluatableExpression", false) } var _ json.UnmarshalerFrom = (*InlineValueTextOrVariableLookupOrEvaluatableExpression)(nil) diff --git a/internal/lsp/lsproto/lsp_json_test.go b/internal/lsp/lsproto/lsp_json_test.go index f09fafab0d8..2a7f24d1be8 100644 --- a/internal/lsp/lsproto/lsp_json_test.go +++ b/internal/lsp/lsproto/lsp_json_test.go @@ -1,6 +1,7 @@ package lsproto import ( + "reflect" "strings" "testing" @@ -889,3 +890,147 @@ func TestEnumStringValues(t *testing.T) { assert.Assert(t, strings.Contains(s, "999"), "should contain the numeric value, got: %s", s) }) } + +// TestRoundTrip locks the generated codecs: every value must survive +// marshal -> unmarshal unchanged. This guards fidelity so codec changes +// (e.g. pruning or table-driving them) cannot silently corrupt the wire +// format. Cover a representative spread of shapes: required fields, +// nullable/non-nullable optionals, enums, slices, nested objects, and +// unions. +func TestRoundTrip(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + value any + }{ + {"Range", &Range{ + Start: Position{Line: 1, Character: 2}, + End: Position{Line: 3, Character: 4}, + }}, + {"TextEdit", &TextEdit{ + Range: Range{Start: Position{Line: 1, Character: 2}, End: Position{Line: 3, Character: 4}}, + NewText: "hello", + }}, + {"MarkupContent", &MarkupContent{Kind: MarkupKindMarkdown, Value: "**x**"}}, + {"DidChangeConfigurationParams object", &DidChangeConfigurationParams{ + Settings: map[string]any{"js/ts": map[string]any{"x": float64(1)}}, + }}, + {"DidChangeConfigurationParams null", &DidChangeConfigurationParams{Settings: nil}}, + {"CompletionItem", &CompletionItem{ + Label: "pageXOffset", + Kind: new(CompletionItemKindField), + SortText: new("15"), + InsertTextFormat: new(InsertTextFormatPlainText), + }}, + // StringOrTuple union (string arm and tuple arm). + {"ParameterInformation string label", &ParameterInformation{ + Label: StringOrTuple{String: new("p: number")}, + }}, + {"ParameterInformation tuple label", &ParameterInformation{ + Label: StringOrTuple{Tuple: &[2]uint32{0, 4}}, + }}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + data, err := json.Marshal(tt.value) + assert.NilError(t, err) + got := reflect.New(reflect.TypeOf(tt.value).Elem()).Interface() + assert.NilError(t, json.Unmarshal(data, got)) + again, err := json.Marshal(got) + assert.NilError(t, err) + assert.Equal(t, string(data), string(again), "re-marshal differs") + }) + } +} + +// TestStrictnessMissingRequired confirms required fields are still enforced; +// default reflective decoding would silently accept these. +func TestStrictnessMissingRequired(t *testing.T) { + t.Parallel() + tests := []struct { + name string + input string + target any + }{ + {"TextEdit missing newText", `{"range":{"start":{"line":0,"character":0},"end":{"line":0,"character":1}}}`, new(TextEdit)}, + {"Range missing end", `{"start":{"line":0,"character":0}}`, new(Range)}, + {"Position missing character", `{"line":0}`, new(Position)}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + err := json.Unmarshal([]byte(tt.input), tt.target) + assert.ErrorContains(t, err, "missing required properties") + }) + } +} + +// TestStrictnessNotObject confirms a non-object where an object is required +// is rejected rather than coerced. +func TestStrictnessNotObject(t *testing.T) { + t.Parallel() + err := json.Unmarshal([]byte(`"oops"`), new(TextEdit)) + assert.Assert(t, err != nil) + assert.Assert(t, strings.Contains(err.Error(), "object") || strings.Contains(err.Error(), "cannot unmarshal")) +} + +// TestUnmarshalParamsRequiresParams verifies that a NoParams method must be +// given no params while every other method must be given params, and that a +// mismatch (including a null value either way) is an InvalidParams error. +func TestUnmarshalParamsRequiresParams(t *testing.T) { + t.Parallel() + + // NoParams: only truly-absent/empty params are accepted; null and any + // present value are rejected. + noParamsTests := []struct { + name string + params any + wantErr bool + }{ + {"absent", nil, false}, + {"empty", json.Value(``), false}, + {"null", json.Value(`null`), true}, + {"object", json.Value(`{}`), true}, + } + for _, tt := range noParamsTests { + t.Run("NoParams/"+tt.name, func(t *testing.T) { + t.Parallel() + _, err := UnmarshalParams[NoParams](&RequestMessage{Params: tt.params}) + if tt.wantErr { + assert.ErrorIs(t, err, ErrorCodeInvalidParams) + } else { + assert.NilError(t, err) + } + }) + } + + // Required-params method: only an object or array is accepted; absent, + // empty, null, and other scalars are rejected. + typedTests := []struct { + name string + params any + wantErr bool + }{ + {"absent", nil, true}, + {"empty", json.Value(``), true}, + {"null", json.Value(`null`), true}, + {"number", json.Value(`5`), true}, + {"string", json.Value(`"x"`), true}, + {"object", json.Value(`{"settings":{"x":1}}`), false}, + } + for _, tt := range typedTests { + t.Run("typed/"+tt.name, func(t *testing.T) { + t.Parallel() + got, err := UnmarshalParams[*DidChangeConfigurationParams](&RequestMessage{Params: tt.params}) + if tt.wantErr { + assert.ErrorIs(t, err, ErrorCodeInvalidParams) + } else { + assert.NilError(t, err) + assert.Assert(t, got != nil && got.Settings != nil) + } + }) + } +} diff --git a/internal/lsp/lsproto/structcodec.go b/internal/lsp/lsproto/structcodec.go new file mode 100644 index 00000000000..6ec01fc1b83 --- /dev/null +++ b/internal/lsp/lsproto/structcodec.go @@ -0,0 +1,164 @@ +package lsproto + +import ( + "reflect" + "strings" + "sync" + + "github.com/microsoft/typescript-go/internal/json" +) + +// This file provides a single reflection-driven object decoder that replaces +// the per-type UnmarshalJSONFrom methods the generator emits for plain +// structs. It preserves the same strictness those methods enforce: the value +// must be an object, all required fields must be present, and a JSON null is +// rejected for nilable fields whose spec is not nullable. Required fields, and +// the rare spec-nullable fields, are marked with an `lsp:"required"` / +// `lsp:"nullable"` struct tag (the spec nullability that decides this is not +// otherwise recoverable from the json tag); any other nilable field rejects +// null by default. The per-type spec is resolved once via reflection and +// cached, so the only per-call work is the object scan. + +type structFieldSpec struct { + index int + requiredID int // bit position among required fields, or -1 + rejectNull bool +} + +type structSpec struct { + byName map[string]structFieldSpec + requiredNames []string + requiredMask uint64 +} + +var structSpecCache sync.Map // reflect.Type -> *structSpec + +func specFor(t reflect.Type) *structSpec { + if cached, ok := structSpecCache.Load(t); ok { + return cached.(*structSpec) + } + spec := &structSpec{byName: make(map[string]structFieldSpec, t.NumField())} + for i := range t.NumField() { + f := t.Field(i) + jsonName, _, _ := strings.Cut(f.Tag.Get("json"), ",") + if jsonName == "" || jsonName == "-" { + continue + } + fs := structFieldSpec{index: i, requiredID: -1} + var nullable bool + for marker := range strings.SplitSeq(f.Tag.Get("lsp"), ",") { + switch marker { + case "required": + fs.requiredID = len(spec.requiredNames) + spec.requiredMask |= 1 << fs.requiredID + spec.requiredNames = append(spec.requiredNames, jsonName) + case "nullable": + nullable = true + } + } + // A nilable field (pointer/slice/map) rejects an explicit JSON null + // unless the spec marks it nullable. + switch f.Type.Kind() { + case reflect.Pointer, reflect.Slice, reflect.Map: + fs.rejectNull = !nullable + } + spec.byName[jsonName] = fs + } + actual, _ := structSpecCache.LoadOrStore(t, spec) + return actual.(*structSpec) +} + +// unmarshalStruct decodes a JSON object into the struct pointed to by v, +// enforcing object-kind, required-field, and non-nullable-field strictness as +// declared by lsp struct tags. Up to 64 required fields are supported. +func unmarshalStruct(v any, dec *json.Decoder) error { + rv := reflect.ValueOf(v).Elem() + spec := specFor(rv.Type()) + + if k := dec.PeekKind(); k != '{' { + return errNotObject(k) + } + if _, err := dec.ReadToken(); err != nil { + return err + } + + var seen uint64 + for dec.PeekKind() != '}' { + name, err := dec.ReadValue() + if err != nil { + return err + } + // name includes surrounding quotes; m[string(b)] is a no-alloc lookup. + fs, ok := spec.byName[string(name[1:len(name)-1])] + if !ok { + if err := dec.SkipValue(); err != nil { + return err + } + continue + } + if fs.requiredID >= 0 { + seen |= 1 << fs.requiredID + } + if fs.rejectNull && dec.PeekKind() == 'n' { + return errNull(string(name[1 : len(name)-1])) + } + if err := json.UnmarshalDecode(dec, rv.Field(fs.index).Addr().Interface()); err != nil { + return err + } + } + if _, err := dec.ReadToken(); err != nil { + return err + } + + if missing := spec.requiredMask &^ seen; missing != 0 { + var missingProps []string + for id, n := range spec.requiredNames { + if missing&(1< 1 { + b.apiState.openProjects[projectPath] = count - 1 + } else if count == 1 { + delete(b.apiState.openProjects, projectPath) + if projectsToClose == nil { + projectsToClose = make(map[tspath.Path]struct{}) + } + projectsToClose[projectPath] = struct{}{} + } } } @@ -155,17 +164,47 @@ func (b *ProjectCollectionBuilder) HandleAPIRequest(apiRequest *APISnapshotReque for configFileName := range apiRequest.OpenProjects.Keys() { configPath := b.toPath(configFileName) if entry := b.findOrCreateProject(configFileName, configPath, projectLoadKindCreate, logger); entry != nil { - if b.apiOpenedProjects == nil { - b.apiOpenedProjects = make(map[tspath.Path]struct{}) + if b.apiState.openProjects == nil { + b.apiState.openProjects = make(map[tspath.Path]int) } - b.apiOpenedProjects[configPath] = struct{}{} + b.apiState.openProjects[configPath]++ + // A project re-opened in the same request shouldn't be closed. + delete(projectsToClose, configPath) } else { return fmt.Errorf("project not found for open: %s", configFileName) } } } - for configPath := range b.apiOpenedProjects { + if apiRequest.CloseFiles != nil { + for path := range apiRequest.CloseFiles.Keys() { + // Ref-counted close mirroring projects above. + if entry, ok := b.apiState.openFiles[path]; ok { + if entry.refCount > 1 { + entry.refCount-- + b.apiState.openFiles[path] = entry + } else { + delete(b.apiState.openFiles, path) + } + } + } + } + + if apiRequest.OpenFiles != nil { + for uri := range apiRequest.OpenFiles.Keys() { + fileName := uri.FileName() + path := b.toPath(fileName) + if b.apiState.openFiles == nil { + b.apiState.openFiles = make(map[tspath.Path]apiOpenedFile) + } + entry := b.apiState.openFiles[path] + entry.fileName = fileName + entry.refCount++ + b.apiState.openFiles[path] = entry + } + } + + for configPath := range b.apiState.openProjects { if entry, ok := b.configuredProjects.Load(configPath); ok { b.updateProgram(entry, logger) } else { @@ -185,6 +224,29 @@ func (b *ProjectCollectionBuilder) HandleAPIRequest(apiRequest *APISnapshotReque } } + // Ensure each API-opened file is placed like LSP's textDocument/didOpen: search + // up ancestor directories for a configured project that contains it, and only + // fall back to the inferred project if none is found. This also keeps already + // loaded configured projects up to date. Then run the same cleanup the LSP open + // path uses, so configured projects auto-loaded for files that are no longer open + // are torn down instead of leaking. + if apiRequest.OpenFiles != nil || apiRequest.CloseFiles != nil { + var retain collections.Set[tspath.Path] + for path, file := range b.apiState.openFiles { + if b.fs.isOpenFile(path) { + // Already an LSP overlay; its project membership is handled by the + // overlay pass in cleanupConfiguredProjects. + continue + } + result := b.ensureConfiguredProjectAndAncestorsForFile(file.fileName, path, logger) + retain.Union(&result.retain) + } + b.cleanupConfiguredProjects(&retain, logger) + if b.inferredProject.Value() != nil { + b.updateProgram(b.inferredProject, logger) + } + } + return nil } @@ -259,89 +321,90 @@ func (b *ProjectCollectionBuilder) DidChangeFiles(summary FileChangeSummary, log // Handle opened file if summary.Opened != "" || summary.Reopened != "" { - var toRemoveProjects collections.Set[tspath.Path] fileName := core.FirstNonZero(summary.Opened, summary.Reopened).FileName() path := b.toPath(fileName) openFileResult := b.ensureConfiguredProjectAndAncestorsForFile(fileName, path, logger) - b.configuredProjects.Range(func(entry *dirty.SyncMapEntry[tspath.Path, *Project]) bool { - toRemoveProjects.Add(entry.Key()) - return true - }) - var isReferencedBy func(project *Project, refPath tspath.Path, seenProjects *collections.Set[*Project]) bool - isReferencedBy = func(project *Project, refPath tspath.Path, seenProjects *collections.Set[*Project]) bool { - if !seenProjects.AddIfAbsent(project) { - return false - } + b.cleanupConfiguredProjects(&openFileResult.retain, logger) + } +} - if project.potentialProjectReferences != nil { - for potentialRef := range project.potentialProjectReferences.Keys() { - if potentialRef == refPath { - return true - } - } - for potentialRef := range project.potentialProjectReferences.Keys() { - if refProject, foundRef := b.configuredProjects.Load(potentialRef); foundRef && isReferencedBy(refProject.Value(), refPath, seenProjects) { - return true - } +// cleanupConfiguredProjects sweeps the loaded configured projects and unloads those +// that are no longer needed. Starting from the set of all configured projects, it +// retains any project that is the default project (along with its references and +// ancestor configs) of an open overlay file or an API-opened file, any project +// explicitly opened through the API, and any project in retain (e.g. the ancestor +// solution tree built for a freshly opened overlay file). Every other configured +// project is deleted, the inferred project roots are recomputed, and the config file +// registry is cleaned up. This is the shared mechanism that keeps the set of loaded +// projects minimal for both LSP file opens and API file opens/closes. +func (b *ProjectCollectionBuilder) cleanupConfiguredProjects(retain *collections.Set[tspath.Path], logger *logging.LogTree) { + var toRemoveProjects collections.Set[tspath.Path] + b.configuredProjects.Range(func(entry *dirty.SyncMapEntry[tspath.Path, *Project]) bool { + toRemoveProjects.Add(entry.Key()) + return true + }) + + retainProjectAndReferences := func(project *Project) { + // Retain project + toRemoveProjects.Delete(project.configFilePath) + if program := project.GetProgram(); program != nil { + program.RangeResolvedProjectReference(func(referencePath tspath.Path, _ *tsoptions.ParsedCommandLine, _ *tsoptions.ParsedCommandLine, _ int) bool { + if _, ok := b.configuredProjects.Load(referencePath); ok { + toRemoveProjects.Delete(referencePath) } - } else if program := project.GetProgram(); program != nil && !program.RangeResolvedProjectReference(func(referencePath tspath.Path, _ *tsoptions.ParsedCommandLine, _ *tsoptions.ParsedCommandLine, _ int) bool { - return referencePath != refPath - }) { return true - } - return false + }) } + } - retainProjectAndReferences := func(project *Project) { - // Retain project - toRemoveProjects.Delete(project.configFilePath) - if program := project.GetProgram(); program != nil { - program.RangeResolvedProjectReference(func(referencePath tspath.Path, _ *tsoptions.ParsedCommandLine, _ *tsoptions.ParsedCommandLine, _ int) bool { - if _, ok := b.configuredProjects.Load(referencePath); ok { - toRemoveProjects.Delete(referencePath) - } - return true - }) - } - } + retainDefaultConfiguredProject := func(openFilePath tspath.Path, project *Project) { + // Retain project and its references + retainProjectAndReferences(project) - retainDefaultConfiguredProject := func(openFile string, openFilePath tspath.Path, project *Project) { - // Retain project and its references - retainProjectAndReferences(project) + // Retain all the ancestor projects + b.configFileRegistryBuilder.forEachConfigFileNameFor(openFilePath, func(configFileName string) { + if ancestor := b.findOrCreateProject(configFileName, b.toPath(configFileName), projectLoadKindFind, logger); ancestor != nil { + retainProjectAndReferences(ancestor.Value()) + } + }) + } - // Retain all the ancestor projects - b.configFileRegistryBuilder.forEachConfigFileNameFor(openFilePath, func(configFileName string) { - if ancestor := b.findOrCreateProject(configFileName, b.toPath(configFileName), projectLoadKindFind, logger); ancestor != nil { - retainProjectAndReferences(ancestor.Value()) - } - }) + var inferredProjectFiles []string + for _, overlay := range b.fs.overlays { + openFile := overlay.FileName() + openFilePath := b.toPath(openFile) + if p := b.findDefaultConfiguredProject(openFile, openFilePath); p != nil { + retainDefaultConfiguredProject(openFilePath, p.Value()) + } else { + inferredProjectFiles = append(inferredProjectFiles, openFile) } - - var inferredProjectFiles []string - for _, overlay := range b.fs.overlays { - openFile := overlay.FileName() - openFilePath := b.toPath(openFile) - if p := b.findDefaultConfiguredProject(openFile, openFilePath); p != nil { - retainDefaultConfiguredProject(openFile, openFilePath, p.Value()) - } else { - inferredProjectFiles = append(inferredProjectFiles, overlay.FileName()) - } + } + // Treat API-opened files like open files: retain their configured project (so + // an LSP-driven open doesn't close it), or keep them as inferred project roots. + for path, file := range b.apiState.openFiles { + if b.fs.isOpenFile(path) { + continue + } + if p := b.findDefaultConfiguredProject(file.fileName, path); p != nil { + retainDefaultConfiguredProject(path, p.Value()) + } else { + inferredProjectFiles = append(inferredProjectFiles, file.fileName) } + } - for projectPath := range toRemoveProjects.Keys() { - if openFileResult.retain.Has(projectPath) { - continue - } - if _, ok := b.apiOpenedProjects[projectPath]; ok { - continue - } - if p, ok := b.configuredProjects.Load(projectPath); ok { - b.deleteConfiguredProject(p, logger) - } + for projectPath := range toRemoveProjects.Keys() { + if retain.Has(projectPath) { + continue + } + if _, ok := b.apiState.openProjects[projectPath]; ok { + continue + } + if p, ok := b.configuredProjects.Load(projectPath); ok { + b.deleteConfiguredProject(p, logger) } - b.updateInferredProjectRoots(inferredProjectFiles, logger) - b.configFileRegistryBuilder.Cleanup() } + b.updateInferredProjectRoots(inferredProjectFiles, logger) + b.configFileRegistryBuilder.Cleanup() } func logChangeFileResult(result changeFileResult, logger *logging.LogTree) { @@ -353,26 +416,39 @@ func logChangeFileResult(result changeFileResult, logger *logging.LogTree) { } } -func (b *ProjectCollectionBuilder) cleanupInferredProject(logger *logging.LogTree) { +func (b *ProjectCollectionBuilder) collectInferredProjectRoots() []string { var inferredProjectFiles []string for path, overlay := range b.fs.overlays { if b.findDefaultConfiguredProject(overlay.FileName(), path) == nil { inferredProjectFiles = append(inferredProjectFiles, overlay.FileName()) } } - b.updateInferredProjectRoots(inferredProjectFiles, logger) + return b.appendAPIOpenedInferredRoots(inferredProjectFiles) +} + +// appendAPIOpenedInferredRoots appends API-opened files that aren't open in an +// overlay and have no configured project, so they're kept as inferred project +// roots and persist across snapshots. +func (b *ProjectCollectionBuilder) appendAPIOpenedInferredRoots(inferredProjectFiles []string) []string { + for path, file := range b.apiState.openFiles { + if b.fs.isOpenFile(path) { + continue + } + if b.findDefaultConfiguredProject(file.fileName, path) == nil { + inferredProjectFiles = append(inferredProjectFiles, file.fileName) + } + } + return inferredProjectFiles +} + +func (b *ProjectCollectionBuilder) cleanupInferredProject(logger *logging.LogTree) { + b.updateInferredProjectRoots(b.collectInferredProjectRoots(), logger) } func (b *ProjectCollectionBuilder) ensureInferredProjectIncludesClosedFile(fileName string, logger *logging.LogTree) { // Collect existing inferred project roots (open files not in configured projects) // plus this closed file. - var inferredProjectFiles []string - for path, overlay := range b.fs.overlays { - if b.findDefaultConfiguredProject(overlay.FileName(), path) == nil { - inferredProjectFiles = append(inferredProjectFiles, overlay.FileName()) - } - } - inferredProjectFiles = append(inferredProjectFiles, fileName) + inferredProjectFiles := append(b.collectInferredProjectRoots(), fileName) b.updateInferredProjectRoots(inferredProjectFiles, logger) if b.inferredProject.Value() != nil { b.updateProgram(b.inferredProject, logger) diff --git a/internal/project/refcountcache_test.go b/internal/project/refcountcache_test.go index 439588cd3e8..3af70bb3688 100644 --- a/internal/project/refcountcache_test.go +++ b/internal/project/refcountcache_test.go @@ -252,6 +252,103 @@ func TestRefCountingCaches(t *testing.T) { }) assert.Equal(t, projectEntries, 0) }) + + t.Run("case-only duplicate imported from multiple files is refcounted once", func(t *testing.T) { + t.Parallel() + + // A file reached through a case-only-different file name from more than one + // import site is parsed and acquired in the parse cache exactly once (same-casing + // loads dedupe), but it must also be recorded as a duplicate exactly once. + // Recording it once per import site would release it from the parse cache more + // times than it was acquired, deleting the live entry out from under a program + // that still references it and panicking the next time it is ref'd during a clone. + testFiles := map[string]any{ + // entry.ts imports the canonical casing first, then pulls in a.ts and b.ts, + // which both import the same file through an upper-cased name. + "/user/username/projects/myproject/src/entry.ts": "import { dep } from './sub/dep';\nimport './a';\nimport './b';\nexport const e = dep;", + "/user/username/projects/myproject/src/a.ts": "import { dep } from './sub/DEP';\nexport const a = dep;", + "/user/username/projects/myproject/src/b.ts": "import { dep } from './sub/DEP';\nexport const b = dep;", + "/user/username/projects/myproject/src/sub/dep.ts": "export const dep = 1;", + "/user/username/projects/myproject/src/c.ts": "export const c = 1;", + } + session := setup(testFiles) + entryURI := lsproto.DocumentUri("file:///user/username/projects/myproject/src/entry.ts") + session.DidOpenFile(context.Background(), entryURI, 1, testFiles["/user/username/projects/myproject/src/entry.ts"].(string), lsproto.LanguageKindTypeScript) + + ls, err := session.GetLanguageService(context.Background(), entryURI) + assert.NilError(t, err) + + // The upper-cased name is recorded as a duplicate, and it should appear exactly once. + program := ls.GetProgram() + var dupKeys []ParseCacheKey + for _, dup := range program.DuplicateSourceFiles() { + if strings.HasSuffix(dup.ParseOptions.FileName, "/sub/DEP.ts") { + dupKeys = append(dupKeys, NewParseCacheKey(dup.ParseOptions, dup.Hash, dup.ScriptKind)) + } + } + assert.Equal(t, len(dupKeys), 1, "case-only duplicate should be recorded exactly once") + dupEntry, ok := session.parseCache.entries.Load(dupKeys[0]) + assert.Assert(t, ok, "duplicate entry should exist in the parse cache") + assert.Equal(t, dupEntry.refCount, 1) + + // Force a full program rebuild (adding an import changes the file's module + // structure). The old snapshot is disposed, releasing each of its source and + // duplicate files exactly once. If the duplicate were recorded twice, the + // shared cache entry would be released to zero and deleted here even though + // the new program still references it. + session.DidChangeFile(context.Background(), entryURI, 2, []lsproto.TextDocumentContentChangePartialOrWholeDocument{ + { + WholeDocument: &lsproto.TextDocumentContentChangeWholeDocument{ + Text: "import { dep } from \"./sub/dep\";\nimport \"./a\";\nimport \"./b\";\nimport \"./c\";\nexport const e = dep;", + }, + }, + }) + lsAfterRebuild, err := session.GetLanguageService(context.Background(), entryURI) + assert.NilError(t, err) + session.WaitForBackgroundTasks() + + // Every parse-cache key referenced by the live program must still exist. + rebuiltProgram := lsAfterRebuild.GetProgram() + assertKeyAlive := func(key ParseCacheKey) { + _, alive := session.parseCache.entries.Load(key) + assert.Assert(t, alive, "live program references a deleted parse-cache entry: %s", key.FileName) + } + for _, file := range rebuiltProgram.SourceFiles() { + assertKeyAlive(NewParseCacheKey(file.ParseOptions(), file.Hash, file.ScriptKind)) + } + for _, dup := range rebuiltProgram.DuplicateSourceFiles() { + assertKeyAlive(NewParseCacheKey(dup.ParseOptions, dup.Hash, dup.ScriptKind)) + } + + // An incremental (clone) update re-references the duplicate files; this must + // not panic with "cache entry not found". + session.DidChangeFile(context.Background(), entryURI, 3, []lsproto.TextDocumentContentChangePartialOrWholeDocument{ + { + WholeDocument: &lsproto.TextDocumentContentChangeWholeDocument{ + Text: "import { dep } from './sub/dep';\nimport './a';\nimport './b';\nimport './c';\nexport const e = dep + 0;", + }, + }, + }) + _, err = session.GetLanguageService(context.Background(), entryURI) + assert.NilError(t, err) + session.WaitForBackgroundTasks() + + // Closing the project releases everything cleanly. + // (The configured project is not disposed until another file in another project is opened, + // so we open an untitled file to trigger that.) + session.DidCloseFile(context.Background(), entryURI) + session.DidOpenFile(context.Background(), "untitled:Untitled-1", 1, "", lsproto.LanguageKindTypeScript) + session.WaitForBackgroundTasks() + + projectEntries := 0 + session.parseCache.entries.Range(func(key ParseCacheKey, _ *refCountCacheEntry[*ast.SourceFile]) bool { + if strings.HasPrefix(key.FileName, "/user/username/projects/myproject/src/") { + projectEntries++ + } + return true + }) + assert.Equal(t, projectEntries, 0) + }) }) t.Run("extendedConfigCache", func(t *testing.T) { diff --git a/internal/project/session.go b/internal/project/session.go index cd04d9817ab..a5c7fefd47f 100644 --- a/internal/project/session.go +++ b/internal/project/session.go @@ -1602,7 +1602,8 @@ func (s *Session) refreshCodeLensIfNeeded(oldPrefs lsutil.UserPreferences, newPr } func (s *Session) refreshDiagnosticsIfNeeded(oldPrefs lsutil.UserPreferences, newPrefs lsutil.UserPreferences) { - if oldPrefs.CustomConfigFileName != newPrefs.CustomConfigFileName { + if oldPrefs.CustomConfigFileName != newPrefs.CustomConfigFileName || + oldPrefs.ReportStyleChecksAsWarnings != newPrefs.ReportStyleChecksAsWarnings { s.ScheduleDiagnosticsRefresh() } } diff --git a/internal/project/session_test.go b/internal/project/session_test.go index f33db22f9f7..79208dfdf49 100644 --- a/internal/project/session_test.go +++ b/internal/project/session_test.go @@ -1406,6 +1406,33 @@ export const value = content;`, assert.Equal(t, len(inlayHintsRefreshCalls), 1, "expected one RefreshInlayHints call after inlay hints preference change") }) + t.Run("schedules diagnostics refresh when reportStyleChecksAsWarnings changes", func(t *testing.T) { + t.Parallel() + files := map[string]any{ + "/src/tsconfig.json": "{}", + "/src/index.ts": "export const x = 1;", + } + session, utils := projecttestutil.Setup(files) + session.DidOpenFile(context.Background(), "file:///src/index.ts", 1, files["/src/index.ts"].(string), lsproto.LanguageKindTypeScript) + _, err := session.GetLanguageService(context.Background(), lsproto.DocumentUri("file:///src/index.ts")) + assert.NilError(t, err) + session.WaitForBackgroundTasks() + + // Record the baseline count of RefreshDiagnostics calls. + baselineRefreshCount := len(utils.Client().RefreshDiagnosticsCalls()) + + // Toggle reportStyleChecksAsWarnings (default is true, so set it to false). + prefs := lsutil.NewDefaultUserPreferences() + prefs.ReportStyleChecksAsWarnings = core.TSFalse + session.Configure(prefs) + session.WaitForBackgroundTasks() + + refreshCount := len(utils.Client().RefreshDiagnosticsCalls()) + assert.Assert(t, refreshCount > baselineRefreshCount, + "expected RefreshDiagnostics to be called after reportStyleChecksAsWarnings change, got %d calls (baseline %d)", + refreshCount, baselineRefreshCount) + }) + t.Run("config parsing", func(t *testing.T) { t.Parallel() files := map[string]any{ @@ -1423,7 +1450,7 @@ export const value = content;`, "quoteStyle": "single", }, "unstable": map[string]any{ - "organizeImportsIgnoreCase": true, + "organizeImportsSort": "ordinalIgnoreCase", }, } session.Configure(lsutil.ParseUserPreferences(map[string]any{"js/ts": configMap1})) @@ -1431,7 +1458,7 @@ export const value = content;`, expectedPrefs1 := lsutil.NewDefaultUserPreferences() expectedPrefs1.UseAliasesForRename = core.TSTrue expectedPrefs1.QuotePreference = lsutil.QuotePreferenceSingle - expectedPrefs1.OrganizeImportsIgnoreCase = core.TSTrue + expectedPrefs1.OrganizeImportsSort = lsutil.OrganizeImportsSortOrdinalIgnoreCase assert.DeepEqual(t, actualConfig1, expectedPrefs1) @@ -1441,7 +1468,7 @@ export const value = content;`, "quoteStyle": "double", }, "unstable": map[string]any{ - "organizeImportsIgnoreCase": false, + "organizeImportsSort": "ordinal", }, } session.Configure(lsutil.ParseUserPreferences(map[string]any{"js/ts": configMap2})) @@ -1449,7 +1476,7 @@ export const value = content;`, expectedPrefs2 := lsutil.NewDefaultUserPreferences() expectedPrefs2.UseAliasesForRename = core.TSFalse expectedPrefs2.QuotePreference = lsutil.QuotePreferenceDouble - expectedPrefs2.OrganizeImportsIgnoreCase = core.TSFalse + expectedPrefs2.OrganizeImportsSort = lsutil.OrganizeImportsSortOrdinal assert.DeepEqual(t, actualConfig2, expectedPrefs2) }) diff --git a/internal/project/snapshot.go b/internal/project/snapshot.go index fde56333707..61af433d3c6 100644 --- a/internal/project/snapshot.go +++ b/internal/project/snapshot.go @@ -159,6 +159,8 @@ func (s *Snapshot) ReadDirectory(currentDir string, path string, extensions []st type APISnapshotRequest struct { OpenProjects *collections.Set[string] CloseProjects *collections.Set[tspath.Path] + OpenFiles *collections.Set[lsproto.DocumentUri] + CloseFiles *collections.Set[tspath.Path] } type ProjectTreeRequest struct { @@ -327,7 +329,7 @@ func (s *Snapshot) Clone(ctx context.Context, change SnapshotChange, overlays ma fs, s.ProjectCollection, s.ConfigFileRegistry, - s.ProjectCollection.apiOpenedProjects, + s.ProjectCollection.apiState, compilerOptionsForInferredProjects, s.sessionOptions, customConfigFileName, diff --git a/internal/pseudochecker/lookup.go b/internal/pseudochecker/lookup.go index 40be9a5cc02..7344d682b3d 100644 --- a/internal/pseudochecker/lookup.go +++ b/internal/pseudochecker/lookup.go @@ -221,7 +221,7 @@ func (ch *PseudoChecker) typeFromSingleReturnExpression(fn *ast.Node) *PseudoTyp if fn != nil && !ast.NodeIsMissing(fn.Body()) { flags := ast.GetFunctionFlags(fn) if flags&ast.FunctionFlagsAsyncGenerator != 0 { - return NewPseudoTypeNoResult(fn) + return NewPseudoTypeInferred(fn, true) } body := fn.Body() @@ -258,7 +258,7 @@ func (ch *PseudoChecker) typeFromSingleReturnExpression(fn *ast.Node) *PseudoTyp return ch.typeFromExpression(candidateExpr) } } - return NewPseudoTypeNoResult(fn) + return NewPseudoTypeInferred(fn, true) } // This is basically `checkExpression` for pseudotypes @@ -292,13 +292,13 @@ func (ch *PseudoChecker) typeFromExpression(node *ast.Node) *PseudoType { case ast.KindObjectLiteralExpression: return ch.typeFromObjectLiteral(node.AsObjectLiteralExpression()) case ast.KindClassExpression: - return NewPseudoTypeInferred(node) // No possible annotation/directly mappable syntax + return NewPseudoTypeInferred(node, false) // No possible annotation/directly mappable syntax case ast.KindTemplateExpression: // templateLitWithHoles as const, not supported if IsInConstContext(node) { - return NewPseudoTypeInferred(node) + return NewPseudoTypeInferred(node, false) } - return NewPseudoTypeMaybeConstLocation(node, NewPseudoTypeInferred(node), PseudoTypeString) + return NewPseudoTypeMaybeConstLocation(node, NewPseudoTypeInferred(node, false), PseudoTypeString) case ast.KindNumericLiteral: return NewPseudoTypeMaybeConstLocation(node, NewPseudoTypeNumericLiteral(node), PseudoTypeNumber) case ast.KindNoSubstitutionTemplateLiteral: @@ -312,12 +312,12 @@ func (ch *PseudoChecker) typeFromExpression(node *ast.Node) *PseudoType { case ast.KindFalseKeyword: return NewPseudoTypeMaybeConstLocation(node, PseudoTypeFalse, PseudoTypeBoolean) } - return NewPseudoTypeInferred(node) + return NewPseudoTypeInferred(node, false) } func (ch *PseudoChecker) typeFromObjectLiteral(node *ast.ObjectLiteralExpression) *PseudoType { if errorNodes := ch.canGetTypeFromObjectLiteral(node); errorNodes != nil { - return NewPseudoTypeInferredWithErrors(node.AsNode(), errorNodes) + return NewPseudoTypeInferredWithErrors(node.AsNode(), false, errorNodes) } // we are in a const context producing an object literal type, there are no shorthand or spread assignments if node.Properties == nil || len(node.Properties.Nodes) == 0 { @@ -440,10 +440,10 @@ func (ch *PseudoChecker) canGetTypeFromObjectLiteral(node *ast.ObjectLiteralExpr func (ch *PseudoChecker) typeFromArrayLiteral(node *ast.ArrayLiteralExpression) *PseudoType { if errorNodes := ch.canGetTypeFromArrayLiteral(node); errorNodes != nil { - return NewPseudoTypeInferredWithErrors(node.AsNode(), errorNodes) + return NewPseudoTypeInferredWithErrors(node.AsNode(), false, errorNodes) } if IsInConstContext(node.AsNode()) && isContextuallyTyped(node.AsNode()) { - return NewPseudoTypeInferred(node.AsNode()) // expr in an as const cast with a contextual type has variable readonly state, bail + return NewPseudoTypeInferred(node.AsNode(), false) // expr in an as const cast with a contextual type has variable readonly state, bail } // we are in a const context producing a tuple type, there are no spread elements results := make([]*PseudoType, 0, len(node.Elements.Nodes)) @@ -522,10 +522,6 @@ func (ch *PseudoChecker) typeFromFunctionLikeExpression(node *ast.Node) *PseudoT return NewPseudoTypeDirect(node.FunctionLikeData().FullSignature) } returnType := ch.createReturnFromSignature(node) - if returnType.Kind == PseudoTypeKindNoResult { - // no result for the return type can just be an inferred result for the whole expression - return NewPseudoTypeInferred(node.AsNode()) - } typeParameters := ch.cloneTypeParameters(node.FunctionLikeData().TypeParameters) parameters := ch.cloneParameters(node.FunctionLikeData().Parameters) return NewPseudoTypeSingleCallSignature( diff --git a/internal/pseudochecker/type.go b/internal/pseudochecker/type.go index d9a8d1816eb..6966ed811e1 100644 --- a/internal/pseudochecker/type.go +++ b/internal/pseudochecker/type.go @@ -98,16 +98,17 @@ func (t *PseudoType) AsPseudoTypeDirect() *PseudoTypeDirect { return t.data.(*Ps // ErrorNodes field, collected during pseudochecker construction. type PseudoTypeInferred struct { PseudoTypeBase - Expression *ast.Node - ErrorNodes []*ast.Node + Expression *ast.Node + ErrorNodes []*ast.Node + IsSignatureReturn bool } -func NewPseudoTypeInferred(expr *ast.Node) *PseudoType { - return newPseudoType(PseudoTypeKindInferred, &PseudoTypeInferred{Expression: expr}) +func NewPseudoTypeInferred(expr *ast.Node, isSignatureReturn bool) *PseudoType { + return newPseudoType(PseudoTypeKindInferred, &PseudoTypeInferred{Expression: expr, IsSignatureReturn: isSignatureReturn}) } -func NewPseudoTypeInferredWithErrors(expr *ast.Node, errorNodes []*ast.Node) *PseudoType { - return newPseudoType(PseudoTypeKindInferred, &PseudoTypeInferred{Expression: expr, ErrorNodes: errorNodes}) +func NewPseudoTypeInferredWithErrors(expr *ast.Node, isSignatureReturn bool, errorNodes []*ast.Node) *PseudoType { + return newPseudoType(PseudoTypeKindInferred, &PseudoTypeInferred{Expression: expr, ErrorNodes: errorNodes, IsSignatureReturn: isSignatureReturn}) } func (t *PseudoType) AsPseudoTypeInferred() *PseudoTypeInferred { return t.data.(*PseudoTypeInferred) } diff --git a/internal/scanner/scanner.go b/internal/scanner/scanner.go index d0f52c900dd..c4617fd31a1 100644 --- a/internal/scanner/scanner.go +++ b/internal/scanner/scanner.go @@ -209,10 +209,9 @@ type Scanner struct { skipTrivia bool ScannerState - containsNonASCII bool - numberCache map[string]string - hexNumberCache map[string]string - hexDigitCache map[string]string + numberCache map[string]string + hexNumberCache map[string]string + hexDigitCache map[string]string } func defaultScanner() Scanner { @@ -322,13 +321,6 @@ func (s *Scanner) HasUnicodeEscape() bool { return s.tokenFlags&ast.TokenFlagsUnicodeEscape != 0 } -// ContainsNonASCII returns true if the scanner encountered any non-ASCII bytes -// during scanning. This is useful for determining whether UTF-8 byte offsets -// may differ from UTF-16 code unit offsets. -func (s *Scanner) ContainsNonASCII() bool { - return s.containsNonASCII -} - func (s *Scanner) HasExtendedUnicodeEscape() bool { return s.tokenFlags&ast.TokenFlagsExtendedUnicodeEscape != 0 } @@ -455,11 +447,7 @@ func (s *Scanner) charAndSize() (rune, int) { return rune(b), 1 } } - r, size := utf8.DecodeRuneInString(s.text[s.pos:]) - if size > 1 { - s.containsNonASCII = true - } - return r, size + return utf8.DecodeRuneInString(s.text[s.pos:]) } // scanASCIIWhile advances s.pos over the longest run of ASCII bytes for which @@ -1851,7 +1839,6 @@ func (s *Scanner) scanEscapeSequence(flags EscapeSequenceScanningFlags) string { var size int ch, size = utf8.DecodeRuneInString(s.text[s.pos:]) s.pos += size - s.containsNonASCII = true } // LineContinuation: a backslash followed by a line terminator is "the empty code unit sequence". if ch == '\u2028' || ch == '\u2029' { diff --git a/internal/stringutil/util.go b/internal/stringutil/util.go index dc3d8938611..2d50d52c9ee 100644 --- a/internal/stringutil/util.go +++ b/internal/stringutil/util.go @@ -84,6 +84,15 @@ func IsASCIILetter(ch rune) bool { return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z' } +func ContainsNonASCII(s string) bool { + for i := range len(s) { + if s[i] >= utf8.RuneSelf { + return true + } + } + return false +} + func SplitLines(text string) []string { lines := make([]string, 0, strings.Count(text, "\n")+1) // preallocate start := 0 diff --git a/internal/stringutil/util_test.go b/internal/stringutil/util_test.go index 68526ed03eb..ebaed49bbbb 100644 --- a/internal/stringutil/util_test.go +++ b/internal/stringutil/util_test.go @@ -35,3 +35,25 @@ func TestEncodeURI(t *testing.T) { }) } } + +func TestContainsNonASCII(t *testing.T) { + t.Parallel() + tests := []struct { + name string + text string + want bool + }{ + {name: "ascii", text: "abc", want: false}, + {name: "non-ascii", text: "é", want: true}, + {name: "lone surrogate sentinel", text: EncodeJSStringRune(0xD800), want: true}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + if got := ContainsNonASCII(tt.text); got != tt.want { + t.Fatalf("ContainsNonASCII(%q) = %v, want %v", tt.text, got, tt.want) + } + }) + } +} diff --git a/internal/testutil/lsptestutil/lspclient.go b/internal/testutil/lsptestutil/lspclient.go index 59b5bd4c5eb..4698abb9883 100644 --- a/internal/testutil/lsptestutil/lspclient.go +++ b/internal/testutil/lsptestutil/lspclient.go @@ -17,42 +17,33 @@ import ( "gotest.tools/v3/assert" ) -// LSPReader reads LSP messages from a channel. -type LSPReader struct { - c <-chan *lsproto.Message +// clientTransport wires a test client to a server using real LSP +// "Content-Length"-framed JSON streamed over byte pipes, exactly like +// communication with a real editor. This exercises the full marshal/unmarshal +// round-trip of every protocol data structure. The two directions are: +// +// client --(clientOut)--> serverIn --> server +// server --(serverOut)--> clientIn --> client +type clientTransport struct { + serverIn lsp.Reader // server reads client->server messages + serverOut lsp.Writer // server writes server->client messages + clientIn lsp.Reader // client reads server->client messages + clientOut lsp.Writer // client writes client->server messages + closeClientOut func() // closes the client->server direction + closeServerOut func() // closes the server->client direction } -func (r *LSPReader) Read() (*lsproto.Message, error) { - msg, ok := <-r.c - if !ok { - return nil, io.EOF +func newClientTransport() clientTransport { + clientToServerReader, clientToServerWriter := io.Pipe() + serverToClientReader, serverToClientWriter := io.Pipe() + return clientTransport{ + serverIn: lsp.ToReader(clientToServerReader), + serverOut: lsp.ToWriter(serverToClientWriter), + clientIn: lsp.ToReader(serverToClientReader), + clientOut: lsp.ToWriter(clientToServerWriter), + closeClientOut: func() { _ = clientToServerWriter.Close() }, + closeServerOut: func() { _ = serverToClientWriter.Close() }, } - return msg, nil -} - -// LSPWriter writes LSP messages to a channel. -type LSPWriter struct { - c chan<- *lsproto.Message -} - -func (w *LSPWriter) Write(msg *lsproto.Message) error { - w.c <- msg - return nil -} - -func (w *LSPWriter) Close() { - close(w.c) -} - -var ( - _ lsp.Reader = (*LSPReader)(nil) - _ lsp.Writer = (*LSPWriter)(nil) -) - -// newLSPPipe creates a paired LSPReader and LSPWriter connected by a buffered channel. -func newLSPPipe() (*LSPReader, *LSPWriter) { - c := make(chan *lsproto.Message, 100) - return &LSPReader{c: c}, &LSPWriter{c: c} } // ServerRequestHandler handles server-initiated requests and returns the response to send back. @@ -64,11 +55,18 @@ type ServerNotificationHandler func(ctx context.Context, req *lsproto.RequestMes // LSPClient provides infrastructure for communicating with an LSP server in tests. type LSPClient struct { Server *lsp.Server - inputWriter *LSPWriter - outputReader *LSPReader + inputWriter lsp.Writer + outputReader lsp.Reader id int32 ctx context.Context + // inputWriterMu serializes writes to the server. The test goroutine (sending + // requests/notifications) and the MessageRouter goroutine (sending responses + // to server-initiated requests) both write to the same stream; a single + // message is written as multiple underlying writes (header, body, flush), so + // concurrent writers must not interleave. + inputWriterMu sync.Mutex + // OnServerRequest handles server-initiated requests (e.g., workspace/configuration). // If nil, all server requests receive a MethodNotFound error. onServerRequest ServerRequestHandler @@ -82,12 +80,18 @@ type LSPClient struct { pendingRequestsMu sync.Mutex } +// writeToServer writes a message to the server, serializing concurrent writers. +func (c *LSPClient) writeToServer(msg *lsproto.Message) error { + c.inputWriterMu.Lock() + defer c.inputWriterMu.Unlock() + return c.inputWriter.Write(msg) +} + // NewLSPClient creates an LSPClient wrapping the given server and pipes. func NewLSPClient(t *testing.T, serverOpts lsp.ServerOptions, onServerRequest ServerRequestHandler) (*LSPClient, func() error) { - inputReader, inputWriter := newLSPPipe() - outputReader, outputWriter := newLSPPipe() - serverOpts.In = inputReader - serverOpts.Out = outputWriter + transport := newClientTransport() + serverOpts.In = transport.serverIn + serverOpts.Out = transport.serverOut server := lsp.NewServer(&serverOpts) @@ -95,8 +99,8 @@ func NewLSPClient(t *testing.T, serverOpts lsp.ServerOptions, onServerRequest Se g, ctx := errgroup.WithContext(ctx) client := &LSPClient{ Server: server, - inputWriter: inputWriter, - outputReader: outputReader, + inputWriter: transport.clientOut, + outputReader: transport.clientIn, pendingRequests: make(map[jsonrpc.ID]chan *lsproto.ResponseMessage), onServerRequest: onServerRequest, ctx: ctx, @@ -104,7 +108,7 @@ func NewLSPClient(t *testing.T, serverOpts lsp.ServerOptions, onServerRequest Se // Start server goroutine g.Go(func() error { - defer outputWriter.Close() + defer transport.closeServerOut() return server.Run(ctx) }) @@ -115,7 +119,7 @@ func NewLSPClient(t *testing.T, serverOpts lsp.ServerOptions, onServerRequest Se return client, func() error { cancel() - inputWriter.Close() + transport.closeClientOut() if err := g.Wait(); err != nil && !errors.Is(err, context.Canceled) { return err } @@ -224,7 +228,7 @@ func (c *LSPClient) handleServerRequest(ctx context.Context, req *lsproto.Reques return nil } - if err := c.inputWriter.Write(response.Message()); err != nil { + if err := c.writeToServer(response.Message()); err != nil { if ctx.Err() != nil { return nil } @@ -237,7 +241,7 @@ func (c *LSPClient) handleServerRequest(ctx context.Context, req *lsproto.Reques // This is an untyped low-level method; prefer SendRequest and SendNotification for typed interactions. func (c *LSPClient) WriteMsg(t *testing.T, msg *lsproto.Message) { assert.NilError(t, json.MarshalWrite(io.Discard, msg), "failed to encode message as JSON") - if err := c.inputWriter.Write(msg); err != nil { + if err := c.writeToServer(msg); err != nil { t.Fatalf("failed to write message: %v", err) } } @@ -252,8 +256,9 @@ func SendRequest[Params, Resp any](t *testing.T, c *LSPClient, info lsproto.Requ if !ok { return nil, *new(Resp), false } - result, ok := resp.Result.(Resp) - return resp.Message(), result, ok + // The result arrives as a raw json.Value; decode it into Resp. + result, err := info.UnmarshalResult(resp.Result) + return resp.Message(), result, err == nil } // SendRequestAsync sends a typed request and returns a waiter for its response. @@ -268,8 +273,8 @@ func SendRequestAsync[Params, Resp any](t *testing.T, c *LSPClient, info lsproto if !ok { return nil, *new(Resp), false } - result, ok := resp.Result.(Resp) - return resp.Message(), result, ok + result, err := info.UnmarshalResult(resp.Result) + return resp.Message(), result, err == nil } } diff --git a/internal/transformers/declarations/transform.go b/internal/transformers/declarations/transform.go index b6596e0d77b..3322b437cf6 100644 --- a/internal/transformers/declarations/transform.go +++ b/internal/transformers/declarations/transform.go @@ -2066,9 +2066,8 @@ caseBlock: if thisTarget.ClassLikeData().HeritageClauses != nil && len(thisTarget.ClassLikeData().HeritageClauses.Nodes) > 0 && !isClassExtendingNull(thisTarget) { // there is a base type any assignments might be "from" tx.tracker.ReportInferenceFallback(thisTarget) // Add an isolated declarations error on this class - we can't know how to transform this prop into an assignment without referring to type information - decls := tx.resolver.GetBaseDeclarationsForPropertyDeclaration(node) - if len(decls) > 0 { - break caseBlock // property lightly overrides a property in a base type - skip it + if tx.resolver.IsThisPropertyAssignmentDeclarationRedundant(node) { + break caseBlock // skip assignments whose member is already provided by an `extends` base type (an inherited accessor/method, or an identical inherited property) // TODO: If the property has an explicit `@type` annotation, we should probably emit it (maybe with an `override` modifier) instead of skipping it } } diff --git a/internal/transformers/moduletransforms/commonjsmodule.go b/internal/transformers/moduletransforms/commonjsmodule.go index 0fd744bfb9a..cc716a425f6 100644 --- a/internal/transformers/moduletransforms/commonjsmodule.go +++ b/internal/transformers/moduletransforms/commonjsmodule.go @@ -1120,6 +1120,8 @@ func (tx *CommonJSModuleTransformer) transformInitializedVariable(node *ast.Vari // re-aliased or multi-exported names (where native destructuring cannot update all // targets) does `visitDestructuringAssignment` fall back to flattening. assignment := transformers.ConvertVariableDeclarationToAssignmentExpression(tx.EmitContext(), node) + grandparentNode := tx.pushNode(assignment) + defer tx.popNode(grandparentNode) return tx.visitDestructuringAssignment(assignment.AsBinaryExpression(), true /*valueIsDiscarded*/) } propertyAccess := tx.Factory().NewPropertyAccessExpression( diff --git a/internal/tsoptions/parsedcommandline.go b/internal/tsoptions/parsedcommandline.go index ab93e527fdc..9f0229165bc 100644 --- a/internal/tsoptions/parsedcommandline.go +++ b/internal/tsoptions/parsedcommandline.go @@ -83,7 +83,7 @@ var ( ) func (p *ParsedCommandLine) ConfigName() string { - if p == nil { + if p == nil || p.ConfigFile == nil { return "" } return p.ConfigFile.SourceFile.FileName() diff --git a/internal/tsoptions/tsconfigparsing.go b/internal/tsoptions/tsconfigparsing.go index 65b7f8495e8..4f85782753d 100644 --- a/internal/tsoptions/tsconfigparsing.go +++ b/internal/tsoptions/tsconfigparsing.go @@ -1562,9 +1562,14 @@ func handleOptionConfigDirTemplateSubstitution(compilerOptions *core.CompilerOpt // !!! don't hardcode this; use options declarations? + var paths *collections.OrderedMap[string, []string] for k, v := range compilerOptions.Paths.Entries() { if substitution := getSubstitutedStringArrayWithConfigDirTemplate(v, basePath); substitution != nil { - compilerOptions.Paths.Set(k, substitution) + if paths == nil { + paths = compilerOptions.Paths.Clone() + compilerOptions.Paths = paths + } + paths.Set(k, substitution) } } diff --git a/internal/tsoptions/tsconfigparsing_test.go b/internal/tsoptions/tsconfigparsing_test.go index 72c2667a7ad..a53b3a66d27 100644 --- a/internal/tsoptions/tsconfigparsing_test.go +++ b/internal/tsoptions/tsconfigparsing_test.go @@ -1531,3 +1531,38 @@ func TestExtendedConfigErrorsAppearOnCacheHit(t *testing.T) { assert.Assert(t, len(second.Errors) > 0, "expected diagnostics for projB parse (cache hit on base), got 0") }) } + +func TestExtendedConfigConfigDirPathsAreNotCached(t *testing.T) { + t.Parallel() + + files := map[string]string{ + "/tsconfig.base.json": `{ + "compilerOptions": { + "paths": { + "@pkg/*": ["${configDir}/src/*"] + } + } +}`, + "/packages/a/tsconfig.json": `{ + "extends": "../../tsconfig.base.json" +}`, + "/packages/b/tsconfig.json": `{ + "extends": "../../tsconfig.base.json" +}`, + "/packages/a/index.ts": "export {}", + "/packages/b/index.ts": "export {}", + } + + host := tsoptionstest.NewVFSParseConfigHost(files, "/", true /*useCaseSensitiveFileNames*/) + cache := &memoCache{} + + parseConfig := func(configFileName string) *tsoptions.ParsedCommandLine { + parsed, errors := tsoptions.GetParsedCommandLineOfConfigFile(configFileName, nil, nil, host, cache) + assert.Assert(t, len(errors) == 0, "unexpected errors parsing %s: %v", configFileName, errors) + return parsed + } + + parseConfig("/packages/a/tsconfig.json") + paths := parseConfig("/packages/b/tsconfig.json").CompilerOptions().Paths + assert.DeepEqual(t, paths.GetOrZero("@pkg/*"), []string{"/packages/b/src/*"}) +} diff --git a/package-lock.json b/package-lock.json index faa5235e4fb..fb9399a91d5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,7 +17,7 @@ "@types/node": "latest", "@types/tmp": "^0.2.6", "@types/which": "^3.0.4", - "@unicode/unicode-15.1.0": "^1.6.16", + "@unicode/unicode-15.1.0": "^1.6.17", "adm-zip": "^0.5.17", "chokidar": "^5.0.0", "dprint": "^0.54.0", @@ -39,13 +39,13 @@ "version": "0.0.0", "dependencies": { "@vscode/extension-telemetry": "^1.5.2", - "vscode-languageclient": "^10.0.0", + "vscode-languageclient": "^10.0.1", "vscode-tas-client": "^0.2.1" }, "devDependencies": { "@types/vscode": "~1.110.0", "@vscode/vsce": "^3.9.2", - "esbuild": "^0.28.0" + "esbuild": "^0.28.1" }, "engines": { "vscode": "^1.110.0" @@ -56,10 +56,10 @@ "version": "0.0.0", "license": "Apache-2.0", "bin": { - "tsgo": "bin/tsgo.js" + "tsgo": "bin/tsgo" }, "devDependencies": { - "@types/node": "^25.9.1", + "@types/node": "^25.9.4", "tinybench": "^6.0.2", "vscode-jsonrpc": "^9.0.0" }, @@ -67,6 +67,16 @@ "node": ">=16.20.0" } }, + "_packages/native-preview/node_modules/@types/node": { + "version": "25.9.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.4.tgz", + "integrity": "sha512-dszCsrKb5U7ZsVZBWiHFklTloVl0mSEnWH/iZXfZUlI4rzCUnsvGmgqfuVRHL54ugE7/wRuxEIXRa2iMZ+BG6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": ">=7.24.0 <7.24.7" + } + }, "node_modules/@azu/format-text": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/@azu/format-text/-/format-text-1.0.2.tgz", @@ -132,9 +142,9 @@ } }, "node_modules/@azure/core-rest-pipeline": { - "version": "1.23.0", - "resolved": "https://registry.npmjs.org/@azure/core-rest-pipeline/-/core-rest-pipeline-1.23.0.tgz", - "integrity": "sha512-Evs1INHo+jUjwHi1T6SG6Ua/LHOQBCLuKEEE6efIpt4ZOoNonaT1kP32GoOcdNDbfqsD2445CPri3MubBy5DEQ==", + "version": "1.24.0", + "resolved": "https://registry.npmjs.org/@azure/core-rest-pipeline/-/core-rest-pipeline-1.24.0.tgz", + "integrity": "sha512-PpLsoDQ3AMmKZ0VU+0GrmqMxgp/sExjlVm4R+nLWngeoEGAzOIPVifaxKGU5gMv+nWELUoHfvrolWD+ZS/nFJg==", "dev": true, "license": "MIT", "dependencies": { @@ -216,22 +226,22 @@ } }, "node_modules/@azure/msal-browser": { - "version": "5.11.0", - "resolved": "https://registry.npmjs.org/@azure/msal-browser/-/msal-browser-5.11.0.tgz", - "integrity": "sha512-zkGNYS3TwY8lUpPIafAmsFCYZbgFixY9y/LZB9GUg0IILoHTqpN26j5OrkL1AQThh/YdZsawe4iWXfp85lFVxg==", + "version": "5.15.0", + "resolved": "https://registry.npmjs.org/@azure/msal-browser/-/msal-browser-5.15.0.tgz", + "integrity": "sha512-2NYT6v+eeQn8kmNddr9LnbXSvXbVELpmFMmfFvtRxD7I/5+5GlkMlncApeuRFj+mY6C9syOwQip1a0Y+TIbyiA==", "dev": true, "license": "MIT", "dependencies": { - "@azure/msal-common": "16.6.2" + "@azure/msal-common": "16.10.0" }, "engines": { "node": ">=0.8.0" } }, "node_modules/@azure/msal-common": { - "version": "16.6.2", - "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-16.6.2.tgz", - "integrity": "sha512-hQjjsekAjB00cM1EmatWJlzhEoK2Qhz7Rj5gvM6tYf8iL7RM3tkxlpU9fG0+ofkulzg9AEEA6dIEnSmDr5ZqUA==", + "version": "16.10.0", + "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-16.10.0.tgz", + "integrity": "sha512-iYtjpanlv6963Jprs0MvzIap07V+QhultjQctfbEDQCflsDAEeO3R7XnVA5gk30fhoBFLdgJT7VqO0TGsEsN9w==", "dev": true, "license": "MIT", "engines": { @@ -239,13 +249,13 @@ } }, "node_modules/@azure/msal-node": { - "version": "5.2.2", - "resolved": "https://registry.npmjs.org/@azure/msal-node/-/msal-node-5.2.2.tgz", - "integrity": "sha512-toS+2AePxqyzb0YOKttDOOiSl3jrkK9aiqIvpurpis0O34QcIS5gToqrgT39p04Dpxw3YoUU0lxJKTpSFFfA6Q==", + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@azure/msal-node/-/msal-node-5.3.0.tgz", + "integrity": "sha512-fXtJX811pX8y8QlrQqBSH6+plvWyKZDI0IxkheAcyAw9OtcpXyFivmTC7eGUqutLWaDlKXuQ3yOESD4zAmkjHg==", "dev": true, "license": "MIT", "dependencies": { - "@azure/msal-common": "16.6.2", + "@azure/msal-common": "16.10.0", "jsonwebtoken": "^9.0.0" }, "engines": { @@ -453,9 +463,9 @@ ] }, "node_modules/@esbuild/aix-ppc64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.0.tgz", - "integrity": "sha512-lhRUCeuOyJQURhTxl4WkpFTjIsbDayJHih5kZC1giwE+MhIzAb7mEsQMqMf18rHLsrb5qI1tafG20mLxEWcWlA==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.1.tgz", + "integrity": "sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==", "cpu": [ "ppc64" ], @@ -470,9 +480,9 @@ } }, "node_modules/@esbuild/android-arm": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.0.tgz", - "integrity": "sha512-wqh0ByljabXLKHeWXYLqoJ5jKC4XBaw6Hk08OfMrCRd2nP2ZQ5eleDZC41XHyCNgktBGYMbqnrJKq/K/lzPMSQ==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.1.tgz", + "integrity": "sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==", "cpu": [ "arm" ], @@ -487,9 +497,9 @@ } }, "node_modules/@esbuild/android-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.0.tgz", - "integrity": "sha512-+WzIXQOSaGs33tLEgYPYe/yQHf0WTU0X42Jca3y8NWMbUVhp7rUnw+vAsRC/QiDrdD31IszMrZy+qwPOPjd+rw==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.1.tgz", + "integrity": "sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==", "cpu": [ "arm64" ], @@ -504,9 +514,9 @@ } }, "node_modules/@esbuild/android-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.0.tgz", - "integrity": "sha512-+VJggoaKhk2VNNqVL7f6S189UzShHC/mR9EE8rDdSkdpN0KflSwWY/gWjDrNxxisg8Fp1ZCD9jLMo4m0OUfeUA==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.1.tgz", + "integrity": "sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==", "cpu": [ "x64" ], @@ -521,9 +531,9 @@ } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.0.tgz", - "integrity": "sha512-0T+A9WZm+bZ84nZBtk1ckYsOvyA3x7e2Acj1KdVfV4/2tdG4fzUp91YHx+GArWLtwqp77pBXVCPn2We7Letr0Q==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.1.tgz", + "integrity": "sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==", "cpu": [ "arm64" ], @@ -538,9 +548,9 @@ } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.0.tgz", - "integrity": "sha512-fyzLm/DLDl/84OCfp2f/XQ4flmORsjU7VKt8HLjvIXChJoFFOIL6pLJPH4Yhd1n1gGFF9mPwtlN5Wf82DZs+LQ==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.1.tgz", + "integrity": "sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==", "cpu": [ "x64" ], @@ -555,9 +565,9 @@ } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.0.tgz", - "integrity": "sha512-l9GeW5UZBT9k9brBYI+0WDffcRxgHQD8ShN2Ur4xWq/NFzUKm3k5lsH4PdaRgb2w7mI9u61nr2gI2mLI27Nh3Q==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.1.tgz", + "integrity": "sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==", "cpu": [ "arm64" ], @@ -572,9 +582,9 @@ } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.0.tgz", - "integrity": "sha512-BXoQai/A0wPO6Es3yFJ7APCiKGc1tdAEOgeTNy3SsB491S3aHn4S4r3e976eUnPdU+NbdtmBuLncYir2tMU9Nw==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.1.tgz", + "integrity": "sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==", "cpu": [ "x64" ], @@ -589,9 +599,9 @@ } }, "node_modules/@esbuild/linux-arm": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.0.tgz", - "integrity": "sha512-CjaaREJagqJp7iTaNQjjidaNbCKYcd4IDkzbwwxtSvjI7NZm79qiHc8HqciMddQ6CKvJT6aBd8lO9kN/ZudLlw==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.1.tgz", + "integrity": "sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==", "cpu": [ "arm" ], @@ -606,9 +616,9 @@ } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.0.tgz", - "integrity": "sha512-RVyzfb3FWsGA55n6WY0MEIEPURL1FcbhFE6BffZEMEekfCzCIMtB5yyDcFnVbTnwk+CLAgTujmV/Lgvih56W+A==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.1.tgz", + "integrity": "sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==", "cpu": [ "arm64" ], @@ -623,9 +633,9 @@ } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.0.tgz", - "integrity": "sha512-KBnSTt1kxl9x70q+ydterVdl+Cn0H18ngRMRCEQfrbqdUuntQQ0LoMZv47uB97NljZFzY6HcfqEZ2SAyIUTQBQ==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.1.tgz", + "integrity": "sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==", "cpu": [ "ia32" ], @@ -640,9 +650,9 @@ } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.0.tgz", - "integrity": "sha512-zpSlUce1mnxzgBADvxKXX5sl8aYQHo2ezvMNI8I0lbblJtp8V4odlm3Yzlj7gPyt3T8ReksE6bK+pT3WD+aJRg==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.1.tgz", + "integrity": "sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==", "cpu": [ "loong64" ], @@ -657,9 +667,9 @@ } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.0.tgz", - "integrity": "sha512-2jIfP6mmjkdmeTlsX/9vmdmhBmKADrWqN7zcdtHIeNSCH1SqIoNI63cYsjQR8J+wGa4Y5izRcSHSm8K3QWmk3w==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.1.tgz", + "integrity": "sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==", "cpu": [ "mips64el" ], @@ -674,9 +684,9 @@ } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.0.tgz", - "integrity": "sha512-bc0FE9wWeC0WBm49IQMPSPILRocGTQt3j5KPCA8os6VprfuJ7KD+5PzESSrJ6GmPIPJK965ZJHTUlSA6GNYEhg==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.1.tgz", + "integrity": "sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==", "cpu": [ "ppc64" ], @@ -691,9 +701,9 @@ } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.0.tgz", - "integrity": "sha512-SQPZOwoTTT/HXFXQJG/vBX8sOFagGqvZyXcgLA3NhIqcBv1BJU1d46c0rGcrij2B56Z2rNiSLaZOYW5cUk7yLQ==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.1.tgz", + "integrity": "sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==", "cpu": [ "riscv64" ], @@ -708,9 +718,9 @@ } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.0.tgz", - "integrity": "sha512-SCfR0HN8CEEjnYnySJTd2cw0k9OHB/YFzt5zgJEwa+wL/T/raGWYMBqwDNAC6dqFKmJYZoQBRfHjgwLHGSrn3Q==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.1.tgz", + "integrity": "sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==", "cpu": [ "s390x" ], @@ -725,9 +735,9 @@ } }, "node_modules/@esbuild/linux-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.0.tgz", - "integrity": "sha512-us0dSb9iFxIi8srnpl931Nvs65it/Jd2a2K3qs7fz2WfGPHqzfzZTfec7oxZJRNPXPnNYZtanmRc4AL/JwVzHQ==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.1.tgz", + "integrity": "sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==", "cpu": [ "x64" ], @@ -742,9 +752,9 @@ } }, "node_modules/@esbuild/netbsd-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.0.tgz", - "integrity": "sha512-CR/RYotgtCKwtftMwJlUU7xCVNg3lMYZ0RzTmAHSfLCXw3NtZtNpswLEj/Kkf6kEL3Gw+BpOekRX0BYCtklhUw==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.1.tgz", + "integrity": "sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==", "cpu": [ "arm64" ], @@ -759,9 +769,9 @@ } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.0.tgz", - "integrity": "sha512-nU1yhmYutL+fQ71Kxnhg8uEOdC0pwEW9entHykTgEbna2pw2dkbFSMeqjjyHZoCmt8SBkOSvV+yNmm94aUrrqw==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.1.tgz", + "integrity": "sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==", "cpu": [ "x64" ], @@ -776,9 +786,9 @@ } }, "node_modules/@esbuild/openbsd-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.0.tgz", - "integrity": "sha512-cXb5vApOsRsxsEl4mcZ1XY3D4DzcoMxR/nnc4IyqYs0rTI8ZKmW6kyyg+11Z8yvgMfAEldKzP7AdP64HnSC/6g==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.1.tgz", + "integrity": "sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==", "cpu": [ "arm64" ], @@ -793,9 +803,9 @@ } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.0.tgz", - "integrity": "sha512-8wZM2qqtv9UP3mzy7HiGYNH/zjTA355mpeuA+859TyR+e+Tc08IHYpLJuMsfpDJwoLo1ikIJI8jC3GFjnRClzA==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.1.tgz", + "integrity": "sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==", "cpu": [ "x64" ], @@ -810,9 +820,9 @@ } }, "node_modules/@esbuild/openharmony-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.0.tgz", - "integrity": "sha512-FLGfyizszcef5C3YtoyQDACyg95+dndv79i2EekILBofh5wpCa1KuBqOWKrEHZg3zrL3t5ouE5jgr94vA+Wb2w==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.1.tgz", + "integrity": "sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==", "cpu": [ "arm64" ], @@ -827,9 +837,9 @@ } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.0.tgz", - "integrity": "sha512-1ZgjUoEdHZZl/YlV76TSCz9Hqj9h9YmMGAgAPYd+q4SicWNX3G5GCyx9uhQWSLcbvPW8Ni7lj4gDa1T40akdlw==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.1.tgz", + "integrity": "sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==", "cpu": [ "x64" ], @@ -844,9 +854,9 @@ } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.0.tgz", - "integrity": "sha512-Q9StnDmQ/enxnpxCCLSg0oo4+34B9TdXpuyPeTedN/6+iXBJ4J+zwfQI28u/Jl40nOYAxGoNi7mFP40RUtkmUA==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.1.tgz", + "integrity": "sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==", "cpu": [ "arm64" ], @@ -861,9 +871,9 @@ } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.0.tgz", - "integrity": "sha512-zF3ag/gfiCe6U2iczcRzSYJKH1DCI+ByzSENHlM2FcDbEeo5Zd2C86Aq0tKUYAJJ1obRP84ymxIAksZUcdztHA==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.1.tgz", + "integrity": "sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==", "cpu": [ "ia32" ], @@ -878,9 +888,9 @@ } }, "node_modules/@esbuild/win32-x64": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.0.tgz", - "integrity": "sha512-pEl1bO9mfAmIC+tW5btTmrKaujg3zGtUmWNdCw/xs70FBjwAL3o9OEKNHvNmnyylD6ubxUERiEhdsL0xBQ9efw==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.1.tgz", + "integrity": "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==", "cpu": [ "x64" ], @@ -983,35 +993,44 @@ } }, "node_modules/@microsoft/applicationinsights-common": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-common/-/applicationinsights-common-3.4.1.tgz", - "integrity": "sha512-CTbD0g/68tiv2yCItsodDQBYxyHdfQkG7VhvVU8OHenukpl/7W4wEuxZuOntqhv5m9Nx/DFncbz+T83nvYTG3g==", + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-common/-/applicationinsights-common-3.4.2.tgz", + "integrity": "sha512-HEoJwACjpAIAId0XAw2+DDydwmilwCpBK3XdQpuXAJlrXhvElw5Yd+ZLmP1J9FjWFh0eJaws1uE9FjW+qqAiFw==", "license": "MIT", "dependencies": { - "@microsoft/applicationinsights-core-js": "3.4.1", + "@microsoft/applicationinsights-core-js": "3.4.2", "@microsoft/applicationinsights-shims": "3.0.1", "@microsoft/dynamicproto-js": "^2.0.3", - "@nevware21/ts-utils": ">= 0.12.6 < 2.x" + "@nevware21/ts-utils": ">= 0.14.0 < 2.x" }, "peerDependencies": { "tslib": ">= 1.0.0" } }, "node_modules/@microsoft/applicationinsights-core-js": { - "version": "3.4.1", - "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-core-js/-/applicationinsights-core-js-3.4.1.tgz", - "integrity": "sha512-eXIHZ1+nvBiJgVpufBiTP801Vtr5FEwjWZioUsb44NC/z/UcsZh2MDJ1mBpjaDO73LVYUw/ZZmDCCo6Pg/61kA==", + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-core-js/-/applicationinsights-core-js-3.4.2.tgz", + "integrity": "sha512-Iw3gq1JREKLbXiVpr3F0+Ezuzphe+o25n9me9H5Kkjmck6tIkuGQea01SNfeemE4wf2mop2QQSvTcKxT8tNN1g==", "license": "MIT", "dependencies": { "@microsoft/applicationinsights-shims": "3.0.1", "@microsoft/dynamicproto-js": "^2.0.3", - "@nevware21/ts-async": ">= 0.5.5 < 2.x", - "@nevware21/ts-utils": ">= 0.12.6 < 2.x" + "@nevware21/ts-async": ">= 0.5.5 < 0.6.0", + "@nevware21/ts-utils": ">= 0.14.0 < 2.x" }, "peerDependencies": { "tslib": ">= 1.0.0" } }, + "node_modules/@microsoft/applicationinsights-core-js/node_modules/@nevware21/ts-async": { + "version": "0.5.5", + "resolved": "https://registry.npmjs.org/@nevware21/ts-async/-/ts-async-0.5.5.tgz", + "integrity": "sha512-vwqaL05iJPjLeh5igPi8MeeAu10i+Aq7xko1fbo9F5Si6MnVN5505qaV7AhSdk5MCBJVT/UYMk3kgInNjDb4Ig==", + "license": "MIT", + "dependencies": { + "@nevware21/ts-utils": ">= 0.12.2 < 2.x" + } + }, "node_modules/@microsoft/applicationinsights-shims": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/@microsoft/applicationinsights-shims/-/applicationinsights-shims-3.0.1.tgz", @@ -1440,15 +1459,22 @@ } }, "node_modules/@types/node": { - "version": "25.9.1", - "resolved": "https://registry.npmjs.org/@types/node/-/node-25.9.1.tgz", - "integrity": "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg==", + "version": "26.0.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.0.1.tgz", + "integrity": "sha512-fc3KiUoBt6kie0N9bIW3E47vZsuaMf0PM2AaUpLCLT0s/LvX1nxAim6Fc049cNxODPpGm6qRAuUOB86SkRuPQw==", "dev": true, "license": "MIT", "dependencies": { - "undici-types": ">=7.24.0 <7.24.7" + "undici-types": "~8.3.0" } }, + "node_modules/@types/node/node_modules/undici-types": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", + "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", + "dev": true, + "license": "MIT" + }, "node_modules/@types/normalize-package-data": { "version": "2.4.4", "resolved": "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.4.tgz", @@ -1504,9 +1530,9 @@ } }, "node_modules/@unicode/unicode-15.1.0": { - "version": "1.6.16", - "resolved": "https://registry.npmjs.org/@unicode/unicode-15.1.0/-/unicode-15.1.0-1.6.16.tgz", - "integrity": "sha512-F8/F0V+mnYJQbHJlP7pZYbNE0DK/vl0IMrCvO59J0IKcBSKiezNHHXQKO37yAxJZGiZ1Zmycfg7GoyI5wsAXyQ==", + "version": "1.6.17", + "resolved": "https://registry.npmjs.org/@unicode/unicode-15.1.0/-/unicode-15.1.0-1.6.17.tgz", + "integrity": "sha512-vhIA4YCwefqQomvbsdkMXVjlTr3OPg99UlRlz04yK6pr2VCrbIA4+4HEbmwx2b92zMwprNGh8Zb6gqf4hE3YXQ==", "dev": true, "license": "MIT" }, @@ -2573,9 +2599,9 @@ } }, "node_modules/esbuild": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.0.tgz", - "integrity": "sha512-sNR9MHpXSUV/XB4zmsFKN+QgVG82Cc7+/aaxJ8Adi8hyOac+EXptIp45QBPaVyX3N70664wRbTcLTOemCAnyqw==", + "version": "0.28.1", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz", + "integrity": "sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -2586,32 +2612,32 @@ "node": ">=18" }, "optionalDependencies": { - "@esbuild/aix-ppc64": "0.28.0", - "@esbuild/android-arm": "0.28.0", - "@esbuild/android-arm64": "0.28.0", - "@esbuild/android-x64": "0.28.0", - "@esbuild/darwin-arm64": "0.28.0", - "@esbuild/darwin-x64": "0.28.0", - "@esbuild/freebsd-arm64": "0.28.0", - "@esbuild/freebsd-x64": "0.28.0", - "@esbuild/linux-arm": "0.28.0", - "@esbuild/linux-arm64": "0.28.0", - "@esbuild/linux-ia32": "0.28.0", - "@esbuild/linux-loong64": "0.28.0", - "@esbuild/linux-mips64el": "0.28.0", - "@esbuild/linux-ppc64": "0.28.0", - "@esbuild/linux-riscv64": "0.28.0", - "@esbuild/linux-s390x": "0.28.0", - "@esbuild/linux-x64": "0.28.0", - "@esbuild/netbsd-arm64": "0.28.0", - "@esbuild/netbsd-x64": "0.28.0", - "@esbuild/openbsd-arm64": "0.28.0", - "@esbuild/openbsd-x64": "0.28.0", - "@esbuild/openharmony-arm64": "0.28.0", - "@esbuild/sunos-x64": "0.28.0", - "@esbuild/win32-arm64": "0.28.0", - "@esbuild/win32-ia32": "0.28.0", - "@esbuild/win32-x64": "0.28.0" + "@esbuild/aix-ppc64": "0.28.1", + "@esbuild/android-arm": "0.28.1", + "@esbuild/android-arm64": "0.28.1", + "@esbuild/android-x64": "0.28.1", + "@esbuild/darwin-arm64": "0.28.1", + "@esbuild/darwin-x64": "0.28.1", + "@esbuild/freebsd-arm64": "0.28.1", + "@esbuild/freebsd-x64": "0.28.1", + "@esbuild/linux-arm": "0.28.1", + "@esbuild/linux-arm64": "0.28.1", + "@esbuild/linux-ia32": "0.28.1", + "@esbuild/linux-loong64": "0.28.1", + "@esbuild/linux-mips64el": "0.28.1", + "@esbuild/linux-ppc64": "0.28.1", + "@esbuild/linux-riscv64": "0.28.1", + "@esbuild/linux-s390x": "0.28.1", + "@esbuild/linux-x64": "0.28.1", + "@esbuild/netbsd-arm64": "0.28.1", + "@esbuild/netbsd-x64": "0.28.1", + "@esbuild/openbsd-arm64": "0.28.1", + "@esbuild/openbsd-x64": "0.28.1", + "@esbuild/openharmony-arm64": "0.28.1", + "@esbuild/sunos-x64": "0.28.1", + "@esbuild/win32-arm64": "0.28.1", + "@esbuild/win32-ia32": "0.28.1", + "@esbuild/win32-x64": "0.28.1" } }, "node_modules/execa": { @@ -2733,17 +2759,17 @@ } }, "node_modules/form-data": { - "version": "4.0.5", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", - "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", + "version": "4.0.6", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.6.tgz", + "integrity": "sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==", "dev": true, "license": "MIT", "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" + "hasown": "^2.0.4", + "mime-types": "^2.1.35" }, "engines": { "node": ">= 6" @@ -4184,13 +4210,14 @@ } }, "node_modules/qs": { - "version": "6.15.2", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz", - "integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==", + "version": "6.15.3", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz", + "integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==", "dev": true, "license": "BSD-3-Clause", "dependencies": { - "side-channel": "^1.1.0" + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" }, "engines": { "node": ">=0.6" @@ -4445,9 +4472,9 @@ } }, "node_modules/semver": { - "version": "7.8.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.2.tgz", - "integrity": "sha512-c8jsqUZm3omBOI66G90z1Dyw5z622G8oLG+omfsHBJf3CWQTlOcwOjvOG6wtiNfW6anKm/eA39LMwMtMez2TiQ==", + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", "license": "ISC", "bin": { "semver": "bin/semver.js" @@ -4480,15 +4507,15 @@ } }, "node_modules/side-channel": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", - "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "object-inspect": "^1.13.3", - "side-channel-list": "^1.0.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" }, @@ -5051,9 +5078,9 @@ "license": "MIT" }, "node_modules/undici": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/undici/-/undici-7.27.1.tgz", - "integrity": "sha512-UDdpiex+mzigiyrXrGbiUaF4HzTNhKbh2vRNFaTMzcqmLIPrZxaCtwo/1TMSuWoM1Xz3WiTo9KdgI3kRqYzJGg==", + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.28.0.tgz", + "integrity": "sha512-cRZYrTDwWznlnRiPjggAGxZXanty6M8RV1ff8Wm4LWXBp7/IG8v5DnOm74DtUBp9OONpK75YlPnIjQqX0dBDtA==", "dev": true, "license": "MIT", "engines": { @@ -5139,14 +5166,14 @@ } }, "node_modules/vscode-languageclient": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-10.0.0.tgz", - "integrity": "sha512-3yRHFkktZQCCg8ehHnD2Z4DZ4mZ17FNo8bxM4OFt8wtpxNBAOZGHmpbIflZSkicvCxi+ozuWntbdeWiY0gP77w==", + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-10.0.1.tgz", + "integrity": "sha512-kXitJTQVKfv69/TY0LnQdsSMaqzRaeoJMMic+B6ad7HLtFPO46MLxpNjnFh1KF1nOhZUoLX+6e+JoIl+Jp3ycQ==", "license": "MIT", "dependencies": { "minimatch": "^10.2.5", "semver": "^7.8.1", - "vscode-languageserver-protocol": "3.18.0", + "vscode-languageserver-protocol": "3.18.1", "vscode-languageserver-textdocument": "1.0.13" }, "engines": { @@ -5154,9 +5181,9 @@ } }, "node_modules/vscode-languageserver-protocol": { - "version": "3.18.0", - "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.18.0.tgz", - "integrity": "sha512-Zdz+kJ12Iz6tc11xfZyEo501bBATHXrCjmMfnaR3pMnf1CoqZBKIynba3P+/bi9VEdrMbNtAVKYpKhbODvqy+Q==", + "version": "3.18.1", + "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.18.1.tgz", + "integrity": "sha512-RTiiVHdpxpYcJVI5sq6S5TLjQ4WDR/rBrIWru+kPXe6sGQ9PFQ3GamrTKLvPqbR4ylr1SoodhmcqbFII0WXVuw==", "license": "MIT", "dependencies": { "vscode-jsonrpc": "9.0.0", @@ -5283,9 +5310,9 @@ "license": "ISC" }, "node_modules/yauzl": { - "version": "3.3.2", - "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-3.3.2.tgz", - "integrity": "sha512-Md9ankxxN23wncAN8s7+Tn3Co52zLUPMtnrLAbVCnfG5d2tKBFfmygYSgXlqFgXObtzIgqkx7aNgDBpso9+4qA==", + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-3.4.0.tgz", + "integrity": "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw==", "dev": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index 48e55ebb926..633b43dc570 100644 --- a/package.json +++ b/package.json @@ -11,7 +11,7 @@ "@types/node": "latest", "@types/tmp": "^0.2.6", "@types/which": "^3.0.4", - "@unicode/unicode-15.1.0": "^1.6.16", + "@unicode/unicode-15.1.0": "^1.6.17", "adm-zip": "^0.5.17", "chokidar": "^5.0.0", "dprint": "^0.54.0", @@ -45,14 +45,14 @@ "@microsoft/1ds-core-js": "4.3.11", "@microsoft/1ds-post-js": "4.3.11" }, - "packageManager": "npm@11.16.0+sha512.03be172fc3b199c7a06433163e459be5b110a6983c1dd6305b7ac10f6b0fa12e1440755a8df6b1064ab2ccb789df0474919fb9c684e322dc57685ede21752ccb", + "packageManager": "npm@11.17.0+sha512.3eeaf18997b11070d313849268b23766b9db0068997dec9471073170fe43fa17f2b4d0337bf0f52330ee2274e7f5754b21b01052742e48f5c9c74d8b1e32ef43", "volta": { "node": "22.22.0", - "npm": "11.16.0" + "npm": "11.17.0" }, "allowScripts": { "dprint@0.54.0": true, - "esbuild@0.28.0": true, + "esbuild@0.28.1": true, "@vscode/vsce-sign@2.0.9": true, "keytar@7.9.0": true } diff --git a/testdata/baselines/reference/api/encodeSourceFileWithUnicodeEscapes.txt b/testdata/baselines/reference/api/encodeSourceFileWithUnicodeEscapes.txt index 51728452ee3..839843b07ab 100644 --- a/testdata/baselines/reference/api/encodeSourceFileWithUnicodeEscapes.txt +++ b/testdata/baselines/reference/api/encodeSourceFileWithUnicodeEscapes.txt @@ -1,27 +1,27 @@ -KindSourceFile [0, 98), i=1, next=0 - NodeList [0, 98), i=2, next=27 - KindVariableStatement [0, 15), i=3, next=9 - KindVariableDeclarationList [0, 14), i=4, next=0 - NodeList [3, 14), i=5, next=0 - KindVariableDeclaration [3, 14), i=6, next=0 +KindSourceFile [0, 96), i=1, next=0 + NodeList [0, 96), i=2, next=27 + KindVariableStatement [0, 13), i=3, next=9 + KindVariableDeclarationList [0, 12), i=4, next=0 + NodeList [3, 12), i=5, next=0 + KindVariableDeclaration [3, 12), i=6, next=0 KindIdentifier "a" [3, 5), i=7, next=8 - KindStringLiteral [7, 14), i=8, next=0 - KindVariableStatement [15, 39), i=9, next=15 - KindVariableDeclarationList [15, 38), i=10, next=0 - NodeList [19, 38), i=11, next=0 - KindVariableDeclaration [19, 38), i=12, next=0 - KindIdentifier "b" [19, 21), i=13, next=14 - KindStringLiteral [23, 38), i=14, next=0 - KindVariableStatement [39, 69), i=15, next=21 - KindVariableDeclarationList [39, 68), i=16, next=0 - NodeList [43, 68), i=17, next=0 - KindVariableDeclaration [43, 68), i=18, next=0 - KindIdentifier "c" [43, 45), i=19, next=20 - KindStringLiteral [47, 68), i=20, next=0 - KindVariableStatement [69, 98), i=21, next=0 - KindVariableDeclarationList [69, 98), i=22, next=0 - NodeList [73, 98), i=23, next=0 - KindVariableDeclaration [73, 98), i=24, next=0 - KindIdentifier "d" [73, 75), i=25, next=26 - KindStringLiteral [77, 98), i=26, next=0 - KindEndOfFile [98, 98), i=27, next=0 + KindStringLiteral [7, 12), i=8, next=0 + KindVariableStatement [13, 37), i=9, next=15 + KindVariableDeclarationList [13, 36), i=10, next=0 + NodeList [17, 36), i=11, next=0 + KindVariableDeclaration [17, 36), i=12, next=0 + KindIdentifier "b" [17, 19), i=13, next=14 + KindStringLiteral [21, 36), i=14, next=0 + KindVariableStatement [37, 67), i=15, next=21 + KindVariableDeclarationList [37, 66), i=16, next=0 + NodeList [41, 66), i=17, next=0 + KindVariableDeclaration [41, 66), i=18, next=0 + KindIdentifier "c" [41, 43), i=19, next=20 + KindStringLiteral [45, 66), i=20, next=0 + KindVariableStatement [67, 96), i=21, next=0 + KindVariableDeclarationList [67, 96), i=22, next=0 + NodeList [71, 96), i=23, next=0 + KindVariableDeclaration [71, 96), i=24, next=0 + KindIdentifier "d" [71, 73), i=25, next=26 + KindStringLiteral [75, 96), i=26, next=0 + KindEndOfFile [96, 96), i=27, next=0 diff --git a/testdata/baselines/reference/compiler/commonjsExportDestructuringImportedValue.js b/testdata/baselines/reference/compiler/commonjsExportDestructuringImportedValue.js new file mode 100644 index 00000000000..3770a97b643 --- /dev/null +++ b/testdata/baselines/reference/compiler/commonjsExportDestructuringImportedValue.js @@ -0,0 +1,77 @@ +//// [tests/cases/compiler/commonjsExportDestructuringImportedValue.ts] //// + +//// [enum.ts] +export class CodePriceType { + static A = "a"; + static B = "b"; +} +export default CodePriceType; +export const pair = ["a", "b"]; +export const fallback = "fallback"; + +//// [repro.ts] +import { CodePriceType } from "./enum"; +export const { A, B } = CodePriceType; + +//// [arrayPattern.ts] +import { pair } from "./enum"; +export const [ArrayA, ArrayB] = pair; + +//// [aliasedNamedObject.ts] +import { CodePriceType as PriceType } from "./enum"; +export const { A: AliasA, B: AliasB } = PriceType; + +//// [defaultObject.ts] +import CodePriceType from "./enum"; +export const { A: DefaultA, B: DefaultB } = CodePriceType; + +//// [defaultInitializer.ts] +import { CodePriceType, fallback } from "./enum"; +export const { Missing = fallback } = CodePriceType as any; + + +//// [enum.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.fallback = exports.pair = exports.CodePriceType = void 0; +class CodePriceType { + static A = "a"; + static B = "b"; +} +exports.CodePriceType = CodePriceType; +exports.default = CodePriceType; +exports.pair = ["a", "b"]; +exports.fallback = "fallback"; +//// [repro.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.B = exports.A = void 0; +const enum_1 = require("./enum"); +({ A: exports.A, B: exports.B } = enum_1.CodePriceType); +//// [arrayPattern.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ArrayB = exports.ArrayA = void 0; +const enum_1 = require("./enum"); +[exports.ArrayA, exports.ArrayB] = enum_1.pair; +//// [aliasedNamedObject.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AliasB = exports.AliasA = void 0; +const enum_1 = require("./enum"); +({ A: exports.AliasA, B: exports.AliasB } = enum_1.CodePriceType); +//// [defaultObject.js] +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DefaultB = exports.DefaultA = void 0; +const enum_1 = __importDefault(require("./enum")); +({ A: exports.DefaultA, B: exports.DefaultB } = enum_1.default); +//// [defaultInitializer.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Missing = void 0; +const enum_1 = require("./enum"); +({ Missing: exports.Missing = enum_1.fallback } = enum_1.CodePriceType); diff --git a/testdata/baselines/reference/compiler/constEnumOnlyModuleImportAliasEmit.js b/testdata/baselines/reference/compiler/constEnumOnlyModuleImportAliasEmit.js new file mode 100644 index 00000000000..90236799b3f --- /dev/null +++ b/testdata/baselines/reference/compiler/constEnumOnlyModuleImportAliasEmit.js @@ -0,0 +1,63 @@ +//// [tests/cases/compiler/constEnumOnlyModuleImportAliasEmit.ts] //// + +//// [mappa.ts] +namespace OnRtls.Mappa { + export const enum TipoCamera { Camera2D = 1, Camera3D = 2 } + export class MappaViewModel { + constructor(public canvas: any, public config: any, public tipo: TipoCamera) {} + } +} + +//// [types.d.ts] +declare namespace OnRtls.Mappa.Server { + const enum SomeFlag { A = 0 } +} + +//// [sensmap.ts] +namespace OnRtls.Carrello.Home { + import mappa = OnRtls.Mappa; + export class SensmapViewModel { + constructor() { + var x = new mappa.MappaViewModel(null, null, mappa.TipoCamera.Camera3D); + } + } +} + + +//// [mappa.js] +"use strict"; +var OnRtls; +(function (OnRtls) { + var Mappa; + (function (Mappa) { + class MappaViewModel { + canvas; + config; + tipo; + constructor(canvas, config, tipo) { + this.canvas = canvas; + this.config = config; + this.tipo = tipo; + } + } + Mappa.MappaViewModel = MappaViewModel; + })(Mappa = OnRtls.Mappa || (OnRtls.Mappa = {})); +})(OnRtls || (OnRtls = {})); +//// [sensmap.js] +"use strict"; +var OnRtls; +(function (OnRtls) { + var Carrello; + (function (Carrello) { + var Home; + (function (Home) { + var mappa = OnRtls.Mappa; + class SensmapViewModel { + constructor() { + var x = new mappa.MappaViewModel(null, null, 2 /* mappa.TipoCamera.Camera3D */); + } + } + Home.SensmapViewModel = SensmapViewModel; + })(Home = Carrello.Home || (Carrello.Home = {})); + })(Carrello = OnRtls.Carrello || (OnRtls.Carrello = {})); +})(OnRtls || (OnRtls = {})); diff --git a/testdata/baselines/reference/compiler/constEnumOnlyModuleImportAliasEmit.symbols b/testdata/baselines/reference/compiler/constEnumOnlyModuleImportAliasEmit.symbols new file mode 100644 index 00000000000..916b147424f --- /dev/null +++ b/testdata/baselines/reference/compiler/constEnumOnlyModuleImportAliasEmit.symbols @@ -0,0 +1,63 @@ +//// [tests/cases/compiler/constEnumOnlyModuleImportAliasEmit.ts] //// + +=== mappa.ts === +namespace OnRtls.Mappa { +>OnRtls : Symbol(OnRtls, Decl(mappa.ts, 0, 0), Decl(types.d.ts, 0, 0), Decl(sensmap.ts, 0, 0)) +>Mappa : Symbol(Mappa, Decl(mappa.ts, 0, 17), Decl(types.d.ts, 0, 25)) + + export const enum TipoCamera { Camera2D = 1, Camera3D = 2 } +>TipoCamera : Symbol(TipoCamera, Decl(mappa.ts, 0, 24)) +>Camera2D : Symbol(TipoCamera.Camera2D, Decl(mappa.ts, 1, 34)) +>Camera3D : Symbol(TipoCamera.Camera3D, Decl(mappa.ts, 1, 48)) + + export class MappaViewModel { +>MappaViewModel : Symbol(MappaViewModel, Decl(mappa.ts, 1, 63)) + + constructor(public canvas: any, public config: any, public tipo: TipoCamera) {} +>canvas : Symbol(MappaViewModel.canvas, Decl(mappa.ts, 3, 20)) +>config : Symbol(MappaViewModel.config, Decl(mappa.ts, 3, 39)) +>tipo : Symbol(MappaViewModel.tipo, Decl(mappa.ts, 3, 59)) +>TipoCamera : Symbol(TipoCamera, Decl(mappa.ts, 0, 24)) + } +} + +=== types.d.ts === +declare namespace OnRtls.Mappa.Server { +>OnRtls : Symbol(OnRtls, Decl(mappa.ts, 0, 0), Decl(types.d.ts, 0, 0), Decl(sensmap.ts, 0, 0)) +>Mappa : Symbol(Mappa, Decl(mappa.ts, 0, 17), Decl(types.d.ts, 0, 25)) +>Server : Symbol(Server, Decl(types.d.ts, 0, 31)) + + const enum SomeFlag { A = 0 } +>SomeFlag : Symbol(SomeFlag, Decl(types.d.ts, 0, 39)) +>A : Symbol(SomeFlag.A, Decl(types.d.ts, 1, 25)) +} + +=== sensmap.ts === +namespace OnRtls.Carrello.Home { +>OnRtls : Symbol(OnRtls, Decl(mappa.ts, 0, 0), Decl(types.d.ts, 0, 0), Decl(sensmap.ts, 0, 0)) +>Carrello : Symbol(Carrello, Decl(sensmap.ts, 0, 17)) +>Home : Symbol(Home, Decl(sensmap.ts, 0, 26)) + + import mappa = OnRtls.Mappa; +>mappa : Symbol(mappa, Decl(sensmap.ts, 0, 32)) +>OnRtls : Symbol(OnRtls, Decl(mappa.ts, 0, 0), Decl(types.d.ts, 0, 0), Decl(sensmap.ts, 0, 0)) +>Mappa : Symbol(mappa, Decl(mappa.ts, 0, 17), Decl(types.d.ts, 0, 25)) + + export class SensmapViewModel { +>SensmapViewModel : Symbol(SensmapViewModel, Decl(sensmap.ts, 1, 32)) + + constructor() { + var x = new mappa.MappaViewModel(null, null, mappa.TipoCamera.Camera3D); +>x : Symbol(x, Decl(sensmap.ts, 4, 15)) +>mappa.MappaViewModel : Symbol(mappa.MappaViewModel, Decl(mappa.ts, 1, 63)) +>mappa : Symbol(mappa, Decl(sensmap.ts, 0, 32)) +>MappaViewModel : Symbol(mappa.MappaViewModel, Decl(mappa.ts, 1, 63)) +>mappa.TipoCamera.Camera3D : Symbol(mappa.TipoCamera.Camera3D, Decl(mappa.ts, 1, 48)) +>mappa.TipoCamera : Symbol(mappa.TipoCamera, Decl(mappa.ts, 0, 24)) +>mappa : Symbol(mappa, Decl(sensmap.ts, 0, 32)) +>TipoCamera : Symbol(mappa.TipoCamera, Decl(mappa.ts, 0, 24)) +>Camera3D : Symbol(mappa.TipoCamera.Camera3D, Decl(mappa.ts, 1, 48)) + } + } +} + diff --git a/testdata/baselines/reference/compiler/constEnumOnlyModuleImportAliasEmit.types b/testdata/baselines/reference/compiler/constEnumOnlyModuleImportAliasEmit.types new file mode 100644 index 00000000000..4bb2ec823dc --- /dev/null +++ b/testdata/baselines/reference/compiler/constEnumOnlyModuleImportAliasEmit.types @@ -0,0 +1,62 @@ +//// [tests/cases/compiler/constEnumOnlyModuleImportAliasEmit.ts] //// + +=== mappa.ts === +namespace OnRtls.Mappa { +>OnRtls : typeof OnRtls +>Mappa : typeof Mappa + + export const enum TipoCamera { Camera2D = 1, Camera3D = 2 } +>TipoCamera : TipoCamera +>Camera2D : TipoCamera.Camera2D +>1 : 1 +>Camera3D : TipoCamera.Camera3D +>2 : 2 + + export class MappaViewModel { +>MappaViewModel : MappaViewModel + + constructor(public canvas: any, public config: any, public tipo: TipoCamera) {} +>canvas : any +>config : any +>tipo : TipoCamera + } +} + +=== types.d.ts === +declare namespace OnRtls.Mappa.Server { + const enum SomeFlag { A = 0 } +>SomeFlag : SomeFlag +>A : SomeFlag.A +>0 : 0 +} + +=== sensmap.ts === +namespace OnRtls.Carrello.Home { +>OnRtls : typeof OnRtls +>Carrello : typeof Carrello +>Home : typeof Home + + import mappa = OnRtls.Mappa; +>mappa : typeof mappa +>OnRtls : typeof OnRtls +>Mappa : typeof mappa + + export class SensmapViewModel { +>SensmapViewModel : SensmapViewModel + + constructor() { + var x = new mappa.MappaViewModel(null, null, mappa.TipoCamera.Camera3D); +>x : mappa.MappaViewModel +>new mappa.MappaViewModel(null, null, mappa.TipoCamera.Camera3D) : mappa.MappaViewModel +>mappa.MappaViewModel : typeof mappa.MappaViewModel +>mappa : typeof mappa +>MappaViewModel : typeof mappa.MappaViewModel +>mappa.TipoCamera.Camera3D : mappa.TipoCamera.Camera3D +>mappa.TipoCamera : typeof mappa.TipoCamera +>mappa : typeof mappa +>TipoCamera : typeof mappa.TipoCamera +>Camera3D : mappa.TipoCamera.Camera3D + } + } +} + diff --git a/testdata/baselines/reference/compiler/distributiveConditionalBaseConstraint.symbols b/testdata/baselines/reference/compiler/distributiveConditionalBaseConstraint.symbols new file mode 100644 index 00000000000..6b6932ac7f1 --- /dev/null +++ b/testdata/baselines/reference/compiler/distributiveConditionalBaseConstraint.symbols @@ -0,0 +1,207 @@ +//// [tests/cases/compiler/distributiveConditionalBaseConstraint.ts] //// + +=== distributiveConditionalBaseConstraint.ts === +// https://github.com/microsoft/TypeScript/issues/63568 + +type Type = { values: string }; +>Type : Symbol(Type, Decl(distributiveConditionalBaseConstraint.ts, 0, 0)) +>values : Symbol(values, Decl(distributiveConditionalBaseConstraint.ts, 2, 13)) + +type Wrapped = { values: T["values"] }; +>Wrapped : Symbol(Wrapped, Decl(distributiveConditionalBaseConstraint.ts, 2, 31)) +>T : Symbol(T, Decl(distributiveConditionalBaseConstraint.ts, 4, 13)) +>Type : Symbol(Type, Decl(distributiveConditionalBaseConstraint.ts, 0, 0)) +>values : Symbol(values, Decl(distributiveConditionalBaseConstraint.ts, 4, 32)) +>T : Symbol(T, Decl(distributiveConditionalBaseConstraint.ts, 4, 13)) + +type FromObject, Props extends Context, Shape extends Record = { +>FromObject : Symbol(FromObject, Decl(distributiveConditionalBaseConstraint.ts, 4, 55)) +>Context : Symbol(Context, Decl(distributiveConditionalBaseConstraint.ts, 6, 16)) +>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) +>Type : Symbol(Type, Decl(distributiveConditionalBaseConstraint.ts, 0, 0)) +>Props : Symbol(Props, Decl(distributiveConditionalBaseConstraint.ts, 6, 53)) +>Context : Symbol(Context, Decl(distributiveConditionalBaseConstraint.ts, 6, 16)) +>Shape : Symbol(Shape, Decl(distributiveConditionalBaseConstraint.ts, 6, 76)) +>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) +>Props : Symbol(Props, Decl(distributiveConditionalBaseConstraint.ts, 6, 53)) +>Type : Symbol(Type, Decl(distributiveConditionalBaseConstraint.ts, 0, 0)) + + [Key in keyof Props]: Wrapped>; +>Key : Symbol(Key, Decl(distributiveConditionalBaseConstraint.ts, 7, 3)) +>Props : Symbol(Props, Decl(distributiveConditionalBaseConstraint.ts, 6, 53)) +>Wrapped : Symbol(Wrapped, Decl(distributiveConditionalBaseConstraint.ts, 2, 31)) +>FromSchema : Symbol(FromSchema, Decl(distributiveConditionalBaseConstraint.ts, 8, 11)) +>Context : Symbol(Context, Decl(distributiveConditionalBaseConstraint.ts, 6, 16)) +>Props : Symbol(Props, Decl(distributiveConditionalBaseConstraint.ts, 6, 53)) +>Key : Symbol(Key, Decl(distributiveConditionalBaseConstraint.ts, 7, 3)) + +}> = Shape; +>Shape : Symbol(Shape, Decl(distributiveConditionalBaseConstraint.ts, 6, 76)) + +type FromSchema, S> = +>FromSchema : Symbol(FromSchema, Decl(distributiveConditionalBaseConstraint.ts, 8, 11)) +>Context : Symbol(Context, Decl(distributiveConditionalBaseConstraint.ts, 10, 16)) +>Record : Symbol(Record, Decl(lib.es5.d.ts, --, --)) +>Type : Symbol(Type, Decl(distributiveConditionalBaseConstraint.ts, 0, 0)) +>S : Symbol(S, Decl(distributiveConditionalBaseConstraint.ts, 10, 53)) + + S extends Type ? FromSchema : never; +>S : Symbol(S, Decl(distributiveConditionalBaseConstraint.ts, 10, 53)) +>Type : Symbol(Type, Decl(distributiveConditionalBaseConstraint.ts, 0, 0)) +>FromSchema : Symbol(FromSchema, Decl(distributiveConditionalBaseConstraint.ts, 8, 11)) +>Context : Symbol(Context, Decl(distributiveConditionalBaseConstraint.ts, 10, 16)) +>Context : Symbol(Context, Decl(distributiveConditionalBaseConstraint.ts, 10, 16)) +>Context : Symbol(Context, Decl(distributiveConditionalBaseConstraint.ts, 10, 16)) + +// https://github.com/microsoft/typescript-go/issues/4463 + +type JSONSchema = +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) + + | boolean + | Readonly<{ +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) + + items?: JSONSchema; +>items : Symbol(items, Decl(distributiveConditionalBaseConstraint.ts, 17, 14)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) + + additionalItems?: JSONSchema; +>additionalItems : Symbol(additionalItems, Decl(distributiveConditionalBaseConstraint.ts, 18, 25)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) + + properties?: JSONSchema; +>properties : Symbol(properties, Decl(distributiveConditionalBaseConstraint.ts, 19, 35)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) + + additionalProperties?: JSONSchema; +>additionalProperties : Symbol(additionalProperties, Decl(distributiveConditionalBaseConstraint.ts, 20, 30)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) + + }>; + +// Stands in for json-schema-to-ts's ParseSchema; its only role here is to impose the +// `extends JSONSchema` constraint on whatever type it is handed. +type ParseSchema = unknown; +>ParseSchema : Symbol(ParseSchema, Decl(distributiveConditionalBaseConstraint.ts, 22, 7)) +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 26, 17)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) + +type RemoveInvalidAdditionalItems = SCHEMA extends Readonly<{ +>RemoveInvalidAdditionalItems : Symbol(RemoveInvalidAdditionalItems, Decl(distributiveConditionalBaseConstraint.ts, 26, 54)) +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 28, 34)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 28, 34)) +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) + + items: JSONSchema; +>items : Symbol(items, Decl(distributiveConditionalBaseConstraint.ts, 28, 88)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) + +}> + ? SCHEMA extends Readonly<{ additionalItems: JSONSchema }> +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 28, 34)) +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) +>additionalItems : Symbol(additionalItems, Decl(distributiveConditionalBaseConstraint.ts, 31, 29)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) + + ? SCHEMA +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 28, 34)) + + : SCHEMA & Readonly<{ additionalItems: true }> +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 28, 34)) +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) +>additionalItems : Symbol(additionalItems, Decl(distributiveConditionalBaseConstraint.ts, 33, 25)) + + : SCHEMA extends boolean +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 28, 34)) + + ? SCHEMA +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 28, 34)) + + : Omit; +>Omit : Symbol(Omit, Decl(lib.es5.d.ts, --, --)) +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 28, 34)) + +type RemoveInvalidAdditionalProperties = SCHEMA extends Readonly<{ +>RemoveInvalidAdditionalProperties : Symbol(RemoveInvalidAdditionalProperties, Decl(distributiveConditionalBaseConstraint.ts, 36, 38)) +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 38, 39)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 38, 39)) +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) + + additionalProperties: JSONSchema; +>additionalProperties : Symbol(additionalProperties, Decl(distributiveConditionalBaseConstraint.ts, 38, 93)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) + +}> + ? SCHEMA extends Readonly<{ properties: JSONSchema }> +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 38, 39)) +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) +>properties : Symbol(properties, Decl(distributiveConditionalBaseConstraint.ts, 41, 29)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) + + ? SCHEMA +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 38, 39)) + + : SCHEMA & Readonly<{ properties: {} }> +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 38, 39)) +>Readonly : Symbol(Readonly, Decl(lib.es5.d.ts, --, --)) +>properties : Symbol(properties, Decl(distributiveConditionalBaseConstraint.ts, 43, 25)) + + : SCHEMA extends boolean +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 38, 39)) + + ? SCHEMA +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 38, 39)) + + : Omit; +>Omit : Symbol(Omit, Decl(lib.es5.d.ts, --, --)) +>SCHEMA : Symbol(SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 38, 39)) + +type MergeSubSchema< +>MergeSubSchema : Symbol(MergeSubSchema, Decl(distributiveConditionalBaseConstraint.ts, 46, 43)) + + SUB_SCHEMA extends JSONSchema, +>SUB_SCHEMA : Symbol(SUB_SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 48, 20)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) + + CLEANED_SUB_SCHEMA extends JSONSchema = RemoveInvalidAdditionalProperties< +>CLEANED_SUB_SCHEMA : Symbol(CLEANED_SUB_SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 49, 32)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) +>RemoveInvalidAdditionalProperties : Symbol(RemoveInvalidAdditionalProperties, Decl(distributiveConditionalBaseConstraint.ts, 36, 38)) + + RemoveInvalidAdditionalItems +>RemoveInvalidAdditionalItems : Symbol(RemoveInvalidAdditionalItems, Decl(distributiveConditionalBaseConstraint.ts, 26, 54)) +>SUB_SCHEMA : Symbol(SUB_SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 48, 20)) + + >, +> = Omit & CLEANED_SUB_SCHEMA; +>Omit : Symbol(Omit, Decl(lib.es5.d.ts, --, --)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) +>CLEANED_SUB_SCHEMA : Symbol(CLEANED_SUB_SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 49, 32)) +>CLEANED_SUB_SCHEMA : Symbol(CLEANED_SUB_SCHEMA, Decl(distributiveConditionalBaseConstraint.ts, 49, 32)) + +// The failing site: MergeSubSchema is rejected as not satisfying +// the `extends JSONSchema` constraint on ParseSchema. +type RecurseOnAllOfSchema = +>RecurseOnAllOfSchema : Symbol(RecurseOnAllOfSchema, Decl(distributiveConditionalBaseConstraint.ts, 53, 68)) +>SUB_SCHEMAS : Symbol(SUB_SCHEMAS, Decl(distributiveConditionalBaseConstraint.ts, 57, 26)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) + + SUB_SCHEMAS extends readonly [infer SUB_SCHEMAS_HEAD] +>SUB_SCHEMAS : Symbol(SUB_SCHEMAS, Decl(distributiveConditionalBaseConstraint.ts, 57, 26)) +>SUB_SCHEMAS_HEAD : Symbol(SUB_SCHEMAS_HEAD, Decl(distributiveConditionalBaseConstraint.ts, 58, 37)) + + ? SUB_SCHEMAS_HEAD extends JSONSchema +>SUB_SCHEMAS_HEAD : Symbol(SUB_SCHEMAS_HEAD, Decl(distributiveConditionalBaseConstraint.ts, 58, 37)) +>JSONSchema : Symbol(JSONSchema, Decl(distributiveConditionalBaseConstraint.ts, 11, 71)) + + ? ParseSchema> +>ParseSchema : Symbol(ParseSchema, Decl(distributiveConditionalBaseConstraint.ts, 22, 7)) +>MergeSubSchema : Symbol(MergeSubSchema, Decl(distributiveConditionalBaseConstraint.ts, 46, 43)) +>SUB_SCHEMAS_HEAD : Symbol(SUB_SCHEMAS_HEAD, Decl(distributiveConditionalBaseConstraint.ts, 58, 37)) + + : never + : never; + diff --git a/testdata/baselines/reference/compiler/distributiveConditionalBaseConstraint.types b/testdata/baselines/reference/compiler/distributiveConditionalBaseConstraint.types new file mode 100644 index 00000000000..c6d02aba98a --- /dev/null +++ b/testdata/baselines/reference/compiler/distributiveConditionalBaseConstraint.types @@ -0,0 +1,107 @@ +//// [tests/cases/compiler/distributiveConditionalBaseConstraint.ts] //// + +=== distributiveConditionalBaseConstraint.ts === +// https://github.com/microsoft/TypeScript/issues/63568 + +type Type = { values: string }; +>Type : Type +>values : string + +type Wrapped = { values: T["values"] }; +>Wrapped : Wrapped +>values : T["values"] + +type FromObject, Props extends Context, Shape extends Record = { +>FromObject : Shape + + [Key in keyof Props]: Wrapped>; +}> = Shape; + +type FromSchema, S> = +>FromSchema : FromSchema + + S extends Type ? FromSchema : never; + +// https://github.com/microsoft/typescript-go/issues/4463 + +type JSONSchema = +>JSONSchema : JSONSchema + + | boolean + | Readonly<{ + items?: JSONSchema; +>items : JSONSchema | undefined + + additionalItems?: JSONSchema; +>additionalItems : JSONSchema | undefined + + properties?: JSONSchema; +>properties : JSONSchema | undefined + + additionalProperties?: JSONSchema; +>additionalProperties : JSONSchema | undefined + + }>; + +// Stands in for json-schema-to-ts's ParseSchema; its only role here is to impose the +// `extends JSONSchema` constraint on whatever type it is handed. +type ParseSchema = unknown; +>ParseSchema : unknown + +type RemoveInvalidAdditionalItems = SCHEMA extends Readonly<{ +>RemoveInvalidAdditionalItems : RemoveInvalidAdditionalItems + + items: JSONSchema; +>items : JSONSchema + +}> + ? SCHEMA extends Readonly<{ additionalItems: JSONSchema }> +>additionalItems : JSONSchema + + ? SCHEMA + : SCHEMA & Readonly<{ additionalItems: true }> +>additionalItems : true +>true : true + + : SCHEMA extends boolean + ? SCHEMA + : Omit; + +type RemoveInvalidAdditionalProperties = SCHEMA extends Readonly<{ +>RemoveInvalidAdditionalProperties : RemoveInvalidAdditionalProperties + + additionalProperties: JSONSchema; +>additionalProperties : JSONSchema + +}> + ? SCHEMA extends Readonly<{ properties: JSONSchema }> +>properties : JSONSchema + + ? SCHEMA + : SCHEMA & Readonly<{ properties: {} }> +>properties : {} + + : SCHEMA extends boolean + ? SCHEMA + : Omit; + +type MergeSubSchema< +>MergeSubSchema : MergeSubSchema + + SUB_SCHEMA extends JSONSchema, + CLEANED_SUB_SCHEMA extends JSONSchema = RemoveInvalidAdditionalProperties< + RemoveInvalidAdditionalItems + >, +> = Omit & CLEANED_SUB_SCHEMA; + +// The failing site: MergeSubSchema is rejected as not satisfying +// the `extends JSONSchema` constraint on ParseSchema. +type RecurseOnAllOfSchema = +>RecurseOnAllOfSchema : RecurseOnAllOfSchema + + SUB_SCHEMAS extends readonly [infer SUB_SCHEMAS_HEAD] + ? SUB_SCHEMAS_HEAD extends JSONSchema + ? ParseSchema> + : never + : never; + diff --git a/testdata/baselines/reference/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.js b/testdata/baselines/reference/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.js new file mode 100644 index 00000000000..874fb37548a --- /dev/null +++ b/testdata/baselines/reference/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.js @@ -0,0 +1,112 @@ +//// [tests/cases/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.ts] //// + +//// [component.d.ts] +export class Component { + state: any; + constructor(props?: any); +} + +export class WithAccessor { + get value(): number; + set value(v: number); +} + +export class WithMethod { + method(): void; +} + +//// [main.js] +import { Component, WithAccessor, WithMethod } from "./component"; + +export class C1 extends Component { + state = { count: 0 }; +} + +export class C2 extends Component { + constructor() { + super({}); + this.state = { count: 0 }; + } +} + +export class C3 extends Component { + update() { + this.state = { count: 1 }; + } +} + +export class C4 extends WithAccessor { + constructor() { + super(); + this.value = 1; + } +} + +/** @implements {WithAccessor} */ +export class C5 { + constructor() { + this.value = 1; + } +} + +export class C6 extends WithMethod { + constructor() { + super(); + this.method = this.method.bind(this); + } +} + +//// [mainTs.ts] +import { Component } from "./component"; + +export class C1 extends Component { + state = { count: 0 }; +} + +export class C2 extends Component { + constructor() { + super({}); + this.state = { count: 0 }; + } +} + + + + +//// [main.d.ts] +import { Component, WithAccessor, WithMethod } from "./component"; +export declare class C1 extends Component { + state: { + count: number; + }; +} +export declare class C2 extends Component { + state: { + count: number; + }; + constructor(); +} +export declare class C3 extends Component { + update(): void; +} +export declare class C4 extends WithAccessor { + constructor(); +} +/** @implements {WithAccessor} */ +export declare class C5 implements WithAccessor { + value: number; + constructor(); +} +export declare class C6 extends WithMethod { + constructor(); +} +//// [mainTs.d.ts] +import { Component } from "./component"; +export declare class C1 extends Component { + state: { + count: number; + }; +} +export declare class C2 extends Component { + constructor(); +} diff --git a/testdata/baselines/reference/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.symbols b/testdata/baselines/reference/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.symbols new file mode 100644 index 00000000000..f01d9a8d487 --- /dev/null +++ b/testdata/baselines/reference/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.symbols @@ -0,0 +1,154 @@ +//// [tests/cases/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.ts] //// + +=== component.d.ts === +export class Component { +>Component : Symbol(Component, Decl(component.d.ts, 0, 0)) + + state: any; +>state : Symbol(Component.state, Decl(component.d.ts, 0, 24)) + + constructor(props?: any); +>props : Symbol(props, Decl(component.d.ts, 2, 16)) +} + +export class WithAccessor { +>WithAccessor : Symbol(WithAccessor, Decl(component.d.ts, 3, 1)) + + get value(): number; +>value : Symbol(WithAccessor.value, Decl(component.d.ts, 5, 27), Decl(component.d.ts, 6, 24)) + + set value(v: number); +>value : Symbol(WithAccessor.value, Decl(component.d.ts, 5, 27), Decl(component.d.ts, 6, 24)) +>v : Symbol(v, Decl(component.d.ts, 7, 14)) +} + +export class WithMethod { +>WithMethod : Symbol(WithMethod, Decl(component.d.ts, 8, 1)) + + method(): void; +>method : Symbol(WithMethod.method, Decl(component.d.ts, 10, 25)) +} + +=== main.js === +import { Component, WithAccessor, WithMethod } from "./component"; +>Component : Symbol(Component, Decl(main.js, 0, 8)) +>WithAccessor : Symbol(WithAccessor, Decl(main.js, 0, 19)) +>WithMethod : Symbol(WithMethod, Decl(main.js, 0, 33)) + +export class C1 extends Component { +>C1 : Symbol(C1, Decl(main.js, 0, 66)) +>Component : Symbol(Component, Decl(main.js, 0, 8)) + + state = { count: 0 }; +>state : Symbol(C1.state, Decl(main.js, 2, 35)) +>count : Symbol(count, Decl(main.js, 3, 13)) +} + +export class C2 extends Component { +>C2 : Symbol(C2, Decl(main.js, 4, 1)) +>Component : Symbol(Component, Decl(main.js, 0, 8)) + + constructor() { + super({}); +>super : Symbol(Component, Decl(component.d.ts, 0, 0)) + + this.state = { count: 0 }; +>this.state : Symbol(C2.state, Decl(main.js, 8, 18)) +>this : Symbol(C2, Decl(main.js, 4, 1)) +>state : Symbol(C2.state, Decl(main.js, 8, 18)) +>count : Symbol(count, Decl(main.js, 9, 22)) + } +} + +export class C3 extends Component { +>C3 : Symbol(C3, Decl(main.js, 11, 1)) +>Component : Symbol(Component, Decl(main.js, 0, 8)) + + update() { +>update : Symbol(C3.update, Decl(main.js, 13, 35)) + + this.state = { count: 1 }; +>this.state : Symbol(C3.state, Decl(main.js, 14, 14)) +>this : Symbol(C3, Decl(main.js, 11, 1)) +>state : Symbol(C3.state, Decl(main.js, 14, 14)) +>count : Symbol(count, Decl(main.js, 15, 22)) + } +} + +export class C4 extends WithAccessor { +>C4 : Symbol(C4, Decl(main.js, 17, 1)) +>WithAccessor : Symbol(WithAccessor, Decl(main.js, 0, 19)) + + constructor() { + super(); +>super : Symbol(WithAccessor, Decl(component.d.ts, 3, 1)) + + this.value = 1; +>this.value : Symbol(C4.value, Decl(main.js, 21, 16)) +>this : Symbol(C4, Decl(main.js, 17, 1)) +>value : Symbol(C4.value, Decl(main.js, 21, 16)) + } +} + +/** @implements {WithAccessor} */ +export class C5 { +>C5 : Symbol(C5, Decl(main.js, 24, 1)) + + constructor() { + this.value = 1; +>this.value : Symbol(C5.value, Decl(main.js, 28, 19)) +>this : Symbol(C5, Decl(main.js, 24, 1)) +>value : Symbol(C5.value, Decl(main.js, 28, 19)) + } +} + +export class C6 extends WithMethod { +>C6 : Symbol(C6, Decl(main.js, 31, 1)) +>WithMethod : Symbol(WithMethod, Decl(main.js, 0, 33)) + + constructor() { + super(); +>super : Symbol(WithMethod, Decl(component.d.ts, 8, 1)) + + this.method = this.method.bind(this); +>this.method : Symbol(C6.method, Decl(main.js, 35, 16)) +>this : Symbol(C6, Decl(main.js, 31, 1)) +>method : Symbol(C6.method, Decl(main.js, 35, 16)) +>this.method.bind : Symbol(CallableFunction.bind, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>this.method : Symbol(C6.method, Decl(main.js, 35, 16)) +>this : Symbol(C6, Decl(main.js, 31, 1)) +>method : Symbol(C6.method, Decl(main.js, 35, 16)) +>bind : Symbol(CallableFunction.bind, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>this : Symbol(C6, Decl(main.js, 31, 1)) + } +} + +=== mainTs.ts === +import { Component } from "./component"; +>Component : Symbol(Component, Decl(mainTs.ts, 0, 8)) + +export class C1 extends Component { +>C1 : Symbol(C1, Decl(mainTs.ts, 0, 40)) +>Component : Symbol(Component, Decl(mainTs.ts, 0, 8)) + + state = { count: 0 }; +>state : Symbol(C1.state, Decl(mainTs.ts, 2, 35)) +>count : Symbol(count, Decl(mainTs.ts, 3, 13)) +} + +export class C2 extends Component { +>C2 : Symbol(C2, Decl(mainTs.ts, 4, 1)) +>Component : Symbol(Component, Decl(mainTs.ts, 0, 8)) + + constructor() { + super({}); +>super : Symbol(Component, Decl(component.d.ts, 0, 0)) + + this.state = { count: 0 }; +>this.state : Symbol(Component.state, Decl(component.d.ts, 0, 24)) +>this : Symbol(C2, Decl(mainTs.ts, 4, 1)) +>state : Symbol(Component.state, Decl(component.d.ts, 0, 24)) +>count : Symbol(count, Decl(mainTs.ts, 9, 22)) + } +} + diff --git a/testdata/baselines/reference/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.types b/testdata/baselines/reference/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.types new file mode 100644 index 00000000000..68b7e075a26 --- /dev/null +++ b/testdata/baselines/reference/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.types @@ -0,0 +1,179 @@ +//// [tests/cases/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.ts] //// + +=== component.d.ts === +export class Component { +>Component : Component + + state: any; +>state : any + + constructor(props?: any); +>props : any +} + +export class WithAccessor { +>WithAccessor : WithAccessor + + get value(): number; +>value : number + + set value(v: number); +>value : number +>v : number +} + +export class WithMethod { +>WithMethod : WithMethod + + method(): void; +>method : () => void +} + +=== main.js === +import { Component, WithAccessor, WithMethod } from "./component"; +>Component : typeof Component +>WithAccessor : typeof WithAccessor +>WithMethod : typeof WithMethod + +export class C1 extends Component { +>C1 : C1 +>Component : Component + + state = { count: 0 }; +>state : { count: number; } +>{ count: 0 } : { count: number; } +>count : number +>0 : 0 +} + +export class C2 extends Component { +>C2 : C2 +>Component : Component + + constructor() { + super({}); +>super({}) : void +>super : typeof Component +>{} : {} + + this.state = { count: 0 }; +>this.state = { count: 0 } : { count: number; } +>this.state : any +>this : this +>state : any +>{ count: 0 } : { count: number; } +>count : number +>0 : 0 + } +} + +export class C3 extends Component { +>C3 : C3 +>Component : Component + + update() { +>update : () => void + + this.state = { count: 1 }; +>this.state = { count: 1 } : { count: number; } +>this.state : any +>this : this +>state : any +>{ count: 1 } : { count: number; } +>count : number +>1 : 1 + } +} + +export class C4 extends WithAccessor { +>C4 : C4 +>WithAccessor : WithAccessor + + constructor() { + super(); +>super() : void +>super : typeof WithAccessor + + this.value = 1; +>this.value = 1 : 1 +>this.value : any +>this : this +>value : any +>1 : 1 + } +} + +/** @implements {WithAccessor} */ +export class C5 { +>C5 : C5 + + constructor() { + this.value = 1; +>this.value = 1 : 1 +>this.value : any +>this : this +>value : any +>1 : 1 + } +} + +export class C6 extends WithMethod { +>C6 : C6 +>WithMethod : WithMethod + + constructor() { + super(); +>super() : void +>super : typeof WithMethod + + this.method = this.method.bind(this); +>this.method = this.method.bind(this) : () => void +>this.method : any +>this : this +>method : any +>this.method.bind(this) : () => void +>this.method.bind : { (this: T, thisArg: ThisParameterType): OmitThisParameter; (this: (this: T, ...args: [...A, ...B]) => R, thisArg: T, ...args: A): (...args: B) => R; } +>this.method : () => void +>this : this +>method : () => void +>bind : { (this: T, thisArg: ThisParameterType): OmitThisParameter; (this: (this: T, ...args: [...A, ...B]) => R, thisArg: T, ...args: A): (...args: B) => R; } +>this : this + } +} + +=== mainTs.ts === +import { Component } from "./component"; +>Component : typeof Component + +export class C1 extends Component { +>C1 : C1 +>Component : Component + + state = { count: 0 }; +>state : { count: number; } +>{ count: 0 } : { count: number; } +>count : number +>0 : 0 +} + +export class C2 extends Component { +>C2 : C2 +>Component : Component + + constructor() { + super({}); +>super({}) : void +>super : typeof Component +>{} : {} + + this.state = { count: 0 }; +>this.state = { count: 0 } : { count: number; } +>this.state : any +>this : this +>state : any +>{ count: 0 } : { count: number; } +>count : number +>0 : 0 + } +} + diff --git a/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=false).symbols b/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=false).symbols new file mode 100644 index 00000000000..e348466a7b7 --- /dev/null +++ b/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=false).symbols @@ -0,0 +1,34 @@ +//// [tests/cases/compiler/jsdocModifiersInClass.ts] //// + +=== test.js === +// Unlike object literal members, class members are real class-like members, so +// JSDoc modifiers are still semantically validated under checkJs: @override +// without a base class errors. With checkJs off, nothing is validated. + +class NoBase { +>NoBase : Symbol(NoBase, Decl(test.js, 0, 0)) + + /** @override */ + foo() { +>foo : Symbol(NoBase.foo, Decl(test.js, 4, 14)) + } +} + +class Base { +>Base : Symbol(Base, Decl(test.js, 8, 1)) + + foo() { +>foo : Symbol(Base.foo, Decl(test.js, 10, 12)) + } +} + +class Derived extends Base { +>Derived : Symbol(Derived, Decl(test.js, 13, 1)) +>Base : Symbol(Base, Decl(test.js, 8, 1)) + + /** @override */ + foo() { +>foo : Symbol(Derived.foo, Decl(test.js, 15, 28)) + } +} + diff --git a/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=false).types b/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=false).types new file mode 100644 index 00000000000..3e51c5244c1 --- /dev/null +++ b/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=false).types @@ -0,0 +1,34 @@ +//// [tests/cases/compiler/jsdocModifiersInClass.ts] //// + +=== test.js === +// Unlike object literal members, class members are real class-like members, so +// JSDoc modifiers are still semantically validated under checkJs: @override +// without a base class errors. With checkJs off, nothing is validated. + +class NoBase { +>NoBase : NoBase + + /** @override */ + foo() { +>foo : () => void + } +} + +class Base { +>Base : Base + + foo() { +>foo : () => void + } +} + +class Derived extends Base { +>Derived : Derived +>Base : Base + + /** @override */ + foo() { +>foo : () => void + } +} + diff --git a/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=true).errors.txt b/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=true).errors.txt new file mode 100644 index 00000000000..dda1a6c97a2 --- /dev/null +++ b/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=true).errors.txt @@ -0,0 +1,27 @@ +test.js(7,3): error TS4121: This member cannot have a JSDoc comment with an '@override' tag because its containing class 'NoBase' does not extend another class. + + +==== test.js (1 errors) ==== + // Unlike object literal members, class members are real class-like members, so + // JSDoc modifiers are still semantically validated under checkJs: @override + // without a base class errors. With checkJs off, nothing is validated. + + class NoBase { + /** @override */ + foo() { + ~~~ +!!! error TS4121: This member cannot have a JSDoc comment with an '@override' tag because its containing class 'NoBase' does not extend another class. + } + } + + class Base { + foo() { + } + } + + class Derived extends Base { + /** @override */ + foo() { + } + } + \ No newline at end of file diff --git a/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=true).symbols b/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=true).symbols new file mode 100644 index 00000000000..e348466a7b7 --- /dev/null +++ b/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=true).symbols @@ -0,0 +1,34 @@ +//// [tests/cases/compiler/jsdocModifiersInClass.ts] //// + +=== test.js === +// Unlike object literal members, class members are real class-like members, so +// JSDoc modifiers are still semantically validated under checkJs: @override +// without a base class errors. With checkJs off, nothing is validated. + +class NoBase { +>NoBase : Symbol(NoBase, Decl(test.js, 0, 0)) + + /** @override */ + foo() { +>foo : Symbol(NoBase.foo, Decl(test.js, 4, 14)) + } +} + +class Base { +>Base : Symbol(Base, Decl(test.js, 8, 1)) + + foo() { +>foo : Symbol(Base.foo, Decl(test.js, 10, 12)) + } +} + +class Derived extends Base { +>Derived : Symbol(Derived, Decl(test.js, 13, 1)) +>Base : Symbol(Base, Decl(test.js, 8, 1)) + + /** @override */ + foo() { +>foo : Symbol(Derived.foo, Decl(test.js, 15, 28)) + } +} + diff --git a/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=true).types b/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=true).types new file mode 100644 index 00000000000..3e51c5244c1 --- /dev/null +++ b/testdata/baselines/reference/compiler/jsdocModifiersInClass(checkjs=true).types @@ -0,0 +1,34 @@ +//// [tests/cases/compiler/jsdocModifiersInClass.ts] //// + +=== test.js === +// Unlike object literal members, class members are real class-like members, so +// JSDoc modifiers are still semantically validated under checkJs: @override +// without a base class errors. With checkJs off, nothing is validated. + +class NoBase { +>NoBase : NoBase + + /** @override */ + foo() { +>foo : () => void + } +} + +class Base { +>Base : Base + + foo() { +>foo : () => void + } +} + +class Derived extends Base { +>Derived : Derived +>Base : Base + + /** @override */ + foo() { +>foo : () => void + } +} + diff --git a/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=false).js b/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=false).js new file mode 100644 index 00000000000..b2d4b0844c5 --- /dev/null +++ b/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=false).js @@ -0,0 +1,44 @@ +//// [tests/cases/compiler/jsdocModifiersInObjectLiteral.ts] //// + +//// [test.js] +// Object literal members aren't class-like members, so JSDoc modifiers like +// @override or @readonly aren't real modifiers and must not produce grammar +// errors, regardless of checkJs (#4437). + +const obj = { + /** @override */ + created() { + }, + + /** @private */ + onClose_() { + }, + + /** @readonly */ + get value() { + return 1; + }, + + /** @protected */ + set value(v) { + }, + + /** @public */ + async load() { + }, +}; + + + + +//// [test.d.ts] +declare const obj: { + /** @override */ + created(): void; + /** @private */ + onClose_(): void; + /** @readonly */ + value: number; + /** @public */ + load(): Promise; +}; diff --git a/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=false).symbols b/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=false).symbols new file mode 100644 index 00000000000..13b21ad5dd1 --- /dev/null +++ b/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=false).symbols @@ -0,0 +1,43 @@ +//// [tests/cases/compiler/jsdocModifiersInObjectLiteral.ts] //// + +=== test.js === +// Object literal members aren't class-like members, so JSDoc modifiers like +// @override or @readonly aren't real modifiers and must not produce grammar +// errors, regardless of checkJs (#4437). + +const obj = { +>obj : Symbol(obj, Decl(test.js, 4, 5)) + + /** @override */ + created() { +>created : Symbol(created, Decl(test.js, 4, 13)) + + }, + + /** @private */ + onClose_() { +>onClose_ : Symbol(onClose_, Decl(test.js, 7, 4)) + + }, + + /** @readonly */ + get value() { +>value : Symbol(value, Decl(test.js, 11, 4), Decl(test.js, 16, 4)) + + return 1; + }, + + /** @protected */ + set value(v) { +>value : Symbol(value, Decl(test.js, 11, 4), Decl(test.js, 16, 4)) +>v : Symbol(v, Decl(test.js, 19, 12)) + + }, + + /** @public */ + async load() { +>load : Symbol(load, Decl(test.js, 20, 4)) + + }, +}; + diff --git a/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=false).types b/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=false).types new file mode 100644 index 00000000000..3935506b989 --- /dev/null +++ b/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=false).types @@ -0,0 +1,46 @@ +//// [tests/cases/compiler/jsdocModifiersInObjectLiteral.ts] //// + +=== test.js === +// Object literal members aren't class-like members, so JSDoc modifiers like +// @override or @readonly aren't real modifiers and must not produce grammar +// errors, regardless of checkJs (#4437). + +const obj = { +>obj : { created(): void; onClose_(): void; value: number; load(): Promise; } +>{ /** @override */ created() { }, /** @private */ onClose_() { }, /** @readonly */ get value() { return 1; }, /** @protected */ set value(v) { }, /** @public */ async load() { },} : { created(): void; onClose_(): void; value: number; load(): Promise; } + + /** @override */ + created() { +>created : () => void + + }, + + /** @private */ + onClose_() { +>onClose_ : () => void + + }, + + /** @readonly */ + get value() { +>value : number + + return 1; +>1 : 1 + + }, + + /** @protected */ + set value(v) { +>value : number +>v : number + + }, + + /** @public */ + async load() { +>load : () => Promise + + }, +}; + diff --git a/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=true).js b/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=true).js new file mode 100644 index 00000000000..b2d4b0844c5 --- /dev/null +++ b/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=true).js @@ -0,0 +1,44 @@ +//// [tests/cases/compiler/jsdocModifiersInObjectLiteral.ts] //// + +//// [test.js] +// Object literal members aren't class-like members, so JSDoc modifiers like +// @override or @readonly aren't real modifiers and must not produce grammar +// errors, regardless of checkJs (#4437). + +const obj = { + /** @override */ + created() { + }, + + /** @private */ + onClose_() { + }, + + /** @readonly */ + get value() { + return 1; + }, + + /** @protected */ + set value(v) { + }, + + /** @public */ + async load() { + }, +}; + + + + +//// [test.d.ts] +declare const obj: { + /** @override */ + created(): void; + /** @private */ + onClose_(): void; + /** @readonly */ + value: number; + /** @public */ + load(): Promise; +}; diff --git a/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=true).symbols b/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=true).symbols new file mode 100644 index 00000000000..13b21ad5dd1 --- /dev/null +++ b/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=true).symbols @@ -0,0 +1,43 @@ +//// [tests/cases/compiler/jsdocModifiersInObjectLiteral.ts] //// + +=== test.js === +// Object literal members aren't class-like members, so JSDoc modifiers like +// @override or @readonly aren't real modifiers and must not produce grammar +// errors, regardless of checkJs (#4437). + +const obj = { +>obj : Symbol(obj, Decl(test.js, 4, 5)) + + /** @override */ + created() { +>created : Symbol(created, Decl(test.js, 4, 13)) + + }, + + /** @private */ + onClose_() { +>onClose_ : Symbol(onClose_, Decl(test.js, 7, 4)) + + }, + + /** @readonly */ + get value() { +>value : Symbol(value, Decl(test.js, 11, 4), Decl(test.js, 16, 4)) + + return 1; + }, + + /** @protected */ + set value(v) { +>value : Symbol(value, Decl(test.js, 11, 4), Decl(test.js, 16, 4)) +>v : Symbol(v, Decl(test.js, 19, 12)) + + }, + + /** @public */ + async load() { +>load : Symbol(load, Decl(test.js, 20, 4)) + + }, +}; + diff --git a/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=true).types b/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=true).types new file mode 100644 index 00000000000..3935506b989 --- /dev/null +++ b/testdata/baselines/reference/compiler/jsdocModifiersInObjectLiteral(checkjs=true).types @@ -0,0 +1,46 @@ +//// [tests/cases/compiler/jsdocModifiersInObjectLiteral.ts] //// + +=== test.js === +// Object literal members aren't class-like members, so JSDoc modifiers like +// @override or @readonly aren't real modifiers and must not produce grammar +// errors, regardless of checkJs (#4437). + +const obj = { +>obj : { created(): void; onClose_(): void; value: number; load(): Promise; } +>{ /** @override */ created() { }, /** @private */ onClose_() { }, /** @readonly */ get value() { return 1; }, /** @protected */ set value(v) { }, /** @public */ async load() { },} : { created(): void; onClose_(): void; value: number; load(): Promise; } + + /** @override */ + created() { +>created : () => void + + }, + + /** @private */ + onClose_() { +>onClose_ : () => void + + }, + + /** @readonly */ + get value() { +>value : number + + return 1; +>1 : 1 + + }, + + /** @protected */ + set value(v) { +>value : number +>v : number + + }, + + /** @public */ + async load() { +>load : () => Promise + + }, +}; + diff --git a/testdata/baselines/reference/compiler/jsxNumericEntityLoneSurrogate.symbols b/testdata/baselines/reference/compiler/jsxNumericEntityLoneSurrogate.symbols index ce9f149609e..3af89b13dae 100644 --- a/testdata/baselines/reference/compiler/jsxNumericEntityLoneSurrogate.symbols +++ b/testdata/baselines/reference/compiler/jsxNumericEntityLoneSurrogate.symbols @@ -21,18 +21,18 @@ declare var React: any; // corrupted to U+FFFD. "\uD800" is a lone high surrogate; "\uDC00" a lone low. const text =
�a�
; >text : Symbol(text, Decl(file.tsx, 10, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) const attr =
; >attr : Symbol(attr, Decl(file.tsx, 11, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >title : Symbol(title, Decl(file.tsx, 11, 17)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // A non-BMP code point reference is a single supplementary character. const supplementary =
😀
; >supplementary : Symbol(supplementary, Decl(file.tsx, 14, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/compiler/namespaceExportDestructuringReferences.js b/testdata/baselines/reference/compiler/namespaceExportDestructuringReferences.js new file mode 100644 index 00000000000..3a0f8092fad --- /dev/null +++ b/testdata/baselines/reference/compiler/namespaceExportDestructuringReferences.js @@ -0,0 +1,24 @@ +//// [tests/cases/compiler/namespaceExportDestructuringReferences.ts] //// + +//// [namespaceExportDestructuringReferences.ts] +namespace N { + export const key = "a"; + export const source: any = { a: 1, b: undefined, pair: [3, 4] }; + export const fallback = 2; + + export const { [key]: computed, b = fallback } = source; + export const [x, y] = source.pair; +} + + +//// [namespaceExportDestructuringReferences.js] +"use strict"; +var N; +(function (N) { + var _a, _b, _c, _d; + N.key = "a"; + N.source = { a: 1, b: undefined, pair: [3, 4] }; + N.fallback = 2; + _a = N.source, _b = N.key, N.computed = _a[_b], _c = _a.b, N.b = _c === void 0 ? N.fallback : _c; + _d = N.source.pair, N.x = _d[0], N.y = _d[1]; +})(N || (N = {})); diff --git a/testdata/baselines/reference/compiler/nestedGenericTypeInference.symbols b/testdata/baselines/reference/compiler/nestedGenericTypeInference.symbols new file mode 100644 index 00000000000..6d6f2f521de --- /dev/null +++ b/testdata/baselines/reference/compiler/nestedGenericTypeInference.symbols @@ -0,0 +1,90 @@ +//// [tests/cases/compiler/nestedGenericTypeInference.ts] //// + +=== nestedGenericTypeInference.ts === +// https://github.com/microsoft/typescript-go/issues/1789 + +declare function flat(args: T[] | T[][]): void; +>flat : Symbol(flat, Decl(nestedGenericTypeInference.ts, 0, 0)) +>T : Symbol(T, Decl(nestedGenericTypeInference.ts, 2, 22)) +>args : Symbol(args, Decl(nestedGenericTypeInference.ts, 2, 25)) +>T : Symbol(T, Decl(nestedGenericTypeInference.ts, 2, 22)) +>T : Symbol(T, Decl(nestedGenericTypeInference.ts, 2, 22)) + +type Value = 1 | 2; +>Value : Symbol(Value, Decl(nestedGenericTypeInference.ts, 2, 50)) + +declare const n: Value[] | Value[][]; +>n : Symbol(n, Decl(nestedGenericTypeInference.ts, 4, 13)) +>Value : Symbol(Value, Decl(nestedGenericTypeInference.ts, 2, 50)) +>Value : Symbol(Value, Decl(nestedGenericTypeInference.ts, 2, 50)) + +flat(n); +>flat : Symbol(flat, Decl(nestedGenericTypeInference.ts, 0, 0)) +>n : Symbol(n, Decl(nestedGenericTypeInference.ts, 4, 13)) + +type Box = { value: T }; +>Box : Symbol(Box, Decl(nestedGenericTypeInference.ts, 5, 8)) +>T : Symbol(T, Decl(nestedGenericTypeInference.ts, 7, 9)) +>value : Symbol(value, Decl(nestedGenericTypeInference.ts, 7, 15)) +>T : Symbol(T, Decl(nestedGenericTypeInference.ts, 7, 9)) + +declare function flat0(args: Box | Box>): void; +>flat0 : Symbol(flat0, Decl(nestedGenericTypeInference.ts, 7, 27)) +>T : Symbol(T, Decl(nestedGenericTypeInference.ts, 9, 23)) +>args : Symbol(args, Decl(nestedGenericTypeInference.ts, 9, 26)) +>Box : Symbol(Box, Decl(nestedGenericTypeInference.ts, 5, 8)) +>T : Symbol(T, Decl(nestedGenericTypeInference.ts, 9, 23)) +>Box : Symbol(Box, Decl(nestedGenericTypeInference.ts, 5, 8)) +>Box : Symbol(Box, Decl(nestedGenericTypeInference.ts, 5, 8)) +>T : Symbol(T, Decl(nestedGenericTypeInference.ts, 9, 23)) + +declare const arg0: Box | Box>; +>arg0 : Symbol(arg0, Decl(nestedGenericTypeInference.ts, 10, 13)) +>Box : Symbol(Box, Decl(nestedGenericTypeInference.ts, 5, 8)) +>Box : Symbol(Box, Decl(nestedGenericTypeInference.ts, 5, 8)) +>Box : Symbol(Box, Decl(nestedGenericTypeInference.ts, 5, 8)) + +flat0(arg0); +>flat0 : Symbol(flat0, Decl(nestedGenericTypeInference.ts, 7, 27)) +>arg0 : Symbol(arg0, Decl(nestedGenericTypeInference.ts, 10, 13)) + +declare function flat1(args: Array | Array>): void; +>flat1 : Symbol(flat1, Decl(nestedGenericTypeInference.ts, 11, 12)) +>T : Symbol(T, Decl(nestedGenericTypeInference.ts, 13, 23)) +>args : Symbol(args, Decl(nestedGenericTypeInference.ts, 13, 26)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --) ... and 4 more) +>T : Symbol(T, Decl(nestedGenericTypeInference.ts, 13, 23)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --) ... and 4 more) +>Box : Symbol(Box, Decl(nestedGenericTypeInference.ts, 5, 8)) +>T : Symbol(T, Decl(nestedGenericTypeInference.ts, 13, 23)) + +declare const arg1: Array | Array>; +>arg1 : Symbol(arg1, Decl(nestedGenericTypeInference.ts, 14, 13)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --) ... and 4 more) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --) ... and 4 more) +>Box : Symbol(Box, Decl(nestedGenericTypeInference.ts, 5, 8)) + +flat1(arg1); +>flat1 : Symbol(flat1, Decl(nestedGenericTypeInference.ts, 11, 12)) +>arg1 : Symbol(arg1, Decl(nestedGenericTypeInference.ts, 14, 13)) + +declare function flat2(args: Box | Box>): void; +>flat2 : Symbol(flat2, Decl(nestedGenericTypeInference.ts, 15, 12)) +>T : Symbol(T, Decl(nestedGenericTypeInference.ts, 17, 23)) +>args : Symbol(args, Decl(nestedGenericTypeInference.ts, 17, 26)) +>Box : Symbol(Box, Decl(nestedGenericTypeInference.ts, 5, 8)) +>T : Symbol(T, Decl(nestedGenericTypeInference.ts, 17, 23)) +>Box : Symbol(Box, Decl(nestedGenericTypeInference.ts, 5, 8)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --) ... and 4 more) +>T : Symbol(T, Decl(nestedGenericTypeInference.ts, 17, 23)) + +declare const arg2: Box | Box>; +>arg2 : Symbol(arg2, Decl(nestedGenericTypeInference.ts, 18, 13)) +>Box : Symbol(Box, Decl(nestedGenericTypeInference.ts, 5, 8)) +>Box : Symbol(Box, Decl(nestedGenericTypeInference.ts, 5, 8)) +>Array : Symbol(Array, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.core.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --) ... and 4 more) + +flat2(arg2); +>flat2 : Symbol(flat2, Decl(nestedGenericTypeInference.ts, 15, 12)) +>arg2 : Symbol(arg2, Decl(nestedGenericTypeInference.ts, 18, 13)) + diff --git a/testdata/baselines/reference/compiler/nestedGenericTypeInference.types b/testdata/baselines/reference/compiler/nestedGenericTypeInference.types new file mode 100644 index 00000000000..2f9c651216c --- /dev/null +++ b/testdata/baselines/reference/compiler/nestedGenericTypeInference.types @@ -0,0 +1,60 @@ +//// [tests/cases/compiler/nestedGenericTypeInference.ts] //// + +=== nestedGenericTypeInference.ts === +// https://github.com/microsoft/typescript-go/issues/1789 + +declare function flat(args: T[] | T[][]): void; +>flat : (args: T[] | T[][]) => void +>args : T[] | T[][] + +type Value = 1 | 2; +>Value : Value + +declare const n: Value[] | Value[][]; +>n : Value[][] | Value[] + +flat(n); +>flat(n) : void +>flat : (args: T[] | T[][]) => void +>n : Value[][] | Value[] + +type Box = { value: T }; +>Box : Box +>value : T + +declare function flat0(args: Box | Box>): void; +>flat0 : (args: Box | Box>) => void +>args : Box | Box> + +declare const arg0: Box | Box>; +>arg0 : Box | Box> + +flat0(arg0); +>flat0(arg0) : void +>flat0 : (args: Box | Box>) => void +>arg0 : Box | Box> + +declare function flat1(args: Array | Array>): void; +>flat1 : (args: Array | Array>) => void +>args : T[] | Box[] + +declare const arg1: Array | Array>; +>arg1 : string[] | Box[] + +flat1(arg1); +>flat1(arg1) : void +>flat1 : (args: Array | Array>) => void +>arg1 : string[] | Box[] + +declare function flat2(args: Box | Box>): void; +>flat2 : (args: Box | Box>) => void +>args : Box | Box + +declare const arg2: Box | Box>; +>arg2 : Box | Box + +flat2(arg2); +>flat2(arg2) : void +>flat2 : (args: Box | Box>) => void +>arg2 : Box | Box + diff --git a/testdata/baselines/reference/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.js b/testdata/baselines/reference/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.js new file mode 100644 index 00000000000..ad884c3ae0a --- /dev/null +++ b/testdata/baselines/reference/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.js @@ -0,0 +1,70 @@ +//// [tests/cases/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.ts] //// + +//// [parametersAliasOverTypeofPreservedAsIsInDeclarations.ts] +interface OverloadUnion { + (arg: string): Promise; + (arg: string, callback: (error: Error | null, result: boolean) => void): void; +} + +declare let overloadInterface: OverloadUnion; +declare let overloadInline: + | ((arg: string) => Promise) + | ((arg: string, callback: (error: Error | null, result: boolean) => void) => void) + +export class C { + classMethodInterface(...args: Parameters) {} + classMethodInline(...args: Parameters) {} + + classFieldFunctionInterface = function (...args: Parameters) {} + classFieldFunctionInline = function (...args: Parameters) {} + + classFieldArrowInterface = (...args: Parameters) => {} + classFieldArrowInline = (...args: Parameters) => {} +} + +export function FunctionInterface(...args: Parameters) {} +export function FunctionInline(...args: Parameters) {} +export const FunctionAssignInterface = function (...args: Parameters) {} +export const FunctionAssignInline = function (...args: Parameters) {} +export const ArrowInterface = (...args: Parameters) => {} +export const ArrowInline = (...args: Parameters) => {} + +//// [parametersAliasOverTypeofPreservedAsIsInDeclarations.js] +export class C { + classMethodInterface(...args) { } + classMethodInline(...args) { } + classFieldFunctionInterface = function (...args) { }; + classFieldFunctionInline = function (...args) { }; + classFieldArrowInterface = (...args) => { }; + classFieldArrowInline = (...args) => { }; +} +export function FunctionInterface(...args) { } +export function FunctionInline(...args) { } +export const FunctionAssignInterface = function (...args) { }; +export const FunctionAssignInline = function (...args) { }; +export const ArrowInterface = (...args) => { }; +export const ArrowInline = (...args) => { }; + + +//// [parametersAliasOverTypeofPreservedAsIsInDeclarations.d.ts] +interface OverloadUnion { + (arg: string): Promise; + (arg: string, callback: (error: Error | null, result: boolean) => void): void; +} +declare let overloadInterface: OverloadUnion; +declare let overloadInline: ((arg: string) => Promise) | ((arg: string, callback: (error: Error | null, result: boolean) => void) => void); +export declare class C { + classMethodInterface(...args: Parameters): void; + classMethodInline(...args: Parameters): void; + classFieldFunctionInterface: (...args: Parameters) => void; + classFieldFunctionInline: (...args: Parameters) => void; + classFieldArrowInterface: (...args: Parameters) => void; + classFieldArrowInline: (...args: Parameters) => void; +} +export declare function FunctionInterface(...args: Parameters): void; +export declare function FunctionInline(...args: Parameters): void; +export declare const FunctionAssignInterface: (...args: Parameters) => void; +export declare const FunctionAssignInline: (...args: Parameters) => void; +export declare const ArrowInterface: (...args: Parameters) => void; +export declare const ArrowInline: (...args: Parameters) => void; +export {}; diff --git a/testdata/baselines/reference/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.symbols b/testdata/baselines/reference/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.symbols new file mode 100644 index 00000000000..146c74a5d60 --- /dev/null +++ b/testdata/baselines/reference/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.symbols @@ -0,0 +1,112 @@ +//// [tests/cases/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.ts] //// + +=== parametersAliasOverTypeofPreservedAsIsInDeclarations.ts === +interface OverloadUnion { +>OverloadUnion : Symbol(OverloadUnion, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 0, 0)) + + (arg: string): Promise; +>arg : Symbol(arg, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 1, 5)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --)) + + (arg: string, callback: (error: Error | null, result: boolean) => void): void; +>arg : Symbol(arg, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 2, 5)) +>callback : Symbol(callback, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 2, 17)) +>error : Symbol(error, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 2, 29)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --)) +>result : Symbol(result, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 2, 49)) +} + +declare let overloadInterface: OverloadUnion; +>overloadInterface : Symbol(overloadInterface, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 5, 11)) +>OverloadUnion : Symbol(OverloadUnion, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 0, 0)) + +declare let overloadInline: +>overloadInline : Symbol(overloadInline, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 6, 11)) + + | ((arg: string) => Promise) +>arg : Symbol(arg, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 7, 8)) +>Promise : Symbol(Promise, Decl(lib.es5.d.ts, --, --), Decl(lib.es2015.iterable.d.ts, --, --), Decl(lib.es2015.promise.d.ts, --, --), Decl(lib.es2015.symbol.wellknown.d.ts, --, --), Decl(lib.es2018.promise.d.ts, --, --)) + + | ((arg: string, callback: (error: Error | null, result: boolean) => void) => void) +>arg : Symbol(arg, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 8, 8)) +>callback : Symbol(callback, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 8, 20)) +>error : Symbol(error, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 8, 32)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --), Decl(lib.es2022.error.d.ts, --, --)) +>result : Symbol(result, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 8, 52)) + +export class C { +>C : Symbol(C, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 8, 87)) + + classMethodInterface(...args: Parameters) {} +>classMethodInterface : Symbol(C.classMethodInterface, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 10, 16)) +>args : Symbol(args, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 11, 25)) +>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --)) +>overloadInterface : Symbol(overloadInterface, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 5, 11)) + + classMethodInline(...args: Parameters) {} +>classMethodInline : Symbol(C.classMethodInline, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 11, 74)) +>args : Symbol(args, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 12, 22)) +>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --)) +>overloadInline : Symbol(overloadInline, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 6, 11)) + + classFieldFunctionInterface = function (...args: Parameters) {} +>classFieldFunctionInterface : Symbol(C.classFieldFunctionInterface, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 12, 68)) +>args : Symbol(args, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 14, 44)) +>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --)) +>overloadInterface : Symbol(overloadInterface, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 5, 11)) + + classFieldFunctionInline = function (...args: Parameters) {} +>classFieldFunctionInline : Symbol(C.classFieldFunctionInline, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 14, 93)) +>args : Symbol(args, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 15, 41)) +>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --)) +>overloadInline : Symbol(overloadInline, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 6, 11)) + + classFieldArrowInterface = (...args: Parameters) => {} +>classFieldArrowInterface : Symbol(C.classFieldArrowInterface, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 15, 87)) +>args : Symbol(args, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 17, 32)) +>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --)) +>overloadInterface : Symbol(overloadInterface, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 5, 11)) + + classFieldArrowInline = (...args: Parameters) => {} +>classFieldArrowInline : Symbol(C.classFieldArrowInline, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 17, 84)) +>args : Symbol(args, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 18, 29)) +>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --)) +>overloadInline : Symbol(overloadInline, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 6, 11)) +} + +export function FunctionInterface(...args: Parameters) {} +>FunctionInterface : Symbol(FunctionInterface, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 19, 1)) +>args : Symbol(args, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 21, 34)) +>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --)) +>overloadInterface : Symbol(overloadInterface, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 5, 11)) + +export function FunctionInline(...args: Parameters) {} +>FunctionInline : Symbol(FunctionInline, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 21, 83)) +>args : Symbol(args, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 22, 31)) +>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --)) +>overloadInline : Symbol(overloadInline, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 6, 11)) + +export const FunctionAssignInterface = function (...args: Parameters) {} +>FunctionAssignInterface : Symbol(FunctionAssignInterface, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 23, 12)) +>args : Symbol(args, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 23, 49)) +>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --)) +>overloadInterface : Symbol(overloadInterface, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 5, 11)) + +export const FunctionAssignInline = function (...args: Parameters) {} +>FunctionAssignInline : Symbol(FunctionAssignInline, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 24, 12)) +>args : Symbol(args, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 24, 46)) +>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --)) +>overloadInline : Symbol(overloadInline, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 6, 11)) + +export const ArrowInterface = (...args: Parameters) => {} +>ArrowInterface : Symbol(ArrowInterface, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 25, 12)) +>args : Symbol(args, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 25, 31)) +>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --)) +>overloadInterface : Symbol(overloadInterface, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 5, 11)) + +export const ArrowInline = (...args: Parameters) => {} +>ArrowInline : Symbol(ArrowInline, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 26, 12)) +>args : Symbol(args, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 26, 28)) +>Parameters : Symbol(Parameters, Decl(lib.es5.d.ts, --, --)) +>overloadInline : Symbol(overloadInline, Decl(parametersAliasOverTypeofPreservedAsIsInDeclarations.ts, 6, 11)) + diff --git a/testdata/baselines/reference/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.types b/testdata/baselines/reference/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.types new file mode 100644 index 00000000000..7b117ca1160 --- /dev/null +++ b/testdata/baselines/reference/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.types @@ -0,0 +1,101 @@ +//// [tests/cases/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.ts] //// + +=== parametersAliasOverTypeofPreservedAsIsInDeclarations.ts === +interface OverloadUnion { + (arg: string): Promise; +>arg : string + + (arg: string, callback: (error: Error | null, result: boolean) => void): void; +>arg : string +>callback : (error: Error | null, result: boolean) => void +>error : Error | null +>result : boolean +} + +declare let overloadInterface: OverloadUnion; +>overloadInterface : OverloadUnion + +declare let overloadInline: +>overloadInline : ((arg: string) => Promise) | ((arg: string, callback: (error: Error | null, result: boolean) => void) => void) + + | ((arg: string) => Promise) +>arg : string + + | ((arg: string, callback: (error: Error | null, result: boolean) => void) => void) +>arg : string +>callback : (error: Error | null, result: boolean) => void +>error : Error | null +>result : boolean + +export class C { +>C : C + + classMethodInterface(...args: Parameters) {} +>classMethodInterface : (arg: string, callback: (error: Error | null, result: boolean) => void) => void +>args : [arg: string, callback: (error: Error | null, result: boolean) => void] +>overloadInterface : OverloadUnion + + classMethodInline(...args: Parameters) {} +>classMethodInline : (...args: Parameters) => void +>args : [arg: string] | [arg: string, callback: (error: Error | null, result: boolean) => void] +>overloadInline : ((arg: string) => Promise) | ((arg: string, callback: (error: Error | null, result: boolean) => void) => void) + + classFieldFunctionInterface = function (...args: Parameters) {} +>classFieldFunctionInterface : (arg: string, callback: (error: Error | null, result: boolean) => void) => void +>function (...args: Parameters) {} : (arg: string, callback: (error: Error | null, result: boolean) => void) => void +>args : [arg: string, callback: (error: Error | null, result: boolean) => void] +>overloadInterface : OverloadUnion + + classFieldFunctionInline = function (...args: Parameters) {} +>classFieldFunctionInline : (...args: Parameters) => void +>function (...args: Parameters) {} : (...args: Parameters) => void +>args : [arg: string] | [arg: string, callback: (error: Error | null, result: boolean) => void] +>overloadInline : ((arg: string) => Promise) | ((arg: string, callback: (error: Error | null, result: boolean) => void) => void) + + classFieldArrowInterface = (...args: Parameters) => {} +>classFieldArrowInterface : (arg: string, callback: (error: Error | null, result: boolean) => void) => void +>(...args: Parameters) => {} : (arg: string, callback: (error: Error | null, result: boolean) => void) => void +>args : [arg: string, callback: (error: Error | null, result: boolean) => void] +>overloadInterface : OverloadUnion + + classFieldArrowInline = (...args: Parameters) => {} +>classFieldArrowInline : (...args: Parameters) => void +>(...args: Parameters) => {} : (...args: Parameters) => void +>args : [arg: string] | [arg: string, callback: (error: Error | null, result: boolean) => void] +>overloadInline : ((arg: string) => Promise) | ((arg: string, callback: (error: Error | null, result: boolean) => void) => void) +} + +export function FunctionInterface(...args: Parameters) {} +>FunctionInterface : (arg: string, callback: (error: Error | null, result: boolean) => void) => void +>args : [arg: string, callback: (error: Error | null, result: boolean) => void] +>overloadInterface : OverloadUnion + +export function FunctionInline(...args: Parameters) {} +>FunctionInline : (...args: Parameters) => void +>args : [arg: string] | [arg: string, callback: (error: Error | null, result: boolean) => void] +>overloadInline : ((arg: string) => Promise) | ((arg: string, callback: (error: Error | null, result: boolean) => void) => void) + +export const FunctionAssignInterface = function (...args: Parameters) {} +>FunctionAssignInterface : (arg: string, callback: (error: Error | null, result: boolean) => void) => void +>function (...args: Parameters) {} : (arg: string, callback: (error: Error | null, result: boolean) => void) => void +>args : [arg: string, callback: (error: Error | null, result: boolean) => void] +>overloadInterface : OverloadUnion + +export const FunctionAssignInline = function (...args: Parameters) {} +>FunctionAssignInline : (...args: Parameters) => void +>function (...args: Parameters) {} : (...args: Parameters) => void +>args : [arg: string] | [arg: string, callback: (error: Error | null, result: boolean) => void] +>overloadInline : ((arg: string) => Promise) | ((arg: string, callback: (error: Error | null, result: boolean) => void) => void) + +export const ArrowInterface = (...args: Parameters) => {} +>ArrowInterface : (arg: string, callback: (error: Error | null, result: boolean) => void) => void +>(...args: Parameters) => {} : (arg: string, callback: (error: Error | null, result: boolean) => void) => void +>args : [arg: string, callback: (error: Error | null, result: boolean) => void] +>overloadInterface : OverloadUnion + +export const ArrowInline = (...args: Parameters) => {} +>ArrowInline : (...args: Parameters) => void +>(...args: Parameters) => {} : (...args: Parameters) => void +>args : [arg: string] | [arg: string, callback: (error: Error | null, result: boolean) => void] +>overloadInline : ((arg: string) => Promise) | ((arg: string, callback: (error: Error | null, result: boolean) => void) => void) + diff --git a/testdata/baselines/reference/fourslash/findRenameLocations/renameNamedImportDefaultInNodeModules.baseline.jsonc b/testdata/baselines/reference/fourslash/findRenameLocations/renameNamedImportDefaultInNodeModules.baseline.jsonc new file mode 100644 index 00000000000..820d690ead8 --- /dev/null +++ b/testdata/baselines/reference/fourslash/findRenameLocations/renameNamedImportDefaultInNodeModules.baseline.jsonc @@ -0,0 +1,13 @@ +// === findRenameLocations === +// === /index.ts === +// import { /*START PREFIX*/Foo as /*RENAME*/[|FooRENAME|] } from "foo"; +// declare const f: [|FooRENAME|]; + + + +// === findRenameLocations === +// @useAliasesForRename: true + +// === /index.ts === +// import { /*START PREFIX*/Foo as /*RENAME*/[|FooRENAME|] } from "foo"; +// declare const f: [|FooRENAME|]; \ No newline at end of file diff --git a/testdata/baselines/reference/fourslash/findRenameLocations/renameNamedImportUseAliasesForRenames.baseline.jsonc b/testdata/baselines/reference/fourslash/findRenameLocations/renameNamedImportUseAliasesForRenames.baseline.jsonc new file mode 100644 index 00000000000..76b66edf0ad --- /dev/null +++ b/testdata/baselines/reference/fourslash/findRenameLocations/renameNamedImportUseAliasesForRenames.baseline.jsonc @@ -0,0 +1,20 @@ +// === findRenameLocations === +// @useAliasesForRename: false + +// === /a.ts === +// import { /*RENAME*/[|MyTypeARENAME|] } from "./b"; +// const type: [|MyTypeARENAME|] = { foo: "bar" }; + +// === /b.ts === +// export interface [|MyTypeARENAME|] { +// foo: string; +// } + + + +// === findRenameLocations === +// @useAliasesForRename: true + +// === /a.ts === +// import { /*START PREFIX*/MyTypeA as /*RENAME*/[|MyTypeARENAME|] } from "./b"; +// const type: [|MyTypeARENAME|] = { foo: "bar" }; \ No newline at end of file diff --git a/testdata/baselines/reference/fourslash/signatureHelp/signatureHelpAnonymousType.baseline b/testdata/baselines/reference/fourslash/signatureHelp/signatureHelpAnonymousType.baseline index 51629360126..a43433b9038 100644 --- a/testdata/baselines/reference/fourslash/signatureHelp/signatureHelpAnonymousType.baseline +++ b/testdata/baselines/reference/fourslash/signatureHelp/signatureHelpAnonymousType.baseline @@ -5,7 +5,7 @@ // comparers.push((a, b) => true); // ^ // | ---------------------------------------------------------------------- -// | þtype(a: any, **b: any**): boolean +// | (a: any, **b: any**): boolean // | ---------------------------------------------------------------------- [ { @@ -21,7 +21,7 @@ "item": { "signatures": [ { - "label": "�type(a: any, b: any): boolean", + "label": "(a: any, b: any): boolean", "parameters": [ { "label": "a: any" diff --git a/testdata/baselines/reference/fourslash/signatureHelp/signatureHelpAnonymousTypeVS.baseline b/testdata/baselines/reference/fourslash/signatureHelp/signatureHelpAnonymousTypeVS.baseline index fbd3d784449..3f6af1e3e73 100644 --- a/testdata/baselines/reference/fourslash/signatureHelp/signatureHelpAnonymousTypeVS.baseline +++ b/testdata/baselines/reference/fourslash/signatureHelp/signatureHelpAnonymousTypeVS.baseline @@ -5,7 +5,7 @@ // comparers.push((a, b) => true); // ^ // | ---------------------------------------------------------------------- -// | þtype(a: any, **b: any**): boolean +// | (a: any, **b: any**): boolean // | ---------------------------------------------------------------------- [ { @@ -21,7 +21,7 @@ "item": { "signatures": [ { - "label": "�type(a: any, b: any): boolean", + "label": "(a: any, b: any): boolean", "parameters": [ { "label": "a: any" @@ -33,11 +33,6 @@ "activeParameter": 1, "_vs_colorizedLabel": { "Runs": [ - { - "ClassificationTypeName": "text", - "Text": "�type", - "_vs_type": "ClassifiedTextRun" - }, { "ClassificationTypeName": "punctuation", "Text": "(", diff --git a/testdata/baselines/reference/fourslash/state/codeLensAcrossProjects.baseline b/testdata/baselines/reference/fourslash/state/codeLensAcrossProjects.baseline index 529c89ae2cc..798f11f5608 100644 --- a/testdata/baselines/reference/fourslash/state/codeLensAcrossProjects.baseline +++ b/testdata/baselines/reference/fourslash/state/codeLensAcrossProjects.baseline @@ -162,45 +162,24 @@ Config File Names:: "params": { "settings": { "js/ts": { - "format": { - "baseIndentSize": 0, - "indentSize": 0, - "indentStyle": 0, - "newLineCharacter": "", - "semicolons": "", - "tabSize": 0 - }, "implementationsCodeLens": { "enabled": true, "showOnAllClassMethods": true, "showOnInterfaceMethods": true }, - "inlayHints": { - "parameterNames": { - "enabled": "" - } - }, - "native-preview": { - "customConfigFileName": "" - }, "preferences": { - "importModuleSpecifier": "", - "importModuleSpecifierEnding": "", - "jsxAttributeCompletionStyle": "", "organizeImports": { "caseFirst": "default", - "locale": "", + "sort": "auto", "typeOrder": "auto", "unicodeCollation": "ordinal" - }, - "quoteStyle": "" + } }, "referencesCodeLens": { "enabled": true, "showOnAllFunctions": true }, "unstable": { - "maximumHoverLength": 0, "preferGoToSourceDefinition": false } } @@ -603,7 +582,6 @@ Config:: "settings": { "js/ts": { "format": { - "baseIndentSize": 0, "convertTabsToSpaces": true, "indentSize": 4, "indentStyle": 2, @@ -627,26 +605,15 @@ Config:: "tabSize": 4, "trimTrailingWhitespace": true }, - "inlayHints": { - "parameterNames": { - "enabled": "" - } - }, - "native-preview": { - "customConfigFileName": "" - }, "preferences": { - "importModuleSpecifier": "", - "importModuleSpecifierEnding": "", - "jsxAttributeCompletionStyle": "", "organizeImports": { "caseFirst": "default", - "locale": "", + "sort": "auto", "typeOrder": "auto", "unicodeCollation": "ordinal" - }, - "quoteStyle": "" + } }, + "reportStyleChecksAsWarnings": true, "suggest": { "autoImports": true, "includeCompletionsForImportStatements": true @@ -655,10 +622,8 @@ Config:: "allowRenameOfImportPath": true, "disableLineTextInReferences": true, "displayPartsForJSDoc": true, - "maximumHoverLength": 0, "preferGoToSourceDefinition": false, - "provideRefactorNotApplicableReason": true, - "reportStyleChecksAsWarnings": true + "provideRefactorNotApplicableReason": true }, "workspaceSymbols": { "excludeLibrarySymbols": true diff --git a/testdata/baselines/reference/submodule/compiler/declarationsWithRecursiveInternalTypesProduceUniqueTypeParams.types b/testdata/baselines/reference/submodule/compiler/declarationsWithRecursiveInternalTypesProduceUniqueTypeParams.types index ea045319373..cb976db5fba 100644 --- a/testdata/baselines/reference/submodule/compiler/declarationsWithRecursiveInternalTypesProduceUniqueTypeParams.types +++ b/testdata/baselines/reference/submodule/compiler/declarationsWithRecursiveInternalTypesProduceUniqueTypeParams.types @@ -17,8 +17,8 @@ export const updateIfChanged = (t: T) => { >t : T const reduce = (u: U, update: (u: U) => T) => { ->reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => (>>>>(key: K_2) => (>>>>>>>>(key: K_3) => (>>>>>>>>>>>>>>>>(key: K_4) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_5) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_6) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_7) => (>(key: K_8) => any & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>>>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } ->(u: U, update: (u: U) => T) => { const set = (newU: U) => Object.is(u, newU) ? t : update(newU); return Object.assign( >(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }), { map: (updater: (u: U) => U) => set(updater(u)), set }); } : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => (>>>>(key: K_2) => (>>>>>>>>(key: K_3) => (>>>>>>>>>>>>>>>>(key: K_4) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_5) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_6) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_7) => (>(key: K_8) => any & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>>>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } +>reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => any & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } +>(u: U, update: (u: U) => T) => { const set = (newU: U) => Object.is(u, newU) ? t : update(newU); return Object.assign( >(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }), { map: (updater: (u: U) => U) => set(updater(u)), set }); } : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => any & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } >u : U >update : (u: U) => T >u : U @@ -40,18 +40,18 @@ export const updateIfChanged = (t: T) => { >newU : U return Object.assign( ->Object.assign( >(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }), { map: (updater: (u: U) => U) => set(updater(u)), set }) : (>(key: K) => (>>(key: K_1) => (>>>>(key: K_2) => (>>>>>>>>(key: K_3) => (>>>>>>>>>>>>>>>>(key: K_4) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_5) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_6) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_7) => (>(key: K_8) => any & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>>>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } +>Object.assign( >(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }), { map: (updater: (u: U) => U) => set(updater(u)), set }) : (>(key: K) => (>>(key: K_1) => any & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } >Object.assign : { (target: T_1, source: U_1): T_1 & U_1; (target: T_1, source1: U_1, source2: V): T_1 & U_1 & V; (target: T_1, source1: U_1, source2: V, source3: W): T_1 & U_1 & V & W; (target: object, ...sources: any[]): any; } >Object : ObjectConstructor >assign : { (target: T_1, source: U_1): T_1 & U_1; (target: T_1, source1: U_1, source2: V): T_1 & U_1 & V; (target: T_1, source1: U_1, source2: V, source3: W): T_1 & U_1 & V & W; (target: object, ...sources: any[]): any; } >(key: K) => ->>(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }) : >(key: K) => (>>(key: K_1) => (>>>>(key: K_2) => (>>>>>>>>(key: K_3) => (>>>>>>>>>>>>>>>>(key: K_4) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_5) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_6) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_7) => (>(key: K_8) => any & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>>>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; } +>>(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }) : >(key: K) => (>>(key: K_1) => any & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; } >key : K reduce>(u[key as keyof U] as Value, (v: Value) => { >reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }) : (>>(key: K) => (>>>>(key: K_2) => (>>>>>>>>(key: K_3) => (>>>>>>>>>>>>>>>>(key: K_4) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_5) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_6) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_7) => (>(key: K_8) => any & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>>>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; } ->reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => (>>>>(key: K_2) => (>>>>>>>>(key: K_3) => (>>>>>>>>>>>>>>>>(key: K_4) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_5) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_6) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_7) => (>(key: K_8) => any & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>>>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } +>reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => any & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } >u[key as keyof U] as Value : Value >u[key as keyof U] : U[keyof U] >u : U @@ -98,7 +98,7 @@ export const updateIfChanged = (t: T) => { }; return reduce(t, (t: T) => t); >reduce(t, (t: T) => t) : (>(key: K) => (>>(key: K_1) => (>>>(key: K_2) => (>>>>(key: K_3) => (>>>>>(key: K_4) => (>>>>>>(key: K_5) => (>>>>>>>(key: K_6) => (>>>>>>>>(key: K_7) => (>>>>>>>>>(key: K_8) => (>>>>>>>>>>(key: K_9) => (>>>>>>>>>>>(key: K_10) => any & { map: (updater: (u: Value>>>>>>>>>>) => Value>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>) => Value>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>) => Value>>>>>>>>) => T; set: (newU: Value>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>) => Value>>>>>>>) => T; set: (newU: Value>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>) => Value>>>>>) => T; set: (newU: Value>>>>>) => T; }) & { map: (updater: (u: Value>>>>) => Value>>>>) => T; set: (newU: Value>>>>) => T; }) & { map: (updater: (u: Value>>>) => Value>>>) => T; set: (newU: Value>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value>) => Value>) => T; set: (newU: Value>) => T; }) & { map: (updater: (u: Value) => Value) => T; set: (newU: Value) => T; }) & { map: (updater: (u: T) => T) => T; set: (newU: T) => T; } ->reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => (>>>>(key: K_2) => (>>>>>>>>(key: K_3) => (>>>>>>>>>>>>>>>>(key: K_4) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_5) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_6) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_7) => (>(key: K_8) => any & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>>>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } +>reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => any & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } >t : T >(t: T) => t : (t: T) => T >t : T diff --git a/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional(strict=false).symbols b/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional(strict=false).symbols index 9ccdaf645a3..9182dec2bc4 100644 --- a/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional(strict=false).symbols +++ b/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional(strict=false).symbols @@ -107,14 +107,14 @@ delete f.j >f : Symbol(f, Decl(deleteExpressionMustBeOptional.ts, 20, 13)) delete a.a ->a.a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) +>a.a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) >a : Symbol(a, Decl(deleteExpressionMustBeOptional.ts, 21, 13)) ->a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) +>a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) delete a.b ->a.b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) +>a.b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) >a : Symbol(a, Decl(deleteExpressionMustBeOptional.ts, 21, 13)) ->b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) +>b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) delete b.a >b : Symbol(b, Decl(deleteExpressionMustBeOptional.ts, 22, 13)) diff --git a/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional(strict=true).symbols b/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional(strict=true).symbols index 9ccdaf645a3..9182dec2bc4 100644 --- a/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional(strict=true).symbols +++ b/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional(strict=true).symbols @@ -107,14 +107,14 @@ delete f.j >f : Symbol(f, Decl(deleteExpressionMustBeOptional.ts, 20, 13)) delete a.a ->a.a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) +>a.a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) >a : Symbol(a, Decl(deleteExpressionMustBeOptional.ts, 21, 13)) ->a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) +>a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) delete a.b ->a.b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) +>a.b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) >a : Symbol(a, Decl(deleteExpressionMustBeOptional.ts, 21, 13)) ->b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) +>b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) delete b.a >b : Symbol(b, Decl(deleteExpressionMustBeOptional.ts, 22, 13)) diff --git a/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=false).symbols b/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=false).symbols index 320c43add83..c02c33fc08d 100644 --- a/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=false).symbols +++ b/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=false).symbols @@ -160,14 +160,14 @@ delete g.j >g : Symbol(g, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 21, 13)) delete a.a ->a.a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) +>a.a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) >a : Symbol(a, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 22, 13)) ->a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) +>a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) delete a.b ->a.b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) +>a.b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) >a : Symbol(a, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 22, 13)) ->b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) +>b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) delete b.a >b : Symbol(b, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 23, 13)) diff --git a/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=true).symbols b/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=true).symbols index 320c43add83..c02c33fc08d 100644 --- a/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=true).symbols +++ b/testdata/baselines/reference/submodule/compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=true).symbols @@ -160,14 +160,14 @@ delete g.j >g : Symbol(g, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 21, 13)) delete a.a ->a.a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) +>a.a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) >a : Symbol(a, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 22, 13)) ->a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) +>a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) delete a.b ->a.b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) +>a.b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) >a : Symbol(a, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 22, 13)) ->b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) +>b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) delete b.a >b : Symbol(b, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 23, 13)) diff --git a/testdata/baselines/reference/submodule/compiler/infiniteConstraints.errors.txt b/testdata/baselines/reference/submodule/compiler/infiniteConstraints.errors.txt index fb0eb7c97fc..7dbe760461e 100644 --- a/testdata/baselines/reference/submodule/compiler/infiniteConstraints.errors.txt +++ b/testdata/baselines/reference/submodule/compiler/infiniteConstraints.errors.txt @@ -1,19 +1,13 @@ -infiniteConstraints.ts(3,37): error TS2321: Excessive stack depth comparing types '"val"' and 'keyof Extract], { val: string; }>'. -infiniteConstraints.ts(3,37): error TS2536: Type '"val"' cannot be used to index type 'Extract], { val: string; }>'. infiniteConstraints.ts(4,37): error TS2536: Type '"val"' cannot be used to index type 'B[Exclude]'. infiniteConstraints.ts(31,43): error TS2322: Type 'Value<"dup">' is not assignable to type 'never'. infiniteConstraints.ts(31,63): error TS2322: Type 'Value<"dup">' is not assignable to type 'never'. infiniteConstraints.ts(36,71): error TS2536: Type '"foo"' cannot be used to index type 'T[keyof T]'. -==== infiniteConstraints.ts (6 errors) ==== +==== infiniteConstraints.ts (4 errors) ==== // Both of the following types trigger the recursion limiter in getImmediateBaseConstraint type T1], { val: string }>["val"] }> = B; - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2321: Excessive stack depth comparing types '"val"' and 'keyof Extract], { val: string; }>'. - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS2536: Type '"val"' cannot be used to index type 'Extract], { val: string; }>'. type T2]["val"] }> = B; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !!! error TS2536: Type '"val"' cannot be used to index type 'B[Exclude]'. diff --git a/testdata/baselines/reference/submodule/compiler/infiniteConstraints.errors.txt.diff b/testdata/baselines/reference/submodule/compiler/infiniteConstraints.errors.txt.diff deleted file mode 100644 index 262b7d316aa..00000000000 --- a/testdata/baselines/reference/submodule/compiler/infiniteConstraints.errors.txt.diff +++ /dev/null @@ -1,23 +0,0 @@ ---- old.infiniteConstraints.errors.txt -+++ new.infiniteConstraints.errors.txt -@@= skipped -0, +0 lines =@@ -+infiniteConstraints.ts(3,37): error TS2321: Excessive stack depth comparing types '"val"' and 'keyof Extract], { val: string; }>'. -+infiniteConstraints.ts(3,37): error TS2536: Type '"val"' cannot be used to index type 'Extract], { val: string; }>'. - infiniteConstraints.ts(4,37): error TS2536: Type '"val"' cannot be used to index type 'B[Exclude]'. - infiniteConstraints.ts(31,43): error TS2322: Type 'Value<"dup">' is not assignable to type 'never'. - infiniteConstraints.ts(31,63): error TS2322: Type 'Value<"dup">' is not assignable to type 'never'. - infiniteConstraints.ts(36,71): error TS2536: Type '"foo"' cannot be used to index type 'T[keyof T]'. - - --==== infiniteConstraints.ts (4 errors) ==== -+==== infiniteConstraints.ts (6 errors) ==== - // Both of the following types trigger the recursion limiter in getImmediateBaseConstraint - - type T1], { val: string }>["val"] }> = B; -+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS2321: Excessive stack depth comparing types '"val"' and 'keyof Extract], { val: string; }>'. -+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS2536: Type '"val"' cannot be used to index type 'Extract], { val: string; }>'. - type T2]["val"] }> = B; - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - !!! error TS2536: Type '"val"' cannot be used to index type 'B[Exclude]'. \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/compiler/isolatedDeclarationErrorsReturnTypes.errors.txt b/testdata/baselines/reference/submodule/compiler/isolatedDeclarationErrorsReturnTypes.errors.txt index b9dfb496711..4981a650dbc 100644 --- a/testdata/baselines/reference/submodule/compiler/isolatedDeclarationErrorsReturnTypes.errors.txt +++ b/testdata/baselines/reference/submodule/compiler/isolatedDeclarationErrorsReturnTypes.errors.txt @@ -2,29 +2,17 @@ isolatedDeclarationErrorsReturnTypes.ts(13,45): error TS9007: Function must have isolatedDeclarationErrorsReturnTypes.ts(16,41): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(19,41): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(109,65): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(110,43): error TS9013: Expression type can't be inferred with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(112,61): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(113,39): error TS9013: Expression type can't be inferred with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(115,61): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(116,39): error TS9013: Expression type can't be inferred with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(119,83): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(120,66): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(122,79): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(123,62): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(125,79): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(126,62): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(129,62): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(130,45): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(132,58): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(133,41): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(135,58): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(136,41): error TS9013: Expression type can't be inferred with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(138,73): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(139,51): error TS9013: Expression type can't be inferred with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(141,69): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(142,47): error TS9013: Expression type can't be inferred with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(144,69): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(145,47): error TS9013: Expression type can't be inferred with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(151,38): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(152,21): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(153,57): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. @@ -41,25 +29,9 @@ isolatedDeclarationErrorsReturnTypes.ts(167,66): error TS9007: Function must hav isolatedDeclarationErrorsReturnTypes.ts(168,49): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(169,85): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. isolatedDeclarationErrorsReturnTypes.ts(170,68): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(173,44): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(174,27): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(175,63): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(176,46): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(178,57): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(179,40): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(180,76): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(181,59): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(184,35): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(185,18): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(186,54): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(187,37): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(189,48): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(190,31): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(191,67): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -isolatedDeclarationErrorsReturnTypes.ts(192,50): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -==== isolatedDeclarationErrorsReturnTypes.ts (59 errors) ==== +==== isolatedDeclarationErrorsReturnTypes.ts (31 errors) ==== // Function Variables export const fnExpressionConstVariable = function foo() { return 0;} export const fnArrowConstVariable = () => "S"; @@ -186,10 +158,6 @@ isolatedDeclarationErrorsReturnTypes.ts(192,50): error TS9013: Expression type c !!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:109:60: Add a type annotation to the parameter cb. !!! related TS9030 isolatedDeclarationErrorsReturnTypes.ts:109:65: Add a return type to the function expression. export const fnParamArrowConstVariable = (cb = () => 1) => "S"; - ~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:110:43: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:110:43: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. export let fnParamExpressionLetVariable = function foo(cb = function(){ }) { return 0;} ~~~~~~~~ @@ -197,10 +165,6 @@ isolatedDeclarationErrorsReturnTypes.ts(192,50): error TS9013: Expression type c !!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:112:56: Add a type annotation to the parameter cb. !!! related TS9030 isolatedDeclarationErrorsReturnTypes.ts:112:61: Add a return type to the function expression. export let fnParamArrowLetVariable = (cb = () => 1) => "S"; - ~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:113:39: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:113:39: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. export var fnParamExpressionVarVariable = function foo(cb = function(){ }) { return 0;} ~~~~~~~~ @@ -208,10 +172,6 @@ isolatedDeclarationErrorsReturnTypes.ts(192,50): error TS9013: Expression type c !!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:115:56: Add a type annotation to the parameter cb. !!! related TS9030 isolatedDeclarationErrorsReturnTypes.ts:115:61: Add a return type to the function expression. export var fnParamArrowVarVariable = (cb = () => 1) => "S"; - ~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:116:39: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:116:39: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. // In Function Variables - No annotations on parameter export const fnParamExpressionConstVariableOwnerHasReturnType = function foo(cb = function(){ }): number { return 0;} @@ -249,37 +209,13 @@ isolatedDeclarationErrorsReturnTypes.ts(192,50): error TS9013: Expression type c // No Errors export const fnParamExpressionConstVariableOk = function foo(cb = function(): void{ }): number { return 0;} - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:129:62: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:129:62: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. export const fnParamArrowConstVariableOk = (cb = function(): void{ }): string => "S"; - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:130:45: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:130:45: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. export let fnParamExpressionLetVariableOk = function foo(cb = function(): void{ }): number { return 0;} - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:132:58: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:132:58: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. export let fnParamArrowLetVariableOk = (cb = function(): void{ }): string => "S"; - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:133:41: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:133:41: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. export var fnParamExpressionVarVariableOk = function foo(cb = function(): void{ }): number { return 0;} - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:135:58: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:135:58: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. export var fnParamArrowVarVariableOk = (cb = function(): void{ }): string => "S"; - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:136:41: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:136:41: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. export const fnParamExpressionConstVariableInternal = function foo(cb = function(){ }) { return 0;} ~~~~~~~~ @@ -287,10 +223,6 @@ isolatedDeclarationErrorsReturnTypes.ts(192,50): error TS9013: Expression type c !!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:138:68: Add a type annotation to the parameter cb. !!! related TS9030 isolatedDeclarationErrorsReturnTypes.ts:138:73: Add a return type to the function expression. export const fnParamArrowConstVariableInternal = (cb = () => 1) => "S"; - ~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:139:51: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:139:51: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. export let fnParamExpressionLetVariableInternal = function foo(cb = function(){ }) { return 0;} ~~~~~~~~ @@ -298,10 +230,6 @@ isolatedDeclarationErrorsReturnTypes.ts(192,50): error TS9013: Expression type c !!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:141:64: Add a type annotation to the parameter cb. !!! related TS9030 isolatedDeclarationErrorsReturnTypes.ts:141:69: Add a return type to the function expression. export let fnParamArrowLetVariableInternal = (cb = () => 1) => "S"; - ~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:142:47: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:142:47: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. export var fnParamExpressionVarVariableInternal = function foo(cb = function(){ }) { return 0;} ~~~~~~~~ @@ -309,10 +237,6 @@ isolatedDeclarationErrorsReturnTypes.ts(192,50): error TS9013: Expression type c !!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:144:64: Add a type annotation to the parameter cb. !!! related TS9030 isolatedDeclarationErrorsReturnTypes.ts:144:69: Add a return type to the function expression. export var fnParamArrowVarVariableInternal = (cb = () => 1) => "S"; - ~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:145:47: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:145:47: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. // In Function Fields @@ -405,89 +329,25 @@ isolatedDeclarationErrorsReturnTypes.ts(192,50): error TS9013: Expression type c // Have annotation only on parameter fnExpressionOnlyOnParam = function foo(cb = function(): void { }) { return 0; } - ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:173:44: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:173:44: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. fnArrowOnlyOnParam = (cb = function(): void { }) => "S"; - ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:174:27: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:174:27: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. protected fnExpressionProtectedOnlyOnParam = function foo(cb = function(): void { }) { return 0; } - ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:175:63: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:175:63: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. protected fnArrowProtectedOnlyOnParam = (cb = function(): void { }) => "S"; - ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:176:46: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:176:46: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. static fnStaticExpressionOnlyOnParam = function foo(cb = function(): void{ }) { return 0; } - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:178:57: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:178:57: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. static fnStaticArrowOnlyOnParam = (cb = function(): void{ }) => "S"; - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:179:40: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:179:40: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. protected static fnStaticExpressionProtectedOnlyOnParam = function foo(cb = function(): void{ }) { return 0; } - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:180:76: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:180:76: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. protected static fnStaticArrowProtectedOnlyOnParam = (cb = function(): void{ }) => "S"; - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:181:59: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:181:59: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. // Have annotation, so ok fnExpressionOk = function foo(cb = function(): void { }): number { return 0; } - ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:184:35: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:184:35: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. fnArrowOK = (cb = function(): void { }): string => "S"; - ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:185:18: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:185:18: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. protected fnExpressionProtectedOk = function foo(cb = function(): void { }): number { return 0; } - ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:186:54: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:186:54: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. protected fnArrowProtectedOK = (cb = function(): void { }): string => "S"; - ~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:187:37: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:187:37: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. static fnStaticExpressionOk = function foo(cb = function(): void{ }): number { return 0; } - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:189:48: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:189:48: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. static fnStaticArrowOk = (cb = function(): void{ }): string => "S"; - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:190:31: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:190:31: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. protected static fnStaticExpressionProtectedOk = function foo(cb = function(): void{ }): number { return 0; } - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:191:67: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:191:67: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. protected static fnStaticArrowProtectedOk = (cb = function(): void{ }): string => "S"; - ~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:192:50: Add a type annotation to the parameter cb. -!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:192:50: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. // No Error, not in declarations diff --git a/testdata/baselines/reference/submodule/compiler/jsxChildrenGenericContextualTypes.symbols b/testdata/baselines/reference/submodule/compiler/jsxChildrenGenericContextualTypes.symbols index 153abdb03d7..51118d42e9f 100644 --- a/testdata/baselines/reference/submodule/compiler/jsxChildrenGenericContextualTypes.symbols +++ b/testdata/baselines/reference/submodule/compiler/jsxChildrenGenericContextualTypes.symbols @@ -34,8 +34,8 @@ const Elem = (p: { prop: T, children: (t: T) => T }) =>
; >t : Symbol(t, Decl(jsxChildrenGenericContextualTypes.tsx, 7, 50)) >T : Symbol(T, Decl(jsxChildrenGenericContextualTypes.tsx, 7, 14)) >T : Symbol(T, Decl(jsxChildrenGenericContextualTypes.tsx, 7, 14)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) Elem({prop: {a: "x"}, children: i => ({a: "z"})}); >Elem : Symbol(Elem, Decl(jsxChildrenGenericContextualTypes.tsx, 7, 5)) @@ -78,8 +78,8 @@ const ElemLit = (p: LitProps) =>
; >p : Symbol(p, Decl(jsxChildrenGenericContextualTypes.tsx, 13, 35)) >LitProps : Symbol(LitProps, Decl(jsxChildrenGenericContextualTypes.tsx, 10, 57)) >T : Symbol(T, Decl(jsxChildrenGenericContextualTypes.tsx, 13, 17)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) ElemLit({prop: "x", children: () => "x"}); >ElemLit : Symbol(ElemLit, Decl(jsxChildrenGenericContextualTypes.tsx, 13, 5)) diff --git a/testdata/baselines/reference/submodule/compiler/jsxChildrenGenericContextualTypes.symbols.diff b/testdata/baselines/reference/submodule/compiler/jsxChildrenGenericContextualTypes.symbols.diff deleted file mode 100644 index 5b210a01331..00000000000 --- a/testdata/baselines/reference/submodule/compiler/jsxChildrenGenericContextualTypes.symbols.diff +++ /dev/null @@ -1,24 +0,0 @@ ---- old.jsxChildrenGenericContextualTypes.symbols -+++ new.jsxChildrenGenericContextualTypes.symbols -@@= skipped -33, +33 lines =@@ - >t : Symbol(t, Decl(jsxChildrenGenericContextualTypes.tsx, 7, 50)) - >T : Symbol(T, Decl(jsxChildrenGenericContextualTypes.tsx, 7, 14)) - >T : Symbol(T, Decl(jsxChildrenGenericContextualTypes.tsx, 7, 14)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) - - Elem({prop: {a: "x"}, children: i => ({a: "z"})}); - >Elem : Symbol(Elem, Decl(jsxChildrenGenericContextualTypes.tsx, 7, 5)) -@@= skipped -44, +44 lines =@@ - >p : Symbol(p, Decl(jsxChildrenGenericContextualTypes.tsx, 13, 35)) - >LitProps : Symbol(LitProps, Decl(jsxChildrenGenericContextualTypes.tsx, 10, 57)) - >T : Symbol(T, Decl(jsxChildrenGenericContextualTypes.tsx, 13, 17)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(jsxChildrenGenericContextualTypes.tsx, 5, 40)) - - ElemLit({prop: "x", children: () => "x"}); - >ElemLit : Symbol(ElemLit, Decl(jsxChildrenGenericContextualTypes.tsx, 13, 5)) \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/compiler/jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.symbols b/testdata/baselines/reference/submodule/compiler/jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.symbols index b17b94e869c..3bd9c7deb0f 100644 --- a/testdata/baselines/reference/submodule/compiler/jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.symbols +++ b/testdata/baselines/reference/submodule/compiler/jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.symbols @@ -20,18 +20,18 @@ declare namespace JSX { } ; ->foobaz : Symbol(JSX.IntrinsicElements[__index], Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31)) +>foobaz : Symbol(JSX.IntrinsicElements.__index, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31)) >prop : Symbol(prop, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 9, 7)) ; ->foobaz : Symbol(JSX.IntrinsicElements[__index], Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31)) +>foobaz : Symbol(JSX.IntrinsicElements.__index, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31)) >prop : Symbol(prop, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 10, 7)) ; ->foobarbaz : Symbol(JSX.IntrinsicElements[__index], Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31), Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 4, 42)) +>foobarbaz : Symbol(JSX.IntrinsicElements.__index, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31), Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 4, 42)) >prop : Symbol(prop, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 12, 10)) ; ->foobarbaz : Symbol(JSX.IntrinsicElements[__index], Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31), Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 4, 42)) +>foobarbaz : Symbol(JSX.IntrinsicElements.__index, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31), Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 4, 42)) >prop : Symbol(prop, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 13, 10)) diff --git a/testdata/baselines/reference/submodule/compiler/jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.symbols.diff b/testdata/baselines/reference/submodule/compiler/jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.symbols.diff deleted file mode 100644 index 0ead9830a67..00000000000 --- a/testdata/baselines/reference/submodule/compiler/jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.symbols.diff +++ /dev/null @@ -1,24 +0,0 @@ ---- old.jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.symbols -+++ new.jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.symbols -@@= skipped -19, +19 lines =@@ - } - - ; -->foobaz : Symbol(JSX.IntrinsicElements.__index, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31)) -+>foobaz : Symbol(JSX.IntrinsicElements[__index], Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31)) - >prop : Symbol(prop, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 9, 7)) - - ; -->foobaz : Symbol(JSX.IntrinsicElements.__index, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31)) -+>foobaz : Symbol(JSX.IntrinsicElements[__index], Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31)) - >prop : Symbol(prop, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 10, 7)) - - ; -->foobarbaz : Symbol(JSX.IntrinsicElements.__index, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31), Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 4, 42)) -+>foobarbaz : Symbol(JSX.IntrinsicElements[__index], Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31), Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 4, 42)) - >prop : Symbol(prop, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 12, 10)) - - ; -->foobarbaz : Symbol(JSX.IntrinsicElements.__index, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31), Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 4, 42)) -+>foobarbaz : Symbol(JSX.IntrinsicElements[__index], Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 3, 31), Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 4, 42)) - >prop : Symbol(prop, Decl(jsxIntrinsicDeclaredUsingTemplateLiteralTypeSignatures.tsx, 13, 10)) diff --git a/testdata/baselines/reference/submodule/compiler/jsxNamespaceReexports.symbols b/testdata/baselines/reference/submodule/compiler/jsxNamespaceReexports.symbols index 209db1d8df2..427748a17d5 100644 --- a/testdata/baselines/reference/submodule/compiler/jsxNamespaceReexports.symbols +++ b/testdata/baselines/reference/submodule/compiler/jsxNamespaceReexports.symbols @@ -29,5 +29,5 @@ import * as MyLib from "./library"; const content = ; >content : Symbol(content, Decl(index.tsx, 2, 5)) ->my-element : Symbol(MyLib.JSX.IntrinsicElements[__index], Decl(library.ts, 3, 38)) +>my-element : Symbol(MyLib.JSX.IntrinsicElements.__index, Decl(library.ts, 3, 38)) diff --git a/testdata/baselines/reference/submodule/compiler/jsxNamespaceReexports.symbols.diff b/testdata/baselines/reference/submodule/compiler/jsxNamespaceReexports.symbols.diff deleted file mode 100644 index 384a9244720..00000000000 --- a/testdata/baselines/reference/submodule/compiler/jsxNamespaceReexports.symbols.diff +++ /dev/null @@ -1,8 +0,0 @@ ---- old.jsxNamespaceReexports.symbols -+++ new.jsxNamespaceReexports.symbols -@@= skipped -28, +28 lines =@@ - - const content = ; - >content : Symbol(content, Decl(index.tsx, 2, 5)) -->my-element : Symbol(MyLib.JSX.IntrinsicElements.__index, Decl(library.ts, 3, 38)) -+>my-element : Symbol(MyLib.JSX.IntrinsicElements[__index], Decl(library.ts, 3, 38)) diff --git a/testdata/baselines/reference/submodule/compiler/propertyAccessOfReadonlyIndexSignature.symbols b/testdata/baselines/reference/submodule/compiler/propertyAccessOfReadonlyIndexSignature.symbols index 3bd3449847f..0c5e0e1f584 100644 --- a/testdata/baselines/reference/submodule/compiler/propertyAccessOfReadonlyIndexSignature.symbols +++ b/testdata/baselines/reference/submodule/compiler/propertyAccessOfReadonlyIndexSignature.symbols @@ -13,7 +13,7 @@ declare var a: Test; >Test : Symbol(Test, Decl(propertyAccessOfReadonlyIndexSignature.ts, 0, 0)) a.foo = 'baz'; ->a.foo : Symbol(Test[__index], Decl(propertyAccessOfReadonlyIndexSignature.ts, 0, 16)) +>a.foo : Symbol(Test.__index, Decl(propertyAccessOfReadonlyIndexSignature.ts, 0, 16)) >a : Symbol(a, Decl(propertyAccessOfReadonlyIndexSignature.ts, 4, 11)) ->foo : Symbol(Test[__index], Decl(propertyAccessOfReadonlyIndexSignature.ts, 0, 16)) +>foo : Symbol(Test.__index, Decl(propertyAccessOfReadonlyIndexSignature.ts, 0, 16)) diff --git a/testdata/baselines/reference/submodule/compiler/propertyAccessOfReadonlyIndexSignature.symbols.diff b/testdata/baselines/reference/submodule/compiler/propertyAccessOfReadonlyIndexSignature.symbols.diff deleted file mode 100644 index 5dd96c80bb0..00000000000 --- a/testdata/baselines/reference/submodule/compiler/propertyAccessOfReadonlyIndexSignature.symbols.diff +++ /dev/null @@ -1,11 +0,0 @@ ---- old.propertyAccessOfReadonlyIndexSignature.symbols -+++ new.propertyAccessOfReadonlyIndexSignature.symbols -@@= skipped -12, +12 lines =@@ - >Test : Symbol(Test, Decl(propertyAccessOfReadonlyIndexSignature.ts, 0, 0)) - - a.foo = 'baz'; -->a.foo : Symbol(Test.__index, Decl(propertyAccessOfReadonlyIndexSignature.ts, 0, 16)) -+>a.foo : Symbol(Test[__index], Decl(propertyAccessOfReadonlyIndexSignature.ts, 0, 16)) - >a : Symbol(a, Decl(propertyAccessOfReadonlyIndexSignature.ts, 4, 11)) -->foo : Symbol(Test.__index, Decl(propertyAccessOfReadonlyIndexSignature.ts, 0, 16)) -+>foo : Symbol(Test[__index], Decl(propertyAccessOfReadonlyIndexSignature.ts, 0, 16)) diff --git a/testdata/baselines/reference/submodule/compiler/reactJsxReactResolvedNodeNext.symbols b/testdata/baselines/reference/submodule/compiler/reactJsxReactResolvedNodeNext.symbols index 5793e35f908..e2ddca8d016 100644 --- a/testdata/baselines/reference/submodule/compiler/reactJsxReactResolvedNodeNext.symbols +++ b/testdata/baselines/reference/submodule/compiler/reactJsxReactResolvedNodeNext.symbols @@ -3,8 +3,8 @@ === file.tsx === export const a =
; >a : Symbol(a, Decl(file.tsx, 0, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(index.d.ts, 1, 33)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(index.d.ts, 1, 33)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(index.d.ts, 1, 33)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(index.d.ts, 1, 33)) === node_modules/@types/react/index.d.ts === declare namespace JSX { diff --git a/testdata/baselines/reference/submodule/compiler/reactJsxReactResolvedNodeNext.symbols.diff b/testdata/baselines/reference/submodule/compiler/reactJsxReactResolvedNodeNext.symbols.diff deleted file mode 100644 index 6acbbb842b8..00000000000 --- a/testdata/baselines/reference/submodule/compiler/reactJsxReactResolvedNodeNext.symbols.diff +++ /dev/null @@ -1,13 +0,0 @@ ---- old.reactJsxReactResolvedNodeNext.symbols -+++ new.reactJsxReactResolvedNodeNext.symbols -@@= skipped -2, +2 lines =@@ - === file.tsx === - export const a =
; - >a : Symbol(a, Decl(file.tsx, 0, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(index.d.ts, 1, 33)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(index.d.ts, 1, 33)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(index.d.ts, 1, 33)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(index.d.ts, 1, 33)) - - === node_modules/@types/react/index.d.ts === - declare namespace JSX { \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/compiler/reactJsxReactResolvedNodeNextEsm.symbols b/testdata/baselines/reference/submodule/compiler/reactJsxReactResolvedNodeNextEsm.symbols index 16beb3eb88d..5c5343253c5 100644 --- a/testdata/baselines/reference/submodule/compiler/reactJsxReactResolvedNodeNextEsm.symbols +++ b/testdata/baselines/reference/submodule/compiler/reactJsxReactResolvedNodeNextEsm.symbols @@ -3,8 +3,8 @@ === file.tsx === export const a =
; >a : Symbol(a, Decl(file.tsx, 0, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(index.d.ts, 1, 33)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(index.d.ts, 1, 33)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(index.d.ts, 1, 33)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(index.d.ts, 1, 33)) === node_modules/@types/react/index.d.ts === declare namespace JSX { diff --git a/testdata/baselines/reference/submodule/compiler/reactJsxReactResolvedNodeNextEsm.symbols.diff b/testdata/baselines/reference/submodule/compiler/reactJsxReactResolvedNodeNextEsm.symbols.diff deleted file mode 100644 index 1397728d617..00000000000 --- a/testdata/baselines/reference/submodule/compiler/reactJsxReactResolvedNodeNextEsm.symbols.diff +++ /dev/null @@ -1,13 +0,0 @@ ---- old.reactJsxReactResolvedNodeNextEsm.symbols -+++ new.reactJsxReactResolvedNodeNextEsm.symbols -@@= skipped -2, +2 lines =@@ - === file.tsx === - export const a =
; - >a : Symbol(a, Decl(file.tsx, 0, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(index.d.ts, 1, 33)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(index.d.ts, 1, 33)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(index.d.ts, 1, 33)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(index.d.ts, 1, 33)) - - === node_modules/@types/react/index.d.ts === - declare namespace JSX { \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/assignmentCompatWithGenericCallSignatures2.errors.txt b/testdata/baselines/reference/submodule/conformance/assignmentCompatWithGenericCallSignatures2.errors.txt index 3ae018672d2..af48acb76b2 100644 --- a/testdata/baselines/reference/submodule/conformance/assignmentCompatWithGenericCallSignatures2.errors.txt +++ b/testdata/baselines/reference/submodule/conformance/assignmentCompatWithGenericCallSignatures2.errors.txt @@ -1,7 +1,6 @@ assignmentCompatWithGenericCallSignatures2.ts(15,1): error TS2322: Type 'B' is not assignable to type 'A'. - Types of parameters 'y' and 'y' are incompatible. - Type 'T[]' is not assignable to type 'T'. - 'T' could be instantiated with an arbitrary type which could be unrelated to 'T[]'. + Types of parameters 'x' and 'x' are incompatible. + Type 'T' is not assignable to type 'T[]'. assignmentCompatWithGenericCallSignatures2.ts(16,1): error TS2322: Type 'A' is not assignable to type 'B'. Types of parameters 'y' and 'y' are incompatible. Type 'S' is not assignable to type 'S[]'. @@ -25,9 +24,9 @@ assignmentCompatWithGenericCallSignatures2.ts(16,1): error TS2322: Type 'A' is n a = b; ~ !!! error TS2322: Type 'B' is not assignable to type 'A'. -!!! error TS2322: Types of parameters 'y' and 'y' are incompatible. -!!! error TS2322: Type 'T[]' is not assignable to type 'T'. -!!! error TS2322: 'T' could be instantiated with an arbitrary type which could be unrelated to 'T[]'. +!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. +!!! error TS2322: Type 'T' is not assignable to type 'T[]'. +!!! related TS2208 assignmentCompatWithGenericCallSignatures2.ts:4:6: This type parameter might need an `extends T[]` constraint. b = a; ~ !!! error TS2322: Type 'A' is not assignable to type 'B'. diff --git a/testdata/baselines/reference/submodule/conformance/assignmentCompatWithGenericCallSignatures2.errors.txt.diff b/testdata/baselines/reference/submodule/conformance/assignmentCompatWithGenericCallSignatures2.errors.txt.diff new file mode 100644 index 00000000000..934faa7d724 --- /dev/null +++ b/testdata/baselines/reference/submodule/conformance/assignmentCompatWithGenericCallSignatures2.errors.txt.diff @@ -0,0 +1,25 @@ +--- old.assignmentCompatWithGenericCallSignatures2.errors.txt ++++ new.assignmentCompatWithGenericCallSignatures2.errors.txt +@@= skipped -0, +0 lines =@@ + assignmentCompatWithGenericCallSignatures2.ts(15,1): error TS2322: Type 'B' is not assignable to type 'A'. +- Types of parameters 'y' and 'y' are incompatible. +- Type 'T[]' is not assignable to type 'T'. +- 'T' could be instantiated with an arbitrary type which could be unrelated to 'T[]'. ++ Types of parameters 'x' and 'x' are incompatible. ++ Type 'T' is not assignable to type 'T[]'. + assignmentCompatWithGenericCallSignatures2.ts(16,1): error TS2322: Type 'A' is not assignable to type 'B'. + Types of parameters 'y' and 'y' are incompatible. + Type 'S' is not assignable to type 'S[]'. +@@= skipped -24, +23 lines =@@ + a = b; + ~ + !!! error TS2322: Type 'B' is not assignable to type 'A'. +-!!! error TS2322: Types of parameters 'y' and 'y' are incompatible. +-!!! error TS2322: Type 'T[]' is not assignable to type 'T'. +-!!! error TS2322: 'T' could be instantiated with an arbitrary type which could be unrelated to 'T[]'. ++!!! error TS2322: Types of parameters 'x' and 'x' are incompatible. ++!!! error TS2322: Type 'T' is not assignable to type 'T[]'. ++!!! related TS2208 assignmentCompatWithGenericCallSignatures2.ts:4:6: This type parameter might need an `extends T[]` constraint. + b = a; + ~ + !!! error TS2322: Type 'A' is not assignable to type 'B'. \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/inlineJsxAndJsxFragPragma.symbols b/testdata/baselines/reference/submodule/conformance/inlineJsxAndJsxFragPragma.symbols index 127f1d62322..b73f57f3fc3 100644 --- a/testdata/baselines/reference/submodule/conformance/inlineJsxAndJsxFragPragma.symbols +++ b/testdata/baselines/reference/submodule/conformance/inlineJsxAndJsxFragPragma.symbols @@ -34,8 +34,8 @@ import {h, Fragment} from "./renderer"; >Fragment : Symbol(Fragment, Decl(preacty.tsx, 4, 10)) <>
->div : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) === snabbdomy.tsx === /* @jsx jsx */ @@ -44,8 +44,8 @@ import {jsx} from "./renderer"; >jsx : Symbol(jsx, Decl(snabbdomy.tsx, 2, 8)) <> ->span : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) === preacty-only-fragment.tsx === /** @@ -93,8 +93,8 @@ import {h, Fragment} from "./renderer"; >Fragment : Symbol(Fragment, Decl(preacty-no-fragment.tsx, 4, 10))
->div : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) === snabbdomy-no-fragment.tsx === /* @jsx jsx */ @@ -103,8 +103,8 @@ import {jsx} from "./renderer"; >jsx : Symbol(jsx, Decl(snabbdomy-no-fragment.tsx, 2, 8))
->div : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) === preacty-only-component.tsx === /** diff --git a/testdata/baselines/reference/submodule/conformance/inlineJsxAndJsxFragPragma.symbols.diff b/testdata/baselines/reference/submodule/conformance/inlineJsxAndJsxFragPragma.symbols.diff deleted file mode 100644 index 7ab6cd551f5..00000000000 --- a/testdata/baselines/reference/submodule/conformance/inlineJsxAndJsxFragPragma.symbols.diff +++ /dev/null @@ -1,46 +0,0 @@ ---- old.inlineJsxAndJsxFragPragma.symbols -+++ new.inlineJsxAndJsxFragPragma.symbols -@@= skipped -33, +33 lines =@@ - >Fragment : Symbol(Fragment, Decl(preacty.tsx, 4, 10)) - - <>
-->div : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - - === snabbdomy.tsx === - /* @jsx jsx */ -@@= skipped -10, +10 lines =@@ - >jsx : Symbol(jsx, Decl(snabbdomy.tsx, 2, 8)) - - <> -->span : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - - === preacty-only-fragment.tsx === - /** -@@= skipped -49, +49 lines =@@ - >Fragment : Symbol(Fragment, Decl(preacty-no-fragment.tsx, 4, 10)) - -
-->div : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - - === snabbdomy-no-fragment.tsx === - /* @jsx jsx */ -@@= skipped -10, +10 lines =@@ - >jsx : Symbol(jsx, Decl(snabbdomy-no-fragment.tsx, 2, 8)) - -
-->div : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - - === preacty-only-component.tsx === - /** \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/inlineJsxAndJsxFragPragmaOverridesCompilerOptions.symbols b/testdata/baselines/reference/submodule/conformance/inlineJsxAndJsxFragPragmaOverridesCompilerOptions.symbols index 29069fea7ec..6479cf0a5e5 100644 --- a/testdata/baselines/reference/submodule/conformance/inlineJsxAndJsxFragPragmaOverridesCompilerOptions.symbols +++ b/testdata/baselines/reference/submodule/conformance/inlineJsxAndJsxFragPragmaOverridesCompilerOptions.symbols @@ -38,8 +38,8 @@ import {createElement, Fragment} from "./react"; >Fragment : Symbol(Fragment, Decl(reacty.tsx, 0, 22)) <> ->span : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) === preacty.tsx === /** @@ -51,8 +51,8 @@ import {h, Frag} from "./preact"; >Frag : Symbol(Frag, Decl(preacty.tsx, 4, 10)) <>
->div : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) === snabbdomy.tsx === /** @@ -63,8 +63,8 @@ import {h} from "./snabbdom"; >h : Symbol(h, Decl(snabbdomy.tsx, 4, 8)) <>
->div : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) === mix-n-match.tsx === /* @jsx h */ @@ -76,6 +76,6 @@ import {Fragment} from "./react"; >Fragment : Symbol(Fragment, Decl(mix-n-match.tsx, 3, 8)) <> ->span : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) diff --git a/testdata/baselines/reference/submodule/conformance/inlineJsxAndJsxFragPragmaOverridesCompilerOptions.symbols.diff b/testdata/baselines/reference/submodule/conformance/inlineJsxAndJsxFragPragmaOverridesCompilerOptions.symbols.diff deleted file mode 100644 index 04a81ca43ab..00000000000 --- a/testdata/baselines/reference/submodule/conformance/inlineJsxAndJsxFragPragmaOverridesCompilerOptions.symbols.diff +++ /dev/null @@ -1,43 +0,0 @@ ---- old.inlineJsxAndJsxFragPragmaOverridesCompilerOptions.symbols -+++ new.inlineJsxAndJsxFragPragmaOverridesCompilerOptions.symbols -@@= skipped -37, +37 lines =@@ - >Fragment : Symbol(Fragment, Decl(reacty.tsx, 0, 22)) - - <> -->span : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) - - === preacty.tsx === - /** -@@= skipped -13, +13 lines =@@ - >Frag : Symbol(Frag, Decl(preacty.tsx, 4, 10)) - - <>
-->div : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) - - === snabbdomy.tsx === - /** -@@= skipped -12, +12 lines =@@ - >h : Symbol(h, Decl(snabbdomy.tsx, 4, 8)) - - <>
-->div : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) - - === mix-n-match.tsx === - /* @jsx h */ -@@= skipped -13, +13 lines =@@ - >Fragment : Symbol(Fragment, Decl(mix-n-match.tsx, 3, 8)) - - <> -->span : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(react.d.ts, 2, 37)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(react.d.ts, 2, 37)) diff --git a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryDeclarations.symbols b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryDeclarations.symbols index 5d9c0fb8d35..b852075f866 100644 --- a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryDeclarations.symbols +++ b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryDeclarations.symbols @@ -34,8 +34,8 @@ import * as React from "./renderer"; >React : Symbol(React, Decl(otherreacty.tsx, 1, 6)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) === other.tsx === /** @jsx h */ @@ -45,8 +45,8 @@ import { dom as h } from "./renderer" export const prerendered = ; >prerendered : Symbol(prerendered, Decl(other.tsx, 2, 12)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) === othernoalias.tsx === /** @jsx otherdom */ @@ -55,8 +55,8 @@ import { otherdom } from "./renderer" export const prerendered2 = ; >prerendered2 : Symbol(prerendered2, Decl(othernoalias.tsx, 2, 12)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) === reacty.tsx === import React from "./renderer" @@ -64,8 +64,8 @@ import React from "./renderer" export const prerendered3 = ; >prerendered3 : Symbol(prerendered3, Decl(reacty.tsx, 1, 12)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) === index.tsx === /** @jsx dom */ @@ -73,8 +73,8 @@ import { dom } from "./renderer" >dom : Symbol(dom, Decl(index.tsx, 1, 8)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) export * from "./other"; export * from "./othernoalias"; diff --git a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryDeclarations.symbols.diff b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryDeclarations.symbols.diff deleted file mode 100644 index a2bb362b9a0..00000000000 --- a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryDeclarations.symbols.diff +++ /dev/null @@ -1,57 +0,0 @@ ---- old.inlineJsxFactoryDeclarations.symbols -+++ new.inlineJsxFactoryDeclarations.symbols -@@= skipped -33, +33 lines =@@ - >React : Symbol(React, Decl(otherreacty.tsx, 1, 6)) - - -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - - === other.tsx === - /** @jsx h */ -@@= skipped -11, +11 lines =@@ - - export const prerendered = ; - >prerendered : Symbol(prerendered, Decl(other.tsx, 2, 12)) -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - - === othernoalias.tsx === - /** @jsx otherdom */ -@@= skipped -10, +10 lines =@@ - - export const prerendered2 = ; - >prerendered2 : Symbol(prerendered2, Decl(othernoalias.tsx, 2, 12)) -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - - === reacty.tsx === - import React from "./renderer" -@@= skipped -9, +9 lines =@@ - - export const prerendered3 = ; - >prerendered3 : Symbol(prerendered3, Decl(reacty.tsx, 1, 12)) -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - - === index.tsx === - /** @jsx dom */ -@@= skipped -9, +9 lines =@@ - >dom : Symbol(dom, Decl(index.tsx, 1, 8)) - - -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - - export * from "./other"; - export * from "./othernoalias"; \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryDeclarationsLocalTypes.symbols b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryDeclarationsLocalTypes.symbols index 63b1dd1dfe3..04dcfda28b1 100644 --- a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryDeclarationsLocalTypes.symbols +++ b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryDeclarationsLocalTypes.symbols @@ -116,7 +116,7 @@ export const MySFC = (props: {x: number, y: number, children?: predom.JSX.Elemen >predom : Symbol(predom, Decl(component.tsx, 1, 8)) >JSX : Symbol(predom.JSX, Decl(renderer2.d.ts, 0, 25)) >Element : Symbol(predom.JSX.Element, Decl(renderer2.d.ts, 4, 9)) ->p : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) +>p : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) >props.x : Symbol(x, Decl(component.tsx, 3, 30)) >props : Symbol(props, Decl(component.tsx, 3, 22)) >x : Symbol(x, Decl(component.tsx, 3, 30)) @@ -129,7 +129,7 @@ export const MySFC = (props: {x: number, y: number, children?: predom.JSX.Elemen >props.y : Symbol(y, Decl(component.tsx, 3, 40)) >props : Symbol(props, Decl(component.tsx, 3, 22)) >y : Symbol(y, Decl(component.tsx, 3, 40)) ->p : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) +>p : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) export class MyClass implements predom.JSX.Element { >MyClass : Symbol(MyClass, Decl(component.tsx, 3, 164)) @@ -155,7 +155,7 @@ export class MyClass implements predom.JSX.Element { >render : Symbol(MyClass.render, Decl(component.tsx, 7, 89)) return

->p : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) +>p : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) {this.props.x} + {this.props.y} = {this.props.x + this.props.y} >this.props.x : Symbol(x, Decl(component.tsx, 7, 31)) @@ -187,7 +187,7 @@ export class MyClass implements predom.JSX.Element { >children : Symbol(children, Decl(component.tsx, 7, 52))

; ->p : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) +>p : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) } } export const tree = @@ -204,8 +204,8 @@ export const tree = MySFC : Symbol(MySFC, Decl(component.tsx, 3, 12)) export default ->h : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) ->h : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) +>h : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) +>h : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) === index.tsx === /** @jsx dom */ @@ -224,8 +224,8 @@ let elem = prerendered; elem = ; // Expect assignability error here >elem : Symbol(elem, Decl(index.tsx, 3, 3)) ->h : Symbol(dom.JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->h : Symbol(dom.JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>h : Symbol(dom.JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>h : Symbol(dom.JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) const DOMSFC = (props: {x: number, y: number, children?: dom.JSX.Element[]}) =>

{props.x} + {props.y} = {props.x + props.y}{props.children}

; >DOMSFC : Symbol(DOMSFC, Decl(index.tsx, 6, 5)) @@ -236,7 +236,7 @@ const DOMSFC = (props: {x: number, y: number, children?: dom.JSX.Element[]}) => >dom : Symbol(dom, Decl(index.tsx, 1, 8)) >JSX : Symbol(dom.JSX, Decl(renderer.d.ts, 0, 22)) >Element : Symbol(dom.JSX.Element, Decl(renderer.d.ts, 4, 9)) ->p : Symbol(dom.JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>p : Symbol(dom.JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) >props.x : Symbol(x, Decl(index.tsx, 6, 24)) >props : Symbol(props, Decl(index.tsx, 6, 16)) >x : Symbol(x, Decl(index.tsx, 6, 24)) @@ -252,7 +252,7 @@ const DOMSFC = (props: {x: number, y: number, children?: dom.JSX.Element[]}) => >props.children : Symbol(children, Decl(index.tsx, 6, 45)) >props : Symbol(props, Decl(index.tsx, 6, 16)) >children : Symbol(children, Decl(index.tsx, 6, 45)) ->p : Symbol(dom.JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>p : Symbol(dom.JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) class DOMClass implements dom.JSX.Element { >DOMClass : Symbol(DOMClass, Decl(index.tsx, 6, 147)) @@ -278,7 +278,7 @@ class DOMClass implements dom.JSX.Element { >render : Symbol(DOMClass.render, Decl(index.tsx, 10, 86)) return

{this.props.x} + {this.props.y} = {this.props.x + this.props.y}{...this.props.children}

; ->p : Symbol(dom.JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>p : Symbol(dom.JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) >this.props.x : Symbol(x, Decl(index.tsx, 10, 31)) >this.props : Symbol(DOMClass.props, Decl(index.tsx, 10, 16)) >this : Symbol(DOMClass, Decl(index.tsx, 6, 147)) @@ -304,7 +304,7 @@ class DOMClass implements dom.JSX.Element { >this : Symbol(DOMClass, Decl(index.tsx, 6, 147)) >props : Symbol(DOMClass.props, Decl(index.tsx, 10, 16)) >children : Symbol(children, Decl(index.tsx, 10, 52)) ->p : Symbol(dom.JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>p : Symbol(dom.JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) } } diff --git a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryDeclarationsLocalTypes.symbols.diff b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryDeclarationsLocalTypes.symbols.diff deleted file mode 100644 index 58334ec4a9c..00000000000 --- a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryDeclarationsLocalTypes.symbols.diff +++ /dev/null @@ -1,112 +0,0 @@ ---- old.inlineJsxFactoryDeclarationsLocalTypes.symbols -+++ new.inlineJsxFactoryDeclarationsLocalTypes.symbols -@@= skipped -115, +115 lines =@@ - >predom : Symbol(predom, Decl(component.tsx, 1, 8)) - >JSX : Symbol(predom.JSX, Decl(renderer2.d.ts, 0, 25)) - >Element : Symbol(predom.JSX.Element, Decl(renderer2.d.ts, 4, 9)) -->p : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) -->props.x : Symbol(x, Decl(component.tsx, 3, 30)) -->props : Symbol(props, Decl(component.tsx, 3, 22)) -->x : Symbol(x, Decl(component.tsx, 3, 30)) -->props.y : Symbol(y, Decl(component.tsx, 3, 40)) -->props : Symbol(props, Decl(component.tsx, 3, 22)) -->y : Symbol(y, Decl(component.tsx, 3, 40)) -->props.x : Symbol(x, Decl(component.tsx, 3, 30)) -->props : Symbol(props, Decl(component.tsx, 3, 22)) -->x : Symbol(x, Decl(component.tsx, 3, 30)) -->props.y : Symbol(y, Decl(component.tsx, 3, 40)) -->props : Symbol(props, Decl(component.tsx, 3, 22)) -->y : Symbol(y, Decl(component.tsx, 3, 40)) -->p : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) -+>p : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) -+>props.x : Symbol(x, Decl(component.tsx, 3, 30)) -+>props : Symbol(props, Decl(component.tsx, 3, 22)) -+>x : Symbol(x, Decl(component.tsx, 3, 30)) -+>props.y : Symbol(y, Decl(component.tsx, 3, 40)) -+>props : Symbol(props, Decl(component.tsx, 3, 22)) -+>y : Symbol(y, Decl(component.tsx, 3, 40)) -+>props.x : Symbol(x, Decl(component.tsx, 3, 30)) -+>props : Symbol(props, Decl(component.tsx, 3, 22)) -+>x : Symbol(x, Decl(component.tsx, 3, 30)) -+>props.y : Symbol(y, Decl(component.tsx, 3, 40)) -+>props : Symbol(props, Decl(component.tsx, 3, 22)) -+>y : Symbol(y, Decl(component.tsx, 3, 40)) -+>p : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) - - export class MyClass implements predom.JSX.Element { - >MyClass : Symbol(MyClass, Decl(component.tsx, 3, 164)) -@@= skipped -39, +39 lines =@@ - >render : Symbol(MyClass.render, Decl(component.tsx, 7, 89)) - - return

-->p : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) -+>p : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) - - {this.props.x} + {this.props.y} = {this.props.x + this.props.y} - >this.props.x : Symbol(x, Decl(component.tsx, 7, 31)) -@@= skipped -32, +32 lines =@@ - >children : Symbol(children, Decl(component.tsx, 7, 52)) - -

; -->p : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) -+>p : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) - } - } - export const tree = -@@= skipped -17, +17 lines =@@ - >MySFC : Symbol(MySFC, Decl(component.tsx, 3, 12)) - - export default -->h : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) -->h : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) -+>h : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) -+>h : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) - - === index.tsx === - /** @jsx dom */ -@@= skipped -20, +20 lines =@@ - - elem = ; // Expect assignability error here - >elem : Symbol(elem, Decl(index.tsx, 3, 3)) -->h : Symbol(dom.JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->h : Symbol(dom.JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(dom.JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(dom.JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - - const DOMSFC = (props: {x: number, y: number, children?: dom.JSX.Element[]}) =>

{props.x} + {props.y} = {props.x + props.y}{props.children}

; - >DOMSFC : Symbol(DOMSFC, Decl(index.tsx, 6, 5)) -@@= skipped -12, +12 lines =@@ - >dom : Symbol(dom, Decl(index.tsx, 1, 8)) - >JSX : Symbol(dom.JSX, Decl(renderer.d.ts, 0, 22)) - >Element : Symbol(dom.JSX.Element, Decl(renderer.d.ts, 4, 9)) -->p : Symbol(dom.JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>p : Symbol(dom.JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - >props.x : Symbol(x, Decl(index.tsx, 6, 24)) - >props : Symbol(props, Decl(index.tsx, 6, 16)) - >x : Symbol(x, Decl(index.tsx, 6, 24)) -@@= skipped -16, +16 lines =@@ - >props.children : Symbol(children, Decl(index.tsx, 6, 45)) - >props : Symbol(props, Decl(index.tsx, 6, 16)) - >children : Symbol(children, Decl(index.tsx, 6, 45)) -->p : Symbol(dom.JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>p : Symbol(dom.JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - - class DOMClass implements dom.JSX.Element { - >DOMClass : Symbol(DOMClass, Decl(index.tsx, 6, 147)) -@@= skipped -26, +26 lines =@@ - >render : Symbol(DOMClass.render, Decl(index.tsx, 10, 86)) - - return

{this.props.x} + {this.props.y} = {this.props.x + this.props.y}{...this.props.children}

; -->p : Symbol(dom.JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>p : Symbol(dom.JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - >this.props.x : Symbol(x, Decl(index.tsx, 10, 31)) - >this.props : Symbol(DOMClass.props, Decl(index.tsx, 10, 16)) - >this : Symbol(DOMClass, Decl(index.tsx, 6, 147)) -@@= skipped -26, +26 lines =@@ - >this : Symbol(DOMClass, Decl(index.tsx, 6, 147)) - >props : Symbol(DOMClass.props, Decl(index.tsx, 10, 16)) - >children : Symbol(children, Decl(index.tsx, 10, 52)) -->p : Symbol(dom.JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>p : Symbol(dom.JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - } - } diff --git a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryLocalTypeGlobalFallback.symbols b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryLocalTypeGlobalFallback.symbols index 7376078367b..de66a23d491 100644 --- a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryLocalTypeGlobalFallback.symbols +++ b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryLocalTypeGlobalFallback.symbols @@ -87,8 +87,8 @@ import { predom } from "./renderer2" >predom : Symbol(predom, Decl(component.tsx, 1, 8)) export default ->h : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) ->h : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) +>h : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) +>h : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) === index.tsx === /** @jsx dom */ @@ -104,6 +104,6 @@ let elem = prerendered; elem = ; // Expect assignability error here >elem : Symbol(elem, Decl(index.tsx, 3, 3)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) diff --git a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryLocalTypeGlobalFallback.symbols.diff b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryLocalTypeGlobalFallback.symbols.diff deleted file mode 100644 index 7ffb9bdb787..00000000000 --- a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryLocalTypeGlobalFallback.symbols.diff +++ /dev/null @@ -1,21 +0,0 @@ ---- old.inlineJsxFactoryLocalTypeGlobalFallback.symbols -+++ new.inlineJsxFactoryLocalTypeGlobalFallback.symbols -@@= skipped -86, +86 lines =@@ - >predom : Symbol(predom, Decl(component.tsx, 1, 8)) - - export default -->h : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) -->h : Symbol(predom.JSX.IntrinsicElements.__index, Decl(renderer2.d.ts, 2, 37)) -+>h : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) -+>h : Symbol(predom.JSX.IntrinsicElements[__index], Decl(renderer2.d.ts, 2, 37)) - - === index.tsx === - /** @jsx dom */ -@@= skipped -17, +17 lines =@@ - - elem = ; // Expect assignability error here - >elem : Symbol(elem, Decl(index.tsx, 3, 3)) -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) diff --git a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryOverridesCompilerOption.symbols b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryOverridesCompilerOption.symbols index 1ca06d53a49..c55a654ee63 100644 --- a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryOverridesCompilerOption.symbols +++ b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryOverridesCompilerOption.symbols @@ -28,14 +28,14 @@ import {dom} from "./renderer"; >dom : Symbol(dom, Decl(reacty.tsx, 1, 8)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) === index.tsx === import { p } from "./renderer"; >p : Symbol(p, Decl(index.tsx, 0, 8)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) diff --git a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryOverridesCompilerOption.symbols.diff b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryOverridesCompilerOption.symbols.diff deleted file mode 100644 index ee80531d9ce..00000000000 --- a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryOverridesCompilerOption.symbols.diff +++ /dev/null @@ -1,20 +0,0 @@ ---- old.inlineJsxFactoryOverridesCompilerOption.symbols -+++ new.inlineJsxFactoryOverridesCompilerOption.symbols -@@= skipped -27, +27 lines =@@ - >dom : Symbol(dom, Decl(reacty.tsx, 1, 8)) - - -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - - === index.tsx === - import { p } from "./renderer"; - >p : Symbol(p, Decl(index.tsx, 0, 8)) - - -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) diff --git a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryWithFragmentIsError.symbols b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryWithFragmentIsError.symbols index 5a726877ac1..6baaa631edb 100644 --- a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryWithFragmentIsError.symbols +++ b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryWithFragmentIsError.symbols @@ -27,8 +27,8 @@ import * as React from "./renderer"; >React : Symbol(React, Decl(reacty.tsx, 1, 6)) <> ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) === index.tsx === /** @jsx dom */ @@ -36,6 +36,6 @@ import { dom } from "./renderer"; >dom : Symbol(dom, Decl(index.tsx, 1, 8)) <> ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) ->h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) +>h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) diff --git a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryWithFragmentIsError.symbols.diff b/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryWithFragmentIsError.symbols.diff deleted file mode 100644 index e7c1a4d58e0..00000000000 --- a/testdata/baselines/reference/submodule/conformance/inlineJsxFactoryWithFragmentIsError.symbols.diff +++ /dev/null @@ -1,21 +0,0 @@ ---- old.inlineJsxFactoryWithFragmentIsError.symbols -+++ new.inlineJsxFactoryWithFragmentIsError.symbols -@@= skipped -26, +26 lines =@@ - >React : Symbol(React, Decl(reacty.tsx, 1, 6)) - - <> -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) - - === index.tsx === - /** @jsx dom */ -@@= skipped -9, +9 lines =@@ - >dom : Symbol(dom, Decl(index.tsx, 1, 8)) - - <> -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -->h : Symbol(JSX.IntrinsicElements.__index, Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) -+>h : Symbol(JSX.IntrinsicElements[__index], Decl(renderer.d.ts, 2, 37)) diff --git a/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingGenerics(target=es2015).js b/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingGenerics(target=es2015).js index 63b0f8f8efe..5b2d0163bef 100644 --- a/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingGenerics(target=es2015).js +++ b/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingGenerics(target=es2015).js @@ -26,31 +26,8 @@ function y(x) { } /** * @param {Array} x */ -declare function x(x: Array): void; +declare function x(x: any[]): void; /** * @param {Promise} x */ -declare function y(x: Promise): void; - - -//// [DtsFileErrors] - - -out/file.d.ts(4,23): error TS2314: Generic type 'Array' requires 1 type argument(s). -out/file.d.ts(8,23): error TS2314: Generic type 'Promise' requires 1 type argument(s). - - -==== out/file.d.ts (2 errors) ==== - /** - * @param {Array} x - */ - declare function x(x: Array): void; - ~~~~~ -!!! error TS2314: Generic type 'Array' requires 1 type argument(s). - /** - * @param {Promise} x - */ - declare function y(x: Promise): void; - ~~~~~~~ -!!! error TS2314: Generic type 'Promise' requires 1 type argument(s). - \ No newline at end of file +declare function y(x: Promise): void; diff --git a/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingTypeParameters(target=es2015).js b/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingTypeParameters(target=es2015).js index d91fb15382e..9539ef1bd87 100644 --- a/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingTypeParameters(target=es2015).js +++ b/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingTypeParameters(target=es2015).js @@ -47,16 +47,16 @@ function w() { return null; } /** * @param {Array=} y desc */ -declare function x(y?: Array | undefined): void; +declare function x(y?: any[] | undefined): void; /** @param {function (Array)} func Invoked */ declare function y(func: Function): void; /** * @return {(Array.<> | null)} list of devices */ -declare function z(): (Array | null); +declare function z(): (any[] | null); /** * * @return {?Promise} A promise */ -declare function w(): Promise | null; +declare function w(): Promise | null; diff --git a/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingTypeParameters(target=es2015).types b/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingTypeParameters(target=es2015).types index b9774e808e5..c093c62ea16 100644 --- a/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingTypeParameters(target=es2015).types +++ b/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingTypeParameters(target=es2015).types @@ -5,7 +5,7 @@ * @param {Array=} y desc */ function x(y) { } ->x : (y?: Array | undefined) => void +>x : (y?: any[] | undefined) => void >y : any[] // @ts-ignore @@ -19,12 +19,12 @@ function y(func) { return; } * @return {(Array.<> | null)} list of devices */ function z() { return null ;} ->z : () => (Array | null) +>z : () => (any[] | null) /** * * @return {?Promise} A promise */ function w() { return null; } ->w : () => Promise | null +>w : () => Promise | null diff --git a/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingTypeParameters(target=es2015).types.diff b/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingTypeParameters(target=es2015).types.diff index 663b84d6263..d9ba8d331c2 100644 --- a/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingTypeParameters(target=es2015).types.diff +++ b/testdata/baselines/reference/submodule/conformance/jsDeclarationsMissingTypeParameters(target=es2015).types.diff @@ -1,14 +1,6 @@ --- old.jsDeclarationsMissingTypeParameters(target=es2015).types +++ new.jsDeclarationsMissingTypeParameters(target=es2015).types -@@= skipped -4, +4 lines =@@ - * @param {Array=} y desc - */ - function x(y) { } -->x : (y?: any[] | undefined) => void -+>x : (y?: Array | undefined) => void - >y : any[] - - // @ts-ignore +@@= skipped -11, +11 lines =@@ /** @param {function (Array)} func Invoked */ function y(func) { return; } @@ -18,16 +10,4 @@ +>func : Function /** - * @return {(Array.<> | null)} list of devices - */ - function z() { return null ;} -->z : () => (any[] | null) -+>z : () => (Array | null) - - /** - * - * @return {?Promise} A promise - */ - function w() { return null; } -->w : () => Promise | null -+>w : () => Promise | null + * @return {(Array.<> | null)} list of devices \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/jsxParsingError1.symbols b/testdata/baselines/reference/submodule/conformance/jsxParsingError1.symbols index 16c617211c1..e5e28a32c35 100644 --- a/testdata/baselines/reference/submodule/conformance/jsxParsingError1.symbols +++ b/testdata/baselines/reference/submodule/conformance/jsxParsingError1.symbols @@ -24,7 +24,7 @@ const class2 = "bar"; const elem =
; >elem : Symbol(elem, Decl(file.tsx, 10, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >className : Symbol(className, Decl(file.tsx, 10, 17)) >class1 : Symbol(class1, Decl(file.tsx, 8, 5)) >class2 : Symbol(class2, Decl(file.tsx, 9, 5)) diff --git a/testdata/baselines/reference/submodule/conformance/jsxParsingError1.symbols.diff b/testdata/baselines/reference/submodule/conformance/jsxParsingError1.symbols.diff deleted file mode 100644 index fadc326910f..00000000000 --- a/testdata/baselines/reference/submodule/conformance/jsxParsingError1.symbols.diff +++ /dev/null @@ -1,11 +0,0 @@ ---- old.jsxParsingError1.symbols -+++ new.jsxParsingError1.symbols -@@= skipped -23, +23 lines =@@ - - const elem =
; - >elem : Symbol(elem, Decl(file.tsx, 10, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >className : Symbol(className, Decl(file.tsx, 10, 17)) - >class1 : Symbol(class1, Decl(file.tsx, 8, 5)) - >class2 : Symbol(class2, Decl(file.tsx, 9, 5)) \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/jsxParsingError2.symbols b/testdata/baselines/reference/submodule/conformance/jsxParsingError2.symbols index 7f193ba2058..6a4af54d11d 100644 --- a/testdata/baselines/reference/submodule/conformance/jsxParsingError2.symbols +++ b/testdata/baselines/reference/submodule/conformance/jsxParsingError2.symbols @@ -19,34 +19,34 @@ declare namespace JSX { // Issue error about missing span closing tag, not missing div closing tag let x1 =
; >x1 : Symbol(x1, Decl(Error1.tsx, 1, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) === Error2.tsx === let x2 =
; >x2 : Symbol(x2, Decl(Error2.tsx, 0, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) === Error3.tsx === let x3 =
; >x3 : Symbol(x3, Decl(Error3.tsx, 0, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) === Error4.tsx === let x4 =
; >x4 : Symbol(x4, Decl(Error4.tsx, 0, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) === Error5.tsx === let x5 =
>x5 : Symbol(x5, Decl(Error5.tsx, 0, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/jsxParsingError2.symbols.diff b/testdata/baselines/reference/submodule/conformance/jsxParsingError2.symbols.diff deleted file mode 100644 index 452dcdaae64..00000000000 --- a/testdata/baselines/reference/submodule/conformance/jsxParsingError2.symbols.diff +++ /dev/null @@ -1,47 +0,0 @@ ---- old.jsxParsingError2.symbols -+++ new.jsxParsingError2.symbols -@@= skipped -18, +18 lines =@@ - // Issue error about missing span closing tag, not missing div closing tag - let x1 =
; - >x1 : Symbol(x1, Decl(Error1.tsx, 1, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - === Error2.tsx === - let x2 =
; - >x2 : Symbol(x2, Decl(Error2.tsx, 0, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - - === Error3.tsx === - let x3 =
; - >x3 : Symbol(x3, Decl(Error3.tsx, 0, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - - === Error4.tsx === - let x4 =
; - >x4 : Symbol(x4, Decl(Error4.tsx, 0, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - === Error5.tsx === - let x5 =
- >x5 : Symbol(x5, Decl(Error5.tsx, 0, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - diff --git a/testdata/baselines/reference/submodule/conformance/jsxParsingError3.symbols b/testdata/baselines/reference/submodule/conformance/jsxParsingError3.symbols index 9b598733ac8..d892deaf870 100644 --- a/testdata/baselines/reference/submodule/conformance/jsxParsingError3.symbols +++ b/testdata/baselines/reference/submodule/conformance/jsxParsingError3.symbols @@ -18,36 +18,36 @@ declare namespace JSX { === Error1.tsx === let x1 =
}
; >x1 : Symbol(x1, Decl(Error1.tsx, 0, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) === Error2.tsx === let x2 =
>
; >x2 : Symbol(x2, Decl(Error2.tsx, 0, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) === Error3.tsx === let x3 =
{"foo"}}
; >x3 : Symbol(x3, Decl(Error3.tsx, 0, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) === Error4.tsx === let x4 =
{"foo"}>
; >x4 : Symbol(x4, Decl(Error4.tsx, 0, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) === Error5.tsx === let x5 =
}{"foo"}
; >x5 : Symbol(x5, Decl(Error5.tsx, 0, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) === Error6.tsx === let x6 =
>{"foo"}
; >x6 : Symbol(x6, Decl(Error6.tsx, 0, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) diff --git a/testdata/baselines/reference/submodule/conformance/jsxParsingError3.symbols.diff b/testdata/baselines/reference/submodule/conformance/jsxParsingError3.symbols.diff deleted file mode 100644 index 51a3af0012f..00000000000 --- a/testdata/baselines/reference/submodule/conformance/jsxParsingError3.symbols.diff +++ /dev/null @@ -1,50 +0,0 @@ ---- old.jsxParsingError3.symbols -+++ new.jsxParsingError3.symbols -@@= skipped -17, +17 lines =@@ - === Error1.tsx === - let x1 =
}
; - >x1 : Symbol(x1, Decl(Error1.tsx, 0, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) - - === Error2.tsx === - let x2 =
>
; - >x2 : Symbol(x2, Decl(Error2.tsx, 0, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) - - === Error3.tsx === - let x3 =
{"foo"}}
; - >x3 : Symbol(x3, Decl(Error3.tsx, 0, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) - - === Error4.tsx === - let x4 =
{"foo"}>
; - >x4 : Symbol(x4, Decl(Error4.tsx, 0, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) - - === Error5.tsx === - let x5 =
}{"foo"}
; - >x5 : Symbol(x5, Decl(Error5.tsx, 0, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) - - === Error6.tsx === - let x6 =
>{"foo"}
; - >x6 : Symbol(x6, Decl(Error6.tsx, 0, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 31)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 31)) diff --git a/testdata/baselines/reference/submodule/conformance/jsxParsingError4(strict=false).symbols b/testdata/baselines/reference/submodule/conformance/jsxParsingError4(strict=false).symbols index 88d0f75a779..9c19e21888e 100644 --- a/testdata/baselines/reference/submodule/conformance/jsxParsingError4(strict=false).symbols +++ b/testdata/baselines/reference/submodule/conformance/jsxParsingError4(strict=false).symbols @@ -19,8 +19,8 @@ const a = ( >a : Symbol(a, Decl(a.tsx, 7, 5)) ->public-foo : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) ->public-foo : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) +>public-foo : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) +>public-foo : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) ); @@ -28,8 +28,8 @@ const b = ( >b : Symbol(b, Decl(a.tsx, 11, 5)) ->public : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) ->public : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) +>public : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) +>public : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) ); diff --git a/testdata/baselines/reference/submodule/conformance/jsxParsingError4(strict=false).symbols.diff b/testdata/baselines/reference/submodule/conformance/jsxParsingError4(strict=false).symbols.diff deleted file mode 100644 index 8419d0e543b..00000000000 --- a/testdata/baselines/reference/submodule/conformance/jsxParsingError4(strict=false).symbols.diff +++ /dev/null @@ -1,23 +0,0 @@ ---- old.jsxParsingError4(strict=false).symbols -+++ new.jsxParsingError4(strict=false).symbols -@@= skipped -18, +18 lines =@@ - >a : Symbol(a, Decl(a.tsx, 7, 5)) - - -->public-foo : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) -->public-foo : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) -+>public-foo : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) -+>public-foo : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) - - ); - -@@= skipped -9, +9 lines =@@ - >b : Symbol(b, Decl(a.tsx, 11, 5)) - - -->public : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) -->public : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) -+>public : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) -+>public : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) - - ); diff --git a/testdata/baselines/reference/submodule/conformance/jsxParsingError4(strict=true).symbols b/testdata/baselines/reference/submodule/conformance/jsxParsingError4(strict=true).symbols index 88d0f75a779..9c19e21888e 100644 --- a/testdata/baselines/reference/submodule/conformance/jsxParsingError4(strict=true).symbols +++ b/testdata/baselines/reference/submodule/conformance/jsxParsingError4(strict=true).symbols @@ -19,8 +19,8 @@ const a = ( >a : Symbol(a, Decl(a.tsx, 7, 5)) ->public-foo : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) ->public-foo : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) +>public-foo : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) +>public-foo : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) ); @@ -28,8 +28,8 @@ const b = ( >b : Symbol(b, Decl(a.tsx, 11, 5)) ->public : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) ->public : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) +>public : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) +>public : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) ); diff --git a/testdata/baselines/reference/submodule/conformance/jsxParsingError4(strict=true).symbols.diff b/testdata/baselines/reference/submodule/conformance/jsxParsingError4(strict=true).symbols.diff deleted file mode 100644 index 37da720fc70..00000000000 --- a/testdata/baselines/reference/submodule/conformance/jsxParsingError4(strict=true).symbols.diff +++ /dev/null @@ -1,23 +0,0 @@ ---- old.jsxParsingError4(strict=true).symbols -+++ new.jsxParsingError4(strict=true).symbols -@@= skipped -18, +18 lines =@@ - >a : Symbol(a, Decl(a.tsx, 7, 5)) - - -->public-foo : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) -->public-foo : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) -+>public-foo : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) -+>public-foo : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) - - ); - -@@= skipped -9, +9 lines =@@ - >b : Symbol(b, Decl(a.tsx, 11, 5)) - - -->public : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) -->public : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 2, 33)) -+>public : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) -+>public : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 2, 33)) - - ); diff --git a/testdata/baselines/reference/submodule/conformance/keyofAndIndexedAccess2.symbols b/testdata/baselines/reference/submodule/conformance/keyofAndIndexedAccess2.symbols index c461e10b233..873e845f00f 100644 --- a/testdata/baselines/reference/submodule/conformance/keyofAndIndexedAccess2.symbols +++ b/testdata/baselines/reference/submodule/conformance/keyofAndIndexedAccess2.symbols @@ -97,9 +97,9 @@ function f2(a: { x: number, y: number }, b: >x : Symbol(__index, Decl(keyofAndIndexedAccess2.ts, 12, 82)) c.x; ->c.x : Symbol(T[__index], Decl(keyofAndIndexedAccess2.ts, 12, 23)) +>c.x : Symbol(T.__index, Decl(keyofAndIndexedAccess2.ts, 12, 23)) >c : Symbol(c, Decl(keyofAndIndexedAccess2.ts, 12, 107)) ->x : Symbol(T[__index], Decl(keyofAndIndexedAccess2.ts, 12, 23)) +>x : Symbol(T.__index, Decl(keyofAndIndexedAccess2.ts, 12, 23)) c[k]; >c : Symbol(c, Decl(keyofAndIndexedAccess2.ts, 12, 107)) @@ -116,9 +116,9 @@ function f2(a: { x: number, y: number }, b: >x : Symbol(__index, Decl(keyofAndIndexedAccess2.ts, 12, 82)) c.x = 1; // Error, cannot write to index signature through constraint ->c.x : Symbol(T[__index], Decl(keyofAndIndexedAccess2.ts, 12, 23)) +>c.x : Symbol(T.__index, Decl(keyofAndIndexedAccess2.ts, 12, 23)) >c : Symbol(c, Decl(keyofAndIndexedAccess2.ts, 12, 107)) ->x : Symbol(T[__index], Decl(keyofAndIndexedAccess2.ts, 12, 23)) +>x : Symbol(T.__index, Decl(keyofAndIndexedAccess2.ts, 12, 23)) c[k] = 1; // Error, cannot write to index signature through constraint >c : Symbol(c, Decl(keyofAndIndexedAccess2.ts, 12, 107)) @@ -523,9 +523,9 @@ export class c { constructor() { this.a = "b"; ->this.a : Symbol(c[__index], Decl(keyofAndIndexedAccess2.ts, 140, 16)) +>this.a : Symbol(c.__index, Decl(keyofAndIndexedAccess2.ts, 140, 16)) >this : Symbol(c, Decl(keyofAndIndexedAccess2.ts, 136, 1)) ->a : Symbol(c[__index], Decl(keyofAndIndexedAccess2.ts, 140, 16)) +>a : Symbol(c.__index, Decl(keyofAndIndexedAccess2.ts, 140, 16)) this["a"] = "b"; >this : Symbol(c, Decl(keyofAndIndexedAccess2.ts, 136, 1)) diff --git a/testdata/baselines/reference/submodule/conformance/keyofAndIndexedAccess2.symbols.diff b/testdata/baselines/reference/submodule/conformance/keyofAndIndexedAccess2.symbols.diff index 7cfe045d31a..2369bbcff5d 100644 --- a/testdata/baselines/reference/submodule/conformance/keyofAndIndexedAccess2.symbols.diff +++ b/testdata/baselines/reference/submodule/conformance/keyofAndIndexedAccess2.symbols.diff @@ -4,9 +4,9 @@ >x : Symbol(__index, Decl(keyofAndIndexedAccess2.ts, 12, 82)) c.x; -+>c.x : Symbol(T[__index], Decl(keyofAndIndexedAccess2.ts, 12, 23)) ++>c.x : Symbol(T.__index, Decl(keyofAndIndexedAccess2.ts, 12, 23)) >c : Symbol(c, Decl(keyofAndIndexedAccess2.ts, 12, 107)) -+>x : Symbol(T[__index], Decl(keyofAndIndexedAccess2.ts, 12, 23)) ++>x : Symbol(T.__index, Decl(keyofAndIndexedAccess2.ts, 12, 23)) c[k]; >c : Symbol(c, Decl(keyofAndIndexedAccess2.ts, 12, 107)) @@ -14,9 +14,9 @@ >x : Symbol(__index, Decl(keyofAndIndexedAccess2.ts, 12, 82)) c.x = 1; // Error, cannot write to index signature through constraint -+>c.x : Symbol(T[__index], Decl(keyofAndIndexedAccess2.ts, 12, 23)) ++>c.x : Symbol(T.__index, Decl(keyofAndIndexedAccess2.ts, 12, 23)) >c : Symbol(c, Decl(keyofAndIndexedAccess2.ts, 12, 107)) -+>x : Symbol(T[__index], Decl(keyofAndIndexedAccess2.ts, 12, 23)) ++>x : Symbol(T.__index, Decl(keyofAndIndexedAccess2.ts, 12, 23)) c[k] = 1; // Error, cannot write to index signature through constraint >c : Symbol(c, Decl(keyofAndIndexedAccess2.ts, 12, 107)) @@ -24,9 +24,9 @@ constructor() { this.a = "b"; -+>this.a : Symbol(c[__index], Decl(keyofAndIndexedAccess2.ts, 140, 16)) ++>this.a : Symbol(c.__index, Decl(keyofAndIndexedAccess2.ts, 140, 16)) >this : Symbol(c, Decl(keyofAndIndexedAccess2.ts, 136, 1)) -+>a : Symbol(c[__index], Decl(keyofAndIndexedAccess2.ts, 140, 16)) ++>a : Symbol(c.__index, Decl(keyofAndIndexedAccess2.ts, 140, 16)) this["a"] = "b"; >this : Symbol(c, Decl(keyofAndIndexedAccess2.ts, 136, 1)) \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/noPropertyAccessFromIndexSignature1.symbols b/testdata/baselines/reference/submodule/conformance/noPropertyAccessFromIndexSignature1.symbols index 7e40812793e..500ccaa7013 100644 --- a/testdata/baselines/reference/submodule/conformance/noPropertyAccessFromIndexSignature1.symbols +++ b/testdata/baselines/reference/submodule/conformance/noPropertyAccessFromIndexSignature1.symbols @@ -53,9 +53,9 @@ a["foo"] // access index signature b.foo; ->b.foo : Symbol(B[__index], Decl(noPropertyAccessFromIndexSignature1.ts, 4, 13)) +>b.foo : Symbol(B.__index, Decl(noPropertyAccessFromIndexSignature1.ts, 4, 13)) >b : Symbol(b, Decl(noPropertyAccessFromIndexSignature1.ts, 14, 13)) ->foo : Symbol(B[__index], Decl(noPropertyAccessFromIndexSignature1.ts, 4, 13)) +>foo : Symbol(B.__index, Decl(noPropertyAccessFromIndexSignature1.ts, 4, 13)) b["foo"]; >b : Symbol(b, Decl(noPropertyAccessFromIndexSignature1.ts, 14, 13)) @@ -72,9 +72,9 @@ c["foo"] // access index signature c.bar; ->c.bar : Symbol(C[__index], Decl(noPropertyAccessFromIndexSignature1.ts, 9, 15)) +>c.bar : Symbol(C.__index, Decl(noPropertyAccessFromIndexSignature1.ts, 9, 15)) >c : Symbol(c, Decl(noPropertyAccessFromIndexSignature1.ts, 15, 13)) ->bar : Symbol(C[__index], Decl(noPropertyAccessFromIndexSignature1.ts, 9, 15)) +>bar : Symbol(C.__index, Decl(noPropertyAccessFromIndexSignature1.ts, 9, 15)) c["bar"]; >c : Symbol(c, Decl(noPropertyAccessFromIndexSignature1.ts, 15, 13)) diff --git a/testdata/baselines/reference/submodule/conformance/noPropertyAccessFromIndexSignature1.symbols.diff b/testdata/baselines/reference/submodule/conformance/noPropertyAccessFromIndexSignature1.symbols.diff deleted file mode 100644 index 3819bb6b11f..00000000000 --- a/testdata/baselines/reference/submodule/conformance/noPropertyAccessFromIndexSignature1.symbols.diff +++ /dev/null @@ -1,26 +0,0 @@ ---- old.noPropertyAccessFromIndexSignature1.symbols -+++ new.noPropertyAccessFromIndexSignature1.symbols -@@= skipped -52, +52 lines =@@ - - // access index signature - b.foo; -->b.foo : Symbol(B.__index, Decl(noPropertyAccessFromIndexSignature1.ts, 4, 13)) -+>b.foo : Symbol(B[__index], Decl(noPropertyAccessFromIndexSignature1.ts, 4, 13)) - >b : Symbol(b, Decl(noPropertyAccessFromIndexSignature1.ts, 14, 13)) -->foo : Symbol(B.__index, Decl(noPropertyAccessFromIndexSignature1.ts, 4, 13)) -+>foo : Symbol(B[__index], Decl(noPropertyAccessFromIndexSignature1.ts, 4, 13)) - - b["foo"]; - >b : Symbol(b, Decl(noPropertyAccessFromIndexSignature1.ts, 14, 13)) -@@= skipped -19, +19 lines =@@ - - // access index signature - c.bar; -->c.bar : Symbol(C.__index, Decl(noPropertyAccessFromIndexSignature1.ts, 9, 15)) -+>c.bar : Symbol(C[__index], Decl(noPropertyAccessFromIndexSignature1.ts, 9, 15)) - >c : Symbol(c, Decl(noPropertyAccessFromIndexSignature1.ts, 15, 13)) -->bar : Symbol(C.__index, Decl(noPropertyAccessFromIndexSignature1.ts, 9, 15)) -+>bar : Symbol(C[__index], Decl(noPropertyAccessFromIndexSignature1.ts, 9, 15)) - - c["bar"]; - >c : Symbol(c, Decl(noPropertyAccessFromIndexSignature1.ts, 15, 13)) \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/noUncheckedIndexedAccessDestructuring.symbols b/testdata/baselines/reference/submodule/conformance/noUncheckedIndexedAccessDestructuring.symbols index 2f8894e61b6..84d34ee3c96 100644 --- a/testdata/baselines/reference/submodule/conformance/noUncheckedIndexedAccessDestructuring.symbols +++ b/testdata/baselines/reference/submodule/conformance/noUncheckedIndexedAccessDestructuring.symbols @@ -62,9 +62,9 @@ const { ...t2 } = strMap; t2.z.toString(); // Should error >t2.z.toString : Symbol(String.toString, Decl(lib.es5.d.ts, --, --)) ->t2.z : Symbol(t2[__index], Decl(noUncheckedIndexedAccessDestructuring.ts, 19, 23)) +>t2.z : Symbol(t2.__index, Decl(noUncheckedIndexedAccessDestructuring.ts, 19, 23)) >t2 : Symbol(t2, Decl(noUncheckedIndexedAccessDestructuring.ts, 24, 7)) ->z : Symbol(t2[__index], Decl(noUncheckedIndexedAccessDestructuring.ts, 19, 23)) +>z : Symbol(t2.__index, Decl(noUncheckedIndexedAccessDestructuring.ts, 19, 23)) >toString : Symbol(String.toString, Decl(lib.es5.d.ts, --, --)) // Test intersections with declared properties @@ -116,9 +116,9 @@ declare const numMapPoint: { x: number, y: number} & { [s: string]: number }; q.z.toFixed(); // Should error >q.z.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ->q.z : Symbol(q[__index], Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) +>q.z : Symbol(q.__index, Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) >q : Symbol(q, Decl(noUncheckedIndexedAccessDestructuring.ts, 37, 14)) ->z : Symbol(q[__index], Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) +>z : Symbol(q.__index, Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) >toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) } @@ -146,11 +146,11 @@ declare const numMapPoint: { x: number, y: number} & { [s: string]: number }; q. >q. z.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) ->q. z : Symbol(q[__index], Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) +>q. z : Symbol(q.__index, Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) >q : Symbol(q, Decl(noUncheckedIndexedAccessDestructuring.ts, 44, 14)) z.toFixed(); // Should error ->z : Symbol(q[__index], Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) +>z : Symbol(q.__index, Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) >toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) } diff --git a/testdata/baselines/reference/submodule/conformance/noUncheckedIndexedAccessDestructuring.symbols.diff b/testdata/baselines/reference/submodule/conformance/noUncheckedIndexedAccessDestructuring.symbols.diff index ad1e1cb6fad..08267c22d77 100644 --- a/testdata/baselines/reference/submodule/conformance/noUncheckedIndexedAccessDestructuring.symbols.diff +++ b/testdata/baselines/reference/submodule/conformance/noUncheckedIndexedAccessDestructuring.symbols.diff @@ -4,9 +4,9 @@ t2.z.toString(); // Should error >t2.z.toString : Symbol(String.toString, Decl(lib.es5.d.ts, --, --)) -+>t2.z : Symbol(t2[__index], Decl(noUncheckedIndexedAccessDestructuring.ts, 19, 23)) ++>t2.z : Symbol(t2.__index, Decl(noUncheckedIndexedAccessDestructuring.ts, 19, 23)) >t2 : Symbol(t2, Decl(noUncheckedIndexedAccessDestructuring.ts, 24, 7)) -+>z : Symbol(t2[__index], Decl(noUncheckedIndexedAccessDestructuring.ts, 19, 23)) ++>z : Symbol(t2.__index, Decl(noUncheckedIndexedAccessDestructuring.ts, 19, 23)) >toString : Symbol(String.toString, Decl(lib.es5.d.ts, --, --)) // Test intersections with declared properties @@ -14,9 +14,9 @@ q.z.toFixed(); // Should error >q.z.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) -+>q.z : Symbol(q[__index], Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) ++>q.z : Symbol(q.__index, Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) >q : Symbol(q, Decl(noUncheckedIndexedAccessDestructuring.ts, 37, 14)) -+>z : Symbol(q[__index], Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) ++>z : Symbol(q.__index, Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) >toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) } @@ -24,10 +24,10 @@ q. >q. z.toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) -+>q. z : Symbol(q[__index], Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) ++>q. z : Symbol(q.__index, Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) >q : Symbol(q, Decl(noUncheckedIndexedAccessDestructuring.ts, 44, 14)) z.toFixed(); // Should error -+>z : Symbol(q[__index], Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) ++>z : Symbol(q.__index, Decl(noUncheckedIndexedAccessDestructuring.ts, 28, 54)) >toFixed : Symbol(Number.toFixed, Decl(lib.es5.d.ts, --, --)) } diff --git a/testdata/baselines/reference/submodule/conformance/propertyAccessStringIndexSignature(noimplicitany=false).symbols b/testdata/baselines/reference/submodule/conformance/propertyAccessStringIndexSignature(noimplicitany=false).symbols index 9ce0f3bcc28..be371f5ff50 100644 --- a/testdata/baselines/reference/submodule/conformance/propertyAccessStringIndexSignature(noimplicitany=false).symbols +++ b/testdata/baselines/reference/submodule/conformance/propertyAccessStringIndexSignature(noimplicitany=false).symbols @@ -10,19 +10,19 @@ declare let flags: Flags; >Flags : Symbol(Flags, Decl(propertyAccessStringIndexSignature.ts, 0, 0)) flags.b; ->flags.b : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) +>flags.b : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) ->b : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) +>b : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) flags.f; ->flags.f : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) +>flags.f : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) ->f : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) +>f : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) flags.isNotNecessarilyNeverFalse; ->flags.isNotNecessarilyNeverFalse : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) +>flags.isNotNecessarilyNeverFalse : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) ->isNotNecessarilyNeverFalse : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) +>isNotNecessarilyNeverFalse : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) flags['this is fine']; >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) diff --git a/testdata/baselines/reference/submodule/conformance/propertyAccessStringIndexSignature(noimplicitany=false).symbols.diff b/testdata/baselines/reference/submodule/conformance/propertyAccessStringIndexSignature(noimplicitany=false).symbols.diff deleted file mode 100644 index 8ee2c1c7b5d..00000000000 --- a/testdata/baselines/reference/submodule/conformance/propertyAccessStringIndexSignature(noimplicitany=false).symbols.diff +++ /dev/null @@ -1,28 +0,0 @@ ---- old.propertyAccessStringIndexSignature(noimplicitany=false).symbols -+++ new.propertyAccessStringIndexSignature(noimplicitany=false).symbols -@@= skipped -9, +9 lines =@@ - >Flags : Symbol(Flags, Decl(propertyAccessStringIndexSignature.ts, 0, 0)) - - flags.b; -->flags.b : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) -+>flags.b : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) - >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) -->b : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) -+>b : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) - - flags.f; -->flags.f : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) -+>flags.f : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) - >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) -->f : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) -+>f : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) - - flags.isNotNecessarilyNeverFalse; -->flags.isNotNecessarilyNeverFalse : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) -+>flags.isNotNecessarilyNeverFalse : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) - >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) -->isNotNecessarilyNeverFalse : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) -+>isNotNecessarilyNeverFalse : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) - - flags['this is fine']; - >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/propertyAccessStringIndexSignature(noimplicitany=true).symbols b/testdata/baselines/reference/submodule/conformance/propertyAccessStringIndexSignature(noimplicitany=true).symbols index 9ce0f3bcc28..be371f5ff50 100644 --- a/testdata/baselines/reference/submodule/conformance/propertyAccessStringIndexSignature(noimplicitany=true).symbols +++ b/testdata/baselines/reference/submodule/conformance/propertyAccessStringIndexSignature(noimplicitany=true).symbols @@ -10,19 +10,19 @@ declare let flags: Flags; >Flags : Symbol(Flags, Decl(propertyAccessStringIndexSignature.ts, 0, 0)) flags.b; ->flags.b : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) +>flags.b : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) ->b : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) +>b : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) flags.f; ->flags.f : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) +>flags.f : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) ->f : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) +>f : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) flags.isNotNecessarilyNeverFalse; ->flags.isNotNecessarilyNeverFalse : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) +>flags.isNotNecessarilyNeverFalse : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) ->isNotNecessarilyNeverFalse : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) +>isNotNecessarilyNeverFalse : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) flags['this is fine']; >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) diff --git a/testdata/baselines/reference/submodule/conformance/propertyAccessStringIndexSignature(noimplicitany=true).symbols.diff b/testdata/baselines/reference/submodule/conformance/propertyAccessStringIndexSignature(noimplicitany=true).symbols.diff deleted file mode 100644 index fb96d78bf96..00000000000 --- a/testdata/baselines/reference/submodule/conformance/propertyAccessStringIndexSignature(noimplicitany=true).symbols.diff +++ /dev/null @@ -1,28 +0,0 @@ ---- old.propertyAccessStringIndexSignature(noimplicitany=true).symbols -+++ new.propertyAccessStringIndexSignature(noimplicitany=true).symbols -@@= skipped -9, +9 lines =@@ - >Flags : Symbol(Flags, Decl(propertyAccessStringIndexSignature.ts, 0, 0)) - - flags.b; -->flags.b : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) -+>flags.b : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) - >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) -->b : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) -+>b : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) - - flags.f; -->flags.f : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) -+>flags.f : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) - >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) -->f : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) -+>f : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) - - flags.isNotNecessarilyNeverFalse; -->flags.isNotNecessarilyNeverFalse : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) -+>flags.isNotNecessarilyNeverFalse : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) - >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) -->isNotNecessarilyNeverFalse : Symbol(Flags.__index, Decl(propertyAccessStringIndexSignature.ts, 0, 17)) -+>isNotNecessarilyNeverFalse : Symbol(Flags[__index], Decl(propertyAccessStringIndexSignature.ts, 0, 17)) - - flags['this is fine']; - >flags : Symbol(flags, Decl(propertyAccessStringIndexSignature.ts, 1, 11)) \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/staticIndexSignature1.symbols b/testdata/baselines/reference/submodule/conformance/staticIndexSignature1.symbols index c56ecaaa189..8b00e678470 100644 --- a/testdata/baselines/reference/submodule/conformance/staticIndexSignature1.symbols +++ b/testdata/baselines/reference/submodule/conformance/staticIndexSignature1.symbols @@ -15,9 +15,9 @@ C["foo"] = 1 >C : Symbol(C, Decl(staticIndexSignature1.ts, 0, 0)) C.bar = 2; ->C.bar : Symbol(C[__index], Decl(staticIndexSignature1.ts, 0, 9)) +>C.bar : Symbol(C.__index, Decl(staticIndexSignature1.ts, 0, 9)) >C : Symbol(C, Decl(staticIndexSignature1.ts, 0, 0)) ->bar : Symbol(C[__index], Decl(staticIndexSignature1.ts, 0, 9)) +>bar : Symbol(C.__index, Decl(staticIndexSignature1.ts, 0, 9)) const foo = C["foo"] >foo : Symbol(foo, Decl(staticIndexSignature1.ts, 7, 5)) diff --git a/testdata/baselines/reference/submodule/conformance/staticIndexSignature1.symbols.diff b/testdata/baselines/reference/submodule/conformance/staticIndexSignature1.symbols.diff deleted file mode 100644 index 9d50df6bebc..00000000000 --- a/testdata/baselines/reference/submodule/conformance/staticIndexSignature1.symbols.diff +++ /dev/null @@ -1,14 +0,0 @@ ---- old.staticIndexSignature1.symbols -+++ new.staticIndexSignature1.symbols -@@= skipped -14, +14 lines =@@ - >C : Symbol(C, Decl(staticIndexSignature1.ts, 0, 0)) - - C.bar = 2; -->C.bar : Symbol(C.__index, Decl(staticIndexSignature1.ts, 0, 9)) -+>C.bar : Symbol(C[__index], Decl(staticIndexSignature1.ts, 0, 9)) - >C : Symbol(C, Decl(staticIndexSignature1.ts, 0, 0)) -->bar : Symbol(C.__index, Decl(staticIndexSignature1.ts, 0, 9)) -+>bar : Symbol(C[__index], Decl(staticIndexSignature1.ts, 0, 9)) - - const foo = C["foo"] - >foo : Symbol(foo, Decl(staticIndexSignature1.ts, 7, 5)) \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/staticIndexSignature2.symbols b/testdata/baselines/reference/submodule/conformance/staticIndexSignature2.symbols index 65971bc29c6..607fceb4a8e 100644 --- a/testdata/baselines/reference/submodule/conformance/staticIndexSignature2.symbols +++ b/testdata/baselines/reference/submodule/conformance/staticIndexSignature2.symbols @@ -15,9 +15,9 @@ C["foo"] = 1 >C : Symbol(C, Decl(staticIndexSignature2.ts, 0, 0)) C.bar = 2; ->C.bar : Symbol(C[__index], Decl(staticIndexSignature2.ts, 0, 9)) +>C.bar : Symbol(C.__index, Decl(staticIndexSignature2.ts, 0, 9)) >C : Symbol(C, Decl(staticIndexSignature2.ts, 0, 0)) ->bar : Symbol(C[__index], Decl(staticIndexSignature2.ts, 0, 9)) +>bar : Symbol(C.__index, Decl(staticIndexSignature2.ts, 0, 9)) const foo = C["foo"] >foo : Symbol(foo, Decl(staticIndexSignature2.ts, 7, 5)) diff --git a/testdata/baselines/reference/submodule/conformance/staticIndexSignature2.symbols.diff b/testdata/baselines/reference/submodule/conformance/staticIndexSignature2.symbols.diff deleted file mode 100644 index f8eea7bb091..00000000000 --- a/testdata/baselines/reference/submodule/conformance/staticIndexSignature2.symbols.diff +++ /dev/null @@ -1,14 +0,0 @@ ---- old.staticIndexSignature2.symbols -+++ new.staticIndexSignature2.symbols -@@= skipped -14, +14 lines =@@ - >C : Symbol(C, Decl(staticIndexSignature2.ts, 0, 0)) - - C.bar = 2; -->C.bar : Symbol(C.__index, Decl(staticIndexSignature2.ts, 0, 9)) -+>C.bar : Symbol(C[__index], Decl(staticIndexSignature2.ts, 0, 9)) - >C : Symbol(C, Decl(staticIndexSignature2.ts, 0, 0)) -->bar : Symbol(C.__index, Decl(staticIndexSignature2.ts, 0, 9)) -+>bar : Symbol(C[__index], Decl(staticIndexSignature2.ts, 0, 9)) - - const foo = C["foo"] - >foo : Symbol(foo, Decl(staticIndexSignature2.ts, 7, 5)) \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/staticIndexSignature4.symbols b/testdata/baselines/reference/submodule/conformance/staticIndexSignature4.symbols index b741b532cfd..221cd554fba 100644 --- a/testdata/baselines/reference/submodule/conformance/staticIndexSignature4.symbols +++ b/testdata/baselines/reference/submodule/conformance/staticIndexSignature4.symbols @@ -42,12 +42,12 @@ if (v === 0) { >v : Symbol(v, Decl(staticIndexSignature4.ts, 15, 13)) B.a = D.a ->B.a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) +>B.a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) >B : Symbol(B, Decl(staticIndexSignature4.ts, 0, 0)) ->a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) ->D.a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) +>a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) +>D.a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) >D : Symbol(D, Decl(staticIndexSignature4.ts, 3, 1)) ->a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) +>a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) B[2] = D[2] >B : Symbol(B, Decl(staticIndexSignature4.ts, 0, 0)) @@ -57,12 +57,12 @@ if (v === 0) { >v : Symbol(v, Decl(staticIndexSignature4.ts, 15, 13)) D.a = B.a ->D.a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) +>D.a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) >D : Symbol(D, Decl(staticIndexSignature4.ts, 3, 1)) ->a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) ->B.a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) +>a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) +>B.a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) >B : Symbol(B, Decl(staticIndexSignature4.ts, 0, 0)) ->a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) +>a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) D[2] = B[2] >D : Symbol(D, Decl(staticIndexSignature4.ts, 3, 1)) @@ -72,24 +72,24 @@ if (v === 0) { >v : Symbol(v, Decl(staticIndexSignature4.ts, 15, 13)) B.a = i.a ->B.a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) +>B.a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) >B : Symbol(B, Decl(staticIndexSignature4.ts, 0, 0)) ->a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) ->i.a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) +>a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) +>i.a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) >i : Symbol(i, Decl(staticIndexSignature4.ts, 16, 13)) ->a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) +>a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) B[2] = i[2] >B : Symbol(B, Decl(staticIndexSignature4.ts, 0, 0)) >i : Symbol(i, Decl(staticIndexSignature4.ts, 16, 13)) D.a = i.a ->D.a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) +>D.a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) >D : Symbol(D, Decl(staticIndexSignature4.ts, 3, 1)) ->a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) ->i.a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) +>a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) +>i.a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) >i : Symbol(i, Decl(staticIndexSignature4.ts, 16, 13)) ->a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) +>a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) D[2] = i [2] >D : Symbol(D, Decl(staticIndexSignature4.ts, 3, 1)) @@ -99,12 +99,12 @@ if (v === 0) { >v : Symbol(v, Decl(staticIndexSignature4.ts, 15, 13)) i.a = B.a ->i.a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) +>i.a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) >i : Symbol(i, Decl(staticIndexSignature4.ts, 16, 13)) ->a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) ->B.a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) +>a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) +>B.a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) >B : Symbol(B, Decl(staticIndexSignature4.ts, 0, 0)) ->a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) +>a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) i[2] = B[2] >i : Symbol(i, Decl(staticIndexSignature4.ts, 16, 13)) @@ -114,12 +114,12 @@ if (v === 0) { >v : Symbol(v, Decl(staticIndexSignature4.ts, 15, 13)) i.a = D.a ->i.a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) +>i.a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) >i : Symbol(i, Decl(staticIndexSignature4.ts, 16, 13)) ->a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) ->D.a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) +>a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) +>D.a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) >D : Symbol(D, Decl(staticIndexSignature4.ts, 3, 1)) ->a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) +>a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) i[2] = B[2] >i : Symbol(i, Decl(staticIndexSignature4.ts, 16, 13)) diff --git a/testdata/baselines/reference/submodule/conformance/staticIndexSignature4.symbols.diff b/testdata/baselines/reference/submodule/conformance/staticIndexSignature4.symbols.diff deleted file mode 100644 index 0d917c52457..00000000000 --- a/testdata/baselines/reference/submodule/conformance/staticIndexSignature4.symbols.diff +++ /dev/null @@ -1,103 +0,0 @@ ---- old.staticIndexSignature4.symbols -+++ new.staticIndexSignature4.symbols -@@= skipped -41, +41 lines =@@ - >v : Symbol(v, Decl(staticIndexSignature4.ts, 15, 13)) - - B.a = D.a -->B.a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) -+>B.a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) - >B : Symbol(B, Decl(staticIndexSignature4.ts, 0, 0)) -->a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) -->D.a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) -+>a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) -+>D.a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) - >D : Symbol(D, Decl(staticIndexSignature4.ts, 3, 1)) -->a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) -+>a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) - - B[2] = D[2] - >B : Symbol(B, Decl(staticIndexSignature4.ts, 0, 0)) -@@= skipped -15, +15 lines =@@ - >v : Symbol(v, Decl(staticIndexSignature4.ts, 15, 13)) - - D.a = B.a -->D.a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) -+>D.a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) - >D : Symbol(D, Decl(staticIndexSignature4.ts, 3, 1)) -->a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) -->B.a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) -+>a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) -+>B.a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) - >B : Symbol(B, Decl(staticIndexSignature4.ts, 0, 0)) -->a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) -+>a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) - - D[2] = B[2] - >D : Symbol(D, Decl(staticIndexSignature4.ts, 3, 1)) -@@= skipped -15, +15 lines =@@ - >v : Symbol(v, Decl(staticIndexSignature4.ts, 15, 13)) - - B.a = i.a -->B.a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) -+>B.a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) - >B : Symbol(B, Decl(staticIndexSignature4.ts, 0, 0)) -->a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) -->i.a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) -+>a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) -+>i.a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) - >i : Symbol(i, Decl(staticIndexSignature4.ts, 16, 13)) -->a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) -+>a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) - - B[2] = i[2] - >B : Symbol(B, Decl(staticIndexSignature4.ts, 0, 0)) - >i : Symbol(i, Decl(staticIndexSignature4.ts, 16, 13)) - - D.a = i.a -->D.a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) -+>D.a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) - >D : Symbol(D, Decl(staticIndexSignature4.ts, 3, 1)) -->a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) -->i.a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) -+>a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) -+>i.a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) - >i : Symbol(i, Decl(staticIndexSignature4.ts, 16, 13)) -->a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) -+>a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) - - D[2] = i [2] - >D : Symbol(D, Decl(staticIndexSignature4.ts, 3, 1)) -@@= skipped -27, +27 lines =@@ - >v : Symbol(v, Decl(staticIndexSignature4.ts, 15, 13)) - - i.a = B.a -->i.a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) -+>i.a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) - >i : Symbol(i, Decl(staticIndexSignature4.ts, 16, 13)) -->a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) -->B.a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) -+>a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) -+>B.a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) - >B : Symbol(B, Decl(staticIndexSignature4.ts, 0, 0)) -->a : Symbol(B.__index, Decl(staticIndexSignature4.ts, 0, 9)) -+>a : Symbol(B[__index], Decl(staticIndexSignature4.ts, 0, 9)) - - i[2] = B[2] - >i : Symbol(i, Decl(staticIndexSignature4.ts, 16, 13)) -@@= skipped -15, +15 lines =@@ - >v : Symbol(v, Decl(staticIndexSignature4.ts, 15, 13)) - - i.a = D.a -->i.a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) -+>i.a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) - >i : Symbol(i, Decl(staticIndexSignature4.ts, 16, 13)) -->a : Symbol(IB.__index, Decl(staticIndexSignature4.ts, 10, 14)) -->D.a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) -+>a : Symbol(IB[__index], Decl(staticIndexSignature4.ts, 10, 14)) -+>D.a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) - >D : Symbol(D, Decl(staticIndexSignature4.ts, 3, 1)) -->a : Symbol(D.__index, Decl(staticIndexSignature4.ts, 5, 9)) -+>a : Symbol(D[__index], Decl(staticIndexSignature4.ts, 5, 9)) - - i[2] = B[2] - >i : Symbol(i, Decl(staticIndexSignature4.ts, 16, 13)) \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/staticIndexSignature6.symbols b/testdata/baselines/reference/submodule/conformance/staticIndexSignature6.symbols index f0a6c7d370d..5befa0b4887 100644 --- a/testdata/baselines/reference/submodule/conformance/staticIndexSignature6.symbols +++ b/testdata/baselines/reference/submodule/conformance/staticIndexSignature6.symbols @@ -26,14 +26,14 @@ const C = foo() >foo : Symbol(foo, Decl(staticIndexSignature6.ts, 0, 0)) C.a; ->C.a : Symbol((Anonymous class)[__index], Decl(staticIndexSignature6.ts, 1, 21)) +>C.a : Symbol((Anonymous class).__index, Decl(staticIndexSignature6.ts, 1, 21)) >C : Symbol(C, Decl(staticIndexSignature6.ts, 9, 5)) ->a : Symbol((Anonymous class)[__index], Decl(staticIndexSignature6.ts, 1, 21)) +>a : Symbol((Anonymous class).__index, Decl(staticIndexSignature6.ts, 1, 21)) C.a = 1; ->C.a : Symbol((Anonymous class)[__index], Decl(staticIndexSignature6.ts, 1, 21)) +>C.a : Symbol((Anonymous class).__index, Decl(staticIndexSignature6.ts, 1, 21)) >C : Symbol(C, Decl(staticIndexSignature6.ts, 9, 5)) ->a : Symbol((Anonymous class)[__index], Decl(staticIndexSignature6.ts, 1, 21)) +>a : Symbol((Anonymous class).__index, Decl(staticIndexSignature6.ts, 1, 21)) C[2]; >C : Symbol(C, Decl(staticIndexSignature6.ts, 9, 5)) diff --git a/testdata/baselines/reference/submodule/conformance/staticIndexSignature6.symbols.diff b/testdata/baselines/reference/submodule/conformance/staticIndexSignature6.symbols.diff deleted file mode 100644 index dc72d5f4f28..00000000000 --- a/testdata/baselines/reference/submodule/conformance/staticIndexSignature6.symbols.diff +++ /dev/null @@ -1,21 +0,0 @@ ---- old.staticIndexSignature6.symbols -+++ new.staticIndexSignature6.symbols -@@= skipped -25, +25 lines =@@ - >foo : Symbol(foo, Decl(staticIndexSignature6.ts, 0, 0)) - - C.a; -->C.a : Symbol((Anonymous class).__index, Decl(staticIndexSignature6.ts, 1, 21)) -+>C.a : Symbol((Anonymous class)[__index], Decl(staticIndexSignature6.ts, 1, 21)) - >C : Symbol(C, Decl(staticIndexSignature6.ts, 9, 5)) -->a : Symbol((Anonymous class).__index, Decl(staticIndexSignature6.ts, 1, 21)) -+>a : Symbol((Anonymous class)[__index], Decl(staticIndexSignature6.ts, 1, 21)) - - C.a = 1; -->C.a : Symbol((Anonymous class).__index, Decl(staticIndexSignature6.ts, 1, 21)) -+>C.a : Symbol((Anonymous class)[__index], Decl(staticIndexSignature6.ts, 1, 21)) - >C : Symbol(C, Decl(staticIndexSignature6.ts, 9, 5)) -->a : Symbol((Anonymous class).__index, Decl(staticIndexSignature6.ts, 1, 21)) -+>a : Symbol((Anonymous class)[__index], Decl(staticIndexSignature6.ts, 1, 21)) - - C[2]; - >C : Symbol(C, Decl(staticIndexSignature6.ts, 9, 5)) \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/thisTypeInFunctions2.symbols b/testdata/baselines/reference/submodule/conformance/thisTypeInFunctions2.symbols index a31e1ca80d1..eefd0aa7b13 100644 --- a/testdata/baselines/reference/submodule/conformance/thisTypeInFunctions2.symbols +++ b/testdata/baselines/reference/submodule/conformance/thisTypeInFunctions2.symbols @@ -95,9 +95,9 @@ extend2({ >this : Symbol(IndexedWithoutThis, Decl(thisTypeInFunctions2.ts, 5, 1)) this.mine ->this.mine : Symbol(IndexedWithoutThis[__index], Decl(thisTypeInFunctions2.ts, 9, 29)) +>this.mine : Symbol(IndexedWithoutThis.__index, Decl(thisTypeInFunctions2.ts, 9, 29)) >this : Symbol(IndexedWithoutThis, Decl(thisTypeInFunctions2.ts, 5, 1)) ->mine : Symbol(IndexedWithoutThis[__index], Decl(thisTypeInFunctions2.ts, 9, 29)) +>mine : Symbol(IndexedWithoutThis.__index, Decl(thisTypeInFunctions2.ts, 9, 29)) }, mine: 13, @@ -110,9 +110,9 @@ extend2({ >this : Symbol(IndexedWithoutThis, Decl(thisTypeInFunctions2.ts, 5, 1)) this.mine ->this.mine : Symbol(IndexedWithoutThis[__index], Decl(thisTypeInFunctions2.ts, 9, 29)) +>this.mine : Symbol(IndexedWithoutThis.__index, Decl(thisTypeInFunctions2.ts, 9, 29)) >this : Symbol(IndexedWithoutThis, Decl(thisTypeInFunctions2.ts, 5, 1)) ->mine : Symbol(IndexedWithoutThis[__index], Decl(thisTypeInFunctions2.ts, 9, 29)) +>mine : Symbol(IndexedWithoutThis.__index, Decl(thisTypeInFunctions2.ts, 9, 29)) } }); diff --git a/testdata/baselines/reference/submodule/conformance/thisTypeInFunctions2.symbols.diff b/testdata/baselines/reference/submodule/conformance/thisTypeInFunctions2.symbols.diff deleted file mode 100644 index 4777e64c3e5..00000000000 --- a/testdata/baselines/reference/submodule/conformance/thisTypeInFunctions2.symbols.diff +++ /dev/null @@ -1,25 +0,0 @@ ---- old.thisTypeInFunctions2.symbols -+++ new.thisTypeInFunctions2.symbols -@@= skipped -94, +94 lines =@@ - >this : Symbol(IndexedWithoutThis, Decl(thisTypeInFunctions2.ts, 5, 1)) - - this.mine -->this.mine : Symbol(IndexedWithoutThis.__index, Decl(thisTypeInFunctions2.ts, 9, 29)) -+>this.mine : Symbol(IndexedWithoutThis[__index], Decl(thisTypeInFunctions2.ts, 9, 29)) - >this : Symbol(IndexedWithoutThis, Decl(thisTypeInFunctions2.ts, 5, 1)) -->mine : Symbol(IndexedWithoutThis.__index, Decl(thisTypeInFunctions2.ts, 9, 29)) -+>mine : Symbol(IndexedWithoutThis[__index], Decl(thisTypeInFunctions2.ts, 9, 29)) - - }, - mine: 13, -@@= skipped -15, +15 lines =@@ - >this : Symbol(IndexedWithoutThis, Decl(thisTypeInFunctions2.ts, 5, 1)) - - this.mine -->this.mine : Symbol(IndexedWithoutThis.__index, Decl(thisTypeInFunctions2.ts, 9, 29)) -+>this.mine : Symbol(IndexedWithoutThis[__index], Decl(thisTypeInFunctions2.ts, 9, 29)) - >this : Symbol(IndexedWithoutThis, Decl(thisTypeInFunctions2.ts, 5, 1)) -->mine : Symbol(IndexedWithoutThis.__index, Decl(thisTypeInFunctions2.ts, 9, 29)) -+>mine : Symbol(IndexedWithoutThis[__index], Decl(thisTypeInFunctions2.ts, 9, 29)) - } - }); diff --git a/testdata/baselines/reference/submodule/conformance/tsxElementResolution2.symbols b/testdata/baselines/reference/submodule/conformance/tsxElementResolution2.symbols index 536e683ff9f..25b5b3ec6c1 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxElementResolution2.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxElementResolution2.symbols @@ -17,9 +17,9 @@ declare namespace JSX { // OK
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // OK ; ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxElementResolution2.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxElementResolution2.symbols.diff deleted file mode 100644 index abcaa25b919..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxElementResolution2.symbols.diff +++ /dev/null @@ -1,13 +0,0 @@ ---- old.tsxElementResolution2.symbols -+++ new.tsxElementResolution2.symbols -@@= skipped -16, +16 lines =@@ - - // OK -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // OK - ; -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxElementResolution3.symbols b/testdata/baselines/reference/submodule/conformance/tsxElementResolution3.symbols index 9c4981b1248..62cd0bf0afd 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxElementResolution3.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxElementResolution3.symbols @@ -18,11 +18,11 @@ declare namespace JSX { // OK
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >n : Symbol(n, Decl(file.tsx, 8, 4)) // Error ; ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >w : Symbol(w, Decl(file.tsx, 11, 5)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxElementResolution3.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxElementResolution3.symbols.diff deleted file mode 100644 index 70d4984b30d..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxElementResolution3.symbols.diff +++ /dev/null @@ -1,15 +0,0 @@ ---- old.tsxElementResolution3.symbols -+++ new.tsxElementResolution3.symbols -@@= skipped -17, +17 lines =@@ - - // OK -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >n : Symbol(n, Decl(file.tsx, 8, 4)) - - // Error - ; -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >w : Symbol(w, Decl(file.tsx, 11, 5)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxEmit1.symbols b/testdata/baselines/reference/submodule/conformance/tsxEmit1.symbols index dbdc926212e..687a92becb5 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxEmit1.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxEmit1.symbols @@ -20,76 +20,76 @@ var p; var selfClosed1 =
; >selfClosed1 : Symbol(selfClosed1, Decl(file.tsx, 8, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var selfClosed2 =
; >selfClosed2 : Symbol(selfClosed2, Decl(file.tsx, 9, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 9, 22)) var selfClosed3 =
; >selfClosed3 : Symbol(selfClosed3, Decl(file.tsx, 10, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 10, 22)) var selfClosed4 =
; >selfClosed4 : Symbol(selfClosed4, Decl(file.tsx, 11, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 11, 22)) >y : Symbol(y, Decl(file.tsx, 11, 28)) var selfClosed5 =
; >selfClosed5 : Symbol(selfClosed5, Decl(file.tsx, 12, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 12, 22)) >y : Symbol(y, Decl(file.tsx, 12, 28)) var selfClosed6 =
; >selfClosed6 : Symbol(selfClosed6, Decl(file.tsx, 13, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 13, 22)) >y : Symbol(y, Decl(file.tsx, 13, 30)) var selfClosed7 =
; >selfClosed7 : Symbol(selfClosed7, Decl(file.tsx, 14, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 14, 22)) >p : Symbol(p, Decl(file.tsx, 7, 3)) >y : Symbol(y, Decl(file.tsx, 14, 28)) var openClosed1 =
; >openClosed1 : Symbol(openClosed1, Decl(file.tsx, 16, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var openClosed2 =
foo
; >openClosed2 : Symbol(openClosed2, Decl(file.tsx, 17, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >n : Symbol(n, Decl(file.tsx, 17, 22)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var openClosed3 =
{p}
; >openClosed3 : Symbol(openClosed3, Decl(file.tsx, 18, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >n : Symbol(n, Decl(file.tsx, 18, 22)) >p : Symbol(p, Decl(file.tsx, 7, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var openClosed4 =
{p < p}
; >openClosed4 : Symbol(openClosed4, Decl(file.tsx, 19, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >n : Symbol(n, Decl(file.tsx, 19, 22)) >p : Symbol(p, Decl(file.tsx, 7, 3)) >p : Symbol(p, Decl(file.tsx, 7, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var openClosed5 =
{p > p}
; >openClosed5 : Symbol(openClosed5, Decl(file.tsx, 20, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >n : Symbol(n, Decl(file.tsx, 20, 22)) >p : Symbol(p, Decl(file.tsx, 7, 3)) >p : Symbol(p, Decl(file.tsx, 7, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) class SomeClass { >SomeClass : Symbol(SomeClass, Decl(file.tsx, 20, 43)) @@ -99,67 +99,67 @@ class SomeClass { var rewrites1 =
{() => this}
; >rewrites1 : Symbol(rewrites1, Decl(file.tsx, 24, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >this : Symbol(SomeClass, Decl(file.tsx, 20, 43)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var rewrites2 =
{[p, ...p, p]}
; >rewrites2 : Symbol(rewrites2, Decl(file.tsx, 25, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >p : Symbol(p, Decl(file.tsx, 7, 3)) >p : Symbol(p, Decl(file.tsx, 7, 3)) >p : Symbol(p, Decl(file.tsx, 7, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var rewrites3 =
{{p}}
; >rewrites3 : Symbol(rewrites3, Decl(file.tsx, 26, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >p : Symbol(p, Decl(file.tsx, 26, 25)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var rewrites4 =
this}>
; >rewrites4 : Symbol(rewrites4, Decl(file.tsx, 28, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >a : Symbol(a, Decl(file.tsx, 28, 22)) >this : Symbol(SomeClass, Decl(file.tsx, 20, 43)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var rewrites5 =
; >rewrites5 : Symbol(rewrites5, Decl(file.tsx, 29, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >a : Symbol(a, Decl(file.tsx, 29, 22)) >p : Symbol(p, Decl(file.tsx, 7, 3)) >p : Symbol(p, Decl(file.tsx, 7, 3)) >p : Symbol(p, Decl(file.tsx, 7, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var rewrites6 =
; >rewrites6 : Symbol(rewrites6, Decl(file.tsx, 30, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >a : Symbol(a, Decl(file.tsx, 30, 22)) >p : Symbol(p, Decl(file.tsx, 30, 27)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) } } var whitespace1 =
; >whitespace1 : Symbol(whitespace1, Decl(file.tsx, 34, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var whitespace2 =
{p}
; >whitespace2 : Symbol(whitespace2, Decl(file.tsx, 35, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >p : Symbol(p, Decl(file.tsx, 7, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var whitespace3 =
>whitespace3 : Symbol(whitespace3, Decl(file.tsx, 36, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) {p} >p : Symbol(p, Decl(file.tsx, 7, 3))
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxEmit1.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxEmit1.symbols.diff deleted file mode 100644 index 69a1ff9effa..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxEmit1.symbols.diff +++ /dev/null @@ -1,184 +0,0 @@ ---- old.tsxEmit1.symbols -+++ new.tsxEmit1.symbols -@@= skipped -19, +19 lines =@@ - - var selfClosed1 =
; - >selfClosed1 : Symbol(selfClosed1, Decl(file.tsx, 8, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var selfClosed2 =
; - >selfClosed2 : Symbol(selfClosed2, Decl(file.tsx, 9, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 9, 22)) - - var selfClosed3 =
; - >selfClosed3 : Symbol(selfClosed3, Decl(file.tsx, 10, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 10, 22)) - - var selfClosed4 =
; - >selfClosed4 : Symbol(selfClosed4, Decl(file.tsx, 11, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 11, 22)) - >y : Symbol(y, Decl(file.tsx, 11, 28)) - - var selfClosed5 =
; - >selfClosed5 : Symbol(selfClosed5, Decl(file.tsx, 12, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 12, 22)) - >y : Symbol(y, Decl(file.tsx, 12, 28)) - - var selfClosed6 =
; - >selfClosed6 : Symbol(selfClosed6, Decl(file.tsx, 13, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 13, 22)) - >y : Symbol(y, Decl(file.tsx, 13, 30)) - - var selfClosed7 =
; - >selfClosed7 : Symbol(selfClosed7, Decl(file.tsx, 14, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 14, 22)) - >p : Symbol(p, Decl(file.tsx, 7, 3)) - >y : Symbol(y, Decl(file.tsx, 14, 28)) - - var openClosed1 =
; - >openClosed1 : Symbol(openClosed1, Decl(file.tsx, 16, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var openClosed2 =
foo
; - >openClosed2 : Symbol(openClosed2, Decl(file.tsx, 17, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >n : Symbol(n, Decl(file.tsx, 17, 22)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var openClosed3 =
{p}
; - >openClosed3 : Symbol(openClosed3, Decl(file.tsx, 18, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >n : Symbol(n, Decl(file.tsx, 18, 22)) - >p : Symbol(p, Decl(file.tsx, 7, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var openClosed4 =
{p < p}
; - >openClosed4 : Symbol(openClosed4, Decl(file.tsx, 19, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >n : Symbol(n, Decl(file.tsx, 19, 22)) - >p : Symbol(p, Decl(file.tsx, 7, 3)) - >p : Symbol(p, Decl(file.tsx, 7, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var openClosed5 =
{p > p}
; - >openClosed5 : Symbol(openClosed5, Decl(file.tsx, 20, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >n : Symbol(n, Decl(file.tsx, 20, 22)) - >p : Symbol(p, Decl(file.tsx, 7, 3)) - >p : Symbol(p, Decl(file.tsx, 7, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - class SomeClass { - >SomeClass : Symbol(SomeClass, Decl(file.tsx, 20, 43)) -@@= skipped -79, +79 lines =@@ - - var rewrites1 =
{() => this}
; - >rewrites1 : Symbol(rewrites1, Decl(file.tsx, 24, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >this : Symbol(SomeClass, Decl(file.tsx, 20, 43)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var rewrites2 =
{[p, ...p, p]}
; - >rewrites2 : Symbol(rewrites2, Decl(file.tsx, 25, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->p : Symbol(p, Decl(file.tsx, 7, 3)) -->p : Symbol(p, Decl(file.tsx, 7, 3)) -->p : Symbol(p, Decl(file.tsx, 7, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>p : Symbol(p, Decl(file.tsx, 7, 3)) -+>p : Symbol(p, Decl(file.tsx, 7, 3)) -+>p : Symbol(p, Decl(file.tsx, 7, 3)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var rewrites3 =
{{p}}
; - >rewrites3 : Symbol(rewrites3, Decl(file.tsx, 26, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >p : Symbol(p, Decl(file.tsx, 26, 25)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var rewrites4 =
this}>
; - >rewrites4 : Symbol(rewrites4, Decl(file.tsx, 28, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >a : Symbol(a, Decl(file.tsx, 28, 22)) - >this : Symbol(SomeClass, Decl(file.tsx, 20, 43)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var rewrites5 =
; - >rewrites5 : Symbol(rewrites5, Decl(file.tsx, 29, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >a : Symbol(a, Decl(file.tsx, 29, 22)) - >p : Symbol(p, Decl(file.tsx, 7, 3)) - >p : Symbol(p, Decl(file.tsx, 7, 3)) - >p : Symbol(p, Decl(file.tsx, 7, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var rewrites6 =
; - >rewrites6 : Symbol(rewrites6, Decl(file.tsx, 30, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >a : Symbol(a, Decl(file.tsx, 30, 22)) - >p : Symbol(p, Decl(file.tsx, 30, 27)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - } - } - - var whitespace1 =
; - >whitespace1 : Symbol(whitespace1, Decl(file.tsx, 34, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var whitespace2 =
{p}
; - >whitespace2 : Symbol(whitespace2, Decl(file.tsx, 35, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >p : Symbol(p, Decl(file.tsx, 7, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var whitespace3 =
- >whitespace3 : Symbol(whitespace3, Decl(file.tsx, 36, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - {p} - >p : Symbol(p, Decl(file.tsx, 7, 3)) - -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxEmit2.symbols b/testdata/baselines/reference/submodule/conformance/tsxEmit2.symbols index eb863d5a7db..f94451232f5 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxEmit2.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxEmit2.symbols @@ -22,44 +22,44 @@ var p1: any, p2: any, p3: any; var spreads1 =
{p2}
; >spreads1 : Symbol(spreads1, Decl(file.tsx, 8, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >p1 : Symbol(p1, Decl(file.tsx, 7, 3)) >p2 : Symbol(p2, Decl(file.tsx, 7, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var spreads2 =
{p2}
; >spreads2 : Symbol(spreads2, Decl(file.tsx, 9, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >p1 : Symbol(p1, Decl(file.tsx, 7, 3)) >p2 : Symbol(p2, Decl(file.tsx, 7, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var spreads3 =
{p2}
; >spreads3 : Symbol(spreads3, Decl(file.tsx, 10, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 10, 19)) >p3 : Symbol(p3, Decl(file.tsx, 7, 21)) >p1 : Symbol(p1, Decl(file.tsx, 7, 3)) >p2 : Symbol(p2, Decl(file.tsx, 7, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var spreads4 =
{p2}
; >spreads4 : Symbol(spreads4, Decl(file.tsx, 11, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >p1 : Symbol(p1, Decl(file.tsx, 7, 3)) >x : Symbol(x, Decl(file.tsx, 11, 27)) >p3 : Symbol(p3, Decl(file.tsx, 7, 21)) >p2 : Symbol(p2, Decl(file.tsx, 7, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var spreads5 =
{p2}
; >spreads5 : Symbol(spreads5, Decl(file.tsx, 12, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 12, 19)) >p2 : Symbol(p2, Decl(file.tsx, 7, 12)) >p1 : Symbol(p1, Decl(file.tsx, 7, 3)) >y : Symbol(y, Decl(file.tsx, 12, 34)) >p3 : Symbol(p3, Decl(file.tsx, 7, 21)) >p2 : Symbol(p2, Decl(file.tsx, 7, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxEmit2.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxEmit2.symbols.diff deleted file mode 100644 index 51ead7b6bdd..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxEmit2.symbols.diff +++ /dev/null @@ -1,56 +0,0 @@ ---- old.tsxEmit2.symbols -+++ new.tsxEmit2.symbols -@@= skipped -21, +21 lines =@@ - - var spreads1 =
{p2}
; - >spreads1 : Symbol(spreads1, Decl(file.tsx, 8, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >p1 : Symbol(p1, Decl(file.tsx, 7, 3)) - >p2 : Symbol(p2, Decl(file.tsx, 7, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var spreads2 =
{p2}
; - >spreads2 : Symbol(spreads2, Decl(file.tsx, 9, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >p1 : Symbol(p1, Decl(file.tsx, 7, 3)) - >p2 : Symbol(p2, Decl(file.tsx, 7, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var spreads3 =
{p2}
; - >spreads3 : Symbol(spreads3, Decl(file.tsx, 10, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 10, 19)) - >p3 : Symbol(p3, Decl(file.tsx, 7, 21)) - >p1 : Symbol(p1, Decl(file.tsx, 7, 3)) - >p2 : Symbol(p2, Decl(file.tsx, 7, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var spreads4 =
{p2}
; - >spreads4 : Symbol(spreads4, Decl(file.tsx, 11, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >p1 : Symbol(p1, Decl(file.tsx, 7, 3)) - >x : Symbol(x, Decl(file.tsx, 11, 27)) - >p3 : Symbol(p3, Decl(file.tsx, 7, 21)) - >p2 : Symbol(p2, Decl(file.tsx, 7, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var spreads5 =
{p2}
; - >spreads5 : Symbol(spreads5, Decl(file.tsx, 12, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 12, 19)) - >p2 : Symbol(p2, Decl(file.tsx, 7, 12)) - >p1 : Symbol(p1, Decl(file.tsx, 7, 3)) - >y : Symbol(y, Decl(file.tsx, 12, 34)) - >p3 : Symbol(p3, Decl(file.tsx, 7, 21)) - >p2 : Symbol(p2, Decl(file.tsx, 7, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxFragmentPreserveEmit.symbols b/testdata/baselines/reference/submodule/conformance/tsxFragmentPreserveEmit.symbols index 8b9245622b2..633cd3cc3ad 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxFragmentPreserveEmit.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxFragmentPreserveEmit.symbols @@ -22,19 +22,19 @@ declare var React: any; < /*starting wrap*/ >; // comments in the tags <>hi; // text inside <>hi
bye
; // children ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) <>1<>2.12.23; // nested fragments ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) <>#; // # would cause scanning error if not in jsxtext diff --git a/testdata/baselines/reference/submodule/conformance/tsxFragmentPreserveEmit.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxFragmentPreserveEmit.symbols.diff deleted file mode 100644 index aa65a99ff02..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxFragmentPreserveEmit.symbols.diff +++ /dev/null @@ -1,34 +0,0 @@ ---- old.tsxFragmentPreserveEmit.symbols -+++ new.tsxFragmentPreserveEmit.symbols -@@= skipped -21, +21 lines =@@ - < /*starting wrap*/ >; // comments in the tags - <>hi; // text inside - <>hi
bye
; // children -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - <>1<>2.12.23; // nested fragments -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - <>#; // # would cause scanning error if not in jsxtext \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/tsxFragmentReactEmit.symbols b/testdata/baselines/reference/submodule/conformance/tsxFragmentReactEmit.symbols index a401c70ffaf..59350f151e0 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxFragmentReactEmit.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxFragmentReactEmit.symbols @@ -22,19 +22,19 @@ declare var React: any; < /*starting wrap*/ >; // comments in the tags <>hi; // text inside <>hi
bye
; // children ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) <>1<>2.12.23; // nested fragments ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) <>#; // # would cause scanning error if not in jsxtext diff --git a/testdata/baselines/reference/submodule/conformance/tsxFragmentReactEmit.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxFragmentReactEmit.symbols.diff deleted file mode 100644 index 4474983e62c..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxFragmentReactEmit.symbols.diff +++ /dev/null @@ -1,34 +0,0 @@ ---- old.tsxFragmentReactEmit.symbols -+++ new.tsxFragmentReactEmit.symbols -@@= skipped -21, +21 lines =@@ - < /*starting wrap*/ >; // comments in the tags - <>hi; // text inside - <>hi
bye
; // children -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - <>1<>2.12.23; // nested fragments -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->span : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>span : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - <>#; // # would cause scanning error if not in jsxtext \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmit1.symbols b/testdata/baselines/reference/submodule/conformance/tsxReactEmit1.symbols index 7702db7e00f..5b0f8a5440b 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmit1.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxReactEmit1.symbols @@ -22,39 +22,39 @@ var p; var selfClosed1 =
; >selfClosed1 : Symbol(selfClosed1, Decl(file.tsx, 9, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var selfClosed2 =
; >selfClosed2 : Symbol(selfClosed2, Decl(file.tsx, 10, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 10, 22)) var selfClosed3 =
; >selfClosed3 : Symbol(selfClosed3, Decl(file.tsx, 11, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 11, 22)) var selfClosed4 =
; >selfClosed4 : Symbol(selfClosed4, Decl(file.tsx, 12, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 12, 22)) >y : Symbol(y, Decl(file.tsx, 12, 28)) var selfClosed5 =
; >selfClosed5 : Symbol(selfClosed5, Decl(file.tsx, 13, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 13, 22)) >y : Symbol(y, Decl(file.tsx, 13, 28)) var selfClosed6 =
; >selfClosed6 : Symbol(selfClosed6, Decl(file.tsx, 14, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 14, 22)) >y : Symbol(y, Decl(file.tsx, 14, 30)) var selfClosed7 =
; >selfClosed7 : Symbol(selfClosed7, Decl(file.tsx, 15, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 15, 22)) >p : Symbol(p, Decl(file.tsx, 8, 3)) >y : Symbol(y, Decl(file.tsx, 15, 28)) @@ -62,38 +62,38 @@ var selfClosed7 =
; var openClosed1 =
; >openClosed1 : Symbol(openClosed1, Decl(file.tsx, 17, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var openClosed2 =
foo
; >openClosed2 : Symbol(openClosed2, Decl(file.tsx, 18, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >n : Symbol(n, Decl(file.tsx, 18, 22)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var openClosed3 =
{p}
; >openClosed3 : Symbol(openClosed3, Decl(file.tsx, 19, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >n : Symbol(n, Decl(file.tsx, 19, 22)) >p : Symbol(p, Decl(file.tsx, 8, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var openClosed4 =
{p < p}
; >openClosed4 : Symbol(openClosed4, Decl(file.tsx, 20, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >n : Symbol(n, Decl(file.tsx, 20, 22)) >p : Symbol(p, Decl(file.tsx, 8, 3)) >p : Symbol(p, Decl(file.tsx, 8, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var openClosed5 =
{p > p}
; >openClosed5 : Symbol(openClosed5, Decl(file.tsx, 21, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >n : Symbol(n, Decl(file.tsx, 21, 22)) >b : Symbol(b, Decl(file.tsx, 21, 28)) >p : Symbol(p, Decl(file.tsx, 8, 3)) >p : Symbol(p, Decl(file.tsx, 8, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) class SomeClass { >SomeClass : Symbol(SomeClass, Decl(file.tsx, 21, 45)) @@ -103,67 +103,67 @@ class SomeClass { var rewrites1 =
{() => this}
; >rewrites1 : Symbol(rewrites1, Decl(file.tsx, 25, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >this : Symbol(SomeClass, Decl(file.tsx, 21, 45)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var rewrites2 =
{[p, ...p, p]}
; >rewrites2 : Symbol(rewrites2, Decl(file.tsx, 26, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >p : Symbol(p, Decl(file.tsx, 8, 3)) >p : Symbol(p, Decl(file.tsx, 8, 3)) >p : Symbol(p, Decl(file.tsx, 8, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var rewrites3 =
{{p}}
; >rewrites3 : Symbol(rewrites3, Decl(file.tsx, 27, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >p : Symbol(p, Decl(file.tsx, 27, 25)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var rewrites4 =
this}>
; >rewrites4 : Symbol(rewrites4, Decl(file.tsx, 29, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >a : Symbol(a, Decl(file.tsx, 29, 22)) >this : Symbol(SomeClass, Decl(file.tsx, 21, 45)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var rewrites5 =
; >rewrites5 : Symbol(rewrites5, Decl(file.tsx, 30, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >a : Symbol(a, Decl(file.tsx, 30, 22)) >p : Symbol(p, Decl(file.tsx, 8, 3)) >p : Symbol(p, Decl(file.tsx, 8, 3)) >p : Symbol(p, Decl(file.tsx, 8, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var rewrites6 =
; >rewrites6 : Symbol(rewrites6, Decl(file.tsx, 31, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >a : Symbol(a, Decl(file.tsx, 31, 22)) >p : Symbol(p, Decl(file.tsx, 31, 27)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) } } var whitespace1 =
; >whitespace1 : Symbol(whitespace1, Decl(file.tsx, 35, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var whitespace2 =
{p}
; >whitespace2 : Symbol(whitespace2, Decl(file.tsx, 36, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >p : Symbol(p, Decl(file.tsx, 8, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var whitespace3 =
>whitespace3 : Symbol(whitespace3, Decl(file.tsx, 37, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) {p} >p : Symbol(p, Decl(file.tsx, 8, 3))
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmit1.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxReactEmit1.symbols.diff deleted file mode 100644 index 8bcfbacb43e..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmit1.symbols.diff +++ /dev/null @@ -1,186 +0,0 @@ ---- old.tsxReactEmit1.symbols -+++ new.tsxReactEmit1.symbols -@@= skipped -21, +21 lines =@@ - - var selfClosed1 =
; - >selfClosed1 : Symbol(selfClosed1, Decl(file.tsx, 9, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var selfClosed2 =
; - >selfClosed2 : Symbol(selfClosed2, Decl(file.tsx, 10, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 10, 22)) - - var selfClosed3 =
; - >selfClosed3 : Symbol(selfClosed3, Decl(file.tsx, 11, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 11, 22)) - - var selfClosed4 =
; - >selfClosed4 : Symbol(selfClosed4, Decl(file.tsx, 12, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 12, 22)) - >y : Symbol(y, Decl(file.tsx, 12, 28)) - - var selfClosed5 =
; - >selfClosed5 : Symbol(selfClosed5, Decl(file.tsx, 13, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 13, 22)) - >y : Symbol(y, Decl(file.tsx, 13, 28)) - - var selfClosed6 =
; - >selfClosed6 : Symbol(selfClosed6, Decl(file.tsx, 14, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 14, 22)) - >y : Symbol(y, Decl(file.tsx, 14, 30)) - - var selfClosed7 =
; - >selfClosed7 : Symbol(selfClosed7, Decl(file.tsx, 15, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 15, 22)) - >p : Symbol(p, Decl(file.tsx, 8, 3)) - >y : Symbol(y, Decl(file.tsx, 15, 28)) -@@= skipped -40, +40 lines =@@ - - var openClosed1 =
; - >openClosed1 : Symbol(openClosed1, Decl(file.tsx, 17, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var openClosed2 =
foo
; - >openClosed2 : Symbol(openClosed2, Decl(file.tsx, 18, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >n : Symbol(n, Decl(file.tsx, 18, 22)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var openClosed3 =
{p}
; - >openClosed3 : Symbol(openClosed3, Decl(file.tsx, 19, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >n : Symbol(n, Decl(file.tsx, 19, 22)) - >p : Symbol(p, Decl(file.tsx, 8, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var openClosed4 =
{p < p}
; - >openClosed4 : Symbol(openClosed4, Decl(file.tsx, 20, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >n : Symbol(n, Decl(file.tsx, 20, 22)) - >p : Symbol(p, Decl(file.tsx, 8, 3)) - >p : Symbol(p, Decl(file.tsx, 8, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var openClosed5 =
{p > p}
; - >openClosed5 : Symbol(openClosed5, Decl(file.tsx, 21, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >n : Symbol(n, Decl(file.tsx, 21, 22)) - >b : Symbol(b, Decl(file.tsx, 21, 28)) - >p : Symbol(p, Decl(file.tsx, 8, 3)) - >p : Symbol(p, Decl(file.tsx, 8, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - class SomeClass { - >SomeClass : Symbol(SomeClass, Decl(file.tsx, 21, 45)) -@@= skipped -41, +41 lines =@@ - - var rewrites1 =
{() => this}
; - >rewrites1 : Symbol(rewrites1, Decl(file.tsx, 25, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >this : Symbol(SomeClass, Decl(file.tsx, 21, 45)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var rewrites2 =
{[p, ...p, p]}
; - >rewrites2 : Symbol(rewrites2, Decl(file.tsx, 26, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->p : Symbol(p, Decl(file.tsx, 8, 3)) -->p : Symbol(p, Decl(file.tsx, 8, 3)) -->p : Symbol(p, Decl(file.tsx, 8, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>p : Symbol(p, Decl(file.tsx, 8, 3)) -+>p : Symbol(p, Decl(file.tsx, 8, 3)) -+>p : Symbol(p, Decl(file.tsx, 8, 3)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var rewrites3 =
{{p}}
; - >rewrites3 : Symbol(rewrites3, Decl(file.tsx, 27, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >p : Symbol(p, Decl(file.tsx, 27, 25)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var rewrites4 =
this}>
; - >rewrites4 : Symbol(rewrites4, Decl(file.tsx, 29, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >a : Symbol(a, Decl(file.tsx, 29, 22)) - >this : Symbol(SomeClass, Decl(file.tsx, 21, 45)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var rewrites5 =
; - >rewrites5 : Symbol(rewrites5, Decl(file.tsx, 30, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >a : Symbol(a, Decl(file.tsx, 30, 22)) - >p : Symbol(p, Decl(file.tsx, 8, 3)) - >p : Symbol(p, Decl(file.tsx, 8, 3)) - >p : Symbol(p, Decl(file.tsx, 8, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var rewrites6 =
; - >rewrites6 : Symbol(rewrites6, Decl(file.tsx, 31, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >a : Symbol(a, Decl(file.tsx, 31, 22)) - >p : Symbol(p, Decl(file.tsx, 31, 27)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - } - } - - var whitespace1 =
; - >whitespace1 : Symbol(whitespace1, Decl(file.tsx, 35, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var whitespace2 =
{p}
; - >whitespace2 : Symbol(whitespace2, Decl(file.tsx, 36, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >p : Symbol(p, Decl(file.tsx, 8, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var whitespace3 =
- >whitespace3 : Symbol(whitespace3, Decl(file.tsx, 37, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - {p} - >p : Symbol(p, Decl(file.tsx, 8, 3)) - -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmit2.symbols b/testdata/baselines/reference/submodule/conformance/tsxReactEmit2.symbols index 43f76da0fbb..9c215b9d661 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmit2.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxReactEmit2.symbols @@ -24,44 +24,44 @@ var p1: any, p2: any, p3: any; var spreads1 =
{p2}
; >spreads1 : Symbol(spreads1, Decl(file.tsx, 9, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >p1 : Symbol(p1, Decl(file.tsx, 8, 3)) >p2 : Symbol(p2, Decl(file.tsx, 8, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var spreads2 =
{p2}
; >spreads2 : Symbol(spreads2, Decl(file.tsx, 10, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >p1 : Symbol(p1, Decl(file.tsx, 8, 3)) >p2 : Symbol(p2, Decl(file.tsx, 8, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var spreads3 =
{p2}
; >spreads3 : Symbol(spreads3, Decl(file.tsx, 11, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 11, 19)) >p3 : Symbol(p3, Decl(file.tsx, 8, 21)) >p1 : Symbol(p1, Decl(file.tsx, 8, 3)) >p2 : Symbol(p2, Decl(file.tsx, 8, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var spreads4 =
{p2}
; >spreads4 : Symbol(spreads4, Decl(file.tsx, 12, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >p1 : Symbol(p1, Decl(file.tsx, 8, 3)) >x : Symbol(x, Decl(file.tsx, 12, 27)) >p3 : Symbol(p3, Decl(file.tsx, 8, 21)) >p2 : Symbol(p2, Decl(file.tsx, 8, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var spreads5 =
{p2}
; >spreads5 : Symbol(spreads5, Decl(file.tsx, 13, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 13, 19)) >p2 : Symbol(p2, Decl(file.tsx, 8, 12)) >p1 : Symbol(p1, Decl(file.tsx, 8, 3)) >y : Symbol(y, Decl(file.tsx, 13, 34)) >p3 : Symbol(p3, Decl(file.tsx, 8, 21)) >p2 : Symbol(p2, Decl(file.tsx, 8, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmit2.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxReactEmit2.symbols.diff deleted file mode 100644 index e69ff073d54..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmit2.symbols.diff +++ /dev/null @@ -1,56 +0,0 @@ ---- old.tsxReactEmit2.symbols -+++ new.tsxReactEmit2.symbols -@@= skipped -23, +23 lines =@@ - - var spreads1 =
{p2}
; - >spreads1 : Symbol(spreads1, Decl(file.tsx, 9, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >p1 : Symbol(p1, Decl(file.tsx, 8, 3)) - >p2 : Symbol(p2, Decl(file.tsx, 8, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var spreads2 =
{p2}
; - >spreads2 : Symbol(spreads2, Decl(file.tsx, 10, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >p1 : Symbol(p1, Decl(file.tsx, 8, 3)) - >p2 : Symbol(p2, Decl(file.tsx, 8, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var spreads3 =
{p2}
; - >spreads3 : Symbol(spreads3, Decl(file.tsx, 11, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 11, 19)) - >p3 : Symbol(p3, Decl(file.tsx, 8, 21)) - >p1 : Symbol(p1, Decl(file.tsx, 8, 3)) - >p2 : Symbol(p2, Decl(file.tsx, 8, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var spreads4 =
{p2}
; - >spreads4 : Symbol(spreads4, Decl(file.tsx, 12, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >p1 : Symbol(p1, Decl(file.tsx, 8, 3)) - >x : Symbol(x, Decl(file.tsx, 12, 27)) - >p3 : Symbol(p3, Decl(file.tsx, 8, 21)) - >p2 : Symbol(p2, Decl(file.tsx, 8, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var spreads5 =
{p2}
; - >spreads5 : Symbol(spreads5, Decl(file.tsx, 13, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 13, 19)) - >p2 : Symbol(p2, Decl(file.tsx, 8, 12)) - >p1 : Symbol(p1, Decl(file.tsx, 8, 3)) - >y : Symbol(y, Decl(file.tsx, 13, 34)) - >p3 : Symbol(p3, Decl(file.tsx, 8, 21)) - >p2 : Symbol(p2, Decl(file.tsx, 8, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmit4.symbols b/testdata/baselines/reference/submodule/conformance/tsxReactEmit4.symbols index 3c9a286de47..ea559d521c5 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmit4.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxReactEmit4.symbols @@ -22,17 +22,17 @@ var p: any; var openClosed1 =
>openClosed1 : Symbol(openClosed1, Decl(file.tsx, 9, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) {blah}
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Should emit React.__spread({}, p, {x: 0}) var spread1 =
; >spread1 : Symbol(spread1, Decl(file.tsx, 16, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >p : Symbol(p, Decl(file.tsx, 8, 3)) >x : Symbol(x, Decl(file.tsx, 16, 25)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmit4.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxReactEmit4.symbols.diff deleted file mode 100644 index 43bb11f0f74..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmit4.symbols.diff +++ /dev/null @@ -1,22 +0,0 @@ ---- old.tsxReactEmit4.symbols -+++ new.tsxReactEmit4.symbols -@@= skipped -21, +21 lines =@@ - - var openClosed1 =
- >openClosed1 : Symbol(openClosed1, Decl(file.tsx, 9, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - {blah} - -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Should emit React.__spread({}, p, {x: 0}) - var spread1 =
; - >spread1 : Symbol(spread1, Decl(file.tsx, 16, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >p : Symbol(p, Decl(file.tsx, 8, 3)) - >x : Symbol(x, Decl(file.tsx, 16, 25)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmit5.symbols b/testdata/baselines/reference/submodule/conformance/tsxReactEmit5.symbols index e05bf3eb507..54bd1c7292b 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmit5.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxReactEmit5.symbols @@ -30,7 +30,7 @@ var foo: any; var spread1 =
; >spread1 : Symbol(spread1, Decl(react-consumer.tsx, 4, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(react-consumer.tsx, 4, 18)) >foo : Symbol(foo, Decl(react-consumer.tsx, 3, 3)) >y : Symbol(y, Decl(react-consumer.tsx, 4, 32)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmit5.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxReactEmit5.symbols.diff deleted file mode 100644 index deafaaf0ee0..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmit5.symbols.diff +++ /dev/null @@ -1,11 +0,0 @@ ---- old.tsxReactEmit5.symbols -+++ new.tsxReactEmit5.symbols -@@= skipped -29, +29 lines =@@ - - var spread1 =
; - >spread1 : Symbol(spread1, Decl(react-consumer.tsx, 4, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(react-consumer.tsx, 4, 18)) - >foo : Symbol(foo, Decl(react-consumer.tsx, 3, 3)) - >y : Symbol(y, Decl(react-consumer.tsx, 4, 32)) \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmit6.symbols b/testdata/baselines/reference/submodule/conformance/tsxReactEmit6.symbols index 495ac7e23d7..e4e5520b616 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmit6.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxReactEmit6.symbols @@ -33,7 +33,7 @@ namespace M { var spread1 =
; >spread1 : Symbol(spread1, Decl(react-consumer.tsx, 8, 4)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(react-consumer.tsx, 8, 19)) >foo : Symbol(foo, Decl(react-consumer.tsx, 7, 4)) >y : Symbol(y, Decl(react-consumer.tsx, 8, 33)) @@ -41,8 +41,8 @@ namespace M { // Quotes var x =
This "quote" thing
; >x : Symbol(x, Decl(react-consumer.tsx, 11, 4)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) } diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmit6.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxReactEmit6.symbols.diff deleted file mode 100644 index 6eacb50b071..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmit6.symbols.diff +++ /dev/null @@ -1,21 +0,0 @@ ---- old.tsxReactEmit6.symbols -+++ new.tsxReactEmit6.symbols -@@= skipped -32, +32 lines =@@ - - var spread1 =
; - >spread1 : Symbol(spread1, Decl(react-consumer.tsx, 8, 4)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(react-consumer.tsx, 8, 19)) - >foo : Symbol(foo, Decl(react-consumer.tsx, 7, 4)) - >y : Symbol(y, Decl(react-consumer.tsx, 8, 33)) -@@= skipped -8, +8 lines =@@ - // Quotes - var x =
This "quote" thing
; - >x : Symbol(x, Decl(react-consumer.tsx, 11, 4)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - } - diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmit7.symbols b/testdata/baselines/reference/submodule/conformance/tsxReactEmit7.symbols index d19cb6f3281..45d6e55d90f 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmit7.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxReactEmit7.symbols @@ -17,56 +17,56 @@ declare namespace JSX { var m =
; >m : Symbol(m, Decl(file.tsx, 7, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x-y : Symbol(x-y, Decl(file.tsx, 7, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var n =
; >n : Symbol(n, Decl(file.tsx, 8, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >xx-y : Symbol(xx-y, Decl(file.tsx, 8, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var o =
; >o : Symbol(o, Decl(file.tsx, 9, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x-yy : Symbol(x-yy, Decl(file.tsx, 9, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var p =
; >p : Symbol(p, Decl(file.tsx, 10, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >xx-yy : Symbol(xx-yy, Decl(file.tsx, 10, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Investigation var a =
; >a : Symbol(a, Decl(file.tsx, 13, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >x : Symbol(x, Decl(file.tsx, 13, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var b =
; >b : Symbol(b, Decl(file.tsx, 14, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >xx : Symbol(xx, Decl(file.tsx, 14, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var c =
; >c : Symbol(c, Decl(file.tsx, 15, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >xxx : Symbol(xxx, Decl(file.tsx, 15, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var d =
; >d : Symbol(d, Decl(file.tsx, 16, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >xxxx : Symbol(xxxx, Decl(file.tsx, 16, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) var e =
; >e : Symbol(e, Decl(file.tsx, 17, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >xxxxx : Symbol(xxxxx, Decl(file.tsx, 17, 12)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmit7.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxReactEmit7.symbols.diff deleted file mode 100644 index cb0b1568419..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmit7.symbols.diff +++ /dev/null @@ -1,76 +0,0 @@ ---- old.tsxReactEmit7.symbols -+++ new.tsxReactEmit7.symbols -@@= skipped -16, +16 lines =@@ - - var m =
; - >m : Symbol(m, Decl(file.tsx, 7, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x-y : Symbol(x-y, Decl(file.tsx, 7, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var n =
; - >n : Symbol(n, Decl(file.tsx, 8, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >xx-y : Symbol(xx-y, Decl(file.tsx, 8, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var o =
; - >o : Symbol(o, Decl(file.tsx, 9, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x-yy : Symbol(x-yy, Decl(file.tsx, 9, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var p =
; - >p : Symbol(p, Decl(file.tsx, 10, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >xx-yy : Symbol(xx-yy, Decl(file.tsx, 10, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Investigation - var a =
; - >a : Symbol(a, Decl(file.tsx, 13, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >x : Symbol(x, Decl(file.tsx, 13, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var b =
; - >b : Symbol(b, Decl(file.tsx, 14, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >xx : Symbol(xx, Decl(file.tsx, 14, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var c =
; - >c : Symbol(c, Decl(file.tsx, 15, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >xxx : Symbol(xxx, Decl(file.tsx, 15, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var d =
; - >d : Symbol(d, Decl(file.tsx, 16, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >xxxx : Symbol(xxxx, Decl(file.tsx, 16, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - var e =
; - >e : Symbol(e, Decl(file.tsx, 17, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >xxxxx : Symbol(xxxxx, Decl(file.tsx, 17, 12)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmitEntities.symbols b/testdata/baselines/reference/submodule/conformance/tsxReactEmitEntities.symbols index 774c35ca38b..475bd8a566f 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmitEntities.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxReactEmitEntities.symbols @@ -18,42 +18,42 @@ declare var React: any; >React : Symbol(React, Decl(file.tsx, 6, 11))
Dot goes here: · ¬AnEntity;
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30))
Be careful of "-ed strings!
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30))
{{braces}}
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Escapes do nothing
\n
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Also works in string literal attributes
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >attr : Symbol(attr, Decl(file.tsx, 15, 4)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Does not happen for a string literal that happens to be inside an attribute (and escapes then work)
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >attr : Symbol(attr, Decl(file.tsx, 17, 4)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Preserves single quotes
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >attr : Symbol(attr, Decl(file.tsx, 19, 4)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // https://github.com/microsoft/TypeScript/issues/35732
🐈🐕🐇🐑
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmitEntities.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxReactEmitEntities.symbols.diff deleted file mode 100644 index 53147c13506..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmitEntities.symbols.diff +++ /dev/null @@ -1,60 +0,0 @@ ---- old.tsxReactEmitEntities.symbols -+++ new.tsxReactEmitEntities.symbols -@@= skipped -17, +17 lines =@@ - >React : Symbol(React, Decl(file.tsx, 6, 11)) - -
Dot goes here: · ¬AnEntity;
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - -
Be careful of "-ed strings!
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - -
{{braces}}
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Escapes do nothing -
\n
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Also works in string literal attributes -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >attr : Symbol(attr, Decl(file.tsx, 15, 4)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Does not happen for a string literal that happens to be inside an attribute (and escapes then work) -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >attr : Symbol(attr, Decl(file.tsx, 17, 4)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Preserves single quotes -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >attr : Symbol(attr, Decl(file.tsx, 19, 4)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // https://github.com/microsoft/TypeScript/issues/35732 -
🐈🐕🐇🐑
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmitWhitespace.symbols b/testdata/baselines/reference/submodule/conformance/tsxReactEmitWhitespace.symbols index c9d916a1663..397c88f13c5 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmitWhitespace.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxReactEmitWhitespace.symbols @@ -25,88 +25,88 @@ var p = 0; // Emit " "
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Emit " ", p, " "
{p}
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) >p : Symbol(p, Decl(file.tsx, 11, 3)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Emit only p
->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) {p} >p : Symbol(p, Decl(file.tsx, 11, 3))
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Emit only p
->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) {p} >p : Symbol(p, Decl(file.tsx, 11, 3))
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Emit " 3"
3 ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30))
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Emit " 3 "
3
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Emit "3"
->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) 3
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Emit no args
->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30))
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Emit "foo bar"
->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) foo bar
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Emit "hello\\ world"
->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) hello\ world
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Emit " a b c d "
a ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) b c d
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmitWhitespace.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxReactEmitWhitespace.symbols.diff deleted file mode 100644 index 23ecbb7def1..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmitWhitespace.symbols.diff +++ /dev/null @@ -1,112 +0,0 @@ ---- old.tsxReactEmitWhitespace.symbols -+++ new.tsxReactEmitWhitespace.symbols -@@= skipped -24, +24 lines =@@ - - // Emit " " -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Emit " ", p, " " -
{p}
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - >p : Symbol(p, Decl(file.tsx, 11, 3)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Emit only p -
-->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - {p} - >p : Symbol(p, Decl(file.tsx, 11, 3)) - -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Emit only p -
-->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - {p} - >p : Symbol(p, Decl(file.tsx, 11, 3)) - -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Emit " 3" -
3 -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Emit " 3 " -
3
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Emit "3" -
-->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - 3 -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Emit no args -
-->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Emit "foo bar" -
-->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - foo - - bar - -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Emit "hello\\ world" -
-->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - hello\ - - world -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Emit " a b c d " -
a -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - b c - d
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmitWhitespace2.symbols b/testdata/baselines/reference/submodule/conformance/tsxReactEmitWhitespace2.symbols index 74fab8f5738..57c05601e71 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmitWhitespace2.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxReactEmitWhitespace2.symbols @@ -19,22 +19,22 @@ declare var React: any; // Emit ' word' in the last string
word code word
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->code : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->code : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>code : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>code : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // Same here
code word
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->code : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->code : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>code : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>code : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) // And here
word
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->code : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>code : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxReactEmitWhitespace2.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxReactEmitWhitespace2.symbols.diff deleted file mode 100644 index b24ee7b9d1f..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxReactEmitWhitespace2.symbols.diff +++ /dev/null @@ -1,35 +0,0 @@ ---- old.tsxReactEmitWhitespace2.symbols -+++ new.tsxReactEmitWhitespace2.symbols -@@= skipped -18, +18 lines =@@ - - // Emit ' word' in the last string -
word code word
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->code : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->code : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>code : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>code : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // Same here -
code word
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->code : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->code : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>code : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>code : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - - // And here -
word
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->code : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>code : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(file.tsx, 2, 30)) - diff --git a/testdata/baselines/reference/submodule/conformance/tsxSpreadChildren.symbols b/testdata/baselines/reference/submodule/conformance/tsxSpreadChildren.symbols index 1528b7c4f14..383f97dbf48 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxSpreadChildren.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxSpreadChildren.symbols @@ -40,7 +40,7 @@ function Todo(prop: { key: number, todo: string }) { >todo : Symbol(todo, Decl(tsxSpreadChildren.tsx, 15, 34)) return
{prop.key.toString() + prop.todo}
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildren.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildren.tsx, 2, 30)) >prop.key.toString : Symbol(Number.toString, Decl(lib.es5.d.ts, --, --)) >prop.key : Symbol(key, Decl(tsxSpreadChildren.tsx, 15, 21)) >prop : Symbol(prop, Decl(tsxSpreadChildren.tsx, 15, 14)) @@ -49,7 +49,7 @@ function Todo(prop: { key: number, todo: string }) { >prop.todo : Symbol(todo, Decl(tsxSpreadChildren.tsx, 15, 34)) >prop : Symbol(prop, Decl(tsxSpreadChildren.tsx, 15, 14)) >todo : Symbol(todo, Decl(tsxSpreadChildren.tsx, 15, 34)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildren.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildren.tsx, 2, 30)) } function TodoList({ todos }: TodoListProps) { >TodoList : Symbol(TodoList, Decl(tsxSpreadChildren.tsx, 17, 1)) @@ -57,7 +57,7 @@ function TodoList({ todos }: TodoListProps) { >TodoListProps : Symbol(TodoListProps, Decl(tsxSpreadChildren.tsx, 11, 1)) return
->div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildren.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildren.tsx, 2, 30)) {...todos.map(todo => )} >todos.map : Symbol(Array.map, Decl(lib.es5.d.ts, --, --)) @@ -75,7 +75,7 @@ function TodoList({ todos }: TodoListProps) { >todo : Symbol(TodoProp.todo, Decl(tsxSpreadChildren.tsx, 9, 15))
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildren.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildren.tsx, 2, 30)) } let x: TodoListProps; >x : Symbol(x, Decl(tsxSpreadChildren.tsx, 23, 3)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxSpreadChildren.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxSpreadChildren.symbols.diff deleted file mode 100644 index 3b3b76fa542..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxSpreadChildren.symbols.diff +++ /dev/null @@ -1,38 +0,0 @@ ---- old.tsxSpreadChildren.symbols -+++ new.tsxSpreadChildren.symbols -@@= skipped -39, +39 lines =@@ - >todo : Symbol(todo, Decl(tsxSpreadChildren.tsx, 15, 34)) - - return
{prop.key.toString() + prop.todo}
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildren.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildren.tsx, 2, 30)) - >prop.key.toString : Symbol(Number.toString, Decl(lib.es5.d.ts, --, --)) - >prop.key : Symbol(key, Decl(tsxSpreadChildren.tsx, 15, 21)) - >prop : Symbol(prop, Decl(tsxSpreadChildren.tsx, 15, 14)) -@@= skipped -9, +9 lines =@@ - >prop.todo : Symbol(todo, Decl(tsxSpreadChildren.tsx, 15, 34)) - >prop : Symbol(prop, Decl(tsxSpreadChildren.tsx, 15, 14)) - >todo : Symbol(todo, Decl(tsxSpreadChildren.tsx, 15, 34)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildren.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildren.tsx, 2, 30)) - } - function TodoList({ todos }: TodoListProps) { - >TodoList : Symbol(TodoList, Decl(tsxSpreadChildren.tsx, 17, 1)) -@@= skipped -8, +8 lines =@@ - >TodoListProps : Symbol(TodoListProps, Decl(tsxSpreadChildren.tsx, 11, 1)) - - return
-->div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildren.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildren.tsx, 2, 30)) - - {...todos.map(todo => )} - >todos.map : Symbol(Array.map, Decl(lib.es5.d.ts, --, --)) -@@= skipped -18, +18 lines =@@ - >todo : Symbol(TodoProp.todo, Decl(tsxSpreadChildren.tsx, 9, 15)) - -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildren.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildren.tsx, 2, 30)) - } - let x: TodoListProps; - >x : Symbol(x, Decl(tsxSpreadChildren.tsx, 23, 3)) \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/tsxSpreadChildrenInvalidType(jsx=react,target=es2015).symbols b/testdata/baselines/reference/submodule/conformance/tsxSpreadChildrenInvalidType(jsx=react,target=es2015).symbols index 7d37c337108..85af82ef468 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxSpreadChildrenInvalidType(jsx=react,target=es2015).symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxSpreadChildrenInvalidType(jsx=react,target=es2015).symbols @@ -40,7 +40,7 @@ function Todo(prop: { key: number, todo: string }) { >todo : Symbol(todo, Decl(tsxSpreadChildrenInvalidType.tsx, 15, 34)) return
{prop.key.toString() + prop.todo}
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) >prop.key.toString : Symbol(Number.toString, Decl(lib.es5.d.ts, --, --)) >prop.key : Symbol(key, Decl(tsxSpreadChildrenInvalidType.tsx, 15, 21)) >prop : Symbol(prop, Decl(tsxSpreadChildrenInvalidType.tsx, 15, 14)) @@ -49,7 +49,7 @@ function Todo(prop: { key: number, todo: string }) { >prop.todo : Symbol(todo, Decl(tsxSpreadChildrenInvalidType.tsx, 15, 34)) >prop : Symbol(prop, Decl(tsxSpreadChildrenInvalidType.tsx, 15, 14)) >todo : Symbol(todo, Decl(tsxSpreadChildrenInvalidType.tsx, 15, 34)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) } function TodoList({ todos }: TodoListProps) { >TodoList : Symbol(TodoList, Decl(tsxSpreadChildrenInvalidType.tsx, 17, 1)) @@ -57,7 +57,7 @@ function TodoList({ todos }: TodoListProps) { >TodoListProps : Symbol(TodoListProps, Decl(tsxSpreadChildrenInvalidType.tsx, 11, 1)) return
->div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) {...} >Todo : Symbol(Todo, Decl(tsxSpreadChildrenInvalidType.tsx, 14, 1)) @@ -71,7 +71,7 @@ function TodoList({ todos }: TodoListProps) { >todo : Symbol(TodoProp.todo, Decl(tsxSpreadChildrenInvalidType.tsx, 9, 15))
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) } function TodoListNoError({ todos }: TodoListProps) { >TodoListNoError : Symbol(TodoListNoError, Decl(tsxSpreadChildrenInvalidType.tsx, 22, 1)) @@ -80,7 +80,7 @@ function TodoListNoError({ todos }: TodoListProps) { // any is not checked return
->div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) {...( as any)} >Todo : Symbol(Todo, Decl(tsxSpreadChildrenInvalidType.tsx, 14, 1)) @@ -94,7 +94,7 @@ function TodoListNoError({ todos }: TodoListProps) { >todo : Symbol(TodoProp.todo, Decl(tsxSpreadChildrenInvalidType.tsx, 9, 15))
; ->div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) } declare let x: TodoListProps; >x : Symbol(x, Decl(tsxSpreadChildrenInvalidType.tsx, 29, 11)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxSpreadChildrenInvalidType(jsx=react,target=es2015).symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxSpreadChildrenInvalidType(jsx=react,target=es2015).symbols.diff deleted file mode 100644 index 7bb249cbb58..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxSpreadChildrenInvalidType(jsx=react,target=es2015).symbols.diff +++ /dev/null @@ -1,56 +0,0 @@ ---- old.tsxSpreadChildrenInvalidType(jsx=react,target=es2015).symbols -+++ new.tsxSpreadChildrenInvalidType(jsx=react,target=es2015).symbols -@@= skipped -39, +39 lines =@@ - >todo : Symbol(todo, Decl(tsxSpreadChildrenInvalidType.tsx, 15, 34)) - - return
{prop.key.toString() + prop.todo}
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) - >prop.key.toString : Symbol(Number.toString, Decl(lib.es5.d.ts, --, --)) - >prop.key : Symbol(key, Decl(tsxSpreadChildrenInvalidType.tsx, 15, 21)) - >prop : Symbol(prop, Decl(tsxSpreadChildrenInvalidType.tsx, 15, 14)) -@@= skipped -9, +9 lines =@@ - >prop.todo : Symbol(todo, Decl(tsxSpreadChildrenInvalidType.tsx, 15, 34)) - >prop : Symbol(prop, Decl(tsxSpreadChildrenInvalidType.tsx, 15, 14)) - >todo : Symbol(todo, Decl(tsxSpreadChildrenInvalidType.tsx, 15, 34)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) - } - function TodoList({ todos }: TodoListProps) { - >TodoList : Symbol(TodoList, Decl(tsxSpreadChildrenInvalidType.tsx, 17, 1)) -@@= skipped -8, +8 lines =@@ - >TodoListProps : Symbol(TodoListProps, Decl(tsxSpreadChildrenInvalidType.tsx, 11, 1)) - - return
-->div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) - - {...} - >Todo : Symbol(Todo, Decl(tsxSpreadChildrenInvalidType.tsx, 14, 1)) -@@= skipped -14, +14 lines =@@ - >todo : Symbol(TodoProp.todo, Decl(tsxSpreadChildrenInvalidType.tsx, 9, 15)) - -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) - } - function TodoListNoError({ todos }: TodoListProps) { - >TodoListNoError : Symbol(TodoListNoError, Decl(tsxSpreadChildrenInvalidType.tsx, 22, 1)) -@@= skipped -9, +9 lines =@@ - - // any is not checked - return
-->div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) - - {...( as any)} - >Todo : Symbol(Todo, Decl(tsxSpreadChildrenInvalidType.tsx, 14, 1)) -@@= skipped -14, +14 lines =@@ - >todo : Symbol(TodoProp.todo, Decl(tsxSpreadChildrenInvalidType.tsx, 9, 15)) - -
; -->div : Symbol(JSX.IntrinsicElements.__index, Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(tsxSpreadChildrenInvalidType.tsx, 2, 30)) - } - declare let x: TodoListProps; - >x : Symbol(x, Decl(tsxSpreadChildrenInvalidType.tsx, 29, 11)) \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/conformance/tsxSpreadInvalidType.symbols b/testdata/baselines/reference/submodule/conformance/tsxSpreadInvalidType.symbols index 494bb425164..99f4dcbd529 100644 --- a/testdata/baselines/reference/submodule/conformance/tsxSpreadInvalidType.symbols +++ b/testdata/baselines/reference/submodule/conformance/tsxSpreadInvalidType.symbols @@ -21,16 +21,16 @@ const c = undefined; const d =
>d : Symbol(d, Decl(a.tsx, 8, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 1, 40)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 1, 40)) >a : Symbol(a, Decl(a.tsx, 4, 5)) const e =
>e : Symbol(e, Decl(a.tsx, 9, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 1, 40)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 1, 40)) >b : Symbol(b, Decl(a.tsx, 5, 5)) const f =
>f : Symbol(f, Decl(a.tsx, 10, 5)) ->div : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 1, 40)) +>div : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 1, 40)) >c : Symbol(c, Decl(a.tsx, 6, 5)) diff --git a/testdata/baselines/reference/submodule/conformance/tsxSpreadInvalidType.symbols.diff b/testdata/baselines/reference/submodule/conformance/tsxSpreadInvalidType.symbols.diff deleted file mode 100644 index 7423fcd02fe..00000000000 --- a/testdata/baselines/reference/submodule/conformance/tsxSpreadInvalidType.symbols.diff +++ /dev/null @@ -1,21 +0,0 @@ ---- old.tsxSpreadInvalidType.symbols -+++ new.tsxSpreadInvalidType.symbols -@@= skipped -20, +20 lines =@@ - - const d =
- >d : Symbol(d, Decl(a.tsx, 8, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 1, 40)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 1, 40)) - >a : Symbol(a, Decl(a.tsx, 4, 5)) - - const e =
- >e : Symbol(e, Decl(a.tsx, 9, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 1, 40)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 1, 40)) - >b : Symbol(b, Decl(a.tsx, 5, 5)) - - const f =
- >f : Symbol(f, Decl(a.tsx, 10, 5)) -->div : Symbol(JSX.IntrinsicElements.__index, Decl(a.tsx, 1, 40)) -+>div : Symbol(JSX.IntrinsicElements[__index], Decl(a.tsx, 1, 40)) - >c : Symbol(c, Decl(a.tsx, 6, 5)) diff --git a/testdata/baselines/reference/submodule/conformance/typeGuardOfFromPropNameInUnionType.symbols b/testdata/baselines/reference/submodule/conformance/typeGuardOfFromPropNameInUnionType.symbols index 613de9f313b..b71764bb73c 100644 --- a/testdata/baselines/reference/submodule/conformance/typeGuardOfFromPropNameInUnionType.symbols +++ b/testdata/baselines/reference/submodule/conformance/typeGuardOfFromPropNameInUnionType.symbols @@ -308,22 +308,22 @@ function f(i: Indexed) { >i : Symbol(i, Decl(typeGuardOfFromPropNameInUnionType.ts, 96, 11)) return i.a; ->i.a : Symbol(Indexed[__index], Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) +>i.a : Symbol(Indexed.__index, Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) >i : Symbol(i, Decl(typeGuardOfFromPropNameInUnionType.ts, 96, 11)) ->a : Symbol(Indexed[__index], Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) +>a : Symbol(Indexed.__index, Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) } else if ("b" in i) { >i : Symbol(i, Decl(typeGuardOfFromPropNameInUnionType.ts, 96, 11)) return i.b; ->i.b : Symbol(Indexed[__index], Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) +>i.b : Symbol(Indexed.__index, Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) >i : Symbol(i, Decl(typeGuardOfFromPropNameInUnionType.ts, 96, 11)) ->b : Symbol(Indexed[__index], Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) +>b : Symbol(Indexed.__index, Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) } return "c" in i && i.c; >i : Symbol(i, Decl(typeGuardOfFromPropNameInUnionType.ts, 96, 11)) ->i.c : Symbol(Indexed[__index], Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) +>i.c : Symbol(Indexed.__index, Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) >i : Symbol(i, Decl(typeGuardOfFromPropNameInUnionType.ts, 96, 11)) ->c : Symbol(Indexed[__index], Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) +>c : Symbol(Indexed.__index, Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) } diff --git a/testdata/baselines/reference/submodule/conformance/typeGuardOfFromPropNameInUnionType.symbols.diff b/testdata/baselines/reference/submodule/conformance/typeGuardOfFromPropNameInUnionType.symbols.diff deleted file mode 100644 index aca50f2c741..00000000000 --- a/testdata/baselines/reference/submodule/conformance/typeGuardOfFromPropNameInUnionType.symbols.diff +++ /dev/null @@ -1,30 +0,0 @@ ---- old.typeGuardOfFromPropNameInUnionType.symbols -+++ new.typeGuardOfFromPropNameInUnionType.symbols -@@= skipped -307, +307 lines =@@ - >i : Symbol(i, Decl(typeGuardOfFromPropNameInUnionType.ts, 96, 11)) - - return i.a; -->i.a : Symbol(Indexed.__index, Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) -+>i.a : Symbol(Indexed[__index], Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) - >i : Symbol(i, Decl(typeGuardOfFromPropNameInUnionType.ts, 96, 11)) -->a : Symbol(Indexed.__index, Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) -+>a : Symbol(Indexed[__index], Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) - } - else if ("b" in i) { - >i : Symbol(i, Decl(typeGuardOfFromPropNameInUnionType.ts, 96, 11)) - - return i.b; -->i.b : Symbol(Indexed.__index, Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) -+>i.b : Symbol(Indexed[__index], Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) - >i : Symbol(i, Decl(typeGuardOfFromPropNameInUnionType.ts, 96, 11)) -->b : Symbol(Indexed.__index, Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) -+>b : Symbol(Indexed[__index], Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) - } - return "c" in i && i.c; - >i : Symbol(i, Decl(typeGuardOfFromPropNameInUnionType.ts, 96, 11)) -->i.c : Symbol(Indexed.__index, Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) -+>i.c : Symbol(Indexed[__index], Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) - >i : Symbol(i, Decl(typeGuardOfFromPropNameInUnionType.ts, 96, 11)) -->c : Symbol(Indexed.__index, Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) -+>c : Symbol(Indexed[__index], Decl(typeGuardOfFromPropNameInUnionType.ts, 92, 19)) - } diff --git a/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsPrefixSuffixPreference.baseline.jsonc b/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsPrefixSuffixPreference.baseline.jsonc index 5fe7d981bc7..2ddccfa5af2 100644 --- a/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsPrefixSuffixPreference.baseline.jsonc +++ b/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsPrefixSuffixPreference.baseline.jsonc @@ -59,13 +59,18 @@ // === /file1.ts === // declare function log(s: string | number): void; // const /*RENAME*/[|qRENAME|] = 1; -// export { [|qRENAME|] as q/*END SUFFIX*/ }; +// export { [|qRENAME|] }; // const x = { // z: 'value' // } // const { z } = x; // log(z); +// === /file2.ts === +// declare function log(s: string | number): void; +// import { [|qRENAME|] } from "./file1"; +// log([|qRENAME|] + 1); + // === findRenameLocations === @@ -73,8 +78,8 @@ // === /file1.ts === // declare function log(s: string | number): void; -// const q = 1; -// export { /*START PREFIX*/q as /*RENAME*/[|qRENAME|] }; +// const [|qRENAME|] = 1; +// export { /*RENAME*/[|qRENAME|] }; // const x = { // z: 'value' // } @@ -91,9 +96,19 @@ // === findRenameLocations === // @useAliasesForRename: false +// === /file1.ts === +// declare function log(s: string | number): void; +// const [|qRENAME|] = 1; +// export { [|qRENAME|] }; +// const x = { +// z: 'value' +// } +// const { z } = x; +// log(z); + // === /file2.ts === // declare function log(s: string | number): void; -// import { /*START PREFIX*/q as /*RENAME*/[|qRENAME|] } from "./file1"; +// import { /*RENAME*/[|qRENAME|] } from "./file1"; // log([|qRENAME|] + 1); @@ -101,9 +116,19 @@ // === findRenameLocations === // @useAliasesForRename: false +// === /file1.ts === +// declare function log(s: string | number): void; +// const [|qRENAME|] = 1; +// export { [|qRENAME|] }; +// const x = { +// z: 'value' +// } +// const { z } = x; +// log(z); + // === /file2.ts === // declare function log(s: string | number): void; -// import { /*START PREFIX*/q as [|qRENAME|] } from "./file1"; +// import { [|qRENAME|] } from "./file1"; // log(/*RENAME*/[|qRENAME|] + 1); @@ -159,8 +184,8 @@ // const x = { // /*RENAME*/[|zRENAME|]: 'value' // } -// const { [|zRENAME|]: z/*END SUFFIX*/ } = x; -// log(z); +// const { [|zRENAME|] } = x; +// log([|zRENAME|]); @@ -168,11 +193,13 @@ // @useAliasesForRename: false // === /file1.ts === -// --- (line: 3) skipped --- +// declare function log(s: string | number): void; +// const q = 1; +// export { q }; // const x = { -// z: 'value' +// [|zRENAME|]: 'value' // } -// const { /*START PREFIX*/z: /*RENAME*/[|zRENAME|] } = x; +// const { /*RENAME*/[|zRENAME|] } = x; // log([|zRENAME|]); @@ -181,9 +208,11 @@ // @useAliasesForRename: false // === /file1.ts === -// --- (line: 3) skipped --- +// declare function log(s: string | number): void; +// const q = 1; +// export { q }; // const x = { -// z: 'value' +// [|zRENAME|]: 'value' // } -// const { /*START PREFIX*/z: [|zRENAME|] } = x; +// const { [|zRENAME|] } = x; // log(/*RENAME*/[|zRENAME|]); \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsPrefixSuffixPreference.baseline.jsonc.diff b/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsPrefixSuffixPreference.baseline.jsonc.diff index 5bb6cfc6b21..ecf75d90862 100644 --- a/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsPrefixSuffixPreference.baseline.jsonc.diff +++ b/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsPrefixSuffixPreference.baseline.jsonc.diff @@ -1,51 +1,24 @@ --- old.findAllRefsPrefixSuffixPreference.baseline.jsonc +++ new.findAllRefsPrefixSuffixPreference.baseline.jsonc -@@= skipped -58, +58 lines =@@ - // === /file1.ts === +@@= skipped -95, +95 lines =@@ + // === findRenameLocations === + // @useAliasesForRename: false + ++// === /file1.ts === ++// declare function log(s: string | number): void; ++// const [|qRENAME|] = 1; ++// export { [|qRENAME|] }; ++// const x = { ++// z: 'value' ++// } ++// const { z } = x; ++// log(z); ++ + // === /file2.ts === // declare function log(s: string | number): void; - // const /*RENAME*/[|qRENAME|] = 1; --// export { [|qRENAME|] }; --// const x = { --// z: 'value' --// } --// const { z } = x; --// log(z); -- --// === /file2.ts === --// declare function log(s: string | number): void; --// import { [|qRENAME|] } from "./file1"; --// log([|qRENAME|] + 1); -- -- -- --// === findRenameLocations === --// @useAliasesForRename: false -- --// === /file1.ts === --// declare function log(s: string | number): void; --// const [|qRENAME|] = 1; --// export { /*RENAME*/[|qRENAME|] }; --// const x = { --// z: 'value' --// } --// const { z } = x; --// log(z); -- --// === /file2.ts === --// declare function log(s: string | number): void; --// import { [|qRENAME|] } from "./file1"; --// log([|qRENAME|] + 1); -- -- -- --// === findRenameLocations === --// @useAliasesForRename: false -- --// === /file2.ts === --// declare function log(s: string | number): void; --// import { /*RENAME*/[|qRENAME|] } from "./file1"; --// log([|qRENAME|] + 1); -- + // import { /*RENAME*/[|qRENAME|] } from "./file1"; + // log([|qRENAME|] + 1); + -// === /file1.ts === -// declare function log(s: string | number): void; -// const [|qRENAME|] = 1; @@ -56,61 +29,26 @@ -// const { z } = x; -// log(z); - -- -- --// === findRenameLocations === --// @useAliasesForRename: false -- --// === /file2.ts === --// declare function log(s: string | number): void; --// import { [|qRENAME|] } from "./file1"; -+// export { [|qRENAME|] as q/*END SUFFIX*/ }; -+// const x = { -+// z: 'value' -+// } -+// const { z } = x; -+// log(z); -+ -+ -+ -+// === findRenameLocations === -+// @useAliasesForRename: false -+ + + + // === findRenameLocations === + // @useAliasesForRename: false + +// === /file1.ts === +// declare function log(s: string | number): void; -+// const q = 1; -+// export { /*START PREFIX*/q as /*RENAME*/[|qRENAME|] }; ++// const [|qRENAME|] = 1; ++// export { [|qRENAME|] }; +// const x = { +// z: 'value' +// } +// const { z } = x; +// log(z); + -+// === /file2.ts === -+// declare function log(s: string | number): void; -+// import { [|qRENAME|] } from "./file1"; -+// log([|qRENAME|] + 1); -+ -+ -+ -+// === findRenameLocations === -+// @useAliasesForRename: false -+ -+// === /file2.ts === -+// declare function log(s: string | number): void; -+// import { /*START PREFIX*/q as /*RENAME*/[|qRENAME|] } from "./file1"; -+// log([|qRENAME|] + 1); -+ -+ -+ -+// === findRenameLocations === -+// @useAliasesForRename: false -+ -+// === /file2.ts === -+// declare function log(s: string | number): void; -+// import { /*START PREFIX*/q as [|qRENAME|] } from "./file1"; + // === /file2.ts === + // declare function log(s: string | number): void; + // import { [|qRENAME|] } from "./file1"; // log(/*RENAME*/[|qRENAME|] + 1); - +- -// === /file1.ts === -// declare function log(s: string | number): void; -// const [|qRENAME|] = 1; @@ -120,70 +58,5 @@ -// } -// const { z } = x; -// log(z); -- - // === findRenameLocations === -@@= skipped -125, +100 lines =@@ - // const x = { - // /*RENAME*/[|zRENAME|]: 'value' - // } --// const { [|zRENAME|] } = x; --// log([|zRENAME|]); -- -- -- --// === findRenameLocations === --// @useAliasesForRename: false -- --// === /file1.ts === --// declare function log(s: string | number): void; --// const q = 1; --// export { q }; --// const x = { --// [|zRENAME|]: 'value' --// } --// const { /*RENAME*/[|zRENAME|] } = x; --// log([|zRENAME|]); -- -- -- --// === findRenameLocations === --// @useAliasesForRename: false -- --// === /file1.ts === --// declare function log(s: string | number): void; --// const q = 1; --// export { q }; --// const x = { --// [|zRENAME|]: 'value' --// } --// const { [|zRENAME|] } = x; -+// const { [|zRENAME|]: z/*END SUFFIX*/ } = x; -+// log(z); -+ -+ -+ -+// === findRenameLocations === -+// @useAliasesForRename: false -+ -+// === /file1.ts === -+// --- (line: 3) skipped --- -+// const x = { -+// z: 'value' -+// } -+// const { /*START PREFIX*/z: /*RENAME*/[|zRENAME|] } = x; -+// log([|zRENAME|]); -+ -+ -+ -+// === findRenameLocations === -+// @useAliasesForRename: false -+ -+// === /file1.ts === -+// --- (line: 3) skipped --- -+// const x = { -+// z: 'value' -+// } -+// const { /*START PREFIX*/z: [|zRENAME|] } = x; - // log(/*RENAME*/[|zRENAME|]); \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsReExportsUseInImportType.baseline.jsonc b/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsReExportsUseInImportType.baseline.jsonc index 5a8fb51b708..11d0ec9dcee 100644 --- a/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsReExportsUseInImportType.baseline.jsonc +++ b/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsReExportsUseInImportType.baseline.jsonc @@ -89,10 +89,14 @@ // @useAliasesForRename: false // === /app.ts === -// import { /*START PREFIX*/foo as /*RENAME*/[|fooRENAME|] } from './foo/types'; +// import { /*RENAME*/[|fooRENAME|] } from './foo/types'; // export type fullType = [|fooRENAME|].Full; // type namespaceImport = typeof import('./foo/types'); -// type fullType2 = import('./foo/types').foo.Full; +// type fullType2 = import('./foo/types').[|fooRENAME|].Full; + +// === /foo/types/index.ts === +// import * as [|fooRENAME|] from './types'; +// export { [|fooRENAME|] }; @@ -100,10 +104,14 @@ // @useAliasesForRename: false // === /app.ts === -// import { /*START PREFIX*/foo as [|fooRENAME|] } from './foo/types'; +// import { [|fooRENAME|] } from './foo/types'; // export type fullType = /*RENAME*/[|fooRENAME|].Full; // type namespaceImport = typeof import('./foo/types'); -// type fullType2 = import('./foo/types').foo.Full; +// type fullType2 = import('./foo/types').[|fooRENAME|].Full; + +// === /foo/types/index.ts === +// import * as [|fooRENAME|] from './types'; +// export { [|fooRENAME|] }; @@ -117,17 +125,23 @@ // type fullType2 = import('./foo/types')./*RENAME*/[|fooRENAME|].Full; // === /foo/types/index.ts === -// import * as foo from './types'; -// export { /*START PREFIX*/foo as [|fooRENAME|] }; +// import * as [|fooRENAME|] from './types'; +// export { [|fooRENAME|] }; // === findRenameLocations === // @useAliasesForRename: false +// === /app.ts === +// import { [|fooRENAME|] } from './foo/types'; +// export type fullType = [|fooRENAME|].Full; +// type namespaceImport = typeof import('./foo/types'); +// type fullType2 = import('./foo/types').[|fooRENAME|].Full; + // === /foo/types/index.ts === // import * as /*RENAME*/[|fooRENAME|] from './types'; -// export { [|fooRENAME|] as foo/*END SUFFIX*/ }; +// export { [|fooRENAME|] }; @@ -141,5 +155,5 @@ // type fullType2 = import('./foo/types').[|fooRENAME|].Full; // === /foo/types/index.ts === -// import * as foo from './types'; -// export { /*START PREFIX*/foo as /*RENAME*/[|fooRENAME|] }; \ No newline at end of file +// import * as [|fooRENAME|] from './types'; +// export { /*RENAME*/[|fooRENAME|] }; \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsReExportsUseInImportType.baseline.jsonc.diff b/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsReExportsUseInImportType.baseline.jsonc.diff index 4a58f402efd..601dee87fc6 100644 --- a/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsReExportsUseInImportType.baseline.jsonc.diff +++ b/testdata/baselines/reference/submodule/fourslash/findRenameLocations/findAllRefsReExportsUseInImportType.baseline.jsonc.diff @@ -44,242 +44,108 @@ // type namespaceImport = typeof import('./foo/types'); // type fullType2 = import('./foo/types').foo./*RENAME*/[|FullRENAME|]; -- -- --// === findRenameLocations === --// === /foo/types/index.ts === --// import * as /*RENAME*/[|fooRENAME|] from './types'; --// export { [|fooRENAME|] as foo/*END SUFFIX*/ }; -- -- -- --// === findRenameLocations === --// === /foo/types/index.ts === --// import * as foo from './types'; --// export { /*START PREFIX*/foo as /*RENAME*/[|fooRENAME|] }; -- --// === /app.ts === --// import { [|fooRENAME|] } from './foo/types'; --// export type fullType = [|fooRENAME|].Full; --// type namespaceImport = typeof import('./foo/types'); ++// === /foo/types/types.ts === ++// export type [|FullRENAME|] = { prop: string; }; ++ + + + // === findRenameLocations === +@@= skipped -41, +41 lines =@@ + + + // === findRenameLocations === ++// === /app.ts === ++// import { [|fooRENAME|] } from './foo/types'; ++// export type fullType = [|fooRENAME|].Full; ++// type namespaceImport = typeof import('./foo/types'); ++// type fullType2 = import('./foo/types').[|fooRENAME|].Full; ++ + // === /foo/types/index.ts === + // import * as foo from './types'; + // export { /*START PREFIX*/foo as /*RENAME*/[|fooRENAME|] }; + ++ ++ ++// === findRenameLocations === + // === /app.ts === + // import { [|fooRENAME|] } from './foo/types'; + // export type fullType = [|fooRENAME|].Full; + // type namespaceImport = typeof import('./foo/types'); -// type fullType2 = import('./foo/types').[|fooRENAME|].Full; - - - -// === findRenameLocations === --// === /foo/types/index.ts === --// import * as foo from './types'; --// export { /*START PREFIX*/foo as [|fooRENAME|] }; -- ++// type fullType2 = import('./foo/types')./*RENAME*/[|fooRENAME|].Full; ++ + // === /foo/types/index.ts === + // import * as foo from './types'; + // export { /*START PREFIX*/foo as [|fooRENAME|] }; + -// === /app.ts === -// import { [|fooRENAME|] } from './foo/types'; -// export type fullType = [|fooRENAME|].Full; -// type namespaceImport = typeof import('./foo/types'); -// type fullType2 = import('./foo/types')./*RENAME*/[|fooRENAME|].Full; - -- -- --// === findRenameLocations === --// === /app.ts === --// import { /*START PREFIX*/foo as /*RENAME*/[|fooRENAME|] } from './foo/types'; --// export type fullType = [|fooRENAME|].Full; --// type namespaceImport = typeof import('./foo/types'); --// type fullType2 = import('./foo/types').foo.Full; -- -- -- --// === findRenameLocations === --// === /app.ts === --// import { /*START PREFIX*/foo as [|fooRENAME|] } from './foo/types'; --// export type fullType = /*RENAME*/[|fooRENAME|].Full; --// type namespaceImport = typeof import('./foo/types'); --// type fullType2 = import('./foo/types').foo.Full; -- -- -- --// === findRenameLocations === --// @useAliasesForRename: false -- --// === /app.ts === --// import { /*RENAME*/[|fooRENAME|] } from './foo/types'; --// export type fullType = [|fooRENAME|].Full; --// type namespaceImport = typeof import('./foo/types'); --// type fullType2 = import('./foo/types').[|fooRENAME|].Full; -- --// === /foo/types/index.ts === --// import * as [|fooRENAME|] from './types'; --// export { [|fooRENAME|] }; -- -- -- --// === findRenameLocations === --// @useAliasesForRename: false -- --// === /app.ts === --// import { [|fooRENAME|] } from './foo/types'; --// export type fullType = /*RENAME*/[|fooRENAME|].Full; --// type namespaceImport = typeof import('./foo/types'); --// type fullType2 = import('./foo/types').[|fooRENAME|].Full; -- --// === /foo/types/index.ts === --// import * as [|fooRENAME|] from './types'; --// export { [|fooRENAME|] }; -- -- -- --// === findRenameLocations === --// @useAliasesForRename: false -- + + + // === findRenameLocations === +@@= skipped -76, +76 lines =@@ + // === findRenameLocations === + // @useAliasesForRename: false + -// === /foo/types/index.ts === -// import * as [|fooRENAME|] from './types'; -// export { [|fooRENAME|] }; - --// === /app.ts === --// import { [|fooRENAME|] } from './foo/types'; --// export type fullType = [|fooRENAME|].Full; --// type namespaceImport = typeof import('./foo/types'); --// type fullType2 = import('./foo/types')./*RENAME*/[|fooRENAME|].Full; -- -- -- --// === findRenameLocations === --// @useAliasesForRename: false -- --// === /foo/types/index.ts === --// import * as /*RENAME*/[|fooRENAME|] from './types'; --// export { [|fooRENAME|] }; -- --// === /app.ts === --// import { [|fooRENAME|] } from './foo/types'; --// export type fullType = [|fooRENAME|].Full; --// type namespaceImport = typeof import('./foo/types'); --// type fullType2 = import('./foo/types').[|fooRENAME|].Full; -- -- -- --// === findRenameLocations === --// @useAliasesForRename: false -- --// === /foo/types/index.ts === --// import * as [|fooRENAME|] from './types'; --// export { /*RENAME*/[|fooRENAME|] }; -- --// === /app.ts === --// import { [|fooRENAME|] } from './foo/types'; --// export type fullType = [|fooRENAME|].Full; --// type namespaceImport = typeof import('./foo/types'); --// type fullType2 = import('./foo/types').[|fooRENAME|].Full; -+// === /foo/types/types.ts === -+// export type [|FullRENAME|] = { prop: string; }; -+ -+ -+ -+// === findRenameLocations === + // === /app.ts === + // import { [|fooRENAME|] } from './foo/types'; + // export type fullType = [|fooRENAME|].Full; + // type namespaceImport = typeof import('./foo/types'); + // type fullType2 = import('./foo/types')./*RENAME*/[|fooRENAME|].Full; + +// === /foo/types/index.ts === -+// import * as /*RENAME*/[|fooRENAME|] from './types'; -+// export { [|fooRENAME|] as foo/*END SUFFIX*/ }; -+ ++// import * as [|fooRENAME|] from './types'; ++// export { [|fooRENAME|] }; + + + + // === findRenameLocations === + // @useAliasesForRename: false + -+// === findRenameLocations === +// === /app.ts === +// import { [|fooRENAME|] } from './foo/types'; +// export type fullType = [|fooRENAME|].Full; +// type namespaceImport = typeof import('./foo/types'); +// type fullType2 = import('./foo/types').[|fooRENAME|].Full; -+ -+// === /foo/types/index.ts === -+// import * as foo from './types'; -+// export { /*START PREFIX*/foo as /*RENAME*/[|fooRENAME|] }; -+ -+ -+ -+// === findRenameLocations === -+// === /app.ts === -+// import { [|fooRENAME|] } from './foo/types'; -+// export type fullType = [|fooRENAME|].Full; -+// type namespaceImport = typeof import('./foo/types'); -+// type fullType2 = import('./foo/types')./*RENAME*/[|fooRENAME|].Full; -+ -+// === /foo/types/index.ts === -+// import * as foo from './types'; -+// export { /*START PREFIX*/foo as [|fooRENAME|] }; -+ -+ -+ -+// === findRenameLocations === -+// === /app.ts === -+// import { /*START PREFIX*/foo as /*RENAME*/[|fooRENAME|] } from './foo/types'; -+// export type fullType = [|fooRENAME|].Full; -+// type namespaceImport = typeof import('./foo/types'); -+// type fullType2 = import('./foo/types').foo.Full; -+ -+ -+ -+// === findRenameLocations === -+// === /app.ts === -+// import { /*START PREFIX*/foo as [|fooRENAME|] } from './foo/types'; -+// export type fullType = /*RENAME*/[|fooRENAME|].Full; -+// type namespaceImport = typeof import('./foo/types'); -+// type fullType2 = import('./foo/types').foo.Full; -+ -+ -+ -+// === findRenameLocations === -+// @useAliasesForRename: false -+ -+// === /app.ts === -+// import { /*START PREFIX*/foo as /*RENAME*/[|fooRENAME|] } from './foo/types'; -+// export type fullType = [|fooRENAME|].Full; -+// type namespaceImport = typeof import('./foo/types'); -+// type fullType2 = import('./foo/types').foo.Full; -+ -+ -+ -+// === findRenameLocations === -+// @useAliasesForRename: false -+ -+// === /app.ts === -+// import { /*START PREFIX*/foo as [|fooRENAME|] } from './foo/types'; -+// export type fullType = /*RENAME*/[|fooRENAME|].Full; -+// type namespaceImport = typeof import('./foo/types'); -+// type fullType2 = import('./foo/types').foo.Full; -+ -+ -+ -+// === findRenameLocations === -+// @useAliasesForRename: false -+ -+// === /app.ts === -+// import { [|fooRENAME|] } from './foo/types'; -+// export type fullType = [|fooRENAME|].Full; -+// type namespaceImport = typeof import('./foo/types'); -+// type fullType2 = import('./foo/types')./*RENAME*/[|fooRENAME|].Full; -+ -+// === /foo/types/index.ts === -+// import * as foo from './types'; -+// export { /*START PREFIX*/foo as [|fooRENAME|] }; -+ -+ -+ -+// === findRenameLocations === -+// @useAliasesForRename: false -+ -+// === /foo/types/index.ts === -+// import * as /*RENAME*/[|fooRENAME|] from './types'; -+// export { [|fooRENAME|] as foo/*END SUFFIX*/ }; -+ + + // === /foo/types/index.ts === + // import * as /*RENAME*/[|fooRENAME|] from './types'; + // export { [|fooRENAME|] }; + + + +// === findRenameLocations === +// @useAliasesForRename: false + -+// === /app.ts === -+// import { [|fooRENAME|] } from './foo/types'; -+// export type fullType = [|fooRENAME|].Full; -+// type namespaceImport = typeof import('./foo/types'); -+// type fullType2 = import('./foo/types').[|fooRENAME|].Full; -+ -+// === /foo/types/index.ts === -+// import * as foo from './types'; -+// export { /*START PREFIX*/foo as /*RENAME*/[|fooRENAME|] }; \ No newline at end of file + // === /app.ts === + // import { [|fooRENAME|] } from './foo/types'; + // export type fullType = [|fooRENAME|].Full; + // type namespaceImport = typeof import('./foo/types'); + // type fullType2 = import('./foo/types').[|fooRENAME|].Full; +- +- +- +-// === findRenameLocations === +-// @useAliasesForRename: false + + // === /foo/types/index.ts === + // import * as [|fooRENAME|] from './types'; + // export { /*RENAME*/[|fooRENAME|] }; +- +-// === /app.ts === +-// import { [|fooRENAME|] } from './foo/types'; +-// export type fullType = [|fooRENAME|].Full; +-// type namespaceImport = typeof import('./foo/types'); +-// type fullType2 = import('./foo/types').[|fooRENAME|].Full; \ No newline at end of file diff --git a/testdata/baselines/reference/submodule/fourslash/findRenameLocations/renameExportSpecifier2.baseline.jsonc b/testdata/baselines/reference/submodule/fourslash/findRenameLocations/renameExportSpecifier2.baseline.jsonc index 0b1ead83bf4..81b791eafa2 100644 --- a/testdata/baselines/reference/submodule/fourslash/findRenameLocations/renameExportSpecifier2.baseline.jsonc +++ b/testdata/baselines/reference/submodule/fourslash/findRenameLocations/renameExportSpecifier2.baseline.jsonc @@ -2,8 +2,8 @@ // @useAliasesForRename: false // === /a.ts === -// const name = {}; -// export { /*START PREFIX*/name as [|nameRENAME|]/*RENAME*/ }; +// const [|nameRENAME|] = {}; +// export { [|nameRENAME|]/*RENAME*/ }; // === /b.ts === // import { [|nameRENAME|] } from './a'; diff --git a/testdata/baselines/reference/submodule/fourslash/findRenameLocations/renameExportSpecifier2.baseline.jsonc.diff b/testdata/baselines/reference/submodule/fourslash/findRenameLocations/renameExportSpecifier2.baseline.jsonc.diff deleted file mode 100644 index b17ced5c571..00000000000 --- a/testdata/baselines/reference/submodule/fourslash/findRenameLocations/renameExportSpecifier2.baseline.jsonc.diff +++ /dev/null @@ -1,13 +0,0 @@ ---- old.renameExportSpecifier2.baseline.jsonc -+++ new.renameExportSpecifier2.baseline.jsonc -@@= skipped -1, +1 lines =@@ - // @useAliasesForRename: false - - // === /a.ts === --// const [|nameRENAME|] = {}; --// export { [|nameRENAME|]/*RENAME*/ }; -+// const name = {}; -+// export { /*START PREFIX*/name as [|nameRENAME|]/*RENAME*/ }; - - // === /b.ts === - // import { [|nameRENAME|] } from './a'; \ No newline at end of file diff --git a/testdata/baselines/reference/submoduleTriaged/compiler/anonClassDeclarationEmitIsAnon.types.diff b/testdata/baselines/reference/submoduleAccepted/compiler/anonClassDeclarationEmitIsAnon.types.diff similarity index 100% rename from testdata/baselines/reference/submoduleTriaged/compiler/anonClassDeclarationEmitIsAnon.types.diff rename to testdata/baselines/reference/submoduleAccepted/compiler/anonClassDeclarationEmitIsAnon.types.diff diff --git a/testdata/baselines/reference/submoduleTriaged/compiler/baseConstraintOfDecorator.types.diff b/testdata/baselines/reference/submoduleAccepted/compiler/baseConstraintOfDecorator.types.diff similarity index 100% rename from testdata/baselines/reference/submoduleTriaged/compiler/baseConstraintOfDecorator.types.diff rename to testdata/baselines/reference/submoduleAccepted/compiler/baseConstraintOfDecorator.types.diff diff --git a/testdata/baselines/reference/submoduleTriaged/compiler/baseExpressionTypeParameters.types.diff b/testdata/baselines/reference/submoduleAccepted/compiler/baseExpressionTypeParameters.types.diff similarity index 100% rename from testdata/baselines/reference/submoduleTriaged/compiler/baseExpressionTypeParameters.types.diff rename to testdata/baselines/reference/submoduleAccepted/compiler/baseExpressionTypeParameters.types.diff diff --git a/testdata/baselines/reference/submoduleTriaged/compiler/declarationEmitGenericTypeParamerSerialization3.types.diff b/testdata/baselines/reference/submoduleAccepted/compiler/declarationEmitGenericTypeParamerSerialization3.types.diff similarity index 100% rename from testdata/baselines/reference/submoduleTriaged/compiler/declarationEmitGenericTypeParamerSerialization3.types.diff rename to testdata/baselines/reference/submoduleAccepted/compiler/declarationEmitGenericTypeParamerSerialization3.types.diff diff --git a/testdata/baselines/reference/submoduleTriaged/compiler/declarationEmitLocalClassDeclarationMixin.types.diff b/testdata/baselines/reference/submoduleAccepted/compiler/declarationEmitLocalClassDeclarationMixin.types.diff similarity index 100% rename from testdata/baselines/reference/submoduleTriaged/compiler/declarationEmitLocalClassDeclarationMixin.types.diff rename to testdata/baselines/reference/submoduleAccepted/compiler/declarationEmitLocalClassDeclarationMixin.types.diff diff --git a/testdata/baselines/reference/submoduleAccepted/compiler/declarationsWithRecursiveInternalTypesProduceUniqueTypeParams.types.diff b/testdata/baselines/reference/submoduleAccepted/compiler/declarationsWithRecursiveInternalTypesProduceUniqueTypeParams.types.diff index 515c9a25586..01b00f218d2 100644 --- a/testdata/baselines/reference/submoduleAccepted/compiler/declarationsWithRecursiveInternalTypesProduceUniqueTypeParams.types.diff +++ b/testdata/baselines/reference/submoduleAccepted/compiler/declarationsWithRecursiveInternalTypesProduceUniqueTypeParams.types.diff @@ -13,8 +13,8 @@ const reduce = (u: U, update: (u: U) => T) => { ->reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>(key: K_1) => (>>(key: K_2) => (>>>(key: K_3) => (>>>>(key: K_4) => (>>>>>(key: K_5) => (>>>>>>(key: K_6) => (>>>>>>>(key: K_7) => (>>>>>>>>(key: K_8) => (>>>>>>>>>(key: K_9) => (>>>>>>>>>>(key: K_10) => any & { map: (updater: (u: Value>>>>>>>>>>) => Value>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>) => Value>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>) => Value>>>>>>>>) => T; set: (newU: Value>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>) => Value>>>>>>>) => T; set: (newU: Value>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>) => Value>>>>>) => T; set: (newU: Value>>>>>) => T; }) & { map: (updater: (u: Value>>>>) => Value>>>>) => T; set: (newU: Value>>>>) => T; }) & { map: (updater: (u: Value>>>) => Value>>>) => T; set: (newU: Value>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value>) => Value>) => T; set: (newU: Value>) => T; }) & { map: (updater: (u: Value) => Value) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } ->(u: U, update: (u: U) => T) => { const set = (newU: U) => Object.is(u, newU) ? t : update(newU); return Object.assign( >(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }), { map: (updater: (u: U) => U) => set(updater(u)), set }); } : (u: U, update: (u: U) => T) => (>(key: K) => (>(key: K_1) => (>>(key: K_2) => (>>>(key: K_3) => (>>>>(key: K_4) => (>>>>>(key: K_5) => (>>>>>>(key: K_6) => (>>>>>>>(key: K_7) => (>>>>>>>>(key: K_8) => (>>>>>>>>>(key: K_9) => (>>>>>>>>>>(key: K_10) => any & { map: (updater: (u: Value>>>>>>>>>>) => Value>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>) => Value>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>) => Value>>>>>>>>) => T; set: (newU: Value>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>) => Value>>>>>>>) => T; set: (newU: Value>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>) => Value>>>>>) => T; set: (newU: Value>>>>>) => T; }) & { map: (updater: (u: Value>>>>) => Value>>>>) => T; set: (newU: Value>>>>) => T; }) & { map: (updater: (u: Value>>>) => Value>>>) => T; set: (newU: Value>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value>) => Value>) => T; set: (newU: Value>) => T; }) & { map: (updater: (u: Value) => Value) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } -+>reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => (>>>>(key: K_2) => (>>>>>>>>(key: K_3) => (>>>>>>>>>>>>>>>>(key: K_4) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_5) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_6) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_7) => (>(key: K_8) => any & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>>>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } -+>(u: U, update: (u: U) => T) => { const set = (newU: U) => Object.is(u, newU) ? t : update(newU); return Object.assign( >(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }), { map: (updater: (u: U) => U) => set(updater(u)), set }); } : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => (>>>>(key: K_2) => (>>>>>>>>(key: K_3) => (>>>>>>>>>>>>>>>>(key: K_4) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_5) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_6) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_7) => (>(key: K_8) => any & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>>>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } ++>reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => any & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } ++>(u: U, update: (u: U) => T) => { const set = (newU: U) => Object.is(u, newU) ? t : update(newU); return Object.assign( >(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }), { map: (updater: (u: U) => U) => set(updater(u)), set }); } : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => any & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } >u : U >update : (u: U) => T >u : U @@ -23,21 +23,21 @@ return Object.assign( ->Object.assign( >(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }), { map: (updater: (u: U) => U) => set(updater(u)), set }) : (>(key: K) => (>(key: K_1) => (>>(key: K_2) => (>>>(key: K_3) => (>>>>(key: K_4) => (>>>>>(key: K_5) => (>>>>>>(key: K_6) => (>>>>>>>(key: K_7) => (>>>>>>>>(key: K_8) => (>>>>>>>>>(key: K_9) => (>>>>>>>>>>(key: K_10) => any & { map: (updater: (u: Value>>>>>>>>>>) => Value>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>) => Value>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>) => Value>>>>>>>>) => T; set: (newU: Value>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>) => Value>>>>>>>) => T; set: (newU: Value>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>) => Value>>>>>) => T; set: (newU: Value>>>>>) => T; }) & { map: (updater: (u: Value>>>>) => Value>>>>) => T; set: (newU: Value>>>>) => T; }) & { map: (updater: (u: Value>>>) => Value>>>) => T; set: (newU: Value>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value>) => Value>) => T; set: (newU: Value>) => T; }) & { map: (updater: (u: Value) => Value) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } -+>Object.assign( >(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }), { map: (updater: (u: U) => U) => set(updater(u)), set }) : (>(key: K) => (>>(key: K_1) => (>>>>(key: K_2) => (>>>>>>>>(key: K_3) => (>>>>>>>>>>>>>>>>(key: K_4) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_5) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_6) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_7) => (>(key: K_8) => any & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>>>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } ++>Object.assign( >(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }), { map: (updater: (u: U) => U) => set(updater(u)), set }) : (>(key: K) => (>>(key: K_1) => any & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } >Object.assign : { (target: T_1, source: U_1): T_1 & U_1; (target: T_1, source1: U_1, source2: V): T_1 & U_1 & V; (target: T_1, source1: U_1, source2: V, source3: W): T_1 & U_1 & V & W; (target: object, ...sources: any[]): any; } >Object : ObjectConstructor >assign : { (target: T_1, source: U_1): T_1 & U_1; (target: T_1, source1: U_1, source2: V): T_1 & U_1 & V; (target: T_1, source1: U_1, source2: V, source3: W): T_1 & U_1 & V & W; (target: object, ...sources: any[]): any; } >(key: K) => ->>(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }) : >(key: K) => (>(key: K_1) => (>>(key: K_2) => (>>>(key: K_3) => (>>>>(key: K_4) => (>>>>>(key: K_5) => (>>>>>>(key: K_6) => (>>>>>>>(key: K_7) => (>>>>>>>>(key: K_8) => (>>>>>>>>>(key: K_9) => (>>>>>>>>>>(key: K_10) => any & { map: (updater: (u: Value>>>>>>>>>>) => Value>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>) => Value>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>) => Value>>>>>>>>) => T; set: (newU: Value>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>) => Value>>>>>>>) => T; set: (newU: Value>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>) => Value>>>>>) => T; set: (newU: Value>>>>>) => T; }) & { map: (updater: (u: Value>>>>) => Value>>>>) => T; set: (newU: Value>>>>) => T; }) & { map: (updater: (u: Value>>>) => Value>>>) => T; set: (newU: Value>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value>) => Value>) => T; set: (newU: Value>) => T; }) & { map: (updater: (u: Value) => Value) => T; set: (newU: Value) => T; } -+>>(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }) : >(key: K) => (>>(key: K_1) => (>>>>(key: K_2) => (>>>>>>>>(key: K_3) => (>>>>>>>>>>>>>>>>(key: K_4) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_5) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_6) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_7) => (>(key: K_8) => any & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>>>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; } ++>>(key: K) => reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }) : >(key: K) => (>>(key: K_1) => any & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; } >key : K reduce>(u[key as keyof U] as Value, (v: Value) => { ->reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }) : (>(key: K) => (>>(key: K_2) => (>>>(key: K_3) => (>>>>(key: K_4) => (>>>>>(key: K_5) => (>>>>>>(key: K_6) => (>>>>>>>(key: K_7) => (>>>>>>>>(key: K_8) => (>>>>>>>>>(key: K_9) => (>>>>>>>>>>(key: K_10) => (>>>>>>>>>>>(key: K_11) => any & { map: (updater: (u: Value>>>>>>>>>>>) => Value>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>) => Value>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>) => Value>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>) => Value>>>>>>>>) => T; set: (newU: Value>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>) => Value>>>>>>>) => T; set: (newU: Value>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>) => Value>>>>>) => T; set: (newU: Value>>>>>) => T; }) & { map: (updater: (u: Value>>>>) => Value>>>>) => T; set: (newU: Value>>>>) => T; }) & { map: (updater: (u: Value>>>) => Value>>>) => T; set: (newU: Value>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value>) => Value>) => T; set: (newU: Value>) => T; }) & { map: (updater: (u: Value) => Value) => T; set: (newU: Value) => T; } ->reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>(key: K_1) => (>>(key: K_2) => (>>>(key: K_3) => (>>>>(key: K_4) => (>>>>>(key: K_5) => (>>>>>>(key: K_6) => (>>>>>>>(key: K_7) => (>>>>>>>>(key: K_8) => (>>>>>>>>>(key: K_9) => (>>>>>>>>>>(key: K_10) => any & { map: (updater: (u: Value>>>>>>>>>>) => Value>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>) => Value>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>) => Value>>>>>>>>) => T; set: (newU: Value>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>) => Value>>>>>>>) => T; set: (newU: Value>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>) => Value>>>>>) => T; set: (newU: Value>>>>>) => T; }) & { map: (updater: (u: Value>>>>) => Value>>>>) => T; set: (newU: Value>>>>) => T; }) & { map: (updater: (u: Value>>>) => Value>>>) => T; set: (newU: Value>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value>) => Value>) => T; set: (newU: Value>) => T; }) & { map: (updater: (u: Value) => Value) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } +>reduce>(u[key as keyof U] as Value, (v: Value) => { return update(Object.assign(Array.isArray(u) ? [] : {}, u, { [key]: v })); }) : (>>(key: K) => (>>>>(key: K_2) => (>>>>>>>>(key: K_3) => (>>>>>>>>>>>>>>>>(key: K_4) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_5) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_6) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_7) => (>(key: K_8) => any & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>>>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; } -+>reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => (>>>>(key: K_2) => (>>>>>>>>(key: K_3) => (>>>>>>>>>>>>>>>>(key: K_4) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_5) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_6) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_7) => (>(key: K_8) => any & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>>>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } ++>reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => any & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } >u[key as keyof U] as Value : Value >u[key as keyof U] : U[keyof U] >u : U @@ -48,7 +48,7 @@ ->reduce(t, (t: T) => t) : ((key: K) => (>(key: K_1) => (>>(key: K_2) => (>>>(key: K_3) => (>>>>(key: K_4) => (>>>>>(key: K_5) => (>>>>>>(key: K_6) => (>>>>>>>(key: K_7) => (>>>>>>>>(key: K_8) => (>>>>>>>>>(key: K_9) => (>>>>>>>>>>(key: K_10) => any & { map: (updater: (u: Value>>>>>>>>>>) => Value>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>) => Value>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>) => Value>>>>>>>>) => T; set: (newU: Value>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>) => Value>>>>>>>) => T; set: (newU: Value>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>) => Value>>>>>) => T; set: (newU: Value>>>>>) => T; }) & { map: (updater: (u: Value>>>>) => Value>>>>) => T; set: (newU: Value>>>>) => T; }) & { map: (updater: (u: Value>>>) => Value>>>) => T; set: (newU: Value>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value>) => Value>) => T; set: (newU: Value>) => T; }) & { map: (updater: (u: Value) => Value) => T; set: (newU: Value) => T; }) & { map: (updater: (u: T) => T) => T; set: (newU: T) => T; } ->reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>(key: K_1) => (>>(key: K_2) => (>>>(key: K_3) => (>>>>(key: K_4) => (>>>>>(key: K_5) => (>>>>>>(key: K_6) => (>>>>>>>(key: K_7) => (>>>>>>>>(key: K_8) => (>>>>>>>>>(key: K_9) => (>>>>>>>>>>(key: K_10) => any & { map: (updater: (u: Value>>>>>>>>>>) => Value>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>) => Value>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>) => Value>>>>>>>>) => T; set: (newU: Value>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>) => Value>>>>>>>) => T; set: (newU: Value>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>) => Value>>>>>) => T; set: (newU: Value>>>>>) => T; }) & { map: (updater: (u: Value>>>>) => Value>>>>) => T; set: (newU: Value>>>>) => T; }) & { map: (updater: (u: Value>>>) => Value>>>) => T; set: (newU: Value>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value>) => Value>) => T; set: (newU: Value>) => T; }) & { map: (updater: (u: Value) => Value) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } +>reduce(t, (t: T) => t) : (>(key: K) => (>>(key: K_1) => (>>>(key: K_2) => (>>>>(key: K_3) => (>>>>>(key: K_4) => (>>>>>>(key: K_5) => (>>>>>>>(key: K_6) => (>>>>>>>>(key: K_7) => (>>>>>>>>>(key: K_8) => (>>>>>>>>>>(key: K_9) => (>>>>>>>>>>>(key: K_10) => any & { map: (updater: (u: Value>>>>>>>>>>) => Value>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>) => Value>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>) => Value>>>>>>>>) => T; set: (newU: Value>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>) => Value>>>>>>>) => T; set: (newU: Value>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>) => Value>>>>>) => T; set: (newU: Value>>>>>) => T; }) & { map: (updater: (u: Value>>>>) => Value>>>>) => T; set: (newU: Value>>>>) => T; }) & { map: (updater: (u: Value>>>) => Value>>>) => T; set: (newU: Value>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value>) => Value>) => T; set: (newU: Value>) => T; }) & { map: (updater: (u: Value) => Value) => T; set: (newU: Value) => T; }) & { map: (updater: (u: T) => T) => T; set: (newU: T) => T; } -+>reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => (>>>>(key: K_2) => (>>>>>>>>(key: K_3) => (>>>>>>>>>>>>>>>>(key: K_4) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_5) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_6) => (>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>(key: K_7) => (>(key: K_8) => any & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: any) => any) => T; set: (newU: any) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>>>>>>>>>) => Value>>>>>>>>>>>>>>>>>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>>>>>>>>>) => T; }) & { map: (updater: (u: Value>>>>>>) => Value>>>>>>>>>>>>>) => T; set: (newU: Value>>>>>>) => T; }) & { map: (updater: (u: Value>>) => Value>>>>>) => T; set: (newU: Value>>) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } ++>reduce : (u: U, update: (u: U) => T) => (>(key: K) => (>>(key: K_1) => any & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: Value) => Value>) => T; set: (newU: Value) => T; }) & { map: (updater: (u: U) => U) => T; set: (newU: U) => T; } >t : T >(t: T) => t : (t: T) => T >t : T diff --git a/testdata/baselines/reference/submoduleAccepted/compiler/deleteExpressionMustBeOptional(strict=false).symbols.diff b/testdata/baselines/reference/submoduleAccepted/compiler/deleteExpressionMustBeOptional(strict=false).symbols.diff deleted file mode 100644 index 5010fcada61..00000000000 --- a/testdata/baselines/reference/submoduleAccepted/compiler/deleteExpressionMustBeOptional(strict=false).symbols.diff +++ /dev/null @@ -1,21 +0,0 @@ ---- old.deleteExpressionMustBeOptional(strict=false).symbols -+++ new.deleteExpressionMustBeOptional(strict=false).symbols -@@= skipped -106, +106 lines =@@ - >f : Symbol(f, Decl(deleteExpressionMustBeOptional.ts, 20, 13)) - - delete a.a -->a.a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) -+>a.a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) - >a : Symbol(a, Decl(deleteExpressionMustBeOptional.ts, 21, 13)) -->a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) -+>a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) - - delete a.b -->a.b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) -+>a.b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) - >a : Symbol(a, Decl(deleteExpressionMustBeOptional.ts, 21, 13)) -->b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) -+>b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) - - delete b.a - >b : Symbol(b, Decl(deleteExpressionMustBeOptional.ts, 22, 13)) \ No newline at end of file diff --git a/testdata/baselines/reference/submoduleAccepted/compiler/deleteExpressionMustBeOptional(strict=true).symbols.diff b/testdata/baselines/reference/submoduleAccepted/compiler/deleteExpressionMustBeOptional(strict=true).symbols.diff deleted file mode 100644 index 19338bdb4a7..00000000000 --- a/testdata/baselines/reference/submoduleAccepted/compiler/deleteExpressionMustBeOptional(strict=true).symbols.diff +++ /dev/null @@ -1,21 +0,0 @@ ---- old.deleteExpressionMustBeOptional(strict=true).symbols -+++ new.deleteExpressionMustBeOptional(strict=true).symbols -@@= skipped -106, +106 lines =@@ - >f : Symbol(f, Decl(deleteExpressionMustBeOptional.ts, 20, 13)) - - delete a.a -->a.a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) -+>a.a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) - >a : Symbol(a, Decl(deleteExpressionMustBeOptional.ts, 21, 13)) -->a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) -+>a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) - - delete a.b -->a.b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) -+>a.b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) - >a : Symbol(a, Decl(deleteExpressionMustBeOptional.ts, 21, 13)) -->b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional.ts, 12, 14)) -+>b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional.ts, 12, 14)) - - delete b.a - >b : Symbol(b, Decl(deleteExpressionMustBeOptional.ts, 22, 13)) \ No newline at end of file diff --git a/testdata/baselines/reference/submoduleAccepted/compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=false).symbols.diff b/testdata/baselines/reference/submoduleAccepted/compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=false).symbols.diff deleted file mode 100644 index c8799981950..00000000000 --- a/testdata/baselines/reference/submoduleAccepted/compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=false).symbols.diff +++ /dev/null @@ -1,21 +0,0 @@ ---- old.deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=false).symbols -+++ new.deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=false).symbols -@@= skipped -159, +159 lines =@@ - >g : Symbol(g, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 21, 13)) - - delete a.a -->a.a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) -+>a.a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) - >a : Symbol(a, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 22, 13)) -->a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) -+>a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) - - delete a.b -->a.b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) -+>a.b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) - >a : Symbol(a, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 22, 13)) -->b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) -+>b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) - - delete b.a - >b : Symbol(b, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 23, 13)) \ No newline at end of file diff --git a/testdata/baselines/reference/submoduleAccepted/compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=true).symbols.diff b/testdata/baselines/reference/submoduleAccepted/compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=true).symbols.diff deleted file mode 100644 index 4e76c3906ef..00000000000 --- a/testdata/baselines/reference/submoduleAccepted/compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=true).symbols.diff +++ /dev/null @@ -1,21 +0,0 @@ ---- old.deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=true).symbols -+++ new.deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=true).symbols -@@= skipped -159, +159 lines =@@ - >g : Symbol(g, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 21, 13)) - - delete a.a -->a.a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) -+>a.a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) - >a : Symbol(a, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 22, 13)) -->a : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) -+>a : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) - - delete a.b -->a.b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) -+>a.b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) - >a : Symbol(a, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 22, 13)) -->b : Symbol(AA.__index, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) -+>b : Symbol(AA[__index], Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 12, 14)) - - delete b.a - >b : Symbol(b, Decl(deleteExpressionMustBeOptional_exactOptionalPropertyTypes.ts, 23, 13)) \ No newline at end of file diff --git a/testdata/baselines/reference/submoduleTriaged/compiler/deprecatedCompilerOptions1.errors.txt.diff b/testdata/baselines/reference/submoduleAccepted/compiler/deprecatedCompilerOptions1.errors.txt.diff similarity index 100% rename from testdata/baselines/reference/submoduleTriaged/compiler/deprecatedCompilerOptions1.errors.txt.diff rename to testdata/baselines/reference/submoduleAccepted/compiler/deprecatedCompilerOptions1.errors.txt.diff diff --git a/testdata/baselines/reference/submoduleTriaged/compiler/deprecatedCompilerOptions3.errors.txt.diff b/testdata/baselines/reference/submoduleAccepted/compiler/deprecatedCompilerOptions3.errors.txt.diff similarity index 100% rename from testdata/baselines/reference/submoduleTriaged/compiler/deprecatedCompilerOptions3.errors.txt.diff rename to testdata/baselines/reference/submoduleAccepted/compiler/deprecatedCompilerOptions3.errors.txt.diff diff --git a/testdata/baselines/reference/submoduleTriaged/compiler/deprecatedCompilerOptions4.errors.txt.diff b/testdata/baselines/reference/submoduleAccepted/compiler/deprecatedCompilerOptions4.errors.txt.diff similarity index 100% rename from testdata/baselines/reference/submoduleTriaged/compiler/deprecatedCompilerOptions4.errors.txt.diff rename to testdata/baselines/reference/submoduleAccepted/compiler/deprecatedCompilerOptions4.errors.txt.diff diff --git a/testdata/baselines/reference/submoduleTriaged/compiler/deprecatedCompilerOptions5.errors.txt.diff b/testdata/baselines/reference/submoduleAccepted/compiler/deprecatedCompilerOptions5.errors.txt.diff similarity index 100% rename from testdata/baselines/reference/submoduleTriaged/compiler/deprecatedCompilerOptions5.errors.txt.diff rename to testdata/baselines/reference/submoduleAccepted/compiler/deprecatedCompilerOptions5.errors.txt.diff diff --git a/testdata/baselines/reference/submoduleTriaged/compiler/noImplicitThisBigThis.js.diff b/testdata/baselines/reference/submoduleAccepted/compiler/noImplicitThisBigThis.js.diff similarity index 100% rename from testdata/baselines/reference/submoduleTriaged/compiler/noImplicitThisBigThis.js.diff rename to testdata/baselines/reference/submoduleAccepted/compiler/noImplicitThisBigThis.js.diff diff --git a/testdata/baselines/reference/submoduleTriaged/conformance/checkJsdocSatisfiesTag15.js.diff b/testdata/baselines/reference/submoduleAccepted/conformance/checkJsdocSatisfiesTag15.js.diff similarity index 100% rename from testdata/baselines/reference/submoduleTriaged/conformance/checkJsdocSatisfiesTag15.js.diff rename to testdata/baselines/reference/submoduleAccepted/conformance/checkJsdocSatisfiesTag15.js.diff diff --git a/testdata/baselines/reference/submoduleAccepted/conformance/jsDeclarationsMissingTypeParameters(target=es2015).js.diff b/testdata/baselines/reference/submoduleAccepted/conformance/jsDeclarationsMissingTypeParameters(target=es2015).js.diff index b2f24c6fc80..53131be77ac 100644 --- a/testdata/baselines/reference/submoduleAccepted/conformance/jsDeclarationsMissingTypeParameters(target=es2015).js.diff +++ b/testdata/baselines/reference/submoduleAccepted/conformance/jsDeclarationsMissingTypeParameters(target=es2015).js.diff @@ -1,23 +1,11 @@ --- old.jsDeclarationsMissingTypeParameters(target=es2015).js +++ new.jsDeclarationsMissingTypeParameters(target=es2015).js -@@= skipped -46, +46 lines =@@ - /** - * @param {Array=} y desc - */ --declare function x(y?: any[] | undefined): void; -+declare function x(y?: Array | undefined): void; +@@= skipped -49, +49 lines =@@ + declare function x(y?: any[] | undefined): void; /** @param {function (Array)} func Invoked */ -declare function y(func: (arg0: any[]) => any): void; +declare function y(func: Function): void; /** * @return {(Array.<> | null)} list of devices - */ --declare function z(): (any[] | null); -+declare function z(): (Array | null); - /** - * - * @return {?Promise} A promise - */ --declare function w(): Promise | null; -+declare function w(): Promise | null; \ No newline at end of file + */ \ No newline at end of file diff --git a/testdata/baselines/reference/submoduleTriaged/conformance/jsDeclarationsOptionalTypeLiteralProps1.js.diff b/testdata/baselines/reference/submoduleAccepted/conformance/jsDeclarationsOptionalTypeLiteralProps1.js.diff similarity index 100% rename from testdata/baselines/reference/submoduleTriaged/conformance/jsDeclarationsOptionalTypeLiteralProps1.js.diff rename to testdata/baselines/reference/submoduleAccepted/conformance/jsDeclarationsOptionalTypeLiteralProps1.js.diff diff --git a/testdata/baselines/reference/submoduleTriaged/conformance/jsDeclarationsOptionalTypeLiteralProps2.js.diff b/testdata/baselines/reference/submoduleAccepted/conformance/jsDeclarationsOptionalTypeLiteralProps2.js.diff similarity index 100% rename from testdata/baselines/reference/submoduleTriaged/conformance/jsDeclarationsOptionalTypeLiteralProps2.js.diff rename to testdata/baselines/reference/submoduleAccepted/conformance/jsDeclarationsOptionalTypeLiteralProps2.js.diff diff --git a/testdata/baselines/reference/submoduleTriaged/conformance/typeFromPropertyAssignment39.js.diff b/testdata/baselines/reference/submoduleAccepted/conformance/typeFromPropertyAssignment39.js.diff similarity index 100% rename from testdata/baselines/reference/submoduleTriaged/conformance/typeFromPropertyAssignment39.js.diff rename to testdata/baselines/reference/submoduleAccepted/conformance/typeFromPropertyAssignment39.js.diff diff --git a/testdata/baselines/reference/submoduleTriaged/compiler/isolatedDeclarationErrorsReturnTypes.errors.txt.diff b/testdata/baselines/reference/submoduleTriaged/compiler/isolatedDeclarationErrorsReturnTypes.errors.txt.diff deleted file mode 100644 index 27ddaaa55e0..00000000000 --- a/testdata/baselines/reference/submoduleTriaged/compiler/isolatedDeclarationErrorsReturnTypes.errors.txt.diff +++ /dev/null @@ -1,255 +0,0 @@ ---- old.isolatedDeclarationErrorsReturnTypes.errors.txt -+++ new.isolatedDeclarationErrorsReturnTypes.errors.txt -@@= skipped -1, +1 lines =@@ - isolatedDeclarationErrorsReturnTypes.ts(16,41): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(19,41): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(109,65): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(110,43): error TS9013: Expression type can't be inferred with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(112,61): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(113,39): error TS9013: Expression type can't be inferred with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(115,61): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(116,39): error TS9013: Expression type can't be inferred with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(119,83): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(120,66): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(122,79): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(123,62): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(125,79): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(126,62): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(129,62): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(130,45): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(132,58): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(133,41): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(135,58): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(136,41): error TS9013: Expression type can't be inferred with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(138,73): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(139,51): error TS9013: Expression type can't be inferred with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(141,69): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(142,47): error TS9013: Expression type can't be inferred with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(144,69): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(145,47): error TS9013: Expression type can't be inferred with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(151,38): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(152,21): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(153,57): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -@@= skipped -27, +39 lines =@@ - isolatedDeclarationErrorsReturnTypes.ts(168,49): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(169,85): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. - isolatedDeclarationErrorsReturnTypes.ts(170,68): error TS9007: Function must have an explicit return type annotation with --isolatedDeclarations. -- -- --==== isolatedDeclarationErrorsReturnTypes.ts (31 errors) ==== -+isolatedDeclarationErrorsReturnTypes.ts(173,44): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(174,27): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(175,63): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(176,46): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(178,57): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(179,40): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(180,76): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(181,59): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(184,35): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(185,18): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(186,54): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(187,37): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(189,48): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(190,31): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(191,67): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+isolatedDeclarationErrorsReturnTypes.ts(192,50): error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+ -+ -+==== isolatedDeclarationErrorsReturnTypes.ts (59 errors) ==== - // Function Variables - export const fnExpressionConstVariable = function foo() { return 0;} - export const fnArrowConstVariable = () => "S"; -@@= skipped -129, +145 lines =@@ - !!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:109:60: Add a type annotation to the parameter cb. - !!! related TS9030 isolatedDeclarationErrorsReturnTypes.ts:109:65: Add a return type to the function expression. - export const fnParamArrowConstVariable = (cb = () => 1) => "S"; -+ ~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:110:43: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:110:43: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - - export let fnParamExpressionLetVariable = function foo(cb = function(){ }) { return 0;} - ~~~~~~~~ -@@= skipped -7, +11 lines =@@ - !!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:112:56: Add a type annotation to the parameter cb. - !!! related TS9030 isolatedDeclarationErrorsReturnTypes.ts:112:61: Add a return type to the function expression. - export let fnParamArrowLetVariable = (cb = () => 1) => "S"; -+ ~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:113:39: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:113:39: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - - export var fnParamExpressionVarVariable = function foo(cb = function(){ }) { return 0;} - ~~~~~~~~ -@@= skipped -7, +11 lines =@@ - !!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:115:56: Add a type annotation to the parameter cb. - !!! related TS9030 isolatedDeclarationErrorsReturnTypes.ts:115:61: Add a return type to the function expression. - export var fnParamArrowVarVariable = (cb = () => 1) => "S"; -+ ~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:116:39: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:116:39: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - - // In Function Variables - No annotations on parameter - export const fnParamExpressionConstVariableOwnerHasReturnType = function foo(cb = function(){ }): number { return 0;} -@@= skipped -37, +41 lines =@@ - - // No Errors - export const fnParamExpressionConstVariableOk = function foo(cb = function(): void{ }): number { return 0;} -+ ~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:129:62: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:129:62: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - export const fnParamArrowConstVariableOk = (cb = function(): void{ }): string => "S"; -+ ~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:130:45: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:130:45: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - - export let fnParamExpressionLetVariableOk = function foo(cb = function(): void{ }): number { return 0;} -+ ~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:132:58: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:132:58: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - export let fnParamArrowLetVariableOk = (cb = function(): void{ }): string => "S"; -+ ~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:133:41: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:133:41: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - - export var fnParamExpressionVarVariableOk = function foo(cb = function(): void{ }): number { return 0;} -+ ~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:135:58: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:135:58: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - export var fnParamArrowVarVariableOk = (cb = function(): void{ }): string => "S"; -+ ~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:136:41: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:136:41: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - - export const fnParamExpressionConstVariableInternal = function foo(cb = function(){ }) { return 0;} - ~~~~~~~~ -@@= skipped -14, +38 lines =@@ - !!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:138:68: Add a type annotation to the parameter cb. - !!! related TS9030 isolatedDeclarationErrorsReturnTypes.ts:138:73: Add a return type to the function expression. - export const fnParamArrowConstVariableInternal = (cb = () => 1) => "S"; -+ ~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:139:51: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:139:51: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - - export let fnParamExpressionLetVariableInternal = function foo(cb = function(){ }) { return 0;} - ~~~~~~~~ -@@= skipped -7, +11 lines =@@ - !!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:141:64: Add a type annotation to the parameter cb. - !!! related TS9030 isolatedDeclarationErrorsReturnTypes.ts:141:69: Add a return type to the function expression. - export let fnParamArrowLetVariableInternal = (cb = () => 1) => "S"; -+ ~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:142:47: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:142:47: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - - export var fnParamExpressionVarVariableInternal = function foo(cb = function(){ }) { return 0;} - ~~~~~~~~ -@@= skipped -7, +11 lines =@@ - !!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:144:64: Add a type annotation to the parameter cb. - !!! related TS9030 isolatedDeclarationErrorsReturnTypes.ts:144:69: Add a return type to the function expression. - export var fnParamArrowVarVariableInternal = (cb = () => 1) => "S"; -+ ~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:145:47: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:145:47: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - - - // In Function Fields -@@= skipped -92, +96 lines =@@ - - // Have annotation only on parameter - fnExpressionOnlyOnParam = function foo(cb = function(): void { }) { return 0; } -+ ~~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:173:44: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:173:44: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - fnArrowOnlyOnParam = (cb = function(): void { }) => "S"; -+ ~~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:174:27: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:174:27: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - protected fnExpressionProtectedOnlyOnParam = function foo(cb = function(): void { }) { return 0; } -+ ~~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:175:63: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:175:63: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - protected fnArrowProtectedOnlyOnParam = (cb = function(): void { }) => "S"; -+ ~~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:176:46: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:176:46: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - - static fnStaticExpressionOnlyOnParam = function foo(cb = function(): void{ }) { return 0; } -+ ~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:178:57: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:178:57: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - static fnStaticArrowOnlyOnParam = (cb = function(): void{ }) => "S"; -+ ~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:179:40: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:179:40: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - protected static fnStaticExpressionProtectedOnlyOnParam = function foo(cb = function(): void{ }) { return 0; } -+ ~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:180:76: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:180:76: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - protected static fnStaticArrowProtectedOnlyOnParam = (cb = function(): void{ }) => "S"; -+ ~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:181:59: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:181:59: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - - // Have annotation, so ok - fnExpressionOk = function foo(cb = function(): void { }): number { return 0; } -+ ~~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:184:35: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:184:35: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - fnArrowOK = (cb = function(): void { }): string => "S"; -+ ~~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:185:18: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:185:18: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - protected fnExpressionProtectedOk = function foo(cb = function(): void { }): number { return 0; } -+ ~~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:186:54: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:186:54: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - protected fnArrowProtectedOK = (cb = function(): void { }): string => "S"; -+ ~~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:187:37: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:187:37: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - - static fnStaticExpressionOk = function foo(cb = function(): void{ }): number { return 0; } -+ ~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:189:48: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:189:48: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - static fnStaticArrowOk = (cb = function(): void{ }): string => "S"; -+ ~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:190:31: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:190:31: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - protected static fnStaticExpressionProtectedOk = function foo(cb = function(): void{ }): number { return 0; } -+ ~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:191:67: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:191:67: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - protected static fnStaticArrowProtectedOk = (cb = function(): void{ }): string => "S"; -+ ~~~~~~~~~~~~~~~~~~~~~~~~ -+!!! error TS9013: Expression type can't be inferred with --isolatedDeclarations. -+!!! related TS9028 isolatedDeclarationErrorsReturnTypes.ts:192:50: Add a type annotation to the parameter cb. -+!!! related TS9035 isolatedDeclarationErrorsReturnTypes.ts:192:50: Add satisfies and a type assertion to this expression (satisfies T as T) to make the type explicit. - - - // No Error, not in declarations \ No newline at end of file diff --git a/testdata/baselines/reference/submoduleTriaged/conformance/jsDeclarationsMissingGenerics(target=es2015).js.diff b/testdata/baselines/reference/submoduleTriaged/conformance/jsDeclarationsMissingGenerics(target=es2015).js.diff deleted file mode 100644 index 71ef97b6e85..00000000000 --- a/testdata/baselines/reference/submoduleTriaged/conformance/jsDeclarationsMissingGenerics(target=es2015).js.diff +++ /dev/null @@ -1,36 +0,0 @@ ---- old.jsDeclarationsMissingGenerics(target=es2015).js -+++ new.jsDeclarationsMissingGenerics(target=es2015).js -@@= skipped -25, +25 lines =@@ - /** - * @param {Array} x - */ --declare function x(x: any[]): void; -+declare function x(x: Array): void; - /** - * @param {Promise} x - */ --declare function y(x: Promise): void; -+declare function y(x: Promise): void; -+ -+ -+//// [DtsFileErrors] -+ -+ -+out/file.d.ts(4,23): error TS2314: Generic type 'Array' requires 1 type argument(s). -+out/file.d.ts(8,23): error TS2314: Generic type 'Promise' requires 1 type argument(s). -+ -+ -+==== out/file.d.ts (2 errors) ==== -+ /** -+ * @param {Array} x -+ */ -+ declare function x(x: Array): void; -+ ~~~~~ -+!!! error TS2314: Generic type 'Array' requires 1 type argument(s). -+ /** -+ * @param {Promise} x -+ */ -+ declare function y(x: Promise): void; -+ ~~~~~~~ -+!!! error TS2314: Generic type 'Promise' requires 1 type argument(s). -+ \ No newline at end of file diff --git a/testdata/baselines/reference/tsbuild/commandLine/emitDeclarationOnly-on-commandline.js b/testdata/baselines/reference/tsbuild/commandLine/emitDeclarationOnly-on-commandline.js index 4ef32d945c0..8f3b8307a47 100644 --- a/testdata/baselines/reference/tsbuild/commandLine/emitDeclarationOnly-on-commandline.js +++ b/testdata/baselines/reference/tsbuild/commandLine/emitDeclarationOnly-on-commandline.js @@ -500,7 +500,7 @@ Output:: [HH:MM:SS AM] Building project 'project1/src/tsconfig.json'... -[HH:MM:SS AM] Project 'project2/src/tsconfig.json' is out of date because output 'project2/src/tsconfig.tsbuildinfo' is older than input 'project1/src' +[HH:MM:SS AM] Project 'project2/src/tsconfig.json' is out of date because output 'project2/src/tsconfig.tsbuildinfo' is older than input 'project1/src/a.d.ts' [HH:MM:SS AM] Building project 'project2/src/tsconfig.json'... @@ -1329,7 +1329,7 @@ Output:: [HH:MM:SS AM] Building project 'project1/src/tsconfig.json'... -[HH:MM:SS AM] Project 'project2/src/tsconfig.json' is out of date because output 'project2/src/tsconfig.tsbuildinfo' is older than input 'project1/src' +[HH:MM:SS AM] Project 'project2/src/tsconfig.json' is out of date because output 'project2/src/tsconfig.tsbuildinfo' is older than input 'project1/src/b.d.ts' [HH:MM:SS AM] Building project 'project2/src/tsconfig.json'... diff --git a/testdata/baselines/reference/tsbuild/declarationEmit/reports-dts-generation-errors-with-incremental.js b/testdata/baselines/reference/tsbuild/declarationEmit/reports-dts-generation-errors-with-incremental.js index 2a4e5b21fd7..c4a8cf8ead0 100644 --- a/testdata/baselines/reference/tsbuild/declarationEmit/reports-dts-generation-errors-with-incremental.js +++ b/testdata/baselines/reference/tsbuild/declarationEmit/reports-dts-generation-errors-with-incremental.js @@ -48,8 +48,8 @@ Output:: 2 export const api = ky.extend({});    ~~~ -TSFILE: /home/src/workspaces/project/index.js -TSFILE: /home/src/workspaces/project/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/project/index.js +TSFILE: /home/src/workspaces/project/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' node_modules/ky/distribution/index.d.ts @@ -89,7 +89,7 @@ import ky from 'ky'; export const api = ky.extend({}); //// [/home/src/workspaces/project/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[3],"fileNames":["lib.es2025.full.d.ts","./node_modules/ky/distribution/index.d.ts","./index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b9b50c37c18e43d94b0dd4fb43967f10-type KyInstance = {\n extend(options: Record): KyInstance;\n}\ndeclare const ky: KyInstance;\nexport default ky;","impliedNodeFormat":99},{"version":"0f5091e963c17913313e4969c59e6eb4-import ky from 'ky';\nexport const api = ky.extend({});","impliedNodeFormat":99}],"fileIdsList":[[2]],"options":{"composite":false,"declaration":true,"module":199,"skipLibCheck":true,"skipDefaultLibCheck":true},"referencedMap":[[3,1]],"emitDiagnosticsPerFile":[[3,[{"pos":34,"end":37,"code":4023,"category":1,"messageKey":"Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023","messageArgs":["api","KyInstance","\"/home/src/workspaces/project/node_modules/ky/distribution/index\""]}]]]} +{"version":"FakeTSVersion","root":[3],"packageJsons":["./node_modules/ky/package.json","./package.json"],"missingPackageJsons":["./node_modules/ky/distribution/package.json"],"fileNames":["lib.es2025.full.d.ts","./node_modules/ky/distribution/index.d.ts","./index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b9b50c37c18e43d94b0dd4fb43967f10-type KyInstance = {\n extend(options: Record): KyInstance;\n}\ndeclare const ky: KyInstance;\nexport default ky;","impliedNodeFormat":99},{"version":"0f5091e963c17913313e4969c59e6eb4-import ky from 'ky';\nexport const api = ky.extend({});","impliedNodeFormat":99}],"fileIdsList":[[2]],"options":{"composite":false,"declaration":true,"module":199,"skipLibCheck":true,"skipDefaultLibCheck":true},"referencedMap":[[3,1]],"emitDiagnosticsPerFile":[[3,[{"pos":34,"end":37,"code":4023,"category":1,"messageKey":"Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023","messageArgs":["api","KyInstance","\"/home/src/workspaces/project/node_modules/ky/distribution/index\""]}]]]} //// [/home/src/workspaces/project/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -101,6 +101,13 @@ export const api = ky.extend({}); "original": 3 } ], + "packageJsons": [ + "./node_modules/ky/package.json", + "./package.json" + ], + "missingPackageJsons": [ + "./node_modules/ky/distribution/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./node_modules/ky/distribution/index.d.ts", @@ -176,7 +183,7 @@ export const api = ky.extend({}); ] ] ], - "size": 1686 + "size": 1823 } tsconfig.json:: diff --git a/testdata/baselines/reference/tsbuild/declarationEmit/reports-dts-generation-errors.js b/testdata/baselines/reference/tsbuild/declarationEmit/reports-dts-generation-errors.js index 81881638d85..f45e776281d 100644 --- a/testdata/baselines/reference/tsbuild/declarationEmit/reports-dts-generation-errors.js +++ b/testdata/baselines/reference/tsbuild/declarationEmit/reports-dts-generation-errors.js @@ -48,8 +48,8 @@ Output:: 2 export const api = ky.extend({});    ~~~ -TSFILE: /home/src/workspaces/project/index.js -TSFILE: /home/src/workspaces/project/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/project/index.js +TSFILE: /home/src/workspaces/project/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' node_modules/ky/distribution/index.d.ts @@ -91,7 +91,7 @@ import ky from 'ky'; export const api = ky.extend({}); //// [/home/src/workspaces/project/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","errors":true,"root":["./index.ts"]} +{"version":"FakeTSVersion","errors":true,"root":["./index.ts"],"packageJsons":["./node_modules/ky/package.json","./package.json"],"missingPackageJsons":["./node_modules/ky/distribution/package.json"]} //// [/home/src/workspaces/project/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -104,7 +104,14 @@ export const api = ky.extend({}); "original": "./index.ts" } ], - "size": 63 + "packageJsons": [ + "./node_modules/ky/package.json", + "./package.json" + ], + "missingPackageJsons": [ + "./node_modules/ky/distribution/package.json" + ], + "size": 200 } tsconfig.json:: @@ -132,8 +139,8 @@ Output:: 2 export const api = ky.extend({});    ~~~ -TSFILE: /home/src/workspaces/project/index.js -TSFILE: /home/src/workspaces/project/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/project/index.js +TSFILE: /home/src/workspaces/project/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' node_modules/ky/distribution/index.d.ts diff --git a/testdata/baselines/reference/tsbuild/declarationEmitForReferencedProjectTypesSubpath/declaration-emit-names-referenced-project-type-via-types-subpath.js b/testdata/baselines/reference/tsbuild/declarationEmitForReferencedProjectTypesSubpath/declaration-emit-names-referenced-project-type-via-types-subpath.js index bed7081799b..7a56da3eb36 100644 --- a/testdata/baselines/reference/tsbuild/declarationEmitForReferencedProjectTypesSubpath/declaration-emit-names-referenced-project-type-via-types-subpath.js +++ b/testdata/baselines/reference/tsbuild/declarationEmitForReferencedProjectTypesSubpath/declaration-emit-names-referenced-project-type-via-types-subpath.js @@ -107,7 +107,7 @@ interface Symbol { } declare const console: { log(msg: any): void; }; //// [/home/src/workspaces/solution/packages/consumer/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[5],"fileNames":["lib.es2025.full.d.ts","../dep/types/themes/componentTypes/formFieldLayout.d.ts","../dep/types/themes/componentTypes/index.d.ts","../dep/types/index.d.ts","./src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"2265bb6aae4ea44359eda1a1333669d7-export type FormFieldLayout = {\n textColor: string;\n fontSize: string;\n};\nexport default FormFieldLayout;\n","262c77b15a9433c1a517a42af08dabc4-import type FormFieldLayout from \"./formFieldLayout.js\";\nexport type ComponentTypes = {\n formFieldLayout: () => FormFieldLayout;\n};\n","8c960f82affa27b6eaa999ea3cdac3e7-import type { ComponentTypes as NewComponentTypes } from \"./themes/componentTypes/index.js\";\nexport type { NewComponentTypes };\n",{"version":"0eb11471bc41fb5a80fd0098368e8295-import type { NewComponentTypes } from \"@scope/dep\"\ndeclare const c: NewComponentTypes\nexport const style = c.formFieldLayout()","signature":"9cca47ad36e3ee3df7f98a27c15d37b0-export declare const style: import(\"@scope/dep/types/themes/componentTypes/formFieldLayout.js\").FormFieldLayout;\n","impliedNodeFormat":1}],"fileIdsList":[[4],[3],[2]],"options":{"composite":true,"emitDeclarationOnly":true,"declaration":true,"declarationDir":"./types","module":99,"outDir":"./types","rootDir":"./src","strict":true},"referencedMap":[[5,1],[4,2],[3,3]],"latestChangedDtsFile":"./types/index.d.ts"} +{"version":"FakeTSVersion","root":[5],"packageJsons":["./package.json","../dep/package.json"],"fileNames":["lib.es2025.full.d.ts","../dep/types/themes/componentTypes/formFieldLayout.d.ts","../dep/types/themes/componentTypes/index.d.ts","../dep/types/index.d.ts","./src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"2265bb6aae4ea44359eda1a1333669d7-export type FormFieldLayout = {\n textColor: string;\n fontSize: string;\n};\nexport default FormFieldLayout;\n","262c77b15a9433c1a517a42af08dabc4-import type FormFieldLayout from \"./formFieldLayout.js\";\nexport type ComponentTypes = {\n formFieldLayout: () => FormFieldLayout;\n};\n","8c960f82affa27b6eaa999ea3cdac3e7-import type { ComponentTypes as NewComponentTypes } from \"./themes/componentTypes/index.js\";\nexport type { NewComponentTypes };\n",{"version":"0eb11471bc41fb5a80fd0098368e8295-import type { NewComponentTypes } from \"@scope/dep\"\ndeclare const c: NewComponentTypes\nexport const style = c.formFieldLayout()","signature":"9cca47ad36e3ee3df7f98a27c15d37b0-export declare const style: import(\"@scope/dep/types/themes/componentTypes/formFieldLayout.js\").FormFieldLayout;\n","impliedNodeFormat":1}],"fileIdsList":[[4],[3],[2]],"options":{"composite":true,"emitDeclarationOnly":true,"declaration":true,"declarationDir":"./types","module":99,"outDir":"./types","rootDir":"./src","strict":true},"referencedMap":[[5,1],[4,2],[3,3]],"latestChangedDtsFile":"./types/index.d.ts"} //// [/home/src/workspaces/solution/packages/consumer/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -119,6 +119,10 @@ declare const console: { log(msg: any): void; }; "original": 5 } ], + "packageJsons": [ + "./package.json", + "../dep/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "../dep/types/themes/componentTypes/formFieldLayout.d.ts", @@ -202,13 +206,13 @@ declare const console: { log(msg: any): void; }; ] }, "latestChangedDtsFile": "./types/index.d.ts", - "size": 2144 + "size": 2200 } //// [/home/src/workspaces/solution/packages/consumer/types/index.d.ts] *new* export declare const style: import("@scope/dep/types/themes/componentTypes/formFieldLayout.js").FormFieldLayout; //// [/home/src/workspaces/solution/packages/dep/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[2,4]],"fileNames":["lib.es2025.full.d.ts","./src/themes/componentTypes/formFieldLayout.ts","./src/themes/componentTypes/index.ts","./src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d384c9df99c755540ca5330780b4f5e5-export type FormFieldLayout = {\n textColor: string\n fontSize: string\n}\nexport default FormFieldLayout","signature":"2265bb6aae4ea44359eda1a1333669d7-export type FormFieldLayout = {\n textColor: string;\n fontSize: string;\n};\nexport default FormFieldLayout;\n","impliedNodeFormat":1},{"version":"7e5adf3645b6325e5ba90d41821e4802-import type FormFieldLayout from \"./formFieldLayout.js\"\nexport type ComponentTypes = {\n formFieldLayout: () => FormFieldLayout\n}","signature":"262c77b15a9433c1a517a42af08dabc4-import type FormFieldLayout from \"./formFieldLayout.js\";\nexport type ComponentTypes = {\n formFieldLayout: () => FormFieldLayout;\n};\n","impliedNodeFormat":1},{"version":"aac956f8322a5530cde691c46bad3b7d-import type { ComponentTypes as NewComponentTypes } from \"./themes/componentTypes/index.js\"\nexport type { NewComponentTypes }","signature":"8c960f82affa27b6eaa999ea3cdac3e7-import type { ComponentTypes as NewComponentTypes } from \"./themes/componentTypes/index.js\";\nexport type { NewComponentTypes };\n","impliedNodeFormat":1}],"fileIdsList":[[3],[2]],"options":{"composite":true,"emitDeclarationOnly":true,"declaration":true,"declarationDir":"./types","module":99,"outDir":"./types","rootDir":"./src","strict":true},"referencedMap":[[4,1],[3,2]],"latestChangedDtsFile":"./types/index.d.ts"} +{"version":"FakeTSVersion","root":[[2,4]],"packageJsons":["./package.json"],"fileNames":["lib.es2025.full.d.ts","./src/themes/componentTypes/formFieldLayout.ts","./src/themes/componentTypes/index.ts","./src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d384c9df99c755540ca5330780b4f5e5-export type FormFieldLayout = {\n textColor: string\n fontSize: string\n}\nexport default FormFieldLayout","signature":"2265bb6aae4ea44359eda1a1333669d7-export type FormFieldLayout = {\n textColor: string;\n fontSize: string;\n};\nexport default FormFieldLayout;\n","impliedNodeFormat":1},{"version":"7e5adf3645b6325e5ba90d41821e4802-import type FormFieldLayout from \"./formFieldLayout.js\"\nexport type ComponentTypes = {\n formFieldLayout: () => FormFieldLayout\n}","signature":"262c77b15a9433c1a517a42af08dabc4-import type FormFieldLayout from \"./formFieldLayout.js\";\nexport type ComponentTypes = {\n formFieldLayout: () => FormFieldLayout;\n};\n","impliedNodeFormat":1},{"version":"aac956f8322a5530cde691c46bad3b7d-import type { ComponentTypes as NewComponentTypes } from \"./themes/componentTypes/index.js\"\nexport type { NewComponentTypes }","signature":"8c960f82affa27b6eaa999ea3cdac3e7-import type { ComponentTypes as NewComponentTypes } from \"./themes/componentTypes/index.js\";\nexport type { NewComponentTypes };\n","impliedNodeFormat":1}],"fileIdsList":[[3],[2]],"options":{"composite":true,"emitDeclarationOnly":true,"declaration":true,"declarationDir":"./types","module":99,"outDir":"./types","rootDir":"./src","strict":true},"referencedMap":[[4,1],[3,2]],"latestChangedDtsFile":"./types/index.d.ts"} //// [/home/src/workspaces/solution/packages/dep/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -225,6 +229,9 @@ export declare const style: import("@scope/dep/types/themes/componentTypes/formF ] } ], + "packageJsons": [ + "./package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./src/themes/componentTypes/formFieldLayout.ts", @@ -305,7 +312,7 @@ export declare const style: import("@scope/dep/types/themes/componentTypes/formF ] }, "latestChangedDtsFile": "./types/index.d.ts", - "size": 2350 + "size": 2384 } //// [/home/src/workspaces/solution/packages/dep/types/index.d.ts] *new* import type { ComponentTypes as NewComponentTypes } from "./themes/componentTypes/index.js"; diff --git a/testdata/baselines/reference/tsbuild/dependencyUpdate/rebuilds-when-absolute-non-root-dependency-is-updated.js b/testdata/baselines/reference/tsbuild/dependencyUpdate/rebuilds-when-absolute-non-root-dependency-is-updated.js new file mode 100644 index 00000000000..89858d56756 --- /dev/null +++ b/testdata/baselines/reference/tsbuild/dependencyUpdate/rebuilds-when-absolute-non-root-dependency-is-updated.js @@ -0,0 +1,254 @@ +currentDirectory::C:/work/project +useCaseSensitiveFileNames::false +Input:: +//// [C:/work/project/src/index.ts] *new* +import { myValue } from "abs-dep"; +export const value: string = myValue; +//// [C:/work/project/tsconfig.json] *new* +{ + "compilerOptions": { + "composite": true, + "outDir": "dist", + "paths": { + "abs-dep": ["D:/work/deps/dep.d.ts"] + }, + "strict": true + }, + "include": ["src/**/*"] +} +//// [D:/work/deps/dep.d.ts] *new* +export declare const myValue: string; + +tsgo --b --verbose +ExitStatus:: Success +Output:: +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is out of date because output file 'dist/tsconfig.tsbuildinfo' does not exist + +[HH:MM:SS AM] Building project 'tsconfig.json'... + +//// [C:/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts] *Lib* +/// +interface Boolean {} +interface Function {} +interface CallableFunction {} +interface NewableFunction {} +interface IArguments {} +interface Number { toExponential: any; } +interface Object {} +interface RegExp {} +interface String { charAt: any; } +interface Array { length: number; [n: number]: T; } +interface ReadonlyArray {} +interface SymbolConstructor { + (desc?: string | number): symbol; + for(name: string): symbol; + readonly toStringTag: symbol; +} +declare var Symbol: SymbolConstructor; +interface Symbol { + readonly [Symbol.toStringTag]: string; +} +declare const console: { log(msg: any): void; }; +//// [C:/work/project/dist/src/index.d.ts] *new* +export declare const value: string; + +//// [C:/work/project/dist/src/index.js] *new* +import { myValue } from "abs-dep"; +export const value = myValue; + +//// [C:/work/project/dist/tsconfig.tsbuildinfo] *new* +{"version":"FakeTSVersion","root":[3],"fileNames":["lib.es2025.full.d.ts","d:/work/deps/dep.d.ts","../src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;",{"version":"6c77917c7b17b3698cb1dbdb7227fbff-import { myValue } from \"abs-dep\";\nexport const value: string = myValue;","signature":"d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./","strict":true},"referencedMap":[[3,1]],"latestChangedDtsFile":"./src/index.d.ts"} +//// [C:/work/project/dist/tsconfig.tsbuildinfo.readable.baseline.txt] *new* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../src/index.ts" + ], + "original": 3 + } + ], + "fileNames": [ + "lib.es2025.full.d.ts", + "d:/work/deps/dep.d.ts", + "../src/index.ts" + ], + "fileInfos": [ + { + "fileName": "lib.es2025.full.d.ts", + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "signature": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": "CommonJS", + "original": { + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": 1 + } + }, + { + "fileName": "d:/work/deps/dep.d.ts", + "version": "4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;", + "signature": "4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;", + "impliedNodeFormat": "CommonJS" + }, + { + "fileName": "../src/index.ts", + "version": "6c77917c7b17b3698cb1dbdb7227fbff-import { myValue } from \"abs-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "6c77917c7b17b3698cb1dbdb7227fbff-import { myValue } from \"abs-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": 1 + } + } + ], + "fileIdsList": [ + [ + "d:/work/deps/dep.d.ts" + ] + ], + "options": { + "composite": true, + "outDir": "./", + "strict": true + }, + "referencedMap": { + "../src/index.ts": [ + "d:/work/deps/dep.d.ts" + ] + }, + "latestChangedDtsFile": "./src/index.d.ts", + "size": 1347 +} + +tsconfig.json:: +SemanticDiagnostics:: +*refresh* C:/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* D:/work/deps/dep.d.ts +*refresh* C:/work/project/src/index.ts +Signatures:: +(stored at emit) C:/work/project/src/index.ts + + +Edit [0]:: update absolute non-root dependency with breaking type change +//// [D:/work/deps/dep.d.ts] *modified* +export declare const myValue: number; + +tsgo --b --verbose +ExitStatus:: DiagnosticsPresent_OutputsGenerated +Output:: +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is out of date because output 'dist/tsconfig.tsbuildinfo' is older than input 'd:/work/deps/dep.d.ts' + +[HH:MM:SS AM] Building project 'tsconfig.json'... + +src/index.ts:2:14 - error TS2322: Type 'number' is not assignable to type 'string'. + +2 export const value: string = myValue; +   ~~~~~ + + +Found 1 error in src/index.ts:2 + +//// [C:/work/project/dist/src/index.js] *rewrite with same content* +//// [C:/work/project/dist/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":[3],"fileNames":["lib.es2025.full.d.ts","d:/work/deps/dep.d.ts","../src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;",{"version":"6c77917c7b17b3698cb1dbdb7227fbff-import { myValue } from \"abs-dep\";\nexport const value: string = myValue;","signature":"d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./","strict":true},"referencedMap":[[3,1]],"semanticDiagnosticsPerFile":[[3,[{"pos":48,"end":53,"code":2322,"category":1,"messageKey":"Type_0_is_not_assignable_to_type_1_2322","messageArgs":["number","string"]}]]],"latestChangedDtsFile":"./src/index.d.ts"} +//// [C:/work/project/dist/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../src/index.ts" + ], + "original": 3 + } + ], + "fileNames": [ + "lib.es2025.full.d.ts", + "d:/work/deps/dep.d.ts", + "../src/index.ts" + ], + "fileInfos": [ + { + "fileName": "lib.es2025.full.d.ts", + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "signature": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": "CommonJS", + "original": { + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": 1 + } + }, + { + "fileName": "d:/work/deps/dep.d.ts", + "version": "936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;", + "signature": "936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;", + "impliedNodeFormat": "CommonJS" + }, + { + "fileName": "../src/index.ts", + "version": "6c77917c7b17b3698cb1dbdb7227fbff-import { myValue } from \"abs-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "6c77917c7b17b3698cb1dbdb7227fbff-import { myValue } from \"abs-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": 1 + } + } + ], + "fileIdsList": [ + [ + "d:/work/deps/dep.d.ts" + ] + ], + "options": { + "composite": true, + "outDir": "./", + "strict": true + }, + "referencedMap": { + "../src/index.ts": [ + "d:/work/deps/dep.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + [ + "../src/index.ts", + [ + { + "pos": 48, + "end": 53, + "code": 2322, + "category": 1, + "messageKey": "Type_0_is_not_assignable_to_type_1_2322", + "messageArgs": [ + "number", + "string" + ] + } + ] + ] + ], + "latestChangedDtsFile": "./src/index.d.ts", + "size": 1518 +} + +tsconfig.json:: +SemanticDiagnostics:: +*refresh* D:/work/deps/dep.d.ts +*refresh* C:/work/project/src/index.ts +Signatures:: +(used version) D:/work/deps/dep.d.ts +(computed .d.ts) C:/work/project/src/index.ts diff --git a/testdata/baselines/reference/tsbuild/dependencyUpdate/rebuilds-when-dependency-in-node_modules-is-updated.js b/testdata/baselines/reference/tsbuild/dependencyUpdate/rebuilds-when-dependency-in-node_modules-is-updated.js new file mode 100644 index 00000000000..2542e44aa31 --- /dev/null +++ b/testdata/baselines/reference/tsbuild/dependencyUpdate/rebuilds-when-dependency-in-node_modules-is-updated.js @@ -0,0 +1,501 @@ +currentDirectory::/home/src/workspaces/project +useCaseSensitiveFileNames::true +Input:: +//// [/home/src/workspaces/project/node_modules/my-dep/index.d.ts] *new* +export declare const myValue: string; +//// [/home/src/workspaces/project/node_modules/my-dep/package.json] *new* +{ + "name": "my-dep", + "version": "1.0.0", + "types": "index.d.ts" +} +//// [/home/src/workspaces/project/src/index.ts] *new* +import { myValue } from "my-dep"; +export const value: string = myValue; +//// [/home/src/workspaces/project/tsconfig.json] *new* +{ + "compilerOptions": { + "composite": true, + "outDir": "dist", + "strict": true + }, + "include": ["src/**/*"] +} + +tsgo --b --verbose +ExitStatus:: Success +Output:: +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is out of date because output file 'dist/tsconfig.tsbuildinfo' does not exist + +[HH:MM:SS AM] Building project 'tsconfig.json'... + +//// [/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts] *Lib* +/// +interface Boolean {} +interface Function {} +interface CallableFunction {} +interface NewableFunction {} +interface IArguments {} +interface Number { toExponential: any; } +interface Object {} +interface RegExp {} +interface String { charAt: any; } +interface Array { length: number; [n: number]: T; } +interface ReadonlyArray {} +interface SymbolConstructor { + (desc?: string | number): symbol; + for(name: string): symbol; + readonly toStringTag: symbol; +} +declare var Symbol: SymbolConstructor; +interface Symbol { + readonly [Symbol.toStringTag]: string; +} +declare const console: { log(msg: any): void; }; +//// [/home/src/workspaces/project/dist/src/index.d.ts] *new* +export declare const value: string; + +//// [/home/src/workspaces/project/dist/src/index.js] *new* +import { myValue } from "my-dep"; +export const value = myValue; + +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo] *new* +{"version":"FakeTSVersion","root":[3],"packageJsons":["../node_modules/my-dep/package.json"],"fileNames":["lib.es2025.full.d.ts","../node_modules/my-dep/index.d.ts","../src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;",{"version":"bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;","signature":"d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./","strict":true},"referencedMap":[[3,1]],"latestChangedDtsFile":"./src/index.d.ts"} +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo.readable.baseline.txt] *new* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../src/index.ts" + ], + "original": 3 + } + ], + "packageJsons": [ + "../node_modules/my-dep/package.json" + ], + "fileNames": [ + "lib.es2025.full.d.ts", + "../node_modules/my-dep/index.d.ts", + "../src/index.ts" + ], + "fileInfos": [ + { + "fileName": "lib.es2025.full.d.ts", + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "signature": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": "CommonJS", + "original": { + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": 1 + } + }, + { + "fileName": "../node_modules/my-dep/index.d.ts", + "version": "4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;", + "signature": "4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;", + "impliedNodeFormat": "CommonJS" + }, + { + "fileName": "../src/index.ts", + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": 1 + } + } + ], + "fileIdsList": [ + [ + "../node_modules/my-dep/index.d.ts" + ] + ], + "options": { + "composite": true, + "outDir": "./", + "strict": true + }, + "referencedMap": { + "../src/index.ts": [ + "../node_modules/my-dep/index.d.ts" + ] + }, + "latestChangedDtsFile": "./src/index.d.ts", + "size": 1413 +} + +tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* /home/src/workspaces/project/node_modules/my-dep/index.d.ts +*refresh* /home/src/workspaces/project/src/index.ts +Signatures:: +(stored at emit) /home/src/workspaces/project/src/index.ts + + +Edit [0]:: no change + +tsgo --b --verbose +ExitStatus:: Success +Output:: +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is up to date because newest input 'src/index.ts' is older than output 'dist/tsconfig.tsbuildinfo' + + + + +Edit [1]:: update dependency d.ts with breaking type change +//// [/home/src/workspaces/project/node_modules/my-dep/index.d.ts] *modified* +export declare const myValue: number; + +tsgo --b --verbose +ExitStatus:: DiagnosticsPresent_OutputsGenerated +Output:: +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is out of date because output 'dist/tsconfig.tsbuildinfo' is older than input 'node_modules/my-dep/index.d.ts' + +[HH:MM:SS AM] Building project 'tsconfig.json'... + +src/index.ts:2:14 - error TS2322: Type 'number' is not assignable to type 'string'. + +2 export const value: string = myValue; +   ~~~~~ + + +Found 1 error in src/index.ts:2 + +//// [/home/src/workspaces/project/dist/src/index.js] *rewrite with same content* +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":[3],"packageJsons":["../node_modules/my-dep/package.json"],"fileNames":["lib.es2025.full.d.ts","../node_modules/my-dep/index.d.ts","../src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;",{"version":"bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;","signature":"d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./","strict":true},"referencedMap":[[3,1]],"semanticDiagnosticsPerFile":[[3,[{"pos":47,"end":52,"code":2322,"category":1,"messageKey":"Type_0_is_not_assignable_to_type_1_2322","messageArgs":["number","string"]}]]],"latestChangedDtsFile":"./src/index.d.ts"} +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../src/index.ts" + ], + "original": 3 + } + ], + "packageJsons": [ + "../node_modules/my-dep/package.json" + ], + "fileNames": [ + "lib.es2025.full.d.ts", + "../node_modules/my-dep/index.d.ts", + "../src/index.ts" + ], + "fileInfos": [ + { + "fileName": "lib.es2025.full.d.ts", + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "signature": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": "CommonJS", + "original": { + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": 1 + } + }, + { + "fileName": "../node_modules/my-dep/index.d.ts", + "version": "936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;", + "signature": "936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;", + "impliedNodeFormat": "CommonJS" + }, + { + "fileName": "../src/index.ts", + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": 1 + } + } + ], + "fileIdsList": [ + [ + "../node_modules/my-dep/index.d.ts" + ] + ], + "options": { + "composite": true, + "outDir": "./", + "strict": true + }, + "referencedMap": { + "../src/index.ts": [ + "../node_modules/my-dep/index.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + [ + "../src/index.ts", + [ + { + "pos": 47, + "end": 52, + "code": 2322, + "category": 1, + "messageKey": "Type_0_is_not_assignable_to_type_1_2322", + "messageArgs": [ + "number", + "string" + ] + } + ] + ] + ], + "latestChangedDtsFile": "./src/index.d.ts", + "size": 1584 +} + +tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/workspaces/project/node_modules/my-dep/index.d.ts +*refresh* /home/src/workspaces/project/src/index.ts +Signatures:: +(used version) /home/src/workspaces/project/node_modules/my-dep/index.d.ts +(computed .d.ts) /home/src/workspaces/project/src/index.ts + + +Edit [2]:: restore dependency d.ts +//// [/home/src/workspaces/project/node_modules/my-dep/index.d.ts] *modified* +export declare const myValue: string; + +tsgo --b --verbose +ExitStatus:: Success +Output:: +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is out of date because buildinfo file 'dist/tsconfig.tsbuildinfo' indicates that program needs to report errors. + +[HH:MM:SS AM] Building project 'tsconfig.json'... + +//// [/home/src/workspaces/project/dist/src/index.js] *rewrite with same content* +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":[3],"packageJsons":["../node_modules/my-dep/package.json"],"fileNames":["lib.es2025.full.d.ts","../node_modules/my-dep/index.d.ts","../src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;",{"version":"bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;","signature":"d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./","strict":true},"referencedMap":[[3,1]],"latestChangedDtsFile":"./src/index.d.ts"} +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../src/index.ts" + ], + "original": 3 + } + ], + "packageJsons": [ + "../node_modules/my-dep/package.json" + ], + "fileNames": [ + "lib.es2025.full.d.ts", + "../node_modules/my-dep/index.d.ts", + "../src/index.ts" + ], + "fileInfos": [ + { + "fileName": "lib.es2025.full.d.ts", + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "signature": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": "CommonJS", + "original": { + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": 1 + } + }, + { + "fileName": "../node_modules/my-dep/index.d.ts", + "version": "4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;", + "signature": "4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;", + "impliedNodeFormat": "CommonJS" + }, + { + "fileName": "../src/index.ts", + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": 1 + } + } + ], + "fileIdsList": [ + [ + "../node_modules/my-dep/index.d.ts" + ] + ], + "options": { + "composite": true, + "outDir": "./", + "strict": true + }, + "referencedMap": { + "../src/index.ts": [ + "../node_modules/my-dep/index.d.ts" + ] + }, + "latestChangedDtsFile": "./src/index.d.ts", + "size": 1413 +} + +tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/workspaces/project/node_modules/my-dep/index.d.ts +*refresh* /home/src/workspaces/project/src/index.ts +Signatures:: +(used version) /home/src/workspaces/project/node_modules/my-dep/index.d.ts +(computed .d.ts) /home/src/workspaces/project/src/index.ts + + +Edit [3]:: update dependency d.ts timestamp without changing text +//// [/home/src/workspaces/project/node_modules/my-dep/index.d.ts] *mTime changed* + +tsgo --b --verbose +ExitStatus:: Success +Output:: +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is up to date but needs to update timestamps of output files that are older than input files + +[HH:MM:SS AM] Updating output timestamps of project 'tsconfig.json'... + +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo] *mTime changed* + + + +Edit [4]:: no change + +tsgo --b --verbose +ExitStatus:: Success +Output:: +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is up to date because newest input 'src/index.ts' is older than output 'dist/tsconfig.tsbuildinfo' + + + + +Edit [5]:: delete dependency d.ts +//// [/home/src/workspaces/project/node_modules/my-dep/index.d.ts] *deleted* + +tsgo --b --verbose +ExitStatus:: DiagnosticsPresent_OutputsGenerated +Output:: +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is out of date because input 'node_modules/my-dep/index.d.ts' does not exist. + +[HH:MM:SS AM] Building project 'tsconfig.json'... + +src/index.ts:1:25 - error TS2307: Cannot find module 'my-dep' or its corresponding type declarations. + +1 import { myValue } from "my-dep"; +   ~~~~~~~~ + + +Found 1 error in src/index.ts:1 + +//// [/home/src/workspaces/project/dist/src/index.js] *rewrite with same content* +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":[2],"packageJsons":["../node_modules/my-dep/package.json"],"fileNames":["lib.es2025.full.d.ts","../src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;","signature":"d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n","impliedNodeFormat":1}],"options":{"composite":true,"outDir":"./","strict":true},"semanticDiagnosticsPerFile":[[2,[{"pos":24,"end":32,"code":2307,"category":1,"messageKey":"Cannot_find_module_0_or_its_corresponding_type_declarations_2307","messageArgs":["my-dep"]}]]],"latestChangedDtsFile":"./src/index.d.ts"} +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../src/index.ts" + ], + "original": 2 + } + ], + "packageJsons": [ + "../node_modules/my-dep/package.json" + ], + "fileNames": [ + "lib.es2025.full.d.ts", + "../src/index.ts" + ], + "fileInfos": [ + { + "fileName": "lib.es2025.full.d.ts", + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "signature": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": "CommonJS", + "original": { + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": 1 + } + }, + { + "fileName": "../src/index.ts", + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": 1 + } + } + ], + "options": { + "composite": true, + "outDir": "./", + "strict": true + }, + "semanticDiagnosticsPerFile": [ + [ + "../src/index.ts", + [ + { + "pos": 24, + "end": 32, + "code": 2307, + "category": 1, + "messageKey": "Cannot_find_module_0_or_its_corresponding_type_declarations_2307", + "messageArgs": [ + "my-dep" + ] + } + ] + ] + ], + "latestChangedDtsFile": "./src/index.d.ts", + "size": 1447 +} + +tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/workspaces/project/src/index.ts +Signatures:: +(computed .d.ts) /home/src/workspaces/project/src/index.ts diff --git a/testdata/baselines/reference/tsbuild/dependencyUpdate/rebuilds-when-dependency-package-json-redirects-to-a-different-declaration-file.js b/testdata/baselines/reference/tsbuild/dependencyUpdate/rebuilds-when-dependency-package-json-redirects-to-a-different-declaration-file.js new file mode 100644 index 00000000000..dfac593a3ec --- /dev/null +++ b/testdata/baselines/reference/tsbuild/dependencyUpdate/rebuilds-when-dependency-package-json-redirects-to-a-different-declaration-file.js @@ -0,0 +1,269 @@ +currentDirectory::/home/src/workspaces/project +useCaseSensitiveFileNames::true +Input:: +//// [/home/src/workspaces/project/node_modules/my-dep/alt.d.ts] *new* +export declare const myValue: number; +//// [/home/src/workspaces/project/node_modules/my-dep/index.d.ts] *new* +export declare const myValue: string; +//// [/home/src/workspaces/project/node_modules/my-dep/package.json] *new* +{ + "name": "my-dep", + "version": "1.0.0", + "types": "index.d.ts" +} +//// [/home/src/workspaces/project/src/index.ts] *new* +import { myValue } from "my-dep"; +export const value: string = myValue; +//// [/home/src/workspaces/project/tsconfig.json] *new* +{ + "compilerOptions": { + "composite": true, + "outDir": "dist", + "strict": true + }, + "include": ["src/**/*"] +} + +tsgo --b --verbose +ExitStatus:: Success +Output:: +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is out of date because output file 'dist/tsconfig.tsbuildinfo' does not exist + +[HH:MM:SS AM] Building project 'tsconfig.json'... + +//// [/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts] *Lib* +/// +interface Boolean {} +interface Function {} +interface CallableFunction {} +interface NewableFunction {} +interface IArguments {} +interface Number { toExponential: any; } +interface Object {} +interface RegExp {} +interface String { charAt: any; } +interface Array { length: number; [n: number]: T; } +interface ReadonlyArray {} +interface SymbolConstructor { + (desc?: string | number): symbol; + for(name: string): symbol; + readonly toStringTag: symbol; +} +declare var Symbol: SymbolConstructor; +interface Symbol { + readonly [Symbol.toStringTag]: string; +} +declare const console: { log(msg: any): void; }; +//// [/home/src/workspaces/project/dist/src/index.d.ts] *new* +export declare const value: string; + +//// [/home/src/workspaces/project/dist/src/index.js] *new* +import { myValue } from "my-dep"; +export const value = myValue; + +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo] *new* +{"version":"FakeTSVersion","root":[3],"packageJsons":["../node_modules/my-dep/package.json"],"fileNames":["lib.es2025.full.d.ts","../node_modules/my-dep/index.d.ts","../src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;",{"version":"bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;","signature":"d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./","strict":true},"referencedMap":[[3,1]],"latestChangedDtsFile":"./src/index.d.ts"} +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo.readable.baseline.txt] *new* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../src/index.ts" + ], + "original": 3 + } + ], + "packageJsons": [ + "../node_modules/my-dep/package.json" + ], + "fileNames": [ + "lib.es2025.full.d.ts", + "../node_modules/my-dep/index.d.ts", + "../src/index.ts" + ], + "fileInfos": [ + { + "fileName": "lib.es2025.full.d.ts", + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "signature": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": "CommonJS", + "original": { + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": 1 + } + }, + { + "fileName": "../node_modules/my-dep/index.d.ts", + "version": "4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;", + "signature": "4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;", + "impliedNodeFormat": "CommonJS" + }, + { + "fileName": "../src/index.ts", + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": 1 + } + } + ], + "fileIdsList": [ + [ + "../node_modules/my-dep/index.d.ts" + ] + ], + "options": { + "composite": true, + "outDir": "./", + "strict": true + }, + "referencedMap": { + "../src/index.ts": [ + "../node_modules/my-dep/index.d.ts" + ] + }, + "latestChangedDtsFile": "./src/index.d.ts", + "size": 1413 +} + +tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* /home/src/workspaces/project/node_modules/my-dep/index.d.ts +*refresh* /home/src/workspaces/project/src/index.ts +Signatures:: +(stored at emit) /home/src/workspaces/project/src/index.ts + + +Edit [0]:: redirect package types to a declaration file with a breaking type change +//// [/home/src/workspaces/project/node_modules/my-dep/package.json] *modified* +{ + "name": "my-dep", + "version": "1.0.0", + "types": "alt.d.ts" +} + +tsgo --b --verbose +ExitStatus:: DiagnosticsPresent_OutputsGenerated +Output:: +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is out of date because output 'dist/tsconfig.tsbuildinfo' is older than input 'node_modules/my-dep/package.json' + +[HH:MM:SS AM] Building project 'tsconfig.json'... + +src/index.ts:2:14 - error TS2322: Type 'number' is not assignable to type 'string'. + +2 export const value: string = myValue; +   ~~~~~ + + +Found 1 error in src/index.ts:2 + +//// [/home/src/workspaces/project/dist/src/index.js] *rewrite with same content* +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":[3],"packageJsons":["../node_modules/my-dep/package.json"],"fileNames":["lib.es2025.full.d.ts","../node_modules/my-dep/alt.d.ts","../src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;",{"version":"bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;","signature":"d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./","strict":true},"referencedMap":[[3,1]],"semanticDiagnosticsPerFile":[[3,[{"pos":47,"end":52,"code":2322,"category":1,"messageKey":"Type_0_is_not_assignable_to_type_1_2322","messageArgs":["number","string"]}]]],"latestChangedDtsFile":"./src/index.d.ts"} +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../src/index.ts" + ], + "original": 3 + } + ], + "packageJsons": [ + "../node_modules/my-dep/package.json" + ], + "fileNames": [ + "lib.es2025.full.d.ts", + "../node_modules/my-dep/alt.d.ts", + "../src/index.ts" + ], + "fileInfos": [ + { + "fileName": "lib.es2025.full.d.ts", + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "signature": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": "CommonJS", + "original": { + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": 1 + } + }, + { + "fileName": "../node_modules/my-dep/alt.d.ts", + "version": "936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;", + "signature": "936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;", + "impliedNodeFormat": "CommonJS" + }, + { + "fileName": "../src/index.ts", + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": 1 + } + } + ], + "fileIdsList": [ + [ + "../node_modules/my-dep/alt.d.ts" + ] + ], + "options": { + "composite": true, + "outDir": "./", + "strict": true + }, + "referencedMap": { + "../src/index.ts": [ + "../node_modules/my-dep/alt.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + [ + "../src/index.ts", + [ + { + "pos": 47, + "end": 52, + "code": 2322, + "category": 1, + "messageKey": "Type_0_is_not_assignable_to_type_1_2322", + "messageArgs": [ + "number", + "string" + ] + } + ] + ] + ], + "latestChangedDtsFile": "./src/index.d.ts", + "size": 1582 +} + +tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/workspaces/project/node_modules/my-dep/alt.d.ts +*refresh* /home/src/workspaces/project/src/index.ts +Signatures:: +(used version) /home/src/workspaces/project/node_modules/my-dep/alt.d.ts +(computed .d.ts) /home/src/workspaces/project/src/index.ts diff --git a/testdata/baselines/reference/tsbuild/dependencyUpdate/rebuilds-when-missing-dependency-package-json-is-added.js b/testdata/baselines/reference/tsbuild/dependencyUpdate/rebuilds-when-missing-dependency-package-json-is-added.js new file mode 100644 index 00000000000..e9dc224f11a --- /dev/null +++ b/testdata/baselines/reference/tsbuild/dependencyUpdate/rebuilds-when-missing-dependency-package-json-is-added.js @@ -0,0 +1,260 @@ +currentDirectory::/home/src/workspaces/project +useCaseSensitiveFileNames::true +Input:: +//// [/home/src/workspaces/project/node_modules/my-dep/alt.d.ts] *new* +export declare const myValue: number; +//// [/home/src/workspaces/project/node_modules/my-dep/index.d.ts] *new* +export declare const myValue: string; +//// [/home/src/workspaces/project/src/index.ts] *new* +import { myValue } from "my-dep"; +export const value: string = myValue; +//// [/home/src/workspaces/project/tsconfig.json] *new* +{ + "compilerOptions": { + "composite": true, + "outDir": "dist", + "strict": true + }, + "include": ["src/**/*"] +} + +tsgo --b --verbose +ExitStatus:: Success +Output:: +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is out of date because output file 'dist/tsconfig.tsbuildinfo' does not exist + +[HH:MM:SS AM] Building project 'tsconfig.json'... + +//// [/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts] *Lib* +/// +interface Boolean {} +interface Function {} +interface CallableFunction {} +interface NewableFunction {} +interface IArguments {} +interface Number { toExponential: any; } +interface Object {} +interface RegExp {} +interface String { charAt: any; } +interface Array { length: number; [n: number]: T; } +interface ReadonlyArray {} +interface SymbolConstructor { + (desc?: string | number): symbol; + for(name: string): symbol; + readonly toStringTag: symbol; +} +declare var Symbol: SymbolConstructor; +interface Symbol { + readonly [Symbol.toStringTag]: string; +} +declare const console: { log(msg: any): void; }; +//// [/home/src/workspaces/project/dist/src/index.d.ts] *new* +export declare const value: string; + +//// [/home/src/workspaces/project/dist/src/index.js] *new* +import { myValue } from "my-dep"; +export const value = myValue; + +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo] *new* +{"version":"FakeTSVersion","root":[3],"missingPackageJsons":["../node_modules/my-dep/package.json","../node_modules/package.json"],"fileNames":["lib.es2025.full.d.ts","../node_modules/my-dep/index.d.ts","../src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;",{"version":"bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;","signature":"d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./","strict":true},"referencedMap":[[3,1]],"latestChangedDtsFile":"./src/index.d.ts"} +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo.readable.baseline.txt] *new* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../src/index.ts" + ], + "original": 3 + } + ], + "missingPackageJsons": [ + "../node_modules/my-dep/package.json", + "../node_modules/package.json" + ], + "fileNames": [ + "lib.es2025.full.d.ts", + "../node_modules/my-dep/index.d.ts", + "../src/index.ts" + ], + "fileInfos": [ + { + "fileName": "lib.es2025.full.d.ts", + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "signature": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": "CommonJS", + "original": { + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": 1 + } + }, + { + "fileName": "../node_modules/my-dep/index.d.ts", + "version": "4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;", + "signature": "4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;", + "impliedNodeFormat": "CommonJS" + }, + { + "fileName": "../src/index.ts", + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": 1 + } + } + ], + "fileIdsList": [ + [ + "../node_modules/my-dep/index.d.ts" + ] + ], + "options": { + "composite": true, + "outDir": "./", + "strict": true + }, + "referencedMap": { + "../src/index.ts": [ + "../node_modules/my-dep/index.d.ts" + ] + }, + "latestChangedDtsFile": "./src/index.d.ts", + "size": 1451 +} + +tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* /home/src/workspaces/project/node_modules/my-dep/index.d.ts +*refresh* /home/src/workspaces/project/src/index.ts +Signatures:: +(stored at emit) /home/src/workspaces/project/src/index.ts + + +Edit [0]:: add package json redirecting types to a declaration file with a breaking type change +//// [/home/src/workspaces/project/node_modules/my-dep/package.json] *new* +{"types":"alt.d.ts"} + +tsgo --b --verbose +ExitStatus:: DiagnosticsPresent_OutputsGenerated +Output:: +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is out of date because output 'dist/tsconfig.tsbuildinfo' is older than input 'node_modules/my-dep/package.json' + +[HH:MM:SS AM] Building project 'tsconfig.json'... + +src/index.ts:2:14 - error TS2322: Type 'number' is not assignable to type 'string'. + +2 export const value: string = myValue; +   ~~~~~ + + +Found 1 error in src/index.ts:2 + +//// [/home/src/workspaces/project/dist/src/index.js] *rewrite with same content* +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":[3],"packageJsons":["../node_modules/my-dep/package.json"],"fileNames":["lib.es2025.full.d.ts","../node_modules/my-dep/alt.d.ts","../src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;",{"version":"bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;","signature":"d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./","strict":true},"referencedMap":[[3,1]],"semanticDiagnosticsPerFile":[[3,[{"pos":47,"end":52,"code":2322,"category":1,"messageKey":"Type_0_is_not_assignable_to_type_1_2322","messageArgs":["number","string"]}]]],"latestChangedDtsFile":"./src/index.d.ts"} +//// [/home/src/workspaces/project/dist/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../src/index.ts" + ], + "original": 3 + } + ], + "packageJsons": [ + "../node_modules/my-dep/package.json" + ], + "fileNames": [ + "lib.es2025.full.d.ts", + "../node_modules/my-dep/alt.d.ts", + "../src/index.ts" + ], + "fileInfos": [ + { + "fileName": "lib.es2025.full.d.ts", + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "signature": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": "CommonJS", + "original": { + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": 1 + } + }, + { + "fileName": "../node_modules/my-dep/alt.d.ts", + "version": "936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;", + "signature": "936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;", + "impliedNodeFormat": "CommonJS" + }, + { + "fileName": "../src/index.ts", + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "bae961fec80482368db43a089f169190-import { myValue } from \"my-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": 1 + } + } + ], + "fileIdsList": [ + [ + "../node_modules/my-dep/alt.d.ts" + ] + ], + "options": { + "composite": true, + "outDir": "./", + "strict": true + }, + "referencedMap": { + "../src/index.ts": [ + "../node_modules/my-dep/alt.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + [ + "../src/index.ts", + [ + { + "pos": 47, + "end": 52, + "code": 2322, + "category": 1, + "messageKey": "Type_0_is_not_assignable_to_type_1_2322", + "messageArgs": [ + "number", + "string" + ] + } + ] + ] + ], + "latestChangedDtsFile": "./src/index.d.ts", + "size": 1582 +} + +tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/workspaces/project/node_modules/my-dep/alt.d.ts +*refresh* /home/src/workspaces/project/src/index.ts +Signatures:: +(used version) /home/src/workspaces/project/node_modules/my-dep/alt.d.ts +(computed .d.ts) /home/src/workspaces/project/src/index.ts diff --git a/testdata/baselines/reference/tsbuild/inferredTypeFromMonorepoReference/inferred-type-from-referenced-project-that-references-another-project-in-monorepo.js b/testdata/baselines/reference/tsbuild/inferredTypeFromMonorepoReference/inferred-type-from-referenced-project-that-references-another-project-in-monorepo.js index 1c65a08a995..f46592f3d93 100644 --- a/testdata/baselines/reference/tsbuild/inferredTypeFromMonorepoReference/inferred-type-from-referenced-project-that-references-another-project-in-monorepo.js +++ b/testdata/baselines/reference/tsbuild/inferredTypeFromMonorepoReference/inferred-type-from-referenced-project-that-references-another-project-in-monorepo.js @@ -178,7 +178,7 @@ declare class MyClass { export { MyClass }; //// [/home/src/workspaces/solution/packages/package-a/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[4],"fileNames":["lib.es2022.full.d.ts","../package-c/out/index.d.ts","../package-b/out/index.d.ts","./src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"fda98a6734eab276b5c9c8694ee117da-export interface MyType {\n id: string;\n name: string;\n enabled: boolean;\n}\n","c244312b1cf9f2fd4ddd2d16bb44d0b9-import type { MyType } from \"package-c\";\nexport declare function createThing(input: MyType): MyType;\n",{"version":"1b8e37ecd837c2f357c793c86828b133-import { createThing } from \"package-b\";\n\nclass MyClass {\n public thing = createThing({ id: \"1\", name: \"test\", enabled: true });\n}\n\nexport { MyClass };","signature":"f0d3d8e75bf995728f62a7d715cdf8a8-declare class MyClass {\n thing: import(\"package-c\").MyType;\n}\nexport { MyClass };\n","impliedNodeFormat":1}],"fileIdsList":[[3],[2]],"options":{"composite":true,"emitDeclarationOnly":true,"declaration":true,"module":99,"outDir":"./out","rootDir":"./src","target":9},"referencedMap":[[4,1],[3,2]],"latestChangedDtsFile":"./out/index.d.ts"} +{"version":"FakeTSVersion","root":[4],"packageJsons":["./package.json","../package-b/package.json","../package-c/package.json"],"fileNames":["lib.es2022.full.d.ts","../package-c/out/index.d.ts","../package-b/out/index.d.ts","./src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"fda98a6734eab276b5c9c8694ee117da-export interface MyType {\n id: string;\n name: string;\n enabled: boolean;\n}\n","c244312b1cf9f2fd4ddd2d16bb44d0b9-import type { MyType } from \"package-c\";\nexport declare function createThing(input: MyType): MyType;\n",{"version":"1b8e37ecd837c2f357c793c86828b133-import { createThing } from \"package-b\";\n\nclass MyClass {\n public thing = createThing({ id: \"1\", name: \"test\", enabled: true });\n}\n\nexport { MyClass };","signature":"f0d3d8e75bf995728f62a7d715cdf8a8-declare class MyClass {\n thing: import(\"package-c\").MyType;\n}\nexport { MyClass };\n","impliedNodeFormat":1}],"fileIdsList":[[3],[2]],"options":{"composite":true,"emitDeclarationOnly":true,"declaration":true,"module":99,"outDir":"./out","rootDir":"./src","target":9},"referencedMap":[[4,1],[3,2]],"latestChangedDtsFile":"./out/index.d.ts"} //// [/home/src/workspaces/solution/packages/package-a/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -190,6 +190,11 @@ export { MyClass }; "original": 4 } ], + "packageJsons": [ + "./package.json", + "../package-b/package.json", + "../package-c/package.json" + ], "fileNames": [ "lib.es2022.full.d.ts", "../package-c/out/index.d.ts", @@ -259,14 +264,14 @@ export { MyClass }; ] }, "latestChangedDtsFile": "./out/index.d.ts", - "size": 1806 + "size": 1896 } //// [/home/src/workspaces/solution/packages/package-b/out/index.d.ts] *new* import type { MyType } from "package-c"; export declare function createThing(input: MyType): MyType; //// [/home/src/workspaces/solution/packages/package-b/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[3],"fileNames":["lib.es2022.full.d.ts","../package-c/out/index.d.ts","./src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"fda98a6734eab276b5c9c8694ee117da-export interface MyType {\n id: string;\n name: string;\n enabled: boolean;\n}\n",{"version":"fbb82e716b8d6d09c2f530e11f7c8614-import type { MyType } from \"package-c\";\n\nexport function createThing(input: MyType): MyType {\n return { ...input };\n}","signature":"c244312b1cf9f2fd4ddd2d16bb44d0b9-import type { MyType } from \"package-c\";\nexport declare function createThing(input: MyType): MyType;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"emitDeclarationOnly":true,"declaration":true,"module":99,"outDir":"./out","rootDir":"./src","target":9},"referencedMap":[[3,1]],"latestChangedDtsFile":"./out/index.d.ts"} +{"version":"FakeTSVersion","root":[3],"packageJsons":["./package.json","../package-c/package.json"],"fileNames":["lib.es2022.full.d.ts","../package-c/out/index.d.ts","./src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"fda98a6734eab276b5c9c8694ee117da-export interface MyType {\n id: string;\n name: string;\n enabled: boolean;\n}\n",{"version":"fbb82e716b8d6d09c2f530e11f7c8614-import type { MyType } from \"package-c\";\n\nexport function createThing(input: MyType): MyType {\n return { ...input };\n}","signature":"c244312b1cf9f2fd4ddd2d16bb44d0b9-import type { MyType } from \"package-c\";\nexport declare function createThing(input: MyType): MyType;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"emitDeclarationOnly":true,"declaration":true,"module":99,"outDir":"./out","rootDir":"./src","target":9},"referencedMap":[[3,1]],"latestChangedDtsFile":"./out/index.d.ts"} //// [/home/src/workspaces/solution/packages/package-b/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -278,6 +283,10 @@ export declare function createThing(input: MyType): MyType; "original": 3 } ], + "packageJsons": [ + "./package.json", + "../package-c/package.json" + ], "fileNames": [ "lib.es2022.full.d.ts", "../package-c/out/index.d.ts", @@ -334,7 +343,7 @@ export declare function createThing(input: MyType): MyType; ] }, "latestChangedDtsFile": "./out/index.d.ts", - "size": 1600 + "size": 1662 } //// [/home/src/workspaces/solution/packages/package-c/out/index.d.ts] *new* export interface MyType { @@ -344,7 +353,7 @@ export interface MyType { } //// [/home/src/workspaces/solution/packages/package-c/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[2],"fileNames":["lib.es2022.full.d.ts","./src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"998713b32693f1c4f45ac4bad0f3285c-export interface MyType {\n id: string;\n name: string;\n enabled: boolean;\n}","signature":"fda98a6734eab276b5c9c8694ee117da-export interface MyType {\n id: string;\n name: string;\n enabled: boolean;\n}\n","impliedNodeFormat":1}],"options":{"composite":true,"emitDeclarationOnly":true,"declaration":true,"module":99,"outDir":"./out","rootDir":"./src","target":9},"latestChangedDtsFile":"./out/index.d.ts"} +{"version":"FakeTSVersion","root":[2],"packageJsons":["./package.json"],"fileNames":["lib.es2022.full.d.ts","./src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"998713b32693f1c4f45ac4bad0f3285c-export interface MyType {\n id: string;\n name: string;\n enabled: boolean;\n}","signature":"fda98a6734eab276b5c9c8694ee117da-export interface MyType {\n id: string;\n name: string;\n enabled: boolean;\n}\n","impliedNodeFormat":1}],"options":{"composite":true,"emitDeclarationOnly":true,"declaration":true,"module":99,"outDir":"./out","rootDir":"./src","target":9},"latestChangedDtsFile":"./out/index.d.ts"} //// [/home/src/workspaces/solution/packages/package-c/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -356,6 +365,9 @@ export interface MyType { "original": 2 } ], + "packageJsons": [ + "./package.json" + ], "fileNames": [ "lib.es2022.full.d.ts", "./src/index.ts" @@ -395,7 +407,7 @@ export interface MyType { "target": 9 }, "latestChangedDtsFile": "./out/index.d.ts", - "size": 1345 + "size": 1379 } packages/package-c/tsconfig.json:: diff --git a/testdata/baselines/reference/tsbuild/libraryResolution/with-config-with-libReplacement.js b/testdata/baselines/reference/tsbuild/libraryResolution/with-config-with-libReplacement.js index f8c3ca8c52c..fb711f4507c 100644 --- a/testdata/baselines/reference/tsbuild/libraryResolution/with-config-with-libReplacement.js +++ b/testdata/baselines/reference/tsbuild/libraryResolution/with-config-with-libReplacement.js @@ -449,7 +449,7 @@ export declare const x = "type1"; export const x = "type1"; //// [/home/src/workspace/projects/project1/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[5,10]],"fileNames":["../node_modules/@typescript/lib-webworker/index.d.ts","../node_modules/@typescript/lib-scripthost/index.d.ts","../node_modules/@typescript/lib-es5/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","./core.d.ts","./file.ts","./file2.ts","./index.ts","./utils.d.ts","./typeroot1/sometype/index.d.ts"],"fileInfos":[{"version":"95c5e18b7871b756fb3bb843e03aa05d-interface WebWorkerInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"2fa71959819338965a3c6b2122d95c96-interface ScriptHostInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},"a1f9b824326bab2c3c8f13eccf69f182-export const core = 10;",{"version":"69c4ea0c9ff13ab7fc078607d9363624-export const file = 10;","signature":"a224c1b0cbd2f5fe611e588db48243cb-export declare const file = 10;\n","impliedNodeFormat":1},{"version":"76f8c505d1aaf1122ce1da0807c21477-/// \n/// \n/// ","signature":"99aa06d3014798d86001c324468d497f-","impliedNodeFormat":1},{"version":"aeb695aed936d7539a32fc3cd25af558-export const x = \"type1\";","signature":"e2f8d12de2edba256e37cf4a656ac52d-export declare const x = \"type1\";\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;","6bf5e0a71dae6fccf68b93fbbb73f178-export type TheNum = \"type1\";"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[[5,10]],"missingPackageJsons":["../node_modules/@typescript/lib-dom/package.json","../node_modules/@typescript/lib-es5/package.json","../node_modules/@typescript/lib-scripthost/package.json","../node_modules/@typescript/lib-webworker/package.json"],"fileNames":["../node_modules/@typescript/lib-webworker/index.d.ts","../node_modules/@typescript/lib-scripthost/index.d.ts","../node_modules/@typescript/lib-es5/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","./core.d.ts","./file.ts","./file2.ts","./index.ts","./utils.d.ts","./typeroot1/sometype/index.d.ts"],"fileInfos":[{"version":"95c5e18b7871b756fb3bb843e03aa05d-interface WebWorkerInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"2fa71959819338965a3c6b2122d95c96-interface ScriptHostInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},"a1f9b824326bab2c3c8f13eccf69f182-export const core = 10;",{"version":"69c4ea0c9ff13ab7fc078607d9363624-export const file = 10;","signature":"a224c1b0cbd2f5fe611e588db48243cb-export declare const file = 10;\n","impliedNodeFormat":1},{"version":"76f8c505d1aaf1122ce1da0807c21477-/// \n/// \n/// ","signature":"99aa06d3014798d86001c324468d497f-","impliedNodeFormat":1},{"version":"aeb695aed936d7539a32fc3cd25af558-export const x = \"type1\";","signature":"e2f8d12de2edba256e37cf4a656ac52d-export declare const x = \"type1\";\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;","6bf5e0a71dae6fccf68b93fbbb73f178-export type TheNum = \"type1\";"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} //// [/home/src/workspace/projects/project1/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -469,6 +469,12 @@ export const x = "type1"; ] } ], + "missingPackageJsons": [ + "../node_modules/@typescript/lib-dom/package.json", + "../node_modules/@typescript/lib-es5/package.json", + "../node_modules/@typescript/lib-scripthost/package.json", + "../node_modules/@typescript/lib-webworker/package.json" + ], "fileNames": [ "../node_modules/@typescript/lib-webworker/index.d.ts", "../node_modules/@typescript/lib-scripthost/index.d.ts", @@ -586,7 +592,7 @@ export const x = "type1"; "composite": true }, "latestChangedDtsFile": "./index.d.ts", - "size": 2354 + "size": 2595 } //// [/home/src/workspace/projects/project2/index.d.ts] *new* export declare const y = 10; @@ -595,7 +601,7 @@ export declare const y = 10; export const y = 10; //// [/home/src/workspace/projects/project2/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[3,4]],"fileNames":["../node_modules/@typescript/lib-es5/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","./index.ts","./utils.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"95e641b4f34db55d73f0f5008cdd30f0-export const y = 10","signature":"7ab1b6e8968172bdd365c972b27a69e2-export declare const y = 10;\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[[3,4]],"missingPackageJsons":["../node_modules/@typescript/lib-dom/package.json","../node_modules/@typescript/lib-es5/package.json"],"fileNames":["../node_modules/@typescript/lib-es5/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","./index.ts","./utils.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"95e641b4f34db55d73f0f5008cdd30f0-export const y = 10","signature":"7ab1b6e8968172bdd365c972b27a69e2-export declare const y = 10;\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} //// [/home/src/workspace/projects/project2/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -611,6 +617,10 @@ export const y = 10; ] } ], + "missingPackageJsons": [ + "../node_modules/@typescript/lib-dom/package.json", + "../node_modules/@typescript/lib-es5/package.json" + ], "fileNames": [ "../node_modules/@typescript/lib-es5/index.d.ts", "../node_modules/@typescript/lib-dom/index.d.ts", @@ -664,7 +674,7 @@ export const y = 10; "composite": true }, "latestChangedDtsFile": "./index.d.ts", - "size": 1378 + "size": 1504 } //// [/home/src/workspace/projects/project3/index.d.ts] *new* export declare const z = 10; @@ -673,7 +683,7 @@ export declare const z = 10; export const z = 10; //// [/home/src/workspace/projects/project3/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[3,4]],"fileNames":["../node_modules/@typescript/lib-es5/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","./index.ts","./utils.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6f4aaa0b206d74bd2835c8fd3a4020fe-export const z = 10","signature":"f4ea7cd61571728ffc44aefcffc4eda1-export declare const z = 10;\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[[3,4]],"missingPackageJsons":["../node_modules/@typescript/lib-dom/package.json","../node_modules/@typescript/lib-es5/package.json"],"fileNames":["../node_modules/@typescript/lib-es5/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","./index.ts","./utils.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6f4aaa0b206d74bd2835c8fd3a4020fe-export const z = 10","signature":"f4ea7cd61571728ffc44aefcffc4eda1-export declare const z = 10;\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} //// [/home/src/workspace/projects/project3/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -689,6 +699,10 @@ export const z = 10; ] } ], + "missingPackageJsons": [ + "../node_modules/@typescript/lib-dom/package.json", + "../node_modules/@typescript/lib-es5/package.json" + ], "fileNames": [ "../node_modules/@typescript/lib-es5/index.d.ts", "../node_modules/@typescript/lib-dom/index.d.ts", @@ -742,7 +756,7 @@ export const z = 10; "composite": true }, "latestChangedDtsFile": "./index.d.ts", - "size": 1378 + "size": 1504 } //// [/home/src/workspace/projects/project4/index.d.ts] *new* export declare const z = 10; @@ -751,7 +765,7 @@ export declare const z = 10; export const z = 10; //// [/home/src/workspace/projects/project4/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[4,5]],"fileNames":["../node_modules/@typescript/lib-esnext/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","../node_modules/@typescript/lib-webworker/index.d.ts","./index.ts","./utils.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"95c5e18b7871b756fb3bb843e03aa05d-interface WebWorkerInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6f4aaa0b206d74bd2835c8fd3a4020fe-export const z = 10","signature":"f4ea7cd61571728ffc44aefcffc4eda1-export declare const z = 10;\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[[4,5]],"missingPackageJsons":["../node_modules/@typescript/lib-dom/package.json","../node_modules/@typescript/lib-esnext/package.json","../node_modules/@typescript/lib-webworker/package.json"],"fileNames":["../node_modules/@typescript/lib-esnext/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","../node_modules/@typescript/lib-webworker/index.d.ts","./index.ts","./utils.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"95c5e18b7871b756fb3bb843e03aa05d-interface WebWorkerInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6f4aaa0b206d74bd2835c8fd3a4020fe-export const z = 10","signature":"f4ea7cd61571728ffc44aefcffc4eda1-export declare const z = 10;\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} //// [/home/src/workspace/projects/project4/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -767,6 +781,11 @@ export const z = 10; ] } ], + "missingPackageJsons": [ + "../node_modules/@typescript/lib-dom/package.json", + "../node_modules/@typescript/lib-esnext/package.json", + "../node_modules/@typescript/lib-webworker/package.json" + ], "fileNames": [ "../node_modules/@typescript/lib-esnext/index.d.ts", "../node_modules/@typescript/lib-dom/index.d.ts", @@ -833,7 +852,7 @@ export const z = 10; "composite": true }, "latestChangedDtsFile": "./index.d.ts", - "size": 1564 + "size": 1750 } project1/tsconfig.json:: diff --git a/testdata/baselines/reference/tsbuild/moduleResolution/impliedNodeFormat-differs-between-projects-for-shared-file.js b/testdata/baselines/reference/tsbuild/moduleResolution/impliedNodeFormat-differs-between-projects-for-shared-file.js index c272be56aa1..2f5f2454655 100644 --- a/testdata/baselines/reference/tsbuild/moduleResolution/impliedNodeFormat-differs-between-projects-for-shared-file.js +++ b/testdata/baselines/reference/tsbuild/moduleResolution/impliedNodeFormat-differs-between-projects-for-shared-file.js @@ -121,7 +121,7 @@ import pg from "pg"; pg.foo(); //// [/home/src/workspaces/project/b/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":["./src/index.ts"]} +{"version":"FakeTSVersion","root":["./src/index.ts"],"packageJsons":["./package.json","../node_modules/@types/pg/package.json"],"missingPackageJsons":["../node_modules/pg/package.json"]} //// [/home/src/workspaces/project/b/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -133,7 +133,14 @@ pg.foo(); "original": "./src/index.ts" } ], - "size": 53 + "packageJsons": [ + "./package.json", + "../node_modules/@types/pg/package.json" + ], + "missingPackageJsons": [ + "../node_modules/pg/package.json" + ], + "size": 186 } a/tsconfig.json:: diff --git a/testdata/baselines/reference/tsbuild/moduleResolution/resolves-specifier-in-output-declaration-file-from-referenced-project-correctly-with-preserveSymlinks.js b/testdata/baselines/reference/tsbuild/moduleResolution/resolves-specifier-in-output-declaration-file-from-referenced-project-correctly-with-preserveSymlinks.js index 992ffe15b3a..29940e1c3bd 100644 --- a/testdata/baselines/reference/tsbuild/moduleResolution/resolves-specifier-in-output-declaration-file-from-referenced-project-correctly-with-preserveSymlinks.js +++ b/testdata/baselines/reference/tsbuild/moduleResolution/resolves-specifier-in-output-declaration-file-from-referenced-project-correctly-with-preserveSymlinks.js @@ -124,7 +124,7 @@ declare const console: { log(msg: any): void; }; export const theNum = 42; //// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":["../index.ts"]} +{"version":"FakeTSVersion","root":["../index.ts"],"packageJsons":["../../pkg2/package.json"],"missingPackageJsons":["../../../node_modules/pkg2/build/package.json"]} //// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -136,7 +136,13 @@ export const theNum = 42; "original": "../index.ts" } ], - "size": 50 + "packageJsons": [ + "../../pkg2/package.json" + ], + "missingPackageJsons": [ + "../../../node_modules/pkg2/build/package.json" + ], + "size": 165 } //// [/user/username/projects/myproject/packages/pkg2/build/const.d.ts] *new* export type TheNum = 42; @@ -151,7 +157,7 @@ export type { TheNum } from 'const'; export {}; //// [/user/username/projects/myproject/packages/pkg2/build/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[2,3]],"fileNames":["lib.es2025.full.d.ts","../const.ts","../index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"be0f939ab1143e4064a3742586332724-export type TheNum = 42;","signature":"56e2d69d2edd1f0edd1a64ecfdf6de0d-export type TheNum = 42;\n","impliedNodeFormat":1},{"version":"0b8e978a1e274cdc446fbbcbc9e78724-export type { TheNum } from 'const';","signature":"1a74e021c93cb748502ffc92156e3427-export type { TheNum } from 'const';\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./"},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[[2,3]],"packageJsons":["../package.json"],"fileNames":["lib.es2025.full.d.ts","../const.ts","../index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"be0f939ab1143e4064a3742586332724-export type TheNum = 42;","signature":"56e2d69d2edd1f0edd1a64ecfdf6de0d-export type TheNum = 42;\n","impliedNodeFormat":1},{"version":"0b8e978a1e274cdc446fbbcbc9e78724-export type { TheNum } from 'const';","signature":"1a74e021c93cb748502ffc92156e3427-export type { TheNum } from 'const';\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./"},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.ts"} //// [/user/username/projects/myproject/packages/pkg2/build/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -167,6 +173,9 @@ export {}; ] } ], + "packageJsons": [ + "../package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "../const.ts", @@ -223,7 +232,7 @@ export {}; ] }, "latestChangedDtsFile": "./index.d.ts", - "size": 1376 + "size": 1411 } packages/pkg2/tsconfig.json:: diff --git a/testdata/baselines/reference/tsbuild/moduleResolution/resolves-specifier-in-output-declaration-file-from-referenced-project-correctly.js b/testdata/baselines/reference/tsbuild/moduleResolution/resolves-specifier-in-output-declaration-file-from-referenced-project-correctly.js index ff2525b60e9..1d8b97785cf 100644 --- a/testdata/baselines/reference/tsbuild/moduleResolution/resolves-specifier-in-output-declaration-file-from-referenced-project-correctly.js +++ b/testdata/baselines/reference/tsbuild/moduleResolution/resolves-specifier-in-output-declaration-file-from-referenced-project-correctly.js @@ -125,7 +125,7 @@ declare const console: { log(msg: any): void; }; export const theNum = 42; //// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":["../index.ts"]} +{"version":"FakeTSVersion","root":["../index.ts"],"packageJsons":["../../pkg2/package.json"]} //// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -137,7 +137,10 @@ export const theNum = 42; "original": "../index.ts" } ], - "size": 50 + "packageJsons": [ + "../../pkg2/package.json" + ], + "size": 93 } //// [/user/username/projects/myproject/packages/pkg2/build/const.d.ts] *new* export type TheNum = 42; @@ -152,7 +155,7 @@ export type { TheNum } from 'const'; export {}; //// [/user/username/projects/myproject/packages/pkg2/build/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[2,3]],"fileNames":["lib.es2025.full.d.ts","../const.ts","../index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"be0f939ab1143e4064a3742586332724-export type TheNum = 42;","signature":"56e2d69d2edd1f0edd1a64ecfdf6de0d-export type TheNum = 42;\n","impliedNodeFormat":1},{"version":"0b8e978a1e274cdc446fbbcbc9e78724-export type { TheNum } from 'const';","signature":"1a74e021c93cb748502ffc92156e3427-export type { TheNum } from 'const';\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./"},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[[2,3]],"packageJsons":["../package.json"],"fileNames":["lib.es2025.full.d.ts","../const.ts","../index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"be0f939ab1143e4064a3742586332724-export type TheNum = 42;","signature":"56e2d69d2edd1f0edd1a64ecfdf6de0d-export type TheNum = 42;\n","impliedNodeFormat":1},{"version":"0b8e978a1e274cdc446fbbcbc9e78724-export type { TheNum } from 'const';","signature":"1a74e021c93cb748502ffc92156e3427-export type { TheNum } from 'const';\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./"},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.ts"} //// [/user/username/projects/myproject/packages/pkg2/build/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -168,6 +171,9 @@ export {}; ] } ], + "packageJsons": [ + "../package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "../const.ts", @@ -224,7 +230,7 @@ export {}; ] }, "latestChangedDtsFile": "./index.d.ts", - "size": 1376 + "size": 1411 } packages/pkg2/tsconfig.json:: diff --git a/testdata/baselines/reference/tsbuild/moduleResolution/shared-resolution-should-not-report-error.js b/testdata/baselines/reference/tsbuild/moduleResolution/shared-resolution-should-not-report-error.js index 93f0720aebf..b327dcfc4ae 100644 --- a/testdata/baselines/reference/tsbuild/moduleResolution/shared-resolution-should-not-report-error.js +++ b/testdata/baselines/reference/tsbuild/moduleResolution/shared-resolution-should-not-report-error.js @@ -145,7 +145,7 @@ export declare const a = "a"; import 'a'; //// [/home/src/workspaces/project/packages/a/types/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[2,3]],"fileNames":["lib.es2025.full.d.ts","../index.js","../test/index.js"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"fb6f7bce1e97f6455fc2f6a3fc00ca67-export const a = 'a';","signature":"410f445844ca5e1f83239796f66520a1-export declare const a = \"a\";\n","impliedNodeFormat":99},{"version":"25c2781885c8232d7ba0f67afa33aa44-import 'a';","signature":"518d564eba22abfaf340ce3ae18a4763-import 'a';\n","impliedNodeFormat":99}],"fileIdsList":[[2]],"options":{"checkJs":true,"composite":true,"emitDeclarationOnly":true,"declaration":true,"module":199,"outDir":"./"},"referencedMap":[[3,1]],"latestChangedDtsFile":"./test/index.d.ts"} +{"version":"FakeTSVersion","root":[[2,3]],"packageJsons":["../package.json"],"fileNames":["lib.es2025.full.d.ts","../index.js","../test/index.js"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"fb6f7bce1e97f6455fc2f6a3fc00ca67-export const a = 'a';","signature":"410f445844ca5e1f83239796f66520a1-export declare const a = \"a\";\n","impliedNodeFormat":99},{"version":"25c2781885c8232d7ba0f67afa33aa44-import 'a';","signature":"518d564eba22abfaf340ce3ae18a4763-import 'a';\n","impliedNodeFormat":99}],"fileIdsList":[[2]],"options":{"checkJs":true,"composite":true,"emitDeclarationOnly":true,"declaration":true,"module":199,"outDir":"./"},"referencedMap":[[3,1]],"latestChangedDtsFile":"./test/index.d.ts"} //// [/home/src/workspaces/project/packages/a/types/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -161,6 +161,9 @@ import 'a'; ] } ], + "packageJsons": [ + "../package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "../index.js", @@ -221,10 +224,10 @@ import 'a'; ] }, "latestChangedDtsFile": "./test/index.d.ts", - "size": 1416 + "size": 1451 } //// [/home/src/workspaces/project/packages/b/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":["./index.js"]} +{"version":"FakeTSVersion","root":["./index.js"],"packageJsons":["../a/package.json","./package.json"]} //// [/home/src/workspaces/project/packages/b/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -236,7 +239,11 @@ import 'a'; "original": "./index.js" } ], - "size": 49 + "packageJsons": [ + "../a/package.json", + "./package.json" + ], + "size": 103 } packages/a/tsconfig.json:: diff --git a/testdata/baselines/reference/tsbuild/moduleResolution/when-resolution-is-not-shared.js b/testdata/baselines/reference/tsbuild/moduleResolution/when-resolution-is-not-shared.js index 4a45568fb05..c4dd89f316a 100644 --- a/testdata/baselines/reference/tsbuild/moduleResolution/when-resolution-is-not-shared.js +++ b/testdata/baselines/reference/tsbuild/moduleResolution/when-resolution-is-not-shared.js @@ -114,7 +114,7 @@ export declare const a = "a"; import 'a'; //// [/home/src/workspaces/project/packages/a/types/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[2,3]],"fileNames":["lib.es2025.full.d.ts","../index.js","../test/index.js"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"fb6f7bce1e97f6455fc2f6a3fc00ca67-export const a = 'a';","signature":"410f445844ca5e1f83239796f66520a1-export declare const a = \"a\";\n","impliedNodeFormat":99},{"version":"25c2781885c8232d7ba0f67afa33aa44-import 'a';","signature":"518d564eba22abfaf340ce3ae18a4763-import 'a';\n","impliedNodeFormat":99}],"fileIdsList":[[2]],"options":{"checkJs":true,"composite":true,"emitDeclarationOnly":true,"declaration":true,"module":199,"outDir":"./"},"referencedMap":[[3,1]],"latestChangedDtsFile":"./test/index.d.ts"} +{"version":"FakeTSVersion","root":[[2,3]],"packageJsons":["../package.json"],"fileNames":["lib.es2025.full.d.ts","../index.js","../test/index.js"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"fb6f7bce1e97f6455fc2f6a3fc00ca67-export const a = 'a';","signature":"410f445844ca5e1f83239796f66520a1-export declare const a = \"a\";\n","impliedNodeFormat":99},{"version":"25c2781885c8232d7ba0f67afa33aa44-import 'a';","signature":"518d564eba22abfaf340ce3ae18a4763-import 'a';\n","impliedNodeFormat":99}],"fileIdsList":[[2]],"options":{"checkJs":true,"composite":true,"emitDeclarationOnly":true,"declaration":true,"module":199,"outDir":"./"},"referencedMap":[[3,1]],"latestChangedDtsFile":"./test/index.d.ts"} //// [/home/src/workspaces/project/packages/a/types/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -130,6 +130,9 @@ import 'a'; ] } ], + "packageJsons": [ + "../package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "../index.js", @@ -190,7 +193,7 @@ import 'a'; ] }, "latestChangedDtsFile": "./test/index.d.ts", - "size": 1416 + "size": 1451 } packages/a/tsconfig.json:: @@ -245,7 +248,7 @@ packages/b/index.js Matched by default include pattern '**/*' File is ECMAScript module because 'packages/b/package.json' has field "type" with value "module" //// [/home/src/workspaces/project/packages/b/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":["./index.js"]} +{"version":"FakeTSVersion","root":["./index.js"],"packageJsons":["../a/package.json","./package.json"]} //// [/home/src/workspaces/project/packages/b/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -257,7 +260,11 @@ packages/b/index.js "original": "./index.js" } ], - "size": 49 + "packageJsons": [ + "../a/package.json", + "./package.json" + ], + "size": 103 } packages/b/tsconfig.json:: diff --git a/testdata/baselines/reference/tsbuild/moduleSpecifiers/synthesized-module-specifiers-across-projects-resolve-correctly.js b/testdata/baselines/reference/tsbuild/moduleSpecifiers/synthesized-module-specifiers-across-projects-resolve-correctly.js index aeacaf8de53..fd067dc2190 100644 --- a/testdata/baselines/reference/tsbuild/moduleSpecifiers/synthesized-module-specifiers-across-projects-resolve-correctly.js +++ b/testdata/baselines/reference/tsbuild/moduleSpecifiers/synthesized-module-specifiers-across-projects-resolve-correctly.js @@ -170,7 +170,7 @@ export class LassieDog extends Dog { } //// [/home/src/workspaces/packages/src-dogs/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[4,8]],"fileNames":["lib.es2025.full.d.ts","../src-types/dogconfig.d.ts","../src-types/index.d.ts","./dogconfig.ts","./dog.ts","./lassie/lassieconfig.ts","./lassie/lassiedog.ts","./index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"a71e22ebb89c8c5bea7cef8d090ace25-export interface DogConfig {\n name: string;\n}\n","impliedNodeFormat":99},{"version":"3c21c50da3a1aea8b6fafa5aa595f160-export * from './dogconfig.js';\n","impliedNodeFormat":99},{"version":"a8c9e5169f1e05ea3fd4da563dc779b7-import { DogConfig } from 'src-types';\n\nexport const DOG_CONFIG: DogConfig = {\n name: 'Default dog',\n};","signature":"55c35bfb192d26f7ab56e9447864b637-import { DogConfig } from 'src-types';\nexport declare const DOG_CONFIG: DogConfig;\n","impliedNodeFormat":99},{"version":"4ef4eb6072aff36903b09b7e1fa75eea-import { DogConfig } from 'src-types';\nimport { DOG_CONFIG } from './dogconfig.js';\n\nexport abstract class Dog {\n\n public static getCapabilities(): DogConfig {\n return DOG_CONFIG;\n }\n}","signature":"1130c09f22ac69e13b25f0c42f3a9379-import { DogConfig } from 'src-types';\nexport declare abstract class Dog {\n static getCapabilities(): DogConfig;\n}\n","impliedNodeFormat":99},{"version":"37fa5afea0e398a9cc485818c902b71c-import { DogConfig } from 'src-types';\n\nexport const LASSIE_CONFIG: DogConfig = { name: 'Lassie' };","signature":"2ef44fffbc07bb77765462af9f6df2a2-import { DogConfig } from 'src-types';\nexport declare const LASSIE_CONFIG: DogConfig;\n","impliedNodeFormat":99},{"version":"16f2a31a47590452f19f34bb56d0345f-import { Dog } from '../dog.js';\nimport { LASSIE_CONFIG } from './lassieconfig.js';\n\nexport class LassieDog extends Dog {\n protected static getDogConfig = () => LASSIE_CONFIG;\n}","signature":"e1943411d89cafd8c6f5a028539f5775-import { Dog } from '../dog.js';\nexport declare class LassieDog extends Dog {\n protected static getDogConfig: () => import(\"src-types\").DogConfig;\n}\n","impliedNodeFormat":99},{"version":"099983d5c3c8b20233df02ca964ad12f-export * from 'src-types';\nexport * from './lassie/lassiedog.js';","signature":"0fb03f7b5b8061b0e2cd78a4131e3df7-export * from 'src-types';\nexport * from './lassie/lassiedog.js';\n","impliedNodeFormat":99}],"fileIdsList":[[3,4],[3],[3,7],[5,6],[2]],"options":{"composite":true,"declaration":true,"module":100},"referencedMap":[[5,1],[4,2],[8,3],[6,2],[7,4],[3,5]],"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[[4,8]],"packageJsons":["./package.json","../src-types/package.json"],"fileNames":["lib.es2025.full.d.ts","../src-types/dogconfig.d.ts","../src-types/index.d.ts","./dogconfig.ts","./dog.ts","./lassie/lassieconfig.ts","./lassie/lassiedog.ts","./index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"a71e22ebb89c8c5bea7cef8d090ace25-export interface DogConfig {\n name: string;\n}\n","impliedNodeFormat":99},{"version":"3c21c50da3a1aea8b6fafa5aa595f160-export * from './dogconfig.js';\n","impliedNodeFormat":99},{"version":"a8c9e5169f1e05ea3fd4da563dc779b7-import { DogConfig } from 'src-types';\n\nexport const DOG_CONFIG: DogConfig = {\n name: 'Default dog',\n};","signature":"55c35bfb192d26f7ab56e9447864b637-import { DogConfig } from 'src-types';\nexport declare const DOG_CONFIG: DogConfig;\n","impliedNodeFormat":99},{"version":"4ef4eb6072aff36903b09b7e1fa75eea-import { DogConfig } from 'src-types';\nimport { DOG_CONFIG } from './dogconfig.js';\n\nexport abstract class Dog {\n\n public static getCapabilities(): DogConfig {\n return DOG_CONFIG;\n }\n}","signature":"1130c09f22ac69e13b25f0c42f3a9379-import { DogConfig } from 'src-types';\nexport declare abstract class Dog {\n static getCapabilities(): DogConfig;\n}\n","impliedNodeFormat":99},{"version":"37fa5afea0e398a9cc485818c902b71c-import { DogConfig } from 'src-types';\n\nexport const LASSIE_CONFIG: DogConfig = { name: 'Lassie' };","signature":"2ef44fffbc07bb77765462af9f6df2a2-import { DogConfig } from 'src-types';\nexport declare const LASSIE_CONFIG: DogConfig;\n","impliedNodeFormat":99},{"version":"16f2a31a47590452f19f34bb56d0345f-import { Dog } from '../dog.js';\nimport { LASSIE_CONFIG } from './lassieconfig.js';\n\nexport class LassieDog extends Dog {\n protected static getDogConfig = () => LASSIE_CONFIG;\n}","signature":"e1943411d89cafd8c6f5a028539f5775-import { Dog } from '../dog.js';\nexport declare class LassieDog extends Dog {\n protected static getDogConfig: () => import(\"src-types\").DogConfig;\n}\n","impliedNodeFormat":99},{"version":"099983d5c3c8b20233df02ca964ad12f-export * from 'src-types';\nexport * from './lassie/lassiedog.js';","signature":"0fb03f7b5b8061b0e2cd78a4131e3df7-export * from 'src-types';\nexport * from './lassie/lassiedog.js';\n","impliedNodeFormat":99}],"fileIdsList":[[3,4],[3],[3,7],[5,6],[2]],"options":{"composite":true,"declaration":true,"module":100},"referencedMap":[[5,1],[4,2],[8,3],[6,2],[7,4],[3,5]],"latestChangedDtsFile":"./index.d.ts"} //// [/home/src/workspaces/packages/src-dogs/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -189,6 +189,10 @@ export class LassieDog extends Dog { ] } ], + "packageJsons": [ + "./package.json", + "../src-types/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "../src-types/dogconfig.d.ts", @@ -337,7 +341,7 @@ export class LassieDog extends Dog { ] }, "latestChangedDtsFile": "./index.d.ts", - "size": 3216 + "size": 3278 } //// [/home/src/workspaces/packages/src-types/dogconfig.d.ts] *new* export interface DogConfig { @@ -354,7 +358,7 @@ export * from './dogconfig.js'; export * from './dogconfig.js'; //// [/home/src/workspaces/packages/src-types/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[2,3]],"fileNames":["lib.es2025.full.d.ts","./dogconfig.ts","./index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d8b224befa78d5f27814a6eb4da56079-export interface DogConfig {\n name: string;\n}","signature":"a71e22ebb89c8c5bea7cef8d090ace25-export interface DogConfig {\n name: string;\n}\n","impliedNodeFormat":99},{"version":"ac3890d1bb11659994f68e147333e98e-export * from './dogconfig.js';","signature":"3c21c50da3a1aea8b6fafa5aa595f160-export * from './dogconfig.js';\n","impliedNodeFormat":99}],"fileIdsList":[[2]],"options":{"composite":true,"declaration":true,"module":100},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[[2,3]],"packageJsons":["./package.json"],"fileNames":["lib.es2025.full.d.ts","./dogconfig.ts","./index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d8b224befa78d5f27814a6eb4da56079-export interface DogConfig {\n name: string;\n}","signature":"a71e22ebb89c8c5bea7cef8d090ace25-export interface DogConfig {\n name: string;\n}\n","impliedNodeFormat":99},{"version":"ac3890d1bb11659994f68e147333e98e-export * from './dogconfig.js';","signature":"3c21c50da3a1aea8b6fafa5aa595f160-export * from './dogconfig.js';\n","impliedNodeFormat":99}],"fileIdsList":[[2]],"options":{"composite":true,"declaration":true,"module":100},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.ts"} //// [/home/src/workspaces/packages/src-types/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -370,6 +374,9 @@ export * from './dogconfig.js'; ] } ], + "packageJsons": [ + "./package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./dogconfig.ts", @@ -427,7 +434,7 @@ export * from './dogconfig.js'; ] }, "latestChangedDtsFile": "./index.d.ts", - "size": 1440 + "size": 1474 } src-types/tsconfig.json:: diff --git a/testdata/baselines/reference/tsbuild/programUpdates/tsbuildinfo-has-fewer-fileInfos-than-fileNames.js b/testdata/baselines/reference/tsbuild/programUpdates/tsbuildinfo-has-fewer-fileInfos-than-fileNames.js new file mode 100644 index 00000000000..2c365f5bc8c --- /dev/null +++ b/testdata/baselines/reference/tsbuild/programUpdates/tsbuildinfo-has-fewer-fileInfos-than-fileNames.js @@ -0,0 +1,138 @@ +currentDirectory::/user/username/projects/project +useCaseSensitiveFileNames::true +Input:: +//// [/user/username/projects/project/dist/tsconfig.tsbuildinfo] *new* +{ + "version": "FakeTSVersion", + "fileNames": ["lib.es2025.full.d.ts", "../src/a.ts", "../src/b.ts"], + "fileInfos": ["abc123"], + "options": {"composite": true, "outDir": "./"}, + "root": [2, 3] + } +//// [/user/username/projects/project/src/a.ts] *new* +export const a = 1; +//// [/user/username/projects/project/src/b.ts] *new* +export const b = 2; +//// [/user/username/projects/project/tsconfig.json] *new* +{"compilerOptions":{"composite":true,"outDir":"dist"},"files":["src/a.ts","src/b.ts"]} + +tsgo --b -v +ExitStatus:: Success +Output:: +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is out of date because output 'dist/tsconfig.tsbuildinfo' is older than input 'src/a.ts' + +[HH:MM:SS AM] Building project 'tsconfig.json'... + +//// [/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts] *Lib* +/// +interface Boolean {} +interface Function {} +interface CallableFunction {} +interface NewableFunction {} +interface IArguments {} +interface Number { toExponential: any; } +interface Object {} +interface RegExp {} +interface String { charAt: any; } +interface Array { length: number; [n: number]: T; } +interface ReadonlyArray {} +interface SymbolConstructor { + (desc?: string | number): symbol; + for(name: string): symbol; + readonly toStringTag: symbol; +} +declare var Symbol: SymbolConstructor; +interface Symbol { + readonly [Symbol.toStringTag]: string; +} +declare const console: { log(msg: any): void; }; +//// [/user/username/projects/project/dist/src/a.d.ts] *new* +export declare const a = 1; + +//// [/user/username/projects/project/dist/src/a.js] *new* +export const a = 1; + +//// [/user/username/projects/project/dist/src/b.d.ts] *new* +export declare const b = 2; + +//// [/user/username/projects/project/dist/src/b.js] *new* +export const b = 2; + +//// [/user/username/projects/project/dist/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":[[2,3]],"fileNames":["lib.es2025.full.d.ts","../src/a.ts","../src/b.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"f5c8fff6e1fca35f4a292d48868d4086-export const a = 1;","signature":"67cd7ccc14045107336f34154f76a8ca-export declare const a = 1;\n","impliedNodeFormat":1},{"version":"a8da94c0a8fada72e123de05c6818d3a-export const b = 2;","signature":"e1d275f86bf4a4a1f6fd0e8d8709f902-export declare const b = 2;\n","impliedNodeFormat":1}],"options":{"composite":true,"outDir":"./"},"latestChangedDtsFile":"./src/b.d.ts"} +//// [/user/username/projects/project/dist/tsconfig.tsbuildinfo.readable.baseline.txt] *new* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../src/a.ts", + "../src/b.ts" + ], + "original": [ + 2, + 3 + ] + } + ], + "fileNames": [ + "lib.es2025.full.d.ts", + "../src/a.ts", + "../src/b.ts" + ], + "fileInfos": [ + { + "fileName": "lib.es2025.full.d.ts", + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "signature": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": "CommonJS", + "original": { + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": 1 + } + }, + { + "fileName": "../src/a.ts", + "version": "f5c8fff6e1fca35f4a292d48868d4086-export const a = 1;", + "signature": "67cd7ccc14045107336f34154f76a8ca-export declare const a = 1;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "f5c8fff6e1fca35f4a292d48868d4086-export const a = 1;", + "signature": "67cd7ccc14045107336f34154f76a8ca-export declare const a = 1;\n", + "impliedNodeFormat": 1 + } + }, + { + "fileName": "../src/b.ts", + "version": "a8da94c0a8fada72e123de05c6818d3a-export const b = 2;", + "signature": "e1d275f86bf4a4a1f6fd0e8d8709f902-export declare const b = 2;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "a8da94c0a8fada72e123de05c6818d3a-export const b = 2;", + "signature": "e1d275f86bf4a4a1f6fd0e8d8709f902-export declare const b = 2;\n", + "impliedNodeFormat": 1 + } + } + ], + "options": { + "composite": true, + "outDir": "./" + }, + "latestChangedDtsFile": "./src/b.d.ts", + "size": 1304 +} + +tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* /user/username/projects/project/src/a.ts +*refresh* /user/username/projects/project/src/b.ts +Signatures:: +(used version) /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +(computed .d.ts) /user/username/projects/project/src/a.ts +(computed .d.ts) /user/username/projects/project/src/b.ts diff --git a/testdata/baselines/reference/tsbuild/projectReferenceRedirect/uses-correct-project-reference-redirect-when-file-belongs-to-multiple-sub-projects.js b/testdata/baselines/reference/tsbuild/projectReferenceRedirect/uses-correct-project-reference-redirect-when-file-belongs-to-multiple-sub-projects.js index 23d9035d61b..65c774fac64 100644 --- a/testdata/baselines/reference/tsbuild/projectReferenceRedirect/uses-correct-project-reference-redirect-when-file-belongs-to-multiple-sub-projects.js +++ b/testdata/baselines/reference/tsbuild/projectReferenceRedirect/uses-correct-project-reference-redirect-when-file-belongs-to-multiple-sub-projects.js @@ -129,7 +129,7 @@ export declare const platform: "web"; export declare const platform: "native"; //// [/home/src/workspaces/project/pkg/dist/tsconfig.native.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[2,4]],"fileNames":["lib.es2025.full.d.ts","../src/util.native.ts","../index.native.ts","../src/util.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"c1f8db351239c175fbb3960262e28684-export const platform = \"native\" as const;","signature":"1f876b2eee633f65aa2e7817bfee737a-export declare const platform: \"native\";\n","impliedNodeFormat":1},{"version":"0a747b719fd37e7b799139c5f607d76b-export { platform } from \"./src/util\";","signature":"b065ccf77d7f1159c74552524b8d4d2b-export { platform } from \"./src/util\";\n","impliedNodeFormat":1},{"version":"7941de8fb997b556c0afef2b586d7205-export const platform = \"web\" as const;","signature":"5082e4a38cc5cc308625a8754198c0e3-export declare const platform: \"web\";\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"emitDeclarationOnly":true,"declaration":true,"module":99,"outDir":"./","strict":true},"referencedMap":[[3,1]],"latestChangedDtsFile":"./src/util.d.ts"} +{"version":"FakeTSVersion","root":[[2,4]],"packageJsons":["../package.json"],"fileNames":["lib.es2025.full.d.ts","../src/util.native.ts","../index.native.ts","../src/util.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"c1f8db351239c175fbb3960262e28684-export const platform = \"native\" as const;","signature":"1f876b2eee633f65aa2e7817bfee737a-export declare const platform: \"native\";\n","impliedNodeFormat":1},{"version":"0a747b719fd37e7b799139c5f607d76b-export { platform } from \"./src/util\";","signature":"b065ccf77d7f1159c74552524b8d4d2b-export { platform } from \"./src/util\";\n","impliedNodeFormat":1},{"version":"7941de8fb997b556c0afef2b586d7205-export const platform = \"web\" as const;","signature":"5082e4a38cc5cc308625a8754198c0e3-export declare const platform: \"web\";\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"emitDeclarationOnly":true,"declaration":true,"module":99,"outDir":"./","strict":true},"referencedMap":[[3,1]],"latestChangedDtsFile":"./src/util.d.ts"} //// [/home/src/workspaces/project/pkg/dist/tsconfig.native.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -146,6 +146,9 @@ export declare const platform: "native"; ] } ], + "packageJsons": [ + "../package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "../src/util.native.ts", @@ -218,10 +221,10 @@ export declare const platform: "native"; ] }, "latestChangedDtsFile": "./src/util.d.ts", - "size": 1731 + "size": 1766 } //// [/home/src/workspaces/project/pkg/dist/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[2,5]],"fileNames":["lib.es2025.full.d.ts","./src/util.native.d.ts","./index.native.d.ts","./src/util.d.ts","../index.ts","../src/util.native.ts","../index.native.ts","../src/util.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"1f876b2eee633f65aa2e7817bfee737a-export declare const platform: \"native\";\n","b065ccf77d7f1159c74552524b8d4d2b-export { platform } from \"./src/util\";\n","5082e4a38cc5cc308625a8754198c0e3-export declare const platform: \"web\";\n",{"version":"0a747b719fd37e7b799139c5f607d76b-export { platform } from \"./src/util\";","signature":"b065ccf77d7f1159c74552524b8d4d2b-export { platform } from \"./src/util\";\n","impliedNodeFormat":1}],"fileIdsList":[[2],[4]],"options":{"composite":true,"emitDeclarationOnly":true,"declaration":true,"module":99,"outDir":"./","strict":true},"referencedMap":[[3,1],[5,2]],"latestChangedDtsFile":"./index.d.ts","resolvedRoot":[[2,6],[3,7],[4,8]]} +{"version":"FakeTSVersion","root":[[2,5]],"packageJsons":["../package.json"],"fileNames":["lib.es2025.full.d.ts","./src/util.native.d.ts","./index.native.d.ts","./src/util.d.ts","../index.ts","../src/util.native.ts","../index.native.ts","../src/util.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"1f876b2eee633f65aa2e7817bfee737a-export declare const platform: \"native\";\n","b065ccf77d7f1159c74552524b8d4d2b-export { platform } from \"./src/util\";\n","5082e4a38cc5cc308625a8754198c0e3-export declare const platform: \"web\";\n",{"version":"0a747b719fd37e7b799139c5f607d76b-export { platform } from \"./src/util\";","signature":"b065ccf77d7f1159c74552524b8d4d2b-export { platform } from \"./src/util\";\n","impliedNodeFormat":1}],"fileIdsList":[[2],[4]],"options":{"composite":true,"emitDeclarationOnly":true,"declaration":true,"module":99,"outDir":"./","strict":true},"referencedMap":[[3,1],[5,2]],"latestChangedDtsFile":"./index.d.ts","resolvedRoot":[[2,6],[3,7],[4,8]]} //// [/home/src/workspaces/project/pkg/dist/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -239,6 +242,9 @@ export declare const platform: "native"; ] } ], + "packageJsons": [ + "../package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./src/util.native.d.ts", @@ -331,10 +337,10 @@ export declare const platform: "native"; "../src/util.ts" ] ], - "size": 1681 + "size": 1716 } //// [/home/src/workspaces/project/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":["./app.ts"]} +{"version":"FakeTSVersion","root":["./app.ts"],"packageJsons":["./pkg/package.json"]} //// [/home/src/workspaces/project/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -346,7 +352,10 @@ export declare const platform: "native"; "original": "./app.ts" } ], - "size": 47 + "packageJsons": [ + "./pkg/package.json" + ], + "size": 85 } pkg/tsconfig.native.json:: diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/files-containing-json-file-non-composite.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/files-containing-json-file-non-composite.js index dd15f557587..3a92ca40ea4 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/files-containing-json-file-non-composite.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/files-containing-json-file-non-composite.js @@ -39,9 +39,9 @@ Output:: 8 "outDir": "dist",    ~~~~~~~~ -TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/files-containing-json-file.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/files-containing-json-file.js index a972e003544..f7a3fb2f59e 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/files-containing-json-file.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/files-containing-json-file.js @@ -33,10 +33,10 @@ Output:: [HH:MM:SS AM] Building project 'project/tsconfig.json'... -TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/src/index.d.ts -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/src/index.d.ts +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-and-files-non-composite.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-and-files-non-composite.js index c4ecedf558a..c0a986d01a7 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-and-files-non-composite.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-and-files-non-composite.js @@ -39,9 +39,9 @@ Output:: 8 "outDir": "dist",    ~~~~~~~~ -TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-and-files.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-and-files.js index 83f8b72d1f7..aeddd76d71d 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-and-files.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-and-files.js @@ -33,10 +33,10 @@ Output:: [HH:MM:SS AM] Building project 'project/tsconfig.json'... -TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/src/index.d.ts -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/src/index.d.ts +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include-and-file-name-matches-ts-file-non-composite.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include-and-file-name-matches-ts-file-non-composite.js index 60a64f88f2d..de8667430f8 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include-and-file-name-matches-ts-file-non-composite.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include-and-file-name-matches-ts-file-non-composite.js @@ -39,9 +39,9 @@ Output:: 8 "outDir": "dist",    ~~~~~~~~ -TSFILE: /home/src/workspaces/solution/project/dist/src/index.json -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/index.json +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/index.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include-and-file-name-matches-ts-file.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include-and-file-name-matches-ts-file.js index 3e9ea58b79c..c0743b69ee8 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include-and-file-name-matches-ts-file.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include-and-file-name-matches-ts-file.js @@ -33,10 +33,10 @@ Output:: [HH:MM:SS AM] Building project 'project/tsconfig.json'... -TSFILE: /home/src/workspaces/solution/project/dist/src/index.json -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/src/index.d.ts -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/index.json +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/src/index.d.ts +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/index.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include-non-composite.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include-non-composite.js index 39811cc20d4..2f9dccf549b 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include-non-composite.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include-non-composite.js @@ -39,9 +39,9 @@ Output:: 8 "outDir": "dist",    ~~~~~~~~ -TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include.js index bc6b10d003b..5456cac4f9d 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-of-json-along-with-other-include.js @@ -33,10 +33,10 @@ Output:: [HH:MM:SS AM] Building project 'project/tsconfig.json'... -TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/src/index.d.ts -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/src/index.d.ts +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-non-composite.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-non-composite.js index 374bc890651..ed4dd8a9c4b 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-non-composite.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-non-composite.js @@ -39,9 +39,9 @@ Output:: 8 "outDir": "dist",    ~~~~~~~~ -TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-not-in-rootDir-non-composite.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-not-in-rootDir-non-composite.js index d9ff524fc44..8fef7f34ac3 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-not-in-rootDir-non-composite.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-not-in-rootDir-non-composite.js @@ -33,8 +33,8 @@ Output:: [HH:MM:SS AM] Building project 'project/tsconfig.json'... -TSFILE: /home/src/workspaces/solution/project/dist/index.js -TSFILE: /home/src/workspaces/solution/project/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/index.js +TSFILE: /home/src/workspaces/solution/project/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-not-in-rootDir.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-not-in-rootDir.js index c411a28df30..b2139a8e5c8 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-not-in-rootDir.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-not-in-rootDir.js @@ -33,9 +33,9 @@ Output:: [HH:MM:SS AM] Building project 'project/tsconfig.json'... -TSFILE: /home/src/workspaces/solution/project/dist/index.js -TSFILE: /home/src/workspaces/solution/project/dist/index.d.ts -TSFILE: /home/src/workspaces/solution/project/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/index.js +TSFILE: /home/src/workspaces/solution/project/dist/index.d.ts +TSFILE: /home/src/workspaces/solution/project/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-without-rootDir-but-outside-configDirectory-non-composite.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-without-rootDir-but-outside-configDirectory-non-composite.js index 2025a6b242f..98e5557856d 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-without-rootDir-but-outside-configDirectory-non-composite.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-without-rootDir-but-outside-configDirectory-non-composite.js @@ -39,8 +39,8 @@ Output:: 8 "outDir": "dist",    ~~~~~~~~ -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-without-rootDir-but-outside-configDirectory.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-without-rootDir-but-outside-configDirectory.js index 9f8bc4f412a..46aa4567da6 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-without-rootDir-but-outside-configDirectory.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-with-json-without-rootDir-but-outside-configDirectory.js @@ -33,9 +33,9 @@ Output:: [HH:MM:SS AM] Building project 'project/tsconfig.json'... -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/src/index.d.ts -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/src/index.d.ts +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-without-outDir-non-composite.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-without-outDir-non-composite.js index 6e1b6f82b82..458b8dc16a8 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-without-outDir-non-composite.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-without-outDir-non-composite.js @@ -33,8 +33,8 @@ Output:: [HH:MM:SS AM] Building project 'project/tsconfig.json'... -TSFILE: /home/src/workspaces/solution/project/src/index.js -TSFILE: /home/src/workspaces/solution/project/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/src/index.js +TSFILE: /home/src/workspaces/solution/project/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-without-outDir.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-without-outDir.js index df1ddac314c..a1921c80902 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-without-outDir.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only-without-outDir.js @@ -33,9 +33,9 @@ Output:: [HH:MM:SS AM] Building project 'project/tsconfig.json'... -TSFILE: /home/src/workspaces/solution/project/src/index.js -TSFILE: /home/src/workspaces/solution/project/src/index.d.ts -TSFILE: /home/src/workspaces/solution/project/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/src/index.js +TSFILE: /home/src/workspaces/solution/project/src/index.d.ts +TSFILE: /home/src/workspaces/solution/project/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only.js index 9614e250a40..c476b7b54da 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/include-only.js @@ -38,10 +38,10 @@ Output:: 1 import hello from "./hello.json"    ~~~~~~~~~~~~~~ -TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/src/index.d.ts -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/src/index.d.ts +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/sourcemap-non-composite.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/sourcemap-non-composite.js index d40fa043398..633bdee3859 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/sourcemap-non-composite.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/sourcemap-non-composite.js @@ -39,10 +39,10 @@ Output:: 8 "outDir": "dist",    ~~~~~~~~ -TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js.map -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js.map +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json @@ -141,10 +141,10 @@ Output:: 8 "outDir": "dist",    ~~~~~~~~ -TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js.map -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js.map +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/sourcemap.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/sourcemap.js index b9cd01d08e8..f08acd893be 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/sourcemap.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/sourcemap.js @@ -33,11 +33,11 @@ Output:: [HH:MM:SS AM] Building project 'project/tsconfig.json'... -TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js.map -TSFILE: /home/src/workspaces/solution/project/dist/src/index.js -TSFILE: /home/src/workspaces/solution/project/dist/src/index.d.ts -TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/dist/src/hello.json +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js.map +TSFILE: /home/src/workspaces/solution/project/dist/src/index.js +TSFILE: /home/src/workspaces/solution/project/dist/src/index.d.ts +TSFILE: /home/src/workspaces/solution/project/dist/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/without-outDir-non-composite.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/without-outDir-non-composite.js index c11fa894568..71d068fb187 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/without-outDir-non-composite.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/without-outDir-non-composite.js @@ -33,8 +33,8 @@ Output:: [HH:MM:SS AM] Building project 'project/tsconfig.json'... -TSFILE: /home/src/workspaces/solution/project/src/index.js -TSFILE: /home/src/workspaces/solution/project/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/src/index.js +TSFILE: /home/src/workspaces/solution/project/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json diff --git a/testdata/baselines/reference/tsbuild/resolveJsonModule/without-outDir.js b/testdata/baselines/reference/tsbuild/resolveJsonModule/without-outDir.js index 0e2ffad7f54..69708413693 100644 --- a/testdata/baselines/reference/tsbuild/resolveJsonModule/without-outDir.js +++ b/testdata/baselines/reference/tsbuild/resolveJsonModule/without-outDir.js @@ -33,9 +33,9 @@ Output:: [HH:MM:SS AM] Building project 'project/tsconfig.json'... -TSFILE: /home/src/workspaces/solution/project/src/index.js -TSFILE: /home/src/workspaces/solution/project/src/index.d.ts -TSFILE: /home/src/workspaces/solution/project/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/solution/project/src/index.js +TSFILE: /home/src/workspaces/solution/project/src/index.d.ts +TSFILE: /home/src/workspaces/solution/project/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' project/src/hello.json diff --git a/testdata/baselines/reference/tsbuild/sample/explainFiles.js b/testdata/baselines/reference/tsbuild/sample/explainFiles.js index c9b54d47720..eaec83b6e11 100644 --- a/testdata/baselines/reference/tsbuild/sample/explainFiles.js +++ b/testdata/baselines/reference/tsbuild/sample/explainFiles.js @@ -489,7 +489,7 @@ core/index.ts Matched by default include pattern '**/*' core/some_decl.d.ts Matched by default include pattern '**/*' -[HH:MM:SS AM] Project 'logic/tsconfig.json' is out of date because output 'logic/tsconfig.tsbuildinfo' is older than input 'core' +[HH:MM:SS AM] Project 'logic/tsconfig.json' is out of date because output 'logic/tsconfig.tsbuildinfo' is older than input 'core/index.d.ts' [HH:MM:SS AM] Building project 'logic/tsconfig.json'... @@ -503,7 +503,7 @@ core/anotherModule.d.ts File is output of project reference source 'core/anotherModule.ts' logic/index.ts Matched by default include pattern '**/*' -[HH:MM:SS AM] Project 'tests/tsconfig.json' is out of date because output 'tests/tsconfig.tsbuildinfo' is older than input 'core' +[HH:MM:SS AM] Project 'tests/tsconfig.json' is out of date because output 'tests/tsconfig.tsbuildinfo' is older than input 'core/index.d.ts' [HH:MM:SS AM] Building project 'tests/tsconfig.json'... diff --git a/testdata/baselines/reference/tsbuild/sample/listEmittedFiles.js b/testdata/baselines/reference/tsbuild/sample/listEmittedFiles.js index 2f2d4929253..66f63a83711 100644 --- a/testdata/baselines/reference/tsbuild/sample/listEmittedFiles.js +++ b/testdata/baselines/reference/tsbuild/sample/listEmittedFiles.js @@ -63,20 +63,20 @@ export const m = mod; tsgo --b tests --listEmittedFiles ExitStatus:: Success Output:: -TSFILE: /user/username/projects/sample1/core/anotherModule.js -TSFILE: /user/username/projects/sample1/core/anotherModule.d.ts.map -TSFILE: /user/username/projects/sample1/core/anotherModule.d.ts -TSFILE: /user/username/projects/sample1/core/index.js -TSFILE: /user/username/projects/sample1/core/index.d.ts.map -TSFILE: /user/username/projects/sample1/core/index.d.ts -TSFILE: /user/username/projects/sample1/core/tsconfig.tsbuildinfo -TSFILE: /user/username/projects/sample1/logic/index.js.map -TSFILE: /user/username/projects/sample1/logic/index.js -TSFILE: /user/username/projects/sample1/logic/index.d.ts -TSFILE: /user/username/projects/sample1/logic/tsconfig.tsbuildinfo -TSFILE: /user/username/projects/sample1/tests/index.js -TSFILE: /user/username/projects/sample1/tests/index.d.ts -TSFILE: /user/username/projects/sample1/tests/tsconfig.tsbuildinfo +TSFILE: /user/username/projects/sample1/core/anotherModule.js +TSFILE: /user/username/projects/sample1/core/anotherModule.d.ts.map +TSFILE: /user/username/projects/sample1/core/anotherModule.d.ts +TSFILE: /user/username/projects/sample1/core/index.js +TSFILE: /user/username/projects/sample1/core/index.d.ts.map +TSFILE: /user/username/projects/sample1/core/index.d.ts +TSFILE: /user/username/projects/sample1/core/tsconfig.tsbuildinfo +TSFILE: /user/username/projects/sample1/logic/index.js.map +TSFILE: /user/username/projects/sample1/logic/index.js +TSFILE: /user/username/projects/sample1/logic/index.d.ts +TSFILE: /user/username/projects/sample1/logic/tsconfig.tsbuildinfo +TSFILE: /user/username/projects/sample1/tests/index.js +TSFILE: /user/username/projects/sample1/tests/index.d.ts +TSFILE: /user/username/projects/sample1/tests/tsconfig.tsbuildinfo //// [/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts] *Lib* /// interface Boolean {} @@ -437,15 +437,15 @@ export class someClass { } tsgo --b tests --listEmittedFiles ExitStatus:: Success Output:: -TSFILE: /user/username/projects/sample1/core/index.js -TSFILE: /user/username/projects/sample1/core/index.d.ts.map -TSFILE: /user/username/projects/sample1/core/index.d.ts -TSFILE: /user/username/projects/sample1/core/tsconfig.tsbuildinfo -TSFILE: /user/username/projects/sample1/logic/index.js.map -TSFILE: /user/username/projects/sample1/logic/index.js -TSFILE: /user/username/projects/sample1/logic/tsconfig.tsbuildinfo -TSFILE: /user/username/projects/sample1/tests/index.js -TSFILE: /user/username/projects/sample1/tests/tsconfig.tsbuildinfo +TSFILE: /user/username/projects/sample1/core/index.js +TSFILE: /user/username/projects/sample1/core/index.d.ts.map +TSFILE: /user/username/projects/sample1/core/index.d.ts +TSFILE: /user/username/projects/sample1/core/tsconfig.tsbuildinfo +TSFILE: /user/username/projects/sample1/logic/index.js.map +TSFILE: /user/username/projects/sample1/logic/index.js +TSFILE: /user/username/projects/sample1/logic/tsconfig.tsbuildinfo +TSFILE: /user/username/projects/sample1/tests/index.js +TSFILE: /user/username/projects/sample1/tests/tsconfig.tsbuildinfo //// [/user/username/projects/sample1/core/index.d.ts] *modified* export declare const someString: string; export declare function leftPad(s: string, n: number): string; @@ -749,9 +749,9 @@ class someClass2 { } tsgo --b tests --listEmittedFiles ExitStatus:: Success Output:: -TSFILE: /user/username/projects/sample1/core/index.js -TSFILE: /user/username/projects/sample1/core/index.d.ts.map -TSFILE: /user/username/projects/sample1/core/tsconfig.tsbuildinfo +TSFILE: /user/username/projects/sample1/core/index.js +TSFILE: /user/username/projects/sample1/core/index.d.ts.map +TSFILE: /user/username/projects/sample1/core/tsconfig.tsbuildinfo //// [/user/username/projects/sample1/core/index.d.ts.map] *rewrite with same content* //// [/user/username/projects/sample1/core/index.js] *modified* export const someString = "HELLO WORLD"; diff --git a/testdata/baselines/reference/tsbuild/sample/sample.js b/testdata/baselines/reference/tsbuild/sample/sample.js index e4b3aeec971..f192798340f 100644 --- a/testdata/baselines/reference/tsbuild/sample/sample.js +++ b/testdata/baselines/reference/tsbuild/sample/sample.js @@ -449,11 +449,11 @@ Output:: [HH:MM:SS AM] Building project 'core/tsconfig.json'... -[HH:MM:SS AM] Project 'logic/tsconfig.json' is out of date because output 'logic/tsconfig.tsbuildinfo' is older than input 'core' +[HH:MM:SS AM] Project 'logic/tsconfig.json' is out of date because output 'logic/tsconfig.tsbuildinfo' is older than input 'core/index.d.ts' [HH:MM:SS AM] Building project 'logic/tsconfig.json'... -[HH:MM:SS AM] Project 'tests/tsconfig.json' is out of date because output 'tests/tsconfig.tsbuildinfo' is older than input 'core' +[HH:MM:SS AM] Project 'tests/tsconfig.json' is out of date because output 'tests/tsconfig.tsbuildinfo' is older than input 'core/index.d.ts' [HH:MM:SS AM] Building project 'tests/tsconfig.json'... diff --git a/testdata/baselines/reference/tsbuild/sample/when-target-option-changes.js b/testdata/baselines/reference/tsbuild/sample/when-target-option-changes.js index 748e0208e6a..65bc6c48a22 100644 --- a/testdata/baselines/reference/tsbuild/sample/when-target-option-changes.js +++ b/testdata/baselines/reference/tsbuild/sample/when-target-option-changes.js @@ -76,9 +76,9 @@ Output:: [HH:MM:SS AM] Building project 'core/tsconfig.json'... -TSFILE: /user/username/projects/sample1/core/anotherModule.js -TSFILE: /user/username/projects/sample1/core/index.js -TSFILE: /user/username/projects/sample1/core/tsconfig.tsbuildinfo +TSFILE: /user/username/projects/sample1/core/anotherModule.js +TSFILE: /user/username/projects/sample1/core/index.js +TSFILE: /user/username/projects/sample1/core/tsconfig.tsbuildinfo /home/src/tslibs/TS/Lib/lib.esnext.d.ts /home/src/tslibs/TS/Lib/lib.esnext.full.d.ts /user/username/projects/sample1/core/anotherModule.ts @@ -226,9 +226,9 @@ Output:: 6 "target": "es5",    ~~~~~ -TSFILE: /user/username/projects/sample1/core/anotherModule.js -TSFILE: /user/username/projects/sample1/core/index.js -TSFILE: /user/username/projects/sample1/core/tsconfig.tsbuildinfo +TSFILE: /user/username/projects/sample1/core/anotherModule.js +TSFILE: /user/username/projects/sample1/core/index.js +TSFILE: /user/username/projects/sample1/core/tsconfig.tsbuildinfo /home/src/tslibs/TS/Lib/lib.d.ts /home/src/tslibs/TS/Lib/lib.esnext.d.ts /user/username/projects/sample1/core/anotherModule.ts diff --git a/testdata/baselines/reference/tsbuildWatch/demo/updates-with-bad-reference.js b/testdata/baselines/reference/tsbuildWatch/demo/updates-with-bad-reference.js index e82e630c5d4..b54b0d2ddfe 100644 --- a/testdata/baselines/reference/tsbuildWatch/demo/updates-with-bad-reference.js +++ b/testdata/baselines/reference/tsbuildWatch/demo/updates-with-bad-reference.js @@ -668,6 +668,7 @@ Directory watches:: /user/username/projects/demo /user/username/projects/demo/animals (recursive) /user/username/projects/demo/core (recursive) + /user/username/projects/demo/lib /user/username/projects/demo/lib/animals /user/username/projects/demo/lib/core /user/username/projects/demo/zoo (recursive) @@ -901,6 +902,7 @@ Directory watches:: /user/username/projects/demo /user/username/projects/demo/animals (recursive) /user/username/projects/demo/core (recursive) + /user/username/projects/demo/lib /user/username/projects/demo/lib/animals /user/username/projects/demo/lib/core /user/username/projects/demo/zoo (recursive) diff --git a/testdata/baselines/reference/tsbuildWatch/demo/updates-with-circular-reference.js b/testdata/baselines/reference/tsbuildWatch/demo/updates-with-circular-reference.js index 4a4953c179b..0ff2c58725a 100644 --- a/testdata/baselines/reference/tsbuildWatch/demo/updates-with-circular-reference.js +++ b/testdata/baselines/reference/tsbuildWatch/demo/updates-with-circular-reference.js @@ -596,6 +596,7 @@ Directory watches:: /user/username/projects/demo /user/username/projects/demo/animals (recursive) /user/username/projects/demo/core (recursive) + /user/username/projects/demo/lib /user/username/projects/demo/lib/animals /user/username/projects/demo/lib/core /user/username/projects/demo/zoo (recursive) diff --git a/testdata/baselines/reference/tsbuildWatch/dependencyUpdate/watches-absolute-non-root-dependency-updates.js b/testdata/baselines/reference/tsbuildWatch/dependencyUpdate/watches-absolute-non-root-dependency-updates.js new file mode 100644 index 00000000000..a5f57b05453 --- /dev/null +++ b/testdata/baselines/reference/tsbuildWatch/dependencyUpdate/watches-absolute-non-root-dependency-updates.js @@ -0,0 +1,270 @@ +currentDirectory::C:/work/project +useCaseSensitiveFileNames::false +Input:: +//// [C:/work/project/src/index.ts] *new* +import { myValue } from "abs-dep"; +export const value: string = myValue; +//// [C:/work/project/tsconfig.json] *new* +{ + "compilerOptions": { + "composite": true, + "outDir": "dist", + "paths": { + "abs-dep": ["D:/work/deps/dep.d.ts"] + }, + "strict": true + }, + "include": ["src/**/*"] +} +//// [D:/work/deps/dep.d.ts] *new* +export declare const myValue: string; + +tsgo --b --verbose --watch +ExitStatus:: Success +Output:: +[HH:MM:SS AM] Starting compilation in watch mode... + +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is out of date because output file 'dist/tsconfig.tsbuildinfo' does not exist + +[HH:MM:SS AM] Building project 'tsconfig.json'... + +[HH:MM:SS AM] Found 0 errors. Watching for file changes. + +//// [C:/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts] *Lib* +/// +interface Boolean {} +interface Function {} +interface CallableFunction {} +interface NewableFunction {} +interface IArguments {} +interface Number { toExponential: any; } +interface Object {} +interface RegExp {} +interface String { charAt: any; } +interface Array { length: number; [n: number]: T; } +interface ReadonlyArray {} +interface SymbolConstructor { + (desc?: string | number): symbol; + for(name: string): symbol; + readonly toStringTag: symbol; +} +declare var Symbol: SymbolConstructor; +interface Symbol { + readonly [Symbol.toStringTag]: string; +} +declare const console: { log(msg: any): void; }; +//// [C:/work/project/dist/src/index.d.ts] *new* +export declare const value: string; + +//// [C:/work/project/dist/src/index.js] *new* +import { myValue } from "abs-dep"; +export const value = myValue; + +//// [C:/work/project/dist/tsconfig.tsbuildinfo] *new* +{"version":"FakeTSVersion","root":[3],"fileNames":["lib.es2025.full.d.ts","d:/work/deps/dep.d.ts","../src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;",{"version":"6c77917c7b17b3698cb1dbdb7227fbff-import { myValue } from \"abs-dep\";\nexport const value: string = myValue;","signature":"d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./","strict":true},"referencedMap":[[3,1]],"latestChangedDtsFile":"./src/index.d.ts"} +//// [C:/work/project/dist/tsconfig.tsbuildinfo.readable.baseline.txt] *new* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../src/index.ts" + ], + "original": 3 + } + ], + "fileNames": [ + "lib.es2025.full.d.ts", + "d:/work/deps/dep.d.ts", + "../src/index.ts" + ], + "fileInfos": [ + { + "fileName": "lib.es2025.full.d.ts", + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "signature": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": "CommonJS", + "original": { + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": 1 + } + }, + { + "fileName": "d:/work/deps/dep.d.ts", + "version": "4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;", + "signature": "4384f7716e1c7cc875e39624007cccc9-export declare const myValue: string;", + "impliedNodeFormat": "CommonJS" + }, + { + "fileName": "../src/index.ts", + "version": "6c77917c7b17b3698cb1dbdb7227fbff-import { myValue } from \"abs-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "6c77917c7b17b3698cb1dbdb7227fbff-import { myValue } from \"abs-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": 1 + } + } + ], + "fileIdsList": [ + [ + "d:/work/deps/dep.d.ts" + ] + ], + "options": { + "composite": true, + "outDir": "./", + "strict": true + }, + "referencedMap": { + "../src/index.ts": [ + "d:/work/deps/dep.d.ts" + ] + }, + "latestChangedDtsFile": "./src/index.d.ts", + "size": 1347 +} + +Watch Registrations:: +Directory watches:: + C:/home/src/tslibs/TS/Lib + C:/work/project + C:/work/project/src (recursive) + D:/work/deps +tsconfig.json:: +SemanticDiagnostics:: +*refresh* C:/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* D:/work/deps/dep.d.ts +*refresh* C:/work/project/src/index.ts +Signatures:: +(stored at emit) C:/work/project/src/index.ts + + +Edit [0]:: update absolute non-root dependency with breaking type change +//// [D:/work/deps/dep.d.ts] *modified* +export declare const myValue: number; + + +Output:: +[HH:MM:SS AM] File change detected. Starting incremental compilation... + +[HH:MM:SS AM] Projects in this build: + * tsconfig.json + +[HH:MM:SS AM] Project 'tsconfig.json' is out of date because output 'dist/tsconfig.tsbuildinfo' is older than input 'd:/work/deps/dep.d.ts' + +[HH:MM:SS AM] Building project 'tsconfig.json'... + +src/index.ts:2:14 - error TS2322: Type 'number' is not assignable to type 'string'. + +2 export const value: string = myValue; +   ~~~~~ + +[HH:MM:SS AM] Found 1 error. Watching for file changes. + +//// [C:/work/project/dist/src/index.js] *rewrite with same content* +//// [C:/work/project/dist/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":[3],"fileNames":["lib.es2025.full.d.ts","d:/work/deps/dep.d.ts","../src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;",{"version":"6c77917c7b17b3698cb1dbdb7227fbff-import { myValue } from \"abs-dep\";\nexport const value: string = myValue;","signature":"d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./","strict":true},"referencedMap":[[3,1]],"semanticDiagnosticsPerFile":[[3,[{"pos":48,"end":53,"code":2322,"category":1,"messageKey":"Type_0_is_not_assignable_to_type_1_2322","messageArgs":["number","string"]}]]],"latestChangedDtsFile":"./src/index.d.ts"} +//// [C:/work/project/dist/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../src/index.ts" + ], + "original": 3 + } + ], + "fileNames": [ + "lib.es2025.full.d.ts", + "d:/work/deps/dep.d.ts", + "../src/index.ts" + ], + "fileInfos": [ + { + "fileName": "lib.es2025.full.d.ts", + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "signature": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": "CommonJS", + "original": { + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": 1 + } + }, + { + "fileName": "d:/work/deps/dep.d.ts", + "version": "936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;", + "signature": "936f1acf4d15f440cdb2eb27f80fb9c9-export declare const myValue: number;", + "impliedNodeFormat": "CommonJS" + }, + { + "fileName": "../src/index.ts", + "version": "6c77917c7b17b3698cb1dbdb7227fbff-import { myValue } from \"abs-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "6c77917c7b17b3698cb1dbdb7227fbff-import { myValue } from \"abs-dep\";\nexport const value: string = myValue;", + "signature": "d704bb9feb766d5360f4081857e4c09e-export declare const value: string;\n", + "impliedNodeFormat": 1 + } + } + ], + "fileIdsList": [ + [ + "d:/work/deps/dep.d.ts" + ] + ], + "options": { + "composite": true, + "outDir": "./", + "strict": true + }, + "referencedMap": { + "../src/index.ts": [ + "d:/work/deps/dep.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + [ + "../src/index.ts", + [ + { + "pos": 48, + "end": 53, + "code": 2322, + "category": 1, + "messageKey": "Type_0_is_not_assignable_to_type_1_2322", + "messageArgs": [ + "number", + "string" + ] + } + ] + ] + ], + "latestChangedDtsFile": "./src/index.d.ts", + "size": 1518 +} + +Watch Registrations:: +Directory watches:: + C:/home/src/tslibs/TS/Lib + C:/work/project + C:/work/project/src (recursive) + D:/work/deps +tsconfig.json:: +SemanticDiagnostics:: +*refresh* D:/work/deps/dep.d.ts +*refresh* C:/work/project/src/index.ts +Signatures:: +(used version) D:/work/deps/dep.d.ts +(computed .d.ts) C:/work/project/src/index.ts diff --git a/testdata/baselines/reference/tsbuildWatch/extends/configDir-template.js b/testdata/baselines/reference/tsbuildWatch/extends/configDir-template.js index b88f944061c..9721c74ed1d 100644 --- a/testdata/baselines/reference/tsbuildWatch/extends/configDir-template.js +++ b/testdata/baselines/reference/tsbuildWatch/extends/configDir-template.js @@ -125,6 +125,7 @@ Directory watches:: /home/src/projects/configs/first /home/src/projects/configs/second /home/src/projects/myproject + /home/src/projects/myproject/types tsconfig.json:: SemanticDiagnostics:: *refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts @@ -184,6 +185,7 @@ Directory watches:: /home/src/projects/configs/first /home/src/projects/configs/second /home/src/projects/myproject + /home/src/projects/myproject/types tsconfig.json:: SemanticDiagnostics:: *refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts diff --git a/testdata/baselines/reference/tsbuildWatch/libraryResolution/with-config-with-libReplacement.js b/testdata/baselines/reference/tsbuildWatch/libraryResolution/with-config-with-libReplacement.js index a41c7510fe4..a87c7223a51 100644 --- a/testdata/baselines/reference/tsbuildWatch/libraryResolution/with-config-with-libReplacement.js +++ b/testdata/baselines/reference/tsbuildWatch/libraryResolution/with-config-with-libReplacement.js @@ -453,7 +453,7 @@ export declare const x = "type1"; export const x = "type1"; //// [/home/src/workspace/projects/project1/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[5,10]],"fileNames":["../node_modules/@typescript/lib-webworker/index.d.ts","../node_modules/@typescript/lib-scripthost/index.d.ts","../node_modules/@typescript/lib-es5/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","./core.d.ts","./file.ts","./file2.ts","./index.ts","./utils.d.ts","./typeroot1/sometype/index.d.ts"],"fileInfos":[{"version":"95c5e18b7871b756fb3bb843e03aa05d-interface WebWorkerInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"2fa71959819338965a3c6b2122d95c96-interface ScriptHostInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},"a1f9b824326bab2c3c8f13eccf69f182-export const core = 10;",{"version":"69c4ea0c9ff13ab7fc078607d9363624-export const file = 10;","signature":"a224c1b0cbd2f5fe611e588db48243cb-export declare const file = 10;\n","impliedNodeFormat":1},{"version":"76f8c505d1aaf1122ce1da0807c21477-/// \n/// \n/// ","signature":"99aa06d3014798d86001c324468d497f-","impliedNodeFormat":1},{"version":"aeb695aed936d7539a32fc3cd25af558-export const x = \"type1\";","signature":"e2f8d12de2edba256e37cf4a656ac52d-export declare const x = \"type1\";\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;","6bf5e0a71dae6fccf68b93fbbb73f178-export type TheNum = \"type1\";"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[[5,10]],"missingPackageJsons":["../node_modules/@typescript/lib-dom/package.json","../node_modules/@typescript/lib-es5/package.json","../node_modules/@typescript/lib-scripthost/package.json","../node_modules/@typescript/lib-webworker/package.json"],"fileNames":["../node_modules/@typescript/lib-webworker/index.d.ts","../node_modules/@typescript/lib-scripthost/index.d.ts","../node_modules/@typescript/lib-es5/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","./core.d.ts","./file.ts","./file2.ts","./index.ts","./utils.d.ts","./typeroot1/sometype/index.d.ts"],"fileInfos":[{"version":"95c5e18b7871b756fb3bb843e03aa05d-interface WebWorkerInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"2fa71959819338965a3c6b2122d95c96-interface ScriptHostInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},"a1f9b824326bab2c3c8f13eccf69f182-export const core = 10;",{"version":"69c4ea0c9ff13ab7fc078607d9363624-export const file = 10;","signature":"a224c1b0cbd2f5fe611e588db48243cb-export declare const file = 10;\n","impliedNodeFormat":1},{"version":"76f8c505d1aaf1122ce1da0807c21477-/// \n/// \n/// ","signature":"99aa06d3014798d86001c324468d497f-","impliedNodeFormat":1},{"version":"aeb695aed936d7539a32fc3cd25af558-export const x = \"type1\";","signature":"e2f8d12de2edba256e37cf4a656ac52d-export declare const x = \"type1\";\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;","6bf5e0a71dae6fccf68b93fbbb73f178-export type TheNum = \"type1\";"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} //// [/home/src/workspace/projects/project1/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -473,6 +473,12 @@ export const x = "type1"; ] } ], + "missingPackageJsons": [ + "../node_modules/@typescript/lib-dom/package.json", + "../node_modules/@typescript/lib-es5/package.json", + "../node_modules/@typescript/lib-scripthost/package.json", + "../node_modules/@typescript/lib-webworker/package.json" + ], "fileNames": [ "../node_modules/@typescript/lib-webworker/index.d.ts", "../node_modules/@typescript/lib-scripthost/index.d.ts", @@ -590,7 +596,7 @@ export const x = "type1"; "composite": true }, "latestChangedDtsFile": "./index.d.ts", - "size": 2354 + "size": 2595 } //// [/home/src/workspace/projects/project2/index.d.ts] *new* export declare const y = 10; @@ -599,7 +605,7 @@ export declare const y = 10; export const y = 10; //// [/home/src/workspace/projects/project2/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[3,4]],"fileNames":["../node_modules/@typescript/lib-es5/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","./index.ts","./utils.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"95e641b4f34db55d73f0f5008cdd30f0-export const y = 10","signature":"7ab1b6e8968172bdd365c972b27a69e2-export declare const y = 10;\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[[3,4]],"missingPackageJsons":["../node_modules/@typescript/lib-dom/package.json","../node_modules/@typescript/lib-es5/package.json"],"fileNames":["../node_modules/@typescript/lib-es5/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","./index.ts","./utils.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"95e641b4f34db55d73f0f5008cdd30f0-export const y = 10","signature":"7ab1b6e8968172bdd365c972b27a69e2-export declare const y = 10;\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} //// [/home/src/workspace/projects/project2/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -615,6 +621,10 @@ export const y = 10; ] } ], + "missingPackageJsons": [ + "../node_modules/@typescript/lib-dom/package.json", + "../node_modules/@typescript/lib-es5/package.json" + ], "fileNames": [ "../node_modules/@typescript/lib-es5/index.d.ts", "../node_modules/@typescript/lib-dom/index.d.ts", @@ -668,7 +678,7 @@ export const y = 10; "composite": true }, "latestChangedDtsFile": "./index.d.ts", - "size": 1378 + "size": 1504 } //// [/home/src/workspace/projects/project3/index.d.ts] *new* export declare const z = 10; @@ -677,7 +687,7 @@ export declare const z = 10; export const z = 10; //// [/home/src/workspace/projects/project3/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[3,4]],"fileNames":["../node_modules/@typescript/lib-es5/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","./index.ts","./utils.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6f4aaa0b206d74bd2835c8fd3a4020fe-export const z = 10","signature":"f4ea7cd61571728ffc44aefcffc4eda1-export declare const z = 10;\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[[3,4]],"missingPackageJsons":["../node_modules/@typescript/lib-dom/package.json","../node_modules/@typescript/lib-es5/package.json"],"fileNames":["../node_modules/@typescript/lib-es5/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","./index.ts","./utils.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6f4aaa0b206d74bd2835c8fd3a4020fe-export const z = 10","signature":"f4ea7cd61571728ffc44aefcffc4eda1-export declare const z = 10;\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} //// [/home/src/workspace/projects/project3/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -693,6 +703,10 @@ export const z = 10; ] } ], + "missingPackageJsons": [ + "../node_modules/@typescript/lib-dom/package.json", + "../node_modules/@typescript/lib-es5/package.json" + ], "fileNames": [ "../node_modules/@typescript/lib-es5/index.d.ts", "../node_modules/@typescript/lib-dom/index.d.ts", @@ -746,7 +760,7 @@ export const z = 10; "composite": true }, "latestChangedDtsFile": "./index.d.ts", - "size": 1378 + "size": 1504 } //// [/home/src/workspace/projects/project4/index.d.ts] *new* export declare const z = 10; @@ -755,7 +769,7 @@ export declare const z = 10; export const z = 10; //// [/home/src/workspace/projects/project4/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[4,5]],"fileNames":["../node_modules/@typescript/lib-esnext/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","../node_modules/@typescript/lib-webworker/index.d.ts","./index.ts","./utils.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"95c5e18b7871b756fb3bb843e03aa05d-interface WebWorkerInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6f4aaa0b206d74bd2835c8fd3a4020fe-export const z = 10","signature":"f4ea7cd61571728ffc44aefcffc4eda1-export declare const z = 10;\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[[4,5]],"missingPackageJsons":["../node_modules/@typescript/lib-dom/package.json","../node_modules/@typescript/lib-esnext/package.json","../node_modules/@typescript/lib-webworker/package.json"],"fileNames":["../node_modules/@typescript/lib-esnext/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","../node_modules/@typescript/lib-webworker/index.d.ts","./index.ts","./utils.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"95c5e18b7871b756fb3bb843e03aa05d-interface WebWorkerInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"6f4aaa0b206d74bd2835c8fd3a4020fe-export const z = 10","signature":"f4ea7cd61571728ffc44aefcffc4eda1-export declare const z = 10;\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} //// [/home/src/workspace/projects/project4/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -771,6 +785,11 @@ export const z = 10; ] } ], + "missingPackageJsons": [ + "../node_modules/@typescript/lib-dom/package.json", + "../node_modules/@typescript/lib-esnext/package.json", + "../node_modules/@typescript/lib-webworker/package.json" + ], "fileNames": [ "../node_modules/@typescript/lib-esnext/index.d.ts", "../node_modules/@typescript/lib-dom/index.d.ts", @@ -837,11 +856,14 @@ export const z = 10; "composite": true }, "latestChangedDtsFile": "./index.d.ts", - "size": 1564 + "size": 1750 } Watch Registrations:: Directory watches:: + /home/src/workspace/projects + /home/src/workspace/projects/node_modules + /home/src/workspace/projects/node_modules/@typescript /home/src/workspace/projects/node_modules/@typescript/lib-dom /home/src/workspace/projects/node_modules/@typescript/lib-es5 /home/src/workspace/projects/node_modules/@typescript/lib-esnext diff --git a/testdata/baselines/reference/tsbuildWatch/libraryResolution/with-config.js b/testdata/baselines/reference/tsbuildWatch/libraryResolution/with-config.js index 7b6be85aa92..6fb3641d4c9 100644 --- a/testdata/baselines/reference/tsbuildWatch/libraryResolution/with-config.js +++ b/testdata/baselines/reference/tsbuildWatch/libraryResolution/with-config.js @@ -606,6 +606,7 @@ export const z = 10; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /home/src/workspace/projects /home/src/workspace/projects/project1 (recursive) /home/src/workspace/projects/project2 (recursive) /home/src/workspace/projects/project3 (recursive) diff --git a/testdata/baselines/reference/tsbuildWatch/moduleResolution/build-mode-watches-for-changes-to-package-json-main-fields.js b/testdata/baselines/reference/tsbuildWatch/moduleResolution/build-mode-watches-for-changes-to-package-json-main-fields.js index 6f0efd314b8..04633aedb36 100644 --- a/testdata/baselines/reference/tsbuildWatch/moduleResolution/build-mode-watches-for-changes-to-package-json-main-fields.js +++ b/testdata/baselines/reference/tsbuildWatch/moduleResolution/build-mode-watches-for-changes-to-package-json-main-fields.js @@ -122,7 +122,7 @@ declare const console: { log(msg: any): void; }; export const theNum = 42; //// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":["../index.ts"]} +{"version":"FakeTSVersion","root":["../index.ts"],"packageJsons":["../package.json","../../pkg2/package.json"]} //// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -134,7 +134,11 @@ export const theNum = 42; "original": "../index.ts" } ], - "size": 50 + "packageJsons": [ + "../package.json", + "../../pkg2/package.json" + ], + "size": 111 } //// [/user/username/projects/myproject/packages/pkg2/build/const.d.ts] *new* export type TheNum = 42; @@ -155,7 +159,7 @@ export type TheStr = string; export {}; //// [/user/username/projects/myproject/packages/pkg2/build/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[2,4]],"fileNames":["lib.es2025.full.d.ts","../const.ts","../index.ts","../other.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"be0f939ab1143e4064a3742586332724-export type TheNum = 42;","signature":"56e2d69d2edd1f0edd1a64ecfdf6de0d-export type TheNum = 42;\n","impliedNodeFormat":1},{"version":"c95c354b23966e289caeaece40bb8d0a-export type { TheNum } from './const.js';","signature":"f257912cfebb94a04c6ba4e8f754166a-export type { TheNum } from './const.js';\n","impliedNodeFormat":1},{"version":"dfadcd1940a5dc36721d3311ebd8eb8b-export type TheStr = string;","signature":"9551f60bc06319547b96535db4cb8520-export type TheStr = string;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./"},"referencedMap":[[3,1]],"latestChangedDtsFile":"./other.d.ts"} +{"version":"FakeTSVersion","root":[[2,4]],"packageJsons":["../package.json"],"fileNames":["lib.es2025.full.d.ts","../const.ts","../index.ts","../other.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"be0f939ab1143e4064a3742586332724-export type TheNum = 42;","signature":"56e2d69d2edd1f0edd1a64ecfdf6de0d-export type TheNum = 42;\n","impliedNodeFormat":1},{"version":"c95c354b23966e289caeaece40bb8d0a-export type { TheNum } from './const.js';","signature":"f257912cfebb94a04c6ba4e8f754166a-export type { TheNum } from './const.js';\n","impliedNodeFormat":1},{"version":"dfadcd1940a5dc36721d3311ebd8eb8b-export type TheStr = string;","signature":"9551f60bc06319547b96535db4cb8520-export type TheStr = string;\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"outDir":"./"},"referencedMap":[[3,1]],"latestChangedDtsFile":"./other.d.ts"} //// [/user/username/projects/myproject/packages/pkg2/build/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -172,6 +176,9 @@ export {}; ] } ], + "packageJsons": [ + "../package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "../const.ts", @@ -240,7 +247,7 @@ export {}; ] }, "latestChangedDtsFile": "./other.d.ts", - "size": 1576 + "size": 1611 } Watch Registrations:: @@ -278,23 +285,98 @@ Edit [0]:: reports import errors after change to package file Output:: +[HH:MM:SS AM] File change detected. Starting incremental compilation... + +[HH:MM:SS AM] Projects in this build: + * packages/pkg2/tsconfig.json + * packages/pkg1/tsconfig.json + +[HH:MM:SS AM] Project 'packages/pkg2/tsconfig.json' is out of date because output 'packages/pkg2/build/tsconfig.tsbuildinfo' is older than input 'packages/pkg2/package.json' + +[HH:MM:SS AM] Building project 'packages/pkg2/tsconfig.json'... + +======== Resolving module './const.js' from '/user/username/projects/myproject/packages/pkg2/index.ts'. ======== +Module resolution kind is not specified, using 'Bundler'. +Resolving in CJS mode with conditions 'import', 'types'. +Loading module as file / folder, candidate module location '/user/username/projects/myproject/packages/pkg2/const.js', target file types: TypeScript, JavaScript, Declaration, JSON. +File name '/user/username/projects/myproject/packages/pkg2/const.js' has a '.js' extension - stripping it. +File '/user/username/projects/myproject/packages/pkg2/const.ts' exists - use it as a name resolution result. +======== Module name './const.js' was successfully resolved to '/user/username/projects/myproject/packages/pkg2/const.ts'. ======== +[HH:MM:SS AM] Updating unchanged output timestamps of project 'packages/pkg2/tsconfig.json'... + +[HH:MM:SS AM] Project 'packages/pkg1/tsconfig.json' is out of date because output 'packages/pkg1/build/tsconfig.tsbuildinfo' is older than input 'packages/pkg2/package.json' + +[HH:MM:SS AM] Building project 'packages/pkg1/tsconfig.json'... + +======== Resolving module 'pkg2' from '/user/username/projects/myproject/packages/pkg1/index.ts'. ======== +Module resolution kind is not specified, using 'Bundler'. +Resolving in CJS mode with conditions 'import', 'types'. +Found 'package.json' at '/user/username/projects/myproject/packages/pkg1/package.json'. +Loading module 'pkg2' from 'node_modules' folder, target file types: TypeScript, JavaScript, Declaration, JSON. +Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration. +Directory '/user/username/projects/myproject/packages/pkg1/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/myproject/packages/node_modules' does not exist, skipping all lookups in it. +Found 'package.json' at '/user/username/projects/myproject/node_modules/pkg2/package.json'. +File '/user/username/projects/myproject/node_modules/pkg2.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.tsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.d.ts' does not exist. +'package.json' does not have a 'typesVersions' field. +'package.json' does not have a 'typings' field. +'package.json' does not have a 'types' field. +'package.json' has 'main' field 'build/other.js' that references '/user/username/projects/myproject/node_modules/pkg2/build/other.js'. +File name '/user/username/projects/myproject/node_modules/pkg2/build/other.js' has a '.js' extension - stripping it. +File '/user/username/projects/myproject/node_modules/pkg2/build/other.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/build/other.tsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/build/other.d.ts' exists - use it as a name resolution result. +'package.json' does not have a 'peerDependencies' field. +Resolving real path for '/user/username/projects/myproject/node_modules/pkg2/build/other.d.ts', result '/user/username/projects/myproject/packages/pkg2/build/other.d.ts'. +======== Module name 'pkg2' was successfully resolved to '/user/username/projects/myproject/packages/pkg2/build/other.d.ts' with Package ID 'pkg2/build/other.d.ts@1.0.0'. ======== +packages/pkg1/index.ts:1:15 - error TS2305: Module '"pkg2"' has no exported member 'TheNum'. + +1 import type { TheNum } from 'pkg2' +   ~~~~~~ + +[HH:MM:SS AM] Found 1 error. Watching for file changes. + +//// [/user/username/projects/myproject/packages/pkg1/build/index.js] *rewrite with same content* +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":["../index.ts"],"packageJsons":["../package.json","../../pkg2/package.json"],"semanticErrors":true} +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../index.ts" + ], + "original": "../index.ts" + } + ], + "packageJsons": [ + "../package.json", + "../../pkg2/package.json" + ], + "size": 133, + "semanticErrors": true +} +//// [/user/username/projects/myproject/packages/pkg2/build/tsconfig.tsbuildinfo] *mTime changed* Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /user/username/projects/myproject/packages/pkg1 (recursive) /user/username/projects/myproject/packages/pkg2 (recursive) +packages/pkg2/tsconfig.json:: +SemanticDiagnostics:: +Signatures:: +packages/pkg1/tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* /user/username/projects/myproject/packages/pkg2/build/other.d.ts +*refresh* /user/username/projects/myproject/packages/pkg1/index.ts +Signatures:: -Diff:: Package.json watch pending, so no change detected yet ---- nonIncremental.output.txt -+++ incremental.output.txt -@@ -1,5 +0,0 @@ --packages/pkg1/index.ts:1:15 - error TS2305: Module '"pkg2"' has no exported member 'TheNum'. -- --1 import type { TheNum } from 'pkg2' --   ~~~~~~ -- Edit [1]:: removes those errors when a package file is changed back //// [/user/username/projects/myproject/packages/pkg2/package.json] *modified* @@ -306,9 +388,97 @@ Edit [1]:: removes those errors when a package file is changed back Output:: +[HH:MM:SS AM] File change detected. Starting incremental compilation... + +[HH:MM:SS AM] Projects in this build: + * packages/pkg2/tsconfig.json + * packages/pkg1/tsconfig.json + +[HH:MM:SS AM] Project 'packages/pkg2/tsconfig.json' is out of date because output 'packages/pkg2/build/tsconfig.tsbuildinfo' is older than input 'packages/pkg2/package.json' + +[HH:MM:SS AM] Building project 'packages/pkg2/tsconfig.json'... + +======== Resolving module './const.js' from '/user/username/projects/myproject/packages/pkg2/index.ts'. ======== +Module resolution kind is not specified, using 'Bundler'. +Resolving in CJS mode with conditions 'import', 'types'. +Loading module as file / folder, candidate module location '/user/username/projects/myproject/packages/pkg2/const.js', target file types: TypeScript, JavaScript, Declaration, JSON. +File name '/user/username/projects/myproject/packages/pkg2/const.js' has a '.js' extension - stripping it. +File '/user/username/projects/myproject/packages/pkg2/const.ts' exists - use it as a name resolution result. +======== Module name './const.js' was successfully resolved to '/user/username/projects/myproject/packages/pkg2/const.ts'. ======== +[HH:MM:SS AM] Updating unchanged output timestamps of project 'packages/pkg2/tsconfig.json'... + +[HH:MM:SS AM] Project 'packages/pkg1/tsconfig.json' is out of date because buildinfo file 'packages/pkg1/build/tsconfig.tsbuildinfo' indicates that program needs to report errors. + +[HH:MM:SS AM] Building project 'packages/pkg1/tsconfig.json'... + +======== Resolving module 'pkg2' from '/user/username/projects/myproject/packages/pkg1/index.ts'. ======== +Module resolution kind is not specified, using 'Bundler'. +Resolving in CJS mode with conditions 'import', 'types'. +Found 'package.json' at '/user/username/projects/myproject/packages/pkg1/package.json'. +Loading module 'pkg2' from 'node_modules' folder, target file types: TypeScript, JavaScript, Declaration, JSON. +Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration. +Directory '/user/username/projects/myproject/packages/pkg1/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/myproject/packages/node_modules' does not exist, skipping all lookups in it. +Found 'package.json' at '/user/username/projects/myproject/node_modules/pkg2/package.json'. +File '/user/username/projects/myproject/node_modules/pkg2.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.tsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.d.ts' does not exist. +'package.json' does not have a 'typesVersions' field. +'package.json' does not have a 'typings' field. +'package.json' does not have a 'types' field. +'package.json' has 'main' field 'build/index.js' that references '/user/username/projects/myproject/node_modules/pkg2/build/index.js'. +File name '/user/username/projects/myproject/node_modules/pkg2/build/index.js' has a '.js' extension - stripping it. +File '/user/username/projects/myproject/node_modules/pkg2/build/index.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/build/index.tsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/build/index.d.ts' exists - use it as a name resolution result. +'package.json' does not have a 'peerDependencies' field. +Resolving real path for '/user/username/projects/myproject/node_modules/pkg2/build/index.d.ts', result '/user/username/projects/myproject/packages/pkg2/build/index.d.ts'. +======== Module name 'pkg2' was successfully resolved to '/user/username/projects/myproject/packages/pkg2/build/index.d.ts' with Package ID 'pkg2/build/index.d.ts@1.0.0'. ======== +======== Resolving module './const.js' from '/user/username/projects/myproject/packages/pkg2/index.ts'. ======== +Using compiler options of project reference redirect '/user/username/projects/myproject/packages/pkg2/tsconfig.json'. +Module resolution kind is not specified, using 'Bundler'. +Resolving in CJS mode with conditions 'import', 'types'. +Loading module as file / folder, candidate module location '/user/username/projects/myproject/packages/pkg2/const.js', target file types: TypeScript, JavaScript, Declaration, JSON. +File name '/user/username/projects/myproject/packages/pkg2/const.js' has a '.js' extension - stripping it. +File '/user/username/projects/myproject/packages/pkg2/const.ts' exists - use it as a name resolution result. +======== Module name './const.js' was successfully resolved to '/user/username/projects/myproject/packages/pkg2/const.ts'. ======== +[HH:MM:SS AM] Found 0 errors. Watching for file changes. + +//// [/user/username/projects/myproject/packages/pkg1/build/index.js] *rewrite with same content* +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":["../index.ts"],"packageJsons":["../package.json","../../pkg2/package.json"]} +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../index.ts" + ], + "original": "../index.ts" + } + ], + "packageJsons": [ + "../package.json", + "../../pkg2/package.json" + ], + "size": 111 +} +//// [/user/username/projects/myproject/packages/pkg2/build/tsconfig.tsbuildinfo] *mTime changed* Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /user/username/projects/myproject/packages/pkg1 (recursive) /user/username/projects/myproject/packages/pkg2 (recursive) +packages/pkg2/tsconfig.json:: +SemanticDiagnostics:: +Signatures:: + +packages/pkg1/tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* /user/username/projects/myproject/packages/pkg2/build/const.d.ts +*refresh* /user/username/projects/myproject/packages/pkg2/build/index.d.ts +*refresh* /user/username/projects/myproject/packages/pkg1/index.ts +Signatures:: diff --git a/testdata/baselines/reference/tsbuildWatch/moduleResolution/build-mode-watches-missing-package-json-lookups.js b/testdata/baselines/reference/tsbuildWatch/moduleResolution/build-mode-watches-missing-package-json-lookups.js new file mode 100644 index 00000000000..d66239b78f7 --- /dev/null +++ b/testdata/baselines/reference/tsbuildWatch/moduleResolution/build-mode-watches-missing-package-json-lookups.js @@ -0,0 +1,292 @@ +currentDirectory::/user/username/projects/myproject +useCaseSensitiveFileNames::true +Input:: +//// [/user/username/projects/myproject/packages/pkg1/index.ts] *new* +import type { TheNum } from 'pkg2' +export const theNum: TheNum = 42; +//// [/user/username/projects/myproject/packages/pkg1/tsconfig.json] *new* +{ + "compilerOptions": { + "outDir": "build", + }, +} + +tsgo -b packages/pkg1 -w --verbose --traceResolution +ExitStatus:: DiagnosticsPresent_OutputsGenerated +Output:: +[HH:MM:SS AM] Starting compilation in watch mode... + +[HH:MM:SS AM] Projects in this build: + * packages/pkg1/tsconfig.json + +[HH:MM:SS AM] Project 'packages/pkg1/tsconfig.json' is out of date because output file 'packages/pkg1/build/tsconfig.tsbuildinfo' does not exist + +[HH:MM:SS AM] Building project 'packages/pkg1/tsconfig.json'... + +======== Resolving module 'pkg2' from '/user/username/projects/myproject/packages/pkg1/index.ts'. ======== +Module resolution kind is not specified, using 'Bundler'. +Resolving in CJS mode with conditions 'import', 'types'. +File '/user/username/projects/myproject/packages/pkg1/package.json' does not exist. +File '/user/username/projects/myproject/packages/package.json' does not exist. +File '/user/username/projects/myproject/package.json' does not exist. +File '/user/username/projects/package.json' does not exist. +File '/user/username/package.json' does not exist. +File '/user/package.json' does not exist. +File '/package.json' does not exist. +Loading module 'pkg2' from 'node_modules' folder, target file types: TypeScript, JavaScript, Declaration, JSON. +Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration. +Directory '/user/username/projects/myproject/packages/pkg1/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/myproject/packages/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/myproject/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/node_modules' does not exist, skipping all lookups in it. +Directory '/user/node_modules' does not exist, skipping all lookups in it. +Directory '/node_modules' does not exist, skipping all lookups in it. +Searching all ancestor node_modules directories for fallback extensions: JavaScript, JSON. +Directory '/user/username/projects/myproject/packages/pkg1/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/myproject/packages/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/myproject/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/node_modules' does not exist, skipping all lookups in it. +Directory '/user/node_modules' does not exist, skipping all lookups in it. +Directory '/node_modules' does not exist, skipping all lookups in it. +======== Module name 'pkg2' was not resolved. ======== +packages/pkg1/index.ts:1:29 - error TS2307: Cannot find module 'pkg2' or its corresponding type declarations. + +1 import type { TheNum } from 'pkg2' +   ~~~~~~ + +[HH:MM:SS AM] Found 1 error. Watching for file changes. + +//// [/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts] *Lib* +/// +interface Boolean {} +interface Function {} +interface CallableFunction {} +interface NewableFunction {} +interface IArguments {} +interface Number { toExponential: any; } +interface Object {} +interface RegExp {} +interface String { charAt: any; } +interface Array { length: number; [n: number]: T; } +interface ReadonlyArray {} +interface SymbolConstructor { + (desc?: string | number): symbol; + for(name: string): symbol; + readonly toStringTag: symbol; +} +declare var Symbol: SymbolConstructor; +interface Symbol { + readonly [Symbol.toStringTag]: string; +} +declare const console: { log(msg: any): void; }; +//// [/user/username/projects/myproject/packages/pkg1/build/index.js] *new* +export const theNum = 42; + +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo] *new* +{"version":"FakeTSVersion","root":["../index.ts"],"semanticErrors":true} +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo.readable.baseline.txt] *new* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../index.ts" + ], + "original": "../index.ts" + } + ], + "size": 72, + "semanticErrors": true +} + +Watch Registrations:: +Directory watches:: + /user/username/projects/myproject + /user/username/projects/myproject/packages + /user/username/projects/myproject/packages/pkg1 (recursive) +packages/pkg1/tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* /user/username/projects/myproject/packages/pkg1/index.ts +Signatures:: + + +Edit [0]:: resolves import after package is installed +//// [/user/username/projects/myproject/node_modules/pkg2/index.d.ts] *new* +export type TheNum = 42; +//// [/user/username/projects/myproject/node_modules/pkg2/package.json] *new* +{ + "name": "pkg2", + "version": "1.0.0", + "types": "index.d.ts" +} + + +Output:: +[HH:MM:SS AM] File change detected. Starting incremental compilation... + +[HH:MM:SS AM] Projects in this build: + * packages/pkg1/tsconfig.json + +[HH:MM:SS AM] Project 'packages/pkg1/tsconfig.json' is out of date because buildinfo file 'packages/pkg1/build/tsconfig.tsbuildinfo' indicates that program needs to report errors. + +[HH:MM:SS AM] Building project 'packages/pkg1/tsconfig.json'... + +======== Resolving module 'pkg2' from '/user/username/projects/myproject/packages/pkg1/index.ts'. ======== +Module resolution kind is not specified, using 'Bundler'. +Resolving in CJS mode with conditions 'import', 'types'. +File '/user/username/projects/myproject/packages/pkg1/package.json' does not exist. +File '/user/username/projects/myproject/packages/package.json' does not exist. +File '/user/username/projects/myproject/package.json' does not exist. +File '/user/username/projects/package.json' does not exist. +File '/user/username/package.json' does not exist. +File '/user/package.json' does not exist. +File '/package.json' does not exist. +Loading module 'pkg2' from 'node_modules' folder, target file types: TypeScript, JavaScript, Declaration, JSON. +Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration. +Directory '/user/username/projects/myproject/packages/pkg1/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/myproject/packages/node_modules' does not exist, skipping all lookups in it. +Found 'package.json' at '/user/username/projects/myproject/node_modules/pkg2/package.json'. +File '/user/username/projects/myproject/node_modules/pkg2.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.tsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.d.ts' does not exist. +'package.json' does not have a 'typesVersions' field. +'package.json' does not have a 'typings' field. +'package.json' has 'types' field 'index.d.ts' that references '/user/username/projects/myproject/node_modules/pkg2/index.d.ts'. +File '/user/username/projects/myproject/node_modules/pkg2/index.d.ts' exists - use it as a name resolution result. +'package.json' does not have a 'peerDependencies' field. +Resolving real path for '/user/username/projects/myproject/node_modules/pkg2/index.d.ts', result '/user/username/projects/myproject/node_modules/pkg2/index.d.ts'. +======== Module name 'pkg2' was successfully resolved to '/user/username/projects/myproject/node_modules/pkg2/index.d.ts' with Package ID 'pkg2/index.d.ts@1.0.0'. ======== +[HH:MM:SS AM] Found 0 errors. Watching for file changes. + +//// [/user/username/projects/myproject/packages/pkg1/build/index.js] *rewrite with same content* +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":["../index.ts"],"packageJsons":["../../../node_modules/pkg2/package.json"]} +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../index.ts" + ], + "original": "../index.ts" + } + ], + "packageJsons": [ + "../../../node_modules/pkg2/package.json" + ], + "size": 109 +} + +Watch Registrations:: +Directory watches:: + /user/username/projects/myproject + /user/username/projects/myproject/node_modules + /user/username/projects/myproject/node_modules/pkg2 + /user/username/projects/myproject/packages + /user/username/projects/myproject/packages/pkg1 (recursive) +packages/pkg1/tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* /user/username/projects/myproject/node_modules/pkg2/index.d.ts +*refresh* /user/username/projects/myproject/packages/pkg1/index.ts +Signatures:: + + +Edit [1]:: reports import errors after package is removed +//// [/user/username/projects/myproject/node_modules/pkg2/index.d.ts] *deleted* +//// [/user/username/projects/myproject/node_modules/pkg2/package.json] *deleted* + + +Output:: +[HH:MM:SS AM] File change detected. Starting incremental compilation... + +[HH:MM:SS AM] Projects in this build: + * packages/pkg1/tsconfig.json + +[HH:MM:SS AM] Project 'packages/pkg1/tsconfig.json' is out of date because input 'node_modules/pkg2/package.json' does not exist. + +[HH:MM:SS AM] Building project 'packages/pkg1/tsconfig.json'... + +======== Resolving module 'pkg2' from '/user/username/projects/myproject/packages/pkg1/index.ts'. ======== +Module resolution kind is not specified, using 'Bundler'. +Resolving in CJS mode with conditions 'import', 'types'. +File '/user/username/projects/myproject/packages/pkg1/package.json' does not exist. +File '/user/username/projects/myproject/packages/package.json' does not exist. +File '/user/username/projects/myproject/package.json' does not exist. +File '/user/username/projects/package.json' does not exist. +File '/user/username/package.json' does not exist. +File '/user/package.json' does not exist. +File '/package.json' does not exist. +Loading module 'pkg2' from 'node_modules' folder, target file types: TypeScript, JavaScript, Declaration, JSON. +Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration. +Directory '/user/username/projects/myproject/packages/pkg1/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/myproject/packages/node_modules' does not exist, skipping all lookups in it. +File '/user/username/projects/myproject/node_modules/pkg2/package.json' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.tsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.d.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/index.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/index.tsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/index.d.ts' does not exist. +Directory '/user/username/projects/myproject/node_modules/@types' does not exist, skipping all lookups in it. +Directory '/user/username/projects/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/node_modules' does not exist, skipping all lookups in it. +Directory '/user/node_modules' does not exist, skipping all lookups in it. +Directory '/node_modules' does not exist, skipping all lookups in it. +Searching all ancestor node_modules directories for fallback extensions: JavaScript, JSON. +Directory '/user/username/projects/myproject/packages/pkg1/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/myproject/packages/node_modules' does not exist, skipping all lookups in it. +File '/user/username/projects/myproject/node_modules/pkg2/package.json' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.js' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.jsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/index.js' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/index.jsx' does not exist. +Directory '/user/username/projects/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/node_modules' does not exist, skipping all lookups in it. +Directory '/user/node_modules' does not exist, skipping all lookups in it. +Directory '/node_modules' does not exist, skipping all lookups in it. +======== Module name 'pkg2' was not resolved. ======== +packages/pkg1/index.ts:1:29 - error TS2307: Cannot find module 'pkg2' or its corresponding type declarations. + +1 import type { TheNum } from 'pkg2' +   ~~~~~~ + +[HH:MM:SS AM] Found 1 error. Watching for file changes. + +//// [/user/username/projects/myproject/packages/pkg1/build/index.js] *rewrite with same content* +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":["../index.ts"],"missingPackageJsons":["../../../node_modules/pkg2/package.json"],"semanticErrors":true} +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../index.ts" + ], + "original": "../index.ts" + } + ], + "missingPackageJsons": [ + "../../../node_modules/pkg2/package.json" + ], + "size": 138, + "semanticErrors": true +} + +Watch Registrations:: +Directory watches:: + /user/username/projects/myproject + /user/username/projects/myproject/node_modules + /user/username/projects/myproject/node_modules/pkg2 + /user/username/projects/myproject/packages + /user/username/projects/myproject/packages/pkg1 (recursive) +packages/pkg1/tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* /user/username/projects/myproject/packages/pkg1/index.ts +Signatures:: diff --git a/testdata/baselines/reference/tsbuildWatch/moduleResolution/build-mode-watches-package-json-lookups-from-existing-buildinfo.js b/testdata/baselines/reference/tsbuildWatch/moduleResolution/build-mode-watches-package-json-lookups-from-existing-buildinfo.js new file mode 100644 index 00000000000..0400dd4b598 --- /dev/null +++ b/testdata/baselines/reference/tsbuildWatch/moduleResolution/build-mode-watches-package-json-lookups-from-existing-buildinfo.js @@ -0,0 +1,180 @@ +currentDirectory::/user/username/projects/myproject +useCaseSensitiveFileNames::true +Input:: +//// [/user/username/projects/myproject/node_modules/pkg2/index.d.ts] *new* +export type TheNum = 42; +//// [/user/username/projects/myproject/node_modules/pkg2/package.json] *new* +{ + "name": "pkg2", + "version": "1.0.0", + "types": "index.d.ts" +} +//// [/user/username/projects/myproject/packages/pkg1/index.ts] *new* +import type { TheNum } from 'pkg2' +export const theNum: TheNum = 42; +//// [/user/username/projects/myproject/packages/pkg1/tsconfig.json] *new* +{ + "compilerOptions": { + "outDir": "zzbuild", + }, +} +//// [/user/username/projects/myproject/packages/pkg1/zzbuild/index.js] *new* +export const theNum = 42; + +//// [/user/username/projects/myproject/packages/pkg1/zzbuild/tsconfig.tsbuildinfo] *new* +{"version":"FakeTSVersion","root":["../index.ts"],"packageJsons":["../../../node_modules/pkg2/package.json"]} +//// [/user/username/projects/myproject/packages/pkg1/zzbuild/tsconfig.tsbuildinfo.readable.baseline.txt] *new* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../index.ts" + ], + "original": "../index.ts" + } + ], + "packageJsons": [ + "../../../node_modules/pkg2/package.json" + ], + "size": 109 +} + +tsgo -b packages/pkg1 -w --verbose --traceResolution +ExitStatus:: Success +Output:: +[HH:MM:SS AM] Starting compilation in watch mode... + +[HH:MM:SS AM] Projects in this build: + * packages/pkg1/tsconfig.json + +[HH:MM:SS AM] Project 'packages/pkg1/tsconfig.json' is up to date because newest input 'packages/pkg1/index.ts' is older than output 'packages/pkg1/zzbuild/index.js' + +[HH:MM:SS AM] Found 0 errors. Watching for file changes. + + +Watch Registrations:: +Directory watches:: + /user/username/projects/myproject + /user/username/projects/myproject/node_modules + /user/username/projects/myproject/node_modules/pkg2 + /user/username/projects/myproject/packages/pkg1 (recursive) + + +Edit [0]:: reports import errors after package is removed +//// [/user/username/projects/myproject/node_modules/pkg2/index.d.ts] *deleted* +//// [/user/username/projects/myproject/node_modules/pkg2/package.json] *deleted* + + +Output:: +[HH:MM:SS AM] File change detected. Starting incremental compilation... + +[HH:MM:SS AM] Projects in this build: + * packages/pkg1/tsconfig.json + +[HH:MM:SS AM] Project 'packages/pkg1/tsconfig.json' is out of date because input 'node_modules/pkg2/package.json' does not exist. + +[HH:MM:SS AM] Building project 'packages/pkg1/tsconfig.json'... + +======== Resolving module 'pkg2' from '/user/username/projects/myproject/packages/pkg1/index.ts'. ======== +Module resolution kind is not specified, using 'Bundler'. +Resolving in CJS mode with conditions 'import', 'types'. +File '/user/username/projects/myproject/packages/pkg1/package.json' does not exist. +File '/user/username/projects/myproject/packages/package.json' does not exist. +File '/user/username/projects/myproject/package.json' does not exist. +File '/user/username/projects/package.json' does not exist. +File '/user/username/package.json' does not exist. +File '/user/package.json' does not exist. +File '/package.json' does not exist. +Loading module 'pkg2' from 'node_modules' folder, target file types: TypeScript, JavaScript, Declaration, JSON. +Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration. +Directory '/user/username/projects/myproject/packages/pkg1/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/myproject/packages/node_modules' does not exist, skipping all lookups in it. +File '/user/username/projects/myproject/node_modules/pkg2/package.json' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.tsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.d.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/index.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/index.tsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/index.d.ts' does not exist. +Directory '/user/username/projects/myproject/node_modules/@types' does not exist, skipping all lookups in it. +Directory '/user/username/projects/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/node_modules' does not exist, skipping all lookups in it. +Directory '/user/node_modules' does not exist, skipping all lookups in it. +Directory '/node_modules' does not exist, skipping all lookups in it. +Searching all ancestor node_modules directories for fallback extensions: JavaScript, JSON. +Directory '/user/username/projects/myproject/packages/pkg1/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/myproject/packages/node_modules' does not exist, skipping all lookups in it. +File '/user/username/projects/myproject/node_modules/pkg2/package.json' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.js' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.jsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/index.js' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/index.jsx' does not exist. +Directory '/user/username/projects/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/node_modules' does not exist, skipping all lookups in it. +Directory '/user/node_modules' does not exist, skipping all lookups in it. +Directory '/node_modules' does not exist, skipping all lookups in it. +======== Module name 'pkg2' was not resolved. ======== +packages/pkg1/index.ts:1:29 - error TS2307: Cannot find module 'pkg2' or its corresponding type declarations. + +1 import type { TheNum } from 'pkg2' +   ~~~~~~ + +[HH:MM:SS AM] Found 1 error. Watching for file changes. + +//// [/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts] *Lib* +/// +interface Boolean {} +interface Function {} +interface CallableFunction {} +interface NewableFunction {} +interface IArguments {} +interface Number { toExponential: any; } +interface Object {} +interface RegExp {} +interface String { charAt: any; } +interface Array { length: number; [n: number]: T; } +interface ReadonlyArray {} +interface SymbolConstructor { + (desc?: string | number): symbol; + for(name: string): symbol; + readonly toStringTag: symbol; +} +declare var Symbol: SymbolConstructor; +interface Symbol { + readonly [Symbol.toStringTag]: string; +} +declare const console: { log(msg: any): void; }; +//// [/user/username/projects/myproject/packages/pkg1/zzbuild/index.js] *rewrite with same content* +//// [/user/username/projects/myproject/packages/pkg1/zzbuild/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":["../index.ts"],"missingPackageJsons":["../../../node_modules/pkg2/package.json"],"semanticErrors":true} +//// [/user/username/projects/myproject/packages/pkg1/zzbuild/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../index.ts" + ], + "original": "../index.ts" + } + ], + "missingPackageJsons": [ + "../../../node_modules/pkg2/package.json" + ], + "size": 138, + "semanticErrors": true +} + +Watch Registrations:: +Directory watches:: + /user/username/projects/myproject + /user/username/projects/myproject/node_modules + /user/username/projects/myproject/node_modules/pkg2 + /user/username/projects/myproject/packages + /user/username/projects/myproject/packages/pkg1 (recursive) +packages/pkg1/tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* /user/username/projects/myproject/packages/pkg1/index.ts +Signatures:: diff --git a/testdata/baselines/reference/tsbuildWatch/moduleResolution/handles-the-cache-correctly-when-two-projects-use-different-module-resolution-settings.js b/testdata/baselines/reference/tsbuildWatch/moduleResolution/handles-the-cache-correctly-when-two-projects-use-different-module-resolution-settings.js index 3453333f920..bb9b4b09483 100644 --- a/testdata/baselines/reference/tsbuildWatch/moduleResolution/handles-the-cache-correctly-when-two-projects-use-different-module-resolution-settings.js +++ b/testdata/baselines/reference/tsbuildWatch/moduleResolution/handles-the-cache-correctly-when-two-projects-use-different-module-resolution-settings.js @@ -90,7 +90,7 @@ export {}; export {}; //// [/user/username/projects/myproject/project1/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[3],"fileNames":["lib.es2025.full.d.ts","./node_modules/file/index.d.ts","./index.ts","../node_modules/@types/foo/index.d.ts","../node_modules/@types/bar/index.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"bf6a9897955595825a99e7ef50878c55-export const foo = 10;",{"version":"7ae42cb6eee47288e3acb472bb3aad16-import { foo } from \"file\";","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":1},"bf6a9897955595825a99e7ef50878c55-export const foo = 10;","a0d503557e945e94b2464694c91a48ba-export const bar = 10;"],"fileIdsList":[[2]],"options":{"composite":true},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[3],"missingPackageJsons":["../node_modules/@types/bar/package.json","../node_modules/@types/foo/package.json","../node_modules/@types/package.json","../node_modules/package.json","./node_modules/file/package.json","./node_modules/package.json"],"fileNames":["lib.es2025.full.d.ts","./node_modules/file/index.d.ts","./index.ts","../node_modules/@types/foo/index.d.ts","../node_modules/@types/bar/index.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"bf6a9897955595825a99e7ef50878c55-export const foo = 10;",{"version":"7ae42cb6eee47288e3acb472bb3aad16-import { foo } from \"file\";","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":1},"bf6a9897955595825a99e7ef50878c55-export const foo = 10;","a0d503557e945e94b2464694c91a48ba-export const bar = 10;"],"fileIdsList":[[2]],"options":{"composite":true},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.ts"} //// [/user/username/projects/myproject/project1/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -102,6 +102,14 @@ export {}; "original": 3 } ], + "missingPackageJsons": [ + "../node_modules/@types/bar/package.json", + "../node_modules/@types/foo/package.json", + "../node_modules/@types/package.json", + "../node_modules/package.json", + "./node_modules/file/package.json", + "./node_modules/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./node_modules/file/index.d.ts", @@ -166,7 +174,7 @@ export {}; ] }, "latestChangedDtsFile": "./index.d.ts", - "size": 1429 + "size": 1671 } //// [/user/username/projects/myproject/project2/index.d.ts] *new* export {}; @@ -176,7 +184,7 @@ export {}; Object.defineProperty(exports, "__esModule", { value: true }); //// [/user/username/projects/myproject/project2/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[3],"fileNames":["lib.es2025.full.d.ts","./node_modules/file/index.d.ts","./index.ts","../node_modules/@types/foo/index.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"bf6a9897955595825a99e7ef50878c55-export const foo = 10;",{"version":"7ae42cb6eee47288e3acb472bb3aad16-import { foo } from \"file\";","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":1},"bf6a9897955595825a99e7ef50878c55-export const foo = 10;"],"fileIdsList":[[2]],"options":{"composite":true,"module":199},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[3],"missingPackageJsons":["../node_modules/@types/foo/package.json","../node_modules/@types/package.json","../node_modules/package.json","./node_modules/file/package.json","./node_modules/package.json"],"fileNames":["lib.es2025.full.d.ts","./node_modules/file/index.d.ts","./index.ts","../node_modules/@types/foo/index.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"bf6a9897955595825a99e7ef50878c55-export const foo = 10;",{"version":"7ae42cb6eee47288e3acb472bb3aad16-import { foo } from \"file\";","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":1},"bf6a9897955595825a99e7ef50878c55-export const foo = 10;"],"fileIdsList":[[2]],"options":{"composite":true,"module":199},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.ts"} //// [/user/username/projects/myproject/project2/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -188,6 +196,13 @@ Object.defineProperty(exports, "__esModule", { value: true }); "original": 3 } ], + "missingPackageJsons": [ + "../node_modules/@types/foo/package.json", + "../node_modules/@types/package.json", + "../node_modules/package.json", + "./node_modules/file/package.json", + "./node_modules/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./node_modules/file/index.d.ts", @@ -246,18 +261,22 @@ Object.defineProperty(exports, "__esModule", { value: true }); ] }, "latestChangedDtsFile": "./index.d.ts", - "size": 1344 + "size": 1544 } Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /user/username/projects/myproject + /user/username/projects/myproject/node_modules + /user/username/projects/myproject/node_modules/@types /user/username/projects/myproject/node_modules/@types/bar /user/username/projects/myproject/node_modules/@types/foo /user/username/projects/myproject/project1 + /user/username/projects/myproject/project1/node_modules /user/username/projects/myproject/project1/node_modules/file /user/username/projects/myproject/project2 + /user/username/projects/myproject/project2/node_modules /user/username/projects/myproject/project2/node_modules/file project1/tsconfig.json:: SemanticDiagnostics:: @@ -303,7 +322,7 @@ const bar = 10; export {}; //// [/user/username/projects/myproject/project1/tsconfig.tsbuildinfo] *modified* -{"version":"FakeTSVersion","root":[3],"fileNames":["lib.es2025.full.d.ts","./node_modules/file/index.d.ts","./index.ts","../node_modules/@types/foo/index.d.ts","../node_modules/@types/bar/index.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"bf6a9897955595825a99e7ef50878c55-export const foo = 10;",{"version":"1ab147b130b9a5309305c28d6be6beb4-import { foo } from \"file\";const bar = 10;","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":1},"bf6a9897955595825a99e7ef50878c55-export const foo = 10;","a0d503557e945e94b2464694c91a48ba-export const bar = 10;"],"fileIdsList":[[2]],"options":{"composite":true},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[3],"missingPackageJsons":["../node_modules/@types/bar/package.json","../node_modules/@types/foo/package.json","../node_modules/@types/package.json","../node_modules/package.json","./node_modules/file/package.json","./node_modules/package.json"],"fileNames":["lib.es2025.full.d.ts","./node_modules/file/index.d.ts","./index.ts","../node_modules/@types/foo/index.d.ts","../node_modules/@types/bar/index.d.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"bf6a9897955595825a99e7ef50878c55-export const foo = 10;",{"version":"1ab147b130b9a5309305c28d6be6beb4-import { foo } from \"file\";const bar = 10;","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":1},"bf6a9897955595825a99e7ef50878c55-export const foo = 10;","a0d503557e945e94b2464694c91a48ba-export const bar = 10;"],"fileIdsList":[[2]],"options":{"composite":true},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.ts"} //// [/user/username/projects/myproject/project1/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* { "version": "FakeTSVersion", @@ -315,6 +334,14 @@ export {}; "original": 3 } ], + "missingPackageJsons": [ + "../node_modules/@types/bar/package.json", + "../node_modules/@types/foo/package.json", + "../node_modules/@types/package.json", + "../node_modules/package.json", + "./node_modules/file/package.json", + "./node_modules/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./node_modules/file/index.d.ts", @@ -379,18 +406,22 @@ export {}; ] }, "latestChangedDtsFile": "./index.d.ts", - "size": 1444 + "size": 1686 } Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /user/username/projects/myproject + /user/username/projects/myproject/node_modules + /user/username/projects/myproject/node_modules/@types /user/username/projects/myproject/node_modules/@types/bar /user/username/projects/myproject/node_modules/@types/foo /user/username/projects/myproject/project1 + /user/username/projects/myproject/project1/node_modules /user/username/projects/myproject/project1/node_modules/file /user/username/projects/myproject/project2 + /user/username/projects/myproject/project2/node_modules /user/username/projects/myproject/project2/node_modules/file project1/tsconfig.json:: SemanticDiagnostics:: diff --git a/testdata/baselines/reference/tsbuildWatch/moduleResolution/resolves-specifier-in-output-declaration-file-from-referenced-project-correctly-with-cts-and-mts-extensions.js b/testdata/baselines/reference/tsbuildWatch/moduleResolution/resolves-specifier-in-output-declaration-file-from-referenced-project-correctly-with-cts-and-mts-extensions.js index fdbf634b8c2..00c07c4d054 100644 --- a/testdata/baselines/reference/tsbuildWatch/moduleResolution/resolves-specifier-in-output-declaration-file-from-referenced-project-correctly-with-cts-and-mts-extensions.js +++ b/testdata/baselines/reference/tsbuildWatch/moduleResolution/resolves-specifier-in-output-declaration-file-from-referenced-project-correctly-with-cts-and-mts-extensions.js @@ -121,7 +121,7 @@ declare const console: { log(msg: any): void; }; export const theNum = 42; //// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":["../index.ts"]} +{"version":"FakeTSVersion","root":["../index.ts"],"packageJsons":["../package.json","../../pkg2/package.json"]} //// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -133,7 +133,11 @@ export const theNum = 42; "original": "../index.ts" } ], - "size": 50 + "packageJsons": [ + "../package.json", + "../../pkg2/package.json" + ], + "size": 111 } //// [/user/username/projects/myproject/packages/pkg2/build/const.cjs] *new* "use strict"; @@ -149,7 +153,7 @@ export type { TheNum } from './const.cjs'; export {}; //// [/user/username/projects/myproject/packages/pkg2/build/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[2,3]],"fileNames":["lib.es2025.full.d.ts","../const.cts","../index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"be0f939ab1143e4064a3742586332724-export type TheNum = 42;","signature":"56e2d69d2edd1f0edd1a64ecfdf6de0d-export type TheNum = 42;\n","impliedNodeFormat":1},{"version":"7bb214373f4d1876e9a0040d287d1b6e-export type { TheNum } from './const.cjs';","signature":"2c7786a1f125eb57a4db00a4d58e384a-export type { TheNum } from './const.cjs';\n","impliedNodeFormat":99}],"fileIdsList":[[2]],"options":{"composite":true,"module":100,"outDir":"./"},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[[2,3]],"packageJsons":["../package.json"],"fileNames":["lib.es2025.full.d.ts","../const.cts","../index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"be0f939ab1143e4064a3742586332724-export type TheNum = 42;","signature":"56e2d69d2edd1f0edd1a64ecfdf6de0d-export type TheNum = 42;\n","impliedNodeFormat":1},{"version":"7bb214373f4d1876e9a0040d287d1b6e-export type { TheNum } from './const.cjs';","signature":"2c7786a1f125eb57a4db00a4d58e384a-export type { TheNum } from './const.cjs';\n","impliedNodeFormat":99}],"fileIdsList":[[2]],"options":{"composite":true,"module":100,"outDir":"./"},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.ts"} //// [/user/username/projects/myproject/packages/pkg2/build/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -165,6 +169,9 @@ export {}; ] } ], + "packageJsons": [ + "../package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "../const.cts", @@ -222,7 +229,7 @@ export {}; ] }, "latestChangedDtsFile": "./index.d.ts", - "size": 1403 + "size": 1438 } Watch Registrations:: @@ -259,33 +266,96 @@ Edit [0]:: reports import errors after change to package file Output:: +[HH:MM:SS AM] File change detected. Starting incremental compilation... + +[HH:MM:SS AM] Projects in this build: + * packages/pkg2/tsconfig.json + * packages/pkg1/tsconfig.json + +[HH:MM:SS AM] Project 'packages/pkg1/tsconfig.json' is out of date because output 'packages/pkg1/build/tsconfig.tsbuildinfo' is older than input 'packages/pkg1/package.json' + +[HH:MM:SS AM] Building project 'packages/pkg1/tsconfig.json'... + +======== Resolving module 'pkg2' from '/user/username/projects/myproject/packages/pkg1/index.ts'. ======== +Module resolution kind is not specified, using 'Node16'. +Resolving in CJS mode with conditions 'require', 'types', 'node'. +Found 'package.json' at '/user/username/projects/myproject/packages/pkg1/package.json'. +Loading module 'pkg2' from 'node_modules' folder, target file types: TypeScript, JavaScript, Declaration. +Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration. +Directory '/user/username/projects/myproject/packages/pkg1/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/myproject/packages/node_modules' does not exist, skipping all lookups in it. +Found 'package.json' at '/user/username/projects/myproject/node_modules/pkg2/package.json'. +File '/user/username/projects/myproject/node_modules/pkg2.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.tsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.d.ts' does not exist. +'package.json' does not have a 'typesVersions' field. +'package.json' does not have a 'typings' field. +'package.json' does not have a 'types' field. +'package.json' has 'main' field 'build/index.js' that references '/user/username/projects/myproject/node_modules/pkg2/build/index.js'. +File name '/user/username/projects/myproject/node_modules/pkg2/build/index.js' has a '.js' extension - stripping it. +File '/user/username/projects/myproject/node_modules/pkg2/build/index.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/build/index.tsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/build/index.d.ts' exists - use it as a name resolution result. +'package.json' does not have a 'peerDependencies' field. +Resolving real path for '/user/username/projects/myproject/node_modules/pkg2/build/index.d.ts', result '/user/username/projects/myproject/packages/pkg2/build/index.d.ts'. +======== Module name 'pkg2' was successfully resolved to '/user/username/projects/myproject/packages/pkg2/build/index.d.ts' with Package ID 'pkg2/build/index.d.ts@1.0.0'. ======== +======== Resolving module './const.cjs' from '/user/username/projects/myproject/packages/pkg2/index.ts'. ======== +Using compiler options of project reference redirect '/user/username/projects/myproject/packages/pkg2/tsconfig.json'. +Module resolution kind is not specified, using 'Node16'. +Resolving in ESM mode with conditions 'import', 'types', 'node'. +Loading module as file / folder, candidate module location '/user/username/projects/myproject/packages/pkg2/const.cjs', target file types: TypeScript, JavaScript, Declaration. +File name '/user/username/projects/myproject/packages/pkg2/const.cjs' has a '.cjs' extension - stripping it. +File '/user/username/projects/myproject/packages/pkg2/const.cts' exists - use it as a name resolution result. +======== Module name './const.cjs' was successfully resolved to '/user/username/projects/myproject/packages/pkg2/const.cts'. ======== +packages/pkg1/index.ts:1:29 - error TS1541: Type-only import of an ECMAScript module from a CommonJS module must have a 'resolution-mode' attribute. + To convert this file to an ECMAScript module, change its file extension to '.mts' or create a local package.json file with `{ "type": "module" }`. + +1 import type { TheNum } from 'pkg2' +   ~~~~~~ + +[HH:MM:SS AM] Found 1 error. Watching for file changes. + +//// [/user/username/projects/myproject/packages/pkg1/build/index.js] *modified* +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.theNum = void 0; +exports.theNum = 42; + +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":["../index.ts"],"packageJsons":["../package.json","../../pkg2/package.json"],"semanticErrors":true} +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../index.ts" + ], + "original": "../index.ts" + } + ], + "packageJsons": [ + "../package.json", + "../../pkg2/package.json" + ], + "size": 133, + "semanticErrors": true +} Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /user/username/projects/myproject/packages/pkg1 (recursive) /user/username/projects/myproject/packages/pkg2 (recursive) +packages/pkg1/tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* /user/username/projects/myproject/packages/pkg2/build/const.d.cts +*refresh* /user/username/projects/myproject/packages/pkg2/build/index.d.ts +*refresh* /user/username/projects/myproject/packages/pkg1/index.ts +Signatures:: -Diff:: Package.json watch pending, so no change detected yet ---- nonIncremental /user/username/projects/myproject/packages/pkg1/build/index.js -+++ incremental /user/username/projects/myproject/packages/pkg1/build/index.js -@@ -1,4 +1,1 @@ --"use strict"; --Object.defineProperty(exports, "__esModule", { value: true }); --exports.theNum = void 0; --exports.theNum = 42; -+export const theNum = 42; ---- nonIncremental.output.txt -+++ incremental.output.txt -@@ -1,6 +0,0 @@ --packages/pkg1/index.ts:1:29 - error TS1541: Type-only import of an ECMAScript module from a CommonJS module must have a 'resolution-mode' attribute. -- To convert this file to an ECMAScript module, change its file extension to '.mts' or create a local package.json file with `{ "type": "module" }`. -- --1 import type { TheNum } from 'pkg2' --   ~~~~~~ -- - Edit [1]:: removes those errors when a package file is changed back //// [/user/username/projects/myproject/packages/pkg1/package.json] *modified* { @@ -297,12 +367,81 @@ Edit [1]:: removes those errors when a package file is changed back Output:: +[HH:MM:SS AM] File change detected. Starting incremental compilation... + +[HH:MM:SS AM] Projects in this build: + * packages/pkg2/tsconfig.json + * packages/pkg1/tsconfig.json + +[HH:MM:SS AM] Project 'packages/pkg1/tsconfig.json' is out of date because buildinfo file 'packages/pkg1/build/tsconfig.tsbuildinfo' indicates that program needs to report errors. + +[HH:MM:SS AM] Building project 'packages/pkg1/tsconfig.json'... + +======== Resolving module 'pkg2' from '/user/username/projects/myproject/packages/pkg1/index.ts'. ======== +Module resolution kind is not specified, using 'Node16'. +Resolving in ESM mode with conditions 'import', 'types', 'node'. +Found 'package.json' at '/user/username/projects/myproject/packages/pkg1/package.json'. +Loading module 'pkg2' from 'node_modules' folder, target file types: TypeScript, JavaScript, Declaration. +Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration. +Directory '/user/username/projects/myproject/packages/pkg1/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/myproject/packages/node_modules' does not exist, skipping all lookups in it. +Found 'package.json' at '/user/username/projects/myproject/node_modules/pkg2/package.json'. +'package.json' does not have a 'typesVersions' field. +'package.json' does not have a 'typings' field. +'package.json' does not have a 'types' field. +'package.json' has 'main' field 'build/index.js' that references '/user/username/projects/myproject/node_modules/pkg2/build/index.js'. +File name '/user/username/projects/myproject/node_modules/pkg2/build/index.js' has a '.js' extension - stripping it. +File '/user/username/projects/myproject/node_modules/pkg2/build/index.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/build/index.tsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/build/index.d.ts' exists - use it as a name resolution result. +'package.json' does not have a 'peerDependencies' field. +Resolving real path for '/user/username/projects/myproject/node_modules/pkg2/build/index.d.ts', result '/user/username/projects/myproject/packages/pkg2/build/index.d.ts'. +======== Module name 'pkg2' was successfully resolved to '/user/username/projects/myproject/packages/pkg2/build/index.d.ts' with Package ID 'pkg2/build/index.d.ts@1.0.0'. ======== +======== Resolving module './const.cjs' from '/user/username/projects/myproject/packages/pkg2/index.ts'. ======== +Using compiler options of project reference redirect '/user/username/projects/myproject/packages/pkg2/tsconfig.json'. +Module resolution kind is not specified, using 'Node16'. +Resolving in ESM mode with conditions 'import', 'types', 'node'. +Loading module as file / folder, candidate module location '/user/username/projects/myproject/packages/pkg2/const.cjs', target file types: TypeScript, JavaScript, Declaration. +File name '/user/username/projects/myproject/packages/pkg2/const.cjs' has a '.cjs' extension - stripping it. +File '/user/username/projects/myproject/packages/pkg2/const.cts' exists - use it as a name resolution result. +======== Module name './const.cjs' was successfully resolved to '/user/username/projects/myproject/packages/pkg2/const.cts'. ======== +[HH:MM:SS AM] Found 0 errors. Watching for file changes. + +//// [/user/username/projects/myproject/packages/pkg1/build/index.js] *modified* +export const theNum = 42; + +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":["../index.ts"],"packageJsons":["../package.json","../../pkg2/package.json"]} +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../index.ts" + ], + "original": "../index.ts" + } + ], + "packageJsons": [ + "../package.json", + "../../pkg2/package.json" + ], + "size": 111 +} Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /user/username/projects/myproject/packages/pkg1 (recursive) /user/username/projects/myproject/packages/pkg2 (recursive) +packages/pkg1/tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* /user/username/projects/myproject/packages/pkg2/build/const.d.cts +*refresh* /user/username/projects/myproject/packages/pkg2/build/index.d.ts +*refresh* /user/username/projects/myproject/packages/pkg1/index.ts +Signatures:: Edit [2]:: reports import errors after change to package file @@ -316,33 +455,96 @@ Edit [2]:: reports import errors after change to package file Output:: +[HH:MM:SS AM] File change detected. Starting incremental compilation... + +[HH:MM:SS AM] Projects in this build: + * packages/pkg2/tsconfig.json + * packages/pkg1/tsconfig.json + +[HH:MM:SS AM] Project 'packages/pkg1/tsconfig.json' is out of date because output 'packages/pkg1/build/tsconfig.tsbuildinfo' is older than input 'packages/pkg1/package.json' + +[HH:MM:SS AM] Building project 'packages/pkg1/tsconfig.json'... + +======== Resolving module 'pkg2' from '/user/username/projects/myproject/packages/pkg1/index.ts'. ======== +Module resolution kind is not specified, using 'Node16'. +Resolving in CJS mode with conditions 'require', 'types', 'node'. +Found 'package.json' at '/user/username/projects/myproject/packages/pkg1/package.json'. +Loading module 'pkg2' from 'node_modules' folder, target file types: TypeScript, JavaScript, Declaration. +Searching all ancestor node_modules directories for preferred extensions: TypeScript, Declaration. +Directory '/user/username/projects/myproject/packages/pkg1/node_modules' does not exist, skipping all lookups in it. +Directory '/user/username/projects/myproject/packages/node_modules' does not exist, skipping all lookups in it. +Found 'package.json' at '/user/username/projects/myproject/node_modules/pkg2/package.json'. +File '/user/username/projects/myproject/node_modules/pkg2.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.tsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2.d.ts' does not exist. +'package.json' does not have a 'typesVersions' field. +'package.json' does not have a 'typings' field. +'package.json' does not have a 'types' field. +'package.json' has 'main' field 'build/index.js' that references '/user/username/projects/myproject/node_modules/pkg2/build/index.js'. +File name '/user/username/projects/myproject/node_modules/pkg2/build/index.js' has a '.js' extension - stripping it. +File '/user/username/projects/myproject/node_modules/pkg2/build/index.ts' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/build/index.tsx' does not exist. +File '/user/username/projects/myproject/node_modules/pkg2/build/index.d.ts' exists - use it as a name resolution result. +'package.json' does not have a 'peerDependencies' field. +Resolving real path for '/user/username/projects/myproject/node_modules/pkg2/build/index.d.ts', result '/user/username/projects/myproject/packages/pkg2/build/index.d.ts'. +======== Module name 'pkg2' was successfully resolved to '/user/username/projects/myproject/packages/pkg2/build/index.d.ts' with Package ID 'pkg2/build/index.d.ts@1.0.0'. ======== +======== Resolving module './const.cjs' from '/user/username/projects/myproject/packages/pkg2/index.ts'. ======== +Using compiler options of project reference redirect '/user/username/projects/myproject/packages/pkg2/tsconfig.json'. +Module resolution kind is not specified, using 'Node16'. +Resolving in ESM mode with conditions 'import', 'types', 'node'. +Loading module as file / folder, candidate module location '/user/username/projects/myproject/packages/pkg2/const.cjs', target file types: TypeScript, JavaScript, Declaration. +File name '/user/username/projects/myproject/packages/pkg2/const.cjs' has a '.cjs' extension - stripping it. +File '/user/username/projects/myproject/packages/pkg2/const.cts' exists - use it as a name resolution result. +======== Module name './const.cjs' was successfully resolved to '/user/username/projects/myproject/packages/pkg2/const.cts'. ======== +packages/pkg1/index.ts:1:29 - error TS1541: Type-only import of an ECMAScript module from a CommonJS module must have a 'resolution-mode' attribute. + To convert this file to an ECMAScript module, change its file extension to '.mts' or create a local package.json file with `{ "type": "module" }`. + +1 import type { TheNum } from 'pkg2' +   ~~~~~~ + +[HH:MM:SS AM] Found 1 error. Watching for file changes. + +//// [/user/username/projects/myproject/packages/pkg1/build/index.js] *modified* +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.theNum = void 0; +exports.theNum = 42; + +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":["../index.ts"],"packageJsons":["../package.json","../../pkg2/package.json"],"semanticErrors":true} +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../index.ts" + ], + "original": "../index.ts" + } + ], + "packageJsons": [ + "../package.json", + "../../pkg2/package.json" + ], + "size": 133, + "semanticErrors": true +} Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /user/username/projects/myproject/packages/pkg1 (recursive) /user/username/projects/myproject/packages/pkg2 (recursive) +packages/pkg1/tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* /user/username/projects/myproject/packages/pkg2/build/const.d.cts +*refresh* /user/username/projects/myproject/packages/pkg2/build/index.d.ts +*refresh* /user/username/projects/myproject/packages/pkg1/index.ts +Signatures:: -Diff:: Package.json watch pending, so no change detected yet ---- nonIncremental /user/username/projects/myproject/packages/pkg1/build/index.js -+++ incremental /user/username/projects/myproject/packages/pkg1/build/index.js -@@ -1,4 +1,1 @@ --"use strict"; --Object.defineProperty(exports, "__esModule", { value: true }); --exports.theNum = void 0; --exports.theNum = 42; -+export const theNum = 42; ---- nonIncremental.output.txt -+++ incremental.output.txt -@@ -1,6 +0,0 @@ --packages/pkg1/index.ts:1:29 - error TS1541: Type-only import of an ECMAScript module from a CommonJS module must have a 'resolution-mode' attribute. -- To convert this file to an ECMAScript module, change its file extension to '.mts' or create a local package.json file with `{ "type": "module" }`. -- --1 import type { TheNum } from 'pkg2' --   ~~~~~~ -- - Edit [3]:: removes those errors when a package file is changed to cjs extensions //// [/user/username/projects/myproject/packages/pkg2/index.cts] *new* export type { TheNum } from './const.cjs'; @@ -374,7 +576,7 @@ Loading module as file / folder, candidate module location '/user/username/proje File name '/user/username/projects/myproject/packages/pkg2/const.cjs' has a '.cjs' extension - stripping it. File '/user/username/projects/myproject/packages/pkg2/const.cts' exists - use it as a name resolution result. ======== Module name './const.cjs' was successfully resolved to '/user/username/projects/myproject/packages/pkg2/const.cts'. ======== -[HH:MM:SS AM] Project 'packages/pkg1/tsconfig.json' is out of date because output 'packages/pkg1/build/index.js' is older than input 'packages/pkg2/tsconfig.json' +[HH:MM:SS AM] Project 'packages/pkg1/tsconfig.json' is out of date because buildinfo file 'packages/pkg1/build/tsconfig.tsbuildinfo' indicates that program needs to report errors. [HH:MM:SS AM] Building project 'packages/pkg1/tsconfig.json'... @@ -410,14 +612,26 @@ File '/user/username/projects/myproject/packages/pkg2/const.cts' exists - use it ======== Module name './const.cjs' was successfully resolved to '/user/username/projects/myproject/packages/pkg2/const.cts'. ======== [HH:MM:SS AM] Found 0 errors. Watching for file changes. -//// [/user/username/projects/myproject/packages/pkg1/build/index.js] *modified* -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.theNum = void 0; -exports.theNum = 42; - -//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo] *rewrite with same content* -//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo.readable.baseline.txt] *rewrite with same content* +//// [/user/username/projects/myproject/packages/pkg1/build/index.js] *rewrite with same content* +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":["../index.ts"],"packageJsons":["../package.json","../../pkg2/package.json"]} +//// [/user/username/projects/myproject/packages/pkg1/build/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "../index.ts" + ], + "original": "../index.ts" + } + ], + "packageJsons": [ + "../package.json", + "../../pkg2/package.json" + ], + "size": 111 +} //// [/user/username/projects/myproject/packages/pkg2/build/index.cjs] *new* "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); @@ -426,7 +640,7 @@ Object.defineProperty(exports, "__esModule", { value: true }); export type { TheNum } from './const.cjs'; //// [/user/username/projects/myproject/packages/pkg2/build/tsconfig.tsbuildinfo] *modified* -{"version":"FakeTSVersion","root":[[2,3]],"fileNames":["lib.es2025.full.d.ts","../const.cts","../index.cts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"be0f939ab1143e4064a3742586332724-export type TheNum = 42;","signature":"56e2d69d2edd1f0edd1a64ecfdf6de0d-export type TheNum = 42;\n","impliedNodeFormat":1},{"version":"7bb214373f4d1876e9a0040d287d1b6e-export type { TheNum } from './const.cjs';","signature":"2c7786a1f125eb57a4db00a4d58e384a-export type { TheNum } from './const.cjs';\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"module":100,"outDir":"./"},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.cts"} +{"version":"FakeTSVersion","root":[[2,3]],"packageJsons":["../package.json"],"fileNames":["lib.es2025.full.d.ts","../const.cts","../index.cts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"be0f939ab1143e4064a3742586332724-export type TheNum = 42;","signature":"56e2d69d2edd1f0edd1a64ecfdf6de0d-export type TheNum = 42;\n","impliedNodeFormat":1},{"version":"7bb214373f4d1876e9a0040d287d1b6e-export type { TheNum } from './const.cjs';","signature":"2c7786a1f125eb57a4db00a4d58e384a-export type { TheNum } from './const.cjs';\n","impliedNodeFormat":1}],"fileIdsList":[[2]],"options":{"composite":true,"module":100,"outDir":"./"},"referencedMap":[[3,1]],"latestChangedDtsFile":"./index.d.cts"} //// [/user/username/projects/myproject/packages/pkg2/build/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* { "version": "FakeTSVersion", @@ -442,6 +656,9 @@ export type { TheNum } from './const.cjs'; ] } ], + "packageJsons": [ + "../package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "../const.cts", @@ -499,7 +716,7 @@ export type { TheNum } from './const.cjs'; ] }, "latestChangedDtsFile": "./index.d.cts", - "size": 1404 + "size": 1439 } Watch Registrations:: diff --git a/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-introduceError-when-file-with-no-error-changes.js b/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-introduceError-when-file-with-no-error-changes.js index 9730ae2c877..c29ff1a88a0 100644 --- a/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-introduceError-when-file-with-no-error-changes.js +++ b/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-introduceError-when-file-with-no-error-changes.js @@ -133,6 +133,7 @@ export class myClass { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/solution /user/username/projects/solution/app (recursive) app/tsconfig.json:: SemanticDiagnostics:: @@ -279,6 +280,7 @@ export var myClassWithError = class { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/solution /user/username/projects/solution/app (recursive) app/tsconfig.json:: SemanticDiagnostics:: @@ -421,6 +423,7 @@ export class myClass2 { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/solution /user/username/projects/solution/app (recursive) app/tsconfig.json:: SemanticDiagnostics:: diff --git a/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-introduceError-when-fixing-errors-only-changed-file-is-emitted.js b/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-introduceError-when-fixing-errors-only-changed-file-is-emitted.js index ebedc41d1cf..27e5d2018ae 100644 --- a/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-introduceError-when-fixing-errors-only-changed-file-is-emitted.js +++ b/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-introduceError-when-fixing-errors-only-changed-file-is-emitted.js @@ -133,6 +133,7 @@ export class myClass { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/solution /user/username/projects/solution/app (recursive) app/tsconfig.json:: SemanticDiagnostics:: @@ -279,6 +280,7 @@ export var myClassWithError = class { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/solution /user/username/projects/solution/app (recursive) app/tsconfig.json:: SemanticDiagnostics:: @@ -373,6 +375,7 @@ export var myClassWithError = class { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/solution /user/username/projects/solution/app (recursive) app/tsconfig.json:: SemanticDiagnostics:: diff --git a/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-when-file-with-no-error-changes.js b/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-when-file-with-no-error-changes.js index e008d8d1a28..7d854c57133 100644 --- a/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-when-file-with-no-error-changes.js +++ b/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-when-file-with-no-error-changes.js @@ -166,6 +166,7 @@ export class myClass { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/solution /user/username/projects/solution/app (recursive) app/tsconfig.json:: SemanticDiagnostics:: @@ -301,6 +302,7 @@ export class myClass2 { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/solution /user/username/projects/solution/app (recursive) app/tsconfig.json:: SemanticDiagnostics:: diff --git a/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-when-fixing-error-files-all-files-are-emitted.js b/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-when-fixing-error-files-all-files-are-emitted.js index e481ff2ee41..d99e8d2345c 100644 --- a/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-when-fixing-error-files-all-files-are-emitted.js +++ b/testdata/baselines/reference/tsbuildWatch/programUpdates/declarationEmitErrors-when-fixing-error-files-all-files-are-emitted.js @@ -166,6 +166,7 @@ export class myClass { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/solution /user/username/projects/solution/app (recursive) app/tsconfig.json:: SemanticDiagnostics:: @@ -269,6 +270,7 @@ export var myClassWithError = class { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/solution /user/username/projects/solution/app (recursive) app/tsconfig.json:: SemanticDiagnostics:: diff --git a/testdata/baselines/reference/tsbuildWatch/programUpdates/when-referenced-project-change-introduces-error-in-the-down-stream-project-and-then-fixes-it.js b/testdata/baselines/reference/tsbuildWatch/programUpdates/when-referenced-project-change-introduces-error-in-the-down-stream-project-and-then-fixes-it.js index 9d6818368db..cfba79d6835 100644 --- a/testdata/baselines/reference/tsbuildWatch/programUpdates/when-referenced-project-change-introduces-error-in-the-down-stream-project-and-then-fixes-it.js +++ b/testdata/baselines/reference/tsbuildWatch/programUpdates/when-referenced-project-change-introduces-error-in-the-down-stream-project-and-then-fixes-it.js @@ -142,6 +142,7 @@ export function createSomeObject() { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/App (recursive) /user/username/projects/sample1/Library (recursive) Library/tsconfig.json:: @@ -271,6 +272,7 @@ export function createSomeObject() { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/App (recursive) /user/username/projects/sample1/Library (recursive) Library/tsconfig.json:: @@ -389,6 +391,7 @@ export function createSomeObject() { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/App (recursive) /user/username/projects/sample1/Library (recursive) Library/tsconfig.json:: diff --git a/testdata/baselines/reference/tsbuildWatch/reexport/Reports-errors-correctly.js b/testdata/baselines/reference/tsbuildWatch/reexport/Reports-errors-correctly.js index 02f6096237e..e763e740bf6 100644 --- a/testdata/baselines/reference/tsbuildWatch/reexport/Reports-errors-correctly.js +++ b/testdata/baselines/reference/tsbuildWatch/reexport/Reports-errors-correctly.js @@ -196,6 +196,9 @@ export {}; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/reexport + /user/username/projects/reexport/out + /user/username/projects/reexport/out/pure /user/username/projects/reexport/src /user/username/projects/reexport/src/main (recursive) /user/username/projects/reexport/src/pure (recursive) @@ -357,6 +360,9 @@ export interface Session { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/reexport + /user/username/projects/reexport/out + /user/username/projects/reexport/out/pure /user/username/projects/reexport/src /user/username/projects/reexport/src/main (recursive) /user/username/projects/reexport/src/pure (recursive) @@ -506,6 +512,9 @@ export interface Session { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/reexport + /user/username/projects/reexport/out + /user/username/projects/reexport/out/pure /user/username/projects/reexport/src /user/username/projects/reexport/src/main (recursive) /user/username/projects/reexport/src/pure (recursive) diff --git a/testdata/baselines/reference/tsbuildWatch/roots/when-root-file-is-from-referenced-project-and-shared-is-first.js b/testdata/baselines/reference/tsbuildWatch/roots/when-root-file-is-from-referenced-project-and-shared-is-first.js index 6e2b9ee3c1c..68da9d8454a 100644 --- a/testdata/baselines/reference/tsbuildWatch/roots/when-root-file-is-from-referenced-project-and-shared-is-first.js +++ b/testdata/baselines/reference/tsbuildWatch/roots/when-root-file-is-from-referenced-project-and-shared-is-first.js @@ -340,9 +340,11 @@ Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /home/src/workspaces/solution + /home/src/workspaces/solution/projects /home/src/workspaces/solution/projects/server /home/src/workspaces/solution/projects/server/src (recursive) /home/src/workspaces/solution/projects/shared + /home/src/workspaces/solution/projects/shared/dist /home/src/workspaces/solution/projects/shared/dist/src /home/src/workspaces/solution/projects/shared/src (recursive) projects/shared/tsconfig.json:: @@ -376,9 +378,11 @@ Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /home/src/workspaces/solution + /home/src/workspaces/solution/projects /home/src/workspaces/solution/projects/server /home/src/workspaces/solution/projects/server/src (recursive) /home/src/workspaces/solution/projects/shared + /home/src/workspaces/solution/projects/shared/dist /home/src/workspaces/solution/projects/shared/dist/src /home/src/workspaces/solution/projects/shared/src (recursive) @@ -636,9 +640,11 @@ Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /home/src/workspaces/solution + /home/src/workspaces/solution/projects /home/src/workspaces/solution/projects/server /home/src/workspaces/solution/projects/server/src (recursive) /home/src/workspaces/solution/projects/shared + /home/src/workspaces/solution/projects/shared/dist /home/src/workspaces/solution/projects/shared/dist/src /home/src/workspaces/solution/projects/shared/src (recursive) projects/shared/tsconfig.json:: @@ -663,9 +669,11 @@ Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /home/src/workspaces/solution + /home/src/workspaces/solution/projects /home/src/workspaces/solution/projects/server /home/src/workspaces/solution/projects/server/src (recursive) /home/src/workspaces/solution/projects/shared + /home/src/workspaces/solution/projects/shared/dist /home/src/workspaces/solution/projects/shared/dist/src /home/src/workspaces/solution/projects/shared/src (recursive) @@ -879,9 +887,11 @@ Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /home/src/workspaces/solution + /home/src/workspaces/solution/projects /home/src/workspaces/solution/projects/server /home/src/workspaces/solution/projects/server/src (recursive) /home/src/workspaces/solution/projects/shared + /home/src/workspaces/solution/projects/shared/dist /home/src/workspaces/solution/projects/shared/dist/src /home/src/workspaces/solution/projects/shared/src (recursive) projects/shared/tsconfig.json:: @@ -902,8 +912,10 @@ Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /home/src/workspaces/solution + /home/src/workspaces/solution/projects /home/src/workspaces/solution/projects/server /home/src/workspaces/solution/projects/server/src (recursive) /home/src/workspaces/solution/projects/shared + /home/src/workspaces/solution/projects/shared/dist /home/src/workspaces/solution/projects/shared/dist/src /home/src/workspaces/solution/projects/shared/src (recursive) diff --git a/testdata/baselines/reference/tsbuildWatch/roots/when-root-file-is-from-referenced-project.js b/testdata/baselines/reference/tsbuildWatch/roots/when-root-file-is-from-referenced-project.js index b238722a135..ab3bfa23c65 100644 --- a/testdata/baselines/reference/tsbuildWatch/roots/when-root-file-is-from-referenced-project.js +++ b/testdata/baselines/reference/tsbuildWatch/roots/when-root-file-is-from-referenced-project.js @@ -340,9 +340,11 @@ Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /home/src/workspaces/solution + /home/src/workspaces/solution/projects /home/src/workspaces/solution/projects/server /home/src/workspaces/solution/projects/server/src (recursive) /home/src/workspaces/solution/projects/shared + /home/src/workspaces/solution/projects/shared/dist /home/src/workspaces/solution/projects/shared/dist/src /home/src/workspaces/solution/projects/shared/src (recursive) projects/shared/tsconfig.json:: @@ -376,9 +378,11 @@ Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /home/src/workspaces/solution + /home/src/workspaces/solution/projects /home/src/workspaces/solution/projects/server /home/src/workspaces/solution/projects/server/src (recursive) /home/src/workspaces/solution/projects/shared + /home/src/workspaces/solution/projects/shared/dist /home/src/workspaces/solution/projects/shared/dist/src /home/src/workspaces/solution/projects/shared/src (recursive) @@ -636,9 +640,11 @@ Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /home/src/workspaces/solution + /home/src/workspaces/solution/projects /home/src/workspaces/solution/projects/server /home/src/workspaces/solution/projects/server/src (recursive) /home/src/workspaces/solution/projects/shared + /home/src/workspaces/solution/projects/shared/dist /home/src/workspaces/solution/projects/shared/dist/src /home/src/workspaces/solution/projects/shared/src (recursive) projects/shared/tsconfig.json:: @@ -663,9 +669,11 @@ Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /home/src/workspaces/solution + /home/src/workspaces/solution/projects /home/src/workspaces/solution/projects/server /home/src/workspaces/solution/projects/server/src (recursive) /home/src/workspaces/solution/projects/shared + /home/src/workspaces/solution/projects/shared/dist /home/src/workspaces/solution/projects/shared/dist/src /home/src/workspaces/solution/projects/shared/src (recursive) @@ -879,9 +887,11 @@ Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /home/src/workspaces/solution + /home/src/workspaces/solution/projects /home/src/workspaces/solution/projects/server /home/src/workspaces/solution/projects/server/src (recursive) /home/src/workspaces/solution/projects/shared + /home/src/workspaces/solution/projects/shared/dist /home/src/workspaces/solution/projects/shared/dist/src /home/src/workspaces/solution/projects/shared/src (recursive) projects/shared/tsconfig.json:: @@ -902,8 +912,10 @@ Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib /home/src/workspaces/solution + /home/src/workspaces/solution/projects /home/src/workspaces/solution/projects/server /home/src/workspaces/solution/projects/server/src (recursive) /home/src/workspaces/solution/projects/shared + /home/src/workspaces/solution/projects/shared/dist /home/src/workspaces/solution/projects/shared/dist/src /home/src/workspaces/solution/projects/shared/src (recursive) diff --git a/testdata/baselines/reference/tsbuildWatch/sample/builds-when-new-file-is-added,-and-its-subsequent-updates-with-circular-references.js b/testdata/baselines/reference/tsbuildWatch/sample/builds-when-new-file-is-added,-and-its-subsequent-updates-with-circular-references.js index d29f94e7e7d..d20a1fba7dc 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/builds-when-new-file-is-added,-and-its-subsequent-updates-with-circular-references.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/builds-when-new-file-is-added,-and-its-subsequent-updates-with-circular-references.js @@ -385,6 +385,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -532,6 +533,7 @@ export const newFileConst = 30; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -667,6 +669,7 @@ export class someClass2 { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests diff --git a/testdata/baselines/reference/tsbuildWatch/sample/builds-when-new-file-is-added,-and-its-subsequent-updates.js b/testdata/baselines/reference/tsbuildWatch/sample/builds-when-new-file-is-added,-and-its-subsequent-updates.js index 81ae9ea03f1..5e4b1500ca6 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/builds-when-new-file-is-added,-and-its-subsequent-updates.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/builds-when-new-file-is-added,-and-its-subsequent-updates.js @@ -390,6 +390,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -541,6 +542,7 @@ export const newFileConst = 30; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -680,6 +682,7 @@ export class someClass2 { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests diff --git a/testdata/baselines/reference/tsbuildWatch/sample/change-builds-changes-and-reports-found-errors-message-with-circular-references.js b/testdata/baselines/reference/tsbuildWatch/sample/change-builds-changes-and-reports-found-errors-message-with-circular-references.js index 9f9d297cb38..8d2fe27879a 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/change-builds-changes-and-reports-found-errors-message-with-circular-references.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/change-builds-changes-and-reports-found-errors-message-with-circular-references.js @@ -385,6 +385,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -699,6 +700,7 @@ export class someClass { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -1001,6 +1003,7 @@ export function multiply(a, b) { return a * b; } Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -1313,6 +1316,7 @@ export class someClass2 { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests diff --git a/testdata/baselines/reference/tsbuildWatch/sample/change-builds-changes-and-reports-found-errors-message.js b/testdata/baselines/reference/tsbuildWatch/sample/change-builds-changes-and-reports-found-errors-message.js index bc14d3d9ffb..a007c1410e2 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/change-builds-changes-and-reports-found-errors-message.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/change-builds-changes-and-reports-found-errors-message.js @@ -390,6 +390,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -708,6 +709,7 @@ export class someClass { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -1014,6 +1016,7 @@ export function multiply(a, b) { return a * b; } Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -1330,6 +1333,7 @@ export class someClass2 { Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests diff --git a/testdata/baselines/reference/tsbuildWatch/sample/incremental-updates-in-verbose-mode.js b/testdata/baselines/reference/tsbuildWatch/sample/incremental-updates-in-verbose-mode.js index 7a30f75d5fe..e7d2208aca5 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/incremental-updates-in-verbose-mode.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/incremental-updates-in-verbose-mode.js @@ -407,6 +407,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -562,6 +563,7 @@ function someFn() { } Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -791,6 +793,7 @@ export function someFn() { } Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests diff --git a/testdata/baselines/reference/tsbuildWatch/sample/non-local-change-does-not-start-build-of-referencing-projects-with-circular-references.js b/testdata/baselines/reference/tsbuildWatch/sample/non-local-change-does-not-start-build-of-referencing-projects-with-circular-references.js index 5e98547c541..f1a06398b21 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/non-local-change-does-not-start-build-of-referencing-projects-with-circular-references.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/non-local-change-does-not-start-build-of-referencing-projects-with-circular-references.js @@ -385,6 +385,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -522,6 +523,7 @@ function foo() { } Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests diff --git a/testdata/baselines/reference/tsbuildWatch/sample/non-local-change-does-not-start-build-of-referencing-projects.js b/testdata/baselines/reference/tsbuildWatch/sample/non-local-change-does-not-start-build-of-referencing-projects.js index dfc20a258f3..3c74020ed97 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/non-local-change-does-not-start-build-of-referencing-projects.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/non-local-change-does-not-start-build-of-referencing-projects.js @@ -390,6 +390,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -530,6 +531,7 @@ function foo() { } Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests diff --git a/testdata/baselines/reference/tsbuildWatch/sample/reportErrors-when-preserveWatchOutput-is-not-used.js b/testdata/baselines/reference/tsbuildWatch/sample/reportErrors-when-preserveWatchOutput-is-not-used.js index 2ce1a4975be..7676772a46e 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/reportErrors-when-preserveWatchOutput-is-not-used.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/reportErrors-when-preserveWatchOutput-is-not-used.js @@ -390,6 +390,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -555,6 +556,7 @@ let y = 10; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -700,6 +702,7 @@ let x = 10; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -826,6 +829,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests diff --git a/testdata/baselines/reference/tsbuildWatch/sample/reportErrors-when-preserveWatchOutput-is-passed-on-command-line.js b/testdata/baselines/reference/tsbuildWatch/sample/reportErrors-when-preserveWatchOutput-is-passed-on-command-line.js index 3344a761254..f6ffd01c57f 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/reportErrors-when-preserveWatchOutput-is-passed-on-command-line.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/reportErrors-when-preserveWatchOutput-is-passed-on-command-line.js @@ -390,6 +390,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -555,6 +556,7 @@ let y = 10; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -700,6 +702,7 @@ let x = 10; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -826,6 +829,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests diff --git a/testdata/baselines/reference/tsbuildWatch/sample/reportErrors-when-stopBuildOnErrors-is-passed-on-command-line.js b/testdata/baselines/reference/tsbuildWatch/sample/reportErrors-when-stopBuildOnErrors-is-passed-on-command-line.js index 9aa5cf34566..cf6dbab45da 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/reportErrors-when-stopBuildOnErrors-is-passed-on-command-line.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/reportErrors-when-stopBuildOnErrors-is-passed-on-command-line.js @@ -390,6 +390,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -554,6 +555,7 @@ let y = 10; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -697,6 +699,7 @@ let x = 10; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -745,6 +748,7 @@ Output:: Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests diff --git a/testdata/baselines/reference/tsbuildWatch/sample/should-not-trigger-recompilation-because-of-program-emit-with-outDir-specified.js b/testdata/baselines/reference/tsbuildWatch/sample/should-not-trigger-recompilation-because-of-program-emit-with-outDir-specified.js index 29e1548ecd4..e6b14ad1239 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/should-not-trigger-recompilation-because-of-program-emit-with-outDir-specified.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/should-not-trigger-recompilation-because-of-program-emit-with-outDir-specified.js @@ -194,6 +194,7 @@ export function multiply(a, b) { return a * b; } Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) core/tsconfig.json:: SemanticDiagnostics:: @@ -214,6 +215,7 @@ Output:: Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) @@ -336,6 +338,7 @@ export const y = 10; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) core/tsconfig.json:: SemanticDiagnostics:: @@ -352,4 +355,5 @@ Output:: Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) diff --git a/testdata/baselines/reference/tsbuildWatch/sample/should-not-trigger-recompilation-because-of-program-emit.js b/testdata/baselines/reference/tsbuildWatch/sample/should-not-trigger-recompilation-because-of-program-emit.js index 210ff58f461..4f838a36eab 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/should-not-trigger-recompilation-because-of-program-emit.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/should-not-trigger-recompilation-because-of-program-emit.js @@ -202,6 +202,7 @@ export function multiply(a, b) { return a * b; } Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) core/tsconfig.json:: SemanticDiagnostics:: @@ -222,6 +223,7 @@ Output:: Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) @@ -348,6 +350,7 @@ export const y = 10; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) core/tsconfig.json:: SemanticDiagnostics:: @@ -364,4 +367,5 @@ Output:: Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) diff --git a/testdata/baselines/reference/tsbuildWatch/sample/skips-builds-downstream-projects-if-upstream-projects-have-errors-with-stopBuildOnErrors-when-test-does-not-reference-core.js b/testdata/baselines/reference/tsbuildWatch/sample/skips-builds-downstream-projects-if-upstream-projects-have-errors-with-stopBuildOnErrors-when-test-does-not-reference-core.js index 185618cabcf..e428153fc53 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/skips-builds-downstream-projects-if-upstream-projects-have-errors-with-stopBuildOnErrors-when-test-does-not-reference-core.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/skips-builds-downstream-projects-if-upstream-projects-have-errors-with-stopBuildOnErrors-when-test-does-not-reference-core.js @@ -251,6 +251,7 @@ multiply(); Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -580,6 +581,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests diff --git a/testdata/baselines/reference/tsbuildWatch/sample/skips-builds-downstream-projects-if-upstream-projects-have-errors-with-stopBuildOnErrors.js b/testdata/baselines/reference/tsbuildWatch/sample/skips-builds-downstream-projects-if-upstream-projects-have-errors-with-stopBuildOnErrors.js index e9053b92b1f..24ee4890e7a 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/skips-builds-downstream-projects-if-upstream-projects-have-errors-with-stopBuildOnErrors.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/skips-builds-downstream-projects-if-upstream-projects-have-errors-with-stopBuildOnErrors.js @@ -252,6 +252,7 @@ multiply(); Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests @@ -581,6 +582,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests diff --git a/testdata/baselines/reference/tsbuildWatch/sample/watches-config-files-that-are-not-present.js b/testdata/baselines/reference/tsbuildWatch/sample/watches-config-files-that-are-not-present.js index 512fce8dceb..f726961eaf7 100644 --- a/testdata/baselines/reference/tsbuildWatch/sample/watches-config-files-that-are-not-present.js +++ b/testdata/baselines/reference/tsbuildWatch/sample/watches-config-files-that-are-not-present.js @@ -320,6 +320,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic /user/username/projects/sample1/tests @@ -549,6 +550,7 @@ export const m = mod; Watch Registrations:: Directory watches:: /home/src/tslibs/TS/Lib + /user/username/projects/sample1 /user/username/projects/sample1/core (recursive) /user/username/projects/sample1/logic (recursive) /user/username/projects/sample1/tests diff --git a/testdata/baselines/reference/tsc/composite/synthetic-jsx-import-of-ESM-module-from-CJS-module-error-on-jsx-element.js b/testdata/baselines/reference/tsc/composite/synthetic-jsx-import-of-ESM-module-from-CJS-module-error-on-jsx-element.js index 86589353fd6..b84e72bc6cc 100644 --- a/testdata/baselines/reference/tsc/composite/synthetic-jsx-import-of-ESM-module-from-CJS-module-error-on-jsx-element.js +++ b/testdata/baselines/reference/tsc/composite/synthetic-jsx-import-of-ESM-module-from-CJS-module-error-on-jsx-element.js @@ -45,7 +45,7 @@ const jsx_runtime_1 = require("solid-js/jsx-runtime"); exports.default = (0, jsx_runtime_1.jsx)("div", {}); //// [/home/src/projects/project/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[3],"fileNames":["lib.es2025.full.d.ts","./node_modules/solid-js/jsx-runtime.d.ts","./src/main.tsx"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"00e459cbb1596f8c4bdf988b0589433f-export namespace JSX {\n type IntrinsicElements = { div: {}; };\n}","impliedNodeFormat":99},{"version":"5af15af7f9b4d97300f8dcfb2bf5b7c4-export default
;","signature":"ca37c00363f904fe93e299b145186400-declare const _default: any;\nexport default _default;\n","impliedNodeFormat":1}],"options":{"composite":true,"jsx":4,"jsxImportSource":"solid-js","module":100},"semanticDiagnosticsPerFile":[[3,[{"pos":15,"end":21,"code":1479,"category":1,"messageKey":"The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479","messageArgs":["solid-js/jsx-runtime"],"messageChain":[{"pos":15,"end":21,"code":1483,"category":3,"messageKey":"To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483","repopulateInfo":{"kind":1}}]}]]],"latestChangedDtsFile":"./src/main.d.ts"} +{"version":"FakeTSVersion","root":[3],"packageJsons":["./node_modules/solid-js/package.json"],"missingPackageJsons":["./node_modules/solid-js/jsx-runtime/package.json"],"fileNames":["lib.es2025.full.d.ts","./node_modules/solid-js/jsx-runtime.d.ts","./src/main.tsx"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"00e459cbb1596f8c4bdf988b0589433f-export namespace JSX {\n type IntrinsicElements = { div: {}; };\n}","impliedNodeFormat":99},{"version":"5af15af7f9b4d97300f8dcfb2bf5b7c4-export default
;","signature":"ca37c00363f904fe93e299b145186400-declare const _default: any;\nexport default _default;\n","impliedNodeFormat":1}],"options":{"composite":true,"jsx":4,"jsxImportSource":"solid-js","module":100},"semanticDiagnosticsPerFile":[[3,[{"pos":15,"end":21,"code":1479,"category":1,"messageKey":"The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479","messageArgs":["solid-js/jsx-runtime"],"messageChain":[{"pos":15,"end":21,"code":1483,"category":3,"messageKey":"To_convert_this_file_to_an_ECMAScript_module_create_a_local_package_json_file_with_type_Colon_module_1483","repopulateInfo":{"kind":1}}]}]]],"latestChangedDtsFile":"./src/main.d.ts"} //// [/home/src/projects/project/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -57,6 +57,12 @@ exports.default = (0, jsx_runtime_1.jsx)("div", {}); "original": 3 } ], + "packageJsons": [ + "./node_modules/solid-js/package.json" + ], + "missingPackageJsons": [ + "./node_modules/solid-js/jsx-runtime/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./node_modules/solid-js/jsx-runtime.d.ts", @@ -130,7 +136,7 @@ exports.default = (0, jsx_runtime_1.jsx)("div", {}); ] ], "latestChangedDtsFile": "./src/main.d.ts", - "size": 1828 + "size": 1959 } //// [/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts] *Lib* /// diff --git a/testdata/baselines/reference/tsc/declarationEmit/reports-dts-generation-errors-with-incremental.js b/testdata/baselines/reference/tsc/declarationEmit/reports-dts-generation-errors-with-incremental.js index 64cd03c85a7..86efd9affac 100644 --- a/testdata/baselines/reference/tsc/declarationEmit/reports-dts-generation-errors-with-incremental.js +++ b/testdata/baselines/reference/tsc/declarationEmit/reports-dts-generation-errors-with-incremental.js @@ -41,8 +41,8 @@ Output:: 2 export const api = ky.extend({});    ~~~ -TSFILE: /home/src/workspaces/project/index.js -TSFILE: /home/src/workspaces/project/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/project/index.js +TSFILE: /home/src/workspaces/project/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' node_modules/ky/distribution/index.d.ts @@ -82,7 +82,7 @@ import ky from 'ky'; export const api = ky.extend({}); //// [/home/src/workspaces/project/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[3],"fileNames":["lib.es2025.full.d.ts","./node_modules/ky/distribution/index.d.ts","./index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b9b50c37c18e43d94b0dd4fb43967f10-type KyInstance = {\n extend(options: Record): KyInstance;\n}\ndeclare const ky: KyInstance;\nexport default ky;","impliedNodeFormat":99},{"version":"0f5091e963c17913313e4969c59e6eb4-import ky from 'ky';\nexport const api = ky.extend({});","impliedNodeFormat":99}],"fileIdsList":[[2]],"options":{"composite":true,"declaration":true,"module":199,"skipLibCheck":true,"skipDefaultLibCheck":true},"referencedMap":[[3,1]],"emitDiagnosticsPerFile":[[3,[{"pos":34,"end":37,"code":4023,"category":1,"messageKey":"Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023","messageArgs":["api","KyInstance","\"/home/src/workspaces/project/node_modules/ky/distribution/index\""]}]]],"emitSignatures":[3]} +{"version":"FakeTSVersion","root":[3],"packageJsons":["./node_modules/ky/package.json","./package.json"],"missingPackageJsons":["./node_modules/ky/distribution/package.json"],"fileNames":["lib.es2025.full.d.ts","./node_modules/ky/distribution/index.d.ts","./index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"b9b50c37c18e43d94b0dd4fb43967f10-type KyInstance = {\n extend(options: Record): KyInstance;\n}\ndeclare const ky: KyInstance;\nexport default ky;","impliedNodeFormat":99},{"version":"0f5091e963c17913313e4969c59e6eb4-import ky from 'ky';\nexport const api = ky.extend({});","impliedNodeFormat":99}],"fileIdsList":[[2]],"options":{"composite":true,"declaration":true,"module":199,"skipLibCheck":true,"skipDefaultLibCheck":true},"referencedMap":[[3,1]],"emitDiagnosticsPerFile":[[3,[{"pos":34,"end":37,"code":4023,"category":1,"messageKey":"Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023","messageArgs":["api","KyInstance","\"/home/src/workspaces/project/node_modules/ky/distribution/index\""]}]]],"emitSignatures":[3]} //// [/home/src/workspaces/project/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -94,6 +94,13 @@ export const api = ky.extend({}); "original": 3 } ], + "packageJsons": [ + "./node_modules/ky/package.json", + "./package.json" + ], + "missingPackageJsons": [ + "./node_modules/ky/distribution/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./node_modules/ky/distribution/index.d.ts", @@ -175,7 +182,7 @@ export const api = ky.extend({}); "original": 3 } ], - "size": 1706 + "size": 1843 } tsconfig.json:: diff --git a/testdata/baselines/reference/tsc/declarationEmit/reports-dts-generation-errors.js b/testdata/baselines/reference/tsc/declarationEmit/reports-dts-generation-errors.js index d0cee971284..295f2b2882c 100644 --- a/testdata/baselines/reference/tsc/declarationEmit/reports-dts-generation-errors.js +++ b/testdata/baselines/reference/tsc/declarationEmit/reports-dts-generation-errors.js @@ -41,7 +41,7 @@ Output:: 2 export const api = ky.extend({});    ~~~ -TSFILE: /home/src/workspaces/project/index.js +TSFILE: /home/src/workspaces/project/index.js ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' node_modules/ky/distribution/index.d.ts @@ -93,7 +93,7 @@ Output:: 2 export const api = ky.extend({});    ~~~ -TSFILE: /home/src/workspaces/project/index.js +TSFILE: /home/src/workspaces/project/index.js ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' node_modules/ky/distribution/index.d.ts @@ -126,8 +126,8 @@ Output:: 2 export const api = ky.extend({});    ~~~ -TSFILE: /home/src/workspaces/project/index.js -TSFILE: /home/src/workspaces/project/tsconfig.tsbuildinfo +TSFILE: /home/src/workspaces/project/index.js +TSFILE: /home/src/workspaces/project/tsconfig.tsbuildinfo ../../tslibs/TS/Lib/lib.es2025.full.d.ts Default library for target 'ES2025' node_modules/ky/distribution/index.d.ts @@ -143,7 +143,7 @@ Found 1 error in index.ts:2 //// [/home/src/workspaces/project/index.js] *rewrite with same content* //// [/home/src/workspaces/project/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","errors":true,"root":["./index.ts"]} +{"version":"FakeTSVersion","errors":true,"root":["./index.ts"],"packageJsons":["./node_modules/ky/package.json","./package.json"],"missingPackageJsons":["./node_modules/ky/distribution/package.json"]} //// [/home/src/workspaces/project/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -156,7 +156,14 @@ Found 1 error in index.ts:2 "original": "./index.ts" } ], - "size": 63 + "packageJsons": [ + "./node_modules/ky/package.json", + "./package.json" + ], + "missingPackageJsons": [ + "./node_modules/ky/distribution/package.json" + ], + "size": 200 } tsconfig.json:: diff --git a/testdata/baselines/reference/tsc/incremental/Compile-incremental-with-case-insensitive-file-names.js b/testdata/baselines/reference/tsc/incremental/Compile-incremental-with-case-insensitive-file-names.js index 1fda1b06b7a..3d384abf361 100644 --- a/testdata/baselines/reference/tsc/incremental/Compile-incremental-with-case-insensitive-file-names.js +++ b/testdata/baselines/reference/tsc/incremental/Compile-incremental-with-case-insensitive-file-names.js @@ -64,7 +64,7 @@ export const foo1 = { foo: "a" }; export const foo2 = { foo: "b" }; //// [/home/project/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","errors":true,"root":[6],"fileNames":["lib.es2025.full.d.ts","../node_modules/otherlib/index.d.ts","../node_modules/somelib/index.d.ts","../node_modules/lib1/index.d.ts","../node_modules/lib2/index.d.ts","./src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"1fe659ed0634bb57b6dc25e9062f1162-export type Str = string;","12e112ff6e2744bb42d8e0b511e44117-import type { Str } from 'otherLib';\nexport type Foo = { foo: Str; };","b6305455d920a6729c435e6acf45eff6-import type { Foo } from 'someLib';\nexport type { Foo as Foo1 };","a5393e550a9c20a242a120bf6410db48-import type { Foo } from 'somelib';\nexport type { Foo as Foo2 };\nexport declare const foo2: Foo;","42aef197ff5f079223e2c29fb2e77cc5-import type { Foo1 } from 'lib1';\nimport type { Foo2 } from 'lib2';\nexport const foo1: Foo1 = { foo: \"a\" };\nexport const foo2: Foo2 = { foo: \"b\" };"],"fileIdsList":[[3],[2],[4,5]],"referencedMap":[[4,1],[5,1],[3,2],[6,3]]} +{"version":"FakeTSVersion","errors":true,"root":[6],"packageJsons":["../node_modules/lib1/package.json","../node_modules/lib2/package.json","../node_modules/otherLib/package.json","../node_modules/someLib/package.json"],"fileNames":["lib.es2025.full.d.ts","../node_modules/otherlib/index.d.ts","../node_modules/somelib/index.d.ts","../node_modules/lib1/index.d.ts","../node_modules/lib2/index.d.ts","./src/index.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"1fe659ed0634bb57b6dc25e9062f1162-export type Str = string;","12e112ff6e2744bb42d8e0b511e44117-import type { Str } from 'otherLib';\nexport type Foo = { foo: Str; };","b6305455d920a6729c435e6acf45eff6-import type { Foo } from 'someLib';\nexport type { Foo as Foo1 };","a5393e550a9c20a242a120bf6410db48-import type { Foo } from 'somelib';\nexport type { Foo as Foo2 };\nexport declare const foo2: Foo;","42aef197ff5f079223e2c29fb2e77cc5-import type { Foo1 } from 'lib1';\nimport type { Foo2 } from 'lib2';\nexport const foo1: Foo1 = { foo: \"a\" };\nexport const foo2: Foo2 = { foo: \"b\" };"],"fileIdsList":[[3],[2],[4,5]],"referencedMap":[[4,1],[5,1],[3,2],[6,3]]} //// [/home/project/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -77,6 +77,12 @@ export const foo2 = { foo: "b" }; "original": 6 } ], + "packageJsons": [ + "../node_modules/lib1/package.json", + "../node_modules/lib2/package.json", + "../node_modules/otherLib/package.json", + "../node_modules/someLib/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "../node_modules/otherlib/index.d.ts", @@ -156,7 +162,7 @@ export const foo2 = { foo: "b" }; "../node_modules/lib2/index.d.ts" ] }, - "size": 1697 + "size": 1865 } //// [/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts] *Lib* /// diff --git a/testdata/baselines/reference/tsc/incremental/react-jsx-emit-mode-with-no-backing-types-found-doesnt-crash-under---strict.js b/testdata/baselines/reference/tsc/incremental/react-jsx-emit-mode-with-no-backing-types-found-doesnt-crash-under---strict.js index a9fd5c534bb..a4ee0e76dcb 100644 --- a/testdata/baselines/reference/tsc/incremental/react-jsx-emit-mode-with-no-backing-types-found-doesnt-crash-under---strict.js +++ b/testdata/baselines/reference/tsc/incremental/react-jsx-emit-mode-with-no-backing-types-found-doesnt-crash-under---strict.js @@ -80,7 +80,7 @@ const App = () => (0, jsx_runtime_1.jsx)("div", { propA: true }); exports.App = App; //// [/home/src/workspaces/project/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[2],"fileNames":["lib.es2025.full.d.ts","./src/index.tsx"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"0c3575e38f9aabc971cea9c73a211979-export const App = () =>
;"],"options":{"jsx":4,"jsxImportSource":"react","module":1,"strict":true},"semanticDiagnosticsPerFile":[[2,[{"pos":25,"end":43,"code":7026,"category":1,"messageKey":"JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026","messageArgs":["IntrinsicElements"]},{"pos":25,"end":49,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["react/jsx-runtime","/home/src/workspaces/project/node_modules/react/jsx-runtime.js"]},{"pos":43,"end":49,"code":7026,"category":1,"messageKey":"JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026","messageArgs":["IntrinsicElements"]}]]]} +{"version":"FakeTSVersion","root":[2],"missingPackageJsons":["./node_modules/@types/react/jsx-runtime/package.json","./node_modules/@types/react/package.json","./node_modules/react/jsx-runtime/package.json","./node_modules/react/package.json"],"fileNames":["lib.es2025.full.d.ts","./src/index.tsx"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"0c3575e38f9aabc971cea9c73a211979-export const App = () =>
;"],"options":{"jsx":4,"jsxImportSource":"react","module":1,"strict":true},"semanticDiagnosticsPerFile":[[2,[{"pos":25,"end":43,"code":7026,"category":1,"messageKey":"JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026","messageArgs":["IntrinsicElements"]},{"pos":25,"end":49,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["react/jsx-runtime","/home/src/workspaces/project/node_modules/react/jsx-runtime.js"]},{"pos":43,"end":49,"code":7026,"category":1,"messageKey":"JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026","messageArgs":["IntrinsicElements"]}]]]} //// [/home/src/workspaces/project/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -92,6 +92,12 @@ exports.App = App; "original": 2 } ], + "missingPackageJsons": [ + "./node_modules/@types/react/jsx-runtime/package.json", + "./node_modules/@types/react/package.json", + "./node_modules/react/jsx-runtime/package.json", + "./node_modules/react/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./src/index.tsx" @@ -160,7 +166,7 @@ exports.App = App; ] ] ], - "size": 1655 + "size": 1861 } tsconfig.json:: diff --git a/testdata/baselines/reference/tsc/incremental/react-jsx-emit-mode-with-no-backing-types-found-doesnt-crash.js b/testdata/baselines/reference/tsc/incremental/react-jsx-emit-mode-with-no-backing-types-found-doesnt-crash.js index 801bc2f3fa9..f61140043a6 100644 --- a/testdata/baselines/reference/tsc/incremental/react-jsx-emit-mode-with-no-backing-types-found-doesnt-crash.js +++ b/testdata/baselines/reference/tsc/incremental/react-jsx-emit-mode-with-no-backing-types-found-doesnt-crash.js @@ -80,7 +80,7 @@ const App = () => (0, jsx_runtime_1.jsx)("div", { propA: true }); exports.App = App; //// [/home/src/workspaces/project/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[2],"fileNames":["lib.es2025.full.d.ts","./src/index.tsx"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"0c3575e38f9aabc971cea9c73a211979-export const App = () =>
;"],"options":{"jsx":4,"jsxImportSource":"react","module":1},"semanticDiagnosticsPerFile":[[2,[{"pos":25,"end":43,"code":7026,"category":1,"messageKey":"JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026","messageArgs":["IntrinsicElements"]},{"pos":25,"end":49,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["react/jsx-runtime","/home/src/workspaces/project/node_modules/react/jsx-runtime.js"]},{"pos":43,"end":49,"code":7026,"category":1,"messageKey":"JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026","messageArgs":["IntrinsicElements"]}]]]} +{"version":"FakeTSVersion","root":[2],"missingPackageJsons":["./node_modules/@types/react/jsx-runtime/package.json","./node_modules/@types/react/package.json","./node_modules/react/jsx-runtime/package.json","./node_modules/react/package.json"],"fileNames":["lib.es2025.full.d.ts","./src/index.tsx"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"0c3575e38f9aabc971cea9c73a211979-export const App = () =>
;"],"options":{"jsx":4,"jsxImportSource":"react","module":1},"semanticDiagnosticsPerFile":[[2,[{"pos":25,"end":43,"code":7026,"category":1,"messageKey":"JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026","messageArgs":["IntrinsicElements"]},{"pos":25,"end":49,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["react/jsx-runtime","/home/src/workspaces/project/node_modules/react/jsx-runtime.js"]},{"pos":43,"end":49,"code":7026,"category":1,"messageKey":"JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists_7026","messageArgs":["IntrinsicElements"]}]]]} //// [/home/src/workspaces/project/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -92,6 +92,12 @@ exports.App = App; "original": 2 } ], + "missingPackageJsons": [ + "./node_modules/@types/react/jsx-runtime/package.json", + "./node_modules/@types/react/package.json", + "./node_modules/react/jsx-runtime/package.json", + "./node_modules/react/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./src/index.tsx" @@ -159,7 +165,7 @@ exports.App = App; ] ] ], - "size": 1641 + "size": 1847 } tsconfig.json:: diff --git a/testdata/baselines/reference/tsc/libraryResolution/with-config-with-libReplacement.js b/testdata/baselines/reference/tsc/libraryResolution/with-config-with-libReplacement.js index b3fd77e558b..ab01382856a 100644 --- a/testdata/baselines/reference/tsc/libraryResolution/with-config-with-libReplacement.js +++ b/testdata/baselines/reference/tsc/libraryResolution/with-config-with-libReplacement.js @@ -254,7 +254,7 @@ export declare const x = "type1"; export const x = "type1"; //// [/home/src/workspace/projects/project1/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[5,10]],"fileNames":["../node_modules/@typescript/lib-webworker/index.d.ts","../node_modules/@typescript/lib-scripthost/index.d.ts","../node_modules/@typescript/lib-es5/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","./core.d.ts","./file.ts","./file2.ts","./index.ts","./utils.d.ts","./typeroot1/sometype/index.d.ts"],"fileInfos":[{"version":"95c5e18b7871b756fb3bb843e03aa05d-interface WebWorkerInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"2fa71959819338965a3c6b2122d95c96-interface ScriptHostInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},"a1f9b824326bab2c3c8f13eccf69f182-export const core = 10;",{"version":"69c4ea0c9ff13ab7fc078607d9363624-export const file = 10;","signature":"a224c1b0cbd2f5fe611e588db48243cb-export declare const file = 10;\n","impliedNodeFormat":1},{"version":"76f8c505d1aaf1122ce1da0807c21477-/// \n/// \n/// ","signature":"99aa06d3014798d86001c324468d497f-","impliedNodeFormat":1},{"version":"aeb695aed936d7539a32fc3cd25af558-export const x = \"type1\";","signature":"e2f8d12de2edba256e37cf4a656ac52d-export declare const x = \"type1\";\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;","6bf5e0a71dae6fccf68b93fbbb73f178-export type TheNum = \"type1\";"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} +{"version":"FakeTSVersion","root":[[5,10]],"missingPackageJsons":["../node_modules/@typescript/lib-dom/package.json","../node_modules/@typescript/lib-es5/package.json","../node_modules/@typescript/lib-scripthost/package.json","../node_modules/@typescript/lib-webworker/package.json"],"fileNames":["../node_modules/@typescript/lib-webworker/index.d.ts","../node_modules/@typescript/lib-scripthost/index.d.ts","../node_modules/@typescript/lib-es5/index.d.ts","../node_modules/@typescript/lib-dom/index.d.ts","./core.d.ts","./file.ts","./file2.ts","./index.ts","./utils.d.ts","./typeroot1/sometype/index.d.ts"],"fileInfos":[{"version":"95c5e18b7871b756fb3bb843e03aa05d-interface WebWorkerInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"2fa71959819338965a3c6b2122d95c96-interface ScriptHostInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"d9b7428535134fcb21dad91303dc6311-interface DOMInterface { }","affectsGlobalScope":true,"impliedNodeFormat":1},"a1f9b824326bab2c3c8f13eccf69f182-export const core = 10;",{"version":"69c4ea0c9ff13ab7fc078607d9363624-export const file = 10;","signature":"a224c1b0cbd2f5fe611e588db48243cb-export declare const file = 10;\n","impliedNodeFormat":1},{"version":"76f8c505d1aaf1122ce1da0807c21477-/// \n/// \n/// ","signature":"99aa06d3014798d86001c324468d497f-","impliedNodeFormat":1},{"version":"aeb695aed936d7539a32fc3cd25af558-export const x = \"type1\";","signature":"e2f8d12de2edba256e37cf4a656ac52d-export declare const x = \"type1\";\n","impliedNodeFormat":1},"4e905e76b648aae5f92e8bd5418e19b3-export const y = 10;","6bf5e0a71dae6fccf68b93fbbb73f178-export type TheNum = \"type1\";"],"options":{"composite":true},"latestChangedDtsFile":"./index.d.ts"} //// [/home/src/workspace/projects/project1/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -274,6 +274,12 @@ export const x = "type1"; ] } ], + "missingPackageJsons": [ + "../node_modules/@typescript/lib-dom/package.json", + "../node_modules/@typescript/lib-es5/package.json", + "../node_modules/@typescript/lib-scripthost/package.json", + "../node_modules/@typescript/lib-webworker/package.json" + ], "fileNames": [ "../node_modules/@typescript/lib-webworker/index.d.ts", "../node_modules/@typescript/lib-scripthost/index.d.ts", @@ -391,7 +397,7 @@ export const x = "type1"; "composite": true }, "latestChangedDtsFile": "./index.d.ts", - "size": 2354 + "size": 2595 } project1/tsconfig.json:: diff --git a/testdata/baselines/reference/tsc/moduleResolution/alternateResult.js b/testdata/baselines/reference/tsc/moduleResolution/alternateResult.js index 1db60aa454a..c872dd96b3c 100644 --- a/testdata/baselines/reference/tsc/moduleResolution/alternateResult.js +++ b/testdata/baselines/reference/tsc/moduleResolution/alternateResult.js @@ -319,7 +319,7 @@ Found 2 errors in the same file, starting at: index.mts:1 export {}; //// [/home/src/projects/project/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[4],"fileNames":["lib.es2025.full.d.ts","./node_modules/foo2/index.d.ts","./node_modules/@types/bar2/index.d.ts","./index.mts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"165b91a7791663df5931f0b63ebf9ce2-export declare const foo2: number;","da9728b78f5d24b38c00844e001b4953-export declare const bar2: number;",{"version":"eee0814e4a127747fb836acc50eaeb5a-import { foo } from \"foo\";\nimport { bar } from \"bar\";\nimport { foo2 } from \"foo2\";\nimport { bar2 } from \"bar2\";","impliedNodeFormat":99}],"fileIdsList":[[2,3]],"options":{"module":100,"strict":true},"referencedMap":[[4,1]],"semanticDiagnosticsPerFile":[[4,[{"pos":20,"end":25,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["foo","/home/src/projects/project/node_modules/foo/index.mjs"],"messageChain":[{"pos":20,"end":25,"code":6278,"category":3,"messageKey":"There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278","messageArgs":["/home/src/projects/project/node_modules/foo/index.d.ts","foo"],"repopulateInfo":{"kind":2,"moduleReference":"foo","mode":99}}]},{"pos":47,"end":52,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["bar","/home/src/projects/project/node_modules/bar/index.mjs"],"messageChain":[{"pos":47,"end":52,"code":6278,"category":3,"messageKey":"There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278","messageArgs":["/home/src/projects/project/node_modules/@types/bar/index.d.ts","@types/bar"],"repopulateInfo":{"kind":2,"moduleReference":"bar","mode":99}}]}]]]} +{"version":"FakeTSVersion","root":[4],"packageJsons":["./node_modules/@types/bar/package.json","./node_modules/@types/bar2/package.json","./node_modules/bar/package.json","./node_modules/bar2/package.json","./node_modules/foo/package.json","./node_modules/foo2/package.json"],"missingPackageJsons":["./node_modules/@types/foo/package.json"],"fileNames":["lib.es2025.full.d.ts","./node_modules/foo2/index.d.ts","./node_modules/@types/bar2/index.d.ts","./index.mts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"165b91a7791663df5931f0b63ebf9ce2-export declare const foo2: number;","da9728b78f5d24b38c00844e001b4953-export declare const bar2: number;",{"version":"eee0814e4a127747fb836acc50eaeb5a-import { foo } from \"foo\";\nimport { bar } from \"bar\";\nimport { foo2 } from \"foo2\";\nimport { bar2 } from \"bar2\";","impliedNodeFormat":99}],"fileIdsList":[[2,3]],"options":{"module":100,"strict":true},"referencedMap":[[4,1]],"semanticDiagnosticsPerFile":[[4,[{"pos":20,"end":25,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["foo","/home/src/projects/project/node_modules/foo/index.mjs"],"messageChain":[{"pos":20,"end":25,"code":6278,"category":3,"messageKey":"There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278","messageArgs":["/home/src/projects/project/node_modules/foo/index.d.ts","foo"],"repopulateInfo":{"kind":2,"moduleReference":"foo","mode":99}}]},{"pos":47,"end":52,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["bar","/home/src/projects/project/node_modules/bar/index.mjs"],"messageChain":[{"pos":47,"end":52,"code":6278,"category":3,"messageKey":"There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278","messageArgs":["/home/src/projects/project/node_modules/@types/bar/index.d.ts","@types/bar"],"repopulateInfo":{"kind":2,"moduleReference":"bar","mode":99}}]}]]]} //// [/home/src/projects/project/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -331,6 +331,17 @@ export {}; "original": 4 } ], + "packageJsons": [ + "./node_modules/@types/bar/package.json", + "./node_modules/@types/bar2/package.json", + "./node_modules/bar/package.json", + "./node_modules/bar2/package.json", + "./node_modules/foo/package.json", + "./node_modules/foo2/package.json" + ], + "missingPackageJsons": [ + "./node_modules/@types/foo/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./node_modules/foo2/index.d.ts", @@ -444,7 +455,7 @@ export {}; ] ] ], - "size": 2501 + "size": 2804 } //// [/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts] *Lib* /// @@ -1488,7 +1499,7 @@ Found 1 error in index.mts:1 //// [/home/src/projects/project/index.mjs] *rewrite with same content* //// [/home/src/projects/project/tsconfig.tsbuildinfo] *modified* -{"version":"FakeTSVersion","root":[5],"fileNames":["lib.es2025.full.d.ts","./node_modules/@types/bar/index.d.ts","./node_modules/foo2/index.d.ts","./node_modules/@types/bar2/index.d.ts","./index.mts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"78bc7ca8c840e090086811119f6d6ba9-export declare const bar: number;","165b91a7791663df5931f0b63ebf9ce2-export declare const foo2: number;","da9728b78f5d24b38c00844e001b4953-export declare const bar2: number;",{"version":"eee0814e4a127747fb836acc50eaeb5a-import { foo } from \"foo\";\nimport { bar } from \"bar\";\nimport { foo2 } from \"foo2\";\nimport { bar2 } from \"bar2\";","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":99}],"fileIdsList":[[2,3,4]],"options":{"module":100,"strict":true},"referencedMap":[[5,1]],"semanticDiagnosticsPerFile":[[5,[{"pos":20,"end":25,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["foo","/home/src/projects/project/node_modules/foo/index.mjs"],"messageChain":[{"pos":20,"end":25,"code":6278,"category":3,"messageKey":"There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278","messageArgs":["/home/src/projects/project/node_modules/foo/index.d.ts","foo"],"repopulateInfo":{"kind":2,"moduleReference":"foo","mode":99}}]}]]]} +{"version":"FakeTSVersion","root":[5],"packageJsons":["./node_modules/@types/bar/package.json","./node_modules/@types/bar2/package.json","./node_modules/bar/package.json","./node_modules/bar2/package.json","./node_modules/foo/package.json","./node_modules/foo2/package.json"],"missingPackageJsons":["./node_modules/@types/foo/package.json"],"fileNames":["lib.es2025.full.d.ts","./node_modules/@types/bar/index.d.ts","./node_modules/foo2/index.d.ts","./node_modules/@types/bar2/index.d.ts","./index.mts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"78bc7ca8c840e090086811119f6d6ba9-export declare const bar: number;","165b91a7791663df5931f0b63ebf9ce2-export declare const foo2: number;","da9728b78f5d24b38c00844e001b4953-export declare const bar2: number;",{"version":"eee0814e4a127747fb836acc50eaeb5a-import { foo } from \"foo\";\nimport { bar } from \"bar\";\nimport { foo2 } from \"foo2\";\nimport { bar2 } from \"bar2\";","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":99}],"fileIdsList":[[2,3,4]],"options":{"module":100,"strict":true},"referencedMap":[[5,1]],"semanticDiagnosticsPerFile":[[5,[{"pos":20,"end":25,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["foo","/home/src/projects/project/node_modules/foo/index.mjs"],"messageChain":[{"pos":20,"end":25,"code":6278,"category":3,"messageKey":"There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278","messageArgs":["/home/src/projects/project/node_modules/foo/index.d.ts","foo"],"repopulateInfo":{"kind":2,"moduleReference":"foo","mode":99}}]}]]]} //// [/home/src/projects/project/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* { "version": "FakeTSVersion", @@ -1500,6 +1511,17 @@ Found 1 error in index.mts:1 "original": 5 } ], + "packageJsons": [ + "./node_modules/@types/bar/package.json", + "./node_modules/@types/bar2/package.json", + "./node_modules/bar/package.json", + "./node_modules/bar2/package.json", + "./node_modules/foo/package.json", + "./node_modules/foo2/package.json" + ], + "missingPackageJsons": [ + "./node_modules/@types/foo/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./node_modules/@types/bar/index.d.ts", @@ -1599,7 +1621,7 @@ Found 1 error in index.mts:1 ] ] ], - "size": 2114 + "size": 2417 } tsconfig.json:: @@ -1732,7 +1754,7 @@ Resolving real path for '/home/src/projects/project/node_modules/@types/bar2/ind ======== Module name 'bar2' was successfully resolved to '/home/src/projects/project/node_modules/@types/bar2/index.d.ts' with Package ID '@types/bar2/index.d.ts@1.0.0'. ======== //// [/home/src/projects/project/index.mjs] *rewrite with same content* //// [/home/src/projects/project/tsconfig.tsbuildinfo] *modified* -{"version":"FakeTSVersion","root":[6],"fileNames":["lib.es2025.full.d.ts","./node_modules/foo/index.d.ts","./node_modules/@types/bar/index.d.ts","./node_modules/foo2/index.d.ts","./node_modules/@types/bar2/index.d.ts","./index.mts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"2a914bfad3bba77712486af8a4cdc415-export declare const foo: number;","78bc7ca8c840e090086811119f6d6ba9-export declare const bar: number;","165b91a7791663df5931f0b63ebf9ce2-export declare const foo2: number;","da9728b78f5d24b38c00844e001b4953-export declare const bar2: number;",{"version":"eee0814e4a127747fb836acc50eaeb5a-import { foo } from \"foo\";\nimport { bar } from \"bar\";\nimport { foo2 } from \"foo2\";\nimport { bar2 } from \"bar2\";","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":99}],"fileIdsList":[[2,3,4,5]],"options":{"module":100,"strict":true},"referencedMap":[[6,1]]} +{"version":"FakeTSVersion","root":[6],"packageJsons":["./node_modules/@types/bar/package.json","./node_modules/@types/bar2/package.json","./node_modules/bar/package.json","./node_modules/bar2/package.json","./node_modules/foo/package.json","./node_modules/foo2/package.json"],"fileNames":["lib.es2025.full.d.ts","./node_modules/foo/index.d.ts","./node_modules/@types/bar/index.d.ts","./node_modules/foo2/index.d.ts","./node_modules/@types/bar2/index.d.ts","./index.mts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"2a914bfad3bba77712486af8a4cdc415-export declare const foo: number;","78bc7ca8c840e090086811119f6d6ba9-export declare const bar: number;","165b91a7791663df5931f0b63ebf9ce2-export declare const foo2: number;","da9728b78f5d24b38c00844e001b4953-export declare const bar2: number;",{"version":"eee0814e4a127747fb836acc50eaeb5a-import { foo } from \"foo\";\nimport { bar } from \"bar\";\nimport { foo2 } from \"foo2\";\nimport { bar2 } from \"bar2\";","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":99}],"fileIdsList":[[2,3,4,5]],"options":{"module":100,"strict":true},"referencedMap":[[6,1]]} //// [/home/src/projects/project/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* { "version": "FakeTSVersion", @@ -1744,6 +1766,14 @@ Resolving real path for '/home/src/projects/project/node_modules/@types/bar2/ind "original": 6 } ], + "packageJsons": [ + "./node_modules/@types/bar/package.json", + "./node_modules/@types/bar2/package.json", + "./node_modules/bar/package.json", + "./node_modules/bar2/package.json", + "./node_modules/foo/package.json", + "./node_modules/foo2/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./node_modules/foo/index.d.ts", @@ -1821,7 +1851,7 @@ Resolving real path for '/home/src/projects/project/node_modules/@types/bar2/ind "./node_modules/@types/bar2/index.d.ts" ] }, - "size": 1637 + "size": 1875 } tsconfig.json:: @@ -2004,7 +2034,7 @@ Found 1 error in index.mts:4 //// [/home/src/projects/project/index.mjs] *rewrite with same content* //// [/home/src/projects/project/tsconfig.tsbuildinfo] *modified* -{"version":"FakeTSVersion","root":[5],"fileNames":["lib.es2025.full.d.ts","./node_modules/foo/index.d.ts","./node_modules/@types/bar/index.d.ts","./node_modules/foo2/index.d.ts","./index.mts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"2a914bfad3bba77712486af8a4cdc415-export declare const foo: number;","78bc7ca8c840e090086811119f6d6ba9-export declare const bar: number;","165b91a7791663df5931f0b63ebf9ce2-export declare const foo2: number;",{"version":"eee0814e4a127747fb836acc50eaeb5a-import { foo } from \"foo\";\nimport { bar } from \"bar\";\nimport { foo2 } from \"foo2\";\nimport { bar2 } from \"bar2\";","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":99}],"fileIdsList":[[2,3,4]],"options":{"module":100,"strict":true},"referencedMap":[[5,1]],"semanticDiagnosticsPerFile":[[5,[{"pos":104,"end":110,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["bar2","/home/src/projects/project/node_modules/bar2/index.mjs"],"messageChain":[{"pos":104,"end":110,"code":6278,"category":3,"messageKey":"There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278","messageArgs":["/home/src/projects/project/node_modules/@types/bar2/index.d.ts","@types/bar2"],"repopulateInfo":{"kind":2,"moduleReference":"bar2","mode":99}}]}]]]} +{"version":"FakeTSVersion","root":[5],"packageJsons":["./node_modules/@types/bar/package.json","./node_modules/@types/bar2/package.json","./node_modules/bar/package.json","./node_modules/bar2/package.json","./node_modules/foo/package.json","./node_modules/foo2/package.json"],"fileNames":["lib.es2025.full.d.ts","./node_modules/foo/index.d.ts","./node_modules/@types/bar/index.d.ts","./node_modules/foo2/index.d.ts","./index.mts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"2a914bfad3bba77712486af8a4cdc415-export declare const foo: number;","78bc7ca8c840e090086811119f6d6ba9-export declare const bar: number;","165b91a7791663df5931f0b63ebf9ce2-export declare const foo2: number;",{"version":"eee0814e4a127747fb836acc50eaeb5a-import { foo } from \"foo\";\nimport { bar } from \"bar\";\nimport { foo2 } from \"foo2\";\nimport { bar2 } from \"bar2\";","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":99}],"fileIdsList":[[2,3,4]],"options":{"module":100,"strict":true},"referencedMap":[[5,1]],"semanticDiagnosticsPerFile":[[5,[{"pos":104,"end":110,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["bar2","/home/src/projects/project/node_modules/bar2/index.mjs"],"messageChain":[{"pos":104,"end":110,"code":6278,"category":3,"messageKey":"There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278","messageArgs":["/home/src/projects/project/node_modules/@types/bar2/index.d.ts","@types/bar2"],"repopulateInfo":{"kind":2,"moduleReference":"bar2","mode":99}}]}]]]} //// [/home/src/projects/project/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* { "version": "FakeTSVersion", @@ -2016,6 +2046,14 @@ Found 1 error in index.mts:4 "original": 5 } ], + "packageJsons": [ + "./node_modules/@types/bar/package.json", + "./node_modules/@types/bar2/package.json", + "./node_modules/bar/package.json", + "./node_modules/bar2/package.json", + "./node_modules/foo/package.json", + "./node_modules/foo2/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./node_modules/foo/index.d.ts", @@ -2115,7 +2153,7 @@ Found 1 error in index.mts:4 ] ] ], - "size": 2128 + "size": 2366 } tsconfig.json:: @@ -2335,7 +2373,7 @@ Found 2 errors in the same file, starting at: index.mts:3 //// [/home/src/projects/project/index.mjs] *rewrite with same content* //// [/home/src/projects/project/tsconfig.tsbuildinfo] *modified* -{"version":"FakeTSVersion","root":[4],"fileNames":["lib.es2025.full.d.ts","./node_modules/foo/index.d.ts","./node_modules/@types/bar/index.d.ts","./index.mts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"2a914bfad3bba77712486af8a4cdc415-export declare const foo: number;","78bc7ca8c840e090086811119f6d6ba9-export declare const bar: number;",{"version":"eee0814e4a127747fb836acc50eaeb5a-import { foo } from \"foo\";\nimport { bar } from \"bar\";\nimport { foo2 } from \"foo2\";\nimport { bar2 } from \"bar2\";","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":99}],"fileIdsList":[[2,3]],"options":{"module":100,"strict":true},"referencedMap":[[4,1]],"semanticDiagnosticsPerFile":[[4,[{"pos":75,"end":81,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["foo2","/home/src/projects/project/node_modules/foo2/index.mjs"],"messageChain":[{"pos":75,"end":81,"code":6278,"category":3,"messageKey":"There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278","messageArgs":["/home/src/projects/project/node_modules/foo2/index.d.ts","foo2"],"repopulateInfo":{"kind":2,"moduleReference":"foo2","mode":99}}]},{"pos":104,"end":110,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["bar2","/home/src/projects/project/node_modules/bar2/index.mjs"],"messageChain":[{"pos":104,"end":110,"code":6278,"category":3,"messageKey":"There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278","messageArgs":["/home/src/projects/project/node_modules/@types/bar2/index.d.ts","@types/bar2"],"repopulateInfo":{"kind":2,"moduleReference":"bar2","mode":99}}]}]]]} +{"version":"FakeTSVersion","root":[4],"packageJsons":["./node_modules/@types/bar/package.json","./node_modules/@types/bar2/package.json","./node_modules/bar/package.json","./node_modules/bar2/package.json","./node_modules/foo/package.json","./node_modules/foo2/package.json"],"missingPackageJsons":["./node_modules/@types/foo2/package.json"],"fileNames":["lib.es2025.full.d.ts","./node_modules/foo/index.d.ts","./node_modules/@types/bar/index.d.ts","./index.mts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},"2a914bfad3bba77712486af8a4cdc415-export declare const foo: number;","78bc7ca8c840e090086811119f6d6ba9-export declare const bar: number;",{"version":"eee0814e4a127747fb836acc50eaeb5a-import { foo } from \"foo\";\nimport { bar } from \"bar\";\nimport { foo2 } from \"foo2\";\nimport { bar2 } from \"bar2\";","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":99}],"fileIdsList":[[2,3]],"options":{"module":100,"strict":true},"referencedMap":[[4,1]],"semanticDiagnosticsPerFile":[[4,[{"pos":75,"end":81,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["foo2","/home/src/projects/project/node_modules/foo2/index.mjs"],"messageChain":[{"pos":75,"end":81,"code":6278,"category":3,"messageKey":"There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278","messageArgs":["/home/src/projects/project/node_modules/foo2/index.d.ts","foo2"],"repopulateInfo":{"kind":2,"moduleReference":"foo2","mode":99}}]},{"pos":104,"end":110,"code":7016,"category":1,"messageKey":"Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016","messageArgs":["bar2","/home/src/projects/project/node_modules/bar2/index.mjs"],"messageChain":[{"pos":104,"end":110,"code":6278,"category":3,"messageKey":"There_are_types_at_0_but_this_result_could_not_be_resolved_when_respecting_package_json_exports_The__6278","messageArgs":["/home/src/projects/project/node_modules/@types/bar2/index.d.ts","@types/bar2"],"repopulateInfo":{"kind":2,"moduleReference":"bar2","mode":99}}]}]]]} //// [/home/src/projects/project/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* { "version": "FakeTSVersion", @@ -2347,6 +2385,17 @@ Found 2 errors in the same file, starting at: index.mts:3 "original": 4 } ], + "packageJsons": [ + "./node_modules/@types/bar/package.json", + "./node_modules/@types/bar2/package.json", + "./node_modules/bar/package.json", + "./node_modules/bar2/package.json", + "./node_modules/foo/package.json", + "./node_modules/foo2/package.json" + ], + "missingPackageJsons": [ + "./node_modules/@types/foo2/package.json" + ], "fileNames": [ "lib.es2025.full.d.ts", "./node_modules/foo/index.d.ts", @@ -2461,7 +2510,7 @@ Found 2 errors in the same file, starting at: index.mts:3 ] ] ], - "size": 2571 + "size": 2875 } tsconfig.json:: diff --git a/testdata/baselines/reference/tsc/moduleResolution/package-json-scope.js b/testdata/baselines/reference/tsc/moduleResolution/package-json-scope.js index ba139d71b6c..5f4cbf53ba7 100644 --- a/testdata/baselines/reference/tsc/moduleResolution/package-json-scope.js +++ b/testdata/baselines/reference/tsc/moduleResolution/package-json-scope.js @@ -106,7 +106,7 @@ exports.x = void 0; exports.x = 10; //// [/home/src/workspaces/project/src/tsconfig.tsbuildinfo] *new* -{"version":"FakeTSVersion","root":[[2,4]],"fileNames":["lib.es2016.full.d.ts","./main.ts","./fileB.mts","./fileA.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"28e8748a7acd58f4f59388926e914f86-export const x = 10;","signature":"f9b4154a9a5944099ecf197d4519d083-export declare const x = 10;\n","impliedNodeFormat":1},{"version":"d03690d860e74c03bcacf63f0dd68b93-export function foo() {}","signature":"7ffb4ea6089b1a385965a214ba412941-export declare function foo(): void;\n","impliedNodeFormat":99},{"version":"cc520ca096f0b81d18073ba8a9776fe3-import { foo } from \"./fileB.mjs\";\nfoo();","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":1}],"fileIdsList":[[3]],"options":{"composite":true,"module":100,"target":3},"referencedMap":[[4,1]],"semanticDiagnosticsPerFile":[[4,[{"pos":20,"end":33,"code":1479,"category":1,"messageKey":"The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479","messageArgs":["./fileB.mjs"],"messageChain":[{"pos":20,"end":33,"code":1481,"category":3,"messageKey":"To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481","messageArgs":[".mts","/home/src/workspaces/project/package.json"],"repopulateInfo":{"kind":1}}]}]]],"latestChangedDtsFile":"./fileA.d.ts"} +{"version":"FakeTSVersion","root":[[2,4]],"packageJsons":["../package.json"],"fileNames":["lib.es2016.full.d.ts","./main.ts","./fileB.mts","./fileA.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"28e8748a7acd58f4f59388926e914f86-export const x = 10;","signature":"f9b4154a9a5944099ecf197d4519d083-export declare const x = 10;\n","impliedNodeFormat":1},{"version":"d03690d860e74c03bcacf63f0dd68b93-export function foo() {}","signature":"7ffb4ea6089b1a385965a214ba412941-export declare function foo(): void;\n","impliedNodeFormat":99},{"version":"cc520ca096f0b81d18073ba8a9776fe3-import { foo } from \"./fileB.mjs\";\nfoo();","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":1}],"fileIdsList":[[3]],"options":{"composite":true,"module":100,"target":3},"referencedMap":[[4,1]],"semanticDiagnosticsPerFile":[[4,[{"pos":20,"end":33,"code":1479,"category":1,"messageKey":"The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479","messageArgs":["./fileB.mjs"],"messageChain":[{"pos":20,"end":33,"code":1481,"category":3,"messageKey":"To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_add_the_field_type_Co_1481","messageArgs":[".mts","/home/src/workspaces/project/package.json"],"repopulateInfo":{"kind":1}}]}]]],"latestChangedDtsFile":"./fileA.d.ts"} //// [/home/src/workspaces/project/src/tsconfig.tsbuildinfo.readable.baseline.txt] *new* { "version": "FakeTSVersion", @@ -123,6 +123,9 @@ exports.x = 10; ] } ], + "packageJsons": [ + "../package.json" + ], "fileNames": [ "lib.es2016.full.d.ts", "./main.ts", @@ -222,7 +225,7 @@ exports.x = 10; ] ], "latestChangedDtsFile": "./fileA.d.ts", - "size": 2071 + "size": 2106 } src/tsconfig.json:: @@ -270,6 +273,124 @@ src/fileA.ts Found 1 error in src/fileA.ts:1 +//// [/home/src/workspaces/project/src/tsconfig.tsbuildinfo] *modified* +{"version":"FakeTSVersion","root":[[2,4]],"fileNames":["lib.es2016.full.d.ts","./main.ts","./fileB.mts","./fileA.ts"],"fileInfos":[{"version":"8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };","affectsGlobalScope":true,"impliedNodeFormat":1},{"version":"28e8748a7acd58f4f59388926e914f86-export const x = 10;","signature":"f9b4154a9a5944099ecf197d4519d083-export declare const x = 10;\n","impliedNodeFormat":1},{"version":"d03690d860e74c03bcacf63f0dd68b93-export function foo() {}","signature":"7ffb4ea6089b1a385965a214ba412941-export declare function foo(): void;\n","impliedNodeFormat":99},{"version":"cc520ca096f0b81d18073ba8a9776fe3-import { foo } from \"./fileB.mjs\";\nfoo();","signature":"abe7d9981d6018efb6b2b794f40a1607-export {};\n","impliedNodeFormat":1}],"fileIdsList":[[3]],"options":{"composite":true,"module":100,"target":3},"referencedMap":[[4,1]],"semanticDiagnosticsPerFile":[[4,[{"pos":20,"end":33,"code":1479,"category":1,"messageKey":"The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479","messageArgs":["./fileB.mjs"],"messageChain":[{"pos":20,"end":33,"code":1480,"category":3,"messageKey":"To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480","messageArgs":[".mts"]}]}]]],"latestChangedDtsFile":"./fileA.d.ts"} +//// [/home/src/workspaces/project/src/tsconfig.tsbuildinfo.readable.baseline.txt] *modified* +{ + "version": "FakeTSVersion", + "root": [ + { + "files": [ + "./main.ts", + "./fileB.mts", + "./fileA.ts" + ], + "original": [ + 2, + 4 + ] + } + ], + "fileNames": [ + "lib.es2016.full.d.ts", + "./main.ts", + "./fileB.mts", + "./fileA.ts" + ], + "fileInfos": [ + { + "fileName": "lib.es2016.full.d.ts", + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "signature": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": "CommonJS", + "original": { + "version": "8859c12c614ce56ba9a18e58384a198f-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ninterface SymbolConstructor {\n (desc?: string | number): symbol;\n for(name: string): symbol;\n readonly toStringTag: symbol;\n}\ndeclare var Symbol: SymbolConstructor;\ninterface Symbol {\n readonly [Symbol.toStringTag]: string;\n}\ndeclare const console: { log(msg: any): void; };", + "affectsGlobalScope": true, + "impliedNodeFormat": 1 + } + }, + { + "fileName": "./main.ts", + "version": "28e8748a7acd58f4f59388926e914f86-export const x = 10;", + "signature": "f9b4154a9a5944099ecf197d4519d083-export declare const x = 10;\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "28e8748a7acd58f4f59388926e914f86-export const x = 10;", + "signature": "f9b4154a9a5944099ecf197d4519d083-export declare const x = 10;\n", + "impliedNodeFormat": 1 + } + }, + { + "fileName": "./fileB.mts", + "version": "d03690d860e74c03bcacf63f0dd68b93-export function foo() {}", + "signature": "7ffb4ea6089b1a385965a214ba412941-export declare function foo(): void;\n", + "impliedNodeFormat": "ESNext", + "original": { + "version": "d03690d860e74c03bcacf63f0dd68b93-export function foo() {}", + "signature": "7ffb4ea6089b1a385965a214ba412941-export declare function foo(): void;\n", + "impliedNodeFormat": 99 + } + }, + { + "fileName": "./fileA.ts", + "version": "cc520ca096f0b81d18073ba8a9776fe3-import { foo } from \"./fileB.mjs\";\nfoo();", + "signature": "abe7d9981d6018efb6b2b794f40a1607-export {};\n", + "impliedNodeFormat": "CommonJS", + "original": { + "version": "cc520ca096f0b81d18073ba8a9776fe3-import { foo } from \"./fileB.mjs\";\nfoo();", + "signature": "abe7d9981d6018efb6b2b794f40a1607-export {};\n", + "impliedNodeFormat": 1 + } + } + ], + "fileIdsList": [ + [ + "./fileB.mts" + ] + ], + "options": { + "composite": true, + "module": 100, + "target": 3 + }, + "referencedMap": { + "./fileA.ts": [ + "./fileB.mts" + ] + }, + "semanticDiagnosticsPerFile": [ + [ + "./fileA.ts", + [ + { + "pos": 20, + "end": 33, + "code": 1479, + "category": 1, + "messageKey": "The_current_file_is_a_CommonJS_module_whose_imports_will_produce_require_calls_however_the_reference_1479", + "messageArgs": [ + "./fileB.mjs" + ], + "messageChain": [ + { + "pos": 20, + "end": 33, + "code": 1480, + "category": 3, + "messageKey": "To_convert_this_file_to_an_ECMAScript_module_change_its_file_extension_to_0_or_create_a_local_packag_1480", + "messageArgs": [ + ".mts" + ] + } + ] + } + ] + ] + ], + "latestChangedDtsFile": "./fileA.d.ts", + "size": 1999 +} src/tsconfig.json:: SemanticDiagnostics:: diff --git a/testdata/baselines/reference/tscWatch/commandLineWatch/watch-handles-many-bun-dependency-files.js b/testdata/baselines/reference/tscWatch/commandLineWatch/watch-handles-many-bun-dependency-files.js new file mode 100644 index 00000000000..dbd33c9fbaf --- /dev/null +++ b/testdata/baselines/reference/tscWatch/commandLineWatch/watch-handles-many-bun-dependency-files.js @@ -0,0 +1,175 @@ +currentDirectory::/home/src/workspaces/project +useCaseSensitiveFileNames::true +Input:: +//// [/home/src/workspaces/project/index.ts] *new* +import { value0 } from "./node_modules/.bun/pkg0/index"; value0; +import { value1 } from "./node_modules/.bun/pkg1/index"; value1; +import { value2 } from "./node_modules/.bun/pkg2/index"; value2; +import { value3 } from "./node_modules/.bun/pkg3/index"; value3; +import { value4 } from "./node_modules/.bun/pkg4/index"; value4; +import { value5 } from "./node_modules/.bun/pkg5/index"; value5; +import { value6 } from "./node_modules/.bun/pkg6/index"; value6; +import { value7 } from "./node_modules/.bun/pkg7/index"; value7; +import { value8 } from "./node_modules/.bun/pkg8/index"; value8; +import { value9 } from "./node_modules/.bun/pkg9/index"; value9; +import { value10 } from "./node_modules/.bun/pkg10/index"; value10; +import { value11 } from "./node_modules/.bun/pkg11/index"; value11; + +//// [/home/src/workspaces/project/node_modules/.bun/pkg0/index.ts] *new* +export const value0 = 0; +//// [/home/src/workspaces/project/node_modules/.bun/pkg1/index.ts] *new* +export const value1 = 1; +//// [/home/src/workspaces/project/node_modules/.bun/pkg10/index.ts] *new* +export const value10 = 10; +//// [/home/src/workspaces/project/node_modules/.bun/pkg11/index.ts] *new* +export const value11 = 11; +//// [/home/src/workspaces/project/node_modules/.bun/pkg2/index.ts] *new* +export const value2 = 2; +//// [/home/src/workspaces/project/node_modules/.bun/pkg3/index.ts] *new* +export const value3 = 3; +//// [/home/src/workspaces/project/node_modules/.bun/pkg4/index.ts] *new* +export const value4 = 4; +//// [/home/src/workspaces/project/node_modules/.bun/pkg5/index.ts] *new* +export const value5 = 5; +//// [/home/src/workspaces/project/node_modules/.bun/pkg6/index.ts] *new* +export const value6 = 6; +//// [/home/src/workspaces/project/node_modules/.bun/pkg7/index.ts] *new* +export const value7 = 7; +//// [/home/src/workspaces/project/node_modules/.bun/pkg8/index.ts] *new* +export const value8 = 8; +//// [/home/src/workspaces/project/node_modules/.bun/pkg9/index.ts] *new* +export const value9 = 9; +//// [/home/src/workspaces/project/tsconfig.json] *new* +{ + "compilerOptions": {}, + "files": ["index.ts", "node_modules/.bun/pkg0/index.ts", "node_modules/.bun/pkg1/index.ts", "node_modules/.bun/pkg2/index.ts", "node_modules/.bun/pkg3/index.ts", "node_modules/.bun/pkg4/index.ts", "node_modules/.bun/pkg5/index.ts", "node_modules/.bun/pkg6/index.ts", "node_modules/.bun/pkg7/index.ts", "node_modules/.bun/pkg8/index.ts", "node_modules/.bun/pkg9/index.ts", "node_modules/.bun/pkg10/index.ts", "node_modules/.bun/pkg11/index.ts"] +} + +tsgo --watch +ExitStatus:: Success +Output:: +[HH:MM:SS AM] Starting compilation in watch mode... + +[HH:MM:SS AM] Found 0 errors. Watching for file changes. + +//// [/home/src/tslibs/TS/Lib/lib.es2025.full.d.ts] *Lib* +/// +interface Boolean {} +interface Function {} +interface CallableFunction {} +interface NewableFunction {} +interface IArguments {} +interface Number { toExponential: any; } +interface Object {} +interface RegExp {} +interface String { charAt: any; } +interface Array { length: number; [n: number]: T; } +interface ReadonlyArray {} +interface SymbolConstructor { + (desc?: string | number): symbol; + for(name: string): symbol; + readonly toStringTag: symbol; +} +declare var Symbol: SymbolConstructor; +interface Symbol { + readonly [Symbol.toStringTag]: string; +} +declare const console: { log(msg: any): void; }; +//// [/home/src/workspaces/project/index.js] *new* +import { value0 } from "./node_modules/.bun/pkg0/index"; +value0; +import { value1 } from "./node_modules/.bun/pkg1/index"; +value1; +import { value2 } from "./node_modules/.bun/pkg2/index"; +value2; +import { value3 } from "./node_modules/.bun/pkg3/index"; +value3; +import { value4 } from "./node_modules/.bun/pkg4/index"; +value4; +import { value5 } from "./node_modules/.bun/pkg5/index"; +value5; +import { value6 } from "./node_modules/.bun/pkg6/index"; +value6; +import { value7 } from "./node_modules/.bun/pkg7/index"; +value7; +import { value8 } from "./node_modules/.bun/pkg8/index"; +value8; +import { value9 } from "./node_modules/.bun/pkg9/index"; +value9; +import { value10 } from "./node_modules/.bun/pkg10/index"; +value10; +import { value11 } from "./node_modules/.bun/pkg11/index"; +value11; + +//// [/home/src/workspaces/project/node_modules/.bun/pkg0/index.js] *new* +export const value0 = 0; + +//// [/home/src/workspaces/project/node_modules/.bun/pkg1/index.js] *new* +export const value1 = 1; + +//// [/home/src/workspaces/project/node_modules/.bun/pkg10/index.js] *new* +export const value10 = 10; + +//// [/home/src/workspaces/project/node_modules/.bun/pkg11/index.js] *new* +export const value11 = 11; + +//// [/home/src/workspaces/project/node_modules/.bun/pkg2/index.js] *new* +export const value2 = 2; + +//// [/home/src/workspaces/project/node_modules/.bun/pkg3/index.js] *new* +export const value3 = 3; + +//// [/home/src/workspaces/project/node_modules/.bun/pkg4/index.js] *new* +export const value4 = 4; + +//// [/home/src/workspaces/project/node_modules/.bun/pkg5/index.js] *new* +export const value5 = 5; + +//// [/home/src/workspaces/project/node_modules/.bun/pkg6/index.js] *new* +export const value6 = 6; + +//// [/home/src/workspaces/project/node_modules/.bun/pkg7/index.js] *new* +export const value7 = 7; + +//// [/home/src/workspaces/project/node_modules/.bun/pkg8/index.js] *new* +export const value8 = 8; + +//// [/home/src/workspaces/project/node_modules/.bun/pkg9/index.js] *new* +export const value9 = 9; + + +Watch Registrations:: +Directory watches:: + /home/src/tslibs/TS/Lib + /home/src/workspaces/project + /home/src/workspaces/project/node_modules + /home/src/workspaces/project/node_modules/.bun + /home/src/workspaces/project/node_modules/.bun/pkg0 + /home/src/workspaces/project/node_modules/.bun/pkg1 + /home/src/workspaces/project/node_modules/.bun/pkg10 + /home/src/workspaces/project/node_modules/.bun/pkg11 + /home/src/workspaces/project/node_modules/.bun/pkg2 + /home/src/workspaces/project/node_modules/.bun/pkg3 + /home/src/workspaces/project/node_modules/.bun/pkg4 + /home/src/workspaces/project/node_modules/.bun/pkg5 + /home/src/workspaces/project/node_modules/.bun/pkg6 + /home/src/workspaces/project/node_modules/.bun/pkg7 + /home/src/workspaces/project/node_modules/.bun/pkg8 + /home/src/workspaces/project/node_modules/.bun/pkg9 +tsconfig.json:: +SemanticDiagnostics:: +*refresh* /home/src/tslibs/TS/Lib/lib.es2025.full.d.ts +*refresh* /home/src/workspaces/project/node_modules/.bun/pkg0/index.ts +*refresh* /home/src/workspaces/project/node_modules/.bun/pkg1/index.ts +*refresh* /home/src/workspaces/project/node_modules/.bun/pkg2/index.ts +*refresh* /home/src/workspaces/project/node_modules/.bun/pkg3/index.ts +*refresh* /home/src/workspaces/project/node_modules/.bun/pkg4/index.ts +*refresh* /home/src/workspaces/project/node_modules/.bun/pkg5/index.ts +*refresh* /home/src/workspaces/project/node_modules/.bun/pkg6/index.ts +*refresh* /home/src/workspaces/project/node_modules/.bun/pkg7/index.ts +*refresh* /home/src/workspaces/project/node_modules/.bun/pkg8/index.ts +*refresh* /home/src/workspaces/project/node_modules/.bun/pkg9/index.ts +*refresh* /home/src/workspaces/project/node_modules/.bun/pkg10/index.ts +*refresh* /home/src/workspaces/project/node_modules/.bun/pkg11/index.ts +*refresh* /home/src/workspaces/project/index.ts +Signatures:: diff --git a/testdata/submoduleAccepted.txt b/testdata/submoduleAccepted.txt index b979f793aaa..6181a924333 100644 --- a/testdata/submoduleAccepted.txt +++ b/testdata/submoduleAccepted.txt @@ -284,10 +284,6 @@ compiler/conditionalTypeContextualTypeSimplificationsSuceeds.types.diff compiler/declarationsWithRecursiveInternalTypesProduceUniqueTypeParams.js.diff compiler/declarationsWithRecursiveInternalTypesProduceUniqueTypeParams.types.diff compiler/defaultPropsEmptyCurlyBecomesAnyForJs.symbols.diff -compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=false).symbols.diff -compiler/deleteExpressionMustBeOptional_exactOptionalPropertyTypes(exactoptionalpropertytypes=true).symbols.diff -compiler/deleteExpressionMustBeOptional(strict=false).symbols.diff -compiler/deleteExpressionMustBeOptional(strict=true).symbols.diff compiler/duplicateStringNamedProperty1.errors.txt.diff compiler/expandoFunctionBlockShadowing.symbols.diff compiler/expandoFunctionBlockShadowing.types.diff @@ -398,6 +394,7 @@ compiler/declarationEmitLateBoundJSAssignments.js.diff compiler/declarationEmitLateBoundJSAssignments.symbols.diff compiler/declarationEmitLateBoundJSAssignments.types.diff compiler/declarationEmitMethodDeclaration.js.diff +compiler/noImplicitThisBigThis.js.diff ## type/symbol differences of no consequence ## compiler/exportDefaultWithJSDoc1.types.diff @@ -428,6 +425,11 @@ compiler/declarationEmitHigherOrderRetainedGenerics.types.diff compiler/declarationEmitMappedTypeDistributivityPreservesConstraints.js.diff compiler/declarationEmitMappedTypeDistributivityPreservesConstraints.types.diff compiler/declarationEmitMappedTypePreservesTypeParameterConstraint.types.diff +compiler/anonClassDeclarationEmitIsAnon.types.diff +compiler/baseConstraintOfDecorator.types.diff +compiler/baseExpressionTypeParameters.types.diff +compiler/declarationEmitGenericTypeParamerSerialization3.types.diff +compiler/declarationEmitLocalClassDeclarationMixin.types.diff ## better error spans/suggestions ## compiler/awaitInNonAsyncFunction.errors.txt.diff @@ -629,6 +631,10 @@ conformance/ES5For-of36(target=es2015).errors.txt.diff conformance/ES5For-of37(target=es2015).errors.txt.diff conformance/forAwaitPerIterationBindingDownlevel(target=es2015).errors.txt.diff conformance/restParameterInDownlevelGenerator(target=es2015).errors.txt.diff +compiler/deprecatedCompilerOptions1.errors.txt.diff +compiler/deprecatedCompilerOptions3.errors.txt.diff +compiler/deprecatedCompilerOptions4.errors.txt.diff +compiler/deprecatedCompilerOptions5.errors.txt.diff ## Corsa reports errors both sides of an import circularity compiler/recursiveExportAssignmentAndFindAliasedType1.errors.txt.diff @@ -1412,3 +1418,13 @@ conformance/callbackTagVariadicType.js.diff # definiteAssignment shorthand in object literal loses optional modifier ## https://github.com/microsoft/typescript-go/issues/3563 conformance/definiteAssignmentAssertionsWithObjectShortHand.js.diff + +# Const arrow functions are now emitted as such, not function declarations +conformance/checkJsdocSatisfiesTag15.js.diff + +# JS declarations respect EOPT +conformance/jsDeclarationsOptionalTypeLiteralProps1.js.diff +conformance/jsDeclarationsOptionalTypeLiteralProps2.js.diff + +# Expando object emitted as object instead of namespace +conformance/typeFromPropertyAssignment39.js.diff diff --git a/testdata/submoduleTriaged.txt b/testdata/submoduleTriaged.txt index 321acdd5586..9fe6ca4b287 100644 --- a/testdata/submoduleTriaged.txt +++ b/testdata/submoduleTriaged.txt @@ -2,25 +2,9 @@ # These are known diffs that we intend to fix. # Each group should include a link to the tracking issue. -# https://github.com/microsoft/typescript-go/issues/3410 -compiler/anonClassDeclarationEmitIsAnon.types.diff -compiler/baseConstraintOfDecorator.types.diff -compiler/baseExpressionTypeParameters.types.diff -compiler/declarationEmitGenericTypeParamerSerialization3.types.diff -compiler/declarationEmitLocalClassDeclarationMixin.types.diff - -# Bug: test harness doesn't report tsconfig errors -## https://github.com/microsoft/typescript-go/issues/3475 -compiler/deprecatedCompilerOptions1.errors.txt.diff -compiler/deprecatedCompilerOptions3.errors.txt.diff -compiler/deprecatedCompilerOptions4.errors.txt.diff -compiler/deprecatedCompilerOptions5.errors.txt.diff - - # Omnibus: Isolated declarations error changes - needs investigation ## https://github.com/microsoft/typescript-go/issues/3477 compiler/isolatedDeclarationErrorsExpandoFunctions.errors.txt.diff -compiler/isolatedDeclarationErrorsReturnTypes.errors.txt.diff compiler/isolatedDeclarationErrorsClasses.errors.txt.diff compiler/isolatedDeclarationErrorsExpressions.errors.txt.diff compiler/isolatedDeclarationErrorsClassesExpressions.errors.txt.diff @@ -38,33 +22,3 @@ compiler/exportAssignmentMembersVisibleInAugmentation.errors.txt.diff compiler/multiLinePropertyAccessAndArrowFunctionIndent1.errors.txt.diff compiler/parseErrorIncorrectReturnToken.errors.txt.diff conformance/parserStatementIsNotAMemberVariableDeclaration1(alwaysstrict=true).errors.txt.diff - -# Namespace-to-const restructuring with DtsFileErrors (redeclaration errors) -## https://github.com/microsoft/typescript-go/issues/3547 -conformance/typeFromPropertyAssignment39.js.diff - -# Missing generic type arguments no longer auto-filled with any (produces TS2314 errors) -## https://github.com/microsoft/typescript-go/issues/3549 -conformance/jsDeclarationsMissingGenerics(target=es2015).js.diff - -# Optional property types in JS declarations drop | undefined -## https://github.com/microsoft/typescript-go/issues/3550 -conformance/jsDeclarationsOptionalTypeLiteralProps1.js.diff -conformance/jsDeclarationsOptionalTypeLiteralProps2.js.diff - -# @satisfies tag handling changes: functions become const declarations -## https://github.com/microsoft/typescript-go/issues/3557 -conformance/checkJsdocSatisfiesTag15.js.diff - -# noImplicitThis functions returning this now fully expand the object type -## https://github.com/microsoft/typescript-go/issues/3561 -compiler/noImplicitThisBigThis.js.diff - -# Late-bound computed property [prop] preserved instead of resolved to plain prop -## https://github.com/microsoft/typescript-go/issues/3566 - -# Symbol getter/setter declaration emit change -## https://github.com/microsoft/typescript-go/issues/3567 - -# Declaration emit simplification of class extending built-in Array -## https://github.com/microsoft/typescript-go/issues/3569 diff --git a/testdata/tests/cases/compiler/commonjsExportDestructuringImportedValue.ts b/testdata/tests/cases/compiler/commonjsExportDestructuringImportedValue.ts new file mode 100644 index 00000000000..3434be72390 --- /dev/null +++ b/testdata/tests/cases/compiler/commonjsExportDestructuringImportedValue.ts @@ -0,0 +1,32 @@ +// @target: es2022 +// @module: commonjs +// @noTypesAndSymbols: true + +// @filename: /enum.ts +export class CodePriceType { + static A = "a"; + static B = "b"; +} +export default CodePriceType; +export const pair = ["a", "b"]; +export const fallback = "fallback"; + +// @filename: /repro.ts +import { CodePriceType } from "./enum"; +export const { A, B } = CodePriceType; + +// @filename: /arrayPattern.ts +import { pair } from "./enum"; +export const [ArrayA, ArrayB] = pair; + +// @filename: /aliasedNamedObject.ts +import { CodePriceType as PriceType } from "./enum"; +export const { A: AliasA, B: AliasB } = PriceType; + +// @filename: /defaultObject.ts +import CodePriceType from "./enum"; +export const { A: DefaultA, B: DefaultB } = CodePriceType; + +// @filename: /defaultInitializer.ts +import { CodePriceType, fallback } from "./enum"; +export const { Missing = fallback } = CodePriceType as any; diff --git a/testdata/tests/cases/compiler/constEnumOnlyModuleImportAliasEmit.ts b/testdata/tests/cases/compiler/constEnumOnlyModuleImportAliasEmit.ts new file mode 100644 index 00000000000..991f5d87f66 --- /dev/null +++ b/testdata/tests/cases/compiler/constEnumOnlyModuleImportAliasEmit.ts @@ -0,0 +1,26 @@ +// @target: esnext +// @module: esnext +// @moduleResolution: bundler + +// @filename: mappa.ts +namespace OnRtls.Mappa { + export const enum TipoCamera { Camera2D = 1, Camera3D = 2 } + export class MappaViewModel { + constructor(public canvas: any, public config: any, public tipo: TipoCamera) {} + } +} + +// @filename: types.d.ts +declare namespace OnRtls.Mappa.Server { + const enum SomeFlag { A = 0 } +} + +// @filename: sensmap.ts +namespace OnRtls.Carrello.Home { + import mappa = OnRtls.Mappa; + export class SensmapViewModel { + constructor() { + var x = new mappa.MappaViewModel(null, null, mappa.TipoCamera.Camera3D); + } + } +} diff --git a/testdata/tests/cases/compiler/distributiveConditionalBaseConstraint.ts b/testdata/tests/cases/compiler/distributiveConditionalBaseConstraint.ts new file mode 100644 index 00000000000..6c945c57990 --- /dev/null +++ b/testdata/tests/cases/compiler/distributiveConditionalBaseConstraint.ts @@ -0,0 +1,65 @@ +// @noEmit: true + +// https://github.com/microsoft/TypeScript/issues/63568 + +type Type = { values: string }; + +type Wrapped = { values: T["values"] }; + +type FromObject, Props extends Context, Shape extends Record = { + [Key in keyof Props]: Wrapped>; +}> = Shape; + +type FromSchema, S> = + S extends Type ? FromSchema : never; + +// https://github.com/microsoft/typescript-go/issues/4463 + +type JSONSchema = + | boolean + | Readonly<{ + items?: JSONSchema; + additionalItems?: JSONSchema; + properties?: JSONSchema; + additionalProperties?: JSONSchema; + }>; + +// Stands in for json-schema-to-ts's ParseSchema; its only role here is to impose the +// `extends JSONSchema` constraint on whatever type it is handed. +type ParseSchema = unknown; + +type RemoveInvalidAdditionalItems = SCHEMA extends Readonly<{ + items: JSONSchema; +}> + ? SCHEMA extends Readonly<{ additionalItems: JSONSchema }> + ? SCHEMA + : SCHEMA & Readonly<{ additionalItems: true }> + : SCHEMA extends boolean + ? SCHEMA + : Omit; + +type RemoveInvalidAdditionalProperties = SCHEMA extends Readonly<{ + additionalProperties: JSONSchema; +}> + ? SCHEMA extends Readonly<{ properties: JSONSchema }> + ? SCHEMA + : SCHEMA & Readonly<{ properties: {} }> + : SCHEMA extends boolean + ? SCHEMA + : Omit; + +type MergeSubSchema< + SUB_SCHEMA extends JSONSchema, + CLEANED_SUB_SCHEMA extends JSONSchema = RemoveInvalidAdditionalProperties< + RemoveInvalidAdditionalItems + >, +> = Omit & CLEANED_SUB_SCHEMA; + +// The failing site: MergeSubSchema is rejected as not satisfying +// the `extends JSONSchema` constraint on ParseSchema. +type RecurseOnAllOfSchema = + SUB_SCHEMAS extends readonly [infer SUB_SCHEMAS_HEAD] + ? SUB_SCHEMAS_HEAD extends JSONSchema + ? ParseSchema> + : never + : never; diff --git a/testdata/tests/cases/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.ts b/testdata/tests/cases/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.ts new file mode 100644 index 00000000000..c5c42c0f70f --- /dev/null +++ b/testdata/tests/cases/compiler/jsDeclarationEmitThisAssignmentWithBaseProperty.ts @@ -0,0 +1,75 @@ +// @allowJs: true +// @checkJs: true +// @declaration: true +// @emitDeclarationOnly: true +// @target: esnext + +// @filename: component.d.ts +export class Component { + state: any; + constructor(props?: any); +} + +export class WithAccessor { + get value(): number; + set value(v: number); +} + +export class WithMethod { + method(): void; +} + +// @filename: main.js +import { Component, WithAccessor, WithMethod } from "./component"; + +export class C1 extends Component { + state = { count: 0 }; +} + +export class C2 extends Component { + constructor() { + super({}); + this.state = { count: 0 }; + } +} + +export class C3 extends Component { + update() { + this.state = { count: 1 }; + } +} + +export class C4 extends WithAccessor { + constructor() { + super(); + this.value = 1; + } +} + +/** @implements {WithAccessor} */ +export class C5 { + constructor() { + this.value = 1; + } +} + +export class C6 extends WithMethod { + constructor() { + super(); + this.method = this.method.bind(this); + } +} + +// @filename: mainTs.ts +import { Component } from "./component"; + +export class C1 extends Component { + state = { count: 0 }; +} + +export class C2 extends Component { + constructor() { + super({}); + this.state = { count: 0 }; + } +} diff --git a/testdata/tests/cases/compiler/jsdocModifiersInClass.ts b/testdata/tests/cases/compiler/jsdocModifiersInClass.ts new file mode 100644 index 00000000000..a9bee7ecdbd --- /dev/null +++ b/testdata/tests/cases/compiler/jsdocModifiersInClass.ts @@ -0,0 +1,25 @@ +// @allowJs: true +// @checkJs: true,false +// @noEmit: true +// @filename: test.js + +// Unlike object literal members, class members are real class-like members, so +// JSDoc modifiers are still semantically validated under checkJs: @override +// without a base class errors. With checkJs off, nothing is validated. + +class NoBase { + /** @override */ + foo() { + } +} + +class Base { + foo() { + } +} + +class Derived extends Base { + /** @override */ + foo() { + } +} diff --git a/testdata/tests/cases/compiler/jsdocModifiersInObjectLiteral.ts b/testdata/tests/cases/compiler/jsdocModifiersInObjectLiteral.ts new file mode 100644 index 00000000000..f4e0b84acff --- /dev/null +++ b/testdata/tests/cases/compiler/jsdocModifiersInObjectLiteral.ts @@ -0,0 +1,32 @@ +// @allowJs: true +// @checkJs: true,false +// @declaration: true +// @emitDeclarationOnly: true +// @filename: test.js + +// Object literal members aren't class-like members, so JSDoc modifiers like +// @override or @readonly aren't real modifiers and must not produce grammar +// errors, regardless of checkJs (#4437). + +const obj = { + /** @override */ + created() { + }, + + /** @private */ + onClose_() { + }, + + /** @readonly */ + get value() { + return 1; + }, + + /** @protected */ + set value(v) { + }, + + /** @public */ + async load() { + }, +}; diff --git a/testdata/tests/cases/compiler/namespaceExportDestructuringReferences.ts b/testdata/tests/cases/compiler/namespaceExportDestructuringReferences.ts new file mode 100644 index 00000000000..282e0195201 --- /dev/null +++ b/testdata/tests/cases/compiler/namespaceExportDestructuringReferences.ts @@ -0,0 +1,11 @@ +// @target: es2022 +// @noTypesAndSymbols: true + +namespace N { + export const key = "a"; + export const source: any = { a: 1, b: undefined, pair: [3, 4] }; + export const fallback = 2; + + export const { [key]: computed, b = fallback } = source; + export const [x, y] = source.pair; +} diff --git a/testdata/tests/cases/compiler/nestedGenericTypeInference.ts b/testdata/tests/cases/compiler/nestedGenericTypeInference.ts new file mode 100644 index 00000000000..f20b557bdaa --- /dev/null +++ b/testdata/tests/cases/compiler/nestedGenericTypeInference.ts @@ -0,0 +1,22 @@ +// @noEmit: true + +// https://github.com/microsoft/typescript-go/issues/1789 + +declare function flat(args: T[] | T[][]): void; +type Value = 1 | 2; +declare const n: Value[] | Value[][]; +flat(n); + +type Box = { value: T }; + +declare function flat0(args: Box | Box>): void; +declare const arg0: Box | Box>; +flat0(arg0); + +declare function flat1(args: Array | Array>): void; +declare const arg1: Array | Array>; +flat1(arg1); + +declare function flat2(args: Box | Box>): void; +declare const arg2: Box | Box>; +flat2(arg2); diff --git a/testdata/tests/cases/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.ts b/testdata/tests/cases/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.ts new file mode 100644 index 00000000000..e0bf1f8427c --- /dev/null +++ b/testdata/tests/cases/compiler/parametersAliasOverTypeofPreservedAsIsInDeclarations.ts @@ -0,0 +1,28 @@ +// @declaration: true +interface OverloadUnion { + (arg: string): Promise; + (arg: string, callback: (error: Error | null, result: boolean) => void): void; +} + +declare let overloadInterface: OverloadUnion; +declare let overloadInline: + | ((arg: string) => Promise) + | ((arg: string, callback: (error: Error | null, result: boolean) => void) => void) + +export class C { + classMethodInterface(...args: Parameters) {} + classMethodInline(...args: Parameters) {} + + classFieldFunctionInterface = function (...args: Parameters) {} + classFieldFunctionInline = function (...args: Parameters) {} + + classFieldArrowInterface = (...args: Parameters) => {} + classFieldArrowInline = (...args: Parameters) => {} +} + +export function FunctionInterface(...args: Parameters) {} +export function FunctionInline(...args: Parameters) {} +export const FunctionAssignInterface = function (...args: Parameters) {} +export const FunctionAssignInline = function (...args: Parameters) {} +export const ArrowInterface = (...args: Parameters) => {} +export const ArrowInline = (...args: Parameters) => {} \ No newline at end of file